<commit_before>#!/usr/bin/env node
'use strict';

const _ = require('lodash');
const chalk = require('chalk');
const EventEmitter = require('events').EventEmitter;
const LineWrapper = require('stream-line-wrapper');
const Promise = require('bluebird');
const Answers = require('answers');
const inquirer = require('inquirer');

function handleStream(stream, target, targetName) {
    const prefix = `[${chalk.yellow(target.label || targetName)}] `;
    console.log(`${prefix}listening`);
    const lineWrapper = new LineWrapper({ prefix });
    stream.stdout.pipe(lineWrapper).pipe(process.stdout);
    stream.stderr.pipe(process.stderr);
    stream.on('error', console.error);
}

function getChoices(config) {
    const { _targets } = config;
    const getterPairs = _.toPairs(_targets);
    return _.map(getterPairs, (pair) => {
        const getter = pair[1];
        const getterKey = pair[0];
        const option = {
            name: getter.label || getterKey,
            value: getterKey
        };
        return option;
    });
}

function getInitialPrompt(config) {
    if (_.isEmpty(config._)) {
        let prompts = [
            {
                type: 'checkbox',
                name: 'targetNames',
                message: 'Please select your targets',
                choices: getChoices(config)
            }
        ];
        return inquirer.prompt(prompts)
            .then((results) => {
                config._ = results.targetNames;
                return config;
            });
    } else {
        return config;
    }
}

function invokeSequentialTargets(config) {
    const { _targets } = config;
    const targetNames = config._forks.sequential;

    function targetReducer(acc, targetName) {
        const target = _targets[targetName];
        if (_.isFunction(target)) {
            let namespace = targetName.split('.').shift();
            let pendingResult = Promise.resolve(target(config[namespace] || {}))
                .then((result) => {
                    if (result instanceof EventEmitter) {
                        handleStream(result, target, targetName);
                        return { _targets, targetName, result: null };
                    } else {
                        return { _targets, targetName, result };
                    }
                })
                .catch(() => {
                    return { _targets, targetName, result: 'unavailable' };
                });
            acc.push(pendingResult);
        } else {
            console.log('no target found');
        }
        return acc;
    }

    const pendingTargets = _.reduce(targetNames, targetReducer, []);

    return Promise.each(pendingTargets, print);
}

function print(data) {
    const label = data._targets[data.targetName].label || data.targetName;
    if (data && data.result) {
        const result = (_.isString(data.result)) ? data.result : JSON.stringify(data.result, null, 4);
        console.log(`[${chalk.yellow(label)}]`, result.split('\n').join(`\n[${chalk.yellow(label)}] `));
    }
    return;
}

function invokeParallelTargets(config) {
    const { _targets } = config;
    const targetNames = config._forks.parallel;

    function targetReducer(acc, targetName) {
        const target = _targets[targetName];
        if (_.isFunction(target)) {
            let namespace = targetName.split('.').shift();
            let pendingResult = Promise.resolve(target(config[namespace] || {}))
                .then((result) => {
                    if (result instanceof EventEmitter) {
                        handleStream(result, target, targetName);
                        return { _targets, targetName, result: null };
                    } else {
                        return { _targets, targetName, result };
                    }
                })
                .catch(() => {
                    return { _targets, targetName, result: 'unavailable' };
                })
                .then(print);
            acc.push(pendingResult);
        } else {
            console.log('no target found');
        }
        return acc;
    }

    const pendingTargets = _.reduce(targetNames, targetReducer, []);

    return Promise.all(pendingTargets);
}

function getMissing(config) {
    const { _targets, _answers } = config;
    const targetNames = flattenTargetNames(config._);
    function promptReducer(acc, targetName) {
        const namespace = targetName.split('.').shift();
        const target = _targets[targetName] || {};
        let allTargetPrompts = target.prompts || [];
        if (_.isFunction(allTargetPrompts)) {
            allTargetPrompts = allTargetPrompts(config[namespace]);
        }
        const targetPrompts = _.map(allTargetPrompts, (prompt) => {
            if (_.isObject(prompt)) {
                if (!prompt.type) prompt.type = "input";
                _.set(prompt, 'name', `${namespace}.${prompt.name}`);
                _.set(prompt, 'message', `[${chalk.yellow(target.label || target.name)}] ${prompt.message}`);
            } else if (_.isString(prompt)) {
                let name = `${namespace}.${prompt}`;
                prompt = {
                    type: 'input',
                    name,
                    message: name
                };
            } else {
                throw new Error(`invalid prompt in ${targetName}`);
            }
            return prompt;
        });
        acc = acc.concat(targetPrompts);
        return acc;
    }
    const prompts = _.uniqBy(_.reduce(targetNames, promptReducer, []), 'name');
    _answers.configure('prompts', prompts);
    return _answers.get().then((c) => {
        c._ = _.isEmpty(config._) ? c._ : config._;
        return forkTargets(c);
    });
}

function flattenTargetNames(targetNames) {
    return _.reduce(targetNames, (acc, targetName) => [ ...acc, ...targetName.split(',') ], []);
}

function forkTargets(config) {
    const targets = _.reduce(config._, (acc, targetName) => {
        if (targetName.indexOf(',') >= 0) {
            acc.sequential = [ ...acc.sequential, ...targetName.split(',') ];
        } else {
            acc.parallel.push(targetName);
        }
        return acc;
    }, { sequential: [], parallel: [] });

    config._forks = {
        parallel: targets.parallel,
        sequential: targets.sequential
    };

    return config;
}

function Targets(options = {}) {
    const { name, targets } = options;
    const answers = Answers({ name });

    function processGroups(config = {}) {
        if (_.isEmpty(config._)) {
            _.each(targets, (target, prop) => {
                if (_.isArray(target)) {
                    delete targets[prop];
                }
            });
        } else {
            config._ = _.reduce(config._, (acc, targetName) => {
                const target = targets[targetName];
                if (_.isArray(target)) {
                    const result = [ ...acc, ...target ];
                    return result;
                } else {
                    return [ ...acc, targetName ];
                }
            }, []);
        }
        return config;
    }

    function augment(config = {}) {
        config._targets = targets;
        config._answers = answers;
        return config;
    }

    function invokeTargets(config) {
        const chains = [];

        if (!_.isEmpty(config._forks.parallel)) {
            chains.push(Promise.resolve(config)
                .then(invokeParallelTargets)
                .catch(console.error));
        }

        if (!_.isEmpty(config._forks.sequential)) {
            chains.push(Promise.resolve(config)
                .then(invokeSequentialTargets)
                .catch(console.error));
        }

        return Promise.all(chains);
    }

    return answers.get()
        .then(processGroups)
        .then(augment)
        .then(getInitialPrompt)
        .then(getMissing)
        .then(augment)
        .then(invokeTargets);

}

module.exports = Targets;
<commit_msg>trim newlines from target output<commit_after>#!/usr/bin/env node
'use strict';

const _ = require('lodash');
const chalk = require('chalk');
const EventEmitter = require('events').EventEmitter;
const LineWrapper = require('stream-line-wrapper');
const Promise = require('bluebird');
const Answers = require('answers');
const inquirer = require('inquirer');

function handleStream(stream, target, targetName) {
    const prefix = `[${chalk.yellow(target.label || targetName)}] `;
    console.log(`${prefix}listening`);
    const lineWrapper = new LineWrapper({ prefix });
    stream.stdout.pipe(lineWrapper).pipe(process.stdout);
    stream.stderr.pipe(process.stderr);
    stream.on('error', console.error);
}

function getChoices(config) {
    const { _targets } = config;
    const getterPairs = _.toPairs(_targets);
    return _.map(getterPairs, (pair) => {
        const getter = pair[1];
        const getterKey = pair[0];
        const option = {
            name: getter.label || getterKey,
            value: getterKey
        };
        return option;
    });
}

function getInitialPrompt(config) {
    if (_.isEmpty(config._)) {
        let prompts = [
            {
                type: 'checkbox',
                name: 'targetNames',
                message: 'Please select your targets',
                choices: getChoices(config)
            }
        ];
        return inquirer.prompt(prompts)
            .then((results) => {
                config._ = results.targetNames;
                return config;
            });
    } else {
        return config;
    }
}

function invokeSequentialTargets(config) {
    const { _targets } = config;
    const targetNames = config._forks.sequential;

    function targetReducer(acc, targetName) {
        const target = _targets[targetName];
        if (_.isFunction(target)) {
            let namespace = targetName.split('.').shift();
            let pendingResult = Promise.resolve(target(config[namespace] || {}))
                .then((result) => {
                    if (result instanceof EventEmitter) {
                        handleStream(result, target, targetName);
                        return { _targets, targetName, result: null };
                    } else {
                        return { _targets, targetName, result };
                    }
                })
                .catch(() => {
                    return { _targets, targetName, result: 'unavailable' };
                });
            acc.push(pendingResult);
        } else {
            console.log('no target found');
        }
        return acc;
    }

    const pendingTargets = _.reduce(targetNames, targetReducer, []);

    return Promise.each(pendingTargets, print);
}

function print(data) {
    const label = data._targets[data.targetName].label || data.targetName;
    if (data && data.result) {
        let result;
        if (_.isString(data.result)) {
            result = data.result;
        } else {
            result = JSON.stringify(data.result, null, 4);
        }
        result = result.replace(/^\n*/, '');
        result = result.replace(/\n*$/, '');
        console.log(`[${chalk.yellow(label)}]`, result.split('\n').join(`\n[${chalk.yellow(label)}] `));
    }
    return;
}

function invokeParallelTargets(config) {
    const { _targets } = config;
    const targetNames = config._forks.parallel;

    function targetReducer(acc, targetName) {
        const target = _targets[targetName];
        if (_.isFunction(target)) {
            let namespace = targetName.split('.').shift();
            let pendingResult = Promise.resolve(target(config[namespace] || {}))
                .then((result) => {
                    if (result instanceof EventEmitter) {
                        handleStream(result, target, targetName);
                        return { _targets, targetName, result: null };
                    } else {
                        return { _targets, targetName, result };
                    }
                })
                .catch(() => {
                    return { _targets, targetName, result: 'unavailable' };
                })
                .then(print);
            acc.push(pendingResult);
        } else {
            console.log('no target found');
        }
        return acc;
    }

    const pendingTargets = _.reduce(targetNames, targetReducer, []);

    return Promise.all(pendingTargets);
}

function getMissing(config) {
    const { _targets, _answers } = config;
    const targetNames = flattenTargetNames(config._);
    function promptReducer(acc, targetName) {
        const namespace = targetName.split('.').shift();
        const target = _targets[targetName] || {};
        let allTargetPrompts = target.prompts || [];
        if (_.isFunction(allTargetPrompts)) {
            allTargetPrompts = allTargetPrompts(config[namespace]);
        }
        const targetPrompts = _.map(allTargetPrompts, (prompt) => {
            if (_.isObject(prompt)) {
                if (!prompt.type) prompt.type = "input";
                _.set(prompt, 'name', `${namespace}.${prompt.name}`);
                _.set(prompt, 'message', `[${chalk.yellow(target.label || target.name)}] ${prompt.message}`);
            } else if (_.isString(prompt)) {
                let name = `${namespace}.${prompt}`;
                prompt = {
                    type: 'input',
                    name,
                    message: name
                };
            } else {
                throw new Error(`invalid prompt in ${targetName}`);
            }
            return prompt;
        });
        acc = acc.concat(targetPrompts);
        return acc;
    }
    const prompts = _.uniqBy(_.reduce(targetNames, promptReducer, []), 'name');
    _answers.configure('prompts', prompts);
    return _answers.get().then((c) => {
        c._ = _.isEmpty(config._) ? c._ : config._;
        return forkTargets(c);
    });
}

function flattenTargetNames(targetNames) {
    return _.reduce(targetNames, (acc, targetName) => [ ...acc, ...targetName.split(',') ], []);
}

function forkTargets(config) {
    const targets = _.reduce(config._, (acc, targetName) => {
        if (targetName.indexOf(',') >= 0) {
            acc.sequential = [ ...acc.sequential, ...targetName.split(',') ];
        } else {
            acc.parallel.push(targetName);
        }
        return acc;
    }, { sequential: [], parallel: [] });

    config._forks = {
        parallel: targets.parallel,
        sequential: targets.sequential
    };

    return config;
}

function Targets(options = {}) {
    const { name, targets } = options;
    const answers = Answers({ name });

    function processGroups(config = {}) {
        if (_.isEmpty(config._)) {
            _.each(targets, (target, prop) => {
                if (_.isArray(target)) {
                    delete targets[prop];
                }
            });
        } else {
            config._ = _.reduce(config._, (acc, targetName) => {
                const target = targets[targetName];
                if (_.isArray(target)) {
                    const result = [ ...acc, ...target ];
                    return result;
                } else {
                    return [ ...acc, targetName ];
                }
            }, []);
        }
        return config;
    }

    function augment(config = {}) {
        config._targets = targets;
        config._answers = answers;
        return config;
    }

    function invokeTargets(config) {
        const chains = [];

        if (!_.isEmpty(config._forks.parallel)) {
            chains.push(Promise.resolve(config)
                .then(invokeParallelTargets)
                .catch(console.error));
        }

        if (!_.isEmpty(config._forks.sequential)) {
            chains.push(Promise.resolve(config)
                .then(invokeSequentialTargets)
                .catch(console.error));
        }

        return Promise.all(chains);
    }

    return answers.get()
        .then(processGroups)
        .then(augment)
        .then(getInitialPrompt)
        .then(getMissing)
        .then(augment)
        .then(invokeTargets);

}

module.exports = Targets;
<|endoftext|>


<commit_before>const Discord = require("discord.js");
const fs = require("fs");
const date = require("date");
const bot = new Discord.Client();
const prefix = "!";
const botToken = require("./bottoken");

bot.on("ready", () => {
    console.log("Klar");
    bot.user.setGame("Skriv !help för hjälp.");
});

var dabRespond = [
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Vad är det du inte förstår?",
    "Jävla människor ska alltid komma och tjata",
    "Okej då, ***DAB***"
];

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(), 0, 1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
}

var weekNumber = (new Date()).getWeek();
var widthSchema = "600"
var heightSchema = "600"

var schemaLink = "http://www.novasoftware.se/ImgGen/schedulegenerator.aspx?format=png&schoolid=80220/sv-se&type=1&id={EA17E85E-CBFC-4836-935C-04780337F6D5}&period=&week="+weekNumber+"&mode=0&printer=0&colors=32&head=0&clock=0&foot=0&day=0&width="+widthSchema+"&height="+heightSchema+"&maxwidth=1883&maxheight=847"

bot.on("message", (message) => {

    if (!message.content.startsWith(prefix)) return;
    if (message.author.bot) return;

    //console.log(test);

    var split = message.content.substring(prefix.length).split(' ');

    switch (split[0].toLowerCase()) {

        case "help":
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Kommandon:", bot.user.avatarURL)
                    .addField("Allmäna kommandon:", "!help - visar denna meny\n!github - skickar länken till botens github repo")
                    .addField("Skolrelaterade kommandon:", "!schema - visar veckans schema")
                    .setColor("0x111111")
            });
            break;
        case "schema":
            message.channel.send({
            embed: new Discord.RichEmbed()
                .setAuthor("Schema:", bot.user.avatarURL)
                .setImage(schemaLink)
                .setColor("0x"+("000000"+Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6))
            });
            break;
        case "github":
            message.author.send("https://github.com/ChilladeChillin/ITGDiscordBot");
            break;
        case "dab":
            message.channel.send(dabRespond[Math.floor(Math.random() * dabRespond.length)]);
            break;
        //case "bordejag"
            //[Math.floor(Math.random() * bordejag.length)]
    }
});

bot.login(botToken);<commit_msg>La till funktionen !säg<commit_after>const Discord = require("discord.js");
const fs = require("fs");
const date = require("date");
const bot = new Discord.Client();
const prefix = "!";
const botToken = require("./bottoken");

bot.on("ready", () => {
    console.log("Klar");
    bot.user.setGame("Skriv !help för hjälp.");
});

var dabRespond = [
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Du kan inte tvinga mig",
    "Vad är det du inte förstår?",
    "Jävla människor ska alltid komma och tjata",
    "Okej då, ***DAB***"
];

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(), 0, 1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
}

var weekNumber = (new Date()).getWeek();
var widthSchema = "600"
var heightSchema = "600"

var schemaLink = "http://www.novasoftware.se/ImgGen/schedulegenerator.aspx?format=png&schoolid=80220/sv-se&type=1&id={EA17E85E-CBFC-4836-935C-04780337F6D5}&period=&week="+weekNumber+"&mode=0&printer=0&colors=32&head=0&clock=0&foot=0&day=0&width="+widthSchema+"&height="+heightSchema+"&maxwidth=1883&maxheight=847"

bot.on("message", (message) => {

    if (!message.content.startsWith(prefix)) return;
    if (message.author.bot) return;

    //console.log(test);

    var split = message.content.substring(prefix.length).split(' ');

    switch (split[0].toLowerCase()) {

        case "help":
            message.channel.send({
                embed: new Discord.RichEmbed()
                    .setAuthor("Kommandon:", bot.user.avatarURL)
                    .addField("Allmäna kommandon:", "!help - visar denna meny\n!github - skickar länken till botens github repo")
                    .addField("Skolrelaterade kommandon:", "!schema - visar veckans schema")
                    .setColor("0x111111")
            });
            break;
        case "schema":
            message.channel.send({
            embed: new Discord.RichEmbed()
                .setAuthor("Schema:", bot.user.avatarURL)
                .setImage(schemaLink)
                .setColor("0x"+("000000"+Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6))
            });
            break;
        case "github":
            message.author.send("https://github.com/ChilladeChillin/ITGDiscordBot");
            break;
        case "dab":
            message.channel.send(dabRespond[Math.floor(Math.random() * dabRespond.length)]);
            break;
        case "säg":
            var textFromSender = message.content;
            message.delete(0);
            if (message.author.id==="164283691802165250") {
                message.channel.send(message.content.substring(5));
                break;
            }
            else {
                break;
            }
        //case "bordejag"
            //[Math.floor(Math.random() * bordejag.length)]
    }
});

bot.login(botToken);<|endoftext|>


<commit_before>var testRunner = require('./testRunner');

var ZSchema = require('z-schema');
var JaySchema = require('jayschema');
var jjv = require('jjv');
var jassi = require('jassi');
var jsv = require('JSV');
var JsonSchema = require('jsonschema');
var tv4 = require('tv4');
var JsonModel = require('json-model');
var Themis = require('themis');
var imjv = require('is-my-json-valid');
var jsck = require('jsck');
var requestValidator = require('request-validator');
var skeemas = require('skeemas');

var refs = {
	'http://localhost:1234/integer.json': require('./JSON-Schema-Test-Suite/remotes/integer.json'),
	'http://localhost:1234/subSchemas.json': require('./JSON-Schema-Test-Suite/remotes/subSchemas.json'),
	'http://localhost:1234/folder/folderInteger.json': require('./JSON-Schema-Test-Suite/remotes/folder/folderInteger.json'),
	'http://json-schema.org/draft-03/schema': require('./refs/json-schema-draft-03.json'),
	'http://json-schema.org/draft-04/schema': require('./refs/json-schema-draft-04.json')
};

testRunner([
	{
		name: 'is-my-json-valid',
		setup: function (schema) {
			// no $refs supported
			return imjv(schema);
		},
		test: function (instance, json, schema) {
			return !!instance(json);
		}
	},
	{
		name: 'themis',
		setup: function (schema) {
			// $refs only supported if they have id attributes and the test suite refs do not
			return Themis.validator(schema);
		},
		test: function (instance, json, schema) {
			return instance(json, '0').valid;
		},
		benchmarks: 'https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html'
	},
	{
		name: 'z-schema',
		setup: function () {
			var validator = new ZSchema({
				ignoreUnresolvableReferences: true
			});
			Object.keys(refs).forEach(function (uri) {
				validator.setRemoteReference(uri, refs[uri]);
			});
			return validator;
		},
		test: function (instance, json, schema) {
			return instance.validate(json, schema);
		},
		benchmarks: 'https://rawgit.com/zaggino/z-schema/master/benchmark/results.html'
	},
	{
		name: 'jjv',
		setup: function () {
			var validator = jjv();
			Object.keys(refs).forEach(function (uri) {
				validator.addSchema(uri, refs[uri]);
			});
			return validator;
		},
		test: function (instance, json, schema) {
			return instance.validate(schema, json) === null;
		}
	},
	{
		name: 'skeemas',
		setup: function (schema) {
			var validator = skeemas();
			Object.keys(refs).forEach(function (uri) {
				validator.addRef(uri, refs[uri]);
			});
			return validator;
		},
		test: function (instance, json, schema) {
			return instance.validate(json, schema).valid;
		}
	},
	{
		name: 'jayschema',
		setup: function () {
			// $refs not supported with synchronous validation, only asyc
			return new JaySchema();
		},
		test: function (instance, json, schema) {
			return instance.validate(json, schema).length === 0;
		}
	},
	{
		name: 'jsck',
		setup: function (schema) {
			// no $refs supported
			return new jsck.draft4(schema);
		},
		test: function (instance, json, schema) {
			return instance.validate(json).valid;
		},
		benchmarks: 'https://github.com/pandastrike/jsck/blob/master/doc/benchmarks.md'
	},
	{
		name: 'jassi',
		// no $refs supported
		setup: function (schema) {
			return jassi;
		},
		test: function (instance, json, schema) {
			return instance(json, schema).length === 0;
		}
	},

	{
		name: 'JSV',
		setup: function (schema) {
			// no documented $refs supported
			return jsv;
		},
		test: function (instance, json, schema) {
			return instance.JSV.createEnvironment().validate(json, schema).errors.length === 0;
		}
	},
	{
		name: 'request-validator',
		setup: function (schema) {
			// no documented $refs supported
			return requestValidator(schema);
		},
		test: function (instance, json, schema) {
			try {
				instance.validate(json);
				return true;
			}
			catch (e) {
				return false;
			}
		}
	},
	{
		name: 'json-model',
		setup: function (schema) {
			// no comprehensible documented $refs supported
			return JsonModel.validator(schema);
		},
		test: function (instance, json, schema) {
			return instance(json).valid;
		}
	},
	{
		name: 'tv4',
		setup: function () {
			//adding this actually makes tv4 fail all tests with "Maximum call stack size exceeded" on loading schemas
			//Object.keys(refs).forEach(function (uri) {
			//	tv4.addSchema(uri, refs[uri]);
			//});
			return tv4;
		},
		test: function (instance, json, schema) {
			return instance.validateResult(json, schema).valid;
		}
	},
	{
		name: 'jsonschema',
		setup: function () {
			var validator = new JsonSchema.Validator();
			Object.keys(refs).forEach(function (uri) {
				validator.addSchema(refs[uri], uri);
			});
			return validator;
		},
		test: function (instance, json, schema) {
			return instance.validate(json, schema).errors.length === 0;
		}
	}
]);
<commit_msg>add revalidator<commit_after>var testRunner = require('./testRunner');

var ZSchema = require('z-schema');
var JaySchema = require('jayschema');
var jjv = require('jjv');
var jassi = require('jassi');
var jsv = require('JSV');
var JsonSchema = require('jsonschema');
var tv4 = require('tv4');
var JsonModel = require('json-model');
var Themis = require('themis');
var imjv = require('is-my-json-valid');
var jsck = require('jsck');
var requestValidator = require('request-validator');
var skeemas = require('skeemas');
var revalidator = require ('revalidator');

var refs = {
	'http://localhost:1234/integer.json': require('./JSON-Schema-Test-Suite/remotes/integer.json'),
	'http://localhost:1234/subSchemas.json': require('./JSON-Schema-Test-Suite/remotes/subSchemas.json'),
	'http://localhost:1234/folder/folderInteger.json': require('./JSON-Schema-Test-Suite/remotes/folder/folderInteger.json'),
	'http://json-schema.org/draft-03/schema': require('./refs/json-schema-draft-03.json'),
	'http://json-schema.org/draft-04/schema': require('./refs/json-schema-draft-04.json')
};

testRunner([
	{
		name: 'is-my-json-valid',
		setup: function (schema) {
			// no $refs supported
			return imjv(schema);
		},
		test: function (instance, json, schema) {
			return !!instance(json);
		}
	},
	{
		name: 'themis',
		setup: function (schema) {
			// $refs only supported if they have id attributes and the test suite refs do not
			return Themis.validator(schema);
		},
		test: function (instance, json, schema) {
			return instance(json, '0').valid;
		},
		benchmarks: 'https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html'
	},
	{
		name: 'z-schema',
		setup: function () {
			var validator = new ZSchema({
				ignoreUnresolvableReferences: true
			});
			Object.keys(refs).forEach(function (uri) {
				validator.setRemoteReference(uri, refs[uri]);
			});
			return validator;
		},
		test: function (instance, json, schema) {
			return instance.validate(json, schema);
		},
		benchmarks: 'https://rawgit.com/zaggino/z-schema/master/benchmark/results.html'
	},
	{
		name: 'jjv',
		setup: function () {
			var validator = jjv();
			Object.keys(refs).forEach(function (uri) {
				validator.addSchema(uri, refs[uri]);
			});
			return validator;
		},
		test: function (instance, json, schema) {
			return instance.validate(schema, json) === null;
		}
	},
	{
		name: 'skeemas',
		setup: function (schema) {
			var validator = skeemas();
			Object.keys(refs).forEach(function (uri) {
				validator.addRef(uri, refs[uri]);
			});
			return validator;
		},
		test: function (instance, json, schema) {
			return instance.validate(json, schema).valid;
		}
	},
	{
		name: 'jayschema',
		setup: function () {
			// $refs not supported with synchronous validation, only asyc
			return new JaySchema();
		},
		test: function (instance, json, schema) {
			return instance.validate(json, schema).length === 0;
		}
	},
	{
		name: 'jsck',
		setup: function (schema) {
			// no $refs supported
			return new jsck.draft4(schema);
		},
		test: function (instance, json, schema) {
			return instance.validate(json).valid;
		},
		benchmarks: 'https://github.com/pandastrike/jsck/blob/master/doc/benchmarks.md'
	},
	{
		name: 'jassi',
		// no $refs supported
		setup: function (schema) {
			return jassi;
		},
		test: function (instance, json, schema) {
			return instance(json, schema).length === 0;
		}
	},

	{
		name: 'JSV',
		setup: function (schema) {
			// no documented $refs supported
			return jsv;
		},
		test: function (instance, json, schema) {
			return instance.JSV.createEnvironment().validate(json, schema).errors.length === 0;
		}
	},
	{
		name: 'request-validator',
		setup: function (schema) {
			// no documented $refs supported
			return requestValidator(schema);
		},
		test: function (instance, json, schema) {
			try {
				instance.validate(json);
				return true;
			}
			catch (e) {
				return false;
			}
		}
	},
	{
		name: 'json-model',
		setup: function (schema) {
			// no comprehensible documented $refs supported
			return JsonModel.validator(schema);
		},
		test: function (instance, json, schema) {
			return instance(json).valid;
		}
	},
	{
		name: 'tv4',
		setup: function () {
			//adding this actually makes tv4 fail all tests with "Maximum call stack size exceeded" on loading schemas
			//Object.keys(refs).forEach(function (uri) {
			//	tv4.addSchema(uri, refs[uri]);
			//});
			return tv4;
		},
		test: function (instance, json, schema) {
			return instance.validateResult(json, schema).valid;
		}
	},
	{
		name: 'jsonschema',
		setup: function () {
			var validator = new JsonSchema.Validator();
			Object.keys(refs).forEach(function (uri) {
				validator.addSchema(refs[uri], uri);
			});
			return validator;
		},
		test: function (instance, json, schema) {
			return instance.validate(json, schema).errors.length === 0;
		}
	},
	{
		name: 'revalidator',
		setup: function () {
			return revalidator;
		},
		test: function (instance, json, schema) {
			return instance.validate(json, schema).valid;
		}
	}
]);
<|endoftext|>


<commit_before>var level = require('level')
var rimraf = require('rimraf')
var os = require('os')
var path = require('path')

function tmpdir () {
  return os.tmpdir ? os.tmpdir() : process.env.TMPDIR
}

module.exports = function (opts) {
  opts = opts || {}
  return function (name, opts, cb) {
    name = name || 'db_' + Date.now()
    var dir = path.join(tmpdir(), name)
    if(opts.clean !== false)
      rimraf.sync(dir)
    return level(dir, opts, cb)
  }

}

<commit_msg>fix dump mistake<commit_after>var level = require('level')
var rimraf = require('rimraf')
var os = require('os')
var path = require('path')

function tmpdir () {
  return os.tmpdir ? os.tmpdir() : process.env.TMPDIR
}

module.exports = function (opts) {
  opts = opts || {}
  return function (name, _opts, cb) {
    name = name || 'db_' + Date.now()
    var dir = path.join(tmpdir(), name)
    if(opts.clean !== false)
      rimraf.sync(dir)
    return level(dir, _opts, cb)
  }

}

<|endoftext|>


<commit_before>'use strict';

const babel = require('babel-core');
const anymatch = require('anymatch');

const reIg = /^(bower_components|node_modules\/[.-\w]-brunch|vendor)/;
const reJsx = /\.(es6|jsx|js)$/;

class BabelCompiler {
  constructor(config) {
    if (!config) config = {};
    const options = config.plugins &&
      (config.plugins.babel || config.plugins.ES6to5) || {};
    const opts = Object.keys(options).reduce((obj, key) => {
      if (key !== 'sourceMap' && key !== 'ignore') {
        obj[key] = options[key];
      }
      return obj;
    }, {});
    opts.sourceMap = !!config.sourceMaps;
    if (opts.pattern) {
      this.pattern = opts.pattern;
      delete opts.pattern;
    }
    if (!opts.presets) opts.presets = ['es2015'];
    if (opts.presets.indexOf('react') !== -1) this.pattern = reJsx;
    if (opts.presets.length === 0) delete opts.presets;
    this.isIgnored = anymatch(options.ignore || reIg);
    this.options = opts;
  }

  compile(params) {
    if (this.isIgnored(params.path)) return Promise.resolve(params);
    this.options.filename = params.path;

    return new Promise((resolve, reject) => {
      let compiled;
      try {
        compiled = babel.transform(params.data, this.options);
      } catch (err) {
        return reject(err);
      }
      var result = {data: compiled.code || compiled};

      // Concatenation is broken by trailing comments in files, which occur
      // frequently when comment nodes are lost in the AST from babel.
      result.data += '\n';

      if (compiled.map) result.map = JSON.stringify(compiled.map);
      resolve(result);
    });
  }
}

BabelCompiler.prototype.brunchPlugin = true;
BabelCompiler.prototype.type = 'javascript';
BabelCompiler.prototype.extension = 'js';

module.exports = BabelCompiler;
<commit_msg>Preserve folder structure for sourcemapped files.<commit_after>'use strict';

const babel = require('babel-core');
const anymatch = require('anymatch');

const reIg = /^(bower_components|node_modules\/[.-\w]-brunch|vendor)/;
const reJsx = /\.(es6|jsx|js)$/;

class BabelCompiler {
  constructor(config) {
    if (!config) config = {};
    const options = config.plugins &&
      (config.plugins.babel || config.plugins.ES6to5) || {};
    const opts = Object.keys(options).reduce((obj, key) => {
      if (key !== 'sourceMap' && key !== 'ignore') {
        obj[key] = options[key];
      }
      return obj;
    }, {});
    opts.sourceMap = !!config.sourceMaps;
    if (opts.pattern) {
      this.pattern = opts.pattern;
      delete opts.pattern;
    }
    if (!opts.presets) opts.presets = ['es2015'];
    if (opts.presets.indexOf('react') !== -1) this.pattern = reJsx;
    if (opts.presets.length === 0) delete opts.presets;
    this.isIgnored = anymatch(options.ignore || reIg);
    this.options = opts;
  }

  compile(params) {
    if (this.isIgnored(params.path)) return Promise.resolve(params);
    this.options.filename = params.path;
    this.options.sourceFileName = params.path;

    return new Promise((resolve, reject) => {
      let compiled;
      try {
        compiled = babel.transform(params.data, this.options);
      } catch (err) {
        return reject(err);
      }
      var result = {data: compiled.code || compiled};

      // Concatenation is broken by trailing comments in files, which occur
      // frequently when comment nodes are lost in the AST from babel.
      result.data += '\n';

      if (compiled.map) result.map = JSON.stringify(compiled.map);
      resolve(result);
    });
  }
}

BabelCompiler.prototype.brunchPlugin = true;
BabelCompiler.prototype.type = 'javascript';
BabelCompiler.prototype.extension = 'js';

module.exports = BabelCompiler;
<|endoftext|>


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

var argv = require('optimist').argv;
var check = require('./src/check-folder');

if (!module.parent) {
  var verbose = argv.verbose;
  var ok = check(process.cwd(), verbose);
  process.exit(ok ? 0 : 1);
  return;
}

module.exports = check;
<commit_msg>added --version command line option<commit_after>#!/usr/bin/env node

var argv = require('optimist').argv;
var check = require('./src/check-folder');

if (!module.parent) {
  if (argv.version) {
    var pkg = require('./package.json');
    console.log(pkg.name, pkg.version);
    process.exit(0);
    return;
  }
  var verbose = argv.verbose;
  var ok = check(process.cwd(), verbose);
  process.exit(ok ? 0 : 1);
  return;
}

module.exports = check;
<|endoftext|>


<commit_before>/** Dependency **/
var socketIO = require('socket.io');
var debug = require('debug')('remote-logger');

module.exports = function(app){

    /** Construct **/
    var io = socketIO(app);

    io.on('connection',function(socket){
        log('New client connected');
    });

    io.on('disconnect',function(){
        log('Client left');
    });

    /*
     * Send those event logs
     * @param data - Option Object
     *
     * **/
    var emitLog = function(data){

        /** Set date when the error is emited **/
        data.date = new Date().toISOString();

        io.emit("log", data);

        io.emit("log" + data.log_type, data);
    };

    /*
     * Log events using debug and web sockets.
     * @param data - Option Object
     *
     * **/
    var log = function(data){
        debug(data.message);

        emitLog(data);
    };

    /*
     * Option log builder
     * @param message
     * @param log-type
     * @param extraArgument (Object)
     *
     * **/
    var optionsBuilder = function(message, type, extraArguments){
        return {
            message: message,
            log_type: type,
            extra: extraArguments,
            date: null
        };
    };

    /** Public methods **/
    return {
        info: function(format, params){
            log(optionsBuilder(format, "INFO", params));
        },
        debug: function(format, params){
            log(optionsBuilder(format, "INFO", params));
        },
        error: function(format, params){
            log(optionsBuilder(format, "INFO", params));
        },
        fatal: function(format, params){
            log(optionsBuilder(format, "FATAL", params));
        }
    };
};

<commit_msg>constant to debug type, date changed to GMT String<commit_after>/** Dependency **/
var socketIO = require('socket.io');
var debug = require('debug')('remote-logger');

/*
 *
 * @param instance ( could be an socket.io instance or express server )
 *
 * **/
module.exports = function(instance){

    /** Construct **/
    var io = null;

    var logType = {
        INFO:"info",
        DEBUG:"debug",
        ERROR:"error",
        FATAL:"fatal"
    };

    if(instance instanceof socketIO){
        io = instance;
    }else{
        io = socketIO(instance);
    }

    io.on('connection',function(socket){
        log(optionsBuilder('New client connected'));
    });

    io.on('disconnect',function(){
        log(optionsBuilder('Client left'));
    });

    /*
     * Send those event logs
     * @param data - Option Object
     *
     * **/
    var emitLog = function(data){

        /** Set date when the error is emited **/
        data.date = new Date().toGMTString();

        io.emit("log", data);

        io.emit("log-" + data.log_type, data);
    };

    /*
     * Log events using debug and web sockets.
     * @param data - Option Object
     *
     * **/
    var log = function(data){
        debug("Log emitted " + data.message);

        emitLog(data);
    };

    /*
     * Option log builder
     * @param message
     * @param log-type
     * @param extraArgument (Object)
     *
     * **/
    var optionsBuilder = function(message, type, extraArguments){

        type = type == undefined? logType.INFO:type;

        return {
            message: message,
            log_type: type,
            extra: extraArguments,
            date: null
        };
    };

    /** Public methods **/
    return {
        info: function(format, params){
            log(optionsBuilder(format, logType.INFO, params));
        },
        debug: function(format, params){
            log(optionsBuilder(format, logType.DEBUG, params));
        },
        error: function(format, params){
            log(optionsBuilder(format, logType.ERROR, params));
        },
        fatal: function(format, params){
            log(optionsBuilder(format, logType.FATAL, params));
        }
    };
};

<|endoftext|>


<commit_before>module.exports = {
	book: { assets: "./book", css: [ "block.css" ] },
	hooks: {
		// Qiita記法を独自フォーマットに変換
		"page:before": function(page) {
			var regixAll = /([^\S]```.*)(:(.+))[\s\S]+?```/g;
			var regix = /([^\S]```.*)(:(.+))[\s\S]+?```/;
			var matchAll = page.content.match(regixAll);

			for(var i = 0; matchAll && i < matchAll.length; i++){
				var match = matchAll[i].match(regix);
				var input = match.input.replace(match[2], "");
				var replace = input.replace(match[1], "!FILENAME " + match[3] + match[1]);
				page.content = page.content.replace(match.input, replace);
			}

			return page;
		},

		// 独自フォーマットからfilenameタグを生成
		"page": function(page) {
			var regixAll = /(
!FILENAME\s([^\s]+)<\/p>)\n
[\s\S]*?(<\/pre>)/g;
			var regix = /(
!FILENAME\s([^\s]+)<\/p>)\n
[\s\S]*?(<\/pre>)/;
			var replacer = function(filename){
				return '
' + filename + '
';
			}

			for(var i = 0; i < page.sections.length; i++){
				var section = page.sections[i];
				var tagAll = section.content.match(regixAll);

				for(var j = 0; tagAll && j < tagAll.length; j++){
					var tag = section.content.match(regix);
					var replace = tag[0].replace(tag[1], replacer(tag[2]));
					section.content = section.content.replace(tag[0], replace);
				}
			}

			return page;
		}
	}
};
<commit_msg>コードブロック直前に文字がある場合のバグを修正<commit_after>module.exports = {
	book: { assets: "./book", css: [ "block.css" ] },
	hooks: {
		// Qiita記法を独自フォーマットに変換
		"page:before": function(page) {
			var regixAll = /([^\S]```.*)(:(.+))[\s\S]+?```/g;
			var regix = /([^\S]```.*)(:(.+))[\s\S]+?```/;
			var matchAll = page.content.match(regixAll);

			for(var i = 0; matchAll && i < matchAll.length; i++){
				var match = matchAll[i].match(regix);
				var input = match.input.replace(match[2], "");
				var replace = input.replace(match[1], "\n\n!FILENAME " + match[3] + match[1]);
				page.content = page.content.replace(match.input, replace);
			}

			return page;
		},

		// 独自フォーマットからfilenameタグを生成
		"page": function(page) {
			var regixAll = /(
!FILENAME\s+([\S].+)<\/p>)\n
[\s\S]*?(<\/pre>)/g;
			var regix = /(
!FILENAME\s+([\S].+)<\/p>)\n
[\s\S]*?(<\/pre>)/;
			var replacer = function(filename){
				return '
' + filename + '
';
			}

			for(var i = 0; i < page.sections.length; i++){
				var section = page.sections[i];
				var tagAll = section.content.match(regixAll);

				for(var j = 0; tagAll && j < tagAll.length; j++){
					console.log(section);
					var tag = section.content.match(regix);
					var replace = tag[0].replace(tag[1], replacer(tag[2]));
					section.content = section.content.replace(tag[0], replace);
				}
			}

			return page;
		}
	}
};

<|endoftext|>


<commit_before>/* globals process */
'use strict'

// other
const bigInt = require('big-integer')

// twitter api
const twitterParse = require('twitter-url-parser')
const twitterAPI = require('node-twitter-api')
const twitter = new twitterAPI({
  consumerKey: process.env.TWITTER_CONSUMER_KEY,
  consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
  callback: process.env.TWITTER_OAUTH_CALLBACK || 'http://localhost:8080/oauth'
})

// redis
const redis = require('redis')
const client = redis.createClient(process.env.REDIS_URL)

client.on('error', (error) => {
  console.log(error)
})

// express
const express = require('express')
const app = express()
const bodyParser = require('body-parser')

app.use(bodyParser.text())

// request body:
// id
// text
// username
app.post('/', (req, res) => {
  console.log(req.body)
  res.end()
  return

  const twitterId = twitterParse(req.body.link).id
  client.hgetall('access', (error, access) => {
    if (error) {
      console.log(error)
    } else if (access) {
      twitter.search(
        {
          q: req.body.text,
          max_id: bigInt(twitterId).minus(1).toString()
        },
        access.token,
        access.tokenSecret,
        (error, data, response) => {
          if (error) {
            console.log(error)
          }
          else if (data && data.statuses && data.statuses[0]) {
            twitter.statuses(
              'update',
              {
                status: 'ney'//'@' + req.body.username + ' @' + data.statuses[0].user.screen_name + ' https://twitter.com/' + data.statuses[0].user.screen_name + '/status/' + data.statuses[0].id_str,
                //in_reply_to_status_id: twitterId
              },
              access.token,
              access.tokenSecret,
              (error, data, response) => {
                if (error) {
                  console.log(error)
                }
              }
            )
          }
        })
    }
  })
  res.end()
})

app.get('/authenticate', (req, res) => {
  twitter.getRequestToken((error, requestToken, requestTokenSecret, results) => {
    if (error) {
      console.log('Error getting OAuth request token : ' + error)
    } else {
      client.del('request')
      client.hmset('request', 'token', requestToken, 'tokenSecret', requestTokenSecret, (error, result) => {
        if (error) {
          console.log(error)
        } else {
          res.redirect(twitter.getAuthUrl(requestToken))
        }
      })

    }
  })
})

app.get('/oauth', (req, res) => {
  client.hgetall('request', (error, request) => {
    if (error) {
      console.log(error)
    } else if (request) {
      twitter.getAccessToken(
        request.token,
        request.tokenSecret,
        req.query.oauth_verifier,
        (error, accessToken, accessTokenSecret, results) => {
          if (error) {
            console.log(error)
          } else {
            twitter.verifyCredentials(
              accessToken,
              accessTokenSecret,
              {},
              (error, data, response) => {
                if (error) {
                  console.log(error)
                } else {
                  client.del('access')
                  client.hmset('access', 'token', accessToken, 'tokenSecret', accessTokenSecret, (error, result) => {
                    if (error) {
                      console.log(error)
                    } else {
                      res.send(data['screen_name'])
                    }
                  })
                }
              })
          }
        })
    }
  })
})

app.listen(process.env.PORT || 8080, () => console.log('listening ' + (process.env.PORT || 8080)))
<commit_msg>rollback troubleshooting changes<commit_after>/* globals process */
'use strict'

// other
const bigInt = require('big-integer')

// twitter api
const twitterParse = require('twitter-url-parser')
const twitterAPI = require('node-twitter-api')
const twitter = new twitterAPI({
  consumerKey: process.env.TWITTER_CONSUMER_KEY,
  consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
  callback: process.env.TWITTER_OAUTH_CALLBACK || 'http://localhost:8080/oauth'
})

// redis
const redis = require('redis')
const client = redis.createClient(process.env.REDIS_URL)

client.on('error', (error) => {
  console.log(error)
})

// express
const express = require('express')
const app = express()
const bodyParser = require('body-parser')

app.use(bodyParser.json())

// request body:
// id
// text
// username
app.post('/', (req, res) => {
  const twitterId = twitterParse(req.body.link).id
  client.hgetall('access', (error, access) => {
    if (error) {
      console.log(error)
    } else if (access) {
      twitter.search(
        {
          q: req.body.text,
          max_id: bigInt(twitterId).minus(1).toString()
        },
        access.token,
        access.tokenSecret,
        (error, data, response) => {
          if (error) {
            console.log(error)
          }
          else if (data && data.statuses && data.statuses[0]) {
            twitter.statuses(
              'update',
              {
                status: 'ney'//'@' + req.body.username + ' @' + data.statuses[0].user.screen_name + ' https://twitter.com/' + data.statuses[0].user.screen_name + '/status/' + data.statuses[0].id_str,
                //in_reply_to_status_id: twitterId
              },
              access.token,
              access.tokenSecret,
              (error, data, response) => {
                if (error) {
                  console.log(error)
                }
              }
            )
          }
        })
    }
  })
  res.end()
})

app.get('/authenticate', (req, res) => {
  twitter.getRequestToken((error, requestToken, requestTokenSecret, results) => {
    if (error) {
      console.log('Error getting OAuth request token : ' + error)
    } else {
      client.del('request')
      client.hmset('request', 'token', requestToken, 'tokenSecret', requestTokenSecret, (error, result) => {
        if (error) {
          console.log(error)
        } else {
          res.redirect(twitter.getAuthUrl(requestToken))
        }
      })

    }
  })
})

app.get('/oauth', (req, res) => {
  client.hgetall('request', (error, request) => {
    if (error) {
      console.log(error)
    } else if (request) {
      twitter.getAccessToken(
        request.token,
        request.tokenSecret,
        req.query.oauth_verifier,
        (error, accessToken, accessTokenSecret, results) => {
          if (error) {
            console.log(error)
          } else {
            twitter.verifyCredentials(
              accessToken,
              accessTokenSecret,
              {},
              (error, data, response) => {
                if (error) {
                  console.log(error)
                } else {
                  client.del('access')
                  client.hmset('access', 'token', accessToken, 'tokenSecret', accessTokenSecret, (error, result) => {
                    if (error) {
                      console.log(error)
                    } else {
                      res.send(data['screen_name'])
                    }
                  })
                }
              })
          }
        })
    }
  })
})

app.listen(process.env.PORT || 8080, () => console.log('listening ' + (process.env.PORT || 8080)))
<|endoftext|>


<commit_before>/*!
 * expand-range <https://github.com/jonschlinkert/expand-range>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT license.
 */

'use strict';

var fill = require('fill-range');

module.exports = function expandRange(str, fn) {
  if (typeof str !== 'string') {
    throw new TypeError('expand-range expects a string.');
  }

  // create arguments to pass to fill-range
  var args = str.split('..');
  var len = args.length;

  // if only one argument, it can't expand so return it
  if (len === 1) { return args; }

  // if `true`, tell fill-range to regexify the string
  if (typeof fn === 'boolean' && fn === true) {
    fn = '~';

    if (len === 3) {
      args[len - 1] += fn;
      fn = null;
    }
  }

  return fill.apply(fill, args.concat(fn));
};
<commit_msg>make it easier to pass args to fill-range<commit_after>/*!
 * expand-range <https://github.com/jonschlinkert/expand-range>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT license.
 */

'use strict';

var fill = require('fill-range');

module.exports = function expandRange(str, options, fn) {
  if (typeof str !== 'string') {
    throw new TypeError('expand-range expects a string.');
  }

  if (typeof options === 'function') {
    fn = options;
    options = {};
  }

  if (typeof options === 'boolean') {
    options = {};
    options.makeRe = true;
  }

  // create arguments to pass to fill-range
  var opts = options || {};
  var args = str.split('..');
  var len = args.length;

  // if only one argument, it can't expand so return it
  if (len === 1) { return args; }

  // if `true`, tell fill-range to regexify the string
  if (typeof fn === 'boolean' && fn === true) {
    opts.makeRe = true;
  }

  args.push(opts);
  return fill.apply(fill, args.concat(fn));
};
<|endoftext|>


<commit_before>var latenize = require('latenize');

// Remove all non-ascii chars
function ascii(str) {
    return str.replace(/[^\x00-\x7F]/g, '');
}

// Basic normalization = latenize + ascii
// Common and basic
function base(str) {
    return ascii(latenize(str)).trim();
}

// Normalize str to be used as a filename
// Strip illegal chars found in http://en.wikipedia.org/wiki/Filename#Reserved%5Fcharacters%5Fand%5Fwords
function filename(str) {
    return base(str)
    .replace(/[\/\\\?\%\*\:\;\|\"\'\\<\\>\#\$\(\)\!\.\@]/g, '')
    .trim()
    .replace(/ /g, '_')
    .toLowerCase();
}

// Normalize name
function name(str) {
    return base(str);
}

// Exports
module.exports = base;
module.exports.ascii = ascii;
module.exports.name = name  ;
module.exports.filename = filename;

module.exports.latenize = latenize;
module.exports.accents = latenize;
<commit_msg>Replace 'name' by 'username'<commit_after>var latenize = require('latenize');

// Remove all non-ascii chars
function ascii(str) {
    return str.replace(/[^\x00-\x7F]/g, '');
}

// Basic normalization = latenize + ascii
// Common and basic
function base(str) {
    return ascii(latenize(str)).trim();
}

// Normalize str to be used as a filename
// Strip illegal chars found in http://en.wikipedia.org/wiki/Filename#Reserved%5Fcharacters%5Fand%5Fwords
function filename(str) {
    return base(str)
    .replace(/[\/\\\?\%\*\:\;\|\"\'\\<\\>\#\$\(\)\!\.\@]/g, '')
    .trim()
    .replace(/ /g, '_')
    .toLowerCase();
}

// Normalize name
function username(str) {
    return base(str).replace(/\s+/g, '');
}

// Exports
module.exports = base;
module.exports.ascii = ascii;
module.exports.username = username;
module.exports.filename = filename;

module.exports.latenize = latenize;
module.exports.accents = latenize;
<|endoftext|>


<commit_before>import { ATTR_KEY } from '../constants';
import { toLowerCase, empty, falsey, isFunction } from '../util';
import { optionsHook } from '../hooks';

export function ensureNodeData(node, data) {
	return node[ATTR_KEY] || (node[ATTR_KEY] = (data || {}));
}

export function getNodeType(node) {
	if (node instanceof Text) return 3;
	if (node instanceof Element) return 1;
	return 0;
}

/** Append multiple children to a Node.
 *	Uses a Document Fragment to batch when appending 2 or more children
 *	@private
 */

/** Removes a given DOM Node from its parent. */
export function removeNode(node) {
	let p = node.parentNode;
	if (p) p.removeChild(node);
}

/** Set a named attribute on the given Node, with special behavior for some names and event handlers.
 *	If `value` is `null`, the attribute/handler will be removed.
 *	@param {Element} node	An element to mutate
 *	@param {string} name	The name/key to set, such as an event or attribute name
 *	@param {any} value		An attribute value, such as a function to be used as an event handler
 *	@param {any} previousValue	The last value that was set for this name/node pair
 *	@private
 */
export function setAccessor(node, name, value) {
	ensureNodeData(node)[name] = value;

	if (name==='key' || name==='children') return;

	if (name==='class') {
		node.className = value || '';
	}
	else if (name==='style') {
		node.style.cssText = value || '';
	}
	else if (name==='dangerouslySetInnerHTML') {
		if (value && value.__html) node.innerHTML = value.__html;
	}
	else if (name!=='type' && name in node) {
		setProperty(node, name, empty(value) ? '' : value);
		if (falsey(value)) node.removeAttribute(name);
	}
	else if (name[0]==='o' && name[1]==='n') {
		let type = normalizeEventName(name),
			l = node._listeners || (node._listeners = {});
		if (!l[type]) node.addEventListener(type, eventProxy);
		else if (!value) node.removeEventListener(type, eventProxy);
		l[type] = value;
	}
	else if (falsey(value)) {
		node.removeAttribute(name);
	}
	else if (typeof value!=='object' && !isFunction(value)) {
		node.setAttribute(name, value);
	}
}

/** Attempt to set a DOM property to the given value.
 *	IE & FF throw for certain property-value combinations.
 */
function setProperty(node, name, value) {
	try {
		node[name] = value;
	} catch (e) { }
}

/** Proxy an event to hooked event handlers
 *	@private
 */
function eventProxy(e) {
	return this._listeners[normalizeEventName(e.type)](optionsHook('event', e) || e);
}

/** Convert an Event name/type to lowercase and strip any "on*" prefix.
 *	@function
 *	@private
 */
let normalizeEventName = memoize( t => toLowerCase(t.replace(/^on/i,'')) );

/** Get a node's attributes as a hashmap.
 *	@private
 */
export function getRawNodeAttributes(node) {
	let list = node.attributes,
		attrs = {},
		i = list.length;
	while (i--) attrs[list[i].name] = list[i].value;
	return attrs;
}
<commit_msg>Small size & performance optimizations for event handlers and attributes.<commit_after>import { ATTR_KEY } from '../constants';
import { toLowerCase, empty, falsey, isFunction } from '../util';
import { optionsHook } from '../hooks';

export function ensureNodeData(node, data) {
	return node[ATTR_KEY] || (node[ATTR_KEY] = (data || {}));
}

export function getNodeType(node) {
	if (node instanceof Text) return 3;
	if (node instanceof Element) return 1;
	return 0;
}

/** Append multiple children to a Node.
 *	Uses a Document Fragment to batch when appending 2 or more children
 *	@private
 */

/** Removes a given DOM Node from its parent. */
export function removeNode(node) {
	let p = node.parentNode;
	if (p) p.removeChild(node);
}

/** Set a named attribute on the given Node, with special behavior for some names and event handlers.
 *	If `value` is `null`, the attribute/handler will be removed.
 *	@param {Element} node	An element to mutate
 *	@param {string} name	The name/key to set, such as an event or attribute name
 *	@param {any} value		An attribute value, such as a function to be used as an event handler
 *	@param {any} previousValue	The last value that was set for this name/node pair
 *	@private
 */
export function setAccessor(node, name, value) {
	ensureNodeData(node)[name] = value;

	if (name==='key' || name==='children') return;

	if (name==='class') {
		node.className = value || '';
	}
	else if (name==='style') {
		node.style.cssText = value || '';
	}
	else if (name==='dangerouslySetInnerHTML') {
		if (value && value.__html) node.innerHTML = value.__html;
	}
	else if (name!=='type' && name in node) {
		setProperty(node, name, empty(value) ? '' : value);
		if (falsey(value)) node.removeAttribute(name);
	}
	else if (name[0]==='o' && name[1]==='n') {
		let l = node._listeners || (node._listeners = {});
		name = toLowerCase(name.substring(2));
		if (!l[name]) node.addEventListener(name, eventProxy);
		else if (!value) node.removeEventListener(name, eventProxy);
		l[name] = value;
	}
	else if (falsey(value)) {
		node.removeAttribute(name);
	}
	else if (typeof value!=='object' && !isFunction(value)) {
		node.setAttribute(name, value);
	}
}

/** Attempt to set a DOM property to the given value.
 *	IE & FF throw for certain property-value combinations.
 */
function setProperty(node, name, value) {
	try {
		node[name] = value;
	} catch (e) { }
}

/** Proxy an event to hooked event handlers
 *	@private
 */
function eventProxy(e) {
	return this._listeners[toLowerCase(e.type)](optionsHook('event', e) || e);
}

/** Get a node's attributes as a hashmap.
 *	@private
 */
export function getRawNodeAttributes(node) {
	let attrs = {};
	for (let i=node.attributes.length; i--; ) {
		attrs[node.attributes[i].name] = node.attributes[i].value;
	}
	return attrs;
}
<|endoftext|>


<commit_before>'use strict';

var PLUGIN_NAME = 'gulp-zetzer';
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var through = require('through2');
var _ = require('underscore');
var fs = require('fs');

var parse_setup = require('zetzer/parse');
var compilers_setup = require('zetzer/compilers');
var process_file_setup = require('zetzer/process');

module.exports = function (opts) {
    if (!opts) {
        throw new PluginError(PLUGIN_NAME, 'Missing options!');
    }

    var options = _.extend({
        partials: '.',
        templates: '.',
        env: {},
        dot_template_settings: {},
        meta_data_separator: /\r?\n\r?\n/
    }, opts);

    var parse = parse_setup(options.meta_data_separator);

    //var compile =  compilers_setup({
    //    read_content: _.compose(parse.content, grunt.file.read),
    //    compilers: [
    //        require("zetzer/dot")({
    //            template_settings: options.dot_template_settings
    //        }),
    //        require("zetzer/markdown")
    //    ]
    //});

    //var process_file = new process_file_setup({
    //    options: options,
    //    compile: compile,
    //    read_header: _.compose(parse.header, grunt.file.read),
    //    find_closest_match: file.find_closest_match
    //});

    function find_closest_match (folder, filename) {
        //if (!grunt.file.isDir(folder)) grunt.fail.warn("The folder " + folder + " does not exist.");
        //
        var pattern = build_pattern(folder, filename);

        //var filepath = grunt.file.expand(pattern);
        //
        //// Warn again if the resulting file doesn't exist
        //if (!filepath.length) grunt.fail.warn("The file " + pattern + " cannot be found.");

        //return filepath[0];
        //gutil.log('find_closest_match folder: ' + folder);
        //gutil.log('find_closest_match filename: ' + filename);
        //gutil.log('find_closest_match pattern: ' + pattern);
        return pattern;
    }

    function build_pattern (folder, filename) {
        var separator = "";
        if (folder) {
            separator = folder.length ? "/" : "";
        }
        var extension = has_extension(filename) ? "" : ".*";
        return folder + separator + filename + extension;
    }

    function has_extension (filename) {
        return filename.toString().match(/\.[0-9a-z]+$/i);
    }

    //this.files.forEach(function (mapping) {
    //    var result = process_file(mapping.src).toString();
    //    grunt.file.write(mapping.dest, result);
    //});

	return through.obj(function (file, enc, cb) {
		if (file.isNull()) {
			return cb(null, file);
		}

        if (file.isStream()) {
            this.emit('error', new PluginError(PLUGIN_NAME, 'Streams are not supported!'));
            return cb();
        }

        if (file.isBuffer()) {
            //gutil.log('file is buffer: ' + file.path);
            //var prefixText = new Buffer('PREFIX TEXT - ');
            //file.contents = Buffer.concat([prefixText, file.contents]);

            //gutil.log('file');
            //gutil.log(file.relative);
            //gutil.log(file.contents);

            var compile =  compilers_setup({
                read_content: function(input_file) { return parse.content(fs.readFileSync(input_file, 'utf8')); }, // _.compose(parse.content, fs.readFileSync),
                compilers: [
                    require('zetzer/dot')({
                        template_settings: options.dot_template_settings
                    }),
                    require('zetzer/markdown')
                ]
            });

            var process_file = new process_file_setup({
                options: options,
                compile: compile,
                read_header: function(input_file) { return parse.header(fs.readFileSync(input_file, 'utf8')); }, // _.compose(parse.header, fs.readFileSync),
                find_closest_match: find_closest_match
            });

            console.log('Processing ' + file.relative);
            var contents = process_file(file.relative).toString();
            file.contents = new Buffer(contents);
            //grunt.file.write(mapping.dest, result);
        }

		cb(null, file);
	});
};
<commit_msg>removed underscore<commit_after>'use strict';

var PLUGIN_NAME = 'gulp-zetzer';
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var through = require('through2');
//var _ = require('underscore');
var fs = require('fs');

var parse_setup = require('zetzer/parse');
var compilers_setup = require('zetzer/compilers');
var process_file_setup = require('zetzer/process');

module.exports = function (opts) {
    if (!opts) {
        throw new PluginError(PLUGIN_NAME, 'Missing options!');
    }

    Object.prototype.extend = function (obj) {
        for (var i in obj) {
            if (obj.hasOwnProperty(i)) {
                this[i] = obj[i];
            }
        }
    };

    var options = {
        partials: '.',
        templates: '.',
        env: {},
        dot_template_settings: {},
        meta_data_separator: /\r?\n\r?\n/
    };

    options.extend(opts);

    //var options = _.extend({
    //    partials: '.',
    //    templates: '.',
    //    env: {},
    //    dot_template_settings: {},
    //    meta_data_separator: /\r?\n\r?\n/
    //}, opts);

    var parse = parse_setup(options.meta_data_separator);

    //var compile =  compilers_setup({
    //    read_content: _.compose(parse.content, grunt.file.read),
    //    compilers: [
    //        require("zetzer/dot")({
    //            template_settings: options.dot_template_settings
    //        }),
    //        require("zetzer/markdown")
    //    ]
    //});

    //var process_file = new process_file_setup({
    //    options: options,
    //    compile: compile,
    //    read_header: _.compose(parse.header, grunt.file.read),
    //    find_closest_match: file.find_closest_match
    //});

    function find_closest_match (folder, filename) {
        //if (!grunt.file.isDir(folder)) grunt.fail.warn("The folder " + folder + " does not exist.");
        //
        var pattern = build_pattern(folder, filename);

        //var filepath = grunt.file.expand(pattern);
        //
        //// Warn again if the resulting file doesn't exist
        //if (!filepath.length) grunt.fail.warn("The file " + pattern + " cannot be found.");

        //return filepath[0];
        //gutil.log('find_closest_match folder: ' + folder);
        //gutil.log('find_closest_match filename: ' + filename);
        //gutil.log('find_closest_match pattern: ' + pattern);
        return pattern;
    }

    function build_pattern (folder, filename) {
        var separator = "";
        if (folder) {
            separator = folder.length ? "/" : "";
        }
        var extension = has_extension(filename) ? "" : ".*";
        return folder + separator + filename + extension;
    }

    function has_extension (filename) {
        return filename.toString().match(/\.[0-9a-z]+$/i);
    }

    //this.files.forEach(function (mapping) {
    //    var result = process_file(mapping.src).toString();
    //    grunt.file.write(mapping.dest, result);
    //});

	return through.obj(function (file, enc, cb) {
		if (file.isNull()) {
			return cb(null, file);
		}

        if (file.isStream()) {
            this.emit('error', new PluginError(PLUGIN_NAME, 'Streams are not supported!'));
            return cb();
        }

        if (file.isBuffer()) {
            //gutil.log('file is buffer: ' + file.path);
            //var prefixText = new Buffer('PREFIX TEXT - ');
            //file.contents = Buffer.concat([prefixText, file.contents]);

            //gutil.log('file');
            //gutil.log(file.relative);
            //gutil.log(file.contents);

            var compile =  compilers_setup({
                read_content: function(input_file) { return parse.content(fs.readFileSync(input_file, 'utf8')); }, // _.compose(parse.content, fs.readFileSync),
                compilers: [
                    require('zetzer/dot')({
                        template_settings: options.dot_template_settings
                    }),
                    require('zetzer/markdown')
                ]
            });

            var process_file = new process_file_setup({
                options: options,
                compile: compile,
                read_header: function(input_file) { return parse.header(fs.readFileSync(input_file, 'utf8')); }, // _.compose(parse.header, fs.readFileSync),
                find_closest_match: find_closest_match
            });

            console.log('Processing ' + file.relative);
            var contents = process_file(file.relative).toString();
            file.contents = new Buffer(contents);
            //grunt.file.write(mapping.dest, result);
        }

		cb(null, file);
	});
};
<|endoftext|>


<commit_before>module.exports = {
	/**
	* Collection of supported voting methods
	* @var {array}
	*/
	methods: [
		{
			id: 'simpleMajority',
			title: 'Simple Majority',
			description: '50% + 1 wins',
		},
		{
			id: '2/3rds',
			title: 'Two-thirds majority',
			description: 'FIXME',
		},
		{
			id: '3/5ths',
			title: 'Three-fifths majority',
			description: 'FIXME',
		},
		{
			id: 'unsc',
			title: 'UN Security Council (9/14ths)',
			description: 'Abstentions do not count during calculation',
		},
		{
			id: 'unanimous',
			title: 'Unanimous',
			description: 'All votes must be in favour, none must reject to pass',
		},
	],

	/**
	* Calculate Win/Lose ratios for various voting types
	* @param {Object} options Options to use
	* @param {string} options.method The vote method to use (see code for valid types)
	* @param {number} options.total The total number of votes
	* @param {number} options.abstain Optional number of the number of abstentions
	* @return {Object} New structure containing voters, toWin, toLose
	*/
	getWinLose: function(options) {
		var realTotal = options.total - (options.abstain || 0);
		switch (options.method) {
			case '2/3rds':
				if (realTotal == 0) return {toWin: 0, toLose: 0, voters: 0};
				if (realTotal == 1) return {toWin: 1, toLose: 1, voters: 1};
				if (realTotal == 2) return {toWin: 2, toLose: 1, voters: 2};

				var third = Math.floor(realTotal / 3);
				return {
					toWin: third * 2,
					toLose: third * 1 + 1,
					voters: realTotal,
				};
				break;
			case '3/5ths':
				if (realTotal == 0) return {toWin: 0, toLose: 0, voters: 0};
				if (realTotal == 1) return {toWin: 1, toLose: 1, voters: 1};
				if (realTotal == 2) return {toWin: 2, toLose: 1, voters: 2};
				if (realTotal == 3) return {toWin: 3, toLose: 1, voters: 3};
				if (realTotal == 4) return {toWin: 3, toLose: 2, voters: 4};

				var fifth = Math.ceil(realTotal / 5);
				return {
					toWin: fifth * 3 + 1,
					toLose: fifth * 2,
					voters: realTotal,
				};
				break;
			case 'unsc':
				realTotal = options.total; // Abstentions are ignored in the UNSC. Total SHOULD also be 14 but we're going to allow for more here

				var segment = realTotal / 14;
				return {
					toWin: Math.ceil(segment * 9),
					toLose: Math.ceil(segment * 5),
					voters: realTotal,
				};
				break;
			case 'unanimous':
				if (realTotal == 0) return {toWin: 0, toLose: 0, voters: 0};

				return {
					toWin: realTotal,
					toLose: 1,
					voters: realTotal,
				};
				break;
			case 'simpleMajority':
				if (realTotal == 0) return {toWin: 0, toLose: 0, voters: 0};
				if (realTotal == 1) return {toWin: 1, toLose: 1, voters: 1};

				return {
					toWin: Math.ceil(realTotal / 2) + 1,
					toLose: Math.ceil(realTotal / 2),
					voters: realTotal,
				};
				break;
			default:
				throw new Error('Unknown vote method: ' + options.method);
		}
	},
};
<commit_msg>Added descriptions to all tests<commit_after>module.exports = {
	/**
	* Collection of supported voting methods
	* @var {array}
	*/
	methods: [
		{
			id: 'simpleMajority',
			title: 'Simple Majority',
			description: 'Voting method employed on non-substantive matters in the UN - 50% + 1 vote passes',
		},
		{
			id: '2/3rds',
			title: 'Two-thirds majority',
			description: 'The common voting ratio used for substantive matters in the UN',
		},
		{
			id: '3/5ths',
			title: 'Three-fifths majority',
			description: 'Used by UN Youth Australia (UNYA) in the Model United Nations competition',
		},
		{
			id: 'unsc',
			title: 'UN Security Council (9/14ths)',
			description: 'Used by the UN Security Council in - abstentions do not count during vote counts',
		},
		{
			id: 'unanimous',
			title: 'Unanimous',
			description: 'All votes must be in favour, none must reject to pass',
		},
	],

	/**
	* Calculate Win/Lose ratios for various voting types
	* @param {Object} options Options to use
	* @param {string} options.method The vote method to use (see code for valid types)
	* @param {number} options.total The total number of votes
	* @param {number} options.abstain Optional number of the number of abstentions
	* @return {Object} New structure containing voters, toWin, toLose
	*/
	getWinLose: function(options) {
		var realTotal = options.total - (options.abstain || 0);
		switch (options.method) {
			case '2/3rds':
				if (realTotal == 0) return {toWin: 0, toLose: 0, voters: 0};
				if (realTotal == 1) return {toWin: 1, toLose: 1, voters: 1};
				if (realTotal == 2) return {toWin: 2, toLose: 1, voters: 2};

				var third = Math.floor(realTotal / 3);
				return {
					toWin: third * 2,
					toLose: third * 1 + 1,
					voters: realTotal,
				};
				break;
			case '3/5ths':
				if (realTotal == 0) return {toWin: 0, toLose: 0, voters: 0};
				if (realTotal == 1) return {toWin: 1, toLose: 1, voters: 1};
				if (realTotal == 2) return {toWin: 2, toLose: 1, voters: 2};
				if (realTotal == 3) return {toWin: 3, toLose: 1, voters: 3};
				if (realTotal == 4) return {toWin: 3, toLose: 2, voters: 4};

				var fifth = Math.ceil(realTotal / 5);
				return {
					toWin: fifth * 3 + 1,
					toLose: fifth * 2,
					voters: realTotal,
				};
				break;
			case 'unsc':
				realTotal = options.total; // Abstentions are ignored in the UNSC. Total SHOULD also be 14 but we're going to allow for more here

				var segment = realTotal / 14;
				return {
					toWin: Math.ceil(segment * 9),
					toLose: Math.ceil(segment * 5),
					voters: realTotal,
				};
				break;
			case 'unanimous':
				if (realTotal == 0) return {toWin: 0, toLose: 0, voters: 0};

				return {
					toWin: realTotal,
					toLose: 1,
					voters: realTotal,
				};
				break;
			case 'simpleMajority':
				if (realTotal == 0) return {toWin: 0, toLose: 0, voters: 0};
				if (realTotal == 1) return {toWin: 1, toLose: 1, voters: 1};

				return {
					toWin: Math.ceil(realTotal / 2) + 1,
					toLose: Math.ceil(realTotal / 2),
					voters: realTotal,
				};
				break;
			default:
				throw new Error('Unknown vote method: ' + options.method);
		}
	},
};
<|endoftext|>


<commit_before>"use strict";

// stdlib
var Fs = require('fs');

// nodeca
var NLib = require('nlib');

// 3rd-party
var StaticLulz = require('static-lulz');
var FsTools = NLib.Vendor.FsTools;
var Async = NLib.Vendor.Async;

module.exports = NLib.Application.create({
  root: __dirname,
  name: 'nodeca.core',
  bootstrap: function (nodeca, callback) {
    // empty bootstrap... for now..
    callback();
  }
});

global.nodeca.hooks.init.after('bundles', function (next) {
  nodeca.runtime.assets_server = new StaticLulz();

  FsTools.walk(nodeca.runtime.assets_path, function (file, stats, next_file) {
    // Fill in Static lulz with files and data
    Async.waterfall([
      Async.apply(Fs.readFile, file),
      function (buffer, callback) {
        var rel_path = file.replace(nodeca.runtime.assets_path, '');
        nodeca.runtime.assets_server.add(rel_path, buffer);
        callback();
      }
    ], next_file);
  }, next);
});

global.nodeca.hooks.init.after('initialization', function (next) {
  var http_server = connect.createServer();
  next();
});

////////////////////////////////////////////////////////////////////////////////
// vim:ts=2:sw=2
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Add server stub<commit_after>"use strict";

// stdlib
var Fs = require('fs');

// nodeca
var NLib = require('nlib');

// 3rd-party
var StaticLulz = require('static-lulz');
var FsTools = NLib.Vendor.FsTools;
var Async = NLib.Vendor.Async;
var Connect = require('connect');

module.exports = NLib.Application.create({
  root: __dirname,
  name: 'nodeca.core',
  bootstrap: function (nodeca, callback) {
    // empty bootstrap... for now..
    callback();
  }
});

global.nodeca.hooks.init.after('bundles', function (next) {
  nodeca.runtime.assets_server = new StaticLulz();

  FsTools.walk(nodeca.runtime.assets_path, function (file, stats, next_file) {
    // Fill in Static lulz with files and data
    Async.waterfall([
      Async.apply(Fs.readFile, file),
      function (buffer, callback) {
        var rel_path = file.replace(nodeca.runtime.assets_path, '');
        nodeca.runtime.assets_server.add(rel_path, buffer);
        callback();
      }
    ], next_file);
  }, next);
});

global.nodeca.hooks.init.after('initialization', function (next) {
  var app = Connect();

  app.use("/", function (req, res) {
    nodeca.logger.error('got request');
    res.end('Hello World');
  });

  require('http').createServer(app).listen(3000);
  next();
});

////////////////////////////////////////////////////////////////////////////////
// vim:ts=2:sw=2
////////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>var Path = require ( "path" ) ;
var fs = require ( "fs" ) ;

var d = Path.join ( __dirname, "/src/" ) ;
var gepard = require ( Path.join ( d, "./Tango" ) ) ;
var _clientCounter = 1 ;
var _Instances = {} ;

gepard.getClient = function ( port, host )
{
	port = port ? port : undefined ;
	host = host ? host : undefined ;
	if ( ! port )
	{
		port = gepard.getProperty ( "gepard.port", "17501" ) ;
	}
	if ( ! host )
	{
		host = gepard.getProperty ( "gepard.host" ) ;
	}
 	var c = _Instances["" + host + ":" + port] ;
  if ( c )
  {
  	return c ;
  }
  c = new gepard.Client ( port, host ) ;
  c.on ( "end", function onend()
  {
  	delete gepard._Instances["" + host + ":" + port] ;
  } ) ;
  c.on ( "shutdown", function onend()
  {
  	delete gepard._Instances["" + host + ":" + port] ;
  } ) ;
  c.on ( "error", function onend()
  {
  	delete gepard._Instances["" + host + ":" + port] ;
  } ) ;
  c._clientCounter = _clientCounter++ ;
  _Instances["" + host + ":" + port] = c
  return c ;
 }

function collectFiles ( target, packageName, dir )
{
	if ( packageName )
	{
		target[packageName] = {} ;
		target = target[packageName] ;
		gepard._packageNames[packageName] = true ;
	}
	var a = fs.readdirSync ( dir ) ;
	for ( var i = 0 ; i < a.length ; i++ )
	{
		if ( a[i] === "Tango.js" ) continue ;
		var fname = Path.join ( dir, a[i] ) ;
		if ( fs.statSync ( fname ).isDirectory() )
		{
			if ( a[i] !== "node_modules" )
			{
				collectFiles ( target, a[i], fname ) ;
				continue ;
			}
		}
		var proxyFunction = function ( fullName )
		{
			return function getterFunction () { return require ( fullName ) ; }
		};
		if ( a[i].indexOf ( ".js" ) !== a[i].length - 3 ) continue ;
		if ( fs.statSync ( fname ).isDirectory() ) continue ;

		var cn = a[i].substring ( 0, a[i].length - 3 ) ;
		var fn = proxyFunction ( fname ) ;
		target.__defineGetter__( cn, fn ) ;
	}
	a.length = 0 ;
}
gepard.exists = function ( name )
{
	return this[name] !== "undefined" ;
};

gepard._vetoHash = {} ;
for ( var k in this )
{
	gepard._vetoHash[k] = true ;
}
gepard._packageNames = {} ;

collectFiles ( gepard, "", d ) ;

module.exports = gepard ;
<commit_msg>Python start+Docu<commit_after>var Path = require ( "path" ) ;
var fs = require ( "fs" ) ;

var d = Path.join ( __dirname, "/src/" ) ;
var gepard = require ( Path.join ( d, "./Tango" ) ) ;
var _clientCounter = 1 ;
var _Instances = {} ;

gepard.getClient = function ( port, host )
{
	port = port ? port : undefined ;
	host = host ? host : undefined ;
	if ( ! port )
	{
		port = gepard.getProperty ( "gepard.port", "17501" ) ;
	}
	if ( ! host )
	{
		host = gepard.getProperty ( "gepard.host" ) ;
	}
	var c = _Instances["" + host + ":" + port] ;
	if ( c )
	{
		return c ;
	}
	c = new gepard.Client ( port, host ) ;
	c.on ( "end", function onend()
	{
		delete gepard._Instances["" + host + ":" + port] ;
	} ) ;
	c.on ( "shutdown", function onend()
	{
		delete gepard._Instances["" + host + ":" + port] ;
	} ) ;
	c.on ( "error", function onend()
	{
		delete gepard._Instances["" + host + ":" + port] ;
	} ) ;
	c._clientCounter = _clientCounter++ ;
	_Instances["" + host + ":" + port] = c
	return c ;
 }

function collectFiles ( target, packageName, dir )
{
	if ( packageName )
	{
		target[packageName] = {} ;
		target = target[packageName] ;
		gepard._packageNames[packageName] = true ;
	}
	var a = fs.readdirSync ( dir ) ;
	for ( var i = 0 ; i < a.length ; i++ )
	{
		if ( a[i] === "Tango.js" ) continue ;
		var fname = Path.join ( dir, a[i] ) ;
		if ( fs.statSync ( fname ).isDirectory() )
		{
			if ( a[i] !== "node_modules" )
			{
				collectFiles ( target, a[i], fname ) ;
				continue ;
			}
		}
		var proxyFunction = function ( fullName )
		{
			return function getterFunction () { return require ( fullName ) ; }
		};
		if ( a[i].indexOf ( ".js" ) !== a[i].length - 3 ) continue ;
		if ( fs.statSync ( fname ).isDirectory() ) continue ;

		var cn = a[i].substring ( 0, a[i].length - 3 ) ;
		var fn = proxyFunction ( fname ) ;
		target.__defineGetter__( cn, fn ) ;
	}
	a.length = 0 ;
}
gepard.exists = function ( name )
{
	return this[name] !== "undefined" ;
};

gepard._vetoHash = {} ;
for ( var k in this )
{
	gepard._vetoHash[k] = true ;
}
gepard._packageNames = {} ;

collectFiles ( gepard, "", d ) ;

module.exports = gepard ;
<|endoftext|>


<commit_before>// Copyright 2014 Andrei Karpushonak

var _ = require('lodash')

var deleteKeysFromObject = function (object, keys) {
  var keysToDelete;

  // do not modify original object
  var finalObject = _.clone(object, isDeep = true)

  if (typeof finalObject === 'undefined') throw new Error('undefined is not a valid object.')
  if (arguments.length != 2) throw new Error("provide two parameters: object and list of keys")

  // collect keys
  if (Array.isArray(keys)) {
    keysToDelete = keys
  } else {
    keysToDelete = [keys]
  }

  keysToDelete.forEach(function(elem) {
    for(var prop in finalObject) {
      if(finalObject.hasOwnProperty(prop))
        if (elem === prop) {
          var deleteResult = delete finalObject[prop]
        } else {
          finalObject[prop] = deleteKeysFromObject(finalObject[prop], keysToDelete)
        }
    }
  })

  return finalObject

}

module.exports = deleteKeysFromObject

<commit_msg>Do not deep copy objects<commit_after>// Copyright 2014 Andrei Karpushonak

var _ = require('lodash')

var deleteKeysFromObject = function (object, keys) {
  var keysToDelete;

  // do not modify original object
  var finalObject = _.clone(object)

  if (typeof finalObject === 'undefined') throw new Error('undefined is not a valid object.')
  if (arguments.length != 2) throw new Error("provide two parameters: object and list of keys")

  // collect keys
  if (Array.isArray(keys)) {
    keysToDelete = keys
  } else {
    keysToDelete = [keys]
  }

  keysToDelete.forEach(function(elem) {
    for(var prop in finalObject) {
      if(finalObject.hasOwnProperty(prop))
        if (elem === prop) {
          var deleteResult = delete finalObject[prop]
        } else {
          finalObject[prop] = deleteKeysFromObject(finalObject[prop], keysToDelete)
        }
    }
  })

  return finalObject

}

module.exports = deleteKeysFromObject

<|endoftext|>


<commit_before>var exec = require('child_process').exec;

var textos = ["q?","Q?"];
var nasus_quotes = [
"Who let the dogs out? Woof. Woof. Woof.",
"No, I will not fetch the ball.",
"My bite is worse than my bark.",
"The cycle of life and death continues. We will live, they will die.",
"Do not try my patience.",
"Life is part of a cycle. Yours is over.",
"Your soul will be measured.",
"Return to the dust."
];

var nasus = exec('tweet stream "nasus" --json');
console.log("Reading 'nasus' tweets");
nasus.stdout.on('data', function(data) {
    var dados = JSON.parse(data);
    console.log("@"+dados.user.screen_name+": "+dados.text);
    var textoAleatorio = textos[Math.floor(Math.random()*textos.length)];
    var comando = 'tweet new "@'+dados.user.screen_name+' '+textoAleatorio+'"';
    var newTweet = exec(comando);
    console.log(comando);
    newTweet.stdout.on('data', function(nasusData) {
      console.log(nasusData);
    });
    newTweet.stderr.on('data', function(data) {
      console.log(data);
    });
});
nasus.on('close', function(code) {
  console.log("stream 'nasus': "+code);
  process.exit();
});
nasus.stderr.on('data', function(data) {
  console.log("stream 'nasus': "+data);
});

var reply = exec('tweet stream "@such_nasus" --json');
console.log("Reading '@such_nasus' tweets");
reply.stdout.on('data', function(data) {
    var dados = JSON.parse(data);
    console.log("@"+dados.user.screen_name+": "+dados.text);
    var quoteAleatorio = nasus_quotes[Math.floor(Math.random()*nasus_quotes.length)];
    var comando = 'tweet new "@'+dados.user.screen_name+' '+quoteAleatorio+'"';
    var newTweet = exec(comando);
    console.log(comando);
    newTweet.stdout.on('data', function(nasusData) {
      console.log(nasusData);
    });
    newTweet.stderr.on('data', function(nasusData) {
      console.log(nasusData);
    });
});
reply.on('close', function(code) {
  console.log("stream '@such_nasus': "+code);
  process.exit();
});
reply.stderr.on('data', function(data) {
  console.log("stream '@such_nasus': "+data);
});
<commit_msg>updating so much thing...<commit_after>var exec = require('child_process').exec;

var textos = ["q?","Q?"];
var nasus_quotes = [
"Who let the dogs out? Woof. Woof. Woof.",
"No, I will not fetch the ball.",
"My bite is worse than my bark.",
"The cycle of life and death continues. We will live, they will die.",
"Do not try my patience.",
"Life is part of a cycle. Yours is over.",
"Your soul will be measured.",
"Return to the dust."
];

var nasus = exec('tweet stream "nasus" --json');
showScreen("Reading 'nasus' tweets");
nasus.stdout.on('data', function(data) {
    var dados = JSON.parse(data);
    showScreen("@"+dados.user.screen_name+": "+dados.text);
    var textoAleatorio = textos[Math.floor(Math.random()*textos.length)];
    var comando = 'tweet new "@'+dados.user.screen_name+' '+textoAleatorio+'"';
    var newTweet = exec(comando);
    showScreen(comando);
    newTweet.stdout.on('data', function(nasusData) {
      showScreen(nasusData);
    });
    newTweet.stderr.on('data', function(data) {
      showScreen(data);
    });
});
nasus.on('close', function(code) {
  showScreen("stream 'nasus': "+code);
  if(code=="Parsing error:Easy there, Turbo. Too many requests recently. Enhance your calm."){
    setTimeout(function() {showScreen('Waiting twitter for a calm down...');}, 30000);
  }
  process.exit();
});
nasus.stderr.on('data', function(data) {
  showScreen("stream 'nasus': "+data);
});

var reply = exec('tweet stream "@such_nasus" --json');
showScreen("Reading '@such_nasus' tweets");
reply.stdout.on('data', function(data) {
    var dados = JSON.parse(data);
    showScreen("@"+dados.user.screen_name+": "+dados.text);
    var quoteAleatorio = nasus_quotes[Math.floor(Math.random()*nasus_quotes.length)];
    var comando = 'tweet new "@'+dados.user.screen_name+' '+quoteAleatorio+'"';
    var newTweet = exec(comando);
    showScreen(comando);
    newTweet.stdout.on('data', function(nasusData) {
      showScreen(nasusData);
    });
    newTweet.stderr.on('data', function(nasusData) {
      showScreen(nasusData);
    });
});
reply.on('close', function(code) {
  showScreen("stream '@such_nasus': "+code);
  if(code=="Parsing error:Easy there, Turbo. Too many requests recently. Enhance your calm."){
    setTimeout(function() {showScreen('Waiting twitter for a calm down...');}, 30000);
  }
  process.exit();
});
reply.stderr.on('data', function(data) {
  showScreen("stream '@such_nasus': "+data);
});

function showScreen(text){
  var date = new Date();
  var current_time = date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
  console.log(current_time+"- "+text);
}
<|endoftext|>


<commit_before>
(function(root){
    "use strict"

    try {root = global} catch(e){ try {root = window} catch(e){} };

    var defer, observer, tasks = [];

    if(root.process && typeof root.process.nextTick === 'function') defer = root.process.nextTick;
    else if(root.vertx && typeof root.vertx.runOnLoop === 'function') defer = root.vertx.RunOnLoop;
    else if(root.vertx && typeof root.vertx.runOnContext === 'function') defer = root.vertx.runOnContext;
    else if(observer = root.MutationObserver || root.WebKitMutationObserver) {
        defer = (function(document, observer, drain) {
            var el = document.createElement('div');
                new observer(drain).observe(el, { attributes: true });
                return function() { el.setAttribute('x', 'y'); };
        }(document, root.MutationObserver, microTask.drain));
    }
    else if(typeof root.setTimeout === 'function' && (root.ActiveXObject || !root.postMessage)) {
        defer = function(f){ root.setTimeout(f,0); }
    }
    else if(root.MessageChannel && typeof root.MessageChannel === 'function') {
        var fifo = [], channel = new root.MessageChannel();
        channel.port1.onmessage = function () { (fifo.shift())() };
        defer = function (f){ fifo[fifo.length] = f; channel.port2.postMessage(0); };
    } else throw new Error("No candidate for microTask defer()")

    function microTask(t){
        if(tasks.push(t) === 1) defer(microTask.drain);
    }

    microTask.drain = function(){
        var t = tasks;
        tasks = [];

        for(var i = 0, l = t.length; i < l; i++) t[i]();
    }

    microTask.insert = function(task,position){
        position = position ? position : 0;
        tasks.splice(position,0,task);
    }

    microTask.indexOf = function(task){
        return tasks.indexOf(task);
    }

    microTask.has = function(task){
        return !(tasks.indexOf(task) < 0)
    }

    microTask.cancel = function(task){
        if(typeof task === 'function' && (task = tasks.indexOf(task)) < 0) return;
        else if(task == undefined) { tasks = []; return; }

        return tasks.splice(task,1);
    }

    if(module && module.exports) module.exports = microTask;
    else if(typeof define ==='function' && define.amd) define(microTask);
    else root.microTask = microTask;
}(this));
<commit_msg>refactored<commit_after>
(function(root){
    "use strict"

    try {root = global} catch(e){ try {root = window} catch(e){} };

    var defer, tasks = [];

    if(root.process && typeof root.process.nextTick === 'function') defer = root.process.nextTick;
    else if(root.vertx && typeof root.vertx.runOnLoop === 'function') defer = root.vertx.RunOnLoop;
    else if(root.vertx && typeof root.vertx.runOnContext === 'function') defer = root.vertx.runOnContext;
    else if(observer = root.MutationObserver || root.WebKitMutationObserver) {
        defer = (function(doc, obs, drain) {
            var el = doc.createElement('div');
            new obs(drain).observe(el, { attributes: true });
            return function() { el.setAttribute('x', 'y'); };
        }(document, root.MutationObserver, microTask.drain));
    }
    else if(typeof root.setTimeout === 'function' && (root.ActiveXObject || !root.postMessage)) {
        defer = function(f){ root.setTimeout(f,0); }
    }
    else if(root.MessageChannel && typeof root.MessageChannel === 'function') {
        var fifo = [], channel = new root.MessageChannel();
        channel.port1.onmessage = function () { (fifo.shift())() };
        defer = function (f){ fifo[fifo.length] = f; channel.port2.postMessage(0); };
    } else throw new Error("No candidate for microTask defer()")

    function microTask(t){
        if(tasks.push(t) === 1) defer(microTask.drain);
    }

    microTask.drain = function(){
        var t = tasks;
        tasks = [];

        for(var i = 0, l = t.length; i < l; i++) t[i]();
    }

    microTask.insert = function(t,p){
        p = p ? p : 0;
        tasks.splice(p,0,t);
    }

    microTask.has = function(t){
        return !(tasks.indexOf(t) < 0)
    }

    microTask.cancel = function(t){
        if(typeof t === 'function' && (t = tasks.indexOf(t)) < 0) return;
        else if(t == undefined) { tasks = []; return; }

        return tasks.splice(t,1);
    }

    if(module && module.exports) module.exports = microTask;
    else if(typeof define ==='function' && define.amd) define(microTask);
    else root.microTask = microTask;
}(this));
<|endoftext|>


<commit_before>module.exports = {
    config: require('./lib/config'),
    debug:  require('./lib/debug'),
    errors: require('./lib/errors'),
    server: require('./lib/server'),
    logging: require('./lib/logging')
};<commit_msg>🎨 lazily require modules in index.js (#32)<commit_after>module.exports = {
    get config() {return require('./lib/config');},
    get debug() {return require('./lib/debug');},
    get errors() {return require('./lib/errors');},
    get server() {return require('./lib/server');},
    get logging() {return require('./lib/logging');}
};
<|endoftext|>