<commit_before>document.addEventListener("DOMContentLoaded", function() {
    var allowHiddenResults = false;
    var canvas = document.querySelector("canvas");
    var examples;
    var req = new XMLHttpRequest();
    req.open("GET", "examples.json");
    req.responseType = "json";
    req.onload = function() {
        examples = req.response;
        $('.ui.search').search({
            duration: 0,
            transition: false,
            maxResults: 50,
            minCharacters: 0,
            searchFields: ['title'],
            searchFullText: true,
            source: examples,
            onResultsOpen: function() {
                $('#ComplexCurves').hide();
                allowHiddenResults = false;
            },
            onResultsClose: function() {
                if (!allowHiddenResults)
                    $('.ui.search').search('show results');
            },
            onSelect: function(example) {
                if (canvas.complexCurves)
                    canvas.complexCurves.unregisterEventHandlers();
                var piOver180 = Math.PI / 180;
                var lat = 75 * piOver180;
                var lon = 30 * piOver180;
                if (example.cached) {
                    canvas.complexCurves =
                        ComplexCurves.fromFile(canvas,
                            'http://complexcurves.org/models/' + example.id +
                            '.bin', example.equation, lat, lon);
                } else {
                    canvas.complexCurves = ComplexCurves.fromEquation(canvas,
                        example.equation ||
                        $('.ui.search').search('get value'),
                        example.depth || 12, lat, lon);
                }
                $('#ComplexCurves').show();
                allowHiddenResults = true;
            },
            templates: {
                message: function(message, type) {
                    var
                        html = '';
                    var value = $('.ui.search').search('get value');
                    try {
                        PolynomialParser.parse(value);
                        html = $('.ui.search').search('generate results', {
                            "results": [{
                                "id": "Custom",
                                "cached": false,
                                "title": "Custom equation",
                                "equation": value,
                                "description": value
                            }]
                        });
                        $('.ui.search').search('add results', html);
                        return;
                    } catch (Error) {}
                    if (message !== undefined && type !== undefined) {
                        html += '' + '
';
                        // message type
                        if (type == 'empty') {
                            html += '' +
                            '
' + 'No Results' + '
' +
                            '
' + message + '
';
                        } else {
                            html += '
' + message +
                            '
';
                        }
                        html += '
';
                    }
                    return html;
                },
                standard: function(response, fields) {
                    var
                        html = '';
                    if (response[fields.results] !== undefined) {

                        // each result
                        $.each(response[fields.results], function(index, result) {
                            if (result[fields.url]) {
                                html += '';
                            } else {
                                html += '';
                            }
                            if (result[fields.image] !== undefined) {
                                html += '' + '
' +
                                ' ' +
                                '
';
                            }
                            html += '
';
                            if (result[fields.price] !== undefined) {
                                html += '
' +
                                result[fields.price] + '
';
                            }
                            if (result[fields.title] !== undefined) {
                                html += '
' +
                                result[fields.title] + '
';
                            }
                            if (result[fields.description] !== undefined) {
                                html += '
' +
                                result[fields.description] + '
';
                            }
                            html += '' + '
';
                            html += '';
                        });

                        if (response[fields.action]) {
                            html += '' + '' +
                            response[fields.action][fields.actionText] + '';
                        }
                        return html;
                    }
                    return false;
                }
            }
        });
        $('.ui.search').search('search local', '');
        $('.ui.search').search('show results');
    };
    req.send();
    $('.ui.dropdown').dropdown().on('change', function (evt) {
        var text = evt.target.value;
        var complexCurves = document.querySelector('canvas').complexCurves;
        var phi = 5 / 12 * Math.PI;
        var theta = Math.PI / 6;
        switch (text) {
            case 'Default':
                complexCurves.rotateLatLong(phi, theta);
                break;
            case 'Front':
                complexCurves.rotateFront();
                break;
            case 'Back':
                complexCurves.rotateBack();
                break;
            case 'Left':
                complexCurves.rotateLeft();
                break;
            case 'Right':
                complexCurves.rotateRight();
                break;
            case 'Top':
                complexCurves.rotateTop();
                break;
            case 'Bottom':
                complexCurves.rotateBottom();
                break;
        }
    });
    $('#autorotateCheckbox').checkbox({
        onChange: function() {
            var complexCurves = document.querySelector('canvas').complexCurves;
            complexCurves.setAutorotate($(this).context.checked);
        }
    });
    $('#clippingCheckbox').checkbox({
        onChange: function() {
            var complexCurves = document.querySelector('canvas').complexCurves;
            complexCurves.setClipping($(this).context.checked);
        }
    });
    $('#orthoCheckbox').checkbox({
        onChange: function() {
            var complexCurves = document.querySelector('canvas').complexCurves;
            complexCurves.setOrtho($(this).context.checked);
        }
    });
    $('#transparencyCheckbox').checkbox({
        onChange: function() {
            var complexCurves = document.querySelector('canvas').complexCurves;
            complexCurves.setTransparency($(this).context.checked);
        }
    });
    $('#surfaceButton').on('click', function () {
        var complexCurves = document.querySelector('canvas').complexCurves;
        complexCurves.exportSurface();
    });
    $('#screenshotButton').on('click', function () {
        var complexCurves = document.querySelector('canvas').complexCurves;
        complexCurves.exportScreenshot();
    });
    $('#domainColouringButton').on('click', function () {
        var complexCurves = document.querySelector('canvas').complexCurves;
        complexCurves.exportDomainColouring();
    });
});
<commit_msg>Leave entered custom equation intact<commit_after>document.addEventListener("DOMContentLoaded", function() {
    var allowHiddenResults = false;
    var canvas = document.querySelector("canvas");
    var examples;
    var req = new XMLHttpRequest();
    req.open("GET", "examples.json");
    req.responseType = "json";
    req.onload = function() {
        examples = req.response;
        $('.ui.search').search({
            duration: 0,
            transition: false,
            maxResults: 50,
            minCharacters: 0,
            searchFields: ['title'],
            searchFullText: true,
            source: examples,
            onResultsOpen: function() {
                $('#ComplexCurves').hide();
                allowHiddenResults = false;
            },
            onResultsClose: function() {
                if (!allowHiddenResults)
                    $('.ui.search').search('show results');
            },
            onSelect: function(example) {
                if (canvas.complexCurves)
                    canvas.complexCurves.unregisterEventHandlers();
                var piOver180 = Math.PI / 180;
                var lat = 75 * piOver180;
                var lon = 30 * piOver180;
                if (example.cached) {
                    canvas.complexCurves =
                        ComplexCurves.fromFile(canvas,
                            'http://complexcurves.org/models/' + example.id +
                            '.bin', example.equation, lat, lon);
                } else {
                    canvas.complexCurves = ComplexCurves.fromEquation(canvas,
                        example.equation ||
                        $('.ui.search').search('get value'),
                        example.depth || 12, lat, lon);
                }
                $('#ComplexCurves').show();
                allowHiddenResults = true;
            },
            templates: {
                message: function(message, type) {
                    var
                        html = '';
                    var value = $('.ui.search').search('get value');
                    try {
                        PolynomialParser.parse(value);
                        html = $('.ui.search').search('generate results', {
                            "results": [{
                                "id": "Custom",
                                "cached": false,
                                "title": value,
                                "equation": value,
                                "description": "Custom equation"
                            }]
                        });
                        $('.ui.search').search('add results', html);
                        return;
                    } catch (Error) {}
                    if (message !== undefined && type !== undefined) {
                        html += '' + '
';
                        // message type
                        if (type == 'empty') {
                            html += '' +
                            '
' + 'No Results' + '
' +
                            '
' + message + '
';
                        } else {
                            html += '
' + message +
                            '
';
                        }
                        html += '
';
                    }
                    return html;
                },
                standard: function(response, fields) {
                    var
                        html = '';
                    if (response[fields.results] !== undefined) {

                        // each result
                        $.each(response[fields.results], function(index, result) {
                            if (result[fields.url]) {
                                html += '';
                            } else {
                                html += '';
                            }
                            if (result[fields.image] !== undefined) {
                                html += '' + '
' +
                                ' ' +
                                '
';
                            }
                            html += '
';
                            if (result[fields.price] !== undefined) {
                                html += '
' +
                                result[fields.price] + '
';
                            }
                            if (result[fields.title] !== undefined) {
                                html += '
' +
                                result[fields.title] + '
';
                            }
                            if (result[fields.description] !== undefined) {
                                html += '
' +
                                result[fields.description] + '
';
                            }
                            html += '' + '
';
                            html += '';
                        });

                        if (response[fields.action]) {
                            html += '' + '' +
                            response[fields.action][fields.actionText] + '';
                        }
                        return html;
                    }
                    return false;
                }
            }
        });
        $('.ui.search').search('search local', '');
        $('.ui.search').search('show results');
    };
    req.send();
    $('.ui.dropdown').dropdown().on('change', function (evt) {
        var text = evt.target.value;
        var complexCurves = document.querySelector('canvas').complexCurves;
        var phi = 5 / 12 * Math.PI;
        var theta = Math.PI / 6;
        switch (text) {
            case 'Default':
                complexCurves.rotateLatLong(phi, theta);
                break;
            case 'Front':
                complexCurves.rotateFront();
                break;
            case 'Back':
                complexCurves.rotateBack();
                break;
            case 'Left':
                complexCurves.rotateLeft();
                break;
            case 'Right':
                complexCurves.rotateRight();
                break;
            case 'Top':
                complexCurves.rotateTop();
                break;
            case 'Bottom':
                complexCurves.rotateBottom();
                break;
        }
    });
    $('#autorotateCheckbox').checkbox({
        onChange: function() {
            var complexCurves = document.querySelector('canvas').complexCurves;
            complexCurves.setAutorotate($(this).context.checked);
        }
    });
    $('#clippingCheckbox').checkbox({
        onChange: function() {
            var complexCurves = document.querySelector('canvas').complexCurves;
            complexCurves.setClipping($(this).context.checked);
        }
    });
    $('#orthoCheckbox').checkbox({
        onChange: function() {
            var complexCurves = document.querySelector('canvas').complexCurves;
            complexCurves.setOrtho($(this).context.checked);
        }
    });
    $('#transparencyCheckbox').checkbox({
        onChange: function() {
            var complexCurves = document.querySelector('canvas').complexCurves;
            complexCurves.setTransparency($(this).context.checked);
        }
    });
    $('#surfaceButton').on('click', function () {
        var complexCurves = document.querySelector('canvas').complexCurves;
        complexCurves.exportSurface();
    });
    $('#screenshotButton').on('click', function () {
        var complexCurves = document.querySelector('canvas').complexCurves;
        complexCurves.exportScreenshot();
    });
    $('#domainColouringButton').on('click', function () {
        var complexCurves = document.querySelector('canvas').complexCurves;
        complexCurves.exportDomainColouring();
    });
});
<|endoftext|>


<commit_before>/* eslint-disable  func-names */
/* eslint quote-props: ["error", "consistent"]*/
/**
 * This sample demonstrates a simple skill built with the Amazon Alexa Skills
 * nodejs skill development kit.
 * This sample supports multiple lauguages. (en-US, en-GB, de-DE).
 * The Intent Schema, Custom Slots and Sample Utterances for this skill, as well
 * as testing instructions are located at https://github.com/alexa/skill-sample-nodejs-fact
 **/

'use strict';

const Alexa = require('alexa-sdk');
const moment = require('moment');
const moment_tz = require('moment-timezone');
const APP_ID = undefined;  // TODO replace with your app ID (OPTIONAL).

const languageStrings = {
    'en-US': {
        translation: {
            QT: {
                "04-19": "Revelation 01:01-18",
                "04-18": "Jude 01:17-25",
                "04-15": "2 John 01:01-13",
                "04-14": "1 John 05:13-21",
                "04-17": "Jude 01:01-16",
                "04-16": "3 John 01:01-15",
                "04-11": "1 John 04:01-06",
                "04-10": "1 John 03:11-24",
                "04-13": "1 John 05:01-12",
                "04-12": "1 John 04:07-21",
                "04-30": "Revelation 05:01-15",
                "05-01": "Revelation 05:16-30",
                "05-02": "Revelation 05:31-47",
                "04-24": "Revelation 02:12-25",
                "04-25": "Revelation 03:01-21",
                "04-26": "Revelation 03:22-36",
                "04-27": "Revelation 04:01-26",
                "04-20": "Revelation 01:19-28",
                "04-21": "Revelation 01:29-34",
                "04-22": "Revelation 01:35-51",
                "04-23": "Revelation 02:01-11",
                "04-28": "Revelation 04:27-42",
                "04-29": "Revelation 04:43-54",
                "04-08": "1 John 02:18-29",
                "04-09": "1 John 03:01-10",
                "04-06": "1 John 01:01-10",
                "04-07": "1 John 02:01-17",
                "04-04": "2 Peter 02:01-22",
                "04-05": "2 Peter 03:01-18",
                "04-02": "2 Peter 01:01-11",
                "04-03": "2 Peter 01:12-21",
                "04-01": "1 Peter 05:01-14"},
            SKILL_NAME: 'QT',
            GET_QT_MESSAGE: "Here's today's qt ",
            HELP_MESSAGE: 'You can say tell me a space fact, or, you can say exit... What can I help you with?',
            HELP_REPROMPT: 'What can I help you with?',
            STOP_MESSAGE: 'Goodbye!',
        },
    }
};

const handlers = {
    'LaunchRequest': function () {
        this.emit('GetQTIntent');
    },
    'GetQTIntent': function() {
       /* var itemSlot = this.event.request.intent.slots.Date;
        var givenDate;
        if(itemSlot && itemSlot.value){
            givenDate = itemSlot.value.toLowerCase();
        } */

        const today = moment().tz('America/Los_Angeles').format("MM-DD");

        const qt = this.t('QT');
        const qtToday = qt[today];
        const speechOutput = this.t('GET_QT_MESSAGE') + qtToday;
        this.emit(':tellWithCard', speechOutput, this.t('SKILL_NAME'), qtToday);
    },
    'AMAZON.HelpIntent': function () {
        const speechOutput = this.t('HELP_MESSAGE');
        const reprompt = this.t('HELP_MESSAGE');
        this.emit(':ask', speechOutput, reprompt);
    },
    'AMAZON.CancelIntent': function () {
        this.emit(':tell', this.t('STOP_MESSAGE'));
    },
    'AMAZON.StopIntent': function () {
        this.emit(':tell', this.t('STOP_MESSAGE'));
    },
    'SessionEndedRequest': function () {
        this.emit(':tell', this.t('STOP_MESSAGE'));
    },
};

exports.handler = (event, context) => {
    const alexa = Alexa.handler(event, context);
    alexa.APP_ID = APP_ID;
    // To enable string internationalization (i18n) features, set a resources object.
    alexa.resources = languageStrings;
    alexa.registerHandlers(handlers);
    alexa.execute();
};
<commit_msg>Testing<commit_after>/* eslint-disable  func-names */
/* eslint quote-props: ["error", "consistent"]*/
/**
 * This sample demonstrates a simple skill built with the Amazon Alexa Skills
 * nodejs skill development kit.
 * This sample supports multiple lauguages. (en-US, en-GB, de-DE).
 * The Intent Schema, Custom Slots and Sample Utterances for this skill, as well
 * as testing instructions are located at https://github.com/alexa/skill-sample-nodejs-fact
 **/

'use strict';

const Alexa = require('alexa-sdk');
const moment = require('moment');
const moment_tz = require('moment-timezone');
const APP_ID = undefined;  // TODO Optional

const languageStrings = {
    'en-US': {
        translation: {
            QT: {
                "04-19": "Revelation 01:01-18",
                "04-18": "Jude 01:17-25",
                "04-15": "2 John 01:01-13",
                "04-14": "1 John 05:13-21",
                "04-17": "Jude 01:01-16",
                "04-16": "3 John 01:01-15",
                "04-11": "1 John 04:01-06",
                "04-10": "1 John 03:11-24",
                "04-13": "1 John 05:01-12",
                "04-12": "1 John 04:07-21",
                "04-30": "Revelation 05:01-15",
                "05-01": "Revelation 05:16-30",
                "05-02": "Revelation 05:31-47",
                "04-24": "Revelation 02:12-25",
                "04-25": "Revelation 03:01-21",
                "04-26": "Revelation 03:22-36",
                "04-27": "Revelation 04:01-26",
                "04-20": "Revelation 01:19-28",
                "04-21": "Revelation 01:29-34",
                "04-22": "Revelation 01:35-51",
                "04-23": "Revelation 02:01-11",
                "04-28": "Revelation 04:27-42",
                "04-29": "Revelation 04:43-54",
                "04-08": "1 John 02:18-29",
                "04-09": "1 John 03:01-10",
                "04-06": "1 John 01:01-10",
                "04-07": "1 John 02:01-17",
                "04-04": "2 Peter 02:01-22",
                "04-05": "2 Peter 03:01-18",
                "04-02": "2 Peter 01:01-11",
                "04-03": "2 Peter 01:12-21",
                "04-01": "1 Peter 05:01-14"},
            SKILL_NAME: 'QT',
            GET_QT_MESSAGE: "Here's today's qt ",
            HELP_MESSAGE: 'You can say tell me a space fact, or, you can say exit... What can I help you with?',
            HELP_REPROMPT: 'What can I help you with?',
            STOP_MESSAGE: 'Goodbye!',
        },
    }
};

const handlers = {
    'LaunchRequest': function () {
        this.emit('GetQTIntent');
    },
    'GetQTIntent': function() {
       /* var itemSlot = this.event.request.intent.slots.Date;
        var givenDate;
        if(itemSlot && itemSlot.value){
            givenDate = itemSlot.value.toLowerCase();
        } */

        const today = moment().tz('America/Los_Angeles').format("MM-DD");

        const qt = this.t('QT');
        const qtToday = qt[today];
        const speechOutput = this.t('GET_QT_MESSAGE') + qtToday;
        this.emit(':tellWithCard', speechOutput, this.t('SKILL_NAME'), qtToday);
    },
    'AMAZON.HelpIntent': function () {
        const speechOutput = this.t('HELP_MESSAGE');
        const reprompt = this.t('HELP_MESSAGE');
        this.emit(':ask', speechOutput, reprompt);
    },
    'AMAZON.CancelIntent': function () {
        this.emit(':tell', this.t('STOP_MESSAGE'));
    },
    'AMAZON.StopIntent': function () {
        this.emit(':tell', this.t('STOP_MESSAGE'));
    },
    'SessionEndedRequest': function () {
        this.emit(':tell', this.t('STOP_MESSAGE'));
    },
};

exports.handler = (event, context) => {
    const alexa = Alexa.handler(event, context);
    alexa.APP_ID = APP_ID;
    // To enable string internationalization (i18n) features, set a resources object.
    alexa.resources = languageStrings;
    alexa.registerHandlers(handlers);
    alexa.execute();
};
<|endoftext|>


<commit_before>window.onload = function () {

  // Init Console
  var cnsl = new Console({}, {
    welcome: 'Hello user. Need any "help"?'
  });

  // Game data
  var player = {
    name: 'Player'
  };

  /**
   * Register console command handlers.
   */

  var handlers = {
    say: function () {
      return player.name + ': "' + Array.prototype.join.call(arguments, ' ') + '"';
    },
    name: 'setname',
    setname: function (name) {
      player.name = name;
      return 'Player name is ' + player.name + ' now.';
    },
    help: function () {
      var cmds = cnsl.commands;
      for (var name in cmds) {
        if (cmds.hasOwnProperty(name)) {
          cmds[name].desc && cnsl.log(' -', cmds[name].usage + ':', cmds[name].desc);
        }
      }
    }
  };

  var handlerProps = {
    say: {
      usage: 'SAY <message string>',
      desc: 'Broadcast a message to other players in the game.'
    },
    setname: {
      usage: 'SETNAME <newname> || NAME <newname>',
      desc: 'Change your name (works in network play too).'
    },
    help: {
      usage: 'HELP',
      desc: 'Show help messages.'
    }
  };

  for (var cmdname in handlers) {
    cnsl.register(cmdname, handlers[cmdname], handlerProps[cmdname]);
  }

  // Init Console 2

  var codes = {
    'showmethecode':
      ' - createconsole: How to init a new console.\n' +
      ' - options: Available options.\n' +
      ' - more: More docs.',
    'createconsole':
      'new Console({\n' +
      '  "addbots": function (num) {\n' +
      '      // add some bots,\n' +
      '      // then tell player:\n' +
      '      return num + " bots added."\n' +
      '  }\n' +
      '});',
    'options':
      'new Console({}, {\n' +
      '    hotkey: 27, \n' +
      '    welcome: "Hello User:",\n' +
      '    caseSensitive: true,\n' +
      '    defaultHandler: function(){}\n' +
      '    onShow: function(){},\n' +
      '    onHide: function(){}\n' +
      '});\n' +
      ' - `hotkey` : {Number|boolean} The keyCode of hotkey. *Hint: If you want to manually put' +
      ' up console(`cnsl.toggle("on")`), set to a falsy value.* `192` by default, the "~".\n' +
      ' - `welcome`: {String} The welcome message. `""` by default.\n' +
      ' - `caseSensitive`: {Boolean} If you want to. `false` by default.' +
      ' - `defaultHandler`: {Function} the default handler for any unspecified command. `null` by default.\n' +
      ' - `onShow` : {Function} On show callback. `null` by default.\n' +
      ' - `onHide` : {Function} On hide callback. `null` by default.',
    'more': 'Visit http://github.com/amio/console.js/'
  };

  var smtc = new Console({}, {
    hotkey: 27, // ESC
    welcome: 'Use "showmethecode":',
    defaultHandler: function (cmd) {
      return codes[cmd];
    }
  });

  // For tablet visiters
  document.getElementById('slash').addEventListener('click', function () {cnsl.toggle()})
  document.getElementById('esc').addEventListener('click', function () {smtc.toggle()})

};
<commit_msg>(chore) update example.<commit_after>window.onload = function () {

  // Init Console
  var cnsl = new Console({}, {
    welcome: 'Hello user. Need any "help"?'
  });

  // Game data
  var player = {
    name: 'Player'
  };

  /**
   * Register console command handlers.
   */

  var handlers = {
    say: function () {
      return player.name + ': "' + Array.prototype.join.call(arguments, ' ') + '"';
    },
    name: 'setname',
    setname: function (name) {
      player.name = name;
      return 'Player name is ' + player.name + ' now.';
    },
    help: function () {
      var cmds = cnsl.commands;
      for (var name in cmds) {
        if (cmds.hasOwnProperty(name)) {
          cmds[name].desc && cnsl.log(' -', cmds[name].usage + ':', cmds[name].desc);
        }
      }
    }
  };

  var handlerProps = {
    say: {
      usage: 'SAY <message string>',
      desc: 'Broadcast a message to other players in the game.'
    },
    setname: {
      usage: 'SETNAME <newname> || NAME <newname>',
      desc: 'Change your name (works in network play too).'
    },
    help: {
      usage: 'HELP',
      desc: 'Show help messages.'
    }
  };

  for (var cmdname in handlers) {
    cnsl.register(cmdname, handlers[cmdname], handlerProps[cmdname]);
  }

  // Init Console 2

  var codes = {
    'showmethecode':
      ' - createconsole: How to init a new console.\n' +
      ' - options: Available options.\n' +
      ' - more: More docs.',
    'create':
      'new Console({\n' +
      '  "addbots": function (num) {\n' +
      '      // add some bots,\n' +
      '      // then tell player:\n' +
      '      return num + " bots added."\n' +
      '  }\n' +
      '});',
    'options':
      'new Console({}, {\n' +
      '    hotkey: 27, \n' +
      '    welcome: "Hello User:",\n' +
      '    caseSensitive: true,\n' +
      '    defaultHandler: function(){}\n' +
      '    onShow: function(){},\n' +
      '    onHide: function(){}\n' +
      '});\n' +
      ' - `hotkey` : {Number|boolean} The keyCode of hotkey. *Hint: If you want to manually put' +
      ' up console(`cnsl.toggle("on")`), set to a falsy value.* `192` by default, the "~".\n' +
      ' - `welcome`: {String} The welcome message. `""` by default.\n' +
      ' - `caseSensitive`: {Boolean} If you want to. `false` by default.' +
      ' - `defaultHandler`: {Function} the default handler for any unspecified command. `null` by default.\n' +
      ' - `onShow` : {Function} On show callback. `null` by default.\n' +
      ' - `onHide` : {Function} On hide callback. `null` by default.',
    'more': 'Visit http://github.com/amio/console.js/'
  };

  var smtc = new Console({}, {
    hotkey: 27, // ESC
    welcome: 'Use "showmethecode":',
    defaultHandler: function (cmd) {
      return codes[cmd];
    }
  });

  smtc.register("showmethecode", function () { return codes['showmethecode'] })
  smtc.register("create", function () { return codes['create'] })
  smtc.register("options", function () { return codes['options'] })
  smtc.register("more", function () { return codes['more'] })

  // For tablet visiters
  document.getElementById('slash').addEventListener('click', function () {cnsl.toggle()})
  document.getElementById('esc').addEventListener('click', function () {smtc.toggle()})

};
<|endoftext|>


<commit_before>//TODO: simple -r provider to get nice test bundles via require global.

//TODO Standalone compilation with no module checking: window.Name = module (use case - weakset);
//TODO Concat stdin
//TODO wrap final result into simple closure to provide closurecompiler scope

//TODO tests
//TODO pass module prefix
//TODO debug mode
//TODO cut comments
//TODO exclude files
//TODO externs - list of global reserved words
//TODO humanized output
//TODO same options as browserify, especially -r

//FIXME provide require function at the top for runtime calculations

var util = require('util');
var map = require('map-stream');
var fs = require('fs');
var slug = require('slug');
var path = require('path');
var concat = require('concat-stream');
var esprima = require('esprima');
var escodegen = require('escodegen');
var escope = require('escope');
var resolve = require('resolve');
var browserify = require('browserify');

/** processing options */
var options = {
	/** Prefix for module global vars */
	prefix: '_m_'
};

/**
 * @module uncommonjs
 *
 * @param {Array|Stream} arg Whether list of files or stdin stream
 *
 * @return {[type]} [description]
 */
module.exports = function(arg, opts, cb){
	//TODO: extend self options with external opts passed

	var b = browserify(arg, opts);

	var bundle, result;

	b.on('error', function(a,b,c){
		throw Error(a,b,c);
	});

	//start pipeline
	b.pipeline.get('dedupe')

	//prepare each module
	.pipe(
		map(
			function(dep, done){
				processModule(dep);
				done(null, dep);
			})
		)

	//form result
	.pipe(
		concat(
			function(list){
				result = processResult(list);

				if (opts.wrap) {
					result = opts.wrap.replace('%output%', result);
				}

				bundle.emit('success', result);
			}
		)
	);

	//Start browserify (bundle)
	bundle = b.bundle();

	return bundle;
};

/** global variables aliases dict: 'var1: var1, var2: var2alias' */
var globalVariables = {};

/** module variable names and aliases keyed by module ids */
var moduleVariableName = {};

/** cache of module paths keyed by ids */
var modulePath = {};

/**
 * catch `require` in code (too bad, I know, but the fastest relative to esprima)
 * Note that require accepts simple numbers also
 */
var requireRe = /require\(\s*['"]([^'")]*)['"]\s*\)/g;

/**
 * Process resulted module dep list once it’s formed
 *
 * @param {array} list A list of module deps
 *
 * @return {[type]} [description]
 */
function processResult(list){
	//sort deps to include innermost first

	//dupes aliases
	var dupes={},

	//dict of items by ids
		items={};

	//filter list of deps
	list = list

	//remove duplicates
	.filter(function(item){
		//create dict of modules by ids
		items[item.id] = item;

		//dedupe found by browserify
		if (item.dedupe) {
			dupes[item.id] = item.dedupeIndex;
			return false;
		}
		//search dupes manually in list
		// for (var i = list.length; i--;){
		// 	if (list[i] !== item && list[i].name === item.name) {
		// 		console.log('dedupe', list[i], item)
				// return false;
		// 	}
		// }
		return true;
	})

	//sort deps to declare in proper order
	.sort(function(a,b){
		//if includes one as an other’s dep - declare independent first
		if (hasDep(a, b)) return 1;
		if (hasDep(b, a)) return -1;

		//calc number of deps, return smaller
		//suppose that less-dependent module is better to be declared first
		if (depNumber(a) > depNumber(b)) return 1;
		else return -1;
	});

	//whether a-dep depends on b
	function hasDep(a, b){
		for (var name in a.deps){
			if (a.deps[name] === b.id || dupes[a.deps[name]] === b.id) return true;

			//find inner dep
			if ( hasDep(items[a.deps[name]], b)) return true;
		}
		return false;
	}

	function depNumber(a){
		return Object.keys(a.deps).length;
	}

	// list.forEach(function(item){
	// 	item.source = item.source.slice(0,30) + '... ' + item.source.length;
	// });
	// console.log(list)
	// console.log('concat:\n',util.inspect(list, {colors:true}));

	//declare all var module names beforehead
	//in order to not get accessed undeclared
	var declStr = '/**\n * Modules declarations\n */\n';
	declStr += 'var ';
	list.forEach(function(item){
		declStr += item.name + ', ';
	});
	declStr = declStr.slice(0, -2) + ';\n';

	//concat sources in the proper order of declaration
	var result = declStr;
	list.forEach(function(dep){
		result += '\n\n\n/**\n * @module ' + moduleVariableName[dep.id] + '\n * @file ' + modulePath[dep.id] + ' \n */\n\n';
		result += dep.source + '\n';
	});

	//replace require calls
	result = result.replace(requireRe, function(requireStr, modPath, idx, fullSrc){
		var modName;

		//get module name from cached paths
		if (modulePath[modPath]) modName = modulePath[modPath];

		//resolve unresolved module
		else modName = resolve.sync(modPath);

		//replace require with var name
		if (moduleVariableName[modName]) {
			return moduleVariableName[modName];
		}

		throw Error('Module to require isn’t found: `' + modName + '`');
	});

	//if there are runtime requires left
	//append `require` function returning found modules' if any
	//TODO
	// if (/\brequire\b/.test(result)) {
	// 	result =
	// 	(function require(name){
	// 		return m[name];
	// 	}).toSource() + '\n'
	// 	+ result;
	// }

	//for each standalone passed, create global unadvancedoptimizable var

	//for each require passed, create an entry in require set

	return result;
}

/**
 * Process a separate module
 *
 * @param {object} dep A dependency object (module info)
 *
 * @return {object} The dep with rebuilt `source` property
 */
function processModule(dep){
	// console.log('---------dep:\n',util.inspect(dep, {colors:true}));
	var dir = path.dirname(dep.file);
	var src = dep.source;

	//get module var name
	var moduleVarName = getModuleVarName(dep);

	//save module name to declare it beforehead as a first-class var
	dep.name = moduleVarName;
	moduleVariableName[dep.id] = moduleVarName;
	moduleVariableName[dep.file] = moduleVarName;
	modulePath[dep.id] = dep.file;
	// console.log('\n> Module', dep.id, ':', moduleVarName);

	//replace `exports` & `module.exports` in code with `newName`
	//stupid regex replacers are the way faster and simpler than esprima for that goal
	src = src.replace(/\bmodule\.exports/g, moduleVarName);
	src = src.replace(/\bmodule\b\[\s*['"]exports['"]\s*\]/g, moduleVarName);
	src = src.replace(/\bexports\b/g, moduleVarName);

	//replace all `module` calls with an empty object
	//FIXME: ensure this is right
	src = src.replace(/\bmodule\b/g, '{}');

	//resolve require calls (insert module paths instead of module names)
	//FIXME: what about runtime/calculated require calls?
	src = src.replace(requireRe, function(requireStr, moduleName, idx, fullSrc){
		try {
			moduleName = resolve.sync(moduleName, {
				basedir: dir
			});
		} catch (e) {

		}

		return 'require(\'' + moduleName.replace(/\\/g, '/') + '\')';
	});
	// console.log(src)

	//Resolve global modules variables conflict - analyze scopes
	var ast = esprima.parse(src);

	//optimistic flag causes getting references for variables (places where they’re met)
	var moduleVars = escope.analyze(ast, {optimistic: true}).scopes[0].variables;

	//rename conflicting first-level vars
	//its first-level vars declared within a module, not the global-scope vars
	moduleVars.forEach(function(item){

		if (globalVariables[item.name]) {
			//rename variable
			var newName = moduleVarName + '_' + item.name;

			//replace each occurence
			item.references.forEach(function(ref){
				ref.identifier.name = newName;
			});

			//as well as a definition
			item.identifiers.forEach(function(ident){
				ident.name = newName;
			});
		} else {
			//reserve var name
			globalVariables[item.name] = item.name;
		}
	});

	//rebuild source
	//FIXME: include comments
	//FIXME: include source map optionally
	dep.source = escodegen.generate(ast);

	return dep;
}

//extend slugifier charmap (replace . and - in paths with $ and _ in code)
slug.charmap['.'] = '$';
slug.charmap['-'] = '_';

/**
 * Name variable based on module id
 */
//TODO: fuck all this stuff. Get rid of fucking name resolving via path. Use natural module names which should be available in deps resolver.
function getModuleVarName(dep){
	var name;

	//path to module
	var modulePath;

	var idx = dep.file.lastIndexOf('node_modules');

	//catch path to dep after the last node_modules dirname, if any
	if (idx >= 0){
		var path = dep.file.slice(idx);
		var matchResult = /node_modules[\/\\](.+)/.exec(path);
		modulePath = matchResult[1];
	}

	//if no node_modules in path and dep is entry - get last dir as module path
	else if (dep.entry) {
		var matchResult = /([^\/\\]+)[\/\\][^\/\\]+$/.exec(dep.file);
		modulePath = matchResult[1];
	}

	//try to take dirname before index.js, if dep is an entry
	if (modulePath)	{
		//shorten index.js
		if (/[\\\/]index.js$/.test(modulePath)) name = modulePath.slice(0, -9);
		else name = modulePath;
	}

	//else take id as a name
	if (!name) name = dep.id;

	name = slug(name).toLowerCase();

	//get rid of .js postfix
	if (name.slice(-3) === '.js') name = name.slice(0,-3);

	return options.prefix + name;
}<commit_msg>Normalize modules sorting algorithm<commit_after>//TODO: simple -r provider to get nice test bundles via require global.

//TODO Standalone compilation with no module checking: window.Name = module (use case - weakset);
//TODO Concat stdin
//TODO wrap final result into simple closure to provide closurecompiler scope

//TODO tests
//TODO pass module prefix
//TODO debug mode
//TODO cut comments
//TODO exclude files
//TODO externs - list of global reserved words
//TODO humanized output
//TODO same options as browserify, especially -r

//FIXME provide require function at the top for runtime calculations

var util = require('util');
var map = require('map-stream');
var fs = require('fs');
var slug = require('slug');
var path = require('path');
var concat = require('concat-stream');
var esprima = require('esprima');
var escodegen = require('escodegen');
var escope = require('escope');
var resolve = require('resolve');
var browserify = require('browserify');

/** processing options */
var options = {
	/** Prefix for module global vars */
	prefix: '_m_'
};

/**
 * @module uncommonjs
 *
 * @param {Array|Stream} arg Whether list of files or stdin stream
 *
 * @return {[type]} [description]
 */
module.exports = function(arg, opts, cb){
	//TODO: extend self options with external opts passed

	var b = browserify(arg, opts);

	var bundle, result;

	b.on('error', function(a,b,c){
		throw Error(a,b,c);
	});

	//start pipeline
	b.pipeline.get('dedupe')

	//prepare each module
	.pipe(
		map(
			function(dep, done){
				processModule(dep);
				done(null, dep);
			})
		)

	//form result
	.pipe(
		concat(
			function(list){
				result = processResult(list);

				if (opts.wrap) {
					result = opts.wrap.replace('%output%', result);
				}

				bundle.emit('success', result);
			}
		)
	);

	//Start browserify (bundle)
	bundle = b.bundle();

	return bundle;
};

/** global variables aliases dict: 'var1: var1, var2: var2alias' */
var globalVariables = {};

/** module variable names and aliases keyed by module ids */
var moduleVariableName = {};

/** cache of module paths keyed by ids */
var modulePath = {};

/**
 * catch `require` in code (too bad, I know, but the fastest relative to esprima)
 * Note that require accepts simple numbers also
 */
var requireRe = /require\(\s*['"]([^'")]*)['"]\s*\)/g;

/**
 * Process resulted module dep list once it’s formed
 *
 * @param {array} list A list of module deps
 *
 * @return {[type]} [description]
 */
function processResult(list){
	//sort deps to include innermost first

	//dupes aliases
	var dupes={},

	//dict of items by ids
		items={};

	//filter list of deps
	list = list

	//remove duplicates
	.filter(function(item){
		//create dict of modules by ids
		items[item.id] = item;

		//dedupe found by browserify
		if (item.dedupe) {
			dupes[item.id] = item.dedupeIndex;
			return false;
		}

		return true;
	});

	//calc weights
	list.forEach(calcWeight);

	//sort items by weights
	list.sort(function(a, b){
		return a.weight > b.weight ? 1 : -1;
	});

	//calc dep weight for the item
	function calcWeight(item){
		if (item.weight) return item.weight;
		var w = 1;
		for (var name in item.deps) {
			w += calcWeight(items[item.deps[name]]);
		}
		item.weight = w;
		return w;
	}

	// list.forEach(function(item){
	// 	item.source = item.source.slice(0,30) + '... ' + item.source.length;
	// });
	// console.log(list)
	// console.log('concat:\n',util.inspect(list, {colors:true}));

	//declare all var module names beforehead
	//in order to not get accessed undeclared
	var declStr = '/**\n * Modules declarations\n */\n';
	declStr += 'var ';
	list.forEach(function(item){
		declStr += item.name + ', ';
	});
	declStr = declStr.slice(0, -2) + ';\n';

	//concat sources in the proper order of declaration
	var result = declStr;
	list.forEach(function(dep){
		result += '\n\n\n/**\n * @module ' + moduleVariableName[dep.id] + '\n * @file ' + modulePath[dep.id] + ' \n */\n\n';
		result += dep.source + '\n';
	});

	//replace require calls
	result = result.replace(requireRe, function(requireStr, modPath, idx, fullSrc){
		var modName;

		//get module name from cached paths
		if (modulePath[modPath]) modName = modulePath[modPath];

		//resolve unresolved module
		else modName = resolve.sync(modPath);

		//replace require with var name
		if (moduleVariableName[modName]) {
			return moduleVariableName[modName];
		}

		throw Error('Module to require isn’t found: `' + modName + '`');
	});

	//if there are runtime requires left
	//append `require` function returning found modules' if any
	//TODO
	// if (/\brequire\b/.test(result)) {
	// 	result =
	// 	(function require(name){
	// 		return m[name];
	// 	}).toSource() + '\n'
	// 	+ result;
	// }

	//for each standalone passed, create global unadvancedoptimizable var

	//for each require passed, create an entry in require set

	return result;
}

/**
 * Process a separate module
 *
 * @param {object} dep A dependency object (module info)
 *
 * @return {object} The dep with rebuilt `source` property
 */
function processModule(dep){
	// console.log('---------dep:\n',util.inspect(dep, {colors:true}));
	var dir = path.dirname(dep.file);
	var src = dep.source;

	//get module var name
	var moduleVarName = getModuleVarName(dep);

	//save module name to declare it beforehead as a first-class var
	dep.name = moduleVarName;
	moduleVariableName[dep.id] = moduleVarName;
	moduleVariableName[dep.file] = moduleVarName;
	modulePath[dep.id] = dep.file;
	// console.log('\n> Module', dep.id, ':', moduleVarName);

	//replace `exports` & `module.exports` in code with `newName`
	//stupid regex replacers are the way faster and simpler than esprima for that goal
	src = src.replace(/\bmodule\.exports/g, moduleVarName);
	src = src.replace(/\bmodule\b\[\s*['"]exports['"]\s*\]/g, moduleVarName);
	src = src.replace(/\bexports\b/g, moduleVarName);

	//replace all `module` calls with an empty object
	//FIXME: ensure this is right
	src = src.replace(/\bmodule\b/g, '{}');

	//resolve require calls (insert module paths instead of module names)
	//FIXME: what about runtime/calculated require calls?
	src = src.replace(requireRe, function(requireStr, moduleName, idx, fullSrc){
		try {
			moduleName = resolve.sync(moduleName, {
				basedir: dir
			});
		} catch (e) {

		}

		return 'require(\'' + moduleName.replace(/\\/g, '/') + '\')';
	});
	// console.log(src)

	//Resolve global modules variables conflict - analyze scopes
	var ast = esprima.parse(src);

	//optimistic flag causes getting references for variables (places where they’re met)
	var moduleVars = escope.analyze(ast, {optimistic: true}).scopes[0].variables;

	//rename conflicting first-level vars
	//its first-level vars declared within a module, not the global-scope vars
	moduleVars.forEach(function(item){

		if (globalVariables[item.name]) {
			//rename variable
			var newName = moduleVarName + '_' + item.name;

			//replace each occurence
			item.references.forEach(function(ref){
				ref.identifier.name = newName;
			});

			//as well as a definition
			item.identifiers.forEach(function(ident){
				ident.name = newName;
			});
		} else {
			//reserve var name
			globalVariables[item.name] = item.name;
		}
	});

	//rebuild source
	//FIXME: include comments
	//FIXME: include source map optionally
	dep.source = escodegen.generate(ast);

	return dep;
}

//extend slugifier charmap (replace . and - in paths with $ and _ in code)
slug.charmap['.'] = '$';
slug.charmap['-'] = '_';

/**
 * Name variable based on module id
 */
//TODO: fuck all this stuff. Get rid of fucking name resolving via path. Use natural module names which should be available in deps resolver.
function getModuleVarName(dep){
	var name;

	//path to module
	var modulePath;

	var idx = dep.file.lastIndexOf('node_modules');

	//catch path to dep after the last node_modules dirname, if any
	if (idx >= 0){
		var path = dep.file.slice(idx);
		var matchResult = /node_modules[\/\\](.+)/.exec(path);
		modulePath = matchResult[1];
	}

	//if no node_modules in path and dep is entry - get last dir as module path
	else if (dep.entry) {
		var matchResult = /([^\/\\]+)[\/\\][^\/\\]+$/.exec(dep.file);
		modulePath = matchResult[1];
	}

	//try to take dirname before index.js, if dep is an entry
	if (modulePath)	{
		//shorten index.js
		if (/[\\\/]index.js$/.test(modulePath)) name = modulePath.slice(0, -9);
		else name = modulePath;
	}

	//else take id as a name
	if (!name) name = dep.id;

	name = slug(name).toLowerCase();

	//get rid of .js postfix
	if (name.slice(-3) === '.js') name = name.slice(0,-3);

	return options.prefix + name;
}<|endoftext|>


<commit_before>module.exports = {
    extends: [
        'eslint-config-airbnb-base',
    ].map(require.resolve),
    rules: {
        indent: [2, 4],
        camelcase: 0,
        yoda: [2, 'always'],
        'key-spacing': [2, {
            singleLine: {
                beforeColon: false,
                afterColon:  true
            },
            multiLine: {
                beforeColon: false,
                afterColon:  true,
                mode: 'minimum'
            }
        }],
        'func-names': 0,
        'class-methods-use-this': 0,
        'import/no-unresolved': 0,
        'import/extensions': 0,
        'react/jsx-indent': [2, 4],
        'react/jsx-indent-props': [2, 4],
        'react/forbid-prop-types': 0,
        'no-unused-vars': [2, {'varsIgnorePattern': '_+'}],
        'react/prefer-stateless-function': [2, { ignorePureComponents: true }],
        'import/no-extraneous-dependencies': [0, { devDependencies: true }],
        'space-before-function-paren': ['error', 'never'],
        'no-multi-spaces': [2, {
            exceptions: {
                Identifier: true,
                ClassProperty: true,
                ImportDeclaration: true,
                VariableDeclarator: true,
                AssignmentExpression: true,
            },
        }],
    },
    globals: {
        fetch: false
    },
    plugins: [
        'react',
        'jsx-a11y',
        'import',
    ],
};
<commit_msg>configure babel eslint and set jsx-uses-vars<commit_after>module.exports = {
    extends: [
        'eslint-config-airbnb-base',
    ].map(require.resolve),
    rules: {
        indent: [2, 4],
        camelcase: 0,
        yoda: [2, 'always'],
        'key-spacing': [2, {
            singleLine: {
                beforeColon: false,
                afterColon:  true
            },
            multiLine: {
                beforeColon: false,
                afterColon:  true,
                mode: 'minimum'
            }
        }],
        'func-names': 0,
        'class-methods-use-this': 0,
        'import/no-unresolved': 0,
        'import/extensions': 0,
        'react/jsx-uses-vars': [2],
        'react/jsx-indent': [2, 4],
        'react/jsx-indent-props': [2, 4],
        'react/forbid-prop-types': 0,
        'no-unused-vars': [2, {'varsIgnorePattern': '_+'}],
        'react/prefer-stateless-function': [2, { ignorePureComponents: true }],
        'import/no-extraneous-dependencies': [0, { devDependencies: true }],
        'space-before-function-paren': ['error', 'never'],
        'no-multi-spaces': [2, {
            exceptions: {
                Identifier: true,
                ClassProperty: true,
                ImportDeclaration: true,
                VariableDeclarator: true,
                AssignmentExpression: true,
            },
        }],
    },
    globals: {
        fetch: false
    },
    plugins: [
        'react',
        'jsx-a11y',
        'import',
    ],
    parser: 'babel-eslint',
    parserOptions: {
        ecmaFeatures: {
            'experimentalObjectRestSpread': true,
            'jsx': true
        },
        sourceType: 'module'
    },
    env: {
        browser: true,
        es6: true
    },
};
<|endoftext|>


<commit_before>/**
  @preserve Copyright (c) 2016 Ben Ilegbodu.
  Licensed under the MIT License (MIT).
  See: https://github.com/benmvp/url-lib.
  Adapted from the Uize.Url module, a part of the UIZE JavaScript Framework.
*/
(function(root, factory) {
    if (typeof define === 'function' && define.amd) {
        define([], factory);
    }
    else if (typeof module === 'object' && module.exports) {
        module.exports = factory();
    }
	else {
        root.urllib = factory();
    }
}(this, function() {
    'use strict';

    var hasOwnProperty = {}.hasOwnProperty,
        sacredEmptyArray = [];

    function _decode(str) {
        return str != null ? decodeURIComponent(str) : '';
    }

    function _encode(str) {
        return encodeURIComponent(str + '');
    }

    // Simplified Object.assign polyfill
    function _merge(target) {
        var output = new Object(target);

        for (var argNo = 0; ++argNo < arguments.length;) {
            var source = arguments[argNo];

            if (source) {
                for (var sourceKey in source) {
                    if (hasOwnProperty.call(source, sourceKey)) {
                        output[sourceKey] = source[sourceKey];
                    }
                }
            }
        }

        return output;
    }

    function _splitOnQuery(url, favorQuery) {
        var urlString = (url || '') + '', // default to a string & then coerce to a string
            queryPos = urlString.indexOf('?');

        // If the URL doesn't have a "?" we have to decide how we want to handle the string.
        // If favorQuery === true, then we'll assume the entire string is the query string.
        // If !favorQuery then we set the queryPos to the end of the string (meaning the
        // query string is empty)
        if (queryPos < 0 && !favorQuery) {
            queryPos = urlString.length;
        }

        return {
            urlPath: urlString.slice(0, queryPos),
            queryString: urlString.slice(queryPos + 1)
        };
    }

    /**
    * Serializes the properties of a params object to produce a URL query string.
    * @param {object|object[]} urlParams - An object (or array of objects) representing the query params to serialize
    * @returns {string} Serialized query string
    */
    function formatQuery(urlParams) {
        var urlParamPairs = [],
            paramsObj = urlParams;

        if (Array.isArray(paramsObj)) {
            paramsObj = paramsObj.length < 2
                ? paramsObj[0]
                : _merge.apply(null, paramsObj);
        }

        for (var paramName in paramsObj) {
            if (paramName) {
                var paramValue = paramsObj[paramName];

                if (paramValue != null) {
                    urlParamPairs.push(_encode(paramName) + '=' + _encode(paramValue));
                }
            }
        }

        return urlParamPairs.join('&');
    }

    /**
    * Parses query parameters from a string, returning the query parameters as an object.
    * @param {string} strToParse - The string from which to parse query parameters
    * @param {boolean} [favorQuery=true] - Whether or not to treat the full string to parse as query parameters when it doesn't have "?" in it
    * @returns {object} Parsed query parameters
    */
    function parseQuery(strToParse, favorQuery) {
        var urlParams = {},

            // Ensure that all we parse is a query string
            queryString = _splitOnQuery(
                strToParse,
                favorQuery !== false
            ).queryString;

        if (queryString) {
            var urlParamPairs = queryString.split('&'),
                urlParamPairsLength = urlParamPairs.length;

            // Loop through all of the pairs and add to urlParams the decoded name & value
            for (var urlParamPairNo = -1; ++urlParamPairNo < urlParamPairsLength;) {
                var urlParamPair = urlParamPairs[urlParamPairNo].split('=');
                var urlParamNameEncoded = urlParamPair[0];

                if (urlParamNameEncoded) {
                    urlParams[_decode(urlParamNameEncoded)] = _decode(urlParamPair[1]);
                }
            }
        }

        return urlParams;
    }

    /**
    * Serializes the specified URL path with properties of a params object to produce a URL.
    * @param {string | array} urlPath - Base URL path
    * @param {object | object[]} urlParams - Query params to combine with base URL
    * @returns {string} Serialized URL
    */
    function formatUrl(urlPath, urlParams) {
        var formattedUrl = urlPath,
            queryParams = urlParams,
            parsedQueryParamsFromUrl,
            normalizedQueryParams,
            queryString;

        // if they passed an array as the first parameter, separate out the first
        // element (url) from the other elements (query params list)
        if (Array.isArray(formattedUrl)) {
            queryParams = formattedUrl.slice(1).concat(queryParams || sacredEmptyArray);
            formattedUrl = formattedUrl[0];
        }

        // Pull out any query params from the URL
        parsedQueryParamsFromUrl = parseQuery(formattedUrl, false);

        // Convert the query params into an array (if it already isn't)
        normalizedQueryParams = Array.isArray(queryParams) ? queryParams : [queryParams];

        // Merge the URL query params to the additional query params
        queryParams = [parsedQueryParamsFromUrl].concat(normalizedQueryParams);

        // Serialize the query params to a query string
        queryString = formatQuery(queryParams);

        // Finally build the URL by stripping out any query string from the URL and
        // appending the query string
        return _splitOnQuery(formattedUrl).urlPath
            + (queryString ? '?' : '')
            + queryString;
    }

    return {
        parseQuery: parseQuery,
        formatUrl: formatUrl,
        formatQuery: formatQuery
    };
}));
<commit_msg>Fix UMD script<commit_after>/**
  @preserve Copyright (c) 2016 Ben Ilegbodu.
  Licensed under the MIT License (MIT).
  See: https://github.com/benmvp/url-lib.
  Adapted from the Uize.Url module, a part of the UIZE JavaScript Framework.
*/
(function(global, factory) {
    if (typeof define === 'function' && define.amd) {
        define(factory);
    }
    else if (typeof module === 'object' && module.exports) {
        module.exports = factory();
    }
	else {
        global.urllib = factory();
    }
}(this, function() {
    'use strict';

    var hasOwnProperty = {}.hasOwnProperty,
        sacredEmptyArray = [];

    function _decode(str) {
        return str != null ? decodeURIComponent(str) : '';
    }

    function _encode(str) {
        return encodeURIComponent(str + '');
    }

    // Simplified Object.assign polyfill
    function _merge(target) {
        var output = new Object(target);

        for (var argNo = 0; ++argNo < arguments.length;) {
            var source = arguments[argNo];

            if (source) {
                for (var sourceKey in source) {
                    if (hasOwnProperty.call(source, sourceKey)) {
                        output[sourceKey] = source[sourceKey];
                    }
                }
            }
        }

        return output;
    }

    function _splitOnQuery(url, favorQuery) {
        var urlString = (url || '') + '', // default to a string & then coerce to a string
            queryPos = urlString.indexOf('?');

        // If the URL doesn't have a "?" we have to decide how we want to handle the string.
        // If favorQuery === true, then we'll assume the entire string is the query string.
        // If !favorQuery then we set the queryPos to the end of the string (meaning the
        // query string is empty)
        if (queryPos < 0 && !favorQuery) {
            queryPos = urlString.length;
        }

        return {
            urlPath: urlString.slice(0, queryPos),
            queryString: urlString.slice(queryPos + 1)
        };
    }

    /**
    * Serializes the properties of a params object to produce a URL query string.
    * @param {object|object[]} urlParams - An object (or array of objects) representing the query params to serialize
    * @returns {string} Serialized query string
    */
    function formatQuery(urlParams) {
        var urlParamPairs = [],
            paramsObj = urlParams;

        if (Array.isArray(paramsObj)) {
            paramsObj = paramsObj.length < 2
                ? paramsObj[0]
                : _merge.apply(null, paramsObj);
        }

        for (var paramName in paramsObj) {
            if (paramName) {
                var paramValue = paramsObj[paramName];

                if (paramValue != null) {
                    urlParamPairs.push(_encode(paramName) + '=' + _encode(paramValue));
                }
            }
        }

        return urlParamPairs.join('&');
    }

    /**
    * Parses query parameters from a string, returning the query parameters as an object.
    * @param {string} strToParse - The string from which to parse query parameters
    * @param {boolean} [favorQuery=true] - Whether or not to treat the full string to parse as query parameters when it doesn't have "?" in it
    * @returns {object} Parsed query parameters
    */
    function parseQuery(strToParse, favorQuery) {
        var urlParams = {},

            // Ensure that all we parse is a query string
            queryString = _splitOnQuery(
                strToParse,
                favorQuery !== false
            ).queryString;

        if (queryString) {
            var urlParamPairs = queryString.split('&'),
                urlParamPairsLength = urlParamPairs.length;

            // Loop through all of the pairs and add to urlParams the decoded name & value
            for (var urlParamPairNo = -1; ++urlParamPairNo < urlParamPairsLength;) {
                var urlParamPair = urlParamPairs[urlParamPairNo].split('=');
                var urlParamNameEncoded = urlParamPair[0];

                if (urlParamNameEncoded) {
                    urlParams[_decode(urlParamNameEncoded)] = _decode(urlParamPair[1]);
                }
            }
        }

        return urlParams;
    }

    /**
    * Serializes the specified URL path with properties of a params object to produce a URL.
    * @param {string | array} urlPath - Base URL path
    * @param {object | object[]} urlParams - Query params to combine with base URL
    * @returns {string} Serialized URL
    */
    function formatUrl(urlPath, urlParams) {
        var formattedUrl = urlPath,
            queryParams = urlParams,
            parsedQueryParamsFromUrl,
            normalizedQueryParams,
            queryString;

        // if they passed an array as the first parameter, separate out the first
        // element (url) from the other elements (query params list)
        if (Array.isArray(formattedUrl)) {
            queryParams = formattedUrl.slice(1).concat(queryParams || sacredEmptyArray);
            formattedUrl = formattedUrl[0];
        }

        // Pull out any query params from the URL
        parsedQueryParamsFromUrl = parseQuery(formattedUrl, false);

        // Convert the query params into an array (if it already isn't)
        normalizedQueryParams = Array.isArray(queryParams) ? queryParams : [queryParams];

        // Merge the URL query params to the additional query params
        queryParams = [parsedQueryParamsFromUrl].concat(normalizedQueryParams);

        // Serialize the query params to a query string
        queryString = formatQuery(queryParams);

        // Finally build the URL by stripping out any query string from the URL and
        // appending the query string
        return _splitOnQuery(formattedUrl).urlPath
            + (queryString ? '?' : '')
            + queryString;
    }

    return {
        parseQuery: parseQuery,
        formatUrl: formatUrl,
        formatQuery: formatQuery
    };
}));
<|endoftext|>


<commit_before>'use strict';

// Exports a train singleton
var db = require('./extension/db');
var Q = require('q');
var extend = require('extend');
var fs = require('fs');
var log = require('../../lib/logger');
var nodecg = {};

function Train(extensionApi) {
    if (Train.prototype._singletonInstance) {
        return Train.prototype._singletonInstance;
    }
    Train.prototype._singletonInstance = this;

    nodecg = extensionApi;
    var self = this;

    // These properties are transient and are not persisted in the DB
    nodecg.declareSyncedVar({ variableName: 'elapsedTime', initialVal: 0 });
    nodecg.declareSyncedVar({ variableName: 'remainingTime', initialVal: 0 });
    nodecg.declareSyncedVar({ variableName: 'isCooldownActive', initialVal: false });

    this._timer = null;

    // Set up options
    this.options = require('./extension/config');
    Object.freeze(this.options);

    this.init()
        .then(function(train) {
            nodecg.declareSyncedVar({ variableName: 'passengers',
                initialVal: train.passengers,
                setter: function(newVal) {
                    self.write({passengers: newVal});
                }
            });
            nodecg.declareSyncedVar({ variableName: 'dayTotal',
                initialVal: train.dayTotal,
                setter: function(newVal) {
                    self.write({dayTotal: newVal});
                }
            });
            nodecg.declareSyncedVar({ variableName: 'threshold',
                initialVal: train.threshold,
                setter: function(newVal) {
                    self.write({threshold: newVal});
                }
            });
            nodecg.declareSyncedVar({ variableName: 'duration',
                initialVal: train.duration,
                setter: function(newVal) {
                    self.write({duration: newVal});
                }
            });
        })
        .fail(function(err) {
            throw err;
        });

    nodecg.listenFor('startCooldown', this.startCooldown.bind(this));
    nodecg.listenFor('endCooldown', this.endCooldown.bind(this));
    nodecg.listenFor('resetCooldown', this.resetCooldown.bind(this));

    // temporary workaround for some bundles until I figure out how to make this better
    nodecg.listenFor('getPassengers', function(data, cb) {
        cb(nodecg.variables.passengers);
    });
    nodecg.listenFor('getDayTotal', function(data, cb) {
        cb(nodecg.variables.dayTotal);
    });
}

Train.prototype.init = function() {
    var deferred = Q.defer();
    db.findOne({ _id: 'train' }, function (err, doc) {
        if (err) {
            deferred.reject(new Error(err));
        } else if (doc === null) {
            // If the train isn't in the DB, make a new one with defaults
            var defaultTrain = {
                _id: 'train',
                passengers: 0,
                dayTotal: 0,
                threshold: 10,
                duration: 300
            };

            db.insert(defaultTrain, function (err, newDoc) {
                if (err) {
                    deferred.reject(new Error(err));
                } else {
                    deferred.resolve(newDoc);
                }
            });
        } else {
            // Else, return the train already present in the DB
            deferred.resolve(doc);
        }
    });
    return deferred.promise;
};

// Allows for setting any or all of the properties.
Train.prototype.write = function(args) {
    db.update({ _id: 'train' }, { $set: args }, { upsert: true }, function (err, numAdded) {
        if (err)
            log.error(err.stack);
    });
};

Train.prototype.startCooldown = function () {
    this._killTimer(); // Kill any existing cooldown timer

    nodecg.variables.elapsedTime = 0;
    nodecg.variables.remainingTime = nodecg.variables.duration;
    nodecg.variables.isCooldownActive = true;
    this._timer = setInterval(this.tickCooldown.bind(this), 1000);

    nodecg.sendMessage('cooldownStart');
};

Train.prototype.tickCooldown = function() {
    nodecg.variables.elapsedTime++;
    nodecg.variables.remainingTime--;

    if (nodecg.variables.remainingTime <= 0) {
        nodecg.variables.remainingTime = 0; // force to zero if we somehow went negative
        this.endCooldown();
    }
};

Train.prototype.resetCooldown = function() {
    nodecg.variables.elapsedTime = 0;
    nodecg.variables.remainingTime = nodecg.variables.duration;
};

Train.prototype.endCooldown = function() {
    this._killTimer();
    nodecg.variables.passengers = 0;
    nodecg.variables.isCooldownActive = false;
    nodecg.sendMessage('cooldownEnd');
};

Train.prototype._killTimer = function () {
    if (this._timer !== null) {
        clearInterval(this._timer);
        this._timer = null;
    }
};

Train.prototype.addPassenger = function() {
    nodecg.variables.passengers++;
    nodecg.variables.dayTotal++;

    if (this.options.autoStartCooldown)
        this.startCooldown();

    var train = nodecg.variables;
    train.isHype = train.passengers >= train.threshold;

    if (train.isHype && this.options.resetAfterThreshold) {
        nodecg.variables.passengers = 0;
        this.endCooldown();
    }

    return train;
};

module.exports = function(extensionApi) { return new Train(extensionApi) };<commit_msg>make sure cooldown ends when threshold is passed if resetAfterThreshold is true<commit_after>'use strict';

// Exports a train singleton
var db = require('./extension/db');
var Q = require('q');
var extend = require('extend');
var fs = require('fs');
var log = require('../../lib/logger');
var nodecg = {};

function Train(extensionApi) {
    if (Train.prototype._singletonInstance) {
        return Train.prototype._singletonInstance;
    }
    Train.prototype._singletonInstance = this;

    nodecg = extensionApi;
    var self = this;

    // These properties are transient and are not persisted in the DB
    nodecg.declareSyncedVar({ variableName: 'elapsedTime', initialVal: 0 });
    nodecg.declareSyncedVar({ variableName: 'remainingTime', initialVal: 0 });
    nodecg.declareSyncedVar({ variableName: 'isCooldownActive', initialVal: false });

    this._timer = null;

    // Set up options
    this.options = require('./extension/config');
    Object.freeze(this.options);

    this.init()
        .then(function(train) {
            nodecg.declareSyncedVar({ variableName: 'passengers',
                initialVal: train.passengers,
                setter: function(newVal) {
                    self.write({passengers: newVal});
                }
            });
            nodecg.declareSyncedVar({ variableName: 'dayTotal',
                initialVal: train.dayTotal,
                setter: function(newVal) {
                    self.write({dayTotal: newVal});
                }
            });
            nodecg.declareSyncedVar({ variableName: 'threshold',
                initialVal: train.threshold,
                setter: function(newVal) {
                    self.write({threshold: newVal});
                }
            });
            nodecg.declareSyncedVar({ variableName: 'duration',
                initialVal: train.duration,
                setter: function(newVal) {
                    self.write({duration: newVal});
                }
            });
        })
        .fail(function(err) {
            throw err;
        });

    nodecg.listenFor('startCooldown', this.startCooldown.bind(this));
    nodecg.listenFor('endCooldown', this.endCooldown.bind(this));
    nodecg.listenFor('resetCooldown', this.resetCooldown.bind(this));

    // temporary workaround for some bundles until I figure out how to make this better
    nodecg.listenFor('getPassengers', function(data, cb) {
        cb(nodecg.variables.passengers);
    });
    nodecg.listenFor('getDayTotal', function(data, cb) {
        cb(nodecg.variables.dayTotal);
    });
}

Train.prototype.init = function() {
    var deferred = Q.defer();
    db.findOne({ _id: 'train' }, function (err, doc) {
        if (err) {
            deferred.reject(new Error(err));
        } else if (doc === null) {
            // If the train isn't in the DB, make a new one with defaults
            var defaultTrain = {
                _id: 'train',
                passengers: 0,
                dayTotal: 0,
                threshold: 10,
                duration: 300
            };

            db.insert(defaultTrain, function (err, newDoc) {
                if (err) {
                    deferred.reject(new Error(err));
                } else {
                    deferred.resolve(newDoc);
                }
            });
        } else {
            // Else, return the train already present in the DB
            deferred.resolve(doc);
        }
    });
    return deferred.promise;
};

// Allows for setting any or all of the properties.
Train.prototype.write = function(args) {
    db.update({ _id: 'train' }, { $set: args }, { upsert: true }, function (err, numAdded) {
        if (err)
            log.error(err.stack);
    });
};

Train.prototype.startCooldown = function () {
    this._killTimer(); // Kill any existing cooldown timer

    nodecg.variables.elapsedTime = 0;
    nodecg.variables.remainingTime = nodecg.variables.duration;
    nodecg.variables.isCooldownActive = true;
    this._timer = setInterval(this.tickCooldown.bind(this), 1000);

    nodecg.sendMessage('cooldownStart');
};

Train.prototype.tickCooldown = function() {
    nodecg.variables.elapsedTime++;
    nodecg.variables.remainingTime--;

    if (nodecg.variables.remainingTime <= 0) {
        nodecg.variables.remainingTime = 0; // force to zero if we somehow went negative
        this.endCooldown();
    }
};

Train.prototype.resetCooldown = function() {
    nodecg.variables.elapsedTime = 0;
    nodecg.variables.remainingTime = nodecg.variables.duration;
};

Train.prototype.endCooldown = function() {
    this._killTimer();
    nodecg.variables.passengers = 0;
    nodecg.variables.isCooldownActive = false;
    nodecg.sendMessage('cooldownEnd');
};

Train.prototype._killTimer = function () {
    if (this._timer !== null) {
        clearInterval(this._timer);
        this._timer = null;
    }
};

Train.prototype.addPassenger = function() {
    nodecg.variables.passengers++;
    nodecg.variables.dayTotal++;

    var train = nodecg.variables;
    train.isHype = train.passengers >= train.threshold;

    if (train.isHype && this.options.resetAfterThreshold) {
        nodecg.variables.passengers = 0;
        this.endCooldown();
    } else if (this.options.autoStartCooldown) {
        this.startCooldown();
    }

    return train;
};

module.exports = function(extensionApi) { return new Train(extensionApi) };<|endoftext|>


<commit_before>var path = require('path')
var fs = require('fs')
var mkdirp = require('mkdirp')

// Init the steamer namespace.
var steamer = {
  "broccoli" : {},
  "sourceTrees" : [],
  "trees" : [],
  "init" : {},
  "dir" : {},
  "css" : {},
  "img" : {},
  "js" : {},
  "steam" : null
};
module.exports = steamer

// Require other broccoli modules
steamer.broccoli.sass = require('broccoli-sass')
steamer.broccoli.imagemin = require('broccoli-imagemin')
steamer.broccoli.CachingWriter = require('broccoli-caching-writer')
steamer.broccoli.Filter = require('broccoli-filter')
var pickFiles = require('broccoli-static-compiler')
var findBowerTrees = require('broccoli-bower')
var cleancss = require('broccoli-clean-css')
var base64CSS = require('broccoli-base64-css');
var uglifyJavaScript = require('broccoli-uglify-js')
var compileES6 = require('broccoli-es6-concatenator')
var env = require('broccoli-env').getEnv()
var mergeTrees = require('broccoli-merge-trees')

// UNUSED projects
// var concat = require('broccoli-concat')
// var morecss = require('broccoli-more-css')

var helper = {};
helper.getAnnotations = function(content, tag) {
  var ret = []
  var found = content.split('@' + tag).forEach(function(v, i) {
    if (i == 0) {
      return
    }
    v = v.trim()
    if (v.substr(0,1) == '"') {
      // @todo Add support for escape chars
      v = v.split('"').shift();
    }
    else {
      v = v.split(/\s/).shift()
    }
    ret.push(v)
  });

  return ret
};

steamer.steam = function() {
  return mergeTrees(steamer.trees, { overwrite: true })
};
steamer.init.bower = function() {
  steamer.sourceTrees = steamer.sourceTrees.concat(findBowerTrees())
  return this
};
steamer.init.dir = function(inputDir, outputDir) {
  steamer.sourceTrees.push(
    pickFiles(inputDir, {
      srcDir: '/',
      destDir: outputDir
    })
  );
  return this
};
steamer.init.path = function(inputDir) {
  steamer.sourceTrees.push(inputDir)
  return this
};
steamer.init.done = function() {
  steamer.sourceTrees = new mergeTrees(steamer.sourceTrees, { overwrite: true })
  return steamer
};

steamer.dir.copy = function(inputDir, outputDir) {
  steamer.trees.push(
    pickFiles(inputDir, {
      srcDir: '/',
      destDir: outputDir
    })
  );
  return this
};

/**
 * Compile SASS to CSS
 */
steamer.css.sass = function(inputFile, outputFile) {
  var ALLOW_SOURCEMAPS = false
  //Also supports imagePath, precision
  //https://github.com/joliss/broccoli-sass
  var css = steamer.broccoli.sass([steamer.sourceTrees], inputFile, outputFile, {
    "sourceComments":false,
    "outputStyle":"compressed",
    "sourceMap":(ALLOW_SOURCEMAPS && env != 'production')
  })
  if (!ALLOW_SOURCEMAPS || env != 'production') {
    // Minify and process imports.
    css = cleancss(css, {
      "relativeTo":"2015"
    })
    // Convert small images to base64 URLs
    css = base64CSS(css, {
      imagePath: '.',
      fontPath: '.',
      maxFileSize: 4096,
      extensions: ['css'],
      fileTypes: ['png', 'jpg', 'jpeg', 'gif', 'svg'],
      assetsFromTree: false
    });
    // Minify again (with a different engine) to remove comments from imports
    // WARNING: morecss breaks the @media queries.
    // css = morecss(css)
  }
  steamer.trees.push(css)
  return this
};

/**
 * Optimize and copy image assets from one folder to another.
 */
steamer.img.copy = function (inputFolder, outputFolder) {
  var image_options = {
    interlaced: true,
    optimizationLevel: 3,
    progressive: true,
    lossyPNG: false
  };
  var imageTree = pickFiles(inputFolder, {
    //    files: ['**/*'],
    srcDir: '/',
    destDir: outputFolder
  })
  imageTree = steamer.broccoli.imagemin(imageTree, image_options)
  steamer.trees.push(imageTree)
  return this
};

/**
 * Compile a single JS file.
 * Supports @steamer.prepend
 */
steamer.js.compile = function(inputFile, outputFile) {
  var content = fs.readFileSync(inputFile) + ""
  var prepends = helper.getAnnotations(content, 'steamer.prepend');
  prepends.push(inputFile)
  return steamer.js.combine(prepends, outputFile)
}

/**
 * Combine multiple JS files into a single output file.
 */
steamer.js.combine = function (inputFiles, outputFile) {
  if (typeof inputFiles == 'string') {
    inputFiles = [inputFiles]
  }

  var defs = {
    DEBUG : (env == "development")
  };
  inputFiles.forEach(function(inputFile){
    try {
      var data = fs.readFileSync(inputFile) + "";
      console.log(inputFile + ", length: "  + data.length);
      data.split('@define ').forEach(function(c, i) {
        if (!i) return;
        var found = c.match(/^([^= ]*) = ([^;]*);/);
        if (typeof found == 'object') {
          defs[found[1]] = JSON.parse(found[2]);
        }
      });
    } catch (err) {
      if (err.message.indexOf('ENOENT') == -1) {
        console.log("  ERROR: " + err.message);
      }
    }
  });
  console.log(outputFile + " constants = " + JSON.stringify(defs));

  // Create the tree.
  var js = null;

  //Combine and minimize JS.
  //https://github.com/joliss/broccoli-es6-concatenator
  js = compileES6(steamer.sourceTrees, {
     // Prepend contents of loader.js
     // loaderFile: 'loader.js',
     ignoredModules: [
    //   'ember/resolver'
     ],
     inputFiles: [
    //   'appkit/**/*.js'
     ],
     legacyFilesToAppend: inputFiles,
     wrapInEval: false,
     outputFile: outputFile
  })
  js = uglifyJavaScript(js, {
   mangle: true,
   compress: {
     // http://lisperator.net/uglifyjs/compress
     // "hoist_funs": false, // 2015-02-17: This configuration caused a 'strict' error in Firefox
     "loops": false,
     "unused": false,
     "global_defs":defs
   },
   output: {
     // http://lisperator.net/uglifyjs/codegen
     "ascii_only": true
   }
  })

  steamer.trees.push(js)
  return this
}
<commit_msg>Add header/footer support and reorganize code.<commit_after>var path = require('path')
var fs = require('fs')
var mkdirp = require('mkdirp')

// Init the steamer namespace.
var steamer = {
  "broccoli" : {},
  "sourceTrees" : [],
  "trees" : [],
  "init" : {},
  "dir" : {},
  "css" : {},
  "img" : {},
  "js" : {},
  "steam" : null
};
module.exports = steamer

// Require other broccoli modules
steamer.broccoli.sass = require('broccoli-sass')
steamer.broccoli.imagemin = require('broccoli-imagemin')
steamer.broccoli.CachingWriter = require('broccoli-caching-writer')
steamer.broccoli.Filter = require('broccoli-filter')
var pickFiles = require('broccoli-static-compiler')
var findBowerTrees = require('broccoli-bower')
var cleancss = require('broccoli-clean-css')
var base64CSS = require('broccoli-base64-css');
var uglifyJavaScript = require('broccoli-uglify-js')
var compileES6 = require('broccoli-es6-concatenator')
var env = require('broccoli-env').getEnv()
var mergeTrees = require('broccoli-merge-trees')

// UNUSED projects
// var concat = require('broccoli-concat')
// var morecss = require('broccoli-more-css')

var helper = {};
helper.getAnnotations = function(content, tag, mode, tgt) {
  mode = mode || "default"

  // Extract a value from the front of the string.
  function getValue(v) {
    v = v.trim()
    if (v.charAt(0) == '"') {
      v = v.match(/^"((?:\\"|.)*?)"/)[0]
      v = JSON.parse(v)
    }
    else {
      v = v.split(/[\s;]/).shift()
      if (!/^[a-zA-Z]/.test(v) || /^(true|false)$/.test(v)) {
        v = JSON.parse(v)
      }
    }
    return v
  }

  var ret = []
  var found = content.split('@' + tag + ' ').forEach(function(v, i) {
    if (i == 0) {
      return
    }
    switch (mode) {
    case 'assign':
      var tmp = v.split('=', 2)
      i = tmp[0].trim()
      v = getValue(tmp[1])
      ret[i] = v
      if (typeof tgt == 'object') {
        tgt[i] = v
      }
      break
    case 'default':
    default:
      v = getValue(v)
      ret.push(v)
      break
    }
  });

  return ret
};
helper.readFileForgiving = function(path) {
  try {
    var data = fs.readFileSync(path) + ""
    return data
  } catch (err) {
    if (err.message.indexOf('ENOENT') == -1) {
      console.log("  ERROR: " + err.message);
    }
  }
  return ""
};

steamer.steam = function() {
  return mergeTrees(steamer.trees, { overwrite: true })
};
steamer.init.bower = function() {
  steamer.sourceTrees = steamer.sourceTrees.concat(findBowerTrees())
  return this
};
steamer.init.dir = function(inputDir, outputDir) {
  steamer.sourceTrees.push(
    pickFiles(inputDir, {
      srcDir: '/',
      destDir: outputDir
    })
  );
  return this
};
steamer.init.path = function(inputDir) {
  steamer.sourceTrees.push(inputDir)
  return this
};
steamer.init.done = function() {
  steamer.sourceTrees = new mergeTrees(steamer.sourceTrees, { overwrite: true })
  return steamer
};

steamer.dir.copy = function(inputDir, outputDir) {
  steamer.trees.push(
    pickFiles(inputDir, {
      srcDir: '/',
      destDir: outputDir
    })
  );
  return this
};

/**
 * Compile SASS to CSS
 */
steamer.css.sass = function(inputFile, outputFile) {
  var ALLOW_SOURCEMAPS = false
  //Also supports imagePath, precision
  //https://github.com/joliss/broccoli-sass
  var css = steamer.broccoli.sass([steamer.sourceTrees], inputFile, outputFile, {
    "sourceComments":false,
    "outputStyle":"compressed",
    "sourceMap":(ALLOW_SOURCEMAPS && env != 'production')
  })
  if (!ALLOW_SOURCEMAPS || env != 'production') {
    // Minify and process imports.
    css = cleancss(css, {
      "relativeTo":"2015"
    })
    // Convert small images to base64 URLs
    css = base64CSS(css, {
      imagePath: '.',
      fontPath: '.',
      maxFileSize: 4096,
      extensions: ['css'],
      fileTypes: ['png', 'jpg', 'jpeg', 'gif', 'svg'],
      assetsFromTree: false
    });
    // Minify again (with a different engine) to remove comments from imports
    // WARNING: morecss breaks the @media queries.
    // css = morecss(css)
  }
  steamer.trees.push(css)
  return this
};

/**
 * Optimize and copy image assets from one folder to another.
 */
steamer.img.copy = function (inputFolder, outputFolder) {
  var image_options = {
    interlaced: true,
    optimizationLevel: 3,
    progressive: true,
    lossyPNG: false
  };
  var imageTree = pickFiles(inputFolder, {
    //    files: ['**/*'],
    srcDir: '/',
    destDir: outputFolder
  })
  imageTree = steamer.broccoli.imagemin(imageTree, image_options)
  steamer.trees.push(imageTree)
  return this
};

/**
 * Compile a single JS file.
 * Supports @steamer.prepend
 */
steamer.js.compile = function(inputFile, outputFile, options) {
  options = options || {}

  // Process any prepends
  var content = fs.readFileSync(inputFile) + ""
  var prepends = helper.getAnnotations(content, 'steamer.prepend');
  prepends.push(inputFile)
  steamer.js.combine(prepends, outputFile)

  // Create the tree.
  var js = null;

  //Combine JS
  //https://github.com/joliss/broccoli-es6-concatenator
  js = compileES6(steamer.sourceTrees, {
     ignoredModules: [],
     inputFiles: [],
     legacyFilesToAppend: prepends,
     wrapInEval: false,
     outputFile: outputFile
  })

  // Extract the definitions
  var defs = {
    DEBUG : (env == "development")
  };
  prepends.forEach(function(path){
    helper.getAnnotations(helper.readFileForgiving(path), 'define', 'assign', defs)
  });
  console.log(outputFile + " constants = " + JSON.stringify(defs));

  // Process the concatenated output.
  postprocessor.prototype = Object.create(steamer.broccoli.Filter.prototype)
  postprocessor.prototype.constructor = postprocessor
  function postprocessor(inputTree, options) {
    if (!(this instanceof postprocessor)) return new postprocessor(inputTree, options)
    steamer.broccoli.Filter.call(this, inputTree, options)
    this.options = options || {}
  }
  postprocessor.prototype.extensions = ['js']
  postprocessor.prototype.targetExtension = 'js'
  postprocessor.prototype.processString = function (content, relativePath) {
    result = content
    var matches, remove;
    var cont = true
    while (cont) {
      cont = false
      // Float headers to the top
      matches = result.match(/,?steamer.header\(\s*([\"'])((?:\\\1|.)*?)\1\s*\),?/)
      if (matches) {
        remove = matches[0]
        if (remove.charAt(0) == remove.substr(-1) && remove.charAt(0) == ',') {
          remove = remove.substr(1)
        }
        result = matches[2] + result.replace(remove, "")
        cont = true
      }
      // Sink footers to the bottom
      matches = result.match(/,?steamer.footer\(\s*([\"'])((?:\\\1|.)*?)\1\s*\),?/)
      if (matches) {
        remove = matches[0]
        if (remove.charAt(0) == remove.substr(-1) && remove.charAt(0) == ',') {
          remove = remove.substr(1)
        }
        result = result.replace(remove, "") + matches[2]
        cont = true
      }
    }
    return result
  }

  // Apply the custom logic.
  js = postprocessor(js, options)

  // Uglify/minify the JS
  js = uglifyJavaScript(js, {
    mangle: true,
    compress: {
      // http://lisperator.net/uglifyjs/compress
      // "hoist_funs": false, // 2015-02-17: This configuration caused a 'strict' error in Firefox
      "loops": false,
      "unused": false,
      "global_defs":defs
    },
    output: {
      // http://lisperator.net/uglifyjs/codegen
      "ascii_only": true
    }
  })

  steamer.trees.push(js)
  return this
}

/**
 * Combine multiple JS files into a single output file.
 */
steamer.js.combine = function (inputFiles, outputFile) {
  if (typeof inputFiles == 'string') {
    inputFiles = [inputFiles]
  }

  // Extract definitions from all JS files.
  var defs = {
    DEBUG : (env == "development")
  };
  inputFiles.forEach(function(inputFile){
    helper.getAnnotations(helper.readFileForgiving(inputFile), 'define', 'assign', defs)
  });
  console.log(outputFile + " constants = " + JSON.stringify(defs));

  // Create the tree.
  var js = null;

  //Combine and minimize JS.
  //https://github.com/joliss/broccoli-es6-concatenator
  js = compileES6(steamer.sourceTrees, {
     // Prepend contents of loader.js
     // loaderFile: 'loader.js',
     ignoredModules: [
    //   'ember/resolver'
     ],
     inputFiles: [
    //   'appkit/**/*.js'
     ],
     legacyFilesToAppend: inputFiles,
     wrapInEval: false,
     outputFile: outputFile
  })
  js = uglifyJavaScript(js, {
   mangle: true,
   compress: {
     // http://lisperator.net/uglifyjs/compress
     // "hoist_funs": false, // 2015-02-17: This configuration caused a 'strict' error in Firefox
     "loops": false,
     "unused": false,
     "global_defs":defs
   },
   output: {
     // http://lisperator.net/uglifyjs/codegen
     "ascii_only": true
   }
  })

  steamer.trees.push(js)
  return this
}
<|endoftext|>


<commit_before>var express=require('express');
var path=require('path');
var request=require('request');
var http= require('http');
var compression=require('compression');
var bodyParser=require('body-parser');

process.env.NODE_ENV = 'production';

const port=9003;
const app=express();

app.use(compression());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));

app.use(express.static('./'));

app.get('/*',function(req,res){
  var response;
  console.log()
  switch (req._parsedOriginalUrl.pathname) {
    case '/performance/read':
       response = [
          {"Januari" : 12},
          {"Februari" : 6},
          {"Maret" : 4},
          {"April" : 9}
      ];break;
    case '/performance/unique_article':
      response = [
        {"Januari" : 2000},
        {"Februari" : 1670},
        {"Maret" : 1430},
        {"April" : 9000}
      ];break;
    case 'performance/video_play':
      [
        {"Januari" : 12},
        {"Februari" : 6},
        {"Maret" : 4},
        {"April" : 9}
      ];break;
    default :
      response = "Welcome To Rizki API";
  }
  var allowedOrigins = ['http://beta.ylitix.com','http://beta.ylitix.com:6969', 'http://localhost:3000'];
  var origin = req.headers.origin;
  if(allowedOrigins.indexOf(origin) > -1){
       res.setHeader('Access-Control-Allow-Origin', origin);
  }
  res.json(response)
});

app.listen(port,function(err){
  if(err){
    console.log(err);
  }
});
<commit_msg>fixing bug<commit_after>var express=require('express');
var path=require('path');
var request=require('request');
var http= require('http');
var compression=require('compression');
var bodyParser=require('body-parser');

process.env.NODE_ENV = 'production';

const port=9003;
const app=express();

app.use(compression());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));

app.use(express.static('./'));

app.get('/*',function(req,res){
  var response;
  console.log()
  switch (req._parsedOriginalUrl.pathname) {
    case '/performance/read':
       response = [
          {"Januari" : 12},
          {"Februari" : 6},
          {"Maret" : 4},
          {"April" : 9}
      ];break;
    case '/performance/unique_article':
      response = [
        {"Januari" : 2000},
        {"Februari" : 1670},
        {"Maret" : 1430},
        {"April" : 9000}
      ];break;
    case '/performance/video_play':
      response = [
        {"Januari" : 12},
        {"Februari" : 6},
        {"Maret" : 4},
        {"April" : 9}
      ];break;
    default :
      response = "Welcome To Rizki API";
  }
  var allowedOrigins = ['http://beta.ylitix.com','http://beta.ylitix.com:6969', 'http://localhost:3000'];
  var origin = req.headers.origin;
  if(allowedOrigins.indexOf(origin) > -1){
       res.setHeader('Access-Control-Allow-Origin', origin);
  }
  res.json(response)
});

app.listen(port,function(err){
  if(err){
    console.log(err);
  }
});
<|endoftext|>


<commit_before>module.exports = (function() {
  'use strict';
  var helpers = require('./utils/helpers');

  var specialActions = {
    image: function(res) {
      return 'http://lorempixel.com/' + res + '?' + ~~(Math.random()*999999);
    },
    id: function() {
      return id++;
    }
  };

  var mocks = {};
  var id = 0;
  var init = function(name, schema) {
    var parsedSchema = {};
    for (var key in schema) {
      parsedSchema[key] = parseElement(schema[key]);
    }

    mocks[name] = parsedSchema;
  };

  var parseElement = function(element) {

    var args = element.split(':');
    var name = args[0];
    args = args[1];

    if (name in specialActions) {
      return {
        fn: specialActions[name],
        args: args
      };
    } else if (name in helpers) {
      return {
        fn: helpers[name],
        args: args
      };
    } else {
      var fn = function(name) { return function() { return name; }; }(name);
      return {
        fn: fn,
        args: args
      };
    }
  };

  init.get = function(name, quantity) {
    if (typeof name === 'number') {

      quantity = name;
      name = Object.keys(mocks)[0];

    } else {

      name = name || Object.keys(mocks)[0];
      quantity = quantity || 20;

    }

    var output = [];
    var singleObject = {};
    var schema = mocks[name];

    while(quantity--) {

      singleObject = {};
      for (var key in schema) {
        singleObject[key] = schema[key].fn(schema[key].args);
      }

      output.push(singleObject);
    }

    return output;
  };

  init.getJSON = function(name, quantity) {
    return JSON.stringify(init.get(name, quantity), null, 2);
  };

  return init;
})();
<commit_msg>:izakaya_lantern: Allow subschemas<commit_after>module.exports = (function() {
  'use strict';
  var helpers = require('./utils/helpers');

  var specialActions = {
    image: function(res) {
      return 'http://lorempixel.com/' + res + '?' + ~~(Math.random()*999999);
    },
    id: function() {
      return id++;
    }
  };

  var mocks = {};
  var id = 0;
  var init = function(name, schema) {
    var parsedSchema = {};
    for (var key in schema) {
      parsedSchema[key] = parseElement(schema[key]);
    }

    mocks[name] = parsedSchema;
  };

  var parseElement = function(element) {

    if (typeof element === 'object') {
      var parsedSubschema = {};
      for (var key in element) {
        parsedSubschema[key] = parseElement(element[key]);
      }
      return parsedSubschema;
    }

    var args = element.split(':');
    var name = args[0];
    args = args[1];

    if (name in specialActions) {
      return {
        fn: specialActions[name],
        args: args
      };
    } else if (name in helpers) {
      return {
        fn: helpers[name],
        args: args
      };
    } else {
      var fn = function(name) { return function() { return name; }; }(name);
      return {
        fn: fn,
        args: args
      };
    }
  };

  init.get = function(name, quantity) {
    if (typeof name === 'number') {

      quantity = name;
      name = Object.keys(mocks)[0];

    } else {

      name = name || Object.keys(mocks)[0];
      quantity = quantity || 20;

    }

    var output = [];
    var singleObject = {};
    var schema = mocks[name];

    while(quantity--) {

      singleObject = {};
      for (var key in schema) {
        if (!schema[key].fn) {
          singleObject[key] = {};
          for (var key2 in schema[key]) {
            singleObject[key][key2] = schema[key][key2].fn(schema[key][key2].args);
          }
        } else {
          singleObject[key] = schema[key].fn(schema[key].args);
        }
      }

      output.push(singleObject);
    }

    return output;
  };

  init.getJSON = function(name, quantity) {
    return JSON.stringify(init.get(name, quantity), null, 2);
  };

  return init;
})();
<|endoftext|>


<commit_before>require('dotenv').load()

let debug = require('debug')('sync')
let local = require('./local')
let parallel = require('run-parallel')
let rpc = require('./rpc')
let zmq = require('./zmq')

// recursively calls connectBlock(id) until `bitcoind[id].next` is falsy
function connectBlock (id, callback) {
  debug(`Connecting ${id}`)

  rpc('getblockheader', [id], (err, header) => {
    if (err) return callback(err)

    local.connect(id, (err) => {
      if (err) return callback(err)

      debug(`Connected ${id}`)
      if (!header.nextblockhash) return callback()

      // recurse until next is falsy
      connectBlock(header.nextblockhash, callback)
    })
  })
}

function disconnectBlock (id, callback) {
  debug(`Disconnecting ${id}`)

  local.disconnect(id, (err) => {
    if (err) return callback(err)

    debug(`Disconnected ${id}`)
    callback()
  })
}

function sync (err, callback) {
  if (err) return callback(err)

  debug('Checking bitcoind/local chains')
  parallel({
    bitcoind: (f) => rpc('getbestblockhash', [], f),
    local: (f) => local.tip(f)
  }, (err, tips) => {
    if (err) return callback(err)

    // Step 0, genesis?
    if (!tips.local) {
      debug('genesis')
      return rpc('getblockhash', [0], (err, genesisId) => {
        if (err) return callback(err)

        connectBlock(genesisId, callback)
      })
    }

    // Step 1, equal?
    debug('tips', tips)
    if (tips.bitcoind === tips.local) return callback()

    // else, Step 2, is local behind? [bitcoind has local tip]
    rpc('getblockheader', [tips.local], (err, common) => {
      // not in bitcoind chain? [forked]
      if (
        (err && err.message === 'Block not found') ||
        (!err && common.confirmations === -1)
      ) {
        debug('local is forked')
        return disconnectBlock(tips.local, sync)
      }
      if (err) return callback(err)

      // behind
      debug('bitcoind is ahead')
      connectBlock(common.nextblockhash, callback)
    })
  })
}

zmq.on('hashblock', () => sync())
zmq.on('hashtx', (txId) => () => {
  debug(`Seen ${txId} ${Date.now()}`)
  local.see(txId)
})
<commit_msg>index: attempt sync on import<commit_after>require('dotenv').load()

let debug = require('debug')('sync')
let local = require('./local')
let parallel = require('run-parallel')
let rpc = require('./rpc')
let zmq = require('./zmq')

// recursively calls connectBlock(id) until `bitcoind[id].next` is falsy
function connectBlock (id, callback) {
  debug(`Connecting ${id}`)

  rpc('getblockheader', [id], (err, header) => {
    if (err) return callback(err)

    local.connect(id, (err) => {
      if (err) return callback(err)

      debug(`Connected ${id}`)
      if (!header.nextblockhash) return callback()

      // recurse until next is falsy
      connectBlock(header.nextblockhash, callback)
    })
  })
}

function disconnectBlock (id, callback) {
  debug(`Disconnecting ${id}`)

  local.disconnect(id, (err) => {
    if (err) return callback(err)

    debug(`Disconnected ${id}`)
    callback()
  })
}

function sync (err, callback) {
  if (err) return callback(err)

  debug('Checking bitcoind/local chains')
  parallel({
    bitcoind: (f) => rpc('getbestblockhash', [], f),
    local: (f) => local.tip(f)
  }, (err, tips) => {
    if (err) return callback(err)

    // Step 0, genesis?
    if (!tips.local) {
      debug('genesis')
      return rpc('getblockhash', [0], (err, genesisId) => {
        if (err) return callback(err)

        connectBlock(genesisId, callback)
      })
    }

    // Step 1, equal?
    debug('tips', tips)
    if (tips.bitcoind === tips.local) return callback()

    // else, Step 2, is local behind? [bitcoind has local tip]
    rpc('getblockheader', [tips.local], (err, common) => {
      // not in bitcoind chain? [forked]
      if (
        (err && err.message === 'Block not found') ||
        (!err && common.confirmations === -1)
      ) {
        debug('local is forked')
        return disconnectBlock(tips.local, sync)
      }
      if (err) return callback(err)

      // behind
      debug('bitcoind is ahead')
      connectBlock(common.nextblockhash, callback)
    })
  })
}

zmq.on('hashblock', () => sync())
zmq.on('hashtx', (txId) => () => {
  debug(`Seen ${txId} ${Date.now()}`)
  local.see(txId)
})

sync(null, (err) => {
  if (err) throw err
})
<|endoftext|>