<commit_before>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */
require(["jquery", "sakai/sakai.api.core"], function($, sakai) {

    /**
     * @name sakai_global.entity
     *
     * @class entity
     *
     * @description
     * Initialize the entity widget
     *
     * @version 0.0.1
     * @param {String} tuid Unique id of the widget
     * @param {Boolean} showSettings Show the settings of the widget or not
     */
    sakai_global.entity = function(tuid, showSettings){

        /////////////////////////////
        // CONFIGURATION VARIABLES //
        /////////////////////////////

        var $rootel = $("#" + tuid);

        // Containers
        var entityContainer = "#entity_container";
        var entityUserPictureDropdown = ".entity_user_picture_dropdown";
        var entityUserCreateAddDropdown = ".entity_user_create_add_dropdown";

        // Buttons
        var entityUserCreateAndAdd = "#entity_user_create_and_add";
        var entityUserImage = "#entity_user_image";
        var entityUserMessage = "#entity_user_message";
        var entityUserAddToContacts = "#entity_user_add_to_contacts";
        var entityUserDropdown = "#entity_user_image.s3d-dropdown-menu";
        var entityGroupDropdown = "#entity_group_image.s3d-dropdown-menu";

        /**
         * The 'context' variable can have the following values:
         * - 'user_me' When the viewed user page is the current logged in user
         * - 'user_other' When the viewed user page is a user that is not a contact
         * - 'contact' When the viewed user page is one of a contact
         * @param {String} context String defining the context of the entity widget
         */
        var addBinding = function(context){
            switch(context.type){
                case "user_me":
                    $(entityUserCreateAndAdd).bind("click", function(){
                        if($(this).hasClass("entity_user_created_add_clicked")){
                            $(this).removeClass("entity_user_created_add_clicked");
                            $(entityUserCreateAddDropdown).hide();
                        }else{
                            $(this).addClass("entity_user_created_add_clicked");
                            $(entityUserCreateAddDropdown).show();
                            $(entityUserCreateAddDropdown).css("left", $(this).position().left - 38);
                        }
                    });
                    $(entityUserDropdown).hover(function(){
                        var $li = $(this);
                        var $subnav = $li.children(".s3d-dropdown-container");

                        var pos = $li.position();
                        $subnav.css("left", pos.left + 15);
                        $subnav.css("margin-top", $li.height() + 4 + "px");
                        $subnav.show();
                    }, function(){
                        var $li = $(this);
                        $li.children(".s3d-dropdown-container").hide();
                    });
                    break;
                case "user_other":
                    $(entityUserMessage).bind("click", function(){
                        // Place message functionality
                    });
                    $(entityUserAddToContacts).bind("click", function(){
                        // Place contacts functionality
                    });
                    break;
                case "contact":
                    $(entityUserMessage).bind("click", function(){
                        // Place message functionality
                    });
                    break;
                case "group_managed":
                    $('#entity_groupsettings_dropdown').html(sakai.api.Util.TemplateRenderer("entity_groupsettings_dropdown", context));

                    $('#ew_group_settings_edit_link').live("click", function(ev) {
                        $(window).trigger("init.worldsettings.sakai", context.data.authprofile['sakai:group-id']);
                        $('#entity_groupsettings_dropdown').jqmHide();
                    });

                    $(entityGroupDropdown).hover(function(){
                        var $li = $(this);
                        var $subnav = $li.children(".s3d-dropdown-container");

                        var pos = $li.position();
                        $subnav.css("left", pos.left + 5);
                        $subnav.css("margin-top", $li.height() + 4 + "px");
                        $subnav.show();
                    }, function(){
                        var $li = $(this);
                        $li.children(".s3d-dropdown-container").hide();
                    });
                    $(window).trigger("setData.changepic.sakai", ["group", context.data.authprofile["sakai:group-id"]]);
                    $(window).bind("ready.changepic.sakai", function(){
                        $(window).trigger("setData.changepic.sakai", ["group", context.data.authprofile["sakai:group-id"]]);
                    });
                    break;
                case "group":
                    $(window).bind("ready.joinrequestbuttons.sakai", function() {
                        var url = "/system/userManager/group/" +
                            context.data.authprofile["sakai:group-id"] + ".managers.json";
                        $.ajax({
                            url: url,
                            success: function(managers){
                                $(window).trigger("init.joinrequestbuttons.sakai", [
                                    context.data.authprofile.groupid,
                                    context.data.authprofile["sakai:group-joinable"],
                                    managers.length,
                                    function (renderedButtons) {
                                        // onShow
                                        $("#joinrequestbuttons_widget", $rootel).show();
                                    }
                                ]);
                            }
                        });
                    });
                    sakai.api.Widgets.widgetLoader.insertWidgets("entity_container", false, $rootel);
                    break;
                case "content_anon": //fallthrough
                case "content_not_shared": //fallthrough
                case "content_shared": //fallthrough
                case "content_managed":
                    var $entityContentUsersDialog = $("#entity_content_users_dialog");
                    var $entityContentUsersDialogContainer = $("#entity_content_users_dialog_list_container");
                    var entityContentUsersDialogTemplate = "#entity_content_users_dialog_list_template";

                    $entityContentUsersDialog.jqm({
                        modal: true,
                        overlay: 20,
                        toTop: true
                    });

                    $(".entity_content_people").live("click", function(){
                        $entityContentUsersDialog.jqmShow();

                        var userList = sakai_global.content_profile.content_data.members.managers.concat(sakai_global.content_profile.content_data.members.viewers);
                        var json = {
                            "userList": userList,
                            "type": "people",
                            sakai: sakai
                        };

                        // render dialog template
                        sakai.api.Util.TemplateRenderer(entityContentUsersDialogTemplate, json, $entityContentUsersDialogContainer);
                        $("#entity_content_users_dialog_heading").html($("#entity_content_people").html());

                        return false;
                    });

                    $(".entity_content_group").live("click", function(){
                        var userList = sakai_global.content_profile.content_data.members.managers.concat(sakai_global.content_profile.content_data.members.viewers);
                        $entityContentUsersDialog.jqmShow();

                        var json = {
                            "userList": userList,
                            "type": "groups",
                            sakai: sakai
                        };

                        // render users dialog template
                        sakai.api.Util.TemplateRenderer(entityContentUsersDialogTemplate, json, $entityContentUsersDialogContainer);
                        $entityContentUsersDialogContainer.show();
                        $("#entity_content_users_dialog_heading").html($("#entity_content_groups").html());

                        return false;
                    });

                    $('#entity_contentsettings_dropdown').html(sakai.api.Util.TemplateRenderer("entity_contentsettings_dropdown", context));

                    $("#entity_comments_link").live("click", function(){
                        $("html:not(:animated),body:not(:animated)").animate({ scrollTop: $("#comments_mainContainer").offset().top}, 500 );
                        $("#comments_txtMessage").focus();
                       return false;

                    });
                    break;
            }
       };

        var renderEntity = function(context){
            context.sakai = sakai;
            $(entityContainer).html(sakai.api.Util.TemplateRenderer("entity_" + context.context + "_template", context));
            $("#entity_message").click(function(){
                var to = {type: context.context};
                if (to.type === "group") {
                    to.uuid = context.data.authprofile["groupid"];
                    to.username = context.data.authprofile["sakai:group-title"];
                }
                $(window).trigger("initialize.sendmessage.sakai", to);
            });
        };

        $(window).bind("sakai.entity.init", function(ev, context, type, data){
            var obj = {
                "context": context,
                "type": type,
                "anon": sakai.data.me.user.anon || false,
                "data": data || {}
            };
            renderEntity(obj);
            addBinding(obj);
            $('#entity_contentsettings_dropdown').jqm({
                modal: false,
                overlay: 1,
                toTop: true,
                zIndex: 3000
            });

            $('#entity_groupsettings_dropdown').jqm({
                modal: false,
                overlay: 1,
                toTop: true,
                zIndex: 3000
            });

            $('#entity_content_permissions').click(function(){
                var $this = $(this);
                $('#entity_contentsettings_dropdown')
                .css({'top':$this.offset().top + $this.height() - 5,'left':$this.offset().left + $this.width() / 2 - 160})
                .jqmShow();
            });

            $("#entity_group_permissions").click(function(){
                var $this = $(this);
                $('#entity_groupsettings_dropdown')
                .css({'top':$this.offset().top + $this.height() - 5,'left':$this.offset().left + $this.width() / 2 - 160})
                .jqmShow();
            });

            $("#ew_group_categories_link").click(function(){
                $("#assignlocation_container").jqmShow();
                $('#entity_groupsettings_dropdown').jqmHide();
            });

            $('#ew_permissions>a').click(function(e){
                e.preventDefault();
                $(window).trigger("init.contentpermissions.sakai");
                $('#entity_contentsettings_dropdown').jqmHide();
            });

            $('#ew_upload>a').click(function(e){
                e.preventDefault();
                $(window).trigger("init.uploadnewversion.sakai");
                $('#entity_contentsettings_dropdown').jqmHide();
            });

            $("#ew_revhistory").click(function(e){
                $(window).trigger("init.versions.sakai", {
                    pageSavePath: sakai_global.content_profile.content_data.content_path,
                    saveRef: "",
                    showByDefault: true
                });
                $('#entity_contentsettings_dropdown').jqmHide();
            });

            $("#ew_content_preview_delete>a").bind("click", function(e){
                e.preventDefault();
                window.scrollTo(0,0);
                $(window).trigger('init.deletecontent.sakai', [sakai_global.content_profile.content_data,
                    function (success) {
                        if (success) {
                            // Wait for 2 seconds
                            setTimeout(function () {
                                // Relocate to the my sakai page
                                document.location = "/dev/me.html";  // TODO TEMPORARY REDIRECT!!!
                            }, 2000);
                        }
                    }]
                );
                $('#entity_contentsettings_dropdown').jqmHide();
            });

            $(".addpeople_init").click(function(){
                $(window).trigger("init.addpeople.sakai", [tuid]);
                $("#entity_groupsettings_dropdown").jqmHide();
            })

        });

        // An event to call from the worldsettings dialog so that we can
        // refresh the title if it's been saved.
        $(window).bind("sakai.entity.updateTitle", function(e, title) {
            $('#entity_name').html(title);
        });

        $(window).trigger("sakai.entity.ready");

    };
    sakai.api.Widgets.widgetLoader.informOnLoad("entity");
});
<commit_msg>SAKIII-3145 - Delete operation fails from the content profile<commit_after>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */
require(["jquery", "sakai/sakai.api.core"], function($, sakai) {

    /**
     * @name sakai_global.entity
     *
     * @class entity
     *
     * @description
     * Initialize the entity widget
     *
     * @version 0.0.1
     * @param {String} tuid Unique id of the widget
     * @param {Boolean} showSettings Show the settings of the widget or not
     */
    sakai_global.entity = function(tuid, showSettings){

        /////////////////////////////
        // CONFIGURATION VARIABLES //
        /////////////////////////////

        var $rootel = $("#" + tuid);

        // Containers
        var entityContainer = "#entity_container";
        var entityUserPictureDropdown = ".entity_user_picture_dropdown";
        var entityUserCreateAddDropdown = ".entity_user_create_add_dropdown";

        // Buttons
        var entityUserCreateAndAdd = "#entity_user_create_and_add";
        var entityUserImage = "#entity_user_image";
        var entityUserMessage = "#entity_user_message";
        var entityUserAddToContacts = "#entity_user_add_to_contacts";
        var entityUserDropdown = "#entity_user_image.s3d-dropdown-menu";
        var entityGroupDropdown = "#entity_group_image.s3d-dropdown-menu";

        /**
         * The 'context' variable can have the following values:
         * - 'user_me' When the viewed user page is the current logged in user
         * - 'user_other' When the viewed user page is a user that is not a contact
         * - 'contact' When the viewed user page is one of a contact
         * @param {String} context String defining the context of the entity widget
         */
        var addBinding = function(context){
            switch(context.type){
                case "user_me":
                    $(entityUserCreateAndAdd).bind("click", function(){
                        if($(this).hasClass("entity_user_created_add_clicked")){
                            $(this).removeClass("entity_user_created_add_clicked");
                            $(entityUserCreateAddDropdown).hide();
                        }else{
                            $(this).addClass("entity_user_created_add_clicked");
                            $(entityUserCreateAddDropdown).show();
                            $(entityUserCreateAddDropdown).css("left", $(this).position().left - 38);
                        }
                    });
                    $(entityUserDropdown).hover(function(){
                        var $li = $(this);
                        var $subnav = $li.children(".s3d-dropdown-container");

                        var pos = $li.position();
                        $subnav.css("left", pos.left + 15);
                        $subnav.css("margin-top", $li.height() + 4 + "px");
                        $subnav.show();
                    }, function(){
                        var $li = $(this);
                        $li.children(".s3d-dropdown-container").hide();
                    });
                    break;
                case "user_other":
                    $(entityUserMessage).bind("click", function(){
                        // Place message functionality
                    });
                    $(entityUserAddToContacts).bind("click", function(){
                        // Place contacts functionality
                    });
                    break;
                case "contact":
                    $(entityUserMessage).bind("click", function(){
                        // Place message functionality
                    });
                    break;
                case "group_managed":
                    $('#entity_groupsettings_dropdown').html(sakai.api.Util.TemplateRenderer("entity_groupsettings_dropdown", context));

                    $('#ew_group_settings_edit_link').live("click", function(ev) {
                        $(window).trigger("init.worldsettings.sakai", context.data.authprofile['sakai:group-id']);
                        $('#entity_groupsettings_dropdown').jqmHide();
                    });

                    $(entityGroupDropdown).hover(function(){
                        var $li = $(this);
                        var $subnav = $li.children(".s3d-dropdown-container");

                        var pos = $li.position();
                        $subnav.css("left", pos.left + 5);
                        $subnav.css("margin-top", $li.height() + 4 + "px");
                        $subnav.show();
                    }, function(){
                        var $li = $(this);
                        $li.children(".s3d-dropdown-container").hide();
                    });
                    $(window).trigger("setData.changepic.sakai", ["group", context.data.authprofile["sakai:group-id"]]);
                    $(window).bind("ready.changepic.sakai", function(){
                        $(window).trigger("setData.changepic.sakai", ["group", context.data.authprofile["sakai:group-id"]]);
                    });
                    break;
                case "group":
                    $(window).bind("ready.joinrequestbuttons.sakai", function() {
                        var url = "/system/userManager/group/" +
                            context.data.authprofile["sakai:group-id"] + ".managers.json";
                        $.ajax({
                            url: url,
                            success: function(managers){
                                $(window).trigger("init.joinrequestbuttons.sakai", [
                                    context.data.authprofile.groupid,
                                    context.data.authprofile["sakai:group-joinable"],
                                    managers.length,
                                    function (renderedButtons) {
                                        // onShow
                                        $("#joinrequestbuttons_widget", $rootel).show();
                                    }
                                ]);
                            }
                        });
                    });
                    sakai.api.Widgets.widgetLoader.insertWidgets("entity_container", false, $rootel);
                    break;
                case "content_anon": //fallthrough
                case "content_not_shared": //fallthrough
                case "content_shared": //fallthrough
                case "content_managed":
                    var $entityContentUsersDialog = $("#entity_content_users_dialog");
                    var $entityContentUsersDialogContainer = $("#entity_content_users_dialog_list_container");
                    var entityContentUsersDialogTemplate = "#entity_content_users_dialog_list_template";

                    $entityContentUsersDialog.jqm({
                        modal: true,
                        overlay: 20,
                        toTop: true
                    });

                    $(".entity_content_people").live("click", function(){
                        $entityContentUsersDialog.jqmShow();

                        var userList = sakai_global.content_profile.content_data.members.managers.concat(sakai_global.content_profile.content_data.members.viewers);
                        var json = {
                            "userList": userList,
                            "type": "people",
                            sakai: sakai
                        };

                        // render dialog template
                        sakai.api.Util.TemplateRenderer(entityContentUsersDialogTemplate, json, $entityContentUsersDialogContainer);
                        $("#entity_content_users_dialog_heading").html($("#entity_content_people").html());

                        return false;
                    });

                    $(".entity_content_group").live("click", function(){
                        var userList = sakai_global.content_profile.content_data.members.managers.concat(sakai_global.content_profile.content_data.members.viewers);
                        $entityContentUsersDialog.jqmShow();

                        var json = {
                            "userList": userList,
                            "type": "groups",
                            sakai: sakai
                        };

                        // render users dialog template
                        sakai.api.Util.TemplateRenderer(entityContentUsersDialogTemplate, json, $entityContentUsersDialogContainer);
                        $entityContentUsersDialogContainer.show();
                        $("#entity_content_users_dialog_heading").html($("#entity_content_groups").html());

                        return false;
                    });

                    $('#entity_contentsettings_dropdown').html(sakai.api.Util.TemplateRenderer("entity_contentsettings_dropdown", context));

                    $("#entity_comments_link").live("click", function(){
                        $("html:not(:animated),body:not(:animated)").animate({ scrollTop: $("#comments_mainContainer").offset().top}, 500 );
                        $("#comments_txtMessage").focus();
                       return false;

                    });
                    break;
            }
       };

        var renderEntity = function(context){
            context.sakai = sakai;
            $(entityContainer).html(sakai.api.Util.TemplateRenderer("entity_" + context.context + "_template", context));
            $("#entity_message").click(function(){
                var to = {type: context.context};
                if (to.type === "group") {
                    to.uuid = context.data.authprofile["groupid"];
                    to.username = context.data.authprofile["sakai:group-title"];
                }
                $(window).trigger("initialize.sendmessage.sakai", to);
            });
        };

        $(window).bind("sakai.entity.init", function(ev, context, type, data){
            var obj = {
                "context": context,
                "type": type,
                "anon": sakai.data.me.user.anon || false,
                "data": data || {}
            };
            renderEntity(obj);
            addBinding(obj);
            $('#entity_contentsettings_dropdown').jqm({
                modal: false,
                overlay: 1,
                toTop: true,
                zIndex: 3000
            });

            $('#entity_groupsettings_dropdown').jqm({
                modal: false,
                overlay: 1,
                toTop: true,
                zIndex: 3000
            });

            $('#entity_content_permissions').click(function(){
                var $this = $(this);
                $('#entity_contentsettings_dropdown')
                .css({'top':$this.offset().top + $this.height() - 5,'left':$this.offset().left + $this.width() / 2 - 160})
                .jqmShow();
            });

            $("#entity_group_permissions").click(function(){
                var $this = $(this);
                $('#entity_groupsettings_dropdown')
                .css({'top':$this.offset().top + $this.height() - 5,'left':$this.offset().left + $this.width() / 2 - 160})
                .jqmShow();
            });

            $("#ew_group_categories_link").click(function(){
                $("#assignlocation_container").jqmShow();
                $('#entity_groupsettings_dropdown').jqmHide();
            });

            $('#ew_permissions>a').click(function(e){
                e.preventDefault();
                $(window).trigger("init.contentpermissions.sakai");
                $('#entity_contentsettings_dropdown').jqmHide();
            });

            $('#ew_upload>a').click(function(e){
                e.preventDefault();
                $(window).trigger("init.uploadnewversion.sakai");
                $('#entity_contentsettings_dropdown').jqmHide();
            });

            $("#ew_revhistory").click(function(e){
                $(window).trigger("init.versions.sakai", {
                    pageSavePath: sakai_global.content_profile.content_data.content_path,
                    saveRef: "",
                    showByDefault: true
                });
                $('#entity_contentsettings_dropdown').jqmHide();
            });

            $("#ew_content_preview_delete>a").bind("click", function(e){
                e.preventDefault();
                window.scrollTo(0,0);
                $(window).trigger('init.deletecontent.sakai', [{"path": sakai_global.content_profile.content_data.content_path},
                    function (success) {
                        if (success) {
                            // Wait for 2 seconds
                            setTimeout(function () {
                                // Relocate to the my sakai page
                                document.location = "/dev/me.html";  // TODO TEMPORARY REDIRECT!!!
                            }, 2000);
                        }
                    }]
                );
                $('#entity_contentsettings_dropdown').jqmHide();
            });

            $(".addpeople_init").click(function(){
                $(window).trigger("init.addpeople.sakai", [tuid]);
                $("#entity_groupsettings_dropdown").jqmHide();
            })

        });

        // An event to call from the worldsettings dialog so that we can
        // refresh the title if it's been saved.
        $(window).bind("sakai.entity.updateTitle", function(e, title) {
            $('#entity_name').html(title);
        });

        $(window).trigger("sakai.entity.ready");

    };
    sakai.api.Widgets.widgetLoader.informOnLoad("entity");
});
<|endoftext|>


<commit_before>/*!
 * Module dependencies.
 */

var cordova = require('./phonegap/util/cordova'),
    emitter = require('./phonegap/util/emitter'),
    bind = require('./phonegap/util/bind');

/**
 * PhoneGap object.
 *
 * Events:
 *
 *   - `err` {Event} triggered with info compatible with console.error.
 *   - `log` {Event} triggered with info compatible with console.log.
 *   - `warn` {Event} triggered with info compatible with console.warn.
 *   - `login` {Event} triggered when login credentials are needed.
 *     - `callback` {Function} is triggered with user credentials
 *       - `username` {String}
 *       - `password` {String}
 */

function PhoneGap() {
    // standardize access to the phonegap object as this.phonegap.
    // required for functions to invoke each other in a testable manner.
    this.phonegap = this;
    this.local.phonegap = this;
    this.remote.phonegap = this;

    // initialize each command and inject the `phonegap` dependency.
    this.app = require('./phonegap/app').init(this);
    this.build = require('./phonegap/build').init(this);
    this.create = require('./phonegap/create').init(this);
    this.local.build = require('./phonegap/local.build').init(this);
    this.remote.build = require('./phonegap/remote.build').init(this);
    this.remote.login = require('./phonegap/remote.login').init(this);
    this.remote.logout = require('./phonegap/remote.logout').init(this);
}

/*!
 * PhoneGap prototype chain composed of isolated actions.
 */

PhoneGap.prototype.local = {};
PhoneGap.prototype.remote = {};

/*!
 * Expose the PhoneGap object.
 */

var phonegap = new PhoneGap();
bind(emitter, phonegap);

module.exports = phonegap;
<commit_msg>[#34] Remove previous dependency management.<commit_after>/*!
 * Module dependencies.
 */

var cordova = require('./phonegap/util/cordova'),
    emitter = require('./phonegap/util/emitter'),
    bind = require('./phonegap/util/bind');

/**
 * PhoneGap object.
 *
 * Events:
 *
 *   - `err` {Event} triggered with info compatible with console.error.
 *   - `log` {Event} triggered with info compatible with console.log.
 *   - `warn` {Event} triggered with info compatible with console.warn.
 *   - `login` {Event} triggered when login credentials are needed.
 *     - `callback` {Function} is triggered with user credentials
 *       - `username` {String}
 *       - `password` {String}
 */

function PhoneGap() {
    // initialize each command and inject the `phonegap` dependency.
    this.app = require('./phonegap/app').init(this);
    this.build = require('./phonegap/build').init(this);
    this.create = require('./phonegap/create').init(this);
    this.local.build = require('./phonegap/local.build').init(this);
    this.remote.build = require('./phonegap/remote.build').init(this);
    this.remote.login = require('./phonegap/remote.login').init(this);
    this.remote.logout = require('./phonegap/remote.logout').init(this);
}

/*!
 * PhoneGap prototype chain.
 */

PhoneGap.prototype.local = {};
PhoneGap.prototype.remote = {};

/*!
 * Expose the PhoneGap object.
 */

var phonegap = new PhoneGap();
bind(emitter, phonegap);

module.exports = phonegap;
<|endoftext|>


<commit_before>/**
* LICENSE MIT
* (C) Daniel Zelisko
* http://github.com/danielzzz/node-ping
*
* a simple wrapper for ping
*
*/

var sys   = require('util'),
    cp = require('child_process');
    os = require('os');

function probe(addr, cb) {
        var p = os.platform();
        var ls = null;

        if (p == 'linux') {
            //linux
            ls = cp.spawn('/bin/ping', ['-n', '-w 2', '-c 1', addr]);
        } else if (p.match(/^win/)) {
            //windows
            var ls = cp.spawn('C:/windows/system32/ping.exe', ['-n', '1', '-w', '5000', addr]);

        } else if (p == 'darwin') {
            //mac osx
            var ls = cp.spawn('/sbin/ping', ['-n', '-t 2', '-c 1', addr]);
        }

        ls.on('error', function(e) {
            throw new Error('ping.probe: there was an error while executing the ping program. check the path or permissions...');
        });

        ls.stdout.on('data', function (data) {
            // workaround for windows machines
            // if host is unreachable ping will return
            // a successfull error code
            // so we ned to handle this ourself
            var s = String(data);
            if (s.indexOf("unreachable") != -1) {
                cb && cb(false);
                cb = undefined;
            }
        });

        ls.stderr.on('data', function (data) {
          //sys.print('stderr: ' + data);
        });*/

        ls.on('exit', function (code) {
            var result = (code === 0 ? true : false);
            cb && cb(result);
        });
}

exports.probe = probe;
<commit_msg>Update ping-sys.js<commit_after>/**
* LICENSE MIT
* (C) Daniel Zelisko
* http://github.com/danielzzz/node-ping
*
* a simple wrapper for ping
*
*/

var sys   = require('util'),
    cp = require('child_process');
    os = require('os');

function probe(addr, cb) {
        var p = os.platform();
        var ls = null;

        if (p == 'linux') {
            //linux
            ls = cp.spawn('/bin/ping', ['-n', '-w 2', '-c 1', addr]);
        } else if (p.match(/^win/)) {
            //windows
            var ls = cp.spawn('C:/windows/system32/ping.exe', ['-n', '1', '-w', '5000', addr]);

        } else if (p == 'darwin') {
            //mac osx
            var ls = cp.spawn('/sbin/ping', ['-n', '-t 2', '-c 1', addr]);
        }

        ls.on('error', function(e) {
            throw new Error('ping.probe: there was an error while executing the ping program. check the path or permissions...');
        });

        ls.stdout.on('data', function (data) {
            // workaround for windows machines
            // if host is unreachable ping will return
            // a successfull error code
            // so we ned to handle this ourself
            var s = String(data);
            if (s.indexOf("unreachable") != -1) {
                cb && cb(false);
                cb = undefined;
            }
        });

        ls.stderr.on('data', function (data) {
          //sys.print('stderr: ' + data);
        });

        ls.on('exit', function (code) {
            var result = (code === 0 ? true : false);
            cb && cb(result);
        });
}

exports.probe = probe;
<|endoftext|>


<commit_before>/**
 * @license Copyright (c) 2010 Brian Cavalier
 * LICENSE: see the LICENSE.txt file. If file is missing, this file is subject
 * to the MIT License at: http://www.opensource.org/licenses/mit-license.php.
 */

/*
	File: dom.js
	wire plugin that provides a resource resolver for dom nodes, by id, in the
	current page.  This allows easy wiring of page-specific dom references into
	generic components that may be page-independent, i.e. makes it easier to write
	components that can be used on multiple pages, but still require a reference
	to one or more nodes on the page.
*/
define({
	/*
		Function: dom
		Resolves a reference to a dom node on the page by its id

		Parameters:
			factory - wiring factory
			name - id of dom node
			refObj - complete JSON ref
			promise - factory-provided <Promise> that will be resolved with the
				dom node.
	*/
	wire$plugin: function resolveDomId(ready, options) {
		return {
			resolvers: {
				dom: function(id, refObj, wire, promise) {
					wire.domReady(function() {
						var node = document.getElementById(id);
						if(node) promise.resolve(node);
						else promise.reject();
					});
				}
			}
		}
	}
});<commit_msg>Minor function expression name change<commit_after>/**
 * @license Copyright (c) 2010 Brian Cavalier
 * LICENSE: see the LICENSE.txt file. If file is missing, this file is subject
 * to the MIT License at: http://www.opensource.org/licenses/mit-license.php.
 */

/*
	File: dom.js
	wire plugin that provides a resource resolver for dom nodes, by id, in the
	current page.  This allows easy wiring of page-specific dom references into
	generic components that may be page-independent, i.e. makes it easier to write
	components that can be used on multiple pages, but still require a reference
	to one or more nodes on the page.
*/
define({
	/*
		Function: dom
		Resolves a reference to a dom node on the page by its id

		Parameters:
			factory - wiring factory
			name - id of dom node
			refObj - complete JSON ref
			promise - factory-provided <Promise> that will be resolved with the
				dom node.
	*/
	wire$plugin: function domPlugin(ready, options) {
		return {
			resolvers: {
				dom: function(id, refObj, wire, promise) {
					wire.domReady(function() {
						var node = document.getElementById(id);
						if(node) promise.resolve(node);
						else promise.reject();
					});
				}
			}
		}
	}
});<|endoftext|>


<commit_before>// Import native modules
var path = require('path');

// Import modules
var del = require('del');
var concat = require('gulp-concat');
var babel = require('gulp-babel');
var gulpif = require('gulp-if');
var jscs = require('gulp-jscs');
var uglify = require('gulp-uglify');
var replace = require('gulp-replace');
var gulpDocs = require('gulp-ngdocs');
var sourcemaps = require('gulp-sourcemaps');

// Import config
var config = require('./_config');
var scripts = config.scripts.concat(config.scriptsSkip);

var env = process.env.NODE_ENV || 'dev';
var live = env === 'prod' || env === 'staging';

// Html module
module.exports = function(gulp, livereload) {
	var concatConf = {
		newLine: '\n'
	};

	gulp.task('scripts', function() {
		return gulp.src(scripts)
			.pipe(gulpif(live, sourcemaps.init()))
			.pipe(concat('app.js', concatConf))
			.pipe(gulpif(live, uglify()))
			.pipe(gulpif(live, sourcemaps.write('./')))
			.pipe(gulpif(live, replace(/\/\/# sourceMappingURL=.*$/g, '')))
			.pipe(gulp.dest('dist'))
			.pipe(livereload());
	});

	gulp.task('script-lint', function() {
		return gulp.src(config.scripts)
			.pipe(jscs({
				fix: false,
				configPath: path.join(__dirname, '..', '/.jscsrc')
			}))
			.pipe(jscs.reporter());
	});

	gulp.task('clean-docs', function() {
		// Clean docs before making a new one
		return del(['docs']);
	});

	gulp.task('script-docs', function () {
		var libs = config.libs.concat(config.docLibs);
		var options = {
			scripts: libs,
			loadDefaults: {
				angular: false,
				angularAnimate: false,
				marked: false
			},
			html5Mode: true,
			startPage: '/docs/api',
			title: 'Prototype builder',
			image: 'http://localhost:3000/assets/favicon.ico',
			imageLink: '/docs/api',
			titleLink: '/docs/api'
		};

		return gulp.src(scripts)
			.pipe(gulpDocs.process(options))
			.pipe(gulp.dest('./docs'));
	});

	gulp.task('build-docs', gulp.series('clean-docs', 'script-docs'));
};
<commit_msg>Add ng-annotate<commit_after>// Import native modules
var path = require('path');

// Import modules
var del = require('del');
var concat = require('gulp-concat');
var babel = require('gulp-babel');
var gulpif = require('gulp-if');
var jscs = require('gulp-jscs');
var uglify = require('gulp-uglify');
var replace = require('gulp-replace');
var gulpDocs = require('gulp-ngdocs');
var sourcemaps = require('gulp-sourcemaps');
var ngAnnotate = require('gulp-ng-annotate');

// Import config
var config = require('./_config');
var scripts = config.scripts.concat(config.scriptsSkip);

var env = process.env.NODE_ENV || 'dev';
var live = env === 'prod' || env === 'staging';

// Html module
module.exports = function(gulp, livereload) {
	var concatConf = {
		newLine: '\n'
	};

	gulp.task('scripts', function() {
		return gulp.src(scripts)
			.pipe(gulpif(live, sourcemaps.init()))
			.pipe(concat('app.js', concatConf))
			.pipe(ngAnnotate())
			.pipe(gulpif(live, uglify()))
			.pipe(gulpif(live, sourcemaps.write('./')))
			.pipe(gulpif(live, replace(/\/\/# sourceMappingURL=.*$/g, '')))
			.pipe(gulp.dest('dist'))
			.pipe(livereload());
	});

	gulp.task('script-lint', function() {
		return gulp.src(config.scripts)
			.pipe(jscs({
				fix: false,
				configPath: path.join(__dirname, '..', '/.jscsrc')
			}))
			.pipe(jscs.reporter());
	});

	gulp.task('clean-docs', function() {
		// Clean docs before making a new one
		return del(['docs']);
	});

	gulp.task('script-docs', function () {
		var libs = config.libs.concat(config.docLibs);
		var options = {
			scripts: libs,
			loadDefaults: {
				angular: false,
				angularAnimate: false,
				marked: false
			},
			html5Mode: true,
			startPage: '/docs/api',
			title: 'Prototype builder',
			image: 'http://localhost:3000/assets/favicon.ico',
			imageLink: '/docs/api',
			titleLink: '/docs/api'
		};

		return gulp.src(scripts)
			.pipe(gulpDocs.process(options))
			.pipe(gulp.dest('./docs'));
	});

	gulp.task('build-docs', gulp.series('clean-docs', 'script-docs'));
};
<|endoftext|>


<commit_before>var copy       = require("../../../util/copy.coffee"),
    fetchColor = require("../../../core/fetch/color.coffee"),
    shapeStyle = require("./style.coffee")
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Draws "square" and "circle" shapes using svg:rect
//------------------------------------------------------------------------------
module.exports = function(vars,selection,enter,exit) {

  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // The position and size of each rectangle on enter and exit.
  //----------------------------------------------------------------------------
  function init(nodes) {

    nodes
      .attr("x",0)
      .attr("y",0)
      .attr("width",0)
      .attr("height",0)

  }

  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // The position and size of each rectangle on update.
  //----------------------------------------------------------------------------
  function update(nodes,mod) {
    if (!mod) var mod = 0
    nodes
      .attr("x",function(d){
        var w = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.width
        return (-w/2)-(mod/2)
      })
      .attr("y",function(d){
        var h = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.height
        return (-h/2)-(mod/2)
      })
      .attr("width",function(d){
        var w = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.width
        return w+mod
      })
      .attr("height",function(d){
        var h = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.height
        return h+mod
      })
      .attr("rx",function(d){
        var w = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.width
        var rounded = ["circle","donut"].indexOf(vars.shape.value) >= 0
        return rounded ? (w+mod)/2 : 0
      })
      .attr("ry",function(d){
        var h = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.height
        var rounded = ["circle","donut"].indexOf(vars.shape.value) >= 0
        return rounded ? (h+mod)/2 : 0
      })
      .attr("shape-rendering",function(d){
        if (["square"].indexOf(vars.shape.value) >= 0) {
          return vars.shape.rendering.value
        }
        else {
          return "auto"
        }
      })
  }

  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // In order to correctly animate each donut's size and arcs, we need to store
  // it's previous values in a lookup object that does not get destroyed when
  // redrawing the visualization.
  //----------------------------------------------------------------------------
  if (!vars.arcs) {
    vars.arcs = {
      "donut": {},
      "active": {},
      "temp": {}
    }
  }

  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // This is the main arc function that determines what values to use for each
  // arc angle and radius.
  //----------------------------------------------------------------------------
  var arc = d3.svg.arc()
    .startAngle(0)
    .endAngle(function(d){
      var a = vars.arcs[d.d3plus.shape][d.d3plus.id].a
      return a > Math.PI*2 ? Math.PI*2 : a;
    })
    .innerRadius(function(d){
      if (shape == "donut" && !d.d3plus.static) {
        var r = vars.arcs[d.d3plus.shape][d.d3plus.id].r
        return r * vars.data.donut.size
      }
      else {
        return 0
      }
    })
    .outerRadius(function(d){
      var r = vars.arcs[d.d3plus.shape][d.d3plus.id].r
      if (d.d3plus.shape != "donut") return r*2
      else return r
    })

  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // This is the main "arcTween" function where all of the animation happens
  // for each arc.
  //----------------------------------------------------------------------------
  function size(path,mod,rad,ang) {
    if (!mod) var mod = 0
    if (typeof rad != "number") var rad = undefined
    if (typeof ang != "number") var ang = undefined
    path.attrTween("d", function(d){
      if (rad == undefined) var r = d.d3plus.r ? d.d3plus.r : d3.max([d.d3plus.width,d.d3plus.height])
      else var r = rad
      if (ang == undefined) var a = d.d3plus.a[d.d3plus.shape]
      else var a = ang
      if (!vars.arcs[d.d3plus.shape][d.d3plus.id]) {
        vars.arcs[d.d3plus.shape][d.d3plus.id] = {"r": 0}
        vars.arcs[d.d3plus.shape][d.d3plus.id].a = d.d3plus.shape == "donut" ? Math.PI * 2 : 0
      }
      var radius = d3.interpolate(vars.arcs[d.d3plus.shape][d.d3plus.id].r,r+mod),
          angle = d3.interpolate(vars.arcs[d.d3plus.shape][d.d3plus.id].a,a)

      return function(t) {
        vars.arcs[d.d3plus.shape][d.d3plus.id].r = radius(t)
        vars.arcs[d.d3plus.shape][d.d3plus.id].a = angle(t)
        return arc(d)
      }
    })
  }

  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // Check each data point for active and temp data
  //----------------------------------------------------------------------------
  selection.each(function(d){

    var active = vars.active.value ? d.d3plus[vars.active.value] : d.d3plus.active,
        temp = vars.temp.value ? d.d3plus[vars.temp.value] : d.d3plus.temp,
        total = vars.total.value ? d.d3plus[vars.total.value] : d.d3plus.total,
        group = d3.select(this),
        color = fetchColor(vars,d)

    var fill_data = [], hatch_data = []

    if (total && vars.types[vars.type.value].fill) {

      if (temp) {
        var c = copy(d)
        c.d3plus.shape = "temp"
        fill_data.push(c)
        hatch_data = ["temp"]
      }

      if (active && (active < total || temp)) {
        var c = copy(d)
        c.d3plus.shape = "active"
        fill_data.push(c)
      }

    }

    function hatch_lines(l) {
      l
        .attr("stroke",color)
        .attr("stroke-width",1)
        .attr("shape-rendering",vars.shape.rendering.value)
    }

    var pattern = vars.defs.selectAll("pattern#d3plus_hatch_"+d.d3plus.id)
      .data(hatch_data)

    if (vars.draw.timing) {

      pattern.selectAll("rect")
        .transition().duration(vars.draw.timing)
        .style("fill",color)

      pattern.selectAll("line")
        .transition().duration(vars.draw.timing)
        .style("stroke",color)

    }
    else {

      pattern.selectAll("rect").style("fill",color)

      pattern.selectAll("line").style("stroke",color)

    }

    var pattern_enter = pattern.enter().append("pattern")
      .attr("id","d3plus_hatch_"+d.d3plus.id)
      .attr("patternUnits","userSpaceOnUse")
      .attr("x","0")
      .attr("y","0")
      .attr("width","10")
      .attr("height","10")
      .append("g")

    pattern_enter.append("rect")
      .attr("x","0")
      .attr("y","0")
      .attr("width","10")
      .attr("height","10")
      .attr("fill",color)
      .attr("fill-opacity",0.25)

    pattern_enter.append("line")
      .attr("x1","0")
      .attr("x2","10")
      .attr("y1","0")
      .attr("y2","10")
      .call(hatch_lines)

    pattern_enter.append("line")
      .attr("x1","-1")
      .attr("x2","1")
      .attr("y1","9")
      .attr("y2","11")
      .call(hatch_lines)

    pattern_enter.append("line")
      .attr("x1","9")
      .attr("x2","11")
      .attr("y1","-1")
      .attr("y2","1")
      .call(hatch_lines)

    var clip_data = fill_data.length ? [d] : []

    var clip = group.selectAll("#d3plus_clip_"+d.d3plus.id)
      .data(clip_data)

    clip.enter().insert("clipPath",".d3plus_mouse")
      .attr("id","d3plus_clip_"+d.d3plus.id)
      .append("rect")
      .attr("class","d3plus_clipping")
      .call(init)

    if (vars.draw.timing) {

      clip.selectAll("rect").transition().duration(vars.draw.timing)
        .call(update)

      clip.exit().transition().delay(vars.draw.timing)
        .remove()

    }
    else {

      clip.selectAll("rect").call(update)

      clip.exit().remove()

    }

    var fills = group.selectAll("path.d3plus_fill")
      .data(fill_data)

    fills.transition().duration(vars.draw.timing)
      .call(shapeStyle,vars)
      .call(size)

    fills.enter().insert("path","rect.d3plus_mouse")
      .attr("class","d3plus_fill")
      .attr("clip-path","url(#d3plus_clip_"+d.d3plus.id+")")
      .transition().duration(0)
        .call(size,0,undefined,0)
        .call(shapeStyle,vars)
        .transition().duration(vars.draw.timing)
          .call(size)

    fills.exit().transition().duration(vars.draw.timing)
      .call(size,0,undefined,0)
      .remove()

  })

}
<commit_msg>fixed issue with .active( ) pie fills<commit_after>var copy       = require("../../../util/copy.coffee"),
    fetchColor = require("../../../core/fetch/color.coffee"),
    shapeStyle = require("./style.coffee");
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Draws "square" and "circle" shapes using svg:rect
//------------------------------------------------------------------------------
module.exports = function(vars,selection,enter,exit) {

  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // The position and size of each rectangle on enter and exit.
  //----------------------------------------------------------------------------
  function init(nodes) {

    nodes
      .attr("x",0)
      .attr("y",0)
      .attr("width",0)
      .attr("height",0);

  }

  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // The position and size of each rectangle on update.
  //----------------------------------------------------------------------------
  function update(nodes,mod) {
    if (!mod) mod = 0;
    nodes
      .attr("x",function(d){
        var w = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.width;
        return (-w/2)-(mod/2);
      })
      .attr("y",function(d){
        var h = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.height;
        return (-h/2)-(mod/2);
      })
      .attr("width",function(d){
        var w = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.width;
        return w+mod;
      })
      .attr("height",function(d){
        var h = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.height;
        return h+mod;
      })
      .attr("rx",function(d){
        var w = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.width;
        var rounded = ["circle","donut"].indexOf(vars.shape.value) >= 0;
        return rounded ? (w+mod)/2 : 0;
      })
      .attr("ry",function(d){
        var h = d.d3plus.r ? d.d3plus.r*2 : d.d3plus.height;
        var rounded = ["circle","donut"].indexOf(vars.shape.value) >= 0;
        return rounded ? (h+mod)/2 : 0;
      })
      .attr("shape-rendering",function(d){
        if (["square"].indexOf(vars.shape.value) >= 0) {
          return vars.shape.rendering.value;
        }
        else {
          return "auto";
        }
      });
  }

  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // In order to correctly animate each donut's size and arcs, we need to store
  // it's previous values in a lookup object that does not get destroyed when
  // redrawing the visualization.
  //----------------------------------------------------------------------------
  if (!vars.arcs) {
    vars.arcs = {
      "donut": {},
      "active": {},
      "temp": {}
    };
  }

  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // This is the main arc function that determines what values to use for each
  // arc angle and radius.
  //----------------------------------------------------------------------------
  var arc = d3.svg.arc()
    .startAngle(0)
    .endAngle(function(d){
      var a = vars.arcs[d.d3plus.shape][d.d3plus.id].a;
      return a > Math.PI*2 ? Math.PI*2 : a;
    })
    .innerRadius(function(d){
      if (d.d3plus.shape === "donut" && !d.d3plus.static) {
        var r = vars.arcs[d.d3plus.shape][d.d3plus.id].r;
        return r * vars.data.donut.size;
      }
      else {
        return 0;
      }
    })
    .outerRadius(function(d){
      var r = vars.arcs[d.d3plus.shape][d.d3plus.id].r;
      if (d.d3plus.shape != "donut") return r*2;
      else return r;
    });

  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // This is the main "arcTween" function where all of the animation happens
  // for each arc.
  //----------------------------------------------------------------------------
  function size(path,mod,rad,ang) {
    if (!mod) mod = 0;
    if (typeof rad != "number") rad = undefined;
    if (typeof ang != "number") ang = undefined;
    path.attrTween("d", function(d){
      if (rad === undefined) var r = d.d3plus.r ? d.d3plus.r : d3.max([d.d3plus.width,d.d3plus.height]);
      else var r = rad;
      if (ang === undefined) var a = d.d3plus.segments[d.d3plus.shape];
      else var a = ang;
      if (!vars.arcs[d.d3plus.shape][d.d3plus.id]) {
        vars.arcs[d.d3plus.shape][d.d3plus.id] = {"r": 0};
        vars.arcs[d.d3plus.shape][d.d3plus.id].a = d.d3plus.shape === "donut" ? Math.PI * 2 : 0;
      }
      var radius = d3.interpolate(vars.arcs[d.d3plus.shape][d.d3plus.id].r,r+mod),
          angle = d3.interpolate(vars.arcs[d.d3plus.shape][d.d3plus.id].a,a);

      return function(t) {
        vars.arcs[d.d3plus.shape][d.d3plus.id].r = radius(t);
        vars.arcs[d.d3plus.shape][d.d3plus.id].a = angle(t);
        return arc(d);
      };
    });
  }

  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // Check each data point for active and temp data
  //----------------------------------------------------------------------------
  selection.each(function(d){

    var active = vars.active.value ? d.d3plus[vars.active.value] : d.d3plus.active,
        temp = vars.temp.value ? d.d3plus[vars.temp.value] : d.d3plus.temp,
        total = vars.total.value ? d.d3plus[vars.total.value] : d.d3plus.total,
        group = d3.select(this),
        color = fetchColor(vars,d);

    var fill_data = [], hatch_data = [];

    if (total && vars.types[vars.type.value].fill) {

      if (temp) {
        var c = copy(d);
        c.d3plus.shape = "temp";
        fill_data.push(c);
        hatch_data = ["temp"];
      }

      if (active && (active < total || temp)) {
        var c = copy(d);
        c.d3plus.shape = "active";
        fill_data.push(c);
      }

    }

    function hatch_lines(l) {
      l
        .attr("stroke",color)
        .attr("stroke-width",1)
        .attr("shape-rendering",vars.shape.rendering.value);
    }

    var pattern = vars.defs.selectAll("pattern#d3plus_hatch_"+d.d3plus.id)
      .data(hatch_data);

    if (vars.draw.timing) {

      pattern.selectAll("rect")
        .transition().duration(vars.draw.timing)
        .style("fill",color);

      pattern.selectAll("line")
        .transition().duration(vars.draw.timing)
        .style("stroke",color);

    }
    else {

      pattern.selectAll("rect").style("fill",color);

      pattern.selectAll("line").style("stroke",color);

    }

    var pattern_enter = pattern.enter().append("pattern")
      .attr("id","d3plus_hatch_"+d.d3plus.id)
      .attr("patternUnits","userSpaceOnUse")
      .attr("x","0")
      .attr("y","0")
      .attr("width","10")
      .attr("height","10")
      .append("g");

    pattern_enter.append("rect")
      .attr("x","0")
      .attr("y","0")
      .attr("width","10")
      .attr("height","10")
      .attr("fill",color)
      .attr("fill-opacity",0.25);

    pattern_enter.append("line")
      .attr("x1","0")
      .attr("x2","10")
      .attr("y1","0")
      .attr("y2","10")
      .call(hatch_lines);

    pattern_enter.append("line")
      .attr("x1","-1")
      .attr("x2","1")
      .attr("y1","9")
      .attr("y2","11")
      .call(hatch_lines);

    pattern_enter.append("line")
      .attr("x1","9")
      .attr("x2","11")
      .attr("y1","-1")
      .attr("y2","1")
      .call(hatch_lines);

    var clip_data = fill_data.length ? [d] : [];

    var clip = group.selectAll("#d3plus_clip_"+d.d3plus.id)
      .data(clip_data);

    clip.enter().insert("clipPath",".d3plus_mouse")
      .attr("id","d3plus_clip_"+d.d3plus.id)
      .append("rect")
      .attr("class","d3plus_clipping")
      .call(init);

    if (vars.draw.timing) {

      clip.selectAll("rect").transition().duration(vars.draw.timing)
        .call(update);

      clip.exit().transition().delay(vars.draw.timing)
        .remove();

    }
    else {

      clip.selectAll("rect").call(update);

      clip.exit().remove();

    }

    var fills = group.selectAll("path.d3plus_fill")
      .data(fill_data);

    fills.transition().duration(vars.draw.timing)
      .call(shapeStyle,vars)
      .call(size);

    fills.enter().insert("path","rect.d3plus_mouse")
      .attr("class","d3plus_fill")
      .attr("clip-path","url(#d3plus_clip_"+d.d3plus.id+")")
      .transition().duration(0)
        .call(size,0,undefined,0)
        .call(shapeStyle,vars)
        .transition().duration(vars.draw.timing)
          .call(size);

    fills.exit().transition().duration(vars.draw.timing)
      .call(size,0,undefined,0)
      .remove();

  });

};
<|endoftext|>


<commit_before>/**
 * @author Krzysztof Winiarski
 * @copyright (c) 2014 Krzysztof Winiarski
 * @license MIT
 */

'use strict';

var CONFIG = require('../config')
  , WILDCARD = '*'
  , support = require('./support')
  , config = require(CONFIG.POLICIES_CONFIG)
  , policyFiles = support.listFiles(CONFIG.POLICIES_DIR)
  , topLevelPolicies = []
  , policies = {};

function getPolicy(policyName) {
  if (policyFiles[policyName]) {
    return policyFiles[policyName];
  } else if (policyFiles[support.camelCaseToDash(policyName)]) {
    return policyFiles[support.camelCaseToDash(policyName)];
  } else {
    var error = new Error('Unknown policy');
    throw error;
  }
}

function getPolicies(policiesIds) {
  if (typeof policiesIds === 'string') {
    policiesIds = policiesIds.split(',');
  }

  return policiesIds.map(getPolicy);
}

function Policy(config) {
  Object.defineProperty(this, '_all', {
    value: config[WILDCARD]
      ? getPolicies(config[WILDCARD])
      : topLevelPolicies,
    enumerable: false
  });

  for (var actionName in config) {
    if (actionName === WILDCARD) {
      continue;
    }
    this[actionName] = getPolicies(config[actionName]);
  }
}

Policy.prototype.get = function(action) {
  return this.has(action) ? this[action] : this._all;
};

Policy.prototype.has = function(action) {
  return this[action] && !!this[action].length;
};

for (var fileName in policyFiles) {
  policyFiles[fileName] = require(policyFiles[fileName]);
}

if (config[WILDCARD]) {
  topLevelPolicies = getPolicies(config[WILDCARD]);
}

for (var id in config) {
  if (id === WILDCARD) {
    continue;
  }
  policies[id] = new Policy(config[id]);
}

module.exports = policies;
<commit_msg>More verbose policy load error.<commit_after>/**
 * @author Krzysztof Winiarski
 * @copyright (c) 2014 Krzysztof Winiarski
 * @license MIT
 */

'use strict';

var CONFIG = require('../config')
  , WILDCARD = '*'
  , support = require('./support')
  , config = require(CONFIG.POLICIES_CONFIG)
  , policyFiles = support.listFiles(CONFIG.POLICIES_DIR)
  , topLevelPolicies = []
  , policies = {};

function getPolicy(policyName) {
  if (policyFiles[policyName]) {
    return policyFiles[policyName];
  } else if (policyFiles[support.camelCaseToDash(policyName)]) {
    return policyFiles[support.camelCaseToDash(policyName)];
  } else {
    var error = new Error('Unknown policy "' + policyName + '"');
    throw error;
  }
}

function getPolicies(policiesIds) {
  if (typeof policiesIds === 'string') {
    policiesIds = policiesIds.split(',');
  }

  return policiesIds.map(getPolicy);
}

function Policy(config) {
  Object.defineProperty(this, '_all', {
    value: config[WILDCARD]
      ? getPolicies(config[WILDCARD])
      : topLevelPolicies,
    enumerable: false
  });

  for (var actionName in config) {
    if (actionName === WILDCARD) {
      continue;
    }
    this[actionName] = getPolicies(config[actionName]);
  }
}

Policy.prototype.get = function(action) {
  return this.has(action) ? this[action] : this._all;
};

Policy.prototype.has = function(action) {
  return this[action] && !!this[action].length;
};

for (var fileName in policyFiles) {
  policyFiles[fileName] = require(policyFiles[fileName]);
}

if (config[WILDCARD]) {
  topLevelPolicies = getPolicies(config[WILDCARD]);
}

for (var id in config) {
  if (id === WILDCARD) {
    continue;
  }
  policies[id] = new Policy(config[id]);
}

module.exports = policies;
<|endoftext|>


<commit_before>var Project = () => {
  console.error('In this version of Woof, please use "Woof.Project" instead of "Project"');
}

var Woof = {};

Number.prototype.between = function(a, b, inclusive) {
  var min = Math.min.apply(Math, [a, b]),
    max = Math.max.apply(Math, [a, b]);
  return inclusive ? this >= min && this <= max : this > min && this < max;
};

Woof.keyCodeToString = (keyCode) => {
  if (keyCode == 38) {
    return "UP";
  }
  else if (keyCode == 37){
    return "LEFT";
  }
  else if (keyCode == 39){
    return "RIGHT";
  }
  else if (keyCode == 40){
    return "DOWN";
  }
  else {
    return String.fromCharCode(keyCode);
  }
};

Woof.unitsToMiliseconds = (time, units) => {
  if (units == "milliseconds" || units == "millisecond"){
    return time;
  } else if (units == "seconds" || units == "second"){
    return time * 1000;
  } else if (units == "minutes" || units == "minute"){
    return time * 1000 * 60;
  } else {
    throw Error("Unrecognized Time");
  }
};

Woof.randomInt = (low, high) => {
  return Math.floor(Math.random() * high + low);
};

Woof.Project = function(canvasId) {
  this.sprites = [];
  this.backdrops = [];
  this.backdrop = 0;

  try {
    this._canvas = document.getElementById(canvasId);
  } catch (e){
    console.error(e);
    console.error("Could not find a canvas on the page with id " + canvasId);
    return null;
  }
  this._context = this._canvas.getContext("2d");
  this.height = this._canvas.height;
  this.width = this._canvas.width;

  this._render = function(){
    this._context.clearRect(0, 0, this._canvas.width, this._canvas.height);
    this._renderBackdrop();
    this._renderSprites();
  };

  this._renderBackdrop = function() {
    if (this.backdrops[this.backdrop]) {
      var image = this.backdrops[this.backdrop];
      this._context.drawImage(image, 0, 0);
    }
  };

  this._renderSprites = () => {
    this.sprites.forEach((sprite) => {
      sprite._render(this);
    });
  };

  this.addSprite = function() {
    var sprite = new Woof.Sprite(this);
    this.sprites.push(sprite);
    return sprite;
  };

  this.addTextSprite = function() {
    var sprite = new Woof.TextSprite(this);
    this.sprites.push(sprite);
    return sprite;
  };

  this.addBackdropURL = function(url){
    var backdrop = new Image();
    backdrop.src = url;
    this.backdrops.push(backdrop);
  };

  this.stopAll = () => {
    this._render();
    clearInterval(renderInterval);

    this._everys.forEach(clearInterval);
    this._afters.forEach(clearInterval);

    this.sprites.forEach(sprite => sprite.delete());
  };

  this.mouseDown = false;
  this.mouseX = 0;
  this.mouseY = 0;
  this._canvas.addEventListener("mousedown", (event) => {
    this.mouseDown = true;
    this.mouseX = event.clientX - this._canvas.offsetLeft;
    this.mouseY = event.clientY - this._canvas.offsetTop;
  });
  this._canvas.addEventListener("mouseup", (event) => {
    this.mouseDown = false;
    this.mouseX = event.clientX - this._canvas.offsetLeft;
    this.mouseY = event.clientY - this._canvas.offsetTop;
  });
  this._canvas.addEventListener("touchstart", (event) => {
    this.mouseDown = true;
    this.mouseX = event.targetTouches[0].clientX - this._canvas.offsetLeft;
    this.mouseY = event.targetTouches[0].clientY - this._canvas.offsetTop;
  });
  this._canvas.addEventListener("touchend", (event) => {
    // for some reason touchend events are firing too quickly
    // and are not getting picked up in 40 ms every-if's
    // so this setTimeout slows things down just enouch so
    // touch events mirror mouse events
    setTimeout(() => {this.mouseDown = false;}, 0);
  });
  this._canvas.addEventListener("mousemove", (event) => {
    this.mouseX = event.clientX - this._canvas.offsetLeft;
    this.mouseY = event.clientY - this._canvas.offsetTop;
  });
  this._canvas.addEventListener("touchmove", event => {
    this.mouseX = event.targetTouches[0].clientX - this._canvas.offsetLeft;
    this.mouseY = event.targetTouches[0].clientY - this._canvas.offsetTop;
    event.preventDefault();
  });

  this.keysDown = [];
  this._canvas.addEventListener("keydown", event => {
    var key = Woof.keyCodeToString(event.keyCode);
    if (!this.keysDown.includes(key)){
     this.keysDown.push(key);
    }
  });
  this._canvas.addEventListener("keyup", event => {
    var key = Woof.keyCodeToString(event.keyCode);
    if (this.keysDown.includes(key)){
      this.keysDown.splice(this.keysDown.indexOf(key), 1);
    }
  });

  this._everys = [];
  this.every = (time, units, func) => {
    func();
    this._everys.push(setInterval(func, Woof.unitsToMiliseconds(time, units)));
  };

  this._afters = [];
  this.after = (time, units, func) => {
    this._afters.push(setTimeout(func, Woof.unitsToMiliseconds(time, units)));
  };

  this._onloads = [];
    document.body.addEventListener("onload", event => {
    this._onloads.forEach((func) => {func.call();});
  });

  var renderInterval = setInterval(() => {
    try {
      this._render();
    } catch (e) {
      console.error(e);
      console.error("Error in render: " + e.message);
      clearInterval(renderInterval);
    }
  }, 40);
};

Woof.Sprite = function(project) {
  this.project = project;

  this.xPosition = 0;
  this.yPosition = 0;

  this.angle = 0;

  this.costumes = [];
  this.costume = 0;
  this.height = null;
  this.width = null;

  this.rotationStyle = "ROTATE";

  this.showing = true;

  this.addCostumeURL = function(url){
    var costume = new Image();
    costume.src = url;
    this.costumes.push(costume);
    return this.costumes.length - 1;
  };

  this._render = function() {
    var angle;
    if (this.rotationStyle == "ROTATE"){
      angle = this.angle;
    } else if (this.rotationStyle == "NO ROTATE"){
      angle = 0;
    }

    if (this.showing) {
      this.project._context.save();
      this.project._context.translate(this.xPosition, this.yPosition);
      this.project._context.rotate(angle * Math.PI / 180);

      if (this.currentCostume() && this.currentCostume().nodeName == "IMG") {
        this.project._context.drawImage(this.currentCostume(), -this.width()/2, -this.height() / 2);
      }
      else if (this instanceof Woof.TextSprite) {
        this.textRender();
      } else if (this.currentCostume() && this.currentCostume().radius) {
      	this.project._context.beginPath();
      	this.project._context.arc(this.currentCostume().x,this.currentCostume().y,this.currentCostume().radius,0,2*Math.PI);
      	this.project._context.fillStyle=this.currentCostume().color;
      	this.project._context.fill();
			}
      this.project._context.restore();
    }
  };

  this.addCostumeCircle = (x, y, radius, color) => {
    this.costumes.push({x:x, y:y, radius: radius, color:color});
  };

  this.move = function(steps){
    this.xPosition += steps * Math.cos(this.angle * Math.PI / 180);
    this.yPosition += steps * Math.sin(this.angle * Math.PI / 180);
  };

  this.setRotationStyle = style => {
    if (style == "ROTATE"){
      this.rotationStyle = "ROTATE";
    }
    else if (style == "NO ROTATE") {
      this.rotationStyle = "NO ROTATE";
    }
    else {
      throw Error("Unrecognized rotation style: " + style);
    }
  };

  this.bounds = () => {
    var leftBounds = this.xPosition - (this.width() / 2);
    var rightBounds = this.xPosition + (this.width() / 2);
    var topBounds = this.yPosition - (this.height() / 2);
    var bottomBounds = this.yPosition + (this.height() / 2);
    return {left: leftBounds, right: rightBounds, top: topBounds, bottom: bottomBounds};
  };

  this.touching = sprite => {
    var r1 = this.bounds();
    var r2 = sprite.bounds();

    return !(r2.left > r1.right ||
             r2.right < r1.left ||
             r2.top > r1.bottom ||
             r2.bottom < r1.top);
  };

  this.mouseOver = function() {
    // TODO account for rotation
    var belowTop = this.project.mouseY >= this.yPosition - (this.height() / 2);
    var aboveBottom = this.project.mouseY <= this.yPosition + (this.height() /2);
    var rightLeft = this.project.mouseX >= this.xPosition - (this.width() / 2);
    var leftRight = this.project.mouseX <= this.xPosition + (this.width() / 2);
    return belowTop && aboveBottom && rightLeft && leftRight;
  };

  this.currentCostume = () => {
    return this.costumes[this.costume];
  };

  this.sendToBack = () => {
    var sprites = this.project.sprites;
    sprites.splice(0, 0, sprites.splice(sprites.indexOf(this), 1)[0]);
  };

  this.sendToFront = () => {
    var sprites = this.project.sprites;
    sprites.splice(sprites.length, 0, sprites.splice(sprites.indexOf(this), 1)[0]);
  };

  this.pointTowards = sprite => {
    var x1 = this.xPosition;
    var y1 = this.yPosition;
    var x2 = sprite.xPosition;
    var y2 = sprite.yPosition;

    this.angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;
  };

  this.pointTowards = (x2,y2) => {
    var x1 = this.xPosition;
    var y1 = this.yPosition;

    this.angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;
  };

  this.height = () => {
    return this.currentCostume().height;
  };

  this.width = () => {
    return this.currentCostume().width;
  };

  this.delete = () => {
    if (this.project.sprites.includes(this)){
      this.project.sprites.splice(this.project.sprites.indexOf(this), 1);
      this._everys.forEach(clearInterval);
      this._afters.forEach(clearInterval);
    }
  };
};

Woof.TextSprite = function(project) {
  Woof.Sprite.call(this, project);
  this.text = "";
  this.fontSize = 12;
  this.fontColor = "black";
  this.fontFamily = "Arial";
  this.textAlign = "left";

  this.width = () => {
    var width;
    this._applyInContext(() => {
      width = this.project._context.measureText(this.text).width;
    });
    return width;
  };

  this.height = () => {
    var height;
    this._applyInContext(() => {
      height = this.project._context.measureText("M").width;
    });
    return height;
  };

  this._applyInContext = (func) => {
    this.project._context.save();

    this.project._context.font = this.fontSize + "px " + this.fontFamily;
    this.project._context.fillStyle = this.fontColor;
    this.project._context.textAlign = this.textAlign;

    func();

    this.project._context.restore();
  };

  this.textRender = () => {
    this._applyInContext(() => {
      this.project._context.fillText(this.text, 0, 0);
    });
  };
};
<commit_msg>removed Number.prototype.between<commit_after>var Project = () => {
  console.error('In this version of Woof, please use "Woof.Project" instead of "Project"');
}

var Woof = {};

Woof.keyCodeToString = (keyCode) => {
  if (keyCode == 38) {
    return "UP";
  }
  else if (keyCode == 37){
    return "LEFT";
  }
  else if (keyCode == 39){
    return "RIGHT";
  }
  else if (keyCode == 40){
    return "DOWN";
  }
  else {
    return String.fromCharCode(keyCode);
  }
};

Woof.unitsToMiliseconds = (time, units) => {
  if (units == "milliseconds" || units == "millisecond"){
    return time;
  } else if (units == "seconds" || units == "second"){
    return time * 1000;
  } else if (units == "minutes" || units == "minute"){
    return time * 1000 * 60;
  } else {
    throw Error("Unrecognized Time");
  }
};

Woof.randomInt = (low, high) => {
  return Math.floor(Math.random() * high + low);
};

Woof.Project = function(canvasId) {
  this.sprites = [];
  this.backdrops = [];
  this.backdrop = 0;

  try {
    this._canvas = document.getElementById(canvasId);
  } catch (e){
    console.error(e);
    console.error("Could not find a canvas on the page with id " + canvasId);
    return null;
  }
  this._context = this._canvas.getContext("2d");
  this.height = this._canvas.height;
  this.width = this._canvas.width;

  this._render = function(){
    this._context.clearRect(0, 0, this._canvas.width, this._canvas.height);
    this._renderBackdrop();
    this._renderSprites();
  };

  this._renderBackdrop = function() {
    if (this.backdrops[this.backdrop]) {
      var image = this.backdrops[this.backdrop];
      this._context.drawImage(image, 0, 0);
    }
  };

  this._renderSprites = () => {
    this.sprites.forEach((sprite) => {
      sprite._render(this);
    });
  };

  this.addSprite = function() {
    var sprite = new Woof.Sprite(this);
    this.sprites.push(sprite);
    return sprite;
  };

  this.addTextSprite = function() {
    var sprite = new Woof.TextSprite(this);
    this.sprites.push(sprite);
    return sprite;
  };

  this.addBackdropURL = function(url){
    var backdrop = new Image();
    backdrop.src = url;
    this.backdrops.push(backdrop);
  };

  this.stopAll = () => {
    this._render();
    clearInterval(renderInterval);

    this._everys.forEach(clearInterval);
    this._afters.forEach(clearInterval);

    this.sprites.forEach(sprite => sprite.delete());
  };

  this.mouseDown = false;
  this.mouseX = 0;
  this.mouseY = 0;
  this._canvas.addEventListener("mousedown", (event) => {
    this.mouseDown = true;
    this.mouseX = event.clientX - this._canvas.offsetLeft;
    this.mouseY = event.clientY - this._canvas.offsetTop;
  });
  this._canvas.addEventListener("mouseup", (event) => {
    this.mouseDown = false;
    this.mouseX = event.clientX - this._canvas.offsetLeft;
    this.mouseY = event.clientY - this._canvas.offsetTop;
  });
  this._canvas.addEventListener("touchstart", (event) => {
    this.mouseDown = true;
    this.mouseX = event.targetTouches[0].clientX - this._canvas.offsetLeft;
    this.mouseY = event.targetTouches[0].clientY - this._canvas.offsetTop;
  });
  this._canvas.addEventListener("touchend", (event) => {
    // for some reason touchend events are firing too quickly
    // and are not getting picked up in 40 ms every-if's
    // so this setTimeout slows things down just enouch so
    // touch events mirror mouse events
    setTimeout(() => {this.mouseDown = false;}, 0);
  });
  this._canvas.addEventListener("mousemove", (event) => {
    this.mouseX = event.clientX - this._canvas.offsetLeft;
    this.mouseY = event.clientY - this._canvas.offsetTop;
  });
  this._canvas.addEventListener("touchmove", event => {
    this.mouseX = event.targetTouches[0].clientX - this._canvas.offsetLeft;
    this.mouseY = event.targetTouches[0].clientY - this._canvas.offsetTop;
    event.preventDefault();
  });

  this.keysDown = [];
  this._canvas.addEventListener("keydown", event => {
    var key = Woof.keyCodeToString(event.keyCode);
    if (!this.keysDown.includes(key)){
     this.keysDown.push(key);
    }
  });
  this._canvas.addEventListener("keyup", event => {
    var key = Woof.keyCodeToString(event.keyCode);
    if (this.keysDown.includes(key)){
      this.keysDown.splice(this.keysDown.indexOf(key), 1);
    }
  });

  this._everys = [];
  this.every = (time, units, func) => {
    func();
    this._everys.push(setInterval(func, Woof.unitsToMiliseconds(time, units)));
  };

  this._afters = [];
  this.after = (time, units, func) => {
    this._afters.push(setTimeout(func, Woof.unitsToMiliseconds(time, units)));
  };

  this._onloads = [];
    document.body.addEventListener("onload", event => {
    this._onloads.forEach((func) => {func.call();});
  });

  var renderInterval = setInterval(() => {
    try {
      this._render();
    } catch (e) {
      console.error(e);
      console.error("Error in render: " + e.message);
      clearInterval(renderInterval);
    }
  }, 40);
};

Woof.Sprite = function(project) {
  this.project = project;

  this.xPosition = 0;
  this.yPosition = 0;

  this.angle = 0;

  this.costumes = [];
  this.costume = 0;
  this.height = null;
  this.width = null;

  this.rotationStyle = "ROTATE";

  this.showing = true;

  this.addCostumeURL = function(url){
    var costume = new Image();
    costume.src = url;
    this.costumes.push(costume);
    return this.costumes.length - 1;
  };

  this._render = function() {
    var angle;
    if (this.rotationStyle == "ROTATE"){
      angle = this.angle;
    } else if (this.rotationStyle == "NO ROTATE"){
      angle = 0;
    }

    if (this.showing) {
      this.project._context.save();
      this.project._context.translate(this.xPosition, this.yPosition);
      this.project._context.rotate(angle * Math.PI / 180);

      if (this.currentCostume() && this.currentCostume().nodeName == "IMG") {
        this.project._context.drawImage(this.currentCostume(), -this.width()/2, -this.height() / 2);
      }
      else if (this instanceof Woof.TextSprite) {
        this.textRender();
      } else if (this.currentCostume() && this.currentCostume().radius) {
      	this.project._context.beginPath();
      	this.project._context.arc(this.currentCostume().x,this.currentCostume().y,this.currentCostume().radius,0,2*Math.PI);
      	this.project._context.fillStyle=this.currentCostume().color;
      	this.project._context.fill();
			}
      this.project._context.restore();
    }
  };

  this.addCostumeCircle = (x, y, radius, color) => {
    this.costumes.push({x:x, y:y, radius: radius, color:color});
  };

  this.move = function(steps){
    this.xPosition += steps * Math.cos(this.angle * Math.PI / 180);
    this.yPosition += steps * Math.sin(this.angle * Math.PI / 180);
  };

  this.setRotationStyle = style => {
    if (style == "ROTATE"){
      this.rotationStyle = "ROTATE";
    }
    else if (style == "NO ROTATE") {
      this.rotationStyle = "NO ROTATE";
    }
    else {
      throw Error("Unrecognized rotation style: " + style);
    }
  };

  this.bounds = () => {
    var leftBounds = this.xPosition - (this.width() / 2);
    var rightBounds = this.xPosition + (this.width() / 2);
    var topBounds = this.yPosition - (this.height() / 2);
    var bottomBounds = this.yPosition + (this.height() / 2);
    return {left: leftBounds, right: rightBounds, top: topBounds, bottom: bottomBounds};
  };

  this.touching = sprite => {
    var r1 = this.bounds();
    var r2 = sprite.bounds();

    return !(r2.left > r1.right ||
             r2.right < r1.left ||
             r2.top > r1.bottom ||
             r2.bottom < r1.top);
  };

  this.mouseOver = function() {
    // TODO account for rotation
    var belowTop = this.project.mouseY >= this.yPosition - (this.height() / 2);
    var aboveBottom = this.project.mouseY <= this.yPosition + (this.height() /2);
    var rightLeft = this.project.mouseX >= this.xPosition - (this.width() / 2);
    var leftRight = this.project.mouseX <= this.xPosition + (this.width() / 2);
    return belowTop && aboveBottom && rightLeft && leftRight;
  };

  this.currentCostume = () => {
    return this.costumes[this.costume];
  };

  this.sendToBack = () => {
    var sprites = this.project.sprites;
    sprites.splice(0, 0, sprites.splice(sprites.indexOf(this), 1)[0]);
  };

  this.sendToFront = () => {
    var sprites = this.project.sprites;
    sprites.splice(sprites.length, 0, sprites.splice(sprites.indexOf(this), 1)[0]);
  };

  this.pointTowards = sprite => {
    var x1 = this.xPosition;
    var y1 = this.yPosition;
    var x2 = sprite.xPosition;
    var y2 = sprite.yPosition;

    this.angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;
  };

  this.pointTowards = (x2,y2) => {
    var x1 = this.xPosition;
    var y1 = this.yPosition;

    this.angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;
  };

  this.height = () => {
    return this.currentCostume().height;
  };

  this.width = () => {
    return this.currentCostume().width;
  };

  this.delete = () => {
    if (this.project.sprites.includes(this)){
      this.project.sprites.splice(this.project.sprites.indexOf(this), 1);
      this._everys.forEach(clearInterval);
      this._afters.forEach(clearInterval);
    }
  };
};

Woof.TextSprite = function(project) {
  Woof.Sprite.call(this, project);
  this.text = "";
  this.fontSize = 12;
  this.fontColor = "black";
  this.fontFamily = "Arial";
  this.textAlign = "left";

  this.width = () => {
    var width;
    this._applyInContext(() => {
      width = this.project._context.measureText(this.text).width;
    });
    return width;
  };

  this.height = () => {
    var height;
    this._applyInContext(() => {
      height = this.project._context.measureText("M").width;
    });
    return height;
  };

  this._applyInContext = (func) => {
    this.project._context.save();

    this.project._context.font = this.fontSize + "px " + this.fontFamily;
    this.project._context.fillStyle = this.fontColor;
    this.project._context.textAlign = this.textAlign;

    func();

    this.project._context.restore();
  };

  this.textRender = () => {
    this._applyInContext(() => {
      this.project._context.fillText(this.text, 0, 0);
    });
  };
};
<|endoftext|>


<commit_before>
var through = require('through');
var serial = require('pinoccio/lib/serial')();
var outputParser = require('./lib/verbose-parser');
var json = require('./lib/json');
var version = require('./package.json').version;

module.exports = function(com,readycb){
  if(typeof options == 'function'){
    readycb = options;
    options = {};
  }

  if(typeof com == 'object'){
    options = com;
    com = options.com;
  }

  var out;
  var parser = outputParser();

  parser.on('data',function(data){
    // send out to event stream
    handle(data);
    // send to bridge.. the bridge can be moved out of this file.
    // must send token first! TODO.
  });

  serial.connect(com,function(err,scoutScript){
    if(err) return out.emit('error');

    out.ready = true;
    out.scoutScript = scoutScript;

    var series = [
      function(){
        out._scommand('hq.gettoken',function(err,data){
          console.log('get token>!',err,data)
          if(err) return out.emit('error',new Error('error getting token. '+err));
          out.token = data;
          done();
        });
      },
      function(){
        out._scommand('mesh.report',function(err,data){
          if(err) return out.emit('error',new Error('error getting mesh config. '+err));
          console.log('MESH!',data);
          out.mesh = json(data);
          done();
        });
      },
      function(){
        //var startup = "function startup.dongle {"
        //  +"verbose(1);"
        //  +"mesh.joingroup"
        //+"}";
        //  +"function on.message.group{"
        //    +"group,from,keys"
        //+"};"
        //+""
        out._scommand('hq.verbose(1);report;',done)
      }
    ], done = function(err){
      if(err) return out.emit('error',err);
      var next = series.shift();
      if(next) {
        return next();
      }

      out.emit('ready',scoutScript);
      readycb(false,out);
      readycb = noop;
    };

    done();

    scoutScript.on('log',function(data){
      //console.log('[log]',data+'');
      parser.write(data);
    });

  });

  // from board
  var handle = function(data){
    console.log('data out of dongle',data);
    var scout;
    //{"type":"mesh","scoutid":2,"troopid":2,"routes":0,"channel":20,"rate":"250 kb/s","power":"3.5 dBm"}
    if(out.mesh) {
      scout = out.mesh.scoutid;
    }

    if(out.token && !out.sentToken){
      out.sentToken = true;
      out.queue({type:"token",token:out.token,dongle:version,scout:scout});
    }

    // add scout id and wrap with type report!
    // make sure its a report!
    // TODO support announce.

    out.queue({type:"report",report:data,from:out.mesh.scoutid});

  }

  out = through(function(data){
    if(!data) return;
    // command stream to board
    console.log('BRIDGE> ',data);
    if(data.type == 'command') {
      if(!data.to || !data.command){
        return console.log('INVALID BRIDGE COMMAND!',data);
      }

      // support external data.timeout
      var t = Date.now();
      out.command(data.to,data.command,function(err,res){
        //data.
        data.type = "reply";
        if(err) data.err = true;
        data.reply = res != undefined?res:err+'';
        data.from = data.to;
        data.basetime = Date.now()-t;
        delete data.to;

        console.log('COMMAND REPLY!',data);

        // send replies back.
        out.queue(data);
      });
    } else if(data.type == 'online') {
      // noop.
    } else {
      console.log('UNKNOWN bridge command!',  data);
    }

  });

  if(readycb) out.once('error',function(err){
    readycb(err); readycb = noop;
  })

  out.ready = false;

  // just expose command because you probably want to run commands from everywhere
  out.command = function(scout,command,cb){
    if(out.mesh && out.mesh.scoutid == scout) return out._scommand(command,cb);

    // needs to support running on other scouts in troop!
    setImmediate(function(){
      cb('dongle cant message other scouts over mesh yet');
    });
  }

  out._scommand = function(command,cb){
    console.log('SCOMMAND',command);
    command = command.trim();
    var attempts = 0
    , z = this
    , run = function _scommand(){
      z.scoutScript.command(command,function(err,data){
        if(err) {
          if(err.code == 'EWRITE' && ++attempts < 2) return _scommand();
        }

        var reply;
        if(!err) {
          var orig = data;
          // remove command just in case it snuck in output.
          if(data.indexOf(command) === 0) data = data.substr(data.indexOf(command));
          var lines = data.split("\r\n");
          reply = [];
          for(var i =0;i<lines.length;++i){
            if(lines[i].indexOf('mesh announcing to') === 0) break;
            reply.push(lines[i]);
          }
          reply = reply.join("\r\n");

          // keep adding data till the next

          console.log('REPLY>',reply,orig);
        }
        if(cb) cb(err,reply);
      })
    }
    run();
  }

  out.close = function(){

  }

  return out;
}

function noop(){};

<commit_msg>woo calling commands from api client works!!!<commit_after>
var through = require('through');
var serial = require('pinoccio/lib/serial')();
var outputParser = require('./lib/verbose-parser');
var json = require('./lib/json');
var version = require('./package.json').version;

module.exports = function(com,readycb){
  if(typeof options == 'function'){
    readycb = options;
    options = {};
  }

  if(typeof com == 'object'){
    options = com;
    com = options.com;
  }

  var out;
  var parser = outputParser();

  parser.on('data',function(data){
    // send out to event stream
    handle(data);
    // send to bridge.. the bridge can be moved out of this file.
    // must send token first! TODO.
  });

  serial.connect(com,function(err,scoutScript){
    if(err) return out.emit('error');

    out.ready = true;
    out.scoutScript = scoutScript;

    var series = [
      function(){
        out._scommand('hq.gettoken',function(err,data){
          if(err) return out.emit('error',new Error('error getting token. '+err));
          out.token = data;
          done();
        });
      },
      function(){
        out._scommand('mesh.report',function(err,data){
          if(err) return out.emit('error',new Error('error getting mesh config. '+err));
          out.mesh = json(data);
          done();
        });
      },
      function(){
        //var startup = "function startup.dongle {"
        //  +"verbose(1);"
        //  +"mesh.joingroup"
        //+"}";
        //  +"function on.message.group{"
        //    +"group,from,keys"
        //+"};"
        //+""
        out._scommand('hq.verbose(1);report;',done)
      }
    ], done = function(err){
      if(err) return out.emit('error',err);
      var next = series.shift();
      if(next) {
        return next();
      }

      out.emit('ready',scoutScript);
      readycb(false,out);
      readycb = noop;
    };

    done();

    // all serial output
    scoutScript.on('log',function(data){
      parser.write(data);
    });

  });

  // from board
  var handle = function(data){
    var scout;
    //{"type":"mesh","scoutid":2,"troopid":2,"routes":0,"channel":20,"rate":"250 kb/s","power":"3.5 dBm"}
    if(out.mesh) {
      scout = out.mesh.scoutid;
    }

    if(out.token && !out.sentToken){
      out.sentToken = true;
      out.queue({type:"token",token:out.token,dongle:version,scout:scout});
    }

    // add scout id and wrap with type report!
    // make sure its a report!
    // TODO support announce.

    out.queue({type:"report",report:data,from:out.mesh.scoutid});

  }

  out = through(function(data){
    if(!data) return;
    // command stream to board
    //console.log('BRIDGE> ',data);
    if(data.type == 'command') {
      if(!data.to || !data.command){
        return console.log('INVALID BRIDGE COMMAND!',data);
      }

      // support external data.timeout
      var t = Date.now();
      out.command(data.to,data.command,function(err,res){
        //data.
        data.type = "reply";
        if(err) data.err = true;
        data.reply = res != undefined?res:err+'';
        data.from = data.to;
        data.basetime = Date.now()-t;
        data.end = true;
        delete data.to;

        //console.log('COMMAND REPLY!',data);

        // send replies back.
        out.queue(data);
      });
    } else if(data.type == 'online') {
      // noop.
    } else {
      console.log('UNKNOWN bridge command!',  data);
    }

  });

  if(readycb) out.once('error',function(err){
    readycb(err); readycb = noop;
  })

  out.ready = false;

  // just expose command because you probably want to run commands from everywhere
  out.command = function(scout,command,cb){
    if(out.mesh && out.mesh.scoutid == scout) return out._scommand(command,cb);

    // needs to support running on other scouts in troop!
    setImmediate(function(){
      cb('dongle cant message other scouts over mesh yet');
    });
  }

  out._scommand = function(command,cb){
    command = command.trim();
    var attempts = 0
    , z = this
    , run = function _scommand(){
      z.scoutScript.command(command,function(err,data){
        if(err) {
          if(err.code == 'EWRITE' && ++attempts < 2) return _scommand();
        }

        var reply;
        if(!err) {
          var orig = data;
          // remove command just in case it snuck in output.
          if(data.indexOf(command) === 0) data = data.substr(data.indexOf(command));
          var lines = data.split("\r\n");
          reply = [];
          for(var i =0;i<lines.length;++i){
            if(lines[i].indexOf('mesh announcing to') === 0) continue;
            reply.push(lines[i]);
          }
          reply = reply.join("\r\n");

        }
        if(cb) cb(err,reply);
      })
    }
    run();
  }

  out.close = function(){

  }

  return out;
}

function noop(){};

<|endoftext|>


<commit_before>'use strict';

var Promise       = require('bluebird')
  , winston       = require('winston')
  , _             = require('lodash')
  , { URL }       = require('universal-url')
  , EventEmitter  = require('events')
  , through2      = require('through2')
  , socket_io     = require('socket.io-client')
  ;

class Producer extends EventEmitter {
  constructor(tailf = 'https://tailf.io') {
    super();

    let url     = new URL(tailf)
      , room    = url.searchParams.get('room')
      , host    = url.origin
      ;

    this.room = room;
    this.host = host;
    this.socket = socket_io(host);

    this.socket.on('connect', () => {
      this.emit('connect');
    });
  }

  uri() {
    return (new URL(`log/${this.socket.id}`, this.socket.io.uri)).toString();
  }

  stream(options) {
    let { socket, room }          = this
      , { meta = {}, spec = {} }  = options
      ;

    function transform (chunk, enc, cb) {
      let time      = new Date().getTime()
        , { type }  = chunk
        , m         = meta
        , s         = spec
        ;

      if (_.isObject(chunk)) {
        if (chunk.meta) {
          m = _.extend({}, meta, chunk.meta);
        }

        if (chunk.spec) {
          s = _.extend({}, spec, chunk.spec);
        }

        chunk = chunk.chunk;
      }

      // io.on(room, { time, meta, chunk });
      // io.emit('chunk', { time, meta, chunk });
      if (chunk) {
        socket.emit('chunk', { time, type, meta : m, spec : s, room, chunk });
      } else {
        socket.emit('end', { time, type, meta : m, spec : s, room }, () => {
          socket.close();
        });
      }

      cb(undefined, chunk);
    };

    function flush (cb) {
      let time = new Date().getTime();

      // io.emit('end', { time, meta }, () => {
      // io.on(room, { time, meta }, () => {
      socket.emit('end', { time, meta, room }, () => {
        socket.close();
        cb();
      });
    };

    return through2.obj(transform, flush);
  }
}

module.exports = Producer;
<commit_msg>catch any errors in transform<commit_after>'use strict';

var Promise       = require('bluebird')
  , winston       = require('winston')
  , _             = require('lodash')
  , { URL }       = require('universal-url')
  , EventEmitter  = require('events')
  , through2      = require('through2')
  , socket_io     = require('socket.io-client')
  ;

class Producer extends EventEmitter {
  constructor(tailf = 'https://tailf.io') {
    super();

    let url     = new URL(tailf)
      , room    = url.searchParams.get('room')
      , host    = url.origin
      ;

    this.room = room;
    this.host = host;
    this.socket = socket_io(host);

    this.socket.on('connect', () => {
      this.emit('connect');
    });
  }

  uri() {
    return (new URL(`log/${this.socket.id}`, this.socket.io.uri)).toString();
  }

  stream(options) {
    let { socket, room }          = this
      , { meta = {}, spec = {} }  = options
      ;

    function transform (chunk, enc, cb) {
      Promise
        .try(() => {
          let time      = new Date().getTime()
          // todo [akamel] looks like chunk might not be object, this line would break
            , { type }  = chunk
            , m         = meta
            , s         = spec
            ;

          if (_.isObject(chunk)) {
            if (chunk.meta) {
              m = _.extend({}, meta, chunk.meta);
            }

            if (chunk.spec) {
              s = _.extend({}, spec, chunk.spec);
            }

            chunk = chunk.chunk;
          }

          // io.on(room, { time, meta, chunk });
          // io.emit('chunk', { time, meta, chunk });
          if (chunk) {
            socket.emit('chunk', { time, type, meta : m, spec : s, room, chunk });
          } else {
            socket.emit('end', { time, type, meta : m, spec : s, room }, () => {
              socket.close();
            });
          }
        })
        .catch((err) => {
          winston.error(err);
          throw err;
        })
        .asCallback(cb);
    };

    function flush (cb) {
      let time = new Date().getTime();

      // io.emit('end', { time, meta }, () => {
      // io.on(room, { time, meta }, () => {
      socket.emit('end', { time, meta, room }, () => {
        socket.close();
        cb();
      });
    };

    return through2.obj(transform, flush);
  }
}

module.exports = Producer;
<|endoftext|>