<commit_before>var express = require('express');
var app = express();
// GaloreTV
// var vids = "https://gdata.youtube.com/feeds/api/playlists/PLPp3tIzLUEwaZfRUCuw1aJbDrTdgdm07b?v=2&alt=jsonc&max-results=49";
// Galore TV 2
// var vids = "https://gdata.youtube.com/feeds/api/playlists/PLPp3tIzLUEwYySnVu0xLsKr13quhabBGr?v=2&alt=jsonc&max-results=49";
// GaloreTV 3
var vids = "https://gdata.youtube.com/feeds/api/playlists/PLPp3tIzLUEwbkwSfDML6R12DCI5XwG6LH?v=2&alt=jsonc&max-results=49";
var request = require('superagent');
var port = 8080;

// Add headers
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://galoremag.com');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

function process(arr) {
	return arr.map(function(item) {
		return {
			url: item.video.id,
			_id: item.id
			// title: item.video.title
		}
	});
}

app.get('/vids', function (req, res) {
	request.get(vids).end(function(err,response) {
		if (err) {
			console.log(err);
			res.status(404).send(err);
		} else {
			var vids = process(response.body.data.items);
			res.status(200).send(vids);
		}
	});
});

app.listen(port, function() {
	console.log("Node app is running at localhost:" + port);
});<commit_msg>update header origin allow to * (all)<commit_after>var express = require('express');
var app = express();
// GaloreTV
// var vids = "https://gdata.youtube.com/feeds/api/playlists/PLPp3tIzLUEwaZfRUCuw1aJbDrTdgdm07b?v=2&alt=jsonc&max-results=49";
// Galore TV 2
// var vids = "https://gdata.youtube.com/feeds/api/playlists/PLPp3tIzLUEwYySnVu0xLsKr13quhabBGr?v=2&alt=jsonc&max-results=49";
// GaloreTV 3
var vids = "https://gdata.youtube.com/feeds/api/playlists/PLPp3tIzLUEwbkwSfDML6R12DCI5XwG6LH?v=2&alt=jsonc&max-results=49";
var request = require('superagent');
var port = 8080;

// Add headers
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

function process(arr) {
	return arr.map(function(item) {
		return {
			url: item.video.id,
			_id: item.id
			// title: item.video.title
		}
	});
}

app.get('/vids', function (req, res) {
	request.get(vids).end(function(err,response) {
		if (err) {
			console.log(err);
			res.status(404).send(err);
		} else {
			var vids = process(response.body.data.items);
			res.status(200).send(vids);
		}
	});
});

app.listen(port, function() {
	console.log("Node app is running at localhost:" + port);
});<|endoftext|>


<commit_before>const { events, Job } = require("brigadier");

// The push event only contains the new commits being pushed. Instead we are
// looking at the pull_request changes, which might be overkill, but provides
// the ability to query all the commits on the PR.
events.on("pull_request", async function(e, project) {

    // The payload is a string we need to parse into JSON to access
    const ghData = JSON.parse(e.payload);

    // Notify GH that
    var ghn = new Notification("dco-labeler", e, project);
    ghn.text = "Checking for DCO";
    await ghn.run();

    // Get the commits to iterate over
    var cj = new Job(`github-pr-commits`, "mattfarina/github-pr-commits:0.1.0");
    cj.env = {
        GITHUB_REPO: project.repo.name,
        GITHUB_TOKEN: project.secrets.ghToken,
        GITHUB_PR_NUMBER: ghData.number.toString(),
    }
    res = await cj.run();
    var tempJson = JSON.stringify(res.toString());
    tempJson = tempJson.replace(/\\n/g, "\\n")
                .replace(/\\'/g, "\\'")
                .replace(/\\"/g, '\\"')
                .replace(/\\&/g, "\\&")
                .replace(/\\r/g, "\\r")
                .replace(/\\t/g, "\\t")
                .replace(/\\b/g, "\\b")
                .replace(/\\f/g, "\\f");
    const commits = JSON.parse(tempJson);
    const re = /^Signed-off-by: (.*) <(.*)>$/im

    var count = 0, missed = 0;

    for (const {commit, parents} of commits) {
        // Skipping old commits that might be merged in but are not part of this PR.
        const isMerge = parents && parents.length > 1;
        if (isMerge) {
          continue;
        }

        var signedOff = re.exec(commit.message);

        if (signedOff === null){
            missed++;
        }
        count++
    }

    // A notification that some were missed
    if (missed > 0) {
        // This is paired with org wide probot DCO checking that will list
        // the commits missing a DCO signoff. We are interested in the label and
        // if this bot is seeing an issue for debugging.
        ghn.text = missed + " out of " + count + " commits are missing signoff";
        ghn.state = "failure";

        // Remove the label if already present
        var j = new Job(`github-label-remover`, "mattfarina/github-label-remover:0.1.0");
        j.env = {
            GITHUB_REPO: project.repo.name,
            GITHUB_ISSUE_LABEL: "Contribution%20Allowed",
            GITHUB_TOKEN: project.secrets.ghToken,
            GITHUB_ISSUE_NUMBER: ghData.number.toString(),
        }
        j.run();
    } else {
        ghn.text = "All commits have signoff";
        ghn.state = "success";

        // Add the label so the bot knows it can merge
        var j = new Job(`github-label-adder`, "mattfarina/github-label-adder:0.1.0");
        j.env = {
            GITHUB_REPO: project.repo.name,
            GITHUB_ISSUE_LABEL: "Contribution Allowed",
            GITHUB_TOKEN: project.secrets.ghToken,
            GITHUB_ISSUE_NUMBER: ghData.number.toString(),
        }
        j.run();
    }
    ghn.run();
})

class Notification {
    constructor(name, e, p) {
        this.proj = p;
        this.e = e;
        this.payload = e.payload;
        this.text = "";

        this.context = name;

        // count allows us to send the notification multiple times, with a distinct pod name
        // each time.
        this.count = 0;

        // One of: "success", "failure", "neutral", "cancelled", or "timed_out".
        this.state = "pending";
    }

    // Send a new notification, and return a Promise<result>.
    run() {
        this.count++
        var j = new Job(`${ this.context }-${ this.count }`, "technosophos/github-notify:1.0.0");
        j.env = {
            GH_REPO: this.proj.repo.name,
            GH_STATE: this.state,
            GH_TOKEN: this.proj.secrets.ghToken,
            GH_COMMIT: this.e.revision.commit,
            GH_DESCRIPTION: this.text,
            GH_CONTEXT: this.context,
        }
        return j.run();
    }
}<commit_msg>Updating to the label remover to one not generating an error (#7375)<commit_after>const { events, Job } = require("brigadier");

// The push event only contains the new commits being pushed. Instead we are
// looking at the pull_request changes, which might be overkill, but provides
// the ability to query all the commits on the PR.
events.on("pull_request", async function(e, project) {

    // The payload is a string we need to parse into JSON to access
    const ghData = JSON.parse(e.payload);

    // Notify GH that
    var ghn = new Notification("dco-labeler", e, project);
    ghn.text = "Checking for DCO";
    await ghn.run();

    // Get the commits to iterate over
    var cj = new Job(`github-pr-commits`, "mattfarina/github-pr-commits:0.1.0");
    cj.env = {
        GITHUB_REPO: project.repo.name,
        GITHUB_TOKEN: project.secrets.ghToken,
        GITHUB_PR_NUMBER: ghData.number.toString(),
    }
    res = await cj.run();
    var tempJson = JSON.stringify(res.toString());
    tempJson = tempJson.replace(/\\n/g, "\\n")
                .replace(/\\'/g, "\\'")
                .replace(/\\"/g, '\\"')
                .replace(/\\&/g, "\\&")
                .replace(/\\r/g, "\\r")
                .replace(/\\t/g, "\\t")
                .replace(/\\b/g, "\\b")
                .replace(/\\f/g, "\\f");
    const commits = JSON.parse(tempJson);
    const re = /^Signed-off-by: (.*) <(.*)>$/im

    var count = 0, missed = 0;

    for (const {commit, parents} of commits) {
        // Skipping old commits that might be merged in but are not part of this PR.
        const isMerge = parents && parents.length > 1;
        if (isMerge) {
          continue;
        }

        var signedOff = re.exec(commit.message);

        if (signedOff === null){
            missed++;
        }
        count++
    }

    // A notification that some were missed
    if (missed > 0) {
        // This is paired with org wide probot DCO checking that will list
        // the commits missing a DCO signoff. We are interested in the label and
        // if this bot is seeing an issue for debugging.
        ghn.text = missed + " out of " + count + " commits are missing signoff";
        ghn.state = "failure";

        // Remove the label if already present
        var j = new Job(`github-label-remover`, "mattfarina/github-label-remover:0.1.1");
        j.env = {
            GITHUB_REPO: project.repo.name,
            GITHUB_ISSUE_LABEL: "Contribution%20Allowed",
            GITHUB_TOKEN: project.secrets.ghToken,
            GITHUB_ISSUE_NUMBER: ghData.number.toString(),
        }
        j.run();
    } else {
        ghn.text = "All commits have signoff";
        ghn.state = "success";

        // Add the label so the bot knows it can merge
        var j = new Job(`github-label-adder`, "mattfarina/github-label-adder:0.1.0");
        j.env = {
            GITHUB_REPO: project.repo.name,
            GITHUB_ISSUE_LABEL: "Contribution Allowed",
            GITHUB_TOKEN: project.secrets.ghToken,
            GITHUB_ISSUE_NUMBER: ghData.number.toString(),
        }
        j.run();
    }
    ghn.run();
})

class Notification {
    constructor(name, e, p) {
        this.proj = p;
        this.e = e;
        this.payload = e.payload;
        this.text = "";

        this.context = name;

        // count allows us to send the notification multiple times, with a distinct pod name
        // each time.
        this.count = 0;

        // One of: "success", "failure", "neutral", "cancelled", or "timed_out".
        this.state = "pending";
    }

    // Send a new notification, and return a Promise<result>.
    run() {
        this.count++
        var j = new Job(`${ this.context }-${ this.count }`, "technosophos/github-notify:1.0.0");
        j.env = {
            GH_REPO: this.proj.repo.name,
            GH_STATE: this.state,
            GH_TOKEN: this.proj.secrets.ghToken,
            GH_COMMIT: this.e.revision.commit,
            GH_DESCRIPTION: this.text,
            GH_CONTEXT: this.context,
        }
        return j.run();
    }
}<|endoftext|>


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

var http = require('http')
var opn = require('opn')
var rc = module.require('rc')
var argv = require('optimist').argv
var config = rc('hcat', {}, argv)

if (argv.usage) {
	console.log(require('./usage.js'))
	process.exit(1)
}

function handler(request, response) {
  // Only accept one request
  server.close();

	var contentType = 'text/html'

	var stream = process.stdin

	response.setHeader('Content-Type', contentType)

	stream.pipe(response)
}

var server = http.createServer(handler)

server.on('listening', function() {
  opn('http://localhost:' + server.address().port)
})

server.listen(config.port || 0, 'localhost')
<commit_msg>Explicitly only handle one request<commit_after>#!/usr/bin/env node

var http = require('http')
var opn = require('opn')
var rc = module.require('rc')
var argv = require('optimist').argv
var config = rc('hcat', {}, argv)

if (argv.usage) {
	console.log(require('./usage.js'))
	process.exit(1)
}

function handler(request, response) {
  // Only accept one request
  this.close();

	var contentType = 'text/html'

	var stream = process.stdin

	response.setHeader('Content-Type', contentType)

	stream.pipe(response)
}

var server = http.createServer();
server.once('request', handler);

server.on('listening', function() {
  opn('http://localhost:' + server.address().port)
})

server.listen(config.port || 0, 'localhost')
<|endoftext|>


<commit_before>'use strict';
const ipc = require('electron').ipcRenderer;
const storage = require('remote').require('./storage');

ipc.on('show-notifications', () => {
	document.querySelector('button.toolbar-button').click();
});

ipc.on('log-out', () => {
	// create the menu for the below
	document.querySelector('md-toolbar md-menu:last-child button').click();

	document.querySelector('.md-open-menu-container md-menu-item:last-child button').click();
});
<commit_msg>refactor(browser.js): Remove useless const<commit_after>'use strict';
const ipc = require('electron').ipcRenderer;

ipc.on('show-notifications', () => {
	document.querySelector('button.toolbar-button').click();
});

ipc.on('log-out', () => {
	// create the menu for the below
	document.querySelector('md-toolbar md-menu:last-child button').click();

	document.querySelector('.md-open-menu-container md-menu-item:last-child button').click();
});
<|endoftext|>


<commit_before>var parseScope = require('lexical-scope');
var through = require('through');

var path = require('path');
var fs = require('fs');
var processModulePath = require.resolve('process/browser.js');

var defaultVars = {
    process: function () {
        return 'require(' + JSON.stringify(processModulePath) + ')';
    },
    global: function () {
        return 'typeof self !== "undefined" ? self : '
            + 'typeof window !== "undefined" ? window : {}'
        ;
    },
    Buffer: function () {
        return 'require("buffer").Buffer';
    },
    __filename: function (file, basedir) {
        var file = '/' + path.relative(basedir, file);
        return JSON.stringify(file);
    },
    __dirname: function (file, basedir) {
        var dir = path.dirname('/' + path.relative(basedir, file));
        return JSON.stringify(dir);
    }
};

module.exports = function (file, opts) {
    if (!opts) opts = {};

    var basedir = opts.basedir || '/';
    var vars = opts.vars || defaultVars
    var varNames = Object.keys(vars);

    var quick = RegExp(varNames.map(function (name) {
        return '\\b' + name + '\\b';
    }).join('|'));

    var resolved = {};
    var chunks = [];

    return through(write, end);

    function write (buf) { chunks.push(buf) }

    function end () {
        var source = Buffer.isBuffer(chunks[0])
            ? Buffer.concat(chunks).toString('utf8')
            : chunks.join('')
        ;
        source = source.replace(/^#![^\n]*\n/, '\n');

        if (opts.always !== true && !quick.test(source)) {
            this.queue(source);
            this.queue(null);
            return;
        }

        try {
            var scope = opts.always
                ? { globals: { implicit: varNames } }
                : parseScope(source)
            ;
        }
        catch (err) {
            var e = new SyntaxError(
                (err.message || err) + ' while parsing ' + file
            );
            e.type = 'syntax';
            e.filename = file;
            return this.emit('error', e);
        }

        var globals = {};

        varNames.forEach(function (name) {
            if (scope.globals.implicit.indexOf(name) >= 0) {
                var value = vars[name](file, basedir);
                if (value) globals[name] = value;
            }
        });

        this.queue(closeOver(globals, source));
        this.queue(null);
    }
};

module.exports.vars = defaultVars;

function closeOver (globals, src) {
    var keys = Object.keys(globals);
    if (keys.length === 0) return src;
    var values = keys.map(function (key) { return globals[key] });

    if (keys.length <= 3) {
        return '(function (' + keys.join(',') + '){'
            + src + '}).call(this,' + values.join(',') + ')'
        ;
    }
    // necessary to make arguments[3..6] still work for workerify etc
    // a,b,c,arguments[3..6],d,e,f...
    var extra = [ '__argument', '__argument', '__argument', '__argument' ];
    var names = keys.slice(0,3).concat(extra).concat(keys.slice(3));
    values.splice(3, 0,
        'arguments[3]','arguments[4]',
        'arguments[5]','arguments[6]'
    );

    return '(function (' + names.join(',') + '){'
        + src + '}).call(this,' + values.join(',') + ')'
    ;
}
<commit_msg>skip json files<commit_after>var parseScope = require('lexical-scope');
var through = require('through');

var path = require('path');
var fs = require('fs');
var processModulePath = require.resolve('process/browser.js');

var defaultVars = {
    process: function () {
        return 'require(' + JSON.stringify(processModulePath) + ')';
    },
    global: function () {
        return 'typeof self !== "undefined" ? self : '
            + 'typeof window !== "undefined" ? window : {}'
        ;
    },
    Buffer: function () {
        return 'require("buffer").Buffer';
    },
    __filename: function (file, basedir) {
        var file = '/' + path.relative(basedir, file);
        return JSON.stringify(file);
    },
    __dirname: function (file, basedir) {
        var dir = path.dirname('/' + path.relative(basedir, file));
        return JSON.stringify(dir);
    }
};

module.exports = function (file, opts) {
    if (/\.json$/i.test(file)) return through();
    if (!opts) opts = {};

    var basedir = opts.basedir || '/';
    var vars = opts.vars || defaultVars
    var varNames = Object.keys(vars);

    var quick = RegExp(varNames.map(function (name) {
        return '\\b' + name + '\\b';
    }).join('|'));

    var resolved = {};
    var chunks = [];

    return through(write, end);

    function write (buf) { chunks.push(buf) }

    function end () {
        var source = Buffer.isBuffer(chunks[0])
            ? Buffer.concat(chunks).toString('utf8')
            : chunks.join('')
        ;
        source = source.replace(/^#![^\n]*\n/, '\n');

        if (opts.always !== true && !quick.test(source)) {
            this.queue(source);
            this.queue(null);
            return;
        }

        try {
            var scope = opts.always
                ? { globals: { implicit: varNames } }
                : parseScope(source)
            ;
        }
        catch (err) {
            var e = new SyntaxError(
                (err.message || err) + ' while parsing ' + file
            );
            e.type = 'syntax';
            e.filename = file;
            return this.emit('error', e);
        }

        var globals = {};

        varNames.forEach(function (name) {
            if (scope.globals.implicit.indexOf(name) >= 0) {
                var value = vars[name](file, basedir);
                if (value) globals[name] = value;
            }
        });

        this.queue(closeOver(globals, source));
        this.queue(null);
    }
};

module.exports.vars = defaultVars;

function closeOver (globals, src) {
    var keys = Object.keys(globals);
    if (keys.length === 0) return src;
    var values = keys.map(function (key) { return globals[key] });

    if (keys.length <= 3) {
        return '(function (' + keys.join(',') + '){'
            + src + '}).call(this,' + values.join(',') + ')'
        ;
    }
    // necessary to make arguments[3..6] still work for workerify etc
    // a,b,c,arguments[3..6],d,e,f...
    var extra = [ '__argument', '__argument', '__argument', '__argument' ];
    var names = keys.slice(0,3).concat(extra).concat(keys.slice(3));
    values.splice(3, 0,
        'arguments[3]','arguments[4]',
        'arguments[5]','arguments[6]'
    );

    return '(function (' + names.join(',') + '){'
        + src + '}).call(this,' + values.join(',') + ')'
    ;
}
<|endoftext|>


<commit_before>'use strict';
const ipc = require('electron').ipcRenderer;
const storage = require('remote').require('./storage');
const listSelector = 'div[role="navigation"] > ul > li';

ipc.on('show-preferences', () => {
	// create the menu for the below
	document.querySelector('._30yy._2fug._p').click();

	document.querySelector('._54nq._2i-c._558b._2n_z li:first-child a').click();
});

ipc.on('new-conversation', () => {
	document.querySelector('._30yy[href=\'/new\']').click();
});

ipc.on('log-out', () => {
	// create the menu for the below
	document.querySelector('._30yy._2fug._p').click();

	document.querySelector('._54nq._2i-c._558b._2n_z li:last-child a').click();
});

ipc.on('find', () => {
	document.querySelector('._58al').focus();
});

ipc.on('next-conversation', nextConversation);

ipc.on('previous-conversation', previousConversation);

ipc.on('dark-mode', toggleDarkMode);

function nextConversation() {
	const index = getNextIndex(true);
	document.querySelectorAll(listSelector)[index].firstChild.firstChild.click();
}

function previousConversation() {
	const index = getNextIndex(false);
	document.querySelectorAll(listSelector)[index].firstChild.firstChild.click();
}

function inDarkMode() {
	return storage.get('darkMode') || false;
}

function toggleDarkMode() {
	if (inDarkMode()) {
		deactivateDarkMode();
	} else {
		activateDarkMode();
	}
}

function activateDarkMode() {
	document.querySelector('html').classList.add('darkMode');
	storage.set('darkMode', true);
}

function deactivateDarkMode() {
	document.querySelector('html').classList.remove('darkMode');
	storage.set('darkMode', false);
}

// return the index for next node if next is true,
// else returns index for the previous node
function getNextIndex(next) {
	const selected = document.querySelector('._5l-3._1ht1._1ht2');
	const list = Array.from(selected.parentNode.children);
	const index = list.indexOf(selected) + (next ? 1 : -1);

	return (index % list.length + list.length) % list.length;
}

// activate Dark Mode if it was set before quitting
if (inDarkMode()) {
	activateDarkMode();
}

// it's not possible to add multiple accelerators
// so need to do this the oldschool way
document.addEventListener('keydown', event => {
	if (process.platform === 'darwin' && event.metaKey && event.shiftKey) {
		if (event.keyCode === 221/* ] */) {
			nextConversation();
		}

		if (event.keyCode === 219/* [ */) {
			previousConversation();
		}
	}
});
<commit_msg>simplify the dark mode implementation<commit_after>'use strict';
const ipc = require('electron').ipcRenderer;
const storage = require('remote').require('./storage');
const listSelector = 'div[role="navigation"] > ul > li';

ipc.on('show-preferences', () => {
	// create the menu for the below
	document.querySelector('._30yy._2fug._p').click();

	document.querySelector('._54nq._2i-c._558b._2n_z li:first-child a').click();
});

ipc.on('new-conversation', () => {
	document.querySelector('._30yy[href=\'/new\']').click();
});

ipc.on('log-out', () => {
	// create the menu for the below
	document.querySelector('._30yy._2fug._p').click();

	document.querySelector('._54nq._2i-c._558b._2n_z li:last-child a').click();
});

ipc.on('find', () => {
	document.querySelector('._58al').focus();
});

ipc.on('next-conversation', nextConversation);

ipc.on('previous-conversation', previousConversation);

ipc.on('dark-mode', toggleDarkMode);

function nextConversation() {
	const index = getNextIndex(true);
	document.querySelectorAll(listSelector)[index].firstChild.firstChild.click();
}

function previousConversation() {
	const index = getNextIndex(false);
	document.querySelectorAll(listSelector)[index].firstChild.firstChild.click();
}

function setDarkMode() {
	document.documentElement.classList.toggle('darkMode', storage.get('darkMode'));
}

function toggleDarkMode() {
	storage.set('darkMode', !storage.get('darkMode'));
	setDarkMode();
}

// return the index for next node if next is true,
// else returns index for the previous node
function getNextIndex(next) {
	const selected = document.querySelector('._5l-3._1ht1._1ht2');
	const list = Array.from(selected.parentNode.children);
	const index = list.indexOf(selected) + (next ? 1 : -1);

	return (index % list.length + list.length) % list.length;
}

// activate Dark Mode if it was set before quitting
setDarkMode();

// it's not possible to add multiple accelerators
// so need to do this the oldschool way
document.addEventListener('keydown', event => {
	if (process.platform === 'darwin' && event.metaKey && event.shiftKey) {
		if (event.keyCode === 221/* ] */) {
			nextConversation();
		}

		if (event.keyCode === 219/* [ */) {
			previousConversation();
		}
	}
});
<|endoftext|>


<commit_before>'use strict';

var consolidate = require('consolidate');
var path        = require('path');
var _           = require('lodash');

module.exports = function(source, config){

    config = _defaultsDeep(config || {}, {
        engine: 'handlebars'
    });

    const partials = {};

    function loadViews(source) {
        for (let item of source.flatten(true)) {
            partials[item.handle] = item.content;
            if (item.alias) {
                partials[item.alias] = item.content;
            }
        }
        viewsLoaded = true;
    }

    source.on('loaded', loadViews);
    source.on('changed', loadViews);

    return {
        engine: consolidate[config.engine],
        render: function(tplPath, str, context, meta){
            if (!viewsLoaded) loadViews(source);
            context.partials = {};
            _.each(partials, function(partialPath, partialKey){
                if (tplPath != partialPath) {
                    const relPath = path.relative(tplPath, partialPath).replace('../', '');
                    const parts = path.parse(relPath);
                    if ( !_.isEmpty(parts.name) && (path.extname(tplPath) == path.extname(partialPath))) {
                        context.partials[partialKey] = path.join(parts.dir, parts.name);
                    }
                }
            });
            return Promise.resolve(consolidate[config.engine](tplPath, context));
        }
    }

};
<commit_msg>Fix typo<commit_after>'use strict';

var consolidate = require('consolidate');
var path        = require('path');
var _           = require('lodash');

module.exports = function(source, config){

    config = _.defaultsDeep(config || {}, {
        engine: 'handlebars'
    });

    const partials = {};

    function loadViews(source) {
        for (let item of source.flatten(true)) {
            partials[item.handle] = item.content;
            if (item.alias) {
                partials[item.alias] = item.content;
            }
        }
        viewsLoaded = true;
    }

    source.on('loaded', loadViews);
    source.on('changed', loadViews);

    return {
        engine: consolidate[config.engine],
        render: function(tplPath, str, context, meta){
            if (!viewsLoaded) loadViews(source);
            context.partials = {};
            _.each(partials, function(partialPath, partialKey){
                if (tplPath != partialPath) {
                    const relPath = path.relative(tplPath, partialPath).replace('../', '');
                    const parts = path.parse(relPath);
                    if ( !_.isEmpty(parts.name) && (path.extname(tplPath) == path.extname(partialPath))) {
                        context.partials[partialKey] = path.join(parts.dir, parts.name);
                    }
                }
            });
            return Promise.resolve(consolidate[config.engine](tplPath, context));
        }
    }

};
<|endoftext|>


<commit_before>
exports.compare = function (a, b) {

  if(Buffer.isBuffer(a)) {
    var l = Math.min(a.length, b.length)
    for(var i = 0; i < l; i++) {
      var cmp = a[i] - b[i]
      if(cmp) return cmp
    }
    return a.length - b.length
  }

  return a < b ? -1 : a > b ? 1 : 0
}

function has(obj, key) {
  return Object.hasOwnProperty.call(obj, key)
}

// to be compatible with the current abstract-leveldown tests
// nullish or empty strings.
// I could use !!val but I want to permit numbers and booleans,
// if possible.

function isDef (val) {
  return val !== undefined && val !== ''
}

function has (range, name) {
  return Object.hasOwnProperty.call(range, name)
}

function hasKey(range, name) {
  return Object.hasOwnProperty.call(range, name) && name
}

var lowerBoundKey = exports.lowerBoundKey = function (range) {
    return (
       hasKey(range, 'gt')
    || hasKey(range, 'gte')
    || hasKey(range, 'min')
    || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start'))
    || undefined
    )
}

var lowerBound = exports.lowerBound = function (range) {
  var k = lowerBoundKey(range)
  return k && range[k]
}

exports.lowerBoundInclusive = function (range) {
  return has(range, 'gt') ? false : true
}

exports.upperBoundInclusive =
  function (range) {
    return has(range, 'lt') || !range.minEx ? false : true
  }

var lowerBoundExclusive = exports.lowerBoundExclusive =
  function (range) {
    return has(range, 'gt') || range.minEx ? true : false
  }

var upperBoundExclusive = exports.upperBoundExclusive =
  function (range) {
    return has(range, 'lt') ? true : false
  }

var upperBoundKey = exports.upperBoundKey = function (range) {
    return (
       hasKey(range, 'lt')
    || hasKey(range, 'lte')
    || hasKey(range, 'max')
    || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end'))
    || undefined
    )
}

var upperBound = exports.upperBound = function (range) {
  var k = upperBoundKey(range)
  return k && range[k]
}

function id (e) { return e }

exports.toLtgt = function (range, _range, map, lower, upper) {
  _range = _range || {}
  map = map || id
  var defaults = arguments.length > 3
  var lb = exports.lowerBoundKey(range)
  var ub = exports.upperBoundKey(range)
  if(lb) {
    if(lb === 'gt') _range.gt = map(range.gt, false)
    else            _range.gte = map(range[lb], false)
  }
  else if(defaults)
    _range.gte = map(lower, false)

  if(ub) {
    if(ub === 'lt') _range.lt = map(range.lt, true)
    else            _range.lte = map(range[ub], true)
  }
  else if(defaults)
    _range.lte = map(upper, true)

  if(range.reverse != null)
    _range.reverse = !!range.reverse

  //if range was used mutably
  //(in level-sublevel it's part of an options object
  //that has more properties on it.)
  if(has(_range, 'max'))   delete _range.max
  if(has(_range, 'min'))   delete _range.min
  if(has(_range, 'start')) delete _range.start
  if(has(_range, 'end'))   delete _range.end

  return _range
}

exports.contains = function (range, key, compare) {
  compare = compare || exports.compare

  var lb = lowerBound(range)
  if(isDef(lb)) {
    var cmp = compare(key, lb)
    if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range)))
      return false
  }

  var ub = upperBound(range)
  if(isDef(ub)) {
    var cmp = compare(key, ub)
    if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range))
      return false
  }

  return true
}

exports.filter = function (range, compare) {
  return function (key) {
    return exports.contains(range, key, compare)
  }
}
<commit_msg>_Exclusive interms of _Inclusive<commit_after>
exports.compare = function (a, b) {

  if(Buffer.isBuffer(a)) {
    var l = Math.min(a.length, b.length)
    for(var i = 0; i < l; i++) {
      var cmp = a[i] - b[i]
      if(cmp) return cmp
    }
    return a.length - b.length
  }

  return a < b ? -1 : a > b ? 1 : 0
}

function has(obj, key) {
  return Object.hasOwnProperty.call(obj, key)
}

// to be compatible with the current abstract-leveldown tests
// nullish or empty strings.
// I could use !!val but I want to permit numbers and booleans,
// if possible.

function isDef (val) {
  return val !== undefined && val !== ''
}

function has (range, name) {
  return Object.hasOwnProperty.call(range, name)
}

function hasKey(range, name) {
  return Object.hasOwnProperty.call(range, name) && name
}

var lowerBoundKey = exports.lowerBoundKey = function (range) {
    return (
       hasKey(range, 'gt')
    || hasKey(range, 'gte')
    || hasKey(range, 'min')
    || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start'))
    || undefined
    )
}

var lowerBound = exports.lowerBound = function (range) {
  var k = lowerBoundKey(range)
  return k && range[k]
}

var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) {
  return has(range, 'gt') ? false : true
}

var upperBoundInclusive = exports.upperBoundInclusive =
  function (range) {
    return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true
  }

var lowerBoundExclusive = exports.lowerBoundExclusive =
  function (range) {
    return !lowerBoundInclusive(range)
  }

var upperBoundExclusive = exports.upperBoundExclusive =
  function (range) {
    return !upperBoundInclusive(range)
  }

var upperBoundKey = exports.upperBoundKey = function (range) {
    return (
       hasKey(range, 'lt')
    || hasKey(range, 'lte')
    || hasKey(range, 'max')
    || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end'))
    || undefined
    )
}

var upperBound = exports.upperBound = function (range) {
  var k = upperBoundKey(range)
  return k && range[k]
}

function id (e) { return e }

exports.toLtgt = function (range, _range, map, lower, upper) {
  _range = _range || {}
  map = map || id
  var defaults = arguments.length > 3
  var lb = exports.lowerBoundKey(range)
  var ub = exports.upperBoundKey(range)
  if(lb) {
    if(lb === 'gt') _range.gt = map(range.gt, false)
    else            _range.gte = map(range[lb], false)
  }
  else if(defaults)
    _range.gte = map(lower, false)

  if(ub) {
    if(ub === 'lt') _range.lt = map(range.lt, true)
    else            _range.lte = map(range[ub], true)
  }
  else if(defaults)
    _range.lte = map(upper, true)

  if(range.reverse != null)
    _range.reverse = !!range.reverse

  //if range was used mutably
  //(in level-sublevel it's part of an options object
  //that has more properties on it.)
  if(has(_range, 'max'))   delete _range.max
  if(has(_range, 'min'))   delete _range.min
  if(has(_range, 'start')) delete _range.start
  if(has(_range, 'end'))   delete _range.end

  return _range
}

exports.contains = function (range, key, compare) {
  compare = compare || exports.compare

  var lb = lowerBound(range)
  if(isDef(lb)) {
    var cmp = compare(key, lb)
    if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range)))
      return false
  }

  var ub = upperBound(range)
  if(isDef(ub)) {
    var cmp = compare(key, ub)
    if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range))
      return false
  }

  return true
}

exports.filter = function (range, compare) {
  return function (key) {
    return exports.contains(range, key, compare)
  }
}

<|endoftext|>


<commit_before>var parseHeaders = require('parse-headers')
var url = require('url')
var CONTENT_TYPE_MAP = {
  'object': 'application/json',
  'string': 'text/plain'
}

module.exports = function (options, callback) {
  var timeout
  function done (err, res) {
    if (!(err instanceof Error)) {
      err = new Error('' + (err || 'Unknown XMLHttpRequest Error'))
    }

    if (timeout) clearTimeout(timeout)
    if (callback) callback(err, res)
    callback = undefined
  }

  // don't mutate
  options = Object.assign({}, options)

  if (options.url) {
    Object.assign(options, url.parse(options.url))
  }

  if (options.body !== undefined) {
    var typeOf = typeof options.body

    options.headers = options.headers || {}
    if (!options.headers['content-type']) {
      // don't mutate
      options.headers = Object.assign({}, options.headers)
      options.headers['content-type'] = CONTENT_TYPE_MAP[typeOf]
    }

    if (typeOf !== 'string') {
      options.body = JSON.stringify(options.body)
    }
  }

  function ready () {
    if (this.readyState < 2) return

    var headers = xhr.getAllResponseHeaders()
    headers = parseHeaders(headers)

    var length = headers['content-length']
    if (options.limit && length > options.limit) return done(new Error('Content-Length exceeded limit'))

    if (this.readyState !== 4) return

    var result = {
      statusCode: xhr.status,
      headers: headers,
      body: xhr.response
    }

    var contentType = headers['content-type']
    if (contentType) {
      if (/application\/json/.test(contentType)) {
        try {
          result.body = JSON.parse(result.body)
        } catch (e) { return done(e) }
      }
      if (/application\/octet-stream/.test(contentType)) {
        result.body = new Buffer(result.body, 'utf-8')
      }
    }

    done(null, result)
  }

  if (options.timeout) {
    timeout = setTimeout(function () {
      xhr.abort()

      done(new Error('ETIMEDOUT'))
    }, options.timeout)
  }

  var xhr = new window.XMLHttpRequest()
  xhr.onreadystatechange = ready
  xhr.onerror = done

  xhr.open(options.method, options.url, true)

  if (options.headers !== undefined && xhr.setRequestHeader) {
    for (var key in options.headers) {
      xhr.setRequestHeader(key, options.headers[key])
    }
  }

  xhr.send(options.body)
}
<commit_msg>browser: not always an error!<commit_after>var parseHeaders = require('parse-headers')
var url = require('url')
var CONTENT_TYPE_MAP = {
  'object': 'application/json',
  'string': 'text/plain'
}

module.exports = function (options, callback) {
  var timeout
  function done (err, res) {
    if (err && !(err instanceof Error)) {
      err = new Error('' + (err || 'Unknown XMLHttpRequest Error'))
    }

    if (timeout) clearTimeout(timeout)
    if (callback) callback(err, res)
    callback = undefined
  }

  // don't mutate
  options = Object.assign({}, options)

  if (options.url) {
    Object.assign(options, url.parse(options.url))
  }

  if (options.body !== undefined) {
    var typeOf = typeof options.body

    options.headers = options.headers || {}
    if (!options.headers['content-type']) {
      // don't mutate
      options.headers = Object.assign({}, options.headers)
      options.headers['content-type'] = CONTENT_TYPE_MAP[typeOf]
    }

    if (typeOf !== 'string') {
      options.body = JSON.stringify(options.body)
    }
  }

  function ready () {
    if (this.readyState < 2) return

    var headers = xhr.getAllResponseHeaders()
    headers = parseHeaders(headers)

    var length = headers['content-length']
    if (options.limit && length > options.limit) return done(new Error('Content-Length exceeded limit'))

    if (this.readyState !== 4) return

    var result = {
      statusCode: xhr.status,
      headers: headers,
      body: xhr.response
    }

    var contentType = headers['content-type']
    if (contentType) {
      if (/application\/json/.test(contentType)) {
        try {
          result.body = JSON.parse(result.body)
        } catch (e) { return done(e) }
      }
      if (/application\/octet-stream/.test(contentType)) {
        result.body = new Buffer(result.body, 'utf-8')
      }
    }

    done(null, result)
  }

  if (options.timeout) {
    timeout = setTimeout(function () {
      xhr.abort()

      done(new Error('ETIMEDOUT'))
    }, options.timeout)
  }

  var xhr = new window.XMLHttpRequest()
  xhr.onreadystatechange = ready
  xhr.onerror = done

  xhr.open(options.method, options.url, true)

  if (options.headers !== undefined && xhr.setRequestHeader) {
    for (var key in options.headers) {
      xhr.setRequestHeader(key, options.headers[key])
    }
  }

  xhr.send(options.body)
}
<|endoftext|>


<commit_before>var express = require('express');
var validUrl = require('valid-url');
var app = express();

var exprs = [
  {
    pattern: /^diff .+$/,
    url: function(inp) {
      return 'https://phab.trifacta.com/differential/?authors=' + inp.slice(5, inp.lenght);
    },
  },
  {
    pattern: /^diff$/,
    url: function() {
      return 'https://phab.trifacta.com/';
    },
  },
  {
    pattern: /^du .+$/,
    url: function(inp) {
      return 'https://phab.trifacta.com/diffusion/TF/browse/dev/' + inp.slice(3, inp.lenght);
    },
  },
  {
    pattern: /^[dD][0-9]+$/,
    url: function(inp) {
      return 'https://phab.trifacta.com/' + inp.toUpperCase();
    },
  },
  {
    pattern: /^macro .+$/,
    url: function(inp) {
      return 'https://phab.trifacta.com/macro/?nameLike=' + inp.slice(6, inp.length);
    },
  },
  {
    pattern: /^macro$/,
    url: function() {
      return 'https://phab.trifacta.com/macro/';
    },
  },
  {
    pattern: /^[tT][dD][-][0-9]+$/,
    url: function(inp) {
      return 'https://trifacta.atlassian.net/browse/' + inp;
    },
  },
  {
    pattern: /^t$/,
    url: function() {
      return 'https://trifacta.atlassian.net/issues/?filter=-1';
    },
  },
  {
    pattern: /^w .+$/,
    url: function(inp) {
      return 'https://confluence.trifacta.com/dosearchsite.action?queryString=' +
          inp.slice(2, inp.length);
    },
  },
  {
    pattern: /^w$/,
    url: function() {
      return 'https://confluence.trifacta.com/';
    },
  },
  {
    pattern: /^g .+$/,
    url: function(inp) {
      return 'https://www.google.com/search?q=' + encodeURIComponent(inp.slice(2, inp.length));
    },
  }
];

app.get('/ping', function(req, res) {
  res.send('I AM ALIVE');
});

app.get('/search', function(req, res) {
  console.log(req.query.q)
  var query = req.query.q;

  if (validUrl.isUri(query)) {
    return res.redirect(query);
  }

  for (var key in exprs) {
    var expr = exprs[key];
    if (expr.pattern.test(query)) {
      return res.redirect(expr.url(query));
    }
  }

  res.redirect('https://www.google.com/search?q=' + encodeURIComponent(query));
});

var port = Number(process.env.PORT || 8008);
app.listen(port, function() {
  console.log('Listening on ' + port);
});
<commit_msg>Fix jira url<commit_after>var express = require('express');
var validUrl = require('valid-url');
var app = express();

var exprs = [
  {
    pattern: /^diff .+$/,
    url: function(inp) {
      return 'https://phab.trifacta.com/differential/?authors=' + inp.slice(5, inp.lenght);
    },
  },
  {
    pattern: /^diff$/,
    url: function() {
      return 'https://phab.trifacta.com/';
    },
  },
  {
    pattern: /^du .+$/,
    url: function(inp) {
      return 'https://phab.trifacta.com/diffusion/TF/browse/dev/' + inp.slice(3, inp.lenght);
    },
  },
  {
    pattern: /^[dD][0-9]+$/,
    url: function(inp) {
      return 'https://phab.trifacta.com/' + inp.toUpperCase();
    },
  },
  {
    pattern: /^macro .+$/,
    url: function(inp) {
      return 'https://phab.trifacta.com/macro/?nameLike=' + inp.slice(6, inp.length);
    },
  },
  {
    pattern: /^macro$/,
    url: function() {
      return 'https://phab.trifacta.com/macro/';
    },
  },
  {
    pattern: /^[tT][dD][-][0-9]+$/,
    url: function(inp) {
      return 'https://jira.trifacta.net/browse/' + inp;
    },
  },
  {
    pattern: /^t$/,
    url: function() {
      return 'https://jira.trifacta.net/issues/?filter=-1';
    },
  },
  {
    pattern: /^w .+$/,
    url: function(inp) {
      return 'https://confluence.trifacta.com/dosearchsite.action?queryString=' +
          inp.slice(2, inp.length);
    },
  },
  {
    pattern: /^w$/,
    url: function() {
      return 'https://confluence.trifacta.com/';
    },
  },
  {
    pattern: /^g .+$/,
    url: function(inp) {
      return 'https://www.google.com/search?q=' + encodeURIComponent(inp.slice(2, inp.length));
    },
  }
];

app.get('/ping', function(req, res) {
  res.send('I AM ALIVE');
});

app.get('/search', function(req, res) {
  console.log(req.query.q)
  var query = req.query.q;

  if (validUrl.isUri(query)) {
    return res.redirect(query);
  }

  for (var key in exprs) {
    var expr = exprs[key];
    if (expr.pattern.test(query)) {
      return res.redirect(expr.url(query));
    }
  }

  res.redirect('https://www.google.com/search?q=' + encodeURIComponent(query));
});

var port = Number(process.env.PORT || 8008);
app.listen(port, function() {
  console.log('Listening on ' + port);
});
<|endoftext|>


<commit_before>/******************************************************************************
* Class encapsulating a LFSR in Fibonacci form
******************************************************************************/

/// Constructor: seed is starting value
Linear_Feedback_Shift_Register = function(seed) {
	if (!seed) {
		seed = 1;
	}
	this.lfsr = parseInt(seed);
}

/// do one step in LFSR, changes inner state of LFSR
Linear_Feedback_Shift_Register.prototype.step = function(number) {
	if (!number) {
		number = 1;
	}
	var i = parseInt(number);
	if (1 > i) {
		i = 1;
	}
	var lfsr = this.lfsr;
	var bit	= 0;

	while (0> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5) ) & 1;
		lfsr = (lfsr >> 1) | (bit << 15);
		--i;
	}

	this.lfsr = lfsr;
	return this.lfsr;
};

/// get inner state
Linear_Feedback_Shift_Register.prototype.get = function() {
	return this.lfsr;
};

/// set inner state, can be used for reseed/restart
Linear_Feedback_Shift_Register.prototype.set = function(seed) {
	if (!seed) {
		seed = 1;
	}
	this.lfsr = parseInt(seed);
};

/******************************************************************************
* Methods for encoding and decoding arbitrary octet streams.
******************************************************************************/
/// constructor: LFSR seed as input
Transcoder = function(seed) {
	if (!seed) {
		seed = 0xACE1; /* Any nonzero start state will work. */
	}
	this.start_state = parseInt(seed);
	this.LFSR = new Linear_Feedback_Shift_Register(this.start_state);
	this.period = 0;
	this.lfsr = this.LFSR.get();
}

/// helper method for checking period of LFSR
Transcoder.prototype.step_check_lfsr_period = function() { // linear feedback shift register
	var lfsr = this.LFSR.step();
	++this.period;
	if (lfsr == this.start_state) {
		return {"finished": true, "period": this.period, "lfsr": lfsr};
	}
	return {"finished": false, "period": this.period, "lfsr": lfsr};
}

/// resetting LFSR
Transcoder.prototype.reset = function() {
	this.LFSR.set(this.start_state);
}

/// encode some message, including conversion to octet stream
Transcoder.prototype.encode = function(message) {
	var str = message.toString();
	var result = Uint8Array.from(str);
	for (var i = 0, len = result.length; i < len; i++) {
//		result[i] = i;//32+str[i]; // TODO doesn't work as expected??
	}
	return result.toString();
}
/*****************************************************************************/

/// our entry point
function main() {
	console.log("HI");
	var text_block = document.querySelector('#text-block');
	console.log(text_block);

	var show = function(message) {
		if (text_block) {
			text_block.innerHTML = message;
		}
	}
	show("Starte Berechnung…");

	var transcoder = new Transcoder();
	var tick = function() {
		var boost = 256; // we don't want to show every single step, to slow
		var result = transcoder.step_check_lfsr_period();
		while (boost > 0 && !result.finished) {
			result = transcoder.step_check_lfsr_period();
			--boost;
		}
		if (!result.finished) {
			/// still some string juggling necessary because of inconveniences of underlying transcoder
			show("Berechnung läuft…
Linear Feedback Shift Register-Wert = 0x"+("000" + result.lfsr.toString(16)).slice(-4)+"
Schritte: "+result.period);
			setTimeout(tick, 1);
		} else {
			show("Fertig!
Linear Feedback Shift Register-Wert = 0x"+("000" + result.lfsr.toString(16)).slice(-4)+"
Periode: "+result.period);
		}
	}

	console.log(transcoder.encode("Hallo Leute!"));
	tick();
}

window.onload = main;
<commit_msg>WIP: Testen des encoders mit multibyte chars.<commit_after>/******************************************************************************
* Class encapsulating a LFSR in Fibonacci form
******************************************************************************/

/// Constructor: seed is starting value
Linear_Feedback_Shift_Register = function(seed) {
	if (!seed) {
		seed = 1;
	}
	this.lfsr = parseInt(seed);
}

/// do one step in LFSR, changes inner state of LFSR
Linear_Feedback_Shift_Register.prototype.step = function(number) {
	if (!number) {
		number = 1;
	}
	var i = parseInt(number);
	if (1 > i) {
		i = 1;
	}
	var lfsr = this.lfsr;
	var bit	= 0;

	while (0> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5) ) & 1;
		lfsr = (lfsr >> 1) | (bit << 15);
		--i;
	}

	this.lfsr = lfsr;
	return this.lfsr;
};

/// get inner state
Linear_Feedback_Shift_Register.prototype.get = function() {
	return this.lfsr;
};

/// set inner state, can be used for reseed/restart
Linear_Feedback_Shift_Register.prototype.set = function(seed) {
	if (!seed) {
		seed = 1;
	}
	this.lfsr = parseInt(seed);
};

/******************************************************************************
* Methods for encoding and decoding arbitrary octet streams.
******************************************************************************/
/// constructor: LFSR seed as input
Transcoder = function(seed) {
	if (!seed) {
		seed = 0xACE1; /* Any nonzero start state will work. */
	}
	this.start_state = parseInt(seed);
	this.LFSR = new Linear_Feedback_Shift_Register(this.start_state);
	this.period = 0;
	this.lfsr = this.LFSR.get();
}

/// helper method for checking period of LFSR
Transcoder.prototype.step_check_lfsr_period = function() { // linear feedback shift register
	var lfsr = this.LFSR.step();
	++this.period;
	if (lfsr == this.start_state) {
		return {"finished": true, "period": this.period, "lfsr": lfsr};
	}
	return {"finished": false, "period": this.period, "lfsr": lfsr};
}

/// resetting LFSR
Transcoder.prototype.reset = function() {
	this.LFSR.set(this.start_state);
}

/// encode some message, including conversion to octet stream
Transcoder.prototype.encode = function(message) {
//  var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
//  var bufView = new Uint16Array(buf);
//  for (var i=0, strLen=str.length; i<strLen; i++) {
//    bufView[i] = str.charCodeAt(i);
//  }
//  return buf;
	var buf = new ArrayBuffer(strLen*2); // TODO wchar is wrong assumption with variable multibyte chars
	var str = message.toString();  // TODO
	console.log("AA: ",str);  // TODO
	var strLen = str.length;  // TODO
	var result = Uint8Array.from(str); // TODO
	for (var i = 0, len = result.length; i < len; i++) { // TODO
		result[i] = str.charCodeAt(i); // TODO doesn't work as expected??
	}
	return result; //result.toString();
}
/*****************************************************************************/

/// our entry point
function main() {
	console.log("HI");
	var text_block = document.querySelector('#text-block');
	console.log(text_block);

	var show = function(message) {
		if (text_block) {
			text_block.innerHTML = message;
		}
	}
	show("Starte Berechnung…");

	var transcoder = new Transcoder();
	var tick = function() {
		var boost = 256; // we don't want to show every single step, to slow
		var result = transcoder.step_check_lfsr_period();
		while (boost > 0 && !result.finished) {
			result = transcoder.step_check_lfsr_period();
			--boost;
		}
		if (!result.finished) {
			/// still some string juggling necessary because of inconveniences of underlying transcoder
			show("Berechnung läuft…
Linear Feedback Shift Register-Wert = 0x"+("000" + result.lfsr.toString(16)).slice(-4)+"
Schritte: "+result.period);
			setTimeout(tick, 1);
		} else {
			show("Fertig!
Linear Feedback Shift Register-Wert = 0x"+("000" + result.lfsr.toString(16)).slice(-4)+"
Periode: "+result.period);
		}
	}

	console.log(transcoder.encode("🏁 Ä Ö Ü ä ö ü ß € µ – · … Hallo Leute!")); // many special multibyte characters.
	tick();
}

window.onload = main;
<|endoftext|>


<commit_before>'use strict';

const VersionChecker = require('ember-cli-version-checker');
let hasBeenWarned = false;

module.exports = {
  name: 'ember-assign-polyfill',
  included() {
    this._ensureThisImport();

    const checker = new VersionChecker(this);
    const emberVersion = checker.forEmber();

    if (emberVersion.lt('2.5.0')) {
      this.import('vendor/ember-assign-polyfill/index.js');
    } else if (this.parent === this.project && !hasBeenWarned){
      console.warn('ember-assign-polyfill is not required for Ember 2.5.0 and later, please remove from your `package.json`.');
      hasBeenWarned = true;
    }
  },

  _ensureThisImport() {
    if (!this.import) {
      this._findHost = function findHostShim() {
        let current = this;
        let app;
        do {
          app = current.app || app;
        } while (current.parent.parent && (current = current.parent));
        return app;
      };
      this.import = function importShim(asset, options) {
        const app = this._findHost();
        app.import(asset, options);
      };
    }
  }
};
<commit_msg>Ensure `_super` is called in included hook<commit_after>'use strict';

const VersionChecker = require('ember-cli-version-checker');
let hasBeenWarned = false;

module.exports = {
  name: 'ember-assign-polyfill',
  included() {
    this._super.included.apply(this, arguments);
    this._ensureThisImport();

    const checker = new VersionChecker(this);
    const emberVersion = checker.forEmber();

    if (emberVersion.lt('2.5.0')) {
      this.import('vendor/ember-assign-polyfill/index.js');
    } else if (this.parent === this.project && !hasBeenWarned){
      console.warn('ember-assign-polyfill is not required for Ember 2.5.0 and later, please remove from your `package.json`.');
      hasBeenWarned = true;
    }
  },

  _ensureThisImport() {
    if (!this.import) {
      this._findHost = function findHostShim() {
        let current = this;
        let app;
        do {
          app = current.app || app;
        } while (current.parent.parent && (current = current.parent));
        return app;
      };
      this.import = function importShim(asset, options) {
        const app = this._findHost();
        app.import(asset, options);
      };
    }
  }
};
<|endoftext|>


<commit_before>var canvas = document.getElementById('can');
var ctx = canvas.getContext('2d');
var pressed = {};
var circles = [];
var converter = new colConvert();

//Should be global attributes
var friction = 1;
var delta_t = 0.05;
var min_alpha = 0.1;
var avg_lifespan = 600; //measured in frames
var avg_decay = Math.pow(min_alpha,1/avg_lifespan);
var border_percent = 1/3; //percent of radius used to make border

//Some thought should be given to these. They are bad. They make me feel bad.
var id = -1; //Used as a unique id for each circle
//var deletions = 0; //Used to modify the unique id when deleting an element

//This function should be changed!
function deleteElem(obj, array) {
    //console.log('Deleted object #:' + obj.id + ', Index:' + array.indexOf(obj)  + ', # deletions:' + deletions);
    array.splice(array.indexOf(obj),1);
    //deletions++;
}
//It's a bad function!

//Commonly used functions:

//Return a real min to max (inclusive)
function getUnif(min, max) {
    return Math.random() * (max - min) + min;
}

//Return an integer min to max (inclusive)
function getRandInt(min,max) {
    return Math.round(getUnif(min,max));
}

//Emulate a normal distribution - this uses the central limit theorem (the more iterations, the closer to a true normal it will be)
function getNorm(mean, iterations) {
    var output = 0;
    for (i = 0; i < iterations; i++) {
        output += Math.random() * mean;
    }
    return output / iterations;
}

var getSetStageSize = function (vert_percent, horz_percent) {
    var body_height = window.innerHeight || document.documentElement.clientHeight || document.getElementsByTagName('body')[0].clientHeight;
    var body_width = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;

    canvas.width = horz_percent * body_width;
    canvas.height = vert_percent * body_height;
}

//Circle object definition:

    function circle(x, y, r, max_veloc, alpha, id, color) {
        this.x = x;
        this.y = y;
        this.r = r;
        this.delta_t = delta_t;
        this.max_veloc = max_veloc;
        this.alpha = alpha;
        this.color = color;
        this.x_veloc = 0;
        this.y_veloc = 0;
        this.id = id
	this.decayRate = avg_decay + 0.01*(Math.random()-0.5);
    }

circle.prototype.draw = function () {

    //----Disks with shaded edges----//
    var inner_r = Math.ceil(this.r*(1-border_percent));
    ctx.fillStyle = "rgba(" + this.color[0] + "," + this.color[1] + "," + this.color[2] + "," + this.alpha + ")";
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
    ctx.fill();
    ctx.closePath();

    var temp_alpha = 1;
    var rho = Math.pow(this.alpha,(1/(this.r*border_percent)));
    for (var i = 0; i <= this.r-1; i++) {
        temp_alpha *= rho;
        ctx.strokeStyle = "rgba(" + this.color[0] + "," + this.color[1] + "," + this.color[2] + "," + temp_alpha + ")";
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.r - i, 0, 2 * Math.PI);
        ctx.stroke();
        ctx.closePath();
    }

/*
    //----Plain jane disks----//
    ctx.fillStyle =  "rgba(" + this.color[0] + "," + this.color[1] + "," + this.color[2] + "," + this.alpha + ")";
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.r-1, 0, 2 * Math.PI);
    ctx.fill();
    ctx.closePath();
*/
};

circle.prototype.updatePosition = function (scale) {
    this.x_veloc += getUnif(-scale, scale) / this.r;
    this.y_veloc += getUnif(-scale, scale) / this.r;
    this.x_veloc /= friction;
    this.y_veloc /= friction;
    this.x_veloc = Math.min(this.x_veloc, this.max_veloc);
    this.y_veloc = Math.min(this.y_veloc, this.max_veloc);
    //Update positions - make sure dot stays on canvas
    this.x += this.x_veloc * delta_t;
    this.y += this.y_veloc * delta_t;

    if (this.x > canvas.width) {
        this.x %= canvas.width;
    } else if (this.x < 0) {
        this.x = canvas.width;
    };

    if (this.y > canvas.height) {
        this.y %= canvas.height;
    } else if (this.y < 0) {
        this.y = canvas.height;
    };
    this.alpha = Math.max(this.alpha*this.decayRate,min_alpha) ;
};

//Running the demo

var setup = function () {
    document.addEventListener('keydown', function (e) {
        pressed[e.keyCode] = true;
    });

    document.addEventListener('keyup', function (e) {
        pressed[e.keyCode] = false;
    });
}

var updateGameState = function () {
    if (pressed[' '.charCodeAt(0)] == true) {
        id++;
        var x = getUnif(0,canvas.width);
        var y = getUnif(0,canvas.height);
        var r = getRandInt(3,35);
        //console.log(x + " " + y);
        //var color = "rgb(" + Math.floor(Math.random() * 256) + "," + Math.floor(Math.random() * 256) + "," + Math.floor(Math.random() * 256) + ")";
        var color = [getRandInt(0,255), getRandInt(0,255), getRandInt(0,255)]
        circles.push(new circle(x, y, r, 20, 1, id, color))
    }

    for (i = 0; i < circles.length; i++) {
        if ((circles.length > 1) && (circles[i].alpha <= min_alpha)) {
            deleteElem(circles[i], circles);
        } else {
            circles[i].updatePosition(15);
            circles[i].draw();
        };
    }
}

var gameLoop = function () {
    getSetStageSize(1, 1);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    updateGameState();
    window.requestAnimFrame(gameLoop);
}

window.requestAnimFrame = (function () {
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) {
        window.setTimeout(callback, 1000 / 60);
    };
})();

$(document).ready(function () {
    setup();
    window.requestAnimFrame(gameLoop);
});<commit_msg>Basic concept nailed down, but needs massive performance improvements<commit_after>var canvas = document.getElementById('can');
var ctx = canvas.getContext('2d');
var pressed = {};
var circles = [];

//Should be global attributes
var friction = 1;
var delta_t = 0.05;

//Some thought should be given to these. They are bad. They make me feel bad.
var id = -1; //Used as a unique id for each circle
//var deletions = 0; //Used to modify the unique id when deleting an element

//This function should be changed!
function deleteElem(obj, array) {
    //console.log('Deleted object #:' + obj.id + ', Index:' + array.indexOf(obj)  + ', # deletions:' + deletions);
    array.splice(array.indexOf(obj),1);
    //deletions++;
}
//It's a bad function!

//Commonly used functions:

//Return a real min to max (inclusive)
function getUnif(min, max) {
    return Math.random() * (max - min) + min;
}

//Return an integer min to max (inclusive)
function getRandInt(min,max) {
    return Math.round(getUnif(min,max));
}

//Emulate a normal distribution - this uses the central limit theorem (the more iterations, the closer to a true normal it will be)
function getNorm(mean, iterations) {
    var output = 0;
    for (i = 0; i < iterations; i++) {
        output += Math.random() * mean;
    }
    return output / iterations;
}

var getSetStageSize = function (vert_percent, horz_percent) {
    var body_height = window.innerHeight || document.documentElement.clientHeight || document.getElementsByTagName('body')[0].clientHeight;
    var body_width = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;

    canvas.width = horz_percent * body_width;
    canvas.height = vert_percent * body_height;
}

//Circle object definition:

function circle(x, y, r, max_veloc, alpha, id, color) {
    this.x = x;
    this.y = y;
    this.r = r;
    this.max_veloc = max_veloc;
    this.alpha = 0;
    this.color = color;
    this.x_veloc = getUnif(-1,1);
    this.y_veloc = getUnif(-1,1);
    this.id = id

    //Randomly generate verticies for craggy-looking asteroid shapes
    this.num_verts = getRandInt(9,Math.max(10,Math.round(this.r/2.5)));
    this.generateVerts(); //creates this.verts[num_verticies][2] - for each vertex there's a theta and an r-offset
}

circle.prototype.generateVerts = function () {
    this.thetas = new Array(this.num_verts);
    var scale = ((2*Math.PI)/this.num_verts);
    for(i=0; i<this.num_verts; i++){
	this.thetas[i] = i*scale + getUnif(-scale/3,scale/3);
    }
    this.thetas.sort();
    this.r_offsets = new Array(this.num_verts);
    for(i=0; i<this.num_verts; i++){
	this.r_offsets[i] = getUnif(-this.r/8,this.r/8);
    }
};

circle.prototype.draw = function () {

    //----Asteriod circles----//
    ctx.strokeStyle = "#ffffff";
    ctx.fillStyle = "rgba(" + this.color[0] + "," + this.color[1] + "," + this.color[2] + "," + this.alpha + ")";
    ctx.lineWidth = 1;

    //ctx.beginPath();
    //ctx.arc(500,500,20,0,2*Math.PI);
    //ctx.fill();
    //ctx.closePath();

    //First get a set of easy drawing instructions - a vector of x and y values representing where the verticies actually are
    var xs = [];
    var ys = [];
    for(i=0; i<this.num_verts; i++){
    	xs[i] = this.x + (this.r + this.r_offsets[i]) * Math.cos(this.thetas[i]);
    	ys[i] = this.y + (this.r + this.r_offsets[i]) * Math.sin(this.thetas[i]);
    	console.log(this.x+', '+xs[i]);
    }
    xs.push(xs[0]);
    ys.push(ys[0]);

    for(i=0; i<this.num_verts; i++){
    	//ctx.beginPath();
    	//ctx.arc(xs[i], ys[i], 20, 0, 2 * Math.PI);
    	//ctx.fill();
    	//ctx.closePath();

    	ctx.beginPath();
    	ctx.moveTo(xs[i], ys[i]);
    	ctx.lineTo(xs[i+1],ys[i+1]);
    	ctx.stroke();
    }

/*
    //----Plain jane disks----//
    ctx.fillStyle =  "rgba(" + this.color[0] + "," + this.color[1] + "," + this.color[2] + "," + this.alpha + ")";
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.r-1, 0, 2 * Math.PI);
    ctx.fill();
    ctx.closePath();
*/
};

circle.prototype.updatePosition = function (scale) {
    this.x_veloc += getUnif(-scale, scale) / this.r;
    this.y_veloc += getUnif(-scale, scale) / this.r;
    this.x_veloc /= friction;
    this.y_veloc /= friction;
    this.x_veloc = Math.min(this.x_veloc, this.max_veloc);
    this.y_veloc = Math.min(this.y_veloc, this.max_veloc);
    //Update positions - make sure dot stays on canvas
    this.x += this.x_veloc * delta_t;
    this.y += this.y_veloc * delta_t;

    if (this.x > canvas.width) {
        this.x %= canvas.width;
    } else if (this.x < 0) {
        this.x = canvas.width;
    };

    if (this.y > canvas.height) {
        this.y %= canvas.height;
    } else if (this.y < 0) {
        this.y = canvas.height;
    };
};

//Running the demo

var setup = function () {
    document.addEventListener('keydown', function (e) {
        pressed[e.keyCode] = true;
    });
    document.addEventListener('keyup', function (e) {
        pressed[e.keyCode] = false;
    });
}

var updateGameState = function () {
    if (pressed[' '.charCodeAt(0)] == true) {
        id++;
        var x = getUnif(0,canvas.width);
        var y = getUnif(0,canvas.height);
        var r = getUnif(20,50);
        //console.log(x + " " + y);
        //var color = "rgb(" + Math.floor(Math.random() * 256) + "," + Math.floor(Math.random() * 256) + "," + Math.floor(Math.random() * 256) + ")";
        var color = [1, 1, 1]
        circles.push(new circle(x, y, r, 20, 1, id, color))
    }

    for (i = 0; i < circles.length; i++) {
        circles[i].updatePosition(15);
        circles[i].draw();
    };
}

var gameLoop = function () {
    getSetStageSize(1, 1);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    updateGameState();
    window.requestAnimFrame(gameLoop);
}

window.requestAnimFrame = (function () {
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) {
        window.setTimeout(callback, 1000 / 60);
    };
})();

$(document).ready(function () {
    setup();
    window.requestAnimFrame(gameLoop);
});<|endoftext|>


<commit_before>define(module, function(exports, require, make) {

  var path = require('path');
  var glob = require('glob');
  var mustache = require('mustache');
  var uglify = require('uglify-js');
  var qp = require('qp-utility');
  var fss = require('qp-library/fss');
  var fso = require('qp-library/fso');
  var log = require('qp-library/log');
  var ver = require('qp-library/version');
  var asset = require('qp-asset');
  var view = require('qp-view');

  make({

    ns: 'qp-build/build',

    debug: false,
    bump: 'patch',
    version: {},
    state: {},
    pages: [],
    working_directory: '',
    site_dirname: 'site',
    page_dirname: 'page',
    template_directory: '',
    source_directory: '',
    target_directory: '',

    site_links: {},

    init: function(options) {

    },

    build: function() {
      this.build_target_directory();
      this.build_site_assets();
      this.build_pages();
    },

    build_target_directory: function() {
      fss.delete_directory(this.target_directory, { children: true });
    },

    build_site_assets: function() {
      var site_assets = this.get_assets(path.join(this.site_dirname, '.asset'));
      var site_links = qp.union(
        this.copy_files(site_assets.files.copy, file => qp.ltrim(file, '/site/')),
        this.merge_files(site_assets.files.merge, 'site')
      );
      this.site_links = this.group_by_extension(site_links);
    },

    build_pages: function() {
      qp.each(this.pages, this.build_page);
    },

    build_page: function(page) {
      var page_dir = page === 'index' ? '' : page;
      var page_assets = this.get_assets(path.join(this.page_dirname, page, '.asset'));
      var page_view = this.get_view(path.join(this.page_dirname, page, page + '.html'));
      page_assets.add_files('merge', page_view.file_list);
      var library_links = this.group_by_extension(this.copy_files(page_assets.files.library));
      var page_links = this.group_by_extension(
        qp.union(
          this.copy_files(page_assets.files.copy),
          this.merge_files(page_assets.files.merge, path.join(page, 'index'))
        )
      );
      var page_state = {
        page_title: page_view.token.title || page_assets.state.app_fullname,
        app_fullname: page_assets.state.app_fullname,
        app_name: page_assets.state.app_name,
        brand_color: page_assets.state.brand_color,
        app_display: page_assets.state.app_display
      };
      var page_html = this.apply_template(page_assets.state.page_template, qp.assign(page_state, {
        appcache: '',
        css_files: qp.union(library_links.css, this.site_links.css, page_links.css),
        js_files: qp.union(library_links.js, this.site_links.js, page_links.js),
        content: page_view.html
      }));
      fss.write(path.join(this.target_directory, page_dir, 'index.html'), page_html);
      fss.write(
        path.join(this.target_directory, 'fav', 'browserconfig.xml'),
        this.apply_template('browserconfig.xml', page_state)
      );
      fss.write(
        path.join(this.target_directory, 'fav', 'manifest.json'),
        this.apply_template('manifest.json', page_state)
      );
    },

    get_assets: function(file) {
      return asset.create({
        state: qp.clone(this.state),
        root: this.working_directory,
        file: path.join(this.source_directory, file)
      });
    },

    get_view: function(file) {
      return view.create({
        root: this.source_directory,
        file: path.join(this.source_directory, file)
      });
    },

    merge_files: function(file_list, filename) {
      var merged_files = [];
      qp.each_own(this.group_by_extension(file_list), (files, ext) => {
        var merge_file = this.make_root_link(filename + '.' + ext);
        var merge_filename = path.join(this.target_directory, merge_file);
        fss.merge_files(files, { out_file: merge_filename });
        merged_files.push(this.make_root_link(merge_file));
      });
      return merged_files;
    },

    copy_files: function(source_files, target) {
      return qp.map(source_files, source_file => {
        var target_file = this.make_root_link(qp.after(source_file, this.source_directory));
        if (target) target_file = target.call(this, target_file);
        this.copy_file(source_file, path.join(this.target_directory, target_file));
        return target_file;
      });
    },

    copy_file: function(source, target) {
      if (!fss.exists(target)) {
        fss.copy(source, target);
      }
    },

    make_root_link: function(link) {
      return '/' + qp.ltrim(qp.ltrim(link, '/'), 'index/');
    },

    group_by_extension: function(files) {
      return files.reduce((group, file) => {
        var ext = fso.extension(file);
        (group[ext] = group[ext] || []).push(file);
        return group;
      }, {});
    },

    apply_template: function(template, data) {
      return mustache.render(fss.read(this.template_directory, template), data);
    }

  });

});
<commit_msg>bump the version each build<commit_after>define(module, function(exports, require, make) {

  var path = require('path');
  var glob = require('glob');
  var mustache = require('mustache');
  var uglify = require('uglify-js');
  var qp = require('qp-utility');
  var fss = require('qp-library/fss');
  var fso = require('qp-library/fso');
  var log = require('qp-library/log');
  var asset = require('qp-asset');
  var view = require('qp-view');
  var version = require('qp-library/version');

  make({

    ns: 'qp-build/build',

    debug: false,
    bump: 'patch',
    version: '',
    state: {},
    pages: [],
    working_directory: '',
    site_dirname: 'site',
    page_dirname: 'page',
    template_directory: '',
    source_directory: '',
    target_directory: '',

    site_links: {},

    init: function(options) {

    },

    build: function() {
      this.build_target_directory();
      this.build_site_assets();
      this.build_pages();
      this.version = version(this.bump);
    },

    build_target_directory: function() {
      fss.delete_directory(this.target_directory, { children: true });
    },

    build_site_assets: function() {
      var site_assets = this.build_assets(path.join(this.site_dirname, '.asset'));
      var site_links = qp.union(
        this.copy_files(site_assets.files.copy, file => qp.ltrim(file, '/site/')),
        this.merge_files(site_assets.files.merge, 'site')
      );
      this.site_links = this.group_by_extension(site_links);
    },

    build_pages: function() {
      qp.each(this.pages, this.build_page);
    },

    build_page: function(page) {
      var page_dir = page === 'index' ? '' : page;
      var page_assets = this.build_assets(path.join(this.page_dirname, page, '.asset'));
      var page_view = this.build_view(path.join(this.page_dirname, page, page + '.html'));
      page_assets.add_files('merge', page_view.file_list);
      var library_links = this.group_by_extension(this.copy_files(page_assets.files.library));
      var page_links = this.group_by_extension(
        qp.union(
          this.copy_files(page_assets.files.copy),
          this.merge_files(page_assets.files.merge, path.join(page, 'index'))
        )
      );
      var page_state = {
        page_title: page_view.token.title || page_assets.state.app_fullname,
        app_fullname: page_assets.state.app_fullname,
        app_name: page_assets.state.app_name,
        brand_color: page_assets.state.brand_color,
        app_display: page_assets.state.app_display
      };
      var page_html = this.apply_template(page_assets.state.page_template, qp.assign(page_state, {
        appcache: '',
        css_files: qp.union(library_links.css, this.site_links.css, page_links.css),
        js_files: qp.union(library_links.js, this.site_links.js, page_links.js),
        content: page_view.html
      }));
      fss.write(path.join(this.target_directory, page_dir, 'index.html'), page_html);
      fss.write(
        path.join(this.target_directory, 'fav', 'browserconfig.xml'),
        this.apply_template('browserconfig.xml', page_state)
      );
      fss.write(
        path.join(this.target_directory, 'fav', 'manifest.json'),
        this.apply_template('manifest.json', page_state)
      );
    },

    build_assets: function(file) {
      return asset.create({
        state: qp.clone(this.state),
        root: this.working_directory,
        file: path.join(this.source_directory, file)
      });
    },

    build_view: function(file) {
      return view.create({
        root: this.source_directory,
        file: path.join(this.source_directory, file)
      });
    },

    merge_files: function(file_list, filename) {
      var merged_files = [];
      qp.each_own(this.group_by_extension(file_list), (files, ext) => {
        var merge_file = this.make_root_link(filename + '.' + ext);
        var merge_filename = path.join(this.target_directory, merge_file);
        fss.merge_files(files, { out_file: merge_filename });
        merged_files.push(this.make_root_link(merge_file));
      });
      return merged_files;
    },

    copy_files: function(source_files, target) {
      return qp.map(source_files, source_file => {
        var target_file = this.make_root_link(qp.after(source_file, this.source_directory));
        if (target) target_file = target.call(this, target_file);
        this.copy_file(source_file, path.join(this.target_directory, target_file));
        return target_file;
      });
    },

    copy_file: function(source, target) {
      if (!fss.exists(target)) {
        fss.copy(source, target);
      }
    },

    make_root_link: function(link) {
      return '/' + qp.ltrim(qp.ltrim(link, '/'), 'index/');
    },

    group_by_extension: function(files) {
      return files.reduce((group, file) => {
        var ext = fso.extension(file);
        (group[ext] = group[ext] || []).push(file);
        return group;
      }, {});
    },

    apply_template: function(template, data) {
      return mustache.render(fss.read(this.template_directory, template), data);
    }

  });

});
<|endoftext|>


<commit_before>/*
  global SRL, $, document
*/

const validatorPatterns = {
  mimeType: new SRL(`
    begin with capture (
        any of (digit, letter) once,
        any of (digit, letter, one of "!#$&-^_.+") between 0 and 126 times
    )
    literally "/"
    capture (
        any of (digit, letter) once,
        any of (digit, letter, one of "!#$&-^_.+") between 0 and 126 times
    )
    must end, case insensitive
  `),
  hostname: new SRL(`
    begin with capture (
      capture (
        any of (digit, letter, one of "-") once or more,
        literally "." once
      ) never or more,
      any of (digit, letter, one of "-") once or more
    ) once,
    capture (
      literally ":" once,
      digit once or more
    ) optional,
    must end, case insensitive
  `),
};

const validators = {
  mimeType (callback) {
    if (validatorPatterns.mimeType.isMatching(this.getValue())) {
      callback({ status: true });
    } else {
      callback({ status: false, message: 'Invalid MIME type e.g. application/vnd.github.v3.raw+json' });
    }
  },
  hostname (callback) {
    if (validatorPatterns.hostname.isMatching(this.getValue())) {
      callback({ status: true });
    } else {
      callback({ status: false, message: 'Invalid hostname e.g. host.example.com:80' });
    }
  },
  basePath () {
    if (!this.getValue().startsWith('/')) {
      this.setValue(`/${this.getValue()}`);
    }
  },
};

function download () {
  const str = `data:text/json;charset=utf-8,${encodeURIComponent(JSON.stringify(this.getValue(), null, '  '))}`;
  const downloadLink = document.createElement('a');
  downloadLink.setAttribute('href', str);
  downloadLink.setAttribute('download', 'swagger.json');
  downloadLink.innerHTML = 'Download Open API specification file';
  downloadLink.hidden = true;
  document.body.appendChild(download);
  downloadLink.click();
  downloadLink.remove();
}

// let form;

// function jsonPreview () {
//   $('#json-preview').removeClass('hidden');
//   if (form !== undefined) {
//     $('#json-preview').JSONView(form);
//   }
// }
//
// function richPreview () {
//   $('#rich-preview').removeClass('hidden');
//   if (form !== undefined) {
//     // TODO rich preview
//   }
// }

$('#form').alpaca({
  schemaSource: './schema.json',
  options: {
    fields: {
      info: {
        fields: {
          host: { validator: validators.hostname },
          basePath: { validator: validators.basePath },
        },
      },
      consumes: {
        items: {
          validator: validators.mimeType,
        },
        toolbarSticky: true,
      },
      produces: {
        items: {
          validator: validators.mimeType,
        },
        toolbarSticky: true,
      },
      paths: {
        type: 'map',
        toolbarSticky: true,
        items: {
          methods: {
            // This isn't working, `methods` isn't a map in the JSON output
            type: 'map',
            toolbarSticky: true,
          },
        },
      },
    },
    form: {
      buttons: {
        download: {
          click: download,
          type: 'button',
          value: 'Download as JSON',
          styles: 'btn btn-primary',
        },
      },
    },
  },
  postRender: (control) => {
    control.on('change', () => {
      const formData = this.getValue();
      if (!$('#json-preview').hasClass('hidden')) {
        $('#json-preview').JSONView(formData);
      } else if (!$('#rich-preview').hasClass('hidden')) {
        // TODO rich preview
      }
    });
  },
});
<commit_msg>Use downloadLink<commit_after>/*
  global SRL, $, document
*/

const validatorPatterns = {
  mimeType: new SRL(`
    begin with capture (
        any of (digit, letter) once,
        any of (digit, letter, one of "!#$&-^_.+") between 0 and 126 times
    )
    literally "/"
    capture (
        any of (digit, letter) once,
        any of (digit, letter, one of "!#$&-^_.+") between 0 and 126 times
    )
    must end, case insensitive
  `),
  hostname: new SRL(`
    begin with capture (
      capture (
        any of (digit, letter, one of "-") once or more,
        literally "." once
      ) never or more,
      any of (digit, letter, one of "-") once or more
    ) once,
    capture (
      literally ":" once,
      digit once or more
    ) optional,
    must end, case insensitive
  `),
};

const validators = {
  mimeType (callback) {
    if (validatorPatterns.mimeType.isMatching(this.getValue())) {
      callback({ status: true });
    } else {
      callback({ status: false, message: 'Invalid MIME type e.g. application/vnd.github.v3.raw+json' });
    }
  },
  hostname (callback) {
    if (validatorPatterns.hostname.isMatching(this.getValue())) {
      callback({ status: true });
    } else {
      callback({ status: false, message: 'Invalid hostname e.g. host.example.com:80' });
    }
  },
  basePath () {
    if (!this.getValue().startsWith('/')) {
      this.setValue(`/${this.getValue()}`);
    }
  },
};

function download () {
  const str = `data:text/json;charset=utf-8,${encodeURIComponent(JSON.stringify(this.getValue(), null, '  '))}`;
  const downloadLink = document.createElement('a');
  downloadLink.setAttribute('href', str);
  downloadLink.setAttribute('download', 'swagger.json');
  downloadLink.innerHTML = 'Download Open API specification file';
  downloadLink.hidden = true;
  document.body.appendChild(downloadLink);
  downloadLink.click();
  downloadLink.remove();
}

// let form;

// function jsonPreview () {
//   $('#json-preview').removeClass('hidden');
//   if (form !== undefined) {
//     $('#json-preview').JSONView(form);
//   }
// }
//
// function richPreview () {
//   $('#rich-preview').removeClass('hidden');
//   if (form !== undefined) {
//     // TODO rich preview
//   }
// }

$('#form').alpaca({
  schemaSource: './schema.json',
  options: {
    fields: {
      info: {
        fields: {
          host: { validator: validators.hostname },
          basePath: { validator: validators.basePath },
        },
      },
      consumes: {
        items: {
          validator: validators.mimeType,
        },
        toolbarSticky: true,
      },
      produces: {
        items: {
          validator: validators.mimeType,
        },
        toolbarSticky: true,
      },
      paths: {
        type: 'map',
        toolbarSticky: true,
        items: {
          methods: {
            // This isn't working, `methods` isn't a map in the JSON output
            type: 'map',
            toolbarSticky: true,
          },
        },
      },
    },
    form: {
      buttons: {
        download: {
          click: download,
          type: 'button',
          value: 'Download as JSON',
          styles: 'btn btn-primary',
        },
      },
    },
  },
  postRender: (control) => {
    control.on('change', () => {
      const formData = this.getValue();
      if (!$('#json-preview').hasClass('hidden')) {
        $('#json-preview').JSONView(formData);
      } else if (!$('#rich-preview').hasClass('hidden')) {
        // TODO rich preview
      }
    });
  },
});
<|endoftext|>