<commit_before>/*
 * Copyright (c) 2012 Gregory Jackson. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, event, showFullListDialog */

/* Special HTML Characters Extension
    to insert special HTML character codes
*/
define(function (require, exports, module) {
    'use strict';

    var
        CommandManager = brackets.getModule('command/CommandManager'),
        Menus = brackets.getModule('command/Menus'),
        EditorManager = brackets.getModule('editor/EditorManager'),
        ExtensionUtils = brackets.getModule('utils/ExtensionUtils'),
        DocumentManager = brackets.getModule('document/DocumentManager'),
        SpecialChars = require('text!specialHTMLChars.json'),
        specialChars = JSON.parse(SpecialChars),
        COMMAND_ID = 'specialhtmlchar.insert',
        FULLCOMMAND_ID = 'full.specialhtmlchar.insert',
        iChars,
        iCharsLen = specialChars.quickLinks.length,
        menu, editMenu, keyCommands,
        $specialCharsDialog = $('<div>', { 'class': 'specialHTMLChar' }),
        $fullSpecialCharsDialog = $('<div>', { 'class': 'specialHTMLChar full' }),
        dialogDimensions,
        Strings = require('strings');

    ExtensionUtils.loadStyleSheet(module, 'style.css');

    /* Construction of popup dialog and events */
    $specialCharsDialog.append(
        function () {
            var $ULElement = $('<ul>', { 'class': 'quick' });
            for (iChars = 0; iChars < iCharsLen; iChars++) {
                $ULElement.append(
                    $('<li>').append(
                        $('<a>', { 'href': '#', 'htmlcode': specialChars.quickLinks[iChars].code, 'text': specialChars.quickLinks[iChars].name }).prepend(
                            $('<span>', { 'class': 'quickChar', 'html': specialChars.quickLinks[iChars].code })
                        )
                    )
                );
            }
            return $ULElement;
        }
    ).append(
        $('<div>', { 'class': 'divider' }),
        $('<a>', { 'href': '#', 'class': 'more', 'text': Strings.MORE}).on('click', function () {
            showFullListDialog();
            $specialCharsDialog.hide();
        })
    ).hide().appendTo('body').on('mouseleave', function () {
        $specialCharsDialog.hide();
    }).find('ul a').on('click', function () {
        var
            cCode = $(this).attr('htmlcode'),
            doc = DocumentManager.getCurrentDocument(),
            editor = EditorManager.getCurrentFullEditor(),
            pos = editor.getCursorPos();
        doc.replaceRange(cCode, pos);
        $specialCharsDialog.hide();
        editor.focus();
    });

    iCharsLen = specialChars.full.length;
    $fullSpecialCharsDialog.append(
        function () {
            var $ULElement = $('<ul>', { 'class': 'full' });
            for (iChars = 0; iChars < iCharsLen; iChars++) {
                $ULElement.append(
                    $('<li>', { 'title': specialChars.full[iChars].title }).append(
                        $('<a>', { 'href': '#', 'htmlcode': specialChars.full[iChars].code, 'html': specialChars.full[iChars].code })
                    )
                );
            }
            return $ULElement;
        }
    ).append(
        $('<div>', { 'class': 'control' }).append(
            $('<p>', { 'text': Strings.CLICK_THE_CHARACTER_YOU_WISH_TO_INSERT }),
            $('<input>', { 'type': 'text', 'class': 'codepreview', 'name': 'fullSpecialCharsDialogCodeDisplay', 'value': '' }),
            $('<a>', { 'href': '#', 'class': 'btn', 'text': Strings.CANCEL }).on('click', function () {
                $fullSpecialCharsDialog.hide();
            })
        )
    ).hide().appendTo('body').find('ul a').on('click', function () {
        var
            cCode = $(this).attr('htmlcode'),
            doc = DocumentManager.getCurrentDocument(),
            editor = EditorManager.getCurrentFullEditor(),
            pos = editor.getCursorPos();
        doc.replaceRange(cCode, pos);
        $fullSpecialCharsDialog.hide();
        editor.focus();
    }).on('mouseenter', function () {
        $('[name=fullSpecialCharsDialogCodeDisplay]').val($(this).attr('htmlcode'));
    }).on('mouseleave', function () {
        $('[name=fullSpecialCharsDialogCodeDisplay]').val('');
    });

    dialogDimensions = {
        height: $specialCharsDialog.outerHeight(),
        width: $specialCharsDialog.outerWidth(),
        offset: 16
    };

    function showDialog() {
        $specialCharsDialog.css({
            'left': ((event.pageX + dialogDimensions.offset) > (event.view.innerWidth - dialogDimensions.width)) ? (event.view.innerWidth - dialogDimensions.width) - 31 : event.pageX - dialogDimensions.offset,
            'top': ((event.pageY + dialogDimensions.offset) > (event.view.innerHeight - dialogDimensions.height)) ? (event.view.innerHeight - dialogDimensions.height) - 68  : event.pageY - dialogDimensions.offset
        }).show();
    }

    function showFullListDialog() {
        var currentDoc = DocumentManager.getCurrentDocument();
        if (currentDoc) {
            $fullSpecialCharsDialog.css({
                'margin-left': -(622 / 2),
                'margin-top': -(520 / 2),
                'width': 620
            }).show();
        }
    }

    CommandManager.register(Strings.SPECIAL_HTML_CHARACTER, COMMAND_ID, showDialog);

    menu = Menus.getContextMenu(Menus.ContextMenuIds.EDITOR_MENU);
    if (menu) {
        menu.addMenuDivider();
        menu.addMenuItem(COMMAND_ID);
    }

    CommandManager.register(Strings.SPECIAL_HTML_CHARACTER, FULLCOMMAND_ID, showFullListDialog);

    editMenu = Menus.getMenu(Menus.AppMenuBar.EDIT_MENU);
    if (editMenu) {
        editMenu.addMenuDivider();
        editMenu.addMenuItem(FULLCOMMAND_ID, 'Alt-C');
    }

});
<commit_msg>Changed inline functions to arrow functions<commit_after>/*
 * Copyright (c) 2012-2017 Gregory Jackson. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50, esversion:6 */
/*global define, $, brackets, event, showFullListDialog */

/* Special HTML Characters Extension
 to insert special HTML character codes
 */
define(function (require, exports, module) {
    'use strict';

    const
        CommandManager = brackets.getModule('command/CommandManager'),
        Menus = brackets.getModule('command/Menus'),
        EditorManager = brackets.getModule('editor/EditorManager'),
        ExtensionUtils = brackets.getModule('utils/ExtensionUtils'),
        DocumentManager = brackets.getModule('document/DocumentManager'),
        SpecialChars = require('text!specialHTMLChars.json'),
        specialChars = JSON.parse(SpecialChars),
        COMMAND_ID = 'specialhtmlchar.insert',
        FULLCOMMAND_ID = 'full.specialhtmlchar.insert',
        $specialCharsDialog = $('<div>', {class: 'specialHTMLChar'}),
        $fullSpecialCharsDialog = $('<div>', {class: 'specialHTMLChar full'}),
        Strings = require('strings');

    let menu, editMenu, dialogDimensions, fullSpecialCharsDialogCodeDisplay;

    ExtensionUtils.loadStyleSheet(module, 'style.css');

    /* Construction of popup dialog and events */
    $specialCharsDialog.append(
        $('<ul>', {class: 'quick'}).append(
            specialChars.quickLinks.map(char => {
                return $('<li>').append(
                    $('<a>', {
                        href: '#',
                        htmlCode: char.code,
                        text: char.name
                    }).prepend(
                        $('<span>', {class: 'quickChar', 'html': char.code})
                    )
                );
            })
        ),
        $('<div>', {class: 'divider'}),
        $('<a>', {href: '#', class: 'more', text: Strings.MORE}).on('click', function () {
            showFullListDialog();
            $specialCharsDialog.hide();
        })
    ).hide().appendTo('body').on('mouseleave', function () {
        $specialCharsDialog.hide();
    }).find('ul a').on('click', writeThisChar);

    $fullSpecialCharsDialog.append(
        $('<ul>', {class: 'full'}).append(
            specialChars.full.map(char => {
                return $('<li>', {'title': char.title}).append(
                    $('<a>', {
                        href: '#',
                        htmlCode: char.code,
                        html: char.code
                    })
                );
            })
        ),
        $('<div>', {class: 'control'}).append(
            $('<p>', {text: Strings.CLICK_THE_CHARACTER_YOU_WISH_TO_INSERT}),
            fullSpecialCharsDialogCodeDisplay = $('<input>', {
                type: 'text',
                class: 'codepreview',
                name: 'fullSpecialCharsDialogCodeDisplay',
                value: ''
            }),
            $('<a>', {href: '#', class: 'btn', text: Strings.CANCEL}).on('click', function () {
                $fullSpecialCharsDialog.hide();
            })
        )
    ).hide().appendTo('body').find('ul a').on('click', writeThisChar).on('mouseenter', function () {
        fullSpecialCharsDialogCodeDisplay.val(this.attributes.htmlCode.value);
    }).on('mouseleave', function () {
        fullSpecialCharsDialogCodeDisplay.val('');
    });

    dialogDimensions = {
        height: $specialCharsDialog.outerHeight(),
        width: $specialCharsDialog.outerWidth(),
        offset: 16
    };

    function showDialog() {
        $specialCharsDialog.css({
            left: ((event.pageX + dialogDimensions.offset) > (event.view.innerWidth - dialogDimensions.width)) ? (event.view.innerWidth - dialogDimensions.width) - 31 : event.pageX - dialogDimensions.offset,
            top: ((event.pageY + dialogDimensions.offset) > (event.view.innerHeight - dialogDimensions.height)) ? (event.view.innerHeight - dialogDimensions.height) - 68 : event.pageY - dialogDimensions.offset
        }).show();
    }

    function showFullListDialog() {
        const currentDoc = DocumentManager.getCurrentDocument();

        if (currentDoc) {
            $fullSpecialCharsDialog.css({
                'margin-left': -(622 / 2),
                'margin-top': -(520 / 2),
                width: 620
            }).show();
        }
    }

    /* this function is called within the scope of the click event target */
    function writeThisChar() {
        const
            doc = DocumentManager.getCurrentDocument(),
            editor = EditorManager.getCurrentFullEditor(),
            pos = editor.getCursorPos();

        doc.replaceRange(this.attributes.htmlCode.value, pos);

        $fullSpecialCharsDialog.hide();
        editor.focus();
    }

    CommandManager.register(Strings.SPECIAL_HTML_CHARACTER, COMMAND_ID, showDialog);

    menu = Menus.getContextMenu(Menus.ContextMenuIds.EDITOR_MENU);
    if (menu) {
        menu.addMenuDivider();
        menu.addMenuItem(COMMAND_ID);
    }

    CommandManager.register(Strings.SPECIAL_HTML_CHARACTER, FULLCOMMAND_ID, showFullListDialog);

    editMenu = Menus.getMenu(Menus.AppMenuBar.EDIT_MENU);
    if (editMenu) {
        editMenu.addMenuDivider();
        editMenu.addMenuItem(FULLCOMMAND_ID, 'Alt-C');
    }

});
<|endoftext|>


<commit_before>function requestJson(text) {
    let requestUrl = "https://socialityfilter.takanakahiko.me/?text=" + text;
    let xhr = new XMLHttpRequest();
    xhr.open("GET", requestUrl, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            let json = JSON.parse(xhr.responseText);
            console.log(json.response);
            let tweetTextArea = document.querySelector(".compose-content .js-compose-text");
            tweetTextArea.value = json.response;
            $('textarea.js-compose-text')[0].dispatchEvent(new Event('change'));
            tweetTextArea.focus()
            let length = tweetTextArea.value.length
            tweetTextArea.selectionStart = length;
            tweetTextArea.selectionEnd = length;
        }
    };
    xhr.send();
}
function translateToNyaan(){
    if(!$('#filter-button').hasClass('is-disabled')){
        let tweetTextArea = document.querySelector(".compose-content .js-compose-text");
        requestJson(tweetTextArea.value);
    }
}

$(function () {
    setTimeout(function () {
        console.log("test");
        let tweetButton = $(".js-send-button-container");
        let filterButton = $("<button></button>", {
            id: "filter-button",
            class: "js-send-button js-spinner-button js-show-tip btn btn-positive btn-extra-height is-disabled",
            text:"< Nyaan",
            "data-original-title":"Nyaan (alt+n)"
        });
        tweetButton.append(filterButton);
        $('.compose-content .js-compose-text').keyup(function() {
            var val = $(this).val();
            if(val.length === 0){
                $("#filter-button").addClass("is-disabled")
            }else{
                $("#filter-button").removeClass("is-disabled");
            }
        });
        $("#filter-button").on("click", function () {
                 translateToNyaan();
        });
    }, 1000);

     $(document).keydown(function(e){
         console.log(e.keyCode)
         if(e.keyCode===78 && e.altKey){//alt+nキー
                 translateToNyaan();
            }
        });
     });
<commit_msg>Revert "chnage parse num"<commit_after>function requestJson(text) {
    let requestUrl = "https://socialityfilter.takanakahiko.me/?text=" + text;
    let xhr = new XMLHttpRequest();
    xhr.open("GET", requestUrl, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            let json = JSON.parse(xhr.responseText);
            json = JSON.parse(json);
            console.log(json.response);
            let tweetTextArea = document.querySelector(".compose-content .js-compose-text");
            tweetTextArea.value = json.response;
            $('textarea.js-compose-text')[0].dispatchEvent(new Event('change'));
            tweetTextArea.focus()
            let length = tweetTextArea.value.length
            tweetTextArea.selectionStart = length;
            tweetTextArea.selectionEnd = length;
        }
    };
    xhr.send();
}
function translateToNyaan(){
    if(!$('#filter-button').hasClass('is-disabled')){
        let tweetTextArea = document.querySelector(".compose-content .js-compose-text");
        requestJson(tweetTextArea.value);
    }
}

$(function () {
    setTimeout(function () {
        console.log("test");
        let tweetButton = $(".js-send-button-container");
        let filterButton = $("<button></button>", {
            id: "filter-button",
            class: "js-send-button js-spinner-button js-show-tip btn btn-positive btn-extra-height is-disabled",
            text:"< Nyaan",
            "data-original-title":"Nyaan (alt+n)"
        });
        tweetButton.append(filterButton);
        $('.compose-content .js-compose-text').keyup(function() {
            var val = $(this).val();
            if(val.length === 0){
                $("#filter-button").addClass("is-disabled")
            }else{
                $("#filter-button").removeClass("is-disabled");
            }
        });
        $("#filter-button").on("click", function () {
                 translateToNyaan();
        });
    }, 1000);

     $(document).keydown(function(e){
         console.log(e.keyCode)
         if(e.keyCode===78 && e.altKey){//alt+nキー
                 translateToNyaan();
            }
        });
     });
<|endoftext|>


<commit_before>const myOptionsManager = new OptionsManager();
const tldStarPattern = /^(.+)\.\*$/;
const redirectUrlPattern = /^https?:\/\/.+(https?)(:\/\/|%3A\/\/|%3A%2F%2F)(.+)$/;

function redirectUrlReplacer(match, p1, p2, p3, offset, string) {
    if (p2[0] == "%") {
        p2 = decodeURIComponent(p2);
    }
    if (/(%26|%2F)/.test(p3)) {
        p3 = p3.replace(/&.+/, "");
    }
    return p1 + p2 + filterUnwantedQueryParams(decodeURIComponent(p3));
}

function parseRedirectUrl(url) {
    return url.replace(redirectUrlPattern, redirectUrlReplacer);
}

function filterQuery(query) {
    let queryParam = query.split("=")[0];
    return !myOptionsManager.options.queryParams.includes(queryParam);
}

function filterUnwantedQueryParams(url) {
    let urlParts = url.split("?");
    for (let i = urlParts.length - 1; i >= 1; i--) {
        urlParts[i] = urlParts[i].split("&").filter(filterQuery).join("&");
        if (urlParts[i].length == 0) {
            urlParts.splice(i, 1);
        }
    }
    return urlParts.join("?");
}

function redirect(request) {
    if (request.method != "GET" || request.tabId == -1) {
        return;
    }
    let redirectUrl = parseRedirectUrl(request.url);
    if (redirectUrl.length < request.url.length) {
        chrome.tabs.update(request.tabId, {url: parseRedirectUrl(request.url)});
        return {
            cancel: true
        };
    }
}

function resolveUrls(rules) {
    let urls = [];
    for (let rule of rules) {
        if (tldStarPattern.test(rule.pattern.host)) {
            for (let TLD of rule.pattern.topLevelDomains) {
                urls.push(tldStarPatternRuleToUrl(rule.pattern, TLD));
            }
        } else {
            urls.push(patternRuleToUrl(rule.pattern));
        }
    }
    return urls;
}

function patternRuleToUrl(pattern) {
    return pattern.scheme + "://" + (pattern.matchSubDomains ? "*." : "") + pattern.host + "/" + pattern.path;
}

function tldStarPatternRuleToUrl(pattern, TLD) {
    return pattern.scheme + "://" + (pattern.matchSubDomains ? "*." : "") + pattern.host.replace(tldStarPattern, "$1." + TLD)  + "/" +  pattern.path;
}

function init() {
    chrome.webRequest.onBeforeRequest.removeListener(redirect);
    chrome.webRequest.onBeforeRequest.addListener(redirect, {
        urls: resolveUrls(myOptionsManager.options.rules),
        types: [
            "main_frame",
            "sub_frame"
        ]
    }, ["blocking"]);
}

myOptionsManager.loadOptions(init);
myOptionsManager.onChanged(init);
<commit_msg>Support for new rule and actions format<commit_after>const myOptionsManager = new OptionsManager();
const tldStarPattern = /^(.+)\.\*$/;
const redirectUrlPattern = /^https?:\/\/.+(https?)(:\/\/|%3A\/\/|%3A%2F%2F)(.+)$/;
const requestListeners = [];

function requestAction(action, redirectUrl) {
    switch (action) {
        case "filter":
            return function (request) {
                if (request.method != "GET" || request.tabId == -1) {
                    return;
                }
                let redirectUrl = parseRedirectUrl(request.url);
                if (redirectUrl.length < request.url.length) {
                    chrome.tabs.update(request.tabId, {
                        url: parseRedirectUrl(request.url)
                    });
                    return {
                        cancel: true
                    };
                }
            };
        case "block":
            return function (request) {
                return {
                    cancel: true
                };
            };
        case "redirect":
            return function (request) {
                return {
                    redirectUrl: redirectUrl
                };
            };
    }
}

function redirectUrlReplacer(match, p1, p2, p3, offset, string) {
    if (p2[0] == "%") {
        p2 = decodeURIComponent(p2);
    }
    if (/(%26|%2F)/.test(p3)) {
        p3 = p3.replace(/&.+/, "");
    }
    return p1 + p2 + filterUnwantedQueryParams(decodeURIComponent(p3));
}

function parseRedirectUrl(url) {
    return url.replace(redirectUrlPattern, redirectUrlReplacer);
}

function filterQuery(query) {
    let queryParam = query.split("=")[0];
    return !myOptionsManager.options.queryParams.includes(queryParam);
}

function filterUnwantedQueryParams(url) {
    let urlParts = url.split("?");
    for (let i = urlParts.length - 1; i >= 1; i--) {
        urlParts[i] = urlParts[i].split("&").filter(filterQuery).join("&");
        if (urlParts[i].length == 0) {
            urlParts.splice(i, 1);
        }
    }
    return urlParts.join("?");
}

function resolveUrls(pattern) {
    let urls = [];
    if (tldStarPattern.test(pattern.host)) {
        for (let TLD of pattern.topLevelDomains) {
            urls.push(tldStarPatternRuleToUrl(pattern, TLD));
        }
    } else {
        urls.push(patternRuleToUrl(pattern));
    }
    return urls;
}

function patternRuleToUrl(pattern) {
    return pattern.scheme + "://" + (pattern.matchSubDomains ? "*." : "") + pattern.host + "/" + pattern.path;
}

function tldStarPatternRuleToUrl(pattern, TLD) {
    return pattern.scheme + "://" + (pattern.matchSubDomains ? "*." : "") + pattern.host.replace(tldStarPattern, "$1." +
        TLD) + "/" + pattern.path;
}

function removePreviousListeners() {
    let listener;
    while (listener = requestListeners.pop()) {
        chrome.webRequest.onBeforeRequest.removeListener(listener);
    }
}

function addListeners() {
    let filter, listener;
    for (let rule of myOptionsManager.options.rules) {
        if (!rule.active) {
            continue;
        }
        filter = {
            urls: resolveUrls(rule.pattern),
            types: rule.types
        };
        listener = new requestAction(rule.action, rule.redirectUrl);
        chrome.webRequest.onBeforeRequest.addListener(listener, filter, ["blocking"]);
        requestListeners.push(listener);
    }
}

function init() {
    removePreviousListeners();
    addListeners();
}

myOptionsManager.loadOptions(init);
myOptionsManager.onChanged(init);
<|endoftext|>


<commit_before>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2010 elements.at New Media Solutions GmbH (http://www.elements.at)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.document.edit.dnd");
pimcore.document.edit.dnd = Class.create({

    dndManager: null,

    initialize: function(parentExt, body, iframeElement, dndZones) {

        this.dndManager = parentExt.dd.DragDropMgr;
        var iFrameElement = parent.Ext.get('document_iframe_' + window.editWindow.document.id);

        //if(!Ext.isSafari){
        parentExt.EventManager.on(body, 'mousemove', this.ddMouseMove.bind(this));
        parentExt.EventManager.on(body, 'mouseup', this.ddMouseUp.bind(this));
        //}

        var dd = new parent.Ext.dd.DropZone(iframeElement, {
            ddGroup: "element",
            validElements: dndZones,

            getTargetFromEvent: function(e) {
                var element = null;

                for (var i = 0; i < this.validElements.length; i++) {
                    element = this.validElements[i];
                    if (element.dndOver) {
                        if (element.reference) {
                            this.onNodeDrop = element.reference.onNodeDrop.bind(element.reference);
                            this.onNodeOver = element.reference.onNodeOver.bind(element.reference);
                            return element;
                        }
                    }
                }
            }
        });

        window.setInterval(this.setIframeOffset.bind(this),1000);
        this.setIframeOffset();
    },

    ddMouseMove: function (e) {
        // update the xy of the event if necessary
        this.setDDPos(e);
        // *** Note that the 'this' scope is the drag drop manager
        this.dndManager.handleMouseMove(e);
    },

    ddMouseUp : function (e) {
        // update the xy of the event if necessary
        this.setDDPos(e);
        // *** Note that the 'this' scope is the drag drop manager
        this.dndManager.handleMouseUp(e);
    },

    setDDPos: function (e) {

        var scrollTop = 0;
        var scrollLeft = 0;

        //if(Ext.isGecko || Ext.isChrome) {
        if (!Ext.isIE) {
            var doc = (window.contentDocument || window.document);
            scrollTop = doc.documentElement.scrollTop || doc.body.scrollTop;
            scrollLeft = doc.documentElement.scrollLeft || doc.body.scrollLeft;
        }

        //if(!Ext.isWebKit) {
        //if(!Ext.isSafari) {
        e.xy = [e.xy[0] + this.iframeOffset[0] - scrollLeft, e.xy[1] + this.iframeOffset[1] - scrollTop];
        //}
    },

    setIframeOffset: function () {
        try {
            this.iframeOffset = parent.Ext.get('document_iframe_' + window.editWindow.document.id).getOffsetsTo(parent.Ext.getBody());
        } catch (e) {

        }
    }

});
<commit_msg>PIMCORE-935<commit_after>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2010 elements.at New Media Solutions GmbH (http://www.elements.at)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.document.edit.dnd");
pimcore.document.edit.dnd = Class.create({

    dndManager: null,

    initialize: function(parentExt, body, iframeElement, dndZones) {

        this.dndManager = parentExt.dd.DragDropMgr;
        var iFrameElement = parent.Ext.get('document_iframe_' + window.editWindow.document.id);

        //if(!Ext.isSafari){
        parentExt.EventManager.on(body, 'mousemove', this.ddMouseMove.bind(this));
        parentExt.EventManager.on(body, 'mouseup', this.ddMouseUp.bind(this));
        //}

        var dd = new parent.Ext.dd.DropZone(iframeElement, {
            ddGroup: "element",
            validElements: dndZones,

            getTargetFromEvent: function(e) {
                var element = null;

                for (var i = 0; i < this.validElements.length; i++) {
                    element = this.validElements[i];
                    if (element.dndOver) {
                        if (element.reference) {
                            this.onNodeDrop = element.reference.onNodeDrop.bind(element.reference);
                            this.onNodeOver = element.reference.onNodeOver.bind(element.reference);
                            return element;
                        }
                    }
                }
            }
        });

        window.setInterval(this.setIframeOffset.bind(this),1000);
        this.setIframeOffset();
    },

    ddMouseMove: function (e) {
        // update the xy of the event if necessary
        this.setDDPos(e);
        // *** Note that the 'this' scope is the drag drop manager
        this.dndManager.handleMouseMove(e);
    },

    ddMouseUp : function (e) {
        // update the xy of the event if necessary
        this.setDDPos(e);
        // *** Note that the 'this' scope is the drag drop manager
        this.dndManager.handleMouseUp(e);
    },

    setDDPos: function (e) {

        var scrollTop = 0;
        var scrollLeft = 0;

        if (!Ext.isIE || parent.Ext.isIE9) {
            var doc = (window.contentDocument || window.document);
            scrollTop = doc.documentElement.scrollTop || doc.body.scrollTop;
            scrollLeft = doc.documentElement.scrollLeft || doc.body.scrollLeft;
        }

        e.xy = [e.xy[0] + this.iframeOffset[0] - scrollLeft, e.xy[1] + this.iframeOffset[1] - scrollTop];
    },

    setIframeOffset: function () {
        try {
            this.iframeOffset = parent.Ext.get('document_iframe_' + window.editWindow.document.id).getOffsetsTo(parent.Ext.getBody());
        } catch (e) {

        }
    }

});
<|endoftext|>


<commit_before>
angular.module('app.dashboard.directives').directive('dealsToCheck', dealsToCheckDirective);

function dealsToCheckDirective() {
    return {
        scope: {},
        templateUrl: 'dashboard/directives/dealstocheck.html',
        controller: DealsToCheckController,
        controllerAs: 'vm',
    };
}

DealsToCheckController.$inject = ['$scope', 'LocalStorage', 'Deal', 'UserTeams'];
function DealsToCheckController($scope, LocalStorage, Deal, UserTeams) {
    var storage = LocalStorage('dealsToCheckkWidget');
    var vm = this;

    vm.users = [];
    vm.table = {
        order: storage.get('order', {
            descending: true,
            column: 'next_step_date',  // string: current sorted column
        }),
        items: [],
        selectedUserId: storage.get('selectedUserId'),
    };
    vm.markDealAsChecked = markDealAsChecked;
    activate();

    ///////////

    function activate() {
        _watchTable();
        _getUsers();
    }

    function _getDealsToCheck() {
        if (vm.table.selectedUserId) {
            var filterQuery = 'stage:2 AND is_checked:false AND new_business:true';

            if (vm.table.selectedUserId) {
                filterQuery += ' AND assigned_to_id:' + vm.table.selectedUserId;
            }

            var dealPromise = Deal.getDeals('', 1, 20, vm.table.order.column, vm.table.order.descending, filterQuery);
            dealPromise.then(function(deals) {
                vm.table.items = deals;
            });
        }
    }

    function _getUsers() {
        UserTeams.mine(function(teams) {
            angular.forEach(teams, function(team) {
                vm.users = vm.users.concat(team.user_set);
            });
        });
    }

    function _watchTable() {
        $scope.$watchGroup(['vm.table.order.descending', 'vm.table.order.column', 'vm.table.selectedUserId'], function() {
            _getDealsToCheck();
            storage.put('order', vm.table.order);
            storage.put('selectedUserId', vm.table.selectedUserId);
        });
    }

    function markDealAsChecked(deal) {
        deal.markDealAsChecked().then(function() {
            vm.table.items.splice(vm.table.items.indexOf(deal), 1);
        });
    }
}
<commit_msg>Hide archived deals in deals to check widget<commit_after>
angular.module('app.dashboard.directives').directive('dealsToCheck', dealsToCheckDirective);

function dealsToCheckDirective() {
    return {
        scope: {},
        templateUrl: 'dashboard/directives/dealstocheck.html',
        controller: DealsToCheckController,
        controllerAs: 'vm',
    };
}

DealsToCheckController.$inject = ['$scope', 'LocalStorage', 'Deal', 'UserTeams'];
function DealsToCheckController($scope, LocalStorage, Deal, UserTeams) {
    var storage = LocalStorage('dealsToCheckkWidget');
    var vm = this;

    vm.users = [];
    vm.table = {
        order: storage.get('order', {
            descending: true,
            column: 'next_step_date',  // string: current sorted column
        }),
        items: [],
        selectedUserId: storage.get('selectedUserId'),
    };
    vm.markDealAsChecked = markDealAsChecked;
    activate();

    ///////////

    function activate() {
        _watchTable();
        _getUsers();
    }

    function _getDealsToCheck() {
        if (vm.table.selectedUserId) {
            var filterQuery = 'stage:2 AND is_checked:false AND new_business:true AND archived:false';

            if (vm.table.selectedUserId) {
                filterQuery += ' AND assigned_to_id:' + vm.table.selectedUserId;
            }

            var dealPromise = Deal.getDeals('', 1, 20, vm.table.order.column, vm.table.order.descending, filterQuery);
            dealPromise.then(function(deals) {
                vm.table.items = deals;
            });
        }
    }

    function _getUsers() {
        UserTeams.mine(function(teams) {
            angular.forEach(teams, function(team) {
                vm.users = vm.users.concat(team.user_set);
            });
        });
    }

    function _watchTable() {
        $scope.$watchGroup(['vm.table.order.descending', 'vm.table.order.column', 'vm.table.selectedUserId'], function() {
            _getDealsToCheck();
            storage.put('order', vm.table.order);
            storage.put('selectedUserId', vm.table.selectedUserId);
        });
    }

    function markDealAsChecked(deal) {
        deal.markDealAsChecked().then(function() {
            vm.table.items.splice(vm.table.items.indexOf(deal), 1);
        });
    }
}
<|endoftext|>


<commit_before>'use strict';

const electron = require('electron');
const app = electron.app;  // Module to control application life.
const BrowserWindow = electron.BrowserWindow;  // Module to create native browser window.
const localShortcut = require('electron-localshortcut');

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null;

function fullScreenHandler () {
  if (!mainWindow.isFocused()) {
    return;
  }
  if (mainWindow.isFullScreen()) {
    mainWindow.setFullScreen(false);
    return;
  }
  mainWindow.setFullScreen(true);
}

function closedHandler () {
  // Dereference the window object, usually you would store windows
  // in an array if your app supports multi windows, this is the time
  // when you should delete the corresponding element.
  mainWindow = null;
}

function readyHandler () {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600});

  // and load the index.html of the app.
  mainWindow.loadURL('file://' + __dirname + '/index.html');

  // Emitted when the window is closed.
  mainWindow.on('closed', closedHandler);

  // Register global shortcuts.
  localShortcut.register(mainWindow, 'cmd+ctrl+f', fullScreenHandler);
}

function allClosedHandler () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform != 'darwin') {
    app.quit();
  }
}

function willQuitHandler () {
  // Un-register all shortcuts.
  localShortcut.unregisterAll(mainWindow);
}

// Quit when all windows are closed.
app.on('window-all-closed', allClosedHandler);

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', readyHandler);

app.on('will-quit', willQuitHandler);
<commit_msg>Main application menu with useful shortcuts<commit_after>'use strict';

const electron = require('electron');
const app = electron.app;  // Module to control application life.
const BrowserWindow = electron.BrowserWindow;  // Module to create native browser window.
const menu = require('menu');
const localShortcut = require('electron-localshortcut');

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null;

/**
 * On full screen, check if main window is focused, and if not return.
 * If main window is focused and on full screen already then set to false
 * otherwise to full screen true.
 */
function fullScreenHandler () {
  if (!mainWindow.isFocused()) {
    return;
  }
  if (mainWindow.isFullScreen()) {
    mainWindow.setFullScreen(false);
    return;
  }
  mainWindow.setFullScreen(true);
}

/**
 * On close dereference the window object, usually you would store windows
 * in an array if your app supports multi windows, this is the time
 * when you should delete the corresponding element.
 */
function closedHandler () {
  mainWindow = null;
}

function readyHandler () {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600});

  // and load the index.html of the app.
  mainWindow.loadURL('file://' + __dirname + '/index.html');

  // Emitted when the window is closed.
  mainWindow.on('closed', closedHandler);

  // Register global shortcuts.
  localShortcut.register(mainWindow, 'Command+Ctrl+F', fullScreenHandler);

  // Create the Application's main menu.
  const template = getMenuTemplate();

  menu.setApplicationMenu(menu.buildFromTemplate(template));
}

/**
 * On OS X it is common for applications and their menu bar
 * to stay active until the user quits explicitly with Cmd + Q.
 */
function allClosedHandler () {
  if (process.platform != 'darwin') {
    app.quit();
  }
}

/**
 * Un-register all shortcuts.
 */
function willQuitHandler () {
  localShortcut.unregisterAll(mainWindow);
}

/**
 * Get the template to use for main application menu.
 * @returns {Object} The template.
 */
function getMenuTemplate () {
  return [{
    label: 'Application',
    submenu: [{
      label: 'About Zazu', selector: 'orderFrontStandardAboutPanel:'
    }, {
      type: 'separator'
    }, {
      label: 'Quit', accelerator: 'Command+Q', click: function () {
        app.quit();
      }
    }]
  }, {
    label: 'Edit',
    submenu: [{
      label: 'Undo', accelerator: 'CmdOrCtrl+Z', selector: 'undo:'
    }, {
      label: 'Redo', accelerator: 'Shift+CmdOrCtrl+Z', selector: 'redo:'
    }, {
      type: 'separator'
    }, {
      label: 'Cut', accelerator: 'CmdOrCtrl+X', selector: 'cut:'
    }, {
      label: 'Copy', accelerator: 'CmdOrCtrl+C', selector: 'copy:'
    }, {
      label: 'Paste', accelerator: 'CmdOrCtrl+V', selector: 'paste:'
    }, {
      label: 'Select All', accelerator: 'CmdOrCtrl+A', selector: 'selectAll:'
    }]
  }];
}

// Quit when all windows are closed.
app.on('window-all-closed', allClosedHandler);

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', readyHandler);

app.on('will-quit', willQuitHandler);
<|endoftext|>


<commit_before>"use strict";

// Check that the deps in node_modules match what's in package.json.
var safestart = require('safestart');
safestart(__dirname);

var app = require('app');  // Module to control application life.
var BrowserWindow = require('browser-window');  // Module to create native browser window.

// Check if we need to kick off the python server-daemon (Desktop app)
if(process.argv[2].toUpperCase() == "startserver".toUpperCase()) {
  // Kick it off
  var subpy = require('child_process').spawn('python', [__dirname + '/OpenBazaar-Server/openbazaard.py', 'start', '--testnet'], {detach: true});
  var stdout = '';
  var stderr = '';
  subpy.stdout.on('data', function(buf) {
    console.log('[STR] stdout "%s"', String(buf));
    stdout += buf;
  });
  subpy.stderr.on('data', function(buf) {
    console.log('[STR] stderr "%s"', String(buf));
    stderr += buf;
  });
  subpy.on('close', function(code) {
    console.log('exited with ' + code);
    console.log('[END] stdout "%s"', stdout);
    console.log('[END] stderr "%s"', stderr);
  });
  subpy.unref();
}

// Report crashes to our server.
require('crash-reporter').start();

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is GCed.
var mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform != 'darwin') {
    app.quit();
  }
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {

  // Create the browser window.
  mainWindow = new BrowserWindow({
    "width": 1200,
    "height": 700,
    "min-width": 1024,
    "min-height": 700,
    "center": true,
    "title": "OpenBazaar"//,
    //frame: false
  });

  // and load the index.html of the app.
  mainWindow.loadUrl('file://' + __dirname + '/index.html');

  // Open the devtools.
  mainWindow.openDevTools();

  // Emitted when the window is closed.
  mainWindow.on('closed', function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
    if(subpy) {
      subpy.kill('SIGHUP');
    }
  });

  app.on('activate-with-no-open-windows', function() {
    mainWindow.show();
  });

});
<commit_msg>Fix the default case npm start<commit_after>"use strict";

// Check that the deps in node_modules match what's in package.json.
var safestart = require('safestart');
safestart(__dirname);

var app = require('app');  // Module to control application life.
var BrowserWindow = require('browser-window');  // Module to create native browser window.

// Check if we need to kick off the python server-daemon (Desktop app)
if(process.argv.length > 2 && (process.argv[2].toUpperCase() == "startserver".toUpperCase())) {
  // Kick it off
  console.log('Starting OpenBazaar Server');
  var subpy = '';
  if(process.argv.length > 3 && process.argv[3].toUpperCase() == "testnet".toUpperCase()) {
    subpy = require('child_process').spawn('python', [__dirname + '/OpenBazaar-Server/openbazaard.py', 'start', '--testnet'], {detach: true});
  } else {
    subpy = require('child_process').spawn('python', [__dirname + '/OpenBazaar-Server/openbazaard.py', 'start'], {detach: true});
  }
  var stdout = '';
  var stderr = '';
  subpy.stdout.on('data', function(buf) {
    console.log('[STR] stdout "%s"', String(buf));
    stdout += buf;
  });
  subpy.stderr.on('data', function(buf) {
    console.log('[STR] stderr "%s"', String(buf));
    stderr += buf;
  });
  subpy.on('close', function(code) {
    console.log('exited with ' + code);
    console.log('[END] stdout "%s"', stdout);
    console.log('[END] stderr "%s"', stderr);
  });
  subpy.unref();
}

// Report crashes to our server.
require('crash-reporter').start();

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is GCed.
var mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform != 'darwin') {
    app.quit();
  }
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {

  // Create the browser window.
  mainWindow = new BrowserWindow({
    "width": 1200,
    "height": 700,
    "min-width": 1024,
    "min-height": 700,
    "center": true,
    "title": "OpenBazaar"//,
    //frame: false
  });

  // and load the index.html of the app.
  mainWindow.loadUrl('file://' + __dirname + '/index.html');

  // Open the devtools.
  mainWindow.openDevTools();

  // Emitted when the window is closed.
  mainWindow.on('closed', function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
    if(subpy) {
      subpy.kill('SIGHUP');
    }
  });

  app.on('activate-with-no-open-windows', function() {
    mainWindow.show();
  });

});
<|endoftext|>


<commit_before>/**
 * @fileoverview This file is the controller for generating one api reference
 * page of the extension documentation.
 *
 * It expects:
 *
 * - To be called from a "shell" page whose "base" name matches an api module
 *   name. For instance ../bookmarks.html -> chrome.bookmarks.
 *
 * - To have available via XHR (relative path):
 *   1) API_TEMPLATE which is the main template for the api pages.
 *   2) A file located at SCHEMA which is shared with the extension system and
 *      defines the methods and events contained in one api.
 *   3) An |apiName| + OVERVIEW_EXTENSION file which contains static authored
 *      content that is inserted into the "overview" slot in the API_TEMPLATE.
 *
 * The "shell" page may have a renderering already contained within it so that
 * the docs can be indexed.
 *
 * TODO(rafaelw): XHR support for IE.
 * TODO(rafaelw): JSON support for non-chrome 3.x clients.
 */

var API_TEMPLATE = "../template/api_template.html";
var SCHEMA = "../../api/extension_api.json";
var OVERVIEW_EXTENSION = "_overview.html";
var REQUEST_TIMEOUT = 2000;

Array.prototype.each = function(f) {
  for (var i = 0; i < this.length; i++) {
    f(this[i], i);
  }
}

/*
 * Assigns all keys & values of |obj2| to |obj1|.
 */
function extend(obj, obj2) {
  for (var k in obj2) {
    obj[k] = obj2[k];
  }
}

// name of the api this reference page is describing. i.e. "bookmarks", "tabs".
var apiName;

window.onload = function() {
  // Determine api module being rendered. Expect ".../<apiName>.html"
  var pathParts = document.location.href.split(/\/|\./);
  apiName = pathParts[pathParts.length - 2];

  // Fetch the api template and insert into the <body>.
  fetchContent(API_TEMPLATE, function(templateContent) {
    document.getElementsByTagName("body")[0].innerHTML = templateContent;

    // Fetch the overview and insert into the "overview" <div>.
    fetchContent(apiName + OVERVIEW_EXTENSION, function(overviewContent) {
      document.getElementById("overview").innerHTML = overviewContent;

      // Now the page is composed with the authored content, we fetch the schema
      // and populate the templates.
      fetchContent(SCHEMA, renderTemplate);
    });
  });
}

/**
 * Fetches |url| and returns it's text contents from the xhr.responseText in
 * onSuccess(content)
 */
function fetchContent(url, onSuccess) {
  var xhr = new XMLHttpRequest();
  var abortTimerId = window.setTimeout(function() {
    xhr.abort();
    console.log("XHR Timed out");
  }, REQUEST_TIMEOUT);

  function handleError(error) {
    window.clearTimeout(abortTimerId);
    console.error("XHR Failed: " + error);
  }

  try {
    xhr.onreadystatechange = function(){
      if (xhr.readyState == 4) {
        if (xhr.responseText) {
          window.clearTimeout(abortTimerId);
          onSuccess(xhr.responseText);
        } else {
          handleError("responseText empty.");
        }
      }
    }

    xhr.onerror = handleError;

    xhr.open("GET", url, true);
    xhr.send(null);
  } catch(e) {
    console.log("ex: " + e);
    console.error("exception: " + e);
    handleError();
  }
}

/**
 * Parses the content in |schema| to json, find appropriate api, adds any
 * additional required values, renders to html via JSTemplate, and unhides the
 * <body>.
 * This uses the root <html> element (the entire document) as the template.
 */
function renderTemplate(schemaContent) {
  var apiDefinition;
  var schema = JSON.parse(schemaContent);

  schema.each(function(module) {
    if (module.namespace == apiName)
      apiDefinition = module;
  });

  types = {};
  apiDefinition.types.each(function(t) {
    types[t.id] = t;
  });

  preprocessApi(apiDefinition, schema, types);

  // Render to template
  var input = new JsEvalContext(apiDefinition);
  var output = document.getElementsByTagName("html")[0];
  jstProcess(input, output);

  // Show.
  document.getElementsByTagName("body")[0].className = "";
}

/**
 * Augment the |module| with additional values that are required by the
 * template. |schema| is the full schema (including all modules). |types| is an
 * array of typeId -> typeSchema.
 */
function preprocessApi(module, schema, types) {
  module.functions.each(function(f) {
    f.fullName = "chrome." + module.namespace + "." + f.name;
    linkTypeReferences(f.parameters, types);
    assignTypeNames(f.parameters);

    // Look for a callback that defines parameters.
    if (f.parameters.length > 0) {
      var lastParam = f.parameters[f.parameters.length - 1];
      if (lastParam.type == "function" && lastParam.parameters) {
        linkTypeReferences(lastParam.parameters, types);
        assignTypeNames(lastParam.parameters);
        f.callbackParameters = lastParam.parameters;
        f.callbackSignature = generateSignatureString(lastParam.parameters);
        f.callbackParameters.each(function(p) {
          addPropertyListIfObject(p);
        });
      }
    }

    // Setup any type: "object" pameters to have an array of params (rather than
    // named properties).
    f.parameters.each(function(param) {
      addPropertyListIfObject(param);
    });

    // Setup return typeName & _propertyList, if any.
    if (f.returns) {
      linkTypeReference(f.returns, types);
      f.returns.typeName = typeName(f.returns);
      addPropertyListIfObject(f.returns);
    }
  });

  module.events.each(function(e) {
    linkTypeReferences(e.parameters, types);
    assignTypeNames(e.parameters);
    e.callSignature = generateSignatureString(e.parameters);
    e.parameters.each(function(p) {
      addPropertyListIfObject(p);
    });
  });

  // Add a list of modules for the master TOC.
  module.apiModules = [];
  schema.each(function(s) {
    var m = {};
    m.module = s.namespace;
    m.name = s.namespace.substring(0, 1).toUpperCase() +
             s.namespace.substring(1);
    module.apiModules.push(m);
  });
  module.apiModules.sort(function(a, b) { return a.name > b.name; });
}

/*
 * For function, callback and event parameters, we want to document the
 * properties of any "object" type. This takes an param, and if it is an
 * "object" type, creates a "_parameterList" property in the form as
 * |parameters| list used by the template.
 */
function addPropertyListIfObject(object) {
  if (object.type != "object" || !object.properties)
    return;

  var propertyList = [];
  for (var p in object.properties) {
    var prop = object.properties[p];
    prop.name = p;
    propertyList.push(prop);
  }
  assignTypeNames(propertyList);
  object._propertyList = propertyList;
}

function linkTypeReferences(parameters, types) {
  parameters.each(function(p) {
    linkTypeReference(p, types);
  });
}

function linkTypeReference(schema, types) {
  if (schema.$ref) {
    extend(schema, types[schema.$ref]);
  }
}

/**
 * Assigns a typeName(param) to each of the |parameters|.
 */
function assignTypeNames(parameters) {
  parameters.each(function(p) {
    p.typeName = typeName(p);
  });
}

/**
 * Generates a short text summary of the |schema| type
 */
function typeName(schema) {
  if (schema.choice) {
    var typeNames = [];
    schema.choice.each(function(c) {
      typeNames.push(typeName(c));
    });

    return typeNames.join(" or ");
  }

  if (schema.type == "array") {
    return "array of " + typeName(schema.item);
  }

  return schema.type;
}

/**
 * Generates a simple string representation of the signature of a function
 * whose |parameters| are json schemas.
 */
function generateSignatureString(parameters) {
  var retval = [];
  parameters.each(function(param, i) {
    retval.push(param.typeName + " " + param.name);
  });

  return retval.join(", ");
}
<commit_msg>Fix broken array.items reference in generate doc script.<commit_after>/**
 * @fileoverview This file is the controller for generating one api reference
 * page of the extension documentation.
 *
 * It expects:
 *
 * - To be called from a "shell" page whose "base" name matches an api module
 *   name. For instance ../bookmarks.html -> chrome.bookmarks.
 *
 * - To have available via XHR (relative path):
 *   1) API_TEMPLATE which is the main template for the api pages.
 *   2) A file located at SCHEMA which is shared with the extension system and
 *      defines the methods and events contained in one api.
 *   3) An |apiName| + OVERVIEW_EXTENSION file which contains static authored
 *      content that is inserted into the "overview" slot in the API_TEMPLATE.
 *
 * The "shell" page may have a renderering already contained within it so that
 * the docs can be indexed.
 *
 * TODO(rafaelw): XHR support for IE.
 * TODO(rafaelw): JSON support for non-chrome 3.x clients.
 */

var API_TEMPLATE = "../template/api_template.html";
var SCHEMA = "../../api/extension_api.json";
var OVERVIEW_EXTENSION = "_overview.html";
var REQUEST_TIMEOUT = 2000;

// Global Schema Types (Referenced via $ref).
var types = {};

Array.prototype.each = function(f) {
  for (var i = 0; i < this.length; i++) {
    f(this[i], i);
  }
}

/*
 * Assigns all keys & values of |obj2| to |obj1|.
 */
function extend(obj, obj2) {
  for (var k in obj2) {
    obj[k] = obj2[k];
  }
}

// name of the api this reference page is describing. i.e. "bookmarks", "tabs".
var apiName;

window.onload = function() {
  // Determine api module being rendered. Expect ".../<apiName>.html"
  var pathParts = document.location.href.split(/\/|\./);
  apiName = pathParts[pathParts.length - 2];

  // Fetch the api template and insert into the <body>.
  fetchContent(API_TEMPLATE, function(templateContent) {
    document.getElementsByTagName("body")[0].innerHTML = templateContent;

    // Fetch the overview and insert into the "overview" <div>.
    fetchContent(apiName + OVERVIEW_EXTENSION, function(overviewContent) {
      document.getElementById("overview").innerHTML = overviewContent;

      // Now the page is composed with the authored content, we fetch the schema
      // and populate the templates.
      fetchContent(SCHEMA, renderTemplate);
    });
  });
}

/**
 * Fetches |url| and returns it's text contents from the xhr.responseText in
 * onSuccess(content)
 */
function fetchContent(url, onSuccess) {
  var xhr = new XMLHttpRequest();
  var abortTimerId = window.setTimeout(function() {
    xhr.abort();
    console.log("XHR Timed out");
  }, REQUEST_TIMEOUT);

  function handleError(error) {
    window.clearTimeout(abortTimerId);
    console.error("XHR Failed: " + error);
  }

  try {
    xhr.onreadystatechange = function(){
      if (xhr.readyState == 4) {
        if (xhr.responseText) {
          window.clearTimeout(abortTimerId);
          onSuccess(xhr.responseText);
        } else {
          handleError("responseText empty.");
        }
      }
    }

    xhr.onerror = handleError;

    xhr.open("GET", url, true);
    xhr.send(null);
  } catch(e) {
    console.log("ex: " + e);
    console.error("exception: " + e);
    handleError();
  }
}

/**
 * Parses the content in |schema| to json, find appropriate api, adds any
 * additional required values, renders to html via JSTemplate, and unhides the
 * <body>.
 * This uses the root <html> element (the entire document) as the template.
 */
function renderTemplate(schemaContent) {
  var apiDefinition;
  var schema = JSON.parse(schemaContent);

  schema.each(function(module) {
    if (module.namespace == apiName)
      apiDefinition = module;
  });

  // Setup Schema Types
  apiDefinition.types.each(function(t) {
    types[t.id] = t;
  });

  preprocessApi(apiDefinition, schema, types);

  // Render to template
  var input = new JsEvalContext(apiDefinition);
  var output = document.getElementsByTagName("html")[0];
  jstProcess(input, output);

  // Show.
  document.getElementsByTagName("body")[0].className = "";
}

/**
 * Augment the |module| with additional values that are required by the
 * template. |schema| is the full schema (including all modules). |types| is an
 * array of typeId -> typeSchema.
 */
function preprocessApi(module, schema, types) {
  module.functions.each(function(f) {
    f.fullName = "chrome." + module.namespace + "." + f.name;
    linkTypeReferences(f.parameters, types);
    assignTypeNames(f.parameters);

    // Look for a callback that defines parameters.
    if (f.parameters.length > 0) {
      var lastParam = f.parameters[f.parameters.length - 1];
      if (lastParam.type == "function" && lastParam.parameters) {
        linkTypeReferences(lastParam.parameters, types);
        assignTypeNames(lastParam.parameters);
        f.callbackParameters = lastParam.parameters;
        f.callbackSignature = generateSignatureString(lastParam.parameters);
        f.callbackParameters.each(function(p) {
          addPropertyListIfObject(p);
        });
      }
    }

    // Setup any type: "object" pameters to have an array of params (rather than
    // named properties).
    f.parameters.each(function(param) {
      addPropertyListIfObject(param);
    });

    // Setup return typeName & _propertyList, if any.
    if (f.returns) {
      linkTypeReference(f.returns, types);
      f.returns.typeName = typeName(f.returns);
      addPropertyListIfObject(f.returns);
    }
  });

  module.events.each(function(e) {
    linkTypeReferences(e.parameters, types);
    assignTypeNames(e.parameters);
    e.callSignature = generateSignatureString(e.parameters);
    e.parameters.each(function(p) {
      addPropertyListIfObject(p);
    });
  });

  // Add a list of modules for the master TOC.
  module.apiModules = [];
  schema.each(function(s) {
    var m = {};
    m.module = s.namespace;
    m.name = s.namespace.substring(0, 1).toUpperCase() +
             s.namespace.substring(1);
    module.apiModules.push(m);
  });
  module.apiModules.sort(function(a, b) { return a.name > b.name; });
}

/*
 * For function, callback and event parameters, we want to document the
 * properties of any "object" type. This takes an param, and if it is an
 * "object" type, creates a "_parameterList" property in the form as
 * |parameters| list used by the template.
 */
function addPropertyListIfObject(object) {
  if (object.type != "object" || !object.properties)
    return;

  var propertyList = [];
  for (var p in object.properties) {
    var prop = object.properties[p];
    prop.name = p;
    propertyList.push(prop);
  }
  assignTypeNames(propertyList);
  object._propertyList = propertyList;
}

function linkTypeReferences(parameters, types) {
  parameters.each(function(p) {
    linkTypeReference(p, types);
  });
}

function linkTypeReference(schema, types) {
  if (schema.$ref)
    extend(schema, types[schema.$ref]);
}

/**
 * Assigns a typeName(param) to each of the |parameters|.
 */
function assignTypeNames(parameters) {
  parameters.each(function(p) {
    p.typeName = typeName(p);
  });
}

/**
 * Generates a short text summary of the |schema| type
 */
function typeName(schema) {
  if (schema.$ref)
    schema = types[schema.$ref];

  if (schema.choice) {
    var typeNames = [];
    schema.choice.each(function(c) {
      typeNames.push(typeName(c));
    });

    return typeNames.join(" or ");
  }

  if (schema.type == "array")
    return "array of " + typeName(schema.items);

  return schema.type;
}

/**
 * Generates a simple string representation of the signature of a function
 * whose |parameters| are json schemas.
 */
function generateSignatureString(parameters) {
  var retval = [];
  parameters.each(function(param, i) {
    retval.push(param.typeName + " " + param.name);
  });

  return retval.join(", ");
}
<|endoftext|>


<commit_before>var VCs;
var verifying = false;

function submitAnswer() {
    /* Protect against multiple requests */
    if (verifying) {
        return;
    }

	verifying = true;
    $("#right .footette").attr("class", "footetteDisabled");

    var content = createEditor.getValue();

    if (checkForTrivials(content)) {
        getVCLines(content);
    } else {
        $("#dialog-message").html("Sorry, not the intended answer. Try again!");
        $("#dialog-box").dialog("open");
        verifying = false;
        $("#right .footetteDisabled").attr("class", "footette");
        createEditor.focus();
    }
}

function checkForTrivials(content) {
    // Find all the confirm statements
    var regex = new RegExp("Confirm [^;]*;", "mg");
    var confirms = content.match(regex);
    if (confirms.length == 0) {
        return false;
    }

    var i;
    for (i = 0; i < confirms.length; i++) {
        // Remove the "Confirm " so that we can find the variable names
        var statement = confirms[i];
        statement = statement.substr(8);

        // Split the string at the conditional
        regex = new RegExp("[<>=]");
        var parts = statement.split(regex);
        if (parts.length != 2) {
            return false;
        }

        // Find the variables used on the left side
        var left = parts[0];
        var right = parts[1];
        regex = new RegExp("[a-zA-Z]", "g");
        var variables = left.match(regex);
        if (variables === null) {
            continue;
        }

        // Search for these variables on the right side
        var j;
        for (j = 0 ; j < variables.length ; j++) {
            variable = variables[j];
            regex = new RegExp("[^#]" + variable, "g");
            if (right.search(regex) > -1) {
                return false;
            }
        }
    }

    return true;
}

function getVCLines(content) {
    removeAllVCMarkers();
    var socket = new WebSocket("wss://resolve.cs.clemson.edu/teaching/Compiler?job=genVCs&project=Teaching_Project");

    socket.onmessage = function (message) {
        if (!verifying) {
            return;
        }

        // Extract the array of VCs from the message (trust me, this works)
        message = JSON.parse(message.data);
        if (message.status == "error") {
            $("#dialog-message").html("Sorry, can't parse your answer. Try again!");
            $("#dialog-box").dialog("open");
            verifying = false;
            $("#right .footetteDisabled").attr("class", "footette");

            createEditor.focus();
            return;
        }

        if (message.status != "complete") {
            return;
        }

        if (message.result == "") {
	        $("#dialog-message").html("Sorry, can't parse your answer. Try again!");
	        $("#dialog-box").dialog("open");
            verifying = false;
            $("#right .footetteDisabled").attr("class", "footette");

            createEditor.focus();
            return;
	    }

        message = decode(message.result);
        message = $(message).text();
        message = JSON.parse(message);

        // Simplify the VC information
        VCs = [];
        $.each(message.vcs, function (index, obj) {
            if (typeof obj.vc !== "undefined") VCs.push(obj);
        });

        addVCMarkers();
        verifyVCs(createEditor.getValue());
    };

    content = encode(content);
    content = toJSON(content);

    socket.onopen = function () {
        socket.send(content);
    };
}

function verifyVCs(content) {
    var socket = new WebSocket("wss://resolve.cs.clemson.edu/teaching/Compiler?job=verify2&project=Teaching_Project");

    socket.onmessage = function (message) {
        message = JSON.parse(message.data);
        if (message.status !== "processing") {
            return;
        }

        updateMarker(message.result);
    };

    content = encode(content);
    content = toJSON(content);

    socket.onopen = function () {
        socket.send(content);
	};

	socket.onclose = function () {
        if (succeed) {
            approved = true;
            $("#dialog-message").html("Correct. On to the next lesson!");
            $("#dialog-box").dialog("open");
            nextLessonAndSuccess();
        } else {
            if (currentLesson.self != currentLesson.nextLessonOnFailure) {
                $("#dialog-message").html("Sorry, not correct. Try this other lesson!");
                $("#dialog-box").dialog("open");
                nextLessonAndFailure();
            } else {
                $("#dialog-message").html("Sorry, not correct. Try again!");
                $("#dialog-box").dialog("open");
            }
        }

        verifying = false;
        $("#right .footetteDisabled").attr("class", "footette");
        sendData();
    }
}<commit_msg>more linting<commit_after>/* global approved currentLesson encode nextLessonAndSuccess nextLessonAndFailure sendData succeed toJSON */

var VCs;
var verifying = false;

function submitAnswer() {
    /* Protect against multiple requests */
    if (verifying) {
        return;
    }

	verifying = true;
    $("#right .footette").attr("class", "footetteDisabled");

    var content = createEditor.getValue();

    if (checkForTrivials(content)) {
        getVCLines(content);
    } else {
        $("#dialog-message").html("Sorry, not the intended answer. Try again!");
        $("#dialog-box").dialog("open");
        verifying = false;
        $("#right .footetteDisabled").attr("class", "footette");
        createEditor.focus();
    }
}

function checkForTrivials(content) {
    // Find all the confirm statements
    var regex = new RegExp("Confirm [^;]*;", "mg");
    var confirms = content.match(regex);
    if (confirms.length == 0) {
        return false;
    }

    var i;
    for (i = 0; i < confirms.length; i++) {
        // Remove the "Confirm " so that we can find the variable names
        var statement = confirms[i];
        statement = statement.substr(8);

        // Split the string at the conditional
        regex = new RegExp("[<>=]");
        var parts = statement.split(regex);
        if (parts.length != 2) {
            return false;
        }

        // Find the variables used on the left side
        var left = parts[0];
        var right = parts[1];
        regex = new RegExp("[a-zA-Z]", "g");
        var variables = left.match(regex);
        if (variables === null) {
            continue;
        }

        // Search for these variables on the right side
        var j;
        for (j = 0 ; j < variables.length ; j++) {
            variable = variables[j];
            regex = new RegExp("[^#]" + variable, "g");
            if (right.search(regex) > -1) {
                return false;
            }
        }
    }

    return true;
}

function getVCLines(content) {
    removeAllVCMarkers();
    var socket = new WebSocket("wss://resolve.cs.clemson.edu/teaching/Compiler?job=genVCs&project=Teaching_Project");

    socket.onmessage = function (message) {
        if (!verifying) {
            return;
        }

        // Extract the array of VCs from the message (trust me, this works)
        message = JSON.parse(message.data);
        if (message.status == "error") {
            $("#dialog-message").html("Sorry, can't parse your answer. Try again!");
            $("#dialog-box").dialog("open");
            verifying = false;
            $("#right .footetteDisabled").attr("class", "footette");

            createEditor.focus();
            return;
        }

        if (message.status != "complete") {
            return;
        }

        if (message.result == "") {
	        $("#dialog-message").html("Sorry, can't parse your answer. Try again!");
	        $("#dialog-box").dialog("open");
            verifying = false;
            $("#right .footetteDisabled").attr("class", "footette");

            createEditor.focus();
            return;
	    }

        message = decode(message.result);
        message = $(message).text();
        message = JSON.parse(message);

        // Simplify the VC information
        VCs = [];
        $.each(message.vcs, function (index, obj) {
            if (typeof obj.vc !== "undefined") VCs.push(obj);
        });

        addVCMarkers();
        verifyVCs(createEditor.getValue());
    };

    content = encode(content);
    content = toJSON(content);

    socket.onopen = function () {
        socket.send(content);
    };
}

function verifyVCs(content) {
    var socket = new WebSocket("wss://resolve.cs.clemson.edu/teaching/Compiler?job=verify2&project=Teaching_Project");

    socket.onmessage = function (message) {
        message = JSON.parse(message.data);
        if (message.status !== "processing") {
            return;
        }

        updateMarker(message.result);
    };

    content = encode(content);
    content = toJSON(content);

    socket.onopen = function () {
        socket.send(content);
    };

    socket.onclose = function () {
        if (succeed) {
            approved = true;
            $("#dialog-message").html("Correct. On to the next lesson!");
            $("#dialog-box").dialog("open");
            nextLessonAndSuccess();
        } else {
            if (currentLesson.self != currentLesson.nextLessonOnFailure) {
                $("#dialog-message").html("Sorry, not correct. Try this other lesson!");
                $("#dialog-box").dialog("open");
                nextLessonAndFailure();
            } else {
                $("#dialog-message").html("Sorry, not correct. Try again!");
                $("#dialog-box").dialog("open");
            }
        }

        verifying = false;
        $("#right .footetteDisabled").attr("class", "footette");
        sendData();
    };
}
<|endoftext|>


<commit_before>angular.module("omniControllers")
  .controller("WalletOverviewController", ["$scope","Account","$location","Wallet",
    function WalletOverviewController($scope,Account,$location,Wallet){
      $scope.uuid = Account.uuid;
      $scope.loginLink = $location.protocol() + "://" + $location.host() + "/login/" + $scope.uuid;
      //console.log(Wallet.addresses);
      $scope.firstLogin = Account.firstLogin;
      $scope.CSYM=Account.getSetting("usercurrency");
      $scope.total=0;
      $scope.chartConfig = {
        tooltips: true,
        mouseover: function() {},
        mouseout: function() {},
        click: function() {}
      };

      $scope.balanceData = {
        data: []
      };

      function refresh(){
        $scope.total = 0;
        Wallet.assets.forEach(function(asset) {
          $scope.total += +asset.value;

          var add = true;
          $scope.balanceData.data.forEach(function(data){
            if(data.x==asset.symbol){
              data.y = [asset.value];
              add = false;
            }
          })
          if(add)
            $scope.balanceData.data.push({x:asset.symbol,y:[asset.value],tooltip:asset.symbol+": $"+asset.value.toFixed(2)})
        });
      }

      $scope.disclaimerSeen = Account.settings.disclaimerSeen;
      $scope.$on('$locationChangeSuccess', function(path) {
        Account.settings.disclaimerSeen = true;
      })

      $scope.$on("BALANCE_CHANGED",function(evt,changed,values){
        refresh();
      })
      $scope.$on("APPRAISER_VALUE_CHANGED",function(evt,changed){
        refresh();
      })

      refresh();
    }]);
<commit_msg>Add Number check<commit_after>angular.module("omniControllers")
  .controller("WalletOverviewController", ["$scope","Account","$location","Wallet",
    function WalletOverviewController($scope,Account,$location,Wallet){
      $scope.uuid = Account.uuid;
      $scope.loginLink = $location.protocol() + "://" + $location.host() + "/login/" + $scope.uuid;
      //console.log(Wallet.addresses);
      $scope.firstLogin = Account.firstLogin;
      $scope.CSYM=Account.getSetting("usercurrency");
      $scope.total=0;
      $scope.chartConfig = {
        tooltips: true,
        mouseover: function() {},
        mouseout: function() {},
        click: function() {}
      };

      $scope.balanceData = {
        data: []
      };

      function refresh(){
        $scope.total = 0;
        Wallet.assets.forEach(function(asset) {
          $scope.total += +asset.value;

          var add = true;
          $scope.balanceData.data.forEach(function(data){
            if(data.x==asset.symbol){
              data.y = [asset.value];
              add = false;
            }
          })
          if(add)
            $scope.balanceData.data.push({x:asset.symbol,y:[asset.value],tooltip:asset.symbol+": "+typeof(asset.value) == Number?"$"+asset.value.toFixed(2):asset.value})
        });
      }

      $scope.disclaimerSeen = Account.settings.disclaimerSeen;
      $scope.$on('$locationChangeSuccess', function(path) {
        Account.settings.disclaimerSeen = true;
      })

      $scope.$on("BALANCE_CHANGED",function(evt,changed,values){
        refresh();
      })
      $scope.$on("APPRAISER_VALUE_CHANGED",function(evt,changed){
        refresh();
      })

      refresh();
    }]);
<|endoftext|>


<commit_before>(function(){
	// the loader provides the platform interfaces for web.
	var root = {}
	root.platformPath = 'platform/'
	root.platform = 'web'
	root.isWindows = typeof navigator !== 'undefined' && navigator.appVersion.indexOf("Win") > -1
	root.isIPad = navigator.userAgent.match(/iPad/)
	root.isIOSDevice = navigator.userAgent.match(/(iPod|iPhone|iPad)/) && navigator.userAgent.match(/AppleWebKit/)
	root.isTouchDevice = ('ontouchstart' in window || navigator.maxTouchPoints)
	root.locationSearch = location.search
	root.hardwareConcurrency = navigator.hardwareConcurrency || 4
	// creates a worker creator
	root.makeWorkerCreator = function(source, fake){
		if(fake){

			var mask = Object.getOwnPropertyNames(window)
			var jsGlobals = getJsGlobals()
			for(var i = 0; i < jsGlobals.length; i++){
				var idx = mask.indexOf(jsGlobals[i])
				if(idx !== -1) mask.splice(idx, 1)
			}

			return function(){
				// exec it
				var inMain = {
					postMessage:function(msg){
						//setTimeout(function(){
							inWorker.onMessage(msg)
						//},0)
					}
				}
				var inWorker = {
					postMessage:function(msg){
						setTimeout(function(){
							inMain.onMessage(msg)
						},0)
					}
				}

				function WrapFunction(){
					var globnames = []
					var globargs = []
					for(var key in global){
						globnames.push(key)
						globargs.push(global[key])
					}

					// lets push in all masked
					for(var i = 0; i < mask.length; i++){
						var name = mask[i]
						if(!(name in global)){
							globnames.push(name)
						}
					}

					var fnargs = []
					var args = arguments
					var len = arguments.length
					var code = '"use strict"\nreturn function('
					for(var i = 0; i < len - 1; i++){
						if(i) code += ','
						code += args[i]
					}
					code += '){'+args[i]+'}'
					globnames.push(code)
					return Function.apply(null, globnames).apply(null, globargs)
				}

				var global = {
					Object:Object,
					String:String,
					Number:Number,
					Boolean:Boolean,
					console:{
						log:console.log.bind(console)
					},
					setTimeout:setTimeout,
					clearTimeout:clearTimeout,
					setInterval:setInterval,
					clearInterval:clearInterval,
					Function:WrapFunction
				}

				function postBoot(){
				}

				new Function("Function","global", "worker", source+'\n'+postBoot.toString()+'\npostBoot()\n')(WrapFunction, global, inWorker)
				return inMain
			}
		}

		var src =
			'(function(){'+
			'	var global = self\n'+
			'	var worker = {postMessage:self.postMessage.bind(self)}\n'+
			'	self.onmessage = function(msg){worker.onMessage(msg.data)}\n'+
			getJsGlobals.toString()+
			cleanWebWorker.toString()+';cleanWebWorker();\n'+
			source+'\n'+
			'})()'

		var blob = URL.createObjectURL(new Blob([src], {type: "text/javascript"}))

		return function(){
			var worker = new Worker(blob)
			worker.onmessage = function(msg){
				this.onMessage(msg.data)
			}
			return worker
		}
	}

	// watches a file
	root.watchFile = function(localFile){

	}

	// inject a script tag for url
	root.showParseError = function(path){
		var script = document.createElement('script')
		script.type = 'text/javascript'
		script.src = location.origin+'/'+path
		document.getElementsByTagName('head')[0].appendChild(script)
	}

	// downloads a resource
	root.resourceCache = {}

	root.downloadResource = function(localFile, isBinary, appProgress){
		return new Promise(function(resolve, reject){
			var req = new XMLHttpRequest()

			// lets add this node to the canvas tag
			var progressDiv
			var progressTimeout
			if(appProgress){
				progressDiv = document.createElement('span')
				progressDiv.style.marginLeft = 50
				progressDiv.style.display = 'none'
				progressDiv.style.fontSize = '10px'
				progressDiv.style.color = 'white'// = 'margin-left:50;display:block;font-size:10px;color:white'
				progressDiv.innerHTML = 'Loading: '+localFile+' 0%'
				document.body.appendChild(progressDiv)
				req.addEventListener("progress", function(e){
					var pos = e.position || e.loaded
					var total = e.totalSize || e.total
					progressDiv.innerHTML = 'Loading: '+localFile+' '+Math.floor(100*pos / total)+'%
'
				})
				progressTimeout = setTimeout(function(){
					progressTimeout = undefined
					progressDiv.style.display = 'block'
				}, 2000)
			}
			req.addEventListener("error", function(){
				console.error('Error loading '+resourceurl+' from '+parenturl)
				reject(resource)
			})
			req.responseType = isBinary?'arraybuffer':'text'
			req.addEventListener("load", function(){
				if(appProgress){
					document.body.removeChild(progressDiv)
					if(progressTimeout) clearTimeout(progressTimeout)
				}
				if(req.status !== 200){
					return reject(resource)
				}
				root.resourceCache[localFile] = req.response
				resolve(req.response)
			})
			req.open("GET", location.origin+'/'+localFile)
			req.send()
		})
	}

	var canvasses =	document.getElementsByClassName('makepad')

	var initApps
	function init(){

		var apps = []
		for(var i = 0; i < canvasses.length; i++){
			var canvas = canvasses[i]
			apps.push({
				main:canvas.getAttribute('main'),
				platform:{
					canvas:canvas,
					search:location.search && location.search.slice(1)
				}
			})
		}
		if(root.onInitApps) root.onInitApps(apps)
		else initApps = apps
	}

	document.addEventListener('DOMContentLoaded', init)

	// load up boot file
	root.downloadResource(root.platformPath+'boot.js').then(function(result){
		// start it up
		try{
			new Function("root", result)(root)
		}
		catch(e){
			root.showParseError(root.platformPath+'boot.js')
			return
		}
		// if we were slower than DOMContentLoaded
		if(initApps) root.onInitApps(initApps)
	})

	function watchFileChange(){
		var req = new XMLHttpRequest()
		req.timeout = 60000
		req.addEventListener("error", function(){
			setTimeout(watchFileChange, 500)
		})
		req.responseType = 'text'
		req.addEventListener("load", function(){
			if(req.response === '{continue:true}') return watchFileChange()
			// do something with data, or not
			location.href = location.href
		})
		req.open("GET", "/$watch?"+(''+Math.random()).slice(2))
		req.send()
	}

	function getJsGlobals(){
		return [
			'console', 'eval', 'Infinity','NaN','undefined','null','isFinite','isNaN','parseFloat','parseInt',
			'Symbol','Error','EvalError','InternalError','RangeError','ReferenceError','TypeError','URIError',
			'Map','Set','WeakMap','WeakSet','SIMD','JSON','Generator','GeneratorFunction','Intl','SyntaxError',
			'Function', 'RegExp', 'Math', 'Object', 'String', 'Number','Boolean','Date', 'Array',
			'Int8Array','Uint8Array','Uint8ClampedArray','Int16Array','Uint16Array','Int32Array','Uint32Array',
			'Float32Array','Float64Array','DataView','ArrayBuffer','setTimeout','clearTimeout','setInterval','clearInterval'
		]
	}

	if(location.hostname === 'localhost' || location.hostname === '127.0.0.1' || location.hostname.indexOf('10.') === 0)
		watchFileChange()

	function cleanWebWorker(){
		var deprecated = [
			'webkitIDBTransaction','webkitIDBRequest','webkitIDBObjectStore','webkitIDBKeyRange','webkitIDBIndex','webkitIDBFactory',
			'webkitIDBDatabase','webkitIDBCursor'
		]
		var jsGlobals = getJsGlobals()
		var mask = Object.getOwnPropertyNames(self)
		var forceMask = []
		var LocalFunction = self.Function
		self.Function = function(){

			var args = []
			var len = arguments.length
			for(var i = 0; i < len - 1; i++) args.push(arguments[i])
			args.push.apply(args, forceMask)

			var code = arguments[len -1]
			args.push(code)
			return LocalFunction.apply(null, args)
		}

		for(var i = 0; i < mask.length; i++){
			var name = mask[i]
			if(jsGlobals.indexOf(name) !== -1) continue
			try{
				if(deprecated.indexOf(name)!==-1){
					self[name] = undefined
				}
				else Object.defineProperty(self, name, {value:undefined})
			}
			catch(e){
				forceMask.push(name)
			}
		}
		self = undefined
	}
})()<commit_msg> progress<commit_after>(function(){
	// the loader provides the platform interfaces for web.
	var root = {}
	root.platformPath = 'platform/'
	root.platform = 'web'
	root.isWindows = typeof navigator !== 'undefined' && navigator.appVersion.indexOf("Win") > -1
	root.isIPad = navigator.userAgent.match(/iPad/)
	root.isIOSDevice = navigator.userAgent.match(/(iPod|iPhone|iPad)/) && navigator.userAgent.match(/AppleWebKit/)
	root.isTouchDevice = ('ontouchstart' in window || navigator.maxTouchPoints)
	root.locationSearch = location.search
	root.hardwareConcurrency = navigator.hardwareConcurrency || 4
	// creates a worker creator
	root.makeWorkerCreator = function(source, fake){
		if(fake){

			var mask = Object.getOwnPropertyNames(window)
			var jsGlobals = getJsGlobals()
			for(var i = 0; i < jsGlobals.length; i++){
				var idx = mask.indexOf(jsGlobals[i])
				if(idx !== -1) mask.splice(idx, 1)
			}

			return function(){
				// exec it
				var inMain = {
					postMessage:function(msg){
						//setTimeout(function(){
							inWorker.onMessage(msg)
						//},0)
					}
				}
				var inWorker = {
					postMessage:function(msg){
						setTimeout(function(){
							inMain.onMessage(msg)
						},0)
					}
				}

				function WrapFunction(){
					var globnames = []
					var globargs = []
					for(var key in global){
						globnames.push(key)
						globargs.push(global[key])
					}

					// lets push in all masked
					for(var i = 0; i < mask.length; i++){
						var name = mask[i]
						if(!(name in global)){
							globnames.push(name)
						}
					}

					var fnargs = []
					var args = arguments
					var len = arguments.length
					var code = '"use strict"\nreturn function('
					for(var i = 0; i < len - 1; i++){
						if(i) code += ','
						code += args[i]
					}
					code += '){'+args[i]+'}'
					globnames.push(code)
					return Function.apply(null, globnames).apply(null, globargs)
				}

				var global = {
					Object:Object,
					String:String,
					Number:Number,
					Boolean:Boolean,
					console:{
						log:console.log.bind(console)
					},
					setTimeout:setTimeout,
					clearTimeout:clearTimeout,
					setInterval:setInterval,
					clearInterval:clearInterval,
					Function:WrapFunction
				}

				function postBoot(){
				}

				new Function("Function","global", "worker", source+'\n'+postBoot.toString()+'\npostBoot()\n')(WrapFunction, global, inWorker)
				return inMain
			}
		}

		var src =
			'(function(){'+
			'	var global = self\n'+
			'	var worker = {postMessage:self.postMessage.bind(self)}\n'+
			'	self.onmessage = function(msg){worker.onMessage(msg.data)}\n'+
			getJsGlobals.toString()+
			cleanWebWorker.toString()+';cleanWebWorker();\n'+
			source+'\n'+
			'})()'

		var blob = URL.createObjectURL(new Blob([src], {type: "text/javascript"}))

		return function(){
			var worker = new Worker(blob)
			worker.onmessage = function(msg){
				this.onMessage(msg.data)
			}
			return worker
		}
	}

	// watches a file
	root.watchFile = function(localFile){

	}

	// inject a script tag for url
	root.showParseError = function(path){
		var script = document.createElement('script')
		script.type = 'text/javascript'
		script.src = location.origin+'/'+path
		document.getElementsByTagName('head')[0].appendChild(script)
	}

	// downloads a resource
	root.resourceCache = {}

	root.downloadResource = function(localFile, isBinary, appProgress){
		return new Promise(function(resolve, reject){
			var req = new XMLHttpRequest()

			// lets add this node to the canvas tag
			var progressDiv
			var progressTimeout
			if(appProgress){
				progressDiv = document.createElement('span')
				progressDiv.style.marginLeft = 50
				progressDiv.style.display = 'none'
				progressDiv.style.fontSize = '10px'
				progressDiv.style.color = 'white'// = 'margin-left:50;display:block;font-size:10px;color:white'
				progressDiv.innerHTML = 'Loading resource 0%'
				document.body.appendChild(progressDiv)
				req.addEventListener("progress", function(e){
					var pos = e.position || e.loaded
					var total = e.totalSize || e.total
					progressDiv.innerHTML = 'Loading resource '+Math.floor(100*pos / total)+'%
'
				})
				progressTimeout = setTimeout(function(){
					progressTimeout = undefined
					progressDiv.style.display = 'block'
				}, 2000)
			}
			req.addEventListener("error", function(){
				console.error('Error loading '+resourceurl+' from '+parenturl)
				reject(resource)
			})
			req.responseType = isBinary?'arraybuffer':'text'
			req.addEventListener("load", function(){
				if(appProgress){
					document.body.removeChild(progressDiv)
					if(progressTimeout) clearTimeout(progressTimeout)
				}
				if(req.status !== 200){
					return reject(resource)
				}
				root.resourceCache[localFile] = req.response
				resolve(req.response)
			})
			req.open("GET", location.origin+'/'+localFile)
			req.send()
		})
	}

	var canvasses =	document.getElementsByClassName('makepad')

	var initApps
	function init(){

		var apps = []
		for(var i = 0; i < canvasses.length; i++){
			var canvas = canvasses[i]
			apps.push({
				main:canvas.getAttribute('main'),
				platform:{
					canvas:canvas,
					search:location.search && location.search.slice(1)
				}
			})
		}
		if(root.onInitApps) root.onInitApps(apps)
		else initApps = apps
	}

	document.addEventListener('DOMContentLoaded', init)

	// load up boot file
	root.downloadResource(root.platformPath+'boot.js').then(function(result){
		// start it up
		try{
			new Function("root", result)(root)
		}
		catch(e){
			root.showParseError(root.platformPath+'boot.js')
			return
		}
		// if we were slower than DOMContentLoaded
		if(initApps) root.onInitApps(initApps)
	})

	function watchFileChange(){
		var req = new XMLHttpRequest()
		req.timeout = 60000
		req.addEventListener("error", function(){
			setTimeout(watchFileChange, 500)
		})
		req.responseType = 'text'
		req.addEventListener("load", function(){
			if(req.response === '{continue:true}') return watchFileChange()
			// do something with data, or not
			location.href = location.href
		})
		req.open("GET", "/$watch?"+(''+Math.random()).slice(2))
		req.send()
	}

	function getJsGlobals(){
		return [
			'console', 'eval', 'Infinity','NaN','undefined','null','isFinite','isNaN','parseFloat','parseInt',
			'Symbol','Error','EvalError','InternalError','RangeError','ReferenceError','TypeError','URIError',
			'Map','Set','WeakMap','WeakSet','SIMD','JSON','Generator','GeneratorFunction','Intl','SyntaxError',
			'Function', 'RegExp', 'Math', 'Object', 'String', 'Number','Boolean','Date', 'Array',
			'Int8Array','Uint8Array','Uint8ClampedArray','Int16Array','Uint16Array','Int32Array','Uint32Array',
			'Float32Array','Float64Array','DataView','ArrayBuffer','setTimeout','clearTimeout','setInterval','clearInterval'
		]
	}

	if(location.hostname === 'localhost' || location.hostname === '127.0.0.1' || location.hostname.indexOf('10.') === 0)
		watchFileChange()

	function cleanWebWorker(){
		var deprecated = [
			'webkitIDBTransaction','webkitIDBRequest','webkitIDBObjectStore','webkitIDBKeyRange','webkitIDBIndex','webkitIDBFactory',
			'webkitIDBDatabase','webkitIDBCursor'
		]
		var jsGlobals = getJsGlobals()
		var mask = Object.getOwnPropertyNames(self)
		var forceMask = []
		var LocalFunction = self.Function
		self.Function = function(){

			var args = []
			var len = arguments.length
			for(var i = 0; i < len - 1; i++) args.push(arguments[i])
			args.push.apply(args, forceMask)

			var code = arguments[len -1]
			args.push(code)
			return LocalFunction.apply(null, args)
		}

		for(var i = 0; i < mask.length; i++){
			var name = mask[i]
			if(jsGlobals.indexOf(name) !== -1) continue
			try{
				if(deprecated.indexOf(name)!==-1){
					self[name] = undefined
				}
				else Object.defineProperty(self, name, {value:undefined})
			}
			catch(e){
				forceMask.push(name)
			}
		}
		self = undefined
	}
})()<|endoftext|>


<commit_before>var mu = require("masm-util");

var argv = require("optimist")
        .default("host", process.env["COUCHDB_PORT_5984_TCP_ADDR"] || "localhost")
        .default("port", process.env["COUCHDB_PORT_5984_TCP_PORT"] || 5984)
        .default("username", process.env["COUCHDB_USERNAME"])
        .default("password", process.env["COUCHDB_PASSWORD"])
        .default("proxy", null)
        .default("force", false)
        .argv;

var cdb = require("masm-cdb").connection(argv.host, argv.port, argv.username, argv.password);

if (argv.proxy) {
    var m = argv.proxy.match(/^([^:]+):([0-9]+)$/);
    if (!m) {
        console.log("Invalid proxy specification");
        process.exit(1);
    }
    cdb.withProxy(m[1], parseInt(m[2], 10));
}

var rcdb = require("masm-rcdb")(cdb);

rcdb.allDBs({
    ok: function (data) {
        mu.eachSync(data, function (dbName, callback) {
            console.log(dbName);
            handleDB(dbName, function (err) {
                console.dir(err);
                callback();
            }, callback);
        }, function () {
            console.log("All done.");
        });
    }
});

function handleDB (dbName, escapeCallback, callback) {
    getDBInfo(dbName, escapeCallback, function (dbInfo) {
        compactDB(dbName, escapeCallback, function () {
            ddocNames(dbName, escapeCallback, function (ddocs) {
                viewCleanup(dbName, escapeCallback, function () {
                    mu.eachSync(ddocs, function (ddoc, next) {
                        compactView(dbName, ddoc, escapeCallback, callback);
                    }, callback);
                });
            });
        });
    });
}

function databaseIsFragmented (dbInfo) {
    return argv.force || dbInfo.data_size / dbInfo.disk_size  < 0.5;
}

function ddocNames (dbName, escapeCallback, callback) {
    rcdb.getAllDocs(dbName, {startkey: JSON.stringify("_design/"), endkey: JSON.stringify("_design/~")}, {
        not_found: function (err, retry) { escapeCallback(err); },
        ok: function (data) {
            var ddocs = (data.rows || []).map(function (row) {
                var m =  row.id.match(/^_design\/(.*)$/);
                return m[1];
            });
            callback(ddocs);
        }
    });
}

function compactDB (dbName, escapeCallback, callback) {
    rcdb.compactDB(dbName, {
        not_found: function (err, retry) { escapeCallback(err); },
        ok: function () {
            waitCompactionDone(dbName, escapeCallback, callback);
        }
    });
}

function waitCompactionDone (dbName, escapeCallback, callback) {
    mu.retryWithThrottling(function (retry) {
        getDBInfo(dbName, escapeCallback, function (data) {
            if (data.compact_running) {
                retry();
            } else {
                callback();
            }
        });
    });
}

function getDBInfo (dbName, escapeCallback, callback) {
    rcdb.getDB(dbName, {
        not_found: function (err, retry) { escapeCallback(err); },
        ok: callback
    });
}

function viewCleanup (dbName, escapeCallback, callback) {
    rcdb.viewCleanup(dbName, {
        not_found: function (err, retry) { escapeCallback(err); },
        ok: callback
    });
}

function compactView (dbName, ddoc, escapeCallback, callback) {
    rcdb.compactViews(dbName, ddoc, {
        not_found: function (err, rerty) { escapeCallback(err); },
        ok: function () {
            waitViewCompactionDone(dbName, ddoc, escapeCallback, callback);
        }
    });
}

function waitViewCompactionDone (dbName, ddoc, escapeCallback, callback) {
    mu.retryWithThrottling(function (retry) {
        getDdocInfo(dbName, ddoc, escapeCallback, function (data) {
            if (data.view_index.compact_running) {
                retry();
            } else {
                callback();
            }
        });
    });
}

function getDdocInfo (dbName, ddoc, escapeCallback, callback) {
    rcdb.ddocInfo(dbName, ddoc,  {
        not_found: function (err, retry) { escapeCallback(err); },
        ok:  callback
    });
}
<commit_msg>Add alternative variables<commit_after>var mu = require("masm-util");

var argv = require("optimist")
        .default("host", process.env["COUCHDB_PORT_5984_TCP_ADDR"] || process.env["COUCHDB_HOST"] || "localhost")
        .default("port", process.env["COUCHDB_PORT_5984_TCP_PORT"] || process.env["COUCHDB_PORT"]  || 5984)
        .default("username", process.env["COUCHDB_USERNAME"])
        .default("password", process.env["COUCHDB_PASSWORD"])
        .default("proxy", null)
        .default("force", false)
        .argv;

var cdb = require("masm-cdb").connection(argv.host, argv.port, argv.username, argv.password);

if (argv.proxy) {
    var m = argv.proxy.match(/^([^:]+):([0-9]+)$/);
    if (!m) {
        console.log("Invalid proxy specification");
        process.exit(1);
    }
    cdb.withProxy(m[1], parseInt(m[2], 10));
}

var rcdb = require("masm-rcdb")(cdb);

rcdb.allDBs({
    ok: function (data) {
        mu.eachSync(data, function (dbName, callback) {
            console.log(dbName);
            handleDB(dbName, function (err) {
                console.dir(err);
                callback();
            }, callback);
        }, function () {
            console.log("All done.");
        });
    }
});

function handleDB (dbName, escapeCallback, callback) {
    getDBInfo(dbName, escapeCallback, function (dbInfo) {
        compactDB(dbName, escapeCallback, function () {
            ddocNames(dbName, escapeCallback, function (ddocs) {
                viewCleanup(dbName, escapeCallback, function () {
                    mu.eachSync(ddocs, function (ddoc, next) {
                        compactView(dbName, ddoc, escapeCallback, callback);
                    }, callback);
                });
            });
        });
    });
}

function databaseIsFragmented (dbInfo) {
    return argv.force || dbInfo.data_size / dbInfo.disk_size  < 0.5;
}

function ddocNames (dbName, escapeCallback, callback) {
    rcdb.getAllDocs(dbName, {startkey: JSON.stringify("_design/"), endkey: JSON.stringify("_design/~")}, {
        not_found: function (err, retry) { escapeCallback(err); },
        ok: function (data) {
            var ddocs = (data.rows || []).map(function (row) {
                var m =  row.id.match(/^_design\/(.*)$/);
                return m[1];
            });
            callback(ddocs);
        }
    });
}

function compactDB (dbName, escapeCallback, callback) {
    rcdb.compactDB(dbName, {
        not_found: function (err, retry) { escapeCallback(err); },
        ok: function () {
            waitCompactionDone(dbName, escapeCallback, callback);
        }
    });
}

function waitCompactionDone (dbName, escapeCallback, callback) {
    mu.retryWithThrottling(function (retry) {
        getDBInfo(dbName, escapeCallback, function (data) {
            if (data.compact_running) {
                retry();
            } else {
                callback();
            }
        });
    });
}

function getDBInfo (dbName, escapeCallback, callback) {
    rcdb.getDB(dbName, {
        not_found: function (err, retry) { escapeCallback(err); },
        ok: callback
    });
}

function viewCleanup (dbName, escapeCallback, callback) {
    rcdb.viewCleanup(dbName, {
        not_found: function (err, retry) { escapeCallback(err); },
        ok: callback
    });
}

function compactView (dbName, ddoc, escapeCallback, callback) {
    rcdb.compactViews(dbName, ddoc, {
        not_found: function (err, rerty) { escapeCallback(err); },
        ok: function () {
            waitViewCompactionDone(dbName, ddoc, escapeCallback, callback);
        }
    });
}

function waitViewCompactionDone (dbName, ddoc, escapeCallback, callback) {
    mu.retryWithThrottling(function (retry) {
        getDdocInfo(dbName, ddoc, escapeCallback, function (data) {
            if (data.view_index.compact_running) {
                retry();
            } else {
                callback();
            }
        });
    });
}

function getDdocInfo (dbName, ddoc, escapeCallback, callback) {
    rcdb.ddocInfo(dbName, ddoc,  {
        not_found: function (err, retry) { escapeCallback(err); },
        ok:  callback
    });
}
<|endoftext|>


<commit_before>/*
 *
 * FocusLine
 *
 */

import React from 'react'
import R from 'ramda'
import PropTypes from 'prop-types'

import { Wrapper, Icon, TextWrapper, Text, Focus } from './styles'

import { makeDebugger } from '../../utils'
/* eslint-disable no-unused-vars */
const debug = makeDebugger('c:FocusLine:index')
/* eslint-enable no-unused-vars */

const FocusLine = ({ iconSrc, before, focus, after }) => (
  <Wrapper>
    <Icon src={iconSrc} show={!R.isEmpty(iconSrc)} />
    <TextWrapper>
      <Text>{before}</Text> <Focus>{focus}</Focus> <Text>{after}</Text>
    </TextWrapper>
  </Wrapper>
)

FocusLine.propTypes = {
  iconSrc: PropTypes.string,
  before: PropTypes.string.isRequired,
  focus: PropTypes.string.isRequired,
  after: PropTypes.string.isRequired,
}

FocusLine.defaultProps = {
  iconSrc: '',
}

export default FocusLine
<commit_msg>fix: fix PropsType warninge<commit_after>/*
 *
 * FocusLine
 *
 */

import React from 'react'
import R from 'ramda'
import PropTypes from 'prop-types'

import { Wrapper, Icon, TextWrapper, Text, Focus } from './styles'

import { makeDebugger } from '../../utils'
/* eslint-disable no-unused-vars */
const debug = makeDebugger('c:FocusLine:index')
/* eslint-enable no-unused-vars */

const FocusLine = ({ iconSrc, before, focus, after }) => (
  <Wrapper>
    <Icon src={iconSrc} show={!R.isEmpty(iconSrc)} />
    <TextWrapper>
      <Text>{before}</Text> <Focus>{focus}</Focus> <Text>{after}</Text>
    </TextWrapper>
  </Wrapper>
)

FocusLine.propTypes = {
  iconSrc: PropTypes.string,
  before: PropTypes.string.isRequired,
  focus: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
  after: PropTypes.string.isRequired,
}

FocusLine.defaultProps = {
  iconSrc: '',
}

export default FocusLine
<|endoftext|>