<commit_before>'use strict';

var aps = Array.prototype.slice;

var segue = function(cb) {

  var running = false;
  var queue = [];
  var nextArgs = [];

  var next = function() {

    var args = aps.call(arguments);
    var err = args.shift(); // `err` is the first argument of the `this` callback
    var arr;

    if (err) { // exit on `err`
      return cb(err);
    }

    if (queue.length) { // call the next function in the `queue`
      arr = queue.shift();
      args = args.concat(arr[1]);
      arr[0].apply(next, args);
    } else {
      nextArgs = args; // save the arguments passed to the `this` callback
      running = false;
    }

  };

  var enqueue = function() {

    var args = aps.call(arguments);
    var fn = args.shift();

    if (!queue.length && !running) {
      running = true;
      fn.apply(next, nextArgs.concat(args));
      nextArgs = [];
    } else {
      queue.push([fn, args]);
    }
    return enqueue;

  };

  return enqueue;

};

module.exports = exports = segue;
<commit_msg>Make the `cb` callback optional<commit_after>'use strict';

var aps = Array.prototype.slice;

var segue = function(cb) {

  cb = cb || function() {}; // no op

  var running = false;
  var queue = [];
  var nextArgs = [];

  var next = function() {

    var args = aps.call(arguments);
    var err = args.shift(); // `err` is the first argument of the `this` callback
    var arr;

    if (err) { // exit on `err`
      return cb(err);
    }

    if (queue.length) { // call the next function in the `queue`
      arr = queue.shift();
      args = args.concat(arr[1]);
      arr[0].apply(next, args);
    } else {
      nextArgs = args; // save the arguments passed to the `this` callback
      running = false;
    }

  };

  var enqueue = function() {

    var args = aps.call(arguments);
    var fn = args.shift();

    if (!queue.length && !running) {
      running = true;
      fn.apply(next, nextArgs.concat(args));
      nextArgs = [];
    } else {
      queue.push([fn, args]);
    }
    return enqueue;

  };

  return enqueue;

};

module.exports = exports = segue;
<|endoftext|>


<commit_before>/* jshint quotmark: single */
/* jshint evil: true */

(function () {
    'use strict';

    String.prototype.format = function() {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function(match, number) {
            return typeof args[number] != 'undefined' ? args[number] : match;
        });
    };

    var editor, settings, title, loading;

    var run = function () {
        $('#output-container').html('');
        $('#debugger').html('');
        $('#restart').hide();
        var result = settings.compile({
            data: editor.getValue(),
            success: function (data) {
                $('#restart').show();

                $('
', { id: 'output' })
                .appendTo('#output-container');

                $('
').appendTo('#output-container');

                if (data.indexOf('Failed') === 0) {
                    $('#output').html(data);
                    return;
                }

                eval(data);
                $('#output').squiffy({
                    scroll: 'element',
                    persist: false,
                    restartPrompt: false,
                    onSet: function (attribute, value) {
                        onSet(attribute, value);
                    }
                });
            },
            fail: function (data) {
                $('#output').html(result.message);
            }
        });
    };

    var restart = function () {
        $('#debugger').html('');
        $('#output').squiffy('restart');
    };

    var downloadSquiffyScript = function () {
        localSave();
        var blob = new Blob([editor.getValue()], {type: 'text/plain'});
        var filename = title + '.squiffy';

        var downloadLink = document.createElement('a');
        downloadLink.download = filename;
        downloadLink.href = window.URL.createObjectURL(blob);
        downloadLink.onclick = function (e) {
            document.body.removeChild(e.target);
        };
        downloadLink.style.display = 'none';
        document.body.appendChild(downloadLink);
        downloadLink.click();
    };

    var localSaveTimeout, autoSaveTimeout;

    var editorChange = function () {
        if (loading) return;
        setInfo('');
        if (localSaveTimeout) clearTimeout(localSaveTimeout);
        localSaveTimeout = setTimeout(localSave, 1000);
        if (settings.autoSave) {
            if (autoSaveTimeout) clearTimeout(autoSaveTimeout);
            autoSaveTimeout = setTimeout(autoSave, 5000);
        }
    };

    var localSave = function () {
        var data = editor.getValue();
        if (settings.storageKey) {
            localStorage[settings.storageKey] = data;
            setInfo('All changes saved locally');
        }
        processFile(data);
    };

    var autoSave = function () {
        settings.autoSave(title);
    };

    var setInfo = function (text) {
        $('#info').html(text);
    };

    var processFile = function (data) {
        var titleRegex = /^@title (.*)$/;
        var newTitle;

        var lines = data.replace(/\r/g, '').split('\n');
        lines.forEach(function (line) {
            var stripLine = line.trim();
            var match = titleRegex.exec(stripLine);

            if (match) {
                newTitle = match[1];
            }
        });

        if (!title || title !== newTitle) {
            title = newTitle || 'Untitled';
            if (settings.updateTitle) {
                settings.updateTitle(title);
            }
        }
    };

    var editorLoad = function (data) {
        loading = true;
        editor.getSession().setValue(data, -1);
        loading = false;
        processFile(data);
    };

    var methods = {
        init: function (options) {
            var element = this;
            settings = options;

            element.html(editorHtml);
            element.layout({
                applyDefaultStyles: true,
                onresize: function () {
                    if (editor) editor.resize();
                },
                north__resizable: false,
                north__closable: false,
                north__spacing_open: 0,
                east__size: 0.5,
                south__size: 80,
            });

            editor = ace.edit('editor');
            editor.setTheme('ace/theme/eclipse');
            editor.getSession().setMode('ace/mode/markdown');
            editor.getSession().setUseWrapMode(true);
            editor.getSession().on('change', editorChange);
            editor.focus();

            editorLoad(options.data);

            if (options.open) {
                $('#open').show();
                $('#open').click(options.open);
            }

            if (options.save) {
                $('#save').show();
                $('#save').click(function () {
                    clearTimeout(localSaveTimeout);
                    localSave();
                    options.save(title);
                });
            }

            $('#run').click(run);
            $('#restart').click(restart);
            $('#download-squiffy-script').click(downloadSquiffyScript);
        },
        load: function (data) {
            editorLoad(data);
            localSave();
        },
        save: function () {
            return editor.getValue();
        },
        setStorageKey: function (key) {
            settings.storageKey = key;
        },
        setInfo: function (text) {
            setInfo(text);
        },
    };

    $.fn.squiffyEditor = function (methodOrOptions) {
        if (methods[methodOrOptions]) {
            return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
        }
        else if (typeof methodOrOptions === 'object' || ! methodOrOptions) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' +  methodOrOptions + ' does not exist');
        }
    };

    var onSet = function (attribute, value) {
        // don't log internal attribute changes
        if (attribute.indexOf('_') === 0) return;

        $('
').html('{0} = {1}'.format(attribute, value)).appendTo('#debugger');
    };

    var editorHtml =
        '
\n' +
            '<button id="open" class="btn btn-primary" style="display: none"> Open</button>\n' +
            '<button id="save" class="btn btn-primary" style="display: none"> Save</button>\n' +
            '<button id="run" class="btn btn-success"> Run</button>\n' +
            '<button id="restart" class="btn btn-success" style="display: none"> Restart</button>\n' +
            '\n' +
            '
\n' +
                '
\n' +
                        '<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="false">\n' +
                                '\n' +
                                'Download\n' +
                                '\n' +
                        '</button>\n' +
                        '
\n' +
                                '
Squiffy script
\n' +
                                '
Export HTML and JavaScript
\n' +
                                '
Export JavaScript only
\n' +
                        '
\n' +
                '
\n' +
                '<button id="preview" class="btn btn-primary"> Preview</button>\n' +
                '<button id="publish" class="btn btn-primary"> Publish</button>\n' +
            '
\n' +
        '
\n' +
        '
\n' +
            '

\n' +
        '
\n' +
        '
\n' +
            '

\n' +
        '
\n' +
        '
\n' +
            '

\n' +
        '
\n';
})();<commit_msg>Export Javascript<commit_after>/* jshint quotmark: single */
/* jshint evil: true */

(function () {
    'use strict';

    String.prototype.format = function() {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function(match, number) {
            return typeof args[number] != 'undefined' ? args[number] : match;
        });
    };

    var editor, settings, title, loading;

    var run = function () {
        $('#output-container').html('');
        $('#debugger').html('');
        $('#restart').hide();
        settings.compile({
            data: editor.getValue(),
            success: function (data) {
                $('#restart').show();

                $('
', { id: 'output' })
                .appendTo('#output-container');

                $('
').appendTo('#output-container');

                if (data.indexOf('Failed') === 0) {
                    $('#output').html(data);
                    return;
                }

                eval(data);
                $('#output').squiffy({
                    scroll: 'element',
                    persist: false,
                    restartPrompt: false,
                    onSet: function (attribute, value) {
                        onSet(attribute, value);
                    }
                });
            },
            fail: function (data) {
                $('#output').html(data.message);
            }
        });
    };

    var restart = function () {
        $('#debugger').html('');
        $('#output').squiffy('restart');
    };

    var downloadSquiffyScript = function () {
        localSave();
        download(editor.getValue(), title + '.squiffy');
    };

    var downloadJavascript = function () {
        localSave();
        settings.compile({
            data: editor.getValue(),
            success: function (data) {
                download(data, title + '.js');
            },
            fail: function (data) {
                $('#output').html(data.message);
            }
        });
    };

    var download = function (data, filename) {
        var blob = new Blob([data], {type: 'text/plain'});
        var downloadLink = document.createElement('a');
        downloadLink.download = filename;
        downloadLink.href = window.URL.createObjectURL(blob);
        downloadLink.onclick = function (e) {
            document.body.removeChild(e.target);
        };
        downloadLink.style.display = 'none';
        document.body.appendChild(downloadLink);
        downloadLink.click();
    };

    var localSaveTimeout, autoSaveTimeout;

    var editorChange = function () {
        if (loading) return;
        setInfo('');
        if (localSaveTimeout) clearTimeout(localSaveTimeout);
        localSaveTimeout = setTimeout(localSave, 1000);
        if (settings.autoSave) {
            if (autoSaveTimeout) clearTimeout(autoSaveTimeout);
            autoSaveTimeout = setTimeout(autoSave, 5000);
        }
    };

    var localSave = function () {
        var data = editor.getValue();
        if (settings.storageKey) {
            localStorage[settings.storageKey] = data;
            setInfo('All changes saved locally');
        }
        processFile(data);
    };

    var autoSave = function () {
        settings.autoSave(title);
    };

    var setInfo = function (text) {
        $('#info').html(text);
    };

    var processFile = function (data) {
        var titleRegex = /^@title (.*)$/;
        var newTitle;

        var lines = data.replace(/\r/g, '').split('\n');
        lines.forEach(function (line) {
            var stripLine = line.trim();
            var match = titleRegex.exec(stripLine);

            if (match) {
                newTitle = match[1];
            }
        });

        if (!title || title !== newTitle) {
            title = newTitle || 'Untitled';
            if (settings.updateTitle) {
                settings.updateTitle(title);
            }
        }
    };

    var editorLoad = function (data) {
        loading = true;
        editor.getSession().setValue(data, -1);
        loading = false;
        processFile(data);
    };

    var methods = {
        init: function (options) {
            var element = this;
            settings = options;

            element.html(editorHtml);
            element.layout({
                applyDefaultStyles: true,
                onresize: function () {
                    if (editor) editor.resize();
                },
                north__resizable: false,
                north__closable: false,
                north__spacing_open: 0,
                east__size: 0.5,
                south__size: 80,
            });

            editor = ace.edit('editor');
            editor.setTheme('ace/theme/eclipse');
            editor.getSession().setMode('ace/mode/markdown');
            editor.getSession().setUseWrapMode(true);
            editor.getSession().on('change', editorChange);
            editor.focus();

            editorLoad(options.data);

            if (options.open) {
                $('#open').show();
                $('#open').click(options.open);
            }

            if (options.save) {
                $('#save').show();
                $('#save').click(function () {
                    clearTimeout(localSaveTimeout);
                    localSave();
                    options.save(title);
                });
            }

            $('#run').click(run);
            $('#restart').click(restart);
            $('#download-squiffy-script').click(downloadSquiffyScript);
            $('#export-js').click(downloadJavascript);
        },
        load: function (data) {
            editorLoad(data);
            localSave();
        },
        save: function () {
            return editor.getValue();
        },
        setStorageKey: function (key) {
            settings.storageKey = key;
        },
        setInfo: function (text) {
            setInfo(text);
        },
    };

    $.fn.squiffyEditor = function (methodOrOptions) {
        if (methods[methodOrOptions]) {
            return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
        }
        else if (typeof methodOrOptions === 'object' || ! methodOrOptions) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' +  methodOrOptions + ' does not exist');
        }
    };

    var onSet = function (attribute, value) {
        // don't log internal attribute changes
        if (attribute.indexOf('_') === 0) return;

        $('
').html('{0} = {1}'.format(attribute, value)).appendTo('#debugger');
    };

    var editorHtml =
        '
\n' +
            '<button id="open" class="btn btn-primary" style="display: none"> Open</button>\n' +
            '<button id="save" class="btn btn-primary" style="display: none"> Save</button>\n' +
            '<button id="run" class="btn btn-success"> Run</button>\n' +
            '<button id="restart" class="btn btn-success" style="display: none"> Restart</button>\n' +
            '\n' +
            '
\n' +
                '
\n' +
                        '<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="false">\n' +
                                '\n' +
                                'Download\n' +
                                '\n' +
                        '</button>\n' +
                        '
\n' +
                                '
Squiffy script
\n' +
                                '
Export HTML and JavaScript
\n' +
                                '
Export JavaScript only
\n' +
                        '
\n' +
                '
\n' +
                '<button id="preview" class="btn btn-primary"> Preview</button>\n' +
                '<button id="publish" class="btn btn-primary"> Publish</button>\n' +
            '
\n' +
        '
\n' +
        '
\n' +
            '

\n' +
        '
\n' +
        '
\n' +
            '

\n' +
        '
\n' +
        '
\n' +
            '

\n' +
        '
\n';
})();<|endoftext|>


<commit_before><commit_msg>fix database display, add route to get database results, fix add bee button<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, bitwise: true */
/*global define: true, require: true */

/* Help construct the svgOM from generator data */

(function () {
"use strict";

    var omgUtils = require("./svgOMGeneratorUtils.js");

    var CONST_COLOR_BLACK = { "red": 0, "green": 0, "blue": 0 };

	function SVGOMGeneratorStyles() {
        var decamelcase = function (string) {
            return string.replace(/([A-Z])/g, "-$1");
        }

        var fetchOpacity = function (layer) {
            if (layer.blendOptions &&
                layer.blendOptions.opacity) {
                return layer.blendOptions.opacity.value / 100;
            }
            return undefined;
        }

        this.fetchBlendMode = function (layer) {
            var blendMode;
            if (layer.blendOptions &&
                layer.blendOptions.mode) {
                blendMode = layer.blendOptions.mode;
                blendMode = decamelcase(blendMode);
            }

            switch (blendMode) {
                case "pass-Through":
                case "normal":
                    return undefined;
                case "multiply":
                case "screen":
                case "overlay":
                case "darken":
                case "lighten":
                case "color-dodge":
                case "color-burn":
                case "hard-light":
                case "soft-light":
                case "difference":
                case "exclusion":
                case "hue":
                case "saturation":
                case "color":
                case "luminosity":
                    return blendMode;
                default:
                    return undefined;
            }
        }

        this.addGlobalStyle = function (svgNode, layer) {

            var propertyFetchers = { // Properties we fetch for all layers
                    "opacity": fetchOpacity,
                    "mix-blend-mode": this.fetchBlendMode
                },
                property;

            for (property in propertyFetchers) {
                var value = propertyFetchers[property](layer);
                if (value !== undefined) {
                    svgNode.style[property] = value;
                }
            }
        };

        this.addStroke = function (svgNode, layer) {
            var stroke = svgNode.style.stroke || {},
                strokeStyle = layer.strokeStyle,
                toStrokeLinecap = {
                    "strokeStyleRoundCap": "round",
                    "strokeStyleButtCap": "butt",
                    "strokeStyleSquareCap": "square"
                },
                toStrokeLinejoin = {
                    "strokeStyleBevelJoin": "bevel",
                    "strokeStyleRoundJoin": "round",
                    "strokeStyleMiterJoin": "miter"
                };

            svgNode.style.stroke = stroke;

            if (strokeStyle) {
                stroke.strokeEnabled = !!strokeStyle.strokeEnabled;
                stroke.lineCap = strokeStyle.strokeStyleLineCapType ? toStrokeLinecap[strokeStyle.strokeStyleLineCapType] : "butt";
                stroke.lineJoin = strokeStyle.strokeStyleLineJoinType ? toStrokeLinejoin[strokeStyle.strokeStyleLineJoinType] : "miter";
                stroke.lineWidth = strokeStyle.strokeStyleLineWidth ? strokeStyle.strokeStyleLineWidth.value : 1;
                stroke.miterLimit = strokeStyle.strokeStyleMiterLimit ? strokeStyle.strokeStyleMiterLimit : 100;
                stroke.dashArray = strokeStyle.strokeStyleLineDashSet ? strokeStyle.strokeStyleLineDashSet : [];
                stroke.dashOffset = strokeStyle.strokeStyleLineDashOffset ? strokeStyle.strokeStyleLineDashOffset.value : "0";
                stroke.color = (strokeStyle.strokeStyleContent && strokeStyle.strokeStyleContent.color) ? omgUtils.toColor(strokeStyle.strokeStyleContent.color) : CONST_COLOR_BLACK;
                stroke.opacity = strokeStyle.strokeStyleOpacity ? strokeStyle.strokeStyleOpacity.value / 100 : 1;
                if (strokeStyle.strokeStyleContent && strokeStyle.strokeStyleContent.gradient) {
                    stroke.gradient = omgUtils.toGradient(strokeStyle.strokeStyleContent);
                }
            } else {
                stroke.strokeEnabled = false;
            }
        };

        this.addFill = function (svgNode, layer) {
            var fill = svgNode.style.fill || {},
                fillStyle = layer.fill,
                strokeStyle = layer.strokeStyle;
            if (!fillStyle || strokeStyle && strokeStyle.fillEnabled === false) {
                return;
            }

            var fillClass = fillStyle["class"];

            svgNode.style.fill = fill;

            if (fillClass === "solidColorLayer") {
                fill.style = "solid";
                fill.color = omgUtils.toColor(fillStyle.color);
            } else if (fillClass == "gradientLayer") {
                fill.style = "gradient";
                fill.gradientType = fillStyle.type;

                if (fill.style === "gradient") {
                    fill.gradient = omgUtils.toGradient(fillStyle);
                } else {
                    console.log("WARNING: Unhandled gradient type = " + JSON.stringify(fill));
                }
            } else {
                //unhandled fill
                console.log("WARNING: Unhandled fill " + fillClass);
            }

            if (layer.blendOptions && layer.blendOptions.fillOpacity) {
                svgNode.style["fill-opacity"] = layer.blendOptions.fillOpacity.value / 100;
            }
        };

        this.addFx = function (svgNode, layer) {
            var color;

            if (!layer.layerEffects) {
                return;
            }
            svgNode.style.fx = JSON.parse(JSON.stringify(layer.layerEffects));

            // Alpha isn't really used in an solid fill since there is a separate opacity passed.
            if (svgNode.style.fx.solidFill) {
                color = svgNode.style.fx.solidFill.color;
                color.r = color.red;
                color.g = color.green;
                color.b = color.blue;
                color.a = 1;
            }

            if (svgNode.style.fx.outerGlow) {
                if (svgNode.style.fx.outerGlow.gradient) {
                    var gradient = omgUtils.toColorStops(svgNode.style.fx.outerGlow);
                    svgNode.style.fx.outerGlow.gradient = gradient;
                } else {
                    color = svgNode.style.fx.outerGlow.color;
                    svgNode.style.fx.outerGlow.color = omgUtils.toColor(color);
                }
            }

            if (svgNode.style.fx.innerGlow) {
                if (svgNode.style.fx.innerGlow.gradient) {
                    var gradient = omgUtils.toColorStops(svgNode.style.fx.innerGlow);
                    // Reverse gradient.
                    for (var i = gradient.stops.length - 1; i >= 0; i--) {
                        gradient.stops[i].position = Math.abs(gradient.stops[i].position - 100);
                    }
                    gradient.stops.sort(function (a, b) {
                        return a.position - b.position;
                    });
                    svgNode.style.fx.innerGlow.gradient = gradient;
                } else {
                    color = svgNode.style.fx.innerGlow.color;
                    svgNode.style.fx.innerGlow.color = omgUtils.toColor(color);
                }
            }

            if (svgNode.style.fx.chromeFX) {
                color = svgNode.style.fx.chromeFX.color;
                svgNode.style.fx.chromeFX.color = omgUtils.toColor(color);
            }

            if (svgNode.style.fx.innerShadow) {
                color = svgNode.style.fx.innerShadow.color;
                svgNode.style.fx.innerShadow.color = omgUtils.toColor(color);
            }

            if (svgNode.style.fx.gradientFill) {
                var gradient = omgUtils.toGradient(svgNode.style.fx.gradientFill);
                svgNode.style.fx.gradientFill.gradient = gradient;
            }

            if (svgNode.style.fx.dropShadow) {
                color = svgNode.style.fx.dropShadow.color;
                svgNode.style.fx.dropShadow.color = omgUtils.toColor(color);
            }

            if (svgNode.style.fx.frameFX) {
                var stroke = {},
                      strokeStyle = svgNode.style.fx.frameFX;

                svgNode.style.stroke = stroke;

                if (strokeStyle) {
                    stroke.strokeEnabled = !!strokeStyle.enabled;
                    stroke.lineWidth = strokeStyle.size ? strokeStyle.size : 1;
                    stroke.color = strokeStyle.color ? omgUtils.toColor(strokeStyle.color) : CONST_COLOR_BLACK;
                    stroke.opacity = strokeStyle.opacity ? strokeStyle.opacity.value / 100 : 1;
                    stroke.lineCap = "butt";
                    stroke.lineJoin = "round";
                    stroke.miterLimit = 100;
                    if (strokeStyle.gradient) {
                        stroke.gradient = omgUtils.toGradient(strokeStyle);
                    }
                } else {
                    stroke.strokeEnabled = false;
                }
            }
        };

        this.addStylingData = function (svgNode, layer) {

            this.addGlobalStyle(svgNode, layer);

            // FIXME: The PS imported image already has all fx effects applied.
            if (svgNode.type == "generic") {
                return;
            }

            this.addStroke(svgNode, layer);
            this.addFill(svgNode, layer);
            this.addFx(svgNode, layer);

            //more stuff...
        };

        this.addTextChunkStyle = function (span, textStyle) {
            var fontFamily;

            if (textStyle.textStyle.color) {
                span.style["fill"] = {
                    style: "solid",
                    color: omgUtils.toColor(textStyle.textStyle.color)
                };
            }

            if (textStyle.textStyle.fontName) {
                fontFamily = textStyle.textStyle.fontName;
                if (textStyle.textStyle.fontPostscriptName) {
                    fontFamily = textStyle.textStyle.fontPostscriptName;
                }
                span.style["font-family"] = '"' + fontFamily + '"';
            }

            if (textStyle.textStyle.size) {
                span.style["font-size"] = textStyle.textStyle.size; // Need to take units into account.
            }

            if (textStyle.textStyle.fontStyleName) {
                if (textStyle.textStyle.fontStyleName.indexOf("Bold") >= 0) {
                    span.style["font-weight"] = "bold";
                }
                if (textStyle.textStyle.fontStyleName.indexOf("Italic") >= 0) {
                    span.style["font-style"] = "italic";
                }
            }

            if (textStyle.textStyle.strikethrough && textStyle.textStyle.strikethrough.indexOf("StrikethroughOn") >= 0) {
                span.style["text-decoration"] = "line-through";
            }

            if (textStyle.textStyle.underline && textStyle.textStyle.underline.indexOf("underlineOn") >= 0) {
                if (span.style["text-decoration"]) {
                    span.style["text-decoration"] += " underline";
                } else {
                    span.style["text-decoration"] = "underline";
                }
            }

            if (textStyle.textStyle.fontCaps) {
                if (textStyle.textStyle.fontCaps === "smallCaps") {
                    span.style["font-variant"] = "small-caps";
                } else if (textStyle.textStyle.fontCaps === "allCaps") {
                    span.style["text-transform"] = "uppercase";
                }
            }

            if (textStyle.textStyle.baseline) {
                if (textStyle.textStyle.baseline === "smallCaps") {
                    span.style["baseline-shift"] = "super";
                } else if (textStyle.textStyle.baseline === "allCaps") {
                    span.style["baseline-shift"] = "sub";
                }
            }
        }

        this.addParagraphStyle = function (paragraphNode, paragraphStyle) {
            function fetchTextAlign(paragraphStyle) {
                var alignment = {
                        "left": undefined,
                        "center": "middle",
                        "right": "end"
                    };

                if (paragraphStyle.align) {
                    return alignment[paragraphStyle.align];
                }
                return undefined;
            }

            function computeMaxFontSize(paragraphNode) {
                var maxSize = { value: 0, units: "pointsUnit" },
                    i = 0;

                // For correct paragraph offset, we need to know the maximal
                // font size.
                if (!paragraphNode.children.length) {
                    return undefined;
                }
                for (i = 0; i < paragraphNode.children.length; ++i) {
                    if (!paragraphNode.children[i].style &&
                        !paragraphNode.children[i].style["font-size"]) {
                        continue;
                    }
                    // FIXME: Support for real unit computation missing. Probably needs to move to writer.
                    // Since fonts always use pt in Adobe products, it most likely doesn't cause issues.
                    maxSize.value = Math.max(maxSize.value, paragraphNode.children[i].style["font-size"].value);
                }
                return maxSize;
            }

            paragraphNode.style = {
                "text-anchor": fetchTextAlign(paragraphStyle),
                "font-size": computeMaxFontSize(paragraphNode)
            }
        }

        this.addTextStyle = function (svgNode, layer) {
            if (layer.text.textShape[0].orientation &&
                layer.text.textShape[0].orientation == "vertical") {
                svgNode.style["writing-mode"] = "tb";
                svgNode.style["glyph-orientation-vertical"] = "0";
            }
        }
	}

	module.exports = new SVGOMGeneratorStyles();

}());

    <commit_msg>don't include layer effects if they are disabled<commit_after>// Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, bitwise: true */
/*global define: true, require: true */

/* Help construct the svgOM from generator data */

(function () {
"use strict";

    var omgUtils = require("./svgOMGeneratorUtils.js");

    var CONST_COLOR_BLACK = { "red": 0, "green": 0, "blue": 0 };

	function SVGOMGeneratorStyles() {
        var decamelcase = function (string) {
            return string.replace(/([A-Z])/g, "-$1");
        }

        var fetchOpacity = function (layer) {
            if (layer.blendOptions &&
                layer.blendOptions.opacity) {
                return layer.blendOptions.opacity.value / 100;
            }
            return undefined;
        }

        this.fetchBlendMode = function (layer) {
            var blendMode;
            if (layer.blendOptions &&
                layer.blendOptions.mode) {
                blendMode = layer.blendOptions.mode;
                blendMode = decamelcase(blendMode);
            }

            switch (blendMode) {
                case "pass-Through":
                case "normal":
                    return undefined;
                case "multiply":
                case "screen":
                case "overlay":
                case "darken":
                case "lighten":
                case "color-dodge":
                case "color-burn":
                case "hard-light":
                case "soft-light":
                case "difference":
                case "exclusion":
                case "hue":
                case "saturation":
                case "color":
                case "luminosity":
                    return blendMode;
                default:
                    return undefined;
            }
        }

        this.addGlobalStyle = function (svgNode, layer) {

            var propertyFetchers = { // Properties we fetch for all layers
                    "opacity": fetchOpacity,
                    "mix-blend-mode": this.fetchBlendMode
                },
                property;

            for (property in propertyFetchers) {
                var value = propertyFetchers[property](layer);
                if (value !== undefined) {
                    svgNode.style[property] = value;
                }
            }
        };

        this.addStroke = function (svgNode, layer) {
            var stroke = svgNode.style.stroke || {},
                strokeStyle = layer.strokeStyle,
                toStrokeLinecap = {
                    "strokeStyleRoundCap": "round",
                    "strokeStyleButtCap": "butt",
                    "strokeStyleSquareCap": "square"
                },
                toStrokeLinejoin = {
                    "strokeStyleBevelJoin": "bevel",
                    "strokeStyleRoundJoin": "round",
                    "strokeStyleMiterJoin": "miter"
                };

            svgNode.style.stroke = stroke;

            if (strokeStyle) {
                stroke.strokeEnabled = !!strokeStyle.strokeEnabled;
                stroke.lineCap = strokeStyle.strokeStyleLineCapType ? toStrokeLinecap[strokeStyle.strokeStyleLineCapType] : "butt";
                stroke.lineJoin = strokeStyle.strokeStyleLineJoinType ? toStrokeLinejoin[strokeStyle.strokeStyleLineJoinType] : "miter";
                stroke.lineWidth = strokeStyle.strokeStyleLineWidth ? strokeStyle.strokeStyleLineWidth.value : 1;
                stroke.miterLimit = strokeStyle.strokeStyleMiterLimit ? strokeStyle.strokeStyleMiterLimit : 100;
                stroke.dashArray = strokeStyle.strokeStyleLineDashSet ? strokeStyle.strokeStyleLineDashSet : [];
                stroke.dashOffset = strokeStyle.strokeStyleLineDashOffset ? strokeStyle.strokeStyleLineDashOffset.value : "0";
                stroke.color = (strokeStyle.strokeStyleContent && strokeStyle.strokeStyleContent.color) ? omgUtils.toColor(strokeStyle.strokeStyleContent.color) : CONST_COLOR_BLACK;
                stroke.opacity = strokeStyle.strokeStyleOpacity ? strokeStyle.strokeStyleOpacity.value / 100 : 1;
                if (strokeStyle.strokeStyleContent && strokeStyle.strokeStyleContent.gradient) {
                    stroke.gradient = omgUtils.toGradient(strokeStyle.strokeStyleContent);
                }
            } else {
                stroke.strokeEnabled = false;
            }
        };

        this.addFill = function (svgNode, layer) {
            var fill = svgNode.style.fill || {},
                fillStyle = layer.fill,
                strokeStyle = layer.strokeStyle;
            if (!fillStyle || strokeStyle && strokeStyle.fillEnabled === false) {
                return;
            }

            var fillClass = fillStyle["class"];

            svgNode.style.fill = fill;

            if (fillClass === "solidColorLayer") {
                fill.style = "solid";
                fill.color = omgUtils.toColor(fillStyle.color);
            } else if (fillClass == "gradientLayer") {
                fill.style = "gradient";
                fill.gradientType = fillStyle.type;

                if (fill.style === "gradient") {
                    fill.gradient = omgUtils.toGradient(fillStyle);
                } else {
                    console.log("WARNING: Unhandled gradient type = " + JSON.stringify(fill));
                }
            } else {
                //unhandled fill
                console.log("WARNING: Unhandled fill " + fillClass);
            }

            if (layer.blendOptions && layer.blendOptions.fillOpacity) {
                svgNode.style["fill-opacity"] = layer.blendOptions.fillOpacity.value / 100;
            }
        };

        this.addFx = function (svgNode, layer) {
            var color;

            if (!layer.layerEffects || layer.layerEffects.masterFXSwitch === false) {
                return;
            }
            svgNode.style.fx = JSON.parse(JSON.stringify(layer.layerEffects));

            // Alpha isn't really used in an solid fill since there is a separate opacity passed.
            if (svgNode.style.fx.solidFill) {
                color = svgNode.style.fx.solidFill.color;
                color.r = color.red;
                color.g = color.green;
                color.b = color.blue;
                color.a = 1;
            }

            if (svgNode.style.fx.outerGlow) {
                if (svgNode.style.fx.outerGlow.gradient) {
                    var gradient = omgUtils.toColorStops(svgNode.style.fx.outerGlow);
                    svgNode.style.fx.outerGlow.gradient = gradient;
                } else {
                    color = svgNode.style.fx.outerGlow.color;
                    svgNode.style.fx.outerGlow.color = omgUtils.toColor(color);
                }
            }

            if (svgNode.style.fx.innerGlow) {
                if (svgNode.style.fx.innerGlow.gradient) {
                    var gradient = omgUtils.toColorStops(svgNode.style.fx.innerGlow);
                    // Reverse gradient.
                    for (var i = gradient.stops.length - 1; i >= 0; i--) {
                        gradient.stops[i].position = Math.abs(gradient.stops[i].position - 100);
                    }
                    gradient.stops.sort(function (a, b) {
                        return a.position - b.position;
                    });
                    svgNode.style.fx.innerGlow.gradient = gradient;
                } else {
                    color = svgNode.style.fx.innerGlow.color;
                    svgNode.style.fx.innerGlow.color = omgUtils.toColor(color);
                }
            }

            if (svgNode.style.fx.chromeFX) {
                color = svgNode.style.fx.chromeFX.color;
                svgNode.style.fx.chromeFX.color = omgUtils.toColor(color);
            }

            if (svgNode.style.fx.innerShadow) {
                color = svgNode.style.fx.innerShadow.color;
                svgNode.style.fx.innerShadow.color = omgUtils.toColor(color);
            }

            if (svgNode.style.fx.gradientFill) {
                var gradient = omgUtils.toGradient(svgNode.style.fx.gradientFill);
                svgNode.style.fx.gradientFill.gradient = gradient;
            }

            if (svgNode.style.fx.dropShadow) {
                color = svgNode.style.fx.dropShadow.color;
                svgNode.style.fx.dropShadow.color = omgUtils.toColor(color);
            }

            if (svgNode.style.fx.frameFX) {
                var stroke = {},
                      strokeStyle = svgNode.style.fx.frameFX;

                svgNode.style.stroke = stroke;

                if (strokeStyle) {
                    stroke.strokeEnabled = !!strokeStyle.enabled;
                    stroke.lineWidth = strokeStyle.size ? strokeStyle.size : 1;
                    stroke.color = strokeStyle.color ? omgUtils.toColor(strokeStyle.color) : CONST_COLOR_BLACK;
                    stroke.opacity = strokeStyle.opacity ? strokeStyle.opacity.value / 100 : 1;
                    stroke.lineCap = "butt";
                    stroke.lineJoin = "round";
                    stroke.miterLimit = 100;
                    if (strokeStyle.gradient) {
                        stroke.gradient = omgUtils.toGradient(strokeStyle);
                    }
                } else {
                    stroke.strokeEnabled = false;
                }
            }
        };

        this.addStylingData = function (svgNode, layer) {

            this.addGlobalStyle(svgNode, layer);

            // FIXME: The PS imported image already has all fx effects applied.
            if (svgNode.type == "generic") {
                return;
            }

            this.addStroke(svgNode, layer);
            this.addFill(svgNode, layer);
            this.addFx(svgNode, layer);

            //more stuff...
        };

        this.addTextChunkStyle = function (span, textStyle) {
            var fontFamily;

            if (textStyle.textStyle.color) {
                span.style["fill"] = {
                    style: "solid",
                    color: omgUtils.toColor(textStyle.textStyle.color)
                };
            }

            if (textStyle.textStyle.fontName) {
                fontFamily = textStyle.textStyle.fontName;
                if (textStyle.textStyle.fontPostscriptName) {
                    fontFamily = textStyle.textStyle.fontPostscriptName;
                }
                span.style["font-family"] = '"' + fontFamily + '"';
            }

            if (textStyle.textStyle.size) {
                span.style["font-size"] = textStyle.textStyle.size; // Need to take units into account.
            }

            if (textStyle.textStyle.fontStyleName) {
                if (textStyle.textStyle.fontStyleName.indexOf("Bold") >= 0) {
                    span.style["font-weight"] = "bold";
                }
                if (textStyle.textStyle.fontStyleName.indexOf("Italic") >= 0) {
                    span.style["font-style"] = "italic";
                }
            }

            if (textStyle.textStyle.strikethrough && textStyle.textStyle.strikethrough.indexOf("StrikethroughOn") >= 0) {
                span.style["text-decoration"] = "line-through";
            }

            if (textStyle.textStyle.underline && textStyle.textStyle.underline.indexOf("underlineOn") >= 0) {
                if (span.style["text-decoration"]) {
                    span.style["text-decoration"] += " underline";
                } else {
                    span.style["text-decoration"] = "underline";
                }
            }

            if (textStyle.textStyle.fontCaps) {
                if (textStyle.textStyle.fontCaps === "smallCaps") {
                    span.style["font-variant"] = "small-caps";
                } else if (textStyle.textStyle.fontCaps === "allCaps") {
                    span.style["text-transform"] = "uppercase";
                }
            }

            if (textStyle.textStyle.baseline) {
                if (textStyle.textStyle.baseline === "smallCaps") {
                    span.style["baseline-shift"] = "super";
                } else if (textStyle.textStyle.baseline === "allCaps") {
                    span.style["baseline-shift"] = "sub";
                }
            }
        }

        this.addParagraphStyle = function (paragraphNode, paragraphStyle) {
            function fetchTextAlign(paragraphStyle) {
                var alignment = {
                        "left": undefined,
                        "center": "middle",
                        "right": "end"
                    };

                if (paragraphStyle.align) {
                    return alignment[paragraphStyle.align];
                }
                return undefined;
            }

            function computeMaxFontSize(paragraphNode) {
                var maxSize = { value: 0, units: "pointsUnit" },
                    i = 0;

                // For correct paragraph offset, we need to know the maximal
                // font size.
                if (!paragraphNode.children.length) {
                    return undefined;
                }
                for (i = 0; i < paragraphNode.children.length; ++i) {
                    if (!paragraphNode.children[i].style &&
                        !paragraphNode.children[i].style["font-size"]) {
                        continue;
                    }
                    // FIXME: Support for real unit computation missing. Probably needs to move to writer.
                    // Since fonts always use pt in Adobe products, it most likely doesn't cause issues.
                    maxSize.value = Math.max(maxSize.value, paragraphNode.children[i].style["font-size"].value);
                }
                return maxSize;
            }

            paragraphNode.style = {
                "text-anchor": fetchTextAlign(paragraphStyle),
                "font-size": computeMaxFontSize(paragraphNode)
            }
        }

        this.addTextStyle = function (svgNode, layer) {
            if (layer.text.textShape[0].orientation &&
                layer.text.textShape[0].orientation == "vertical") {
                svgNode.style["writing-mode"] = "tb";
                svgNode.style["glyph-orientation-vertical"] = "0";
            }
        }
	}

	module.exports = new SVGOMGeneratorStyles();

}());
<|endoftext|>


<commit_before>import issueStrats from '../issue-strategies/index.js';
import * as promiseUtils from '../promise-utils.js';

function validateStrategies(issueKey, jiraClientAPI) {
  return jiraClientAPI.findIssue(issueKey)
  .then(content => {
    if (!issueStrats[content.fields.issuetype.name]) {
      return issueStrats[Unknown].apply(content, jiraClientAPI);
    }

    return issueStrats[content.fields.issuetype.name].apply(content, jiraClientAPI);
  });
}

export default function apply(issues, jiraClientAPI) {
  return promiseUtils.anyPromise(issues.map(i => validateStrategies(i, jiraClientAPI)));
}
<commit_msg>Changed unknown to dot notation<commit_after>import issueStrats from '../issue-strategies/index.js';
import * as promiseUtils from '../promise-utils.js';

function validateStrategies(issueKey, jiraClientAPI) {
  return jiraClientAPI.findIssue(issueKey)
  .then(content => {
    if (!issueStrats[content.fields.issuetype.name]) {
      return issueStrats.Unknown.apply(content, jiraClientAPI);
    }

    return issueStrats[content.fields.issuetype.name].apply(content, jiraClientAPI);
  });
}

export default function apply(issues, jiraClientAPI) {
  return promiseUtils.anyPromise(issues.map(i => validateStrategies(i, jiraClientAPI)));
}
<|endoftext|>


<commit_before>'use strict';
import React, {
  TextInput,
  TouchableOpacity,
  Text,
  View,
  Component
} from 'react-native';
import styles from './styles';
const TEXT_INPUT_REF = 'urlInput';

export default class AddressBar extends Component {
  constructor(props) {
    super(props);
    this.inputText = '';
    this.state = {
      url: this.props.url
    };
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      url: nextProps.url
    });
  }

  handleTextInputChange(event) {
    let url = event.nativeEvent.text;
    if (!/^[a-zA-Z-_]+:/.test(url)) {
      url = 'http://' + url;
    }
    this.inputText = url;
  }

  onSubmitEditing(event) {
    this.load();
  }

  load() {
    const url = this.inputText;
    if (url === this.props.url) {
      this.props.onReload();
    } else {
      this.props.onLoad(url);
    }
    // dismiss keyboard
    this.refs[TEXT_INPUT_REF].blur();
  }

  render() {
    return (
      <View style={styles.addressBarRow}>
          <TouchableOpacity
            onPress={this.state.onBack}>
              <Text
                style={styles.button}>
                {'←'}
              </Text>
          </TouchableOpacity>
        <TextInput
          ref={TEXT_INPUT_REF}
          autoCapitalize="none"
          defaultValue={this.state.url}
          onSubmitEditing={this.onSubmitEditing.bind(this)}
          onChange={this.handleTextInputChange.bind(this)}
          clearButtonMode="while-editing"
          style={styles.addressBarTextInput}
        />
      </View>
    );
  }
}
<commit_msg>fix goBack goForward<commit_after>'use strict';
import React, {
  Image,
  TextInput,
  TouchableOpacity,
  Text,
  View,
  Component
} from 'react-native';
import styles from './styles';
const TEXT_INPUT_REF = 'urlInput';

export default class AddressBar extends Component {
  constructor(props) {
    super(props);
    this.inputText = '';
    this.state = {
      url: this.props.url,
      backButtonEnabled: this.props.backButtonEnabled,
      forwardButtonEnabled: this.props.forwardButtonEnabled,
      onBack: this.props.onBack,
      onForward: this.props.onForward
    };
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      url: nextProps.url,
      backButtonEnabled: nextProps.backButtonEnabled,
      forwardButtonEnabled: nextProps.forwardButtonEnabled,
      onBack: nextProps.onBack,
      onForward: nextProps.onForward
    });
  }

  handleTextInputChange(event) {
    let url = event.nativeEvent.text;
    if (!/^[a-zA-Z-_]+:/.test(url)) {
      url = 'http://' + url;
    }
    this.inputText = url;
  }

  onSubmitEditing(event) {
    this.load();
  }

  load() {
    const url = this.inputText;
    if (url === this.props.url) {
      this.props.onReload();
    } else {
      this.props.onLoad(url);
    }
    // dismiss keyboard
    this.refs[TEXT_INPUT_REF].blur();
  }

  render() {
    return (
      <View style={styles.addressBarRow}>
          <TouchableOpacity
            onPress={this.state.onBack}>
            <Text
              style={styles.button}>
              {'<'}
            </Text>
            <Text
              style={styles.button}>
              {'>'}
            </Text>
          </TouchableOpacity>
        <TextInput
          ref={TEXT_INPUT_REF}
          autoCapitalize="none"
          defaultValue={this.state.url}
          onSubmitEditing={this.onSubmitEditing.bind(this)}
          onChange={this.handleTextInputChange.bind(this)}
          clearButtonMode="while-editing"
          style={styles.addressBarTextInput}
        />
      </View>
    );
  }
}
<|endoftext|>


<commit_before>var _ = require('underscore');
var express = require('express');
var fs = require('fs');
var grappling = require('grappling-hook');
var path = require('path');
var utils = require('keystone-utils');

/**
 * Don't use process.cwd() as it breaks module encapsulation
 * Instead, let's use module.parent if it's present, or the module itself if there is no parent (probably testing keystone directly if that's the case)
 * This way, the consuming app/module can be an embedded node_module and path resolutions will still work
 * (process.cwd() breaks module encapsulation if the consuming app/module is itself a node_module)
 */
var moduleRoot = (function (_rootPath) {
	var parts = _rootPath.split(path.sep);
	parts.pop(); // get rid of /node_modules from the end of the path
	return parts.join(path.sep);
})(module.parent ? module.parent.paths[0] : module.paths[0]);

/**
 * Keystone Class
 *
 * @api public
 */
var Keystone = function () {
	grappling.mixin(this).allowHooks('pre:static', 'pre:bodyparser', 'pre:session', 'pre:routes', 'pre:render', 'updates', 'signout', 'signin', 'pre:logger');
	this.lists = {};
	this.paths = {};
	this._options = {
		'name': 'Keystone',
		'brand': 'Keystone',
		'admin path': 'keystone',
		'compress': true,
		'headless': false,
		'logger': ':method :url :status :response-time ms',
		'auto update': false,
		'model prefix': null,
		'module root': moduleRoot,
		'frame guard': 'sameorigin',
	};
	this._redirects = {};

	// expose express
	this.express = express;

	// init environment defaults
	this.set('env', process.env.NODE_ENV || 'development');

	this.set('port', process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT);
	this.set('host', process.env.HOST || process.env.IP || process.env.OPENSHIFT_NODEJS_IP);
	this.set('listen', process.env.LISTEN);

	this.set('ssl', process.env.SSL);
	this.set('ssl port', process.env.SSL_PORT);
	this.set('ssl host', process.env.SSL_HOST || process.env.SSL_IP);
	this.set('ssl key', process.env.SSL_KEY);
	this.set('ssl cert', process.env.SSL_CERT);

	this.set('cookie secret', process.env.COOKIE_SECRET);
	this.set('cookie signin', (this.get('env') === 'development') ? true : false);

	this.set('embedly api key', process.env.EMBEDLY_API_KEY || process.env.EMBEDLY_APIKEY);
	this.set('mandrill api key', process.env.MANDRILL_API_KEY || process.env.MANDRILL_APIKEY);
	this.set('mandrill username', process.env.MANDRILL_USERNAME);
	this.set('google api key', process.env.GOOGLE_BROWSER_KEY);
	this.set('google server api key', process.env.GOOGLE_SERVER_KEY);
	this.set('ga property', process.env.GA_PROPERTY);
	this.set('ga domain', process.env.GA_DOMAIN);
	this.set('chartbeat property', process.env.CHARTBEAT_PROPERTY);
	this.set('chartbeat domain', process.env.CHARTBEAT_DOMAIN);
	this.set('allowed ip ranges', process.env.ALLOWED_IP_RANGES);

	if (process.env.S3_BUCKET && process.env.S3_KEY && process.env.S3_SECRET) {
		this.set('s3 config', { bucket: process.env.S3_BUCKET, key: process.env.S3_KEY, secret: process.env.S3_SECRET, region: process.env.S3_REGION });
	}

	if (process.env.AZURE_STORAGE_ACCOUNT && process.env.AZURE_STORAGE_ACCESS_KEY) {
		this.set('azurefile config', { account: process.env.AZURE_STORAGE_ACCOUNT, key: process.env.AZURE_STORAGE_ACCESS_KEY });
	}

	if (process.env.CLOUDINARY_URL) {
		// process.env.CLOUDINARY_URL is processed by the cloudinary package when this is set
		this.set('cloudinary config', true);
	}

	// init mongoose
	this.set('mongoose', require('mongoose'));

	// Attach middleware packages, bound to this instance
	this.middleware = {
		api: require('./lib/middleware/api')(this),
		cors: require('./lib/middleware/cors')(this),
	};
};

_.extend(Keystone.prototype, require('./lib/core/options')());

Keystone.prototype.prefixModel = function (key) {
	var modelPrefix = this.get('model prefix');

	if (modelPrefix) {
		key = modelPrefix + '_' + key;
	}

	return require('mongoose/lib/utils').toCollectionName(key);
};

/* Attach core functionality to Keystone.prototype */
Keystone.prototype.createItems = require('./lib/core/createItems');
Keystone.prototype.getOrphanedLists = require('./lib/core/getOrphanedLists');
Keystone.prototype.importer = require('./lib/core/importer');
Keystone.prototype.init = require('./lib/core/init');
Keystone.prototype.initDatabase = require('./lib/core/initDatabase');
Keystone.prototype.initExpressApp = require('./lib/core/initExpressApp');
Keystone.prototype.initExpressSession = require('./lib/core/initExpressSession');
Keystone.prototype.initNav = require('./lib/core/initNav');
Keystone.prototype.list = require('./lib/core/list');
Keystone.prototype.openDatabaseConnection = require('./lib/core/openDatabaseConnection');
Keystone.prototype.populateRelated = require('./lib/core/populateRelated');
Keystone.prototype.redirect = require('./lib/core/redirect');
Keystone.prototype.render = require('./lib/core/render');
Keystone.prototype.start = require('./lib/core/start');
Keystone.prototype.wrapHTMLError = require('./lib/core/wrapHTMLError');

/**
 * The exports object is an instance of Keystone.
 *
 * @api public
 */
var keystone = module.exports = new Keystone();

// Expose modules and Classes
keystone.Admin = {
	Server: require('./admin/server'),
};
keystone.Email = require('./lib/email');
keystone.Field = require('./fields/types/Type');
keystone.Field.Types = require('./lib/fieldTypes');
keystone.Keystone = Keystone;
keystone.List = require('./lib/list');
keystone.View = require('./lib/view');

keystone.content = require('./lib/content');
keystone.security = {
	csrf: require('./lib/security/csrf'),
};
keystone.utils = utils;

/**
 * returns all .js modules (recursively) in the path specified, relative
 * to the module root (where the keystone project is being consumed from).
 *
 * ####Example:
 *
 *     var models = keystone.import('models');
 *
 * @param {String} dirname
 * @api public
 */

Keystone.prototype.import = function (dirname) {

	var initialPath = path.join(this.get('module root'), dirname);

	var doImport = function (fromPath) {

		var imported = {};

		fs.readdirSync(fromPath).forEach(function (name) {

			var fsPath = path.join(fromPath, name);
			var info = fs.statSync(fsPath);

			// recur
			if (info.isDirectory()) {
				imported[name] = doImport(fsPath);
			} else {
				// only import files that we can `require`
				var ext = path.extname(name);
				var base = path.basename(name, ext);
				if (require.extensions[ext]) {
					imported[base] = require(fsPath);
				}
			}

		});

		return imported;
	};

	return doImport(initialPath);
};

/**
 * Applies Application updates
 */

Keystone.prototype.applyUpdates = function (callback) {
	var self = this;
	self.callHook('pre:updates', function (err) {
		if (err) return callback(err);
		require('./lib/updates').apply(function (err) {
			if (err) return callback(err);
			self.callHook('post:updates', callback);
		});
	});
};

/**
 * Logs a configuration error to the console
 *
 * @api public
 */

Keystone.prototype.console = {};
Keystone.prototype.console.err = function (type, msg) {
	if (keystone.get('logger')) {
		var dashes = '\n------------------------------------------------\n';
		console.log(dashes + 'KeystoneJS: ' + type + ':\n\n' + msg + dashes);
	}
};

/**
 * Keystone version
 *
 * @api public
 */

keystone.version = require('./package.json').version;

// Expose Modules
keystone.session = require('./lib/session');
<commit_msg>missing lodash migration<commit_after>var _ = require('lodash');
var express = require('express');
var fs = require('fs');
var grappling = require('grappling-hook');
var path = require('path');
var utils = require('keystone-utils');

/**
 * Don't use process.cwd() as it breaks module encapsulation
 * Instead, let's use module.parent if it's present, or the module itself if there is no parent (probably testing keystone directly if that's the case)
 * This way, the consuming app/module can be an embedded node_module and path resolutions will still work
 * (process.cwd() breaks module encapsulation if the consuming app/module is itself a node_module)
 */
var moduleRoot = (function (_rootPath) {
	var parts = _rootPath.split(path.sep);
	parts.pop(); // get rid of /node_modules from the end of the path
	return parts.join(path.sep);
})(module.parent ? module.parent.paths[0] : module.paths[0]);

/**
 * Keystone Class
 *
 * @api public
 */
var Keystone = function () {
	grappling.mixin(this).allowHooks('pre:static', 'pre:bodyparser', 'pre:session', 'pre:routes', 'pre:render', 'updates', 'signout', 'signin', 'pre:logger');
	this.lists = {};
	this.paths = {};
	this._options = {
		'name': 'Keystone',
		'brand': 'Keystone',
		'admin path': 'keystone',
		'compress': true,
		'headless': false,
		'logger': ':method :url :status :response-time ms',
		'auto update': false,
		'model prefix': null,
		'module root': moduleRoot,
		'frame guard': 'sameorigin',
	};
	this._redirects = {};

	// expose express
	this.express = express;

	// init environment defaults
	this.set('env', process.env.NODE_ENV || 'development');

	this.set('port', process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT);
	this.set('host', process.env.HOST || process.env.IP || process.env.OPENSHIFT_NODEJS_IP);
	this.set('listen', process.env.LISTEN);

	this.set('ssl', process.env.SSL);
	this.set('ssl port', process.env.SSL_PORT);
	this.set('ssl host', process.env.SSL_HOST || process.env.SSL_IP);
	this.set('ssl key', process.env.SSL_KEY);
	this.set('ssl cert', process.env.SSL_CERT);

	this.set('cookie secret', process.env.COOKIE_SECRET);
	this.set('cookie signin', (this.get('env') === 'development') ? true : false);

	this.set('embedly api key', process.env.EMBEDLY_API_KEY || process.env.EMBEDLY_APIKEY);
	this.set('mandrill api key', process.env.MANDRILL_API_KEY || process.env.MANDRILL_APIKEY);
	this.set('mandrill username', process.env.MANDRILL_USERNAME);
	this.set('google api key', process.env.GOOGLE_BROWSER_KEY);
	this.set('google server api key', process.env.GOOGLE_SERVER_KEY);
	this.set('ga property', process.env.GA_PROPERTY);
	this.set('ga domain', process.env.GA_DOMAIN);
	this.set('chartbeat property', process.env.CHARTBEAT_PROPERTY);
	this.set('chartbeat domain', process.env.CHARTBEAT_DOMAIN);
	this.set('allowed ip ranges', process.env.ALLOWED_IP_RANGES);

	if (process.env.S3_BUCKET && process.env.S3_KEY && process.env.S3_SECRET) {
		this.set('s3 config', { bucket: process.env.S3_BUCKET, key: process.env.S3_KEY, secret: process.env.S3_SECRET, region: process.env.S3_REGION });
	}

	if (process.env.AZURE_STORAGE_ACCOUNT && process.env.AZURE_STORAGE_ACCESS_KEY) {
		this.set('azurefile config', { account: process.env.AZURE_STORAGE_ACCOUNT, key: process.env.AZURE_STORAGE_ACCESS_KEY });
	}

	if (process.env.CLOUDINARY_URL) {
		// process.env.CLOUDINARY_URL is processed by the cloudinary package when this is set
		this.set('cloudinary config', true);
	}

	// init mongoose
	this.set('mongoose', require('mongoose'));

	// Attach middleware packages, bound to this instance
	this.middleware = {
		api: require('./lib/middleware/api')(this),
		cors: require('./lib/middleware/cors')(this),
	};
};

_.extend(Keystone.prototype, require('./lib/core/options')());

Keystone.prototype.prefixModel = function (key) {
	var modelPrefix = this.get('model prefix');

	if (modelPrefix) {
		key = modelPrefix + '_' + key;
	}

	return require('mongoose/lib/utils').toCollectionName(key);
};

/* Attach core functionality to Keystone.prototype */
Keystone.prototype.createItems = require('./lib/core/createItems');
Keystone.prototype.getOrphanedLists = require('./lib/core/getOrphanedLists');
Keystone.prototype.importer = require('./lib/core/importer');
Keystone.prototype.init = require('./lib/core/init');
Keystone.prototype.initDatabase = require('./lib/core/initDatabase');
Keystone.prototype.initExpressApp = require('./lib/core/initExpressApp');
Keystone.prototype.initExpressSession = require('./lib/core/initExpressSession');
Keystone.prototype.initNav = require('./lib/core/initNav');
Keystone.prototype.list = require('./lib/core/list');
Keystone.prototype.openDatabaseConnection = require('./lib/core/openDatabaseConnection');
Keystone.prototype.populateRelated = require('./lib/core/populateRelated');
Keystone.prototype.redirect = require('./lib/core/redirect');
Keystone.prototype.render = require('./lib/core/render');
Keystone.prototype.start = require('./lib/core/start');
Keystone.prototype.wrapHTMLError = require('./lib/core/wrapHTMLError');

/**
 * The exports object is an instance of Keystone.
 *
 * @api public
 */
var keystone = module.exports = new Keystone();

// Expose modules and Classes
keystone.Admin = {
	Server: require('./admin/server'),
};
keystone.Email = require('./lib/email');
keystone.Field = require('./fields/types/Type');
keystone.Field.Types = require('./lib/fieldTypes');
keystone.Keystone = Keystone;
keystone.List = require('./lib/list');
keystone.View = require('./lib/view');

keystone.content = require('./lib/content');
keystone.security = {
	csrf: require('./lib/security/csrf'),
};
keystone.utils = utils;

/**
 * returns all .js modules (recursively) in the path specified, relative
 * to the module root (where the keystone project is being consumed from).
 *
 * ####Example:
 *
 *     var models = keystone.import('models');
 *
 * @param {String} dirname
 * @api public
 */

Keystone.prototype.import = function (dirname) {

	var initialPath = path.join(this.get('module root'), dirname);

	var doImport = function (fromPath) {

		var imported = {};

		fs.readdirSync(fromPath).forEach(function (name) {

			var fsPath = path.join(fromPath, name);
			var info = fs.statSync(fsPath);

			// recur
			if (info.isDirectory()) {
				imported[name] = doImport(fsPath);
			} else {
				// only import files that we can `require`
				var ext = path.extname(name);
				var base = path.basename(name, ext);
				if (require.extensions[ext]) {
					imported[base] = require(fsPath);
				}
			}

		});

		return imported;
	};

	return doImport(initialPath);
};

/**
 * Applies Application updates
 */

Keystone.prototype.applyUpdates = function (callback) {
	var self = this;
	self.callHook('pre:updates', function (err) {
		if (err) return callback(err);
		require('./lib/updates').apply(function (err) {
			if (err) return callback(err);
			self.callHook('post:updates', callback);
		});
	});
};

/**
 * Logs a configuration error to the console
 *
 * @api public
 */

Keystone.prototype.console = {};
Keystone.prototype.console.err = function (type, msg) {
	if (keystone.get('logger')) {
		var dashes = '\n------------------------------------------------\n';
		console.log(dashes + 'KeystoneJS: ' + type + ':\n\n' + msg + dashes);
	}
};

/**
 * Keystone version
 *
 * @api public
 */

keystone.version = require('./package.json').version;

// Expose Modules
keystone.session = require('./lib/session');
<|endoftext|>


<commit_before>var acornToEsprima = require("./acorn-to-esprima");
var traverse       = require("babel-core").traverse;
var assign         = require("lodash.assign");
var Module         = require("module");
var parse          = require("babel-core").parse;
var path           = require("path");
var t              = require("babel-core").types;

var estraverse;
var hasPatched = false;

function createModule(filename) {
  var mod = new Module(filename);
  mod.filename = filename;
  mod.paths = Module._nodeModulePaths(path.dirname(filename));
  return mod;
}

function monkeypatch() {
  if (hasPatched) return;
  hasPatched = true;

  var eslintLoc;
  try {
    eslintLoc = Module._resolveFilename("eslint", module.parent);
  } catch (err) {
    throw new ReferenceError("couldn't resolve eslint");
  }

  // get modules relative to what eslint will load
  var eslintMod = createModule(eslintLoc);
  var escopeLoc = Module._resolveFilename("escope", eslintMod);
  var escopeMod = createModule(escopeLoc);

  // monkeypatch estraverse
  estraverse = escopeMod.require("estraverse");
  assign(estraverse.VisitorKeys, t.VISITOR_KEYS);

  // monkeypatch escope
  var escope  = require(escopeLoc);
  var analyze = escope.analyze;
  escope.analyze = function (ast, opts) {
    opts.ecmaVersion = 6;
    opts.sourceType = "module";
    // Don't visit TypeAlias when analyzing scope, but retain them for other
    // eslint rules.
    var TypeAliasKeys = estraverse.VisitorKeys.TypeAlias;
    estraverse.VisitorKeys.TypeAlias = [];
    var results = analyze.call(this, ast, opts);
    estraverse.VisitorKeys.TypeAlias = TypeAliasKeys;
    return results;
  };
}

exports.attachComments = function(ast, comments, tokens) {
  estraverse.attachComments(ast, comments, tokens);

  if (comments.length) {
    var firstComment = comments[0];
    var lastComment = comments[comments.length - 1];
    // fixup program start
    if (!tokens.length) {
      // if no tokens, the program starts at the end of the last comment
      ast.range[0] = lastComment.range[1];
      ast.loc.start.line = lastComment.loc.end.line;
      ast.loc.start.column = lastComment.loc.end.column;
    } else if (firstComment.start < tokens[0].range[0]) {
      // if there are comments before the first token, the program starts at the first token
      var token = tokens[0];
      ast.range[0] = token.range[0];
      ast.loc.start.line = token.loc.start.line;
      ast.loc.start.column = token.loc.start.column;

      // estraverse do not put leading comments on first node when the comment
      // appear before the first token
      if (ast.body.length) {
        var node = ast.body[0];
        node.leadingComments = [];
        var firstTokenStart = token.range[0];
        var len = comments.length;
        for(var i = 0; i < len && comments[i].start < firstTokenStart; i++ ) {
          node.leadingComments.push(comments[i]);
        }
      }
    }
    // fixup program end
    if (tokens.length) {
      var lastToken = tokens[tokens.length - 1];
      if (lastComment.end > lastToken.range[1]) {
        // If there is a comment after the last token, the program ends at the
        // last token and not the comment
        ast.range[1] = lastToken.range[1];
        ast.loc.end.line = lastToken.loc.end.line;
        ast.loc.end.column = lastToken.loc.end.column;
      }
    }
  }
};

exports.parse = function (code) {
  try {
    monkeypatch();
  } catch (err) {
    console.error(err.stack);
    process.exit(1);
  }

  var opts = {
    locations: true,
    ranges: true,
  };

  var comments = opts.onComment = [];
  var tokens = opts.onToken = [];

  var ast;
  try {
    ast = parse(code, opts);
  } catch (err) {
    if (err instanceof SyntaxError) {
      err.lineNumber = err.loc.line;
      err.column = err.loc.column;

      // remove trailing "(LINE:COLUMN)" acorn message and add in esprima syntax error message start
      err.message = "Line X: " + err.message.replace(/ \((\d+):(\d+)\)$/, "");
    }

    throw err;
  }

  // remove EOF token, eslint doesn't use this for anything and it interferes with some rules
  // see https://github.com/babel/babel-eslint/issues/2 for more info
  // todo: find a more elegant way to do this
  tokens.pop();

  // convert tokens
  ast.tokens = tokens.map(acornToEsprima.toToken);

  // add comments
  ast.comments = comments;
  exports.attachComments(ast, comments, tokens);

  // transform esprima and acorn divergent nodes
  acornToEsprima.toAST(ast);

  return ast;
};
<commit_msg>also patch estraverse-fb - fixes #73<commit_after>var acornToEsprima = require("./acorn-to-esprima");
var traverse       = require("babel-core").traverse;
var assign         = require("lodash.assign");
var Module         = require("module");
var parse          = require("babel-core").parse;
var path           = require("path");
var t              = require("babel-core").types;

var estraverse;
var hasPatched = false;

function createModule(filename) {
  var mod = new Module(filename);
  mod.filename = filename;
  mod.paths = Module._nodeModulePaths(path.dirname(filename));
  return mod;
}

function monkeypatch() {
  if (hasPatched) return;
  hasPatched = true;

  var eslintLoc;
  try {
    eslintLoc = Module._resolveFilename("eslint", module.parent);
  } catch (err) {
    throw new ReferenceError("couldn't resolve eslint");
  }

  // get modules relative to what eslint will load
  var eslintMod = createModule(eslintLoc);
  var escopeLoc = Module._resolveFilename("escope", eslintMod);
  var escopeMod = createModule(escopeLoc);

  // monkeypatch estraverse
  estraverse = escopeMod.require("estraverse");
  assign(estraverse.VisitorKeys, t.VISITOR_KEYS);

  // monkeypatch estraverse-fb
  var estraverseFb = eslintMod.require("estraverse-fb");
  assign(estraverseFb.VisitorKeys, t.VISITOR_KEYS);

  // monkeypatch escope
  var escope  = require(escopeLoc);
  var analyze = escope.analyze;
  escope.analyze = function (ast, opts) {
    opts.ecmaVersion = 6;
    opts.sourceType = "module";
    // Don't visit TypeAlias when analyzing scope, but retain them for other
    // eslint rules.
    var TypeAliasKeys = estraverse.VisitorKeys.TypeAlias;
    estraverse.VisitorKeys.TypeAlias = [];
    var results = analyze.call(this, ast, opts);
    estraverse.VisitorKeys.TypeAlias = TypeAliasKeys;
    return results;
  };
}

exports.attachComments = function(ast, comments, tokens) {
  estraverse.attachComments(ast, comments, tokens);

  if (comments.length) {
    var firstComment = comments[0];
    var lastComment = comments[comments.length - 1];
    // fixup program start
    if (!tokens.length) {
      // if no tokens, the program starts at the end of the last comment
      ast.range[0] = lastComment.range[1];
      ast.loc.start.line = lastComment.loc.end.line;
      ast.loc.start.column = lastComment.loc.end.column;
    } else if (firstComment.start < tokens[0].range[0]) {
      // if there are comments before the first token, the program starts at the first token
      var token = tokens[0];
      ast.range[0] = token.range[0];
      ast.loc.start.line = token.loc.start.line;
      ast.loc.start.column = token.loc.start.column;

      // estraverse do not put leading comments on first node when the comment
      // appear before the first token
      if (ast.body.length) {
        var node = ast.body[0];
        node.leadingComments = [];
        var firstTokenStart = token.range[0];
        var len = comments.length;
        for(var i = 0; i < len && comments[i].start < firstTokenStart; i++ ) {
          node.leadingComments.push(comments[i]);
        }
      }
    }
    // fixup program end
    if (tokens.length) {
      var lastToken = tokens[tokens.length - 1];
      if (lastComment.end > lastToken.range[1]) {
        // If there is a comment after the last token, the program ends at the
        // last token and not the comment
        ast.range[1] = lastToken.range[1];
        ast.loc.end.line = lastToken.loc.end.line;
        ast.loc.end.column = lastToken.loc.end.column;
      }
    }
  }
};

exports.parse = function (code) {
  try {
    monkeypatch();
  } catch (err) {
    console.error(err.stack);
    process.exit(1);
  }

  var opts = {
    locations: true,
    ranges: true,
  };

  var comments = opts.onComment = [];
  var tokens = opts.onToken = [];

  var ast;
  try {
    ast = parse(code, opts);
  } catch (err) {
    if (err instanceof SyntaxError) {
      err.lineNumber = err.loc.line;
      err.column = err.loc.column;

      // remove trailing "(LINE:COLUMN)" acorn message and add in esprima syntax error message start
      err.message = "Line X: " + err.message.replace(/ \((\d+):(\d+)\)$/, "");
    }

    throw err;
  }

  // remove EOF token, eslint doesn't use this for anything and it interferes with some rules
  // see https://github.com/babel/babel-eslint/issues/2 for more info
  // todo: find a more elegant way to do this
  tokens.pop();

  // convert tokens
  ast.tokens = tokens.map(acornToEsprima.toToken);

  // add comments
  ast.comments = comments;
  exports.attachComments(ast, comments, tokens);

  // transform esprima and acorn divergent nodes
  acornToEsprima.toAST(ast);

  return ast;
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Dependencies.
 */

var information,
    nlcstToString;

information = require('./data/emoticon.json');
nlcstToString = require('nlcst-to-string');

/**
 * Constants: node types.
 */

var EMOTICON_NODE;

EMOTICON_NODE = 'EmoticonNode';

/**
 * Constants: magic numbers.
 *
 * Emoticons are treated by a parser as multiple nodes.
 * Because this modifier walks forwards, when a non-
 * emoticon matches it would normaly walk to the end
 * (the last node). However, because the longest emoticon
 * is tokenized as `Punctuation` (eyes), `Punctuation`
 * (a tear), `Punctuation` (another tear), `Punctuation`
 * (a nose), and `Punctuation` (a frowning mouth), we can
 * safely break when the modifier has walked 5 characters.
 */

var MAX_EMOTICON_LENGTH;

MAX_EMOTICON_LENGTH = 5;

/**
 * Constants: info.
 */

var emoticons,
    start,
    end;

emoticons = information.emoticons;
start = information.start;
end = information.end;

start = new RegExp(start.join('|'));

/**
 * Merge emoticons into an `EmoticonNode`.
 *
 * @param {CSTNode} child
 * @param {number} index
 * @param {CSTNode} parent
 * @return {undefined|number} - Either void, or the
 *   next index to iterate over.
 */

function mergeEmoticons(child, index, parent) {
    var siblings,
        siblingIndex,
        node,
        value,
        subvalue;

    /**
     * Check if `child`s first character could be used
     * to start an emoticon.
     */

    if (start.test(nlcstToString(child).charAt(0))) {
        siblings = parent.children;

        value = '';

        siblingIndex = index;

        node = child;

        while (node) {
            if (value.length >= MAX_EMOTICON_LENGTH) {
                return;
            }

            subvalue = nlcstToString(node);

            value += subvalue;

            /**
             * The second test, if the last character of
             * the current node is superfluous but
             * improves performance by 30%.
             */

            if (
                node.type !== EMOTICON_NODE &&
                end.indexOf(subvalue.charAt(subvalue.length - 1)) !== -1 &&
                emoticons.indexOf(value) !== -1
            ) {
                siblings.splice(index + 1, siblingIndex - index);

                child.type = EMOTICON_NODE;
                child.value = value;

                /**
                 * Some emoticons, like `:-`, can be followed by
                 * more characters to form other emoticons.
                 */

                return index - 1;
            }

            node = siblings[++siblingIndex];
        }
    }
}

var emoticonModifier;

function attach(parser) {
    if (!parser || !parser.parse) {
        throw new Error(
            '`parser` is not a valid parser for ' +
            '`attach(parser)`. Make sure something ' +
            'like `parse-latin` is passed.'
        );
    }

    /**
     * Make sure to not re-attach the modifiers.
     */

    if (!emoticonModifier) {
        emoticonModifier = parser.constructor.modifier(mergeEmoticons);
    }

    parser.useFirst('tokenizeSentence', emoticonModifier);
}

/**
 * Expose `attach`.
 */

module.exports = attach;
<commit_msg>Fix bug when adding a `value` to a Parent<commit_after>'use strict';

/**
 * Dependencies.
 */

var information,
    nlcstToString;

information = require('./data/emoticon.json');
nlcstToString = require('nlcst-to-string');

/**
 * Constants: node types.
 */

var EMOTICON_NODE;

EMOTICON_NODE = 'EmoticonNode';

/**
 * Constants: magic numbers.
 *
 * Emoticons are treated by a parser as multiple nodes.
 * Because this modifier walks forwards, when a non-
 * emoticon matches it would normaly walk to the end
 * (the last node). However, because the longest emoticon
 * is tokenized as `Punctuation` (eyes), `Punctuation`
 * (a tear), `Punctuation` (another tear), `Punctuation`
 * (a nose), and `Punctuation` (a frowning mouth), we can
 * safely break when the modifier has walked 5 characters.
 */

var MAX_EMOTICON_LENGTH;

MAX_EMOTICON_LENGTH = 5;

/**
 * Constants: info.
 */

var emoticons,
    start,
    end;

emoticons = information.emoticons;
start = information.start;
end = information.end;

start = new RegExp(start.join('|'));

/**
 * Merge emoticons into an `EmoticonNode`.
 *
 * @param {CSTNode} child
 * @param {number} index
 * @param {CSTNode} parent
 * @return {undefined|number} - Either void, or the
 *   next index to iterate over.
 */

function mergeEmoticons(child, index, parent) {
    var siblings,
        siblingIndex,
        node,
        value,
        subvalue;

    /**
     * Check if `child`s first character could be used
     * to start an emoticon.
     */

    if (start.test(nlcstToString(child).charAt(0))) {
        siblings = parent.children;

        value = '';

        siblingIndex = index;

        node = child;

        while (node) {
            if (value.length >= MAX_EMOTICON_LENGTH) {
                return;
            }

            subvalue = nlcstToString(node);

            value += subvalue;

            /**
             * The second test, if the last character of
             * the current node is superfluous but
             * improves performance by 30%.
             */

            if (
                node.type !== EMOTICON_NODE &&
                end.indexOf(subvalue.charAt(subvalue.length - 1)) !== -1 &&
                emoticons.indexOf(value) !== -1
            ) {
                siblings.splice(index, siblingIndex - index + 1, {
                    'type': EMOTICON_NODE,
                    'value': value
                });

                /**
                 * Some emoticons, like `:-`, can be followed by
                 * more characters to form other emoticons.
                 */

                return index - 1;
            }

            node = siblings[++siblingIndex];
        }
    }
}

var emoticonModifier;

function attach(parser) {
    if (!parser || !parser.parse) {
        throw new Error(
            '`parser` is not a valid parser for ' +
            '`attach(parser)`. Make sure something ' +
            'like `parse-latin` is passed.'
        );
    }

    /**
     * Make sure to not re-attach the modifiers.
     */

    if (!emoticonModifier) {
        emoticonModifier = parser.constructor.modifier(mergeEmoticons);
    }

    parser.useFirst('tokenizeSentence', emoticonModifier);
}

/**
 * Expose `attach`.
 */

module.exports = attach;
<|endoftext|>


<commit_before>var bodyParser = require('body-parser');
var childProcess = require('child_process');
var express = require('express');
var fs = require('fs');

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

var app = express();

var TOKEN = process.env.GITHUB_TOKEN;
var REPO = config.repo;

// Clone repository.
new Promise((resolve, reject) => {
  if (fs.existsSync('aframe')) { return resolve(); }

  childProcess.spawn('git', ['clone', `https://${TOKEN}@github.com/${REPO}.git`], {
    stdio: 'inherit'
  }).on('close', resolve);
}).then(initApp);

// Git config.
// execSync('git config user.email aframebot@gmail.com');

function initApp () {
  // Set up Express.
  app.set('port', (process.env.PORT || 5000));
  app.use(bodyParser.json());
  app.get('/', function (req, res) {
    res.send('AFRO');
  })

  // Webhook handler.
  app.post('/postreceive', function handler (req, res) {
    var data = req.body;

    console.log(`Received message for ${data.repository.full_name}.`);

    if (data.repository.full_name === 'aframevr/aframe') {
      bumpAframeDist(data);
    }

    res.send(data);
  })

  // Express listen.
  app.listen(app.get('port'), function () {
    console.log('Node app is running on port', app.get('port'));
  })
}

/**
 * Bump A-Frame master build on every commit.
 */
function bumpAframeDist (data) {
  if (!hasAframeCodeChanges(data)) { return Promise.resolve(false); }

  console.log('Bumping aframevr/aframe dist...');
  return new Promise(resolve => {
    exec([
      'git pull --rebase origin master',
      'npm install',
      'npm run dist',
      'git commit -m "bump dist"',
      `git push https://${TOKEN}@github.com/${REPO}.git master`
    ].join(' && '), {cwd: 'aframe', stdio: 'inherit'}, (err, stdout, stderr) => {
      resolve(true);
    });
  });
}
module.exports.bumpAframeDist = bumpAframeDist;

/**
 * Check if A-Frame commit has actual code changes.
 */
function hasAframeCodeChanges (data) {
  return data.head_commit.modified.filter(function (file) {
    return file.indexOf('src/') === 0 || file.indexOf('vendor/') === 0 ||
           file === 'package.json';
  }).length !== 0;
}
module.exports.hasAframeCodeChanges = hasAframeCodeChanges;
<commit_msg>test repo<commit_after>var bodyParser = require('body-parser');
var childProcess = require('child_process');
var express = require('express');
var fs = require('fs');

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

var app = express();

var TOKEN = process.env.GITHUB_TOKEN;
var REPO = config.repo;

// Clone repository.
new Promise((resolve, reject) => {
  if (fs.existsSync('aframe')) { return resolve(); }

  childProcess.spawn('git', ['clone', `https://${TOKEN}@github.com/${REPO}.git`], {
    stdio: 'inherit'
  }).on('close', resolve);
}).then(initApp);

// Git config.
// execSync('git config user.email aframebot@gmail.com');

function initApp () {
  // Set up Express.
  app.set('port', (process.env.PORT || 5000));
  app.use(bodyParser.json());
  app.get('/', function (req, res) {
    res.send('AFRO');
  })

  // Webhook handler.
  app.post('/postreceive', function handler (req, res) {
    var data = req.body;

    console.log(`Received message for ${data.repository.full_name}.`);

    if (data.repository.full_name === REPO) {
      bumpAframeDist(data);
    }

    res.send(data);
  })

  // Express listen.
  app.listen(app.get('port'), function () {
    console.log('Node app is running on port', app.get('port'));
  })
}

/**
 * Bump A-Frame master build on every commit.
 */
function bumpAframeDist (data) {
  if (!hasAframeCodeChanges(data)) { return Promise.resolve(false); }

  console.log('Bumping aframevr/aframe dist...');
  return new Promise(resolve => {
    exec([
      'git pull --rebase origin master',
      'npm install',
      'npm run dist',
      'git commit -m "bump dist"',
      `git push https://${TOKEN}@github.com/${REPO}.git master`
    ].join(' && '), {cwd: 'aframe', stdio: 'inherit'}, (err, stdout, stderr) => {
      resolve(true);
    });
  });
}
module.exports.bumpAframeDist = bumpAframeDist;

/**
 * Check if A-Frame commit has actual code changes.
 */
function hasAframeCodeChanges (data) {
  return data.head_commit.modified.filter(function (file) {
    return file.indexOf('src/') === 0 || file.indexOf('vendor/') === 0 ||
           file === 'package.json';
  }).length !== 0;
}
module.exports.hasAframeCodeChanges = hasAframeCodeChanges;
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';
var path = require('path');

module.exports = {
  name: 'ember-cli-jquery-datatables',
	blueprintsPath: function() {
		return path.join(__dirname, 'blueprints');
	},

	included: function(app) {
		this._super.included(app);

		var _dt = app.options.datatables || {
			// import core
			core: true,
			legacy: false,

			// import core css
			// datatables, bootstrap, jqueryui, or foundation
			// false, 'dt', 'bs', 'jqui', or 'zf'
			style: false,

			// import extensions
			// 'autofill',
			// 'buttons',
			// 'colreorder',
			// 'fixedcolumns',
			// 'fixedheader',
			// 'keytable',
			// 'responsive',
			// 'scroller',
			// 'select'
			extensions: [],

		};

		var styleMap = {
			dt: 'dataTables',
			bs: 'bootstrap',
			jqui: 'jqueryui',
			zf: 'foundation'
		};

		// packages with js in style
		var extHasJs = {
			buttons: true,
			responsive: true,
			autofill: true,
		};

		var corePath = 'datatables.net';
		var core = 'jquery.dataTables.js';
		var packages = [];

		if (_dt.legacy) { this.app.import(app.bowerDirectory + '/datatables/media/js/jquery.dataTables.js'); }

		if (_dt.core) {
			packages.push(path.join(corePath, 'js', core));

			if (_dt.style && styleMap.hasOwnProperty(_dt.style)) {
				if (_dt.style === 'dt') {
					packages.push(path.join([corePath,_dt.style].join('-'), 'css', 'jquery.dataTables.css'));
				} else {
					// other packages
					packages.push(path.join([corePath,_dt.style].join('-'), 'css', ['dataTables',styleMap[_dt.style],'css'].join('.')));
					packages.push(path.join([corePath,_dt.style].join('-'), 'js', ['dataTables',styleMap[_dt.style],'js'].join('.')));
				}
			}

			_dt.extensions.forEach(function(ext){
				packages.push(path.join([corePath, ext].join('-'), 'js', ['dataTables', ext, 'js'].join('.')));

				if (_dt.style && styleMap.hasOwnProperty(_dt.style)) {
					packages.push(path.join([corePath,ext,_dt.style].join('-'), 'css', [ext, styleMap[_dt.style],'css'].join('.')));

					// some extensions require js as well
					if (_dt.style !== 'dt' && extHasJs[ext] === true) {
						packages.push(path.join([corePath,ext,_dt.style].join('-'), 'js', [ext, styleMap[_dt.style],'js'].join('.')));
					}
				}
			});

			console.log(packages);
			console.log(app.bowerDirectory);
			packages.forEach(function(pkg) {
				console.log(pkg);
				this.app.import(app.bowerDirectory + '/' + pkg);
			}, this);

		}
	}
};
<commit_msg>removed console.logs<commit_after>/* jshint node: true */
'use strict';
var path = require('path');

module.exports = {
  name: 'ember-cli-jquery-datatables',
	blueprintsPath: function() {
		return path.join(__dirname, 'blueprints');
	},

	included: function(app) {
		this._super.included(app);

		var _dt = app.options.datatables || {
			// import core
			core: true,
			legacy: false,

			// import core css
			// datatables, bootstrap, jqueryui, or foundation
			// false, 'dt', 'bs', 'jqui', or 'zf'
			style: false,

			// import extensions
			// 'autofill',
			// 'buttons',
			// 'colreorder',
			// 'fixedcolumns',
			// 'fixedheader',
			// 'keytable',
			// 'responsive',
			// 'scroller',
			// 'select'
			extensions: [],

		};

		var styleMap = {
			dt: 'dataTables',
			bs: 'bootstrap',
			jqui: 'jqueryui',
			zf: 'foundation'
		};

		// packages with js in style
		var extHasJs = {
			buttons: true,
			responsive: true,
			autofill: true,
		};

		var corePath = 'datatables.net';
		var core = 'jquery.dataTables.js';
		var packages = [];

		if (_dt.legacy) { this.app.import(app.bowerDirectory + '/datatables/media/js/jquery.dataTables.js'); }

		if (_dt.core) {
			packages.push(path.join(corePath, 'js', core));

			if (_dt.style && styleMap.hasOwnProperty(_dt.style)) {
				if (_dt.style === 'dt') {
					packages.push(path.join([corePath,_dt.style].join('-'), 'css', 'jquery.dataTables.css'));
				} else {
					// other packages
					packages.push(path.join([corePath,_dt.style].join('-'), 'css', ['dataTables',styleMap[_dt.style],'css'].join('.')));
					packages.push(path.join([corePath,_dt.style].join('-'), 'js', ['dataTables',styleMap[_dt.style],'js'].join('.')));
				}
			}

			_dt.extensions.forEach(function(ext){
				packages.push(path.join([corePath, ext].join('-'), 'js', ['dataTables', ext, 'js'].join('.')));

				if (_dt.style && styleMap.hasOwnProperty(_dt.style)) {
					packages.push(path.join([corePath,ext,_dt.style].join('-'), 'css', [ext, styleMap[_dt.style],'css'].join('.')));

					// some extensions require js as well
					if (_dt.style !== 'dt' && extHasJs[ext] === true) {
						packages.push(path.join([corePath,ext,_dt.style].join('-'), 'js', [ext, styleMap[_dt.style],'js'].join('.')));
					}
				}
			});

			packages.forEach(function(pkg) {
				this.app.import(app.bowerDirectory + '/' + pkg);
			}, this);

		}
	}
};
<|endoftext|>


<commit_before>//var bt = Windows.Devices.Bluetooth;
//var deviceWatcher = Windows.Devices.Enumeration.DeviceWatcher;
var deviceWatcher = null;
var devices = new Array();
var devicesScanned = 0;

// Check for the Windows namespace
if (typeof Windows !== 'undefined') {
    // The Windows APIs are projected in the DOM
    //deviceWatcher = Windows.Devices.Enumeration.DeviceWatcher;
}
document.addEventListener("DOMContentLoaded", function () {
    document.getElementById("enumerateBtn").addEventListener("click", handleEnumerateBtnClick);
    document.getElementById("reloadBtn").addEventListener("click", reload);
    hideloader();
    deviceWatcher = null;
});

function handleEnumerateBtnClick(evt) {
    console.log("enumerateBtnClick occured");
    if (typeof Windows !== 'undefined') {

        if (deviceWatcher == null) {
            deviceWatcher = Windows.Devices.Enumeration.DeviceWatcher;
            startBleDeviceWatcher();
        } else {

        }
    }
}

function startBleDeviceWatcher() {
    requestedProperties = ["System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected"];
    deviceWatcher = Windows.Devices.Enumeration.DeviceInformation.createWatcher(
        'System.Devices.Aep.ProtocolId:="{bb7bb05e-5972-42b5-94fc-76eaa7084d49}"',
        requestedProperties,
        Windows.Devices.Enumeration.DeviceInformationKind.associationEndpoint);

    deviceWatcher.addEventListener("added", deviceWatcherAdded);
    deviceWatcher.addEventListener("updated", deviceWatcherUpdated);
    deviceWatcher.addEventListener("removed", deviceWatcherRemoved);
    deviceWatcher.addEventListener("enumerationcompleted", deviceWatcherEnumerationCompleted);
    deviceWatcher.addEventListener("stopped", deviceWatcherStopped);

    showloader();
    deviceWatcher.start();
}

function deviceWatcherAdded(evt) {
    console.log("deviceWatcherAdded");
    // Add device information to devices array
    devices.push(evt.detail[0]);
    document.querySelector("#found").innerHTML = (++devicesScanned);
}

function deviceWatcherUpdated(evt) {
    console.log("deviceWatcherUpdated");
}

function deviceWatcherRemoved(evt) {
    console.log("deviceWatcherRemoved");
}

function deviceWatcherEnumerationCompleted(evt) {
    console.log("deviceWatcherEnumerationCompleted");
    displayDevices();
}

function deviceWatcherStopped(evt) {
    console.log("deviceWatcherStopped");
}

function displayDevices() {
    hideloader();
    var deviceAnchorElement = document.getElementById("devices")
    for (var i = 0; i < devices.length; i++) {
        var deviceDiv = document.createElement("div");
        var id = document.createAttribute("id");
        id.value = devices[i].id;
        var t = document.createTextNode(devices[i].name);
        deviceDiv.setAttributeNode(id);
        deviceDiv.appendChild(t);
        deviceAnchorElement.appendChild(deviceDiv);
    }
}

function hideloader(){
    document.getElementById("loader").style.display = 'none';
}

function showloader(){
    document.getElementById("loader").style.display = 'block';
}

function reload(){
    document.location.reload(true);
}<commit_msg>updating device list faster<commit_after>//var bt = Windows.Devices.Bluetooth;
//var deviceWatcher = Windows.Devices.Enumeration.DeviceWatcher;
var deviceWatcher = null;
var devices = new Array();
var devicesScanned = 0;

// Check for the Windows namespace
if (typeof Windows !== 'undefined') {
    // The Windows APIs are projected in the DOM
}
document.addEventListener("DOMContentLoaded", function () {
    // Setup initial page state
    document.getElementById("enumerateBtn").addEventListener("click", handleEnumerateBtnClick);
    document.getElementById("reloadBtn").addEventListener("click", reload);
    hideloader();
    deviceWatcher = null;
});

function handleEnumerateBtnClick(evt) {
    console.log("enumerateBtnClick occured");
    // Check for Windows namespace
    if (typeof Windows !== 'undefined') {
        if (deviceWatcher == null) {
            deviceWatcher = Windows.Devices.Enumeration.DeviceWatcher;
            startBleDeviceWatcher();
        } else {

        }
    } else {
        console.log("Windows namespace is not defined")
    }
}

function startBleDeviceWatcher() {
    requestedProperties = ["System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected"];
    deviceWatcher = Windows.Devices.Enumeration.DeviceInformation.createWatcher(
        'System.Devices.Aep.ProtocolId:="{bb7bb05e-5972-42b5-94fc-76eaa7084d49}"',
        requestedProperties,
        Windows.Devices.Enumeration.DeviceInformationKind.associationEndpoint);

    deviceWatcher.addEventListener("added", deviceWatcherAdded);
    deviceWatcher.addEventListener("updated", deviceWatcherUpdated);
    deviceWatcher.addEventListener("removed", deviceWatcherRemoved);
    deviceWatcher.addEventListener("enumerationcompleted", deviceWatcherEnumerationCompleted);
    deviceWatcher.addEventListener("stopped", deviceWatcherStopped);

    showloader();
    deviceWatcher.start();
}

function deviceWatcherAdded(evt) {
    console.log("deviceWatcherAdded");
    // Add device information to devices array
    devices.push(evt.detail[0]);
    document.querySelector("#found").innerHTML = (++devicesScanned);
    displayDevices();
}

function deviceWatcherUpdated(evt) {
    console.log("deviceWatcherUpdated");
}

function deviceWatcherRemoved(evt) {
    console.log("deviceWatcherRemoved");
}

function deviceWatcherEnumerationCompleted(evt) {
    console.log("deviceWatcherEnumerationCompleted");
    displayDevices();
}

function deviceWatcherStopped(evt) {
    console.log("deviceWatcherStopped");
}

function displayDevices() {
    hideloader();
    var deviceAnchorElement = document.getElementById("devices");
    deviceAnchorElement.innerHTML = "";
    for (var i = 0; i < devices.length; i++) {
        var deviceDiv = document.createElement("div");
        var id = document.createAttribute("id");
        id.value = devices[i].id;
        var t = document.createTextNode(devices[i].name);
        deviceDiv.setAttributeNode(id);
        deviceDiv.appendChild(t);
        deviceAnchorElement.appendChild(deviceDiv);
    }
}

function hideloader(){
    document.getElementById("loader").style.display = 'none';
}

function showloader(){
    document.getElementById("loader").style.display = 'block';
}

function reload(){
    document.location.reload(true);
}<|endoftext|>