<commit_before>(function($) {
  $(function() {
    $('a[data-obfu]').each(function() {
      var self = $(this)
        , obfu = self.data('obfu')
        , text = ''
        , rand
        , i;

      rand = parseInt(obfu.substr(0, 2), 16);

      for (i = 1; i < obfu.length / 2; ++i) {
        text += String.fromCharCode(parseInt(obfu.substr(i * 2, 2), 16) ^ rand);
      }
      self.attr('href', text);
    });
  });

  $(function() {
    var $win = $(window)
      , $body = $('body')
      , $navbar = $('#navbar')
      , $navbarContainer = $('#navbar .container')
      , $navbarCollapse = $('#navbar .navbar-collapse')
      , navHeight = $('#navbar').height()
      , navTop = $('#navbar').length && $('#navbar').offset().top
      , marginTop = parseInt($body.css('margin-top'), 10);

    $win.ready(processScroll);
    $win.scroll(processScroll);
    $win.resize(processScroll);
    $win.ready(fixNavTop);
    $win.resize(fixNavTop);

    function processScroll() {
      if ($body.width() < 750) {
        return;
      }

      var scrollTop = $win.scrollTop()
        , navTop = $('#banner').height() + $('#banner').offset().top
        , navHeight = $('#navbar').height();

      if (scrollTop >= navTop) {
        $navbar.addClass('navbar-fixed-top');
        $navbarContainer.removeClass('navbar-container-style');
        $body.css('margin-top', marginTop + navHeight + 'px');

      } else if (scrollTop <= navTop){
        $navbar.removeClass('navbar-fixed-top');
        $navbarContainer.addClass('navbar-container-style');
        $body.css('margin-top', marginTop + 'px');
      }
    }

    function fixNavTop() {
      if ($body.width() < 750) {
        $navbar.removeClass('navbar-fixed-top');
      }

      if ($body.width() < 768) {
        $navbarCollapse.removeClass('navbar-collapse-style');
      }

      if ($body.width() > 750) {
        $navbarCollapse.addClass('navbar-collapse-style');
      }
    }
  });

  $(function() {
    var MIN_WIDTH = 768;
    $('.navbar-search-form input').click(function() {
      var width = $('body').width();
      if (width >= MIN_WIDTH) {
        $(this).parent().parent().addClass('open');
      }
    });

    $('.navbar-search-form input').blur(function() {
      var width = $('body').width();
      if (width >= MIN_WIDTH && !trim($(this).val())) {
        $(this).val('');
        $(this).parent().parent().removeClass('open');
      }
    });

    function trim(str) {
      return str.replace(/(^\s*)|(\s*$)/g, '');
    }
  });

  $(function() {
    var $win = $(window)
      , topIcon = $('#goto-top-icon')
      , distance = 300;

    $win.scroll(function() {
      if ($win.scrollTop() > distance) {
        topIcon.focusout();
        topIcon.fadeIn();
      } else {
        topIcon.focusout();
        topIcon.fadeOut();
      }
    });

    topIcon.click(function() {
      $('html, body').animate({
        scrollTop: 0
      }, 1000);
    });
  });
})(window.jQuery);<commit_msg>Improved navigation bar display experience<commit_after>(function($) {
  $(function() {
    $('a[data-obfu]').each(function() {
      var self = $(this)
        , obfu = self.data('obfu')
        , text = ''
        , rand
        , i;

      rand = parseInt(obfu.substr(0, 2), 16);

      for (i = 1; i < obfu.length / 2; ++i) {
        text += String.fromCharCode(parseInt(obfu.substr(i * 2, 2), 16) ^ rand);
      }
      self.attr('href', text);
    });
  });

  $(function() {
    var $win = $(window)
      , $body = $('body')
      , $navbar = $('#navbar')
      , $navbarContainer = $('#navbar .container')
      , $navbarCollapse = $('#navbar .navbar-collapse')
      , navHeight = $('#navbar').height()
      , navTop = $('#navbar').length && $('#navbar').offset().top
      , marginTop = parseInt($body.css('margin-top'), 10);

    $win.ready(processScroll);
    $win.scroll(processScroll);
    $win.resize(processScroll);
    $win.ready(fixNavTop);
    $win.resize(fixNavTop);

    function processScroll() {
      var scrollTop = $win.scrollTop()
        , navTop = $('#banner').height() + $('#banner').offset().top
        , navHeight = $('#navbar').height();

      if (scrollTop >= navTop) {
        $navbar.addClass('navbar-fixed-top');
        $navbarContainer.removeClass('navbar-container-style');
        $body.css('margin-top', marginTop + navHeight + 'px');

      } else if (scrollTop <= navTop){
        $navbar.removeClass('navbar-fixed-top');
        $navbarContainer.addClass('navbar-container-style');
        $body.css('margin-top', marginTop + 'px');
      }
    }

    function fixNavTop() {
      if ($body.width() < 768) {
        $navbarCollapse.removeClass('navbar-collapse-style');
      }

      if ($body.width() > 750) {
        $navbarCollapse.addClass('navbar-collapse-style');
      }
    }
  });

  $(function() {
    var MIN_WIDTH = 768;
    $('.navbar-search-form input').click(function() {
      var width = $('body').width();
        $(this).parent().parent().addClass('open');
    });

    $('.navbar-search-form input').blur(function() {
      var width = $('body').width();
      if (!trim($(this).val())) {
        $(this).val('');
        $(this).parent().parent().removeClass('open');
      }
    });

    function trim(str) {
      return str.replace(/(^\s*)|(\s*$)/g, '');
    }
  });

  $(function() {
    var $win = $(window)
      , topIcon = $('#goto-top-icon')
      , distance = 300;

    $win.scroll(function() {
      if ($win.scrollTop() > distance) {
        topIcon.focusout();
        topIcon.fadeIn();
      } else {
        topIcon.focusout();
        topIcon.fadeOut();
      }
    });

    topIcon.click(function() {
      $('html, body').animate({
        scrollTop: 0
      }, 1000);
    });
  });
})(window.jQuery);<|endoftext|>


<commit_before>import React from 'react'
import NotificationItem from 'app/components/notifications/item'

function NotificationsMenu(props){
  return (

        {(props.unread || []).map((p) => (
          <NotificationItem key={p.id} notification={p} now={props.open_time}/>
        ))}

          View all

  )
}

export default NotificationsMenu
<commit_msg>Can view messages if more than visible. Limit to 5.<commit_after>import React from 'react'
import NotificationItem from 'app/components/notifications/item'

function NotificationsMenu(props){
  const unread=props.unread || []
  return (

        {(unread).slice(0,5).map((p) => (
          <NotificationItem key={p.id} notification={p} now={props.open_time}/>
        ))}
        {unread.length > 5 ? (

          And {unread.length - 5} more...

        ) : null}

          View all

  )
}

export default NotificationsMenu
<|endoftext|>


<commit_before>/*jslint */

/*global tangelo */

/**
 *
 * @fileOverview Provides generic utilities.
 */

(function () {
    "use strict";

    var mod;

    /**
     *
     * @name util
     *
     * @memberOf tangelo
     *
     * @namespace General utilities cutting across several application needs.
     */
    mod = tangelo.namespace("util");

    mod.drawer_size = function () {
        return 23;
    };

    mod.drawer_toggle = function (divsel, buttonsel) {
        var div,
            button,
            state,
            divheight,
            iconheight;

        // Use the selectors to grab the DOM elements.
        div = d3.select(divsel);
        button = d3.select(buttonsel);

        // Initially, the panel is open.
        state = 'uncollapsed'

        // Save the original height of the panel.
        //
        // TODO(choudhury): when the panel is collapsed and then uncollapsed, it
        // is too short for some reason.  Adding 40 pixels makes things so all
        // the panel content can be seen, but it would be better to figure out
        // why this happens.
        divheight = +div.style("height").slice(0,-2) + 40 + "px";
        console.log(divheight);

        // The glyphicon halfings are around 22.875 pixels tall.
        iconheight = mod.drawer_size() + "px";

        // This function, when called, will toggle the state of the panel.
        return function () {
            if(state === 'uncollapsed'){
                div.transition()
                    .duration(500)
                    .style("height", iconheight);

                button.classed("icon-chevron-down", false)
                    .classed("icon-chevron-up", true);

                state = 'collapsed';
            } else if (state === 'collapsed') {
                div.transition()
                    .duration(500)
                    .style("height", divheight);

                button.classed("icon-chevron-down", true)
                    .classed("icon-chevron-up", false);

                state = 'uncollapsed';
            } else {
                throw "Illegal state: " + state;
            }
        };
    };

    mod.svgColorLegend = function (legend, cmap_func, xoffset, yoffset, categories, height_padding, width_padding, text_spacing, legend_margins, clear) {
        var bbox,
            bg,
            bottom,
            height,
            heightfunc,
            left,
            maxheight,
            maxwidth,
            right,
            text,
            top,
            totalheight,
            totalwidth,
            width;

        // Clear the svg element, if requested.
        clear = clear || false;
        if (clear) {
            legend.selectAll("*").remove();
        }

        maxwidth = 0;
        maxheight = 0;

        // Place a rect that will serve as a container/background for the legend
        // list items.  Leave its dimensions undefined for now (they will be
        // computed from the size of all the elements later).
        bg = legend.append("rect")
            //.style("fill", "gray");
            .style("fill", "white")
            .style("opacity", 0.7);

        $.each(categories, function (i, d) {
            legend.append("rect")
            .classed("colorbox", true)
            .attr("x", xoffset)
            // "y", "width", and "height" intentionally left unset
            .style("fill", cmap_func(d));

        text = legend.append("text")
            .classed("legendtext", true)
            // "x" and "y" intentionally left unset
            .text(d);

        // Compute the max height and width out of all the text bgs.
        bbox = text[0][0].getBBox();

        if (bbox.width > maxwidth) {
            maxwidth = bbox.width;
        }

        if (bbox.height > maxheight) {
            maxheight = bbox.height;
        }
        });

        // Compute the height and width of each color swatch.
        height = maxheight + height_padding;
        width = height;

        // Compute the total height and width of all the legend items together.
        totalheight = height * categories.length;
        totalwidth = width + width_padding + maxwidth;

        // Get the user-supplied margin values.
        left = legend_margins.left || 0;
        top = legend_margins.top || 0;
        right = legend_margins.right || 0;
        bottom = legend_margins.bottom || 0;

        // Set the dimensions of the container rect, based on the height/width of
        // all the items, plus the user supplied margins.
        bg.attr("x", xoffset - left || 0)
            .attr("y", yoffset - top || 0)
            .attr("width", left + totalwidth + right)
            .attr("height", top + totalheight + bottom);

        heightfunc = function (d, i) {
            return yoffset + i * height;
        };

        legend.selectAll(".colorbox")
            .attr("width", height)
            .attr("height", height)
            .attr("y", heightfunc);

        legend.selectAll(".legendtext")
            .attr("x", xoffset + width + width_padding)
            .attr("y", function (d, i) {
                //return 19 + heightfunc(d, i);
                return text_spacing + heightfunc(d, i);
            });
    };

    mod.allDefined = function () {
        // Returns true if all arguments are defined; false otherwise.

        var i;

        for (i = 0; i < arguments.length; i += 1) {
            if (arguments[i] === undefined) {
                return false;
            }
        }

        return true;
    };

    mod.landingPage = function (cfg) {
        var specFile,
            appLeftSelector,
            appRightSelector,
            extLeftSelector,
            extRightSelector;

        // Pull values from the config object argument.
        specFile = cfg.specFile;
        appLeftSelector = cfg.appLeftSelector;
        appRightSelector = cfg.appRightSelector;
        extLeftSelector = cfg.extLeftSelector;
        extRightSelector = cfg.extRightSelector;

        // Retrieve the contents of the specification file, then build up the
        // page.
        d3.json(specFile, function (err, spec) {
            var app,
                apps,
                col,
                cols,
                external,
                i,
                left,
                right,
                text;

            if (err !== null) {
                console.log("fatal error: could not load app list from " + specFile);
                return;
            }

            // Pull out the two lists in the specification - one for the list of
            // apps, and one for the list of external links.
            apps = spec.apps;
            external = spec.external;

            if (apps !== undefined) {
                if (!tangelo.util.allDefined(appLeftSelector, appRightSelector)){
                    throw "Required config argument property appLeftSelector or appRightSelector missing!";
                }

                // Grab a reference to each of the two index columns.
                left = d3.select(appLeftSelector);
                right = d3.select(appRightSelector);
                cols = [left, right];

                // Place the app info/links into the two columns, alternating
                // between left and right.
                for (i = 0; i < apps.length; i = i + 1) {
                    col = cols[i % 2];
                    app = apps[i];

                    col.append("a")
                        .attr("href", "/app/" + app.path + "/")
                        .append("h4")
                        .html(app.name);
                    col.append("p")
                        .html(app.description);
                }
            }

            if (external !== undefined) {
                if (!tangelo.util.allDefined(extLeftSelector, extRightSelector)) {
                    throw "Required config argument property extLeftSelector or extRightSelector missing!";
                }

                // List out the external links in the two columns, as above.
                left = d3.select(extLeftSelector);
                right = d3.select(extRightSelector);
                cols = [left, right];
                text = function (d) {
                    return "" + "" + d.name + "" + "" +
                        " (" + d.institution + ") - " +
                        d.description;
                };
                for (i = 0; i < external.length; i = i + 1) {
                    col = cols[i % 2];
                    app = external[i];

                    col.append("div")
                        .html(text(app));
                }
            }
        });
    };
}());
<commit_msg>Correctly finding height panel, fixes #83<commit_after>/*jslint */

/*global tangelo */

/**
 *
 * @fileOverview Provides generic utilities.
 */

(function () {
    "use strict";

    var mod;

    /**
     *
     * @name util
     *
     * @memberOf tangelo
     *
     * @namespace General utilities cutting across several application needs.
     */
    mod = tangelo.namespace("util");

    mod.drawer_size = function () {
        return 23;
    };

    mod.drawer_toggle = function (divsel, buttonsel) {
        var div,
            button,
            state,
            divheight,
            iconheight;

        // Use the selectors to grab the DOM elements.
        div = d3.select(divsel);
        button = d3.select(buttonsel);

        // Initially, the panel is open.
        state = 'uncollapsed';

        // The glyphicon halfings are around 22.875 pixels tall.
        iconheight = mod.drawer_size() + "px";

        // Save the original height of the panel.
        // This requires a DOM update to do this correctly, so we wait a second.
        // I have found that waiting less than 200ms can cause undefined behavior,
        // since there may be other callback that need to populate the panel.
        function updateHeight() {
            divheight = $(div.node()).height() + "px";
        }
        window.setTimeout(updateHeight, 1000);

        // This function, when called, will toggle the state of the panel.
        return function () {
            if(state === 'uncollapsed'){
                div.transition()
                    .duration(500)
                    .style("height", iconheight);

                button.classed("icon-chevron-down", false)
                    .classed("icon-chevron-up", true);

                state = 'collapsed';
            } else if (state === 'collapsed') {
                div.transition()
                    .duration(500)
                    .style("height", divheight);

                button.classed("icon-chevron-down", true)
                    .classed("icon-chevron-up", false);

                state = 'uncollapsed';
            } else {
                throw "Illegal state: " + state;
            }
        };
    };

    mod.svgColorLegend = function (legend, cmap_func, xoffset, yoffset, categories, height_padding, width_padding, text_spacing, legend_margins, clear) {
        var bbox,
            bg,
            bottom,
            height,
            heightfunc,
            left,
            maxheight,
            maxwidth,
            right,
            text,
            top,
            totalheight,
            totalwidth,
            width;

        // Clear the svg element, if requested.
        clear = clear || false;
        if (clear) {
            legend.selectAll("*").remove();
        }

        maxwidth = 0;
        maxheight = 0;

        // Place a rect that will serve as a container/background for the legend
        // list items.  Leave its dimensions undefined for now (they will be
        // computed from the size of all the elements later).
        bg = legend.append("rect")
            //.style("fill", "gray");
            .style("fill", "white")
            .style("opacity", 0.7);

        $.each(categories, function (i, d) {
            legend.append("rect")
            .classed("colorbox", true)
            .attr("x", xoffset)
            // "y", "width", and "height" intentionally left unset
            .style("fill", cmap_func(d));

        text = legend.append("text")
            .classed("legendtext", true)
            // "x" and "y" intentionally left unset
            .text(d);

        // Compute the max height and width out of all the text bgs.
        bbox = text[0][0].getBBox();

        if (bbox.width > maxwidth) {
            maxwidth = bbox.width;
        }

        if (bbox.height > maxheight) {
            maxheight = bbox.height;
        }
        });

        // Compute the height and width of each color swatch.
        height = maxheight + height_padding;
        width = height;

        // Compute the total height and width of all the legend items together.
        totalheight = height * categories.length;
        totalwidth = width + width_padding + maxwidth;

        // Get the user-supplied margin values.
        left = legend_margins.left || 0;
        top = legend_margins.top || 0;
        right = legend_margins.right || 0;
        bottom = legend_margins.bottom || 0;

        // Set the dimensions of the container rect, based on the height/width of
        // all the items, plus the user supplied margins.
        bg.attr("x", xoffset - left || 0)
            .attr("y", yoffset - top || 0)
            .attr("width", left + totalwidth + right)
            .attr("height", top + totalheight + bottom);

        heightfunc = function (d, i) {
            return yoffset + i * height;
        };

        legend.selectAll(".colorbox")
            .attr("width", height)
            .attr("height", height)
            .attr("y", heightfunc);

        legend.selectAll(".legendtext")
            .attr("x", xoffset + width + width_padding)
            .attr("y", function (d, i) {
                //return 19 + heightfunc(d, i);
                return text_spacing + heightfunc(d, i);
            });
    };

    mod.allDefined = function () {
        // Returns true if all arguments are defined; false otherwise.

        var i;

        for (i = 0; i < arguments.length; i += 1) {
            if (arguments[i] === undefined) {
                return false;
            }
        }

        return true;
    };

    mod.landingPage = function (cfg) {
        var specFile,
            appLeftSelector,
            appRightSelector,
            extLeftSelector,
            extRightSelector;

        // Pull values from the config object argument.
        specFile = cfg.specFile;
        appLeftSelector = cfg.appLeftSelector;
        appRightSelector = cfg.appRightSelector;
        extLeftSelector = cfg.extLeftSelector;
        extRightSelector = cfg.extRightSelector;

        // Retrieve the contents of the specification file, then build up the
        // page.
        d3.json(specFile, function (err, spec) {
            var app,
                apps,
                col,
                cols,
                external,
                i,
                left,
                right,
                text;

            if (err !== null) {
                console.log("fatal error: could not load app list from " + specFile);
                return;
            }

            // Pull out the two lists in the specification - one for the list of
            // apps, and one for the list of external links.
            apps = spec.apps;
            external = spec.external;

            if (apps !== undefined) {
                if (!tangelo.util.allDefined(appLeftSelector, appRightSelector)){
                    throw "Required config argument property appLeftSelector or appRightSelector missing!";
                }

                // Grab a reference to each of the two index columns.
                left = d3.select(appLeftSelector);
                right = d3.select(appRightSelector);
                cols = [left, right];

                // Place the app info/links into the two columns, alternating
                // between left and right.
                for (i = 0; i < apps.length; i = i + 1) {
                    col = cols[i % 2];
                    app = apps[i];

                    col.append("a")
                        .attr("href", "/app/" + app.path + "/")
                        .append("h4")
                        .html(app.name);
                    col.append("p")
                        .html(app.description);
                }
            }

            if (external !== undefined) {
                if (!tangelo.util.allDefined(extLeftSelector, extRightSelector)) {
                    throw "Required config argument property extLeftSelector or extRightSelector missing!";
                }

                // List out the external links in the two columns, as above.
                left = d3.select(extLeftSelector);
                right = d3.select(extRightSelector);
                cols = [left, right];
                text = function (d) {
                    return "" + "" + d.name + "" + "" +
                        " (" + d.institution + ") - " +
                        d.description;
                };
                for (i = 0; i < external.length; i = i + 1) {
                    col = cols[i % 2];
                    app = external[i];

                    col.append("div")
                        .html(text(app));
                }
            }
        });
    };
}());
<|endoftext|>


<commit_before>/**
 * Client to connect to a darkwallet gateway.
 *
 * @param {String}   connect_uri Gateway websocket URI
 * @param {Function} handle_connect Callback to run when connected
 */
function GatewayClient(connect_uri, handle_connect) {
    var self = this;
    this.handler_map = {};
    this.websocket = new WebSocket(connect_uri);
    this.websocket.onopen = function(evt) {
        handle_connect();
    };
    this.websocket.onclose = function(evt) {
        self.on_close(evt);
    };
    this.websocket.onerror = function(evt) {
        self.on_error(evt);
    };
    this.websocket.onmessage = function(evt) {
        self._on_message(evt);
    };
}

/**
 * Get last height
 *
 * @param {Function} handle_fetch Callback to handle the returned height
 */
GatewayClient.prototype.fetch_last_height = function(handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_last_height", [], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

/**
 * Fetch transaction
 *
 * @param {String}   tx_hash Transaction identifier hash
 * @param {Function} handle_fetch Callback to handle the JSON object
 * representing the transaction
 */
GatewayClient.prototype.fetch_transaction = function(tx_hash, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_transaction", [tx_hash], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

/**
 * Fetch history
 *
 * @param {String}   address
 * @param {Function} handle_fetch Callback to handle the JSON object
 * representing the history of the address
 */
GatewayClient.prototype.fetch_history = function(address, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_history", [address], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

/**
 * Subscribe
 *
 * @param {String}   address
 * @param {Function} handle_fetch Callback to handle subscription result
 * @param {Function} handle_update Callback to handle the JSON object
 * representing for updates
 */
GatewayClient.prototype.subscribe = function(
    address, handle_fetch, handle_update)
{
    var self = this;
    this.make_request("subscribe_address", [address], function(response) {
        handle_fetch(response["error"], response["result"][0]);
        if (handle_update) {
            self.handler_map["update." + address] = handle_update;
        }
    });
}

GatewayClient.prototype.fetch_block_header = function(index, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_block_header", [index], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

GatewayClient.prototype.fetch_block_transaction_hashes = function(
    index, handle_fetch)
{
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_block_transaction_hashes", [index],
        function(response) {
            handle_fetch(response["error"], response["result"][0]);
        });
};

GatewayClient.prototype.fetch_spend = function(outpoint, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_spend", [outpoint], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

GatewayClient.prototype.fetch_transaction_index = function(
    tx_hash, handle_fetch)
{
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_transaction_index", [tx_hash],
        function(response) {
            result = response["result"];
            handle_fetch(response["error"], result[0], result[1]);
        });
};

GatewayClient.prototype.fetch_block_height = function(blk_hash, handle_fetch)
{
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_block_height", [blk_hash], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

GatewayClient.prototype.broadcast_transaction = function(
    raw_tx, handle_fetch)
{
    GatewayClient._check_function(handle_fetch);

    this.make_request("broadcast_transaction", [raw_tx], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

/**
 * Renew
 *
 * @param {String}   address
 * @param {Function} handle_fetch Callback to handle subscription result
 * @param {Function} handle_update Callback to handle the JSON object
 * representing for updates
 */
GatewayClient.prototype.renew = function(address, handle_fetch, handle_update)
{
    var self = this;
    this.make_request("renew_address", [address], function(response) {
        handle_fetch(response["error"], response["result"][0]);
        if (handle_update) {
            self.handler_map["update."+address] = handle_update;
        }
    });
}

/**
 * Make requests to the server
 *
 * @param {String} command
 * @param {Array} params
 * @param {Function} handler
 */
GatewayClient.prototype.make_request = function(command, params, handler) {
    GatewayClient._check_function(handler);

    var id = GatewayClient._random_integer();
    var request = {
        "id": id,
        "command": command,
        "params": params
    };
    var message = JSON.stringify(request);
    this.websocket.send(message);
    this.handler_map[id] = handler;
};

/**
 * Close event handler
 *
 * @param {Object} evt event
 */
GatewayClient.prototype.on_close = function(evt) {
};

/**
 * Error event handler
 *
 * @param {Object} evt event
 *
 * @throws {Object}
 */
GatewayClient.prototype.on_error = function(evt) {
    throw evt;
};

/**
 * After triggering message event, calls to the handler of the petition
 *
 * @param {Object} evt event
 * @private
 */
GatewayClient.prototype._on_message = function(evt) {
    this.on_message(evt)
    response = JSON.parse(evt.data);
    id = response.id;
    // Should be a separate map entirely. This is a hack.
    if (response.name == "update")
        id = "update." + response.address;
    // Prefer flat code over nested.
    if (!this.handler_map[id]) {
        console.log("Handler not found");
        return;
    }
    handler = this.handler_map[id];
    handler(response);
};

/**
 * Message event handler
 *
 * @param {Object} evt event
 */
GatewayClient.prototype.on_message = function(evt) {
}

/**
 * (Pseudo-)Random integer generator
 *
 * @return {Number} Random integer
 * @private
 */
GatewayClient._random_integer = function() {
    return Math.floor((Math.random() * 4294967296));
};

/**
 * Checks if param can be executed
 *
 * @param {Function} Function to be checked
 *
 * @throws {String} Parameter is not a function
 * @protected
 */
GatewayClient._check_function = function(func) {
    if (typeof func !== 'function') {
        throw "Parameter is not a function";
    }
};

<commit_msg>update to upstream.<commit_after>/**
 * Client to connect to a darkwallet gateway.
 *
 * @param {String}   connect_uri Gateway websocket URI
 * @param {Function} handle_connect Callback to run when connected
 */
function GatewayClient(connect_uri, handle_connect) {
    var self = this;
    this.handler_map = {};
    this.websocket = new WebSocket(connect_uri);
    this.websocket.onopen = function(evt) {
        handle_connect();
    };
    this.websocket.onclose = function(evt) {
        self.on_close(evt);
    };
    this.websocket.onerror = function(evt) {
        self.on_error(evt);
    };
    this.websocket.onmessage = function(evt) {
        self._on_message(evt);
    };
}

/**
 * Get last height
 *
 * @param {Function} handle_fetch Callback to handle the returned height
 */
GatewayClient.prototype.fetch_last_height = function(handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_last_height", [], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

/**
 * Fetch transaction
 *
 * @param {String}   tx_hash Transaction identifier hash
 * @param {Function} handle_fetch Callback to handle the JSON object
 * representing the transaction
 */
GatewayClient.prototype.fetch_transaction = function(tx_hash, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_transaction", [tx_hash], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

/**
 * Fetch history
 *
 * @param {String}   address
 * @param {Function} handle_fetch Callback to handle the JSON object
 * representing the history of the address
 */
GatewayClient.prototype.fetch_history = function(address, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_history", [address], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

GatewayClient.prototype.fetch_stealth = function(
    prefix, handle_fetch, from_height)
{
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_stealth", [prefix, from_height],
        function(response) {
            handle_fetch(response["error"], response["result"][0]);
        });
};

/**
 * Subscribe
 *
 * @param {String}   address
 * @param {Function} handle_fetch Callback to handle subscription result
 * @param {Function} handle_update Callback to handle the JSON object
 * representing for updates
 */
GatewayClient.prototype.subscribe = function(
    address, handle_fetch, handle_update)
{
    var self = this;
    this.make_request("subscribe_address", [address], function(response) {
        handle_fetch(response["error"], response["result"][0]);
        if (handle_update) {
            self.handler_map["update." + address] = handle_update;
        }
    });
}

GatewayClient.prototype.fetch_block_header = function(index, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_block_header", [index], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

GatewayClient.prototype.fetch_block_transaction_hashes = function(
    index, handle_fetch)
{
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_block_transaction_hashes", [index],
        function(response) {
            handle_fetch(response["error"], response["result"][0]);
        });
};

GatewayClient.prototype.fetch_spend = function(outpoint, handle_fetch) {
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_spend", [outpoint], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

GatewayClient.prototype.fetch_transaction_index = function(
    tx_hash, handle_fetch)
{
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_transaction_index", [tx_hash],
        function(response) {
            result = response["result"];
            handle_fetch(response["error"], result[0], result[1]);
        });
};

GatewayClient.prototype.fetch_block_height = function(blk_hash, handle_fetch)
{
    GatewayClient._check_function(handle_fetch);

    this.make_request("fetch_block_height", [blk_hash], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

GatewayClient.prototype.broadcast_transaction = function(
    raw_tx, handle_fetch)
{
    GatewayClient._check_function(handle_fetch);

    this.make_request("broadcast_transaction", [raw_tx], function(response) {
        handle_fetch(response["error"], response["result"][0]);
    });
};

/**
 * Renew
 *
 * @param {String}   address
 * @param {Function} handle_fetch Callback to handle subscription result
 * @param {Function} handle_update Callback to handle the JSON object
 * representing for updates
 */
GatewayClient.prototype.renew = function(address, handle_fetch, handle_update)
{
    var self = this;
    this.make_request("renew_address", [address], function(response) {
        handle_fetch(response["error"], response["result"][0]);
        if (handle_update) {
            self.handler_map["update."+address] = handle_update;
        }
    });
}

/**
 * Make requests to the server
 *
 * @param {String} command
 * @param {Array} params
 * @param {Function} handler
 */
GatewayClient.prototype.make_request = function(command, params, handler) {
    GatewayClient._check_function(handler);

    var id = GatewayClient._random_integer();
    var request = {
        "id": id,
        "command": command,
        "params": params
    };
    var message = JSON.stringify(request);
    this.websocket.send(message);
    this.handler_map[id] = handler;
};

/**
 * Close event handler
 *
 * @param {Object} evt event
 */
GatewayClient.prototype.on_close = function(evt) {
};

/**
 * Error event handler
 *
 * @param {Object} evt event
 *
 * @throws {Object}
 */
GatewayClient.prototype.on_error = function(evt) {
    throw evt;
};

/**
 * After triggering message event, calls to the handler of the petition
 *
 * @param {Object} evt event
 * @private
 */
GatewayClient.prototype._on_message = function(evt) {
    this.on_message(evt)
    response = JSON.parse(evt.data);
    id = response.id;
    // Should be a separate map entirely. This is a hack.
    if (response.name == "update")
        id = "update." + response.address;
    // Prefer flat code over nested.
    if (!this.handler_map[id]) {
        console.log("Handler not found");
        return;
    }
    handler = this.handler_map[id];
    handler(response);
};

/**
 * Message event handler
 *
 * @param {Object} evt event
 */
GatewayClient.prototype.on_message = function(evt) {
}

/**
 * (Pseudo-)Random integer generator
 *
 * @return {Number} Random integer
 * @private
 */
GatewayClient._random_integer = function() {
    return Math.floor((Math.random() * 4294967296));
};

/**
 * Checks if param can be executed
 *
 * @param {Function} Function to be checked
 *
 * @throws {String} Parameter is not a function
 * @protected
 */
GatewayClient._check_function = function(func) {
    if (typeof func !== 'function') {
        throw "Parameter is not a function";
    }
};

<|endoftext|>


<commit_before>
import invariant from 'invariant'
import pathmaker from '../util/pathmaker'

import sf from '../util/sf'
import mklog from '../util/log'
const log = mklog('tasks/uninstall')

import core from './install/core'

const keepArchives = (process.env.REMEMBER_ME_WHEN_IM_GONE === '1')

export default async function start (out, opts) {
  const {cave, globalMarket} = opts
  invariant(cave, 'uninstall has cave')
  invariant(globalMarket, 'uninstall has cave')

  const onProgress = (info) => out.emit('progress', info.percent)

  const destPath = pathmaker.appPath(cave)

  if (cave.uploadId && cave.uploads && cave.uploads[cave.uploadId]) {
    const upload = cave.uploads[cave.uploadId]

    const archivePath = pathmaker.archivePath(upload)

    log(opts, `Uninstalling app in ${destPath} from archive ${archivePath}`)

    const coreOpts = {
      ...opts,
      onProgress,
      archivePath
    }
    globalMarket.saveEntity('caves', cave.id, {launchable: false})

    try {
      await core.uninstall(out, coreOpts)
      log(opts, `Uninstallation successful`)
    } catch (e) {
      if (e instanceof core.UnhandledFormat) {
        log(opts, e.message)
        log(opts, `Imploding anyway`)
        await sf.wipe(destPath)
      } else {
        // re-raise other errors
        throw e
      }
    }

    if (!keepArchives) {
      log(opts, `Erasing archive ${archivePath}`)
      await sf.wipe(archivePath)
    }
  }

  log(opts, `Imploding ${destPath}`)
  globalMarket.deleteEntity('caves', cave.id)
}
<commit_msg>:bug:<commit_after>
import invariant from 'invariant'
import pathmaker from '../util/pathmaker'

import sf from '../util/sf'
import mklog from '../util/log'
const log = mklog('tasks/uninstall')

import core from './install/core'

const keepArchives = (process.env.REMEMBER_ME_WHEN_IM_GONE === '1')

export default async function start (out, opts) {
  const {cave, globalMarket} = opts
  invariant(cave, 'uninstall has cave')
  invariant(globalMarket, 'uninstall has cave')

  const onProgress = (info) => out.emit('progress', info.percent)

  const destPath = pathmaker.appPath(cave)

  if (cave.uploadId && cave.uploads && cave.uploads[cave.uploadId]) {
    const upload = cave.uploads[cave.uploadId]

    const archivePath = pathmaker.downloadPath(upload)

    log(opts, `Uninstalling app in ${destPath} from archive ${archivePath}`)

    const coreOpts = {
      ...opts,
      onProgress,
      archivePath
    }
    globalMarket.saveEntity('caves', cave.id, {launchable: false})

    try {
      await core.uninstall(out, coreOpts)
      log(opts, `Uninstallation successful`)
    } catch (e) {
      if (e instanceof core.UnhandledFormat) {
        log(opts, e.message)
        log(opts, `Imploding anyway`)
        await sf.wipe(destPath)
      } else {
        // re-raise other errors
        throw e
      }
    }

    if (!keepArchives) {
      log(opts, `Erasing archive ${archivePath}`)
      await sf.wipe(archivePath)
    }
  }

  log(opts, `Imploding ${destPath}`)
  globalMarket.deleteEntity('caves', cave.id)
}
<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const app = express();
const config = require('config');
const router = require('./app/core/router');<% if (options.templateEngine === 'twig') { %>
const twig = require('./app/templating/twig/engine');<% } else { %>
const hbs = require('./app/templating/hbs/engine');<% } %>
const compression = require('compression');
const bodyParser = require('body-parser');

<% if (options.templateEngine === 'twig') { %>
	twig.cache(false);
<% } else { %>
	// partials
	require('./app/templating/hbs/partials')(hbs);
<% } %>

// compress all requests
app.use(compression());

// translations
require('./app/core/i18n')(app);

// Loads custom project routes
require('./app/core/routeLoader')(app);

app.use(router);
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', config.get('nitro.viewFileExtension'));
app.set('views', config.get('nitro.basePath') + config.get('nitro.viewDirectory'));

<% if (options.templateEngine === 'twig') { %>
	app.engine(config.get('nitro.viewFileExtension'), twig.renderWithLayout);
<% } else { %>
	app.engine(config.get('nitro.viewFileExtension'), hbs.__express);
<% } %>

require('./app/core/listen')(app);
<commit_msg> #130 fix formatting<commit_after>'use strict';

const express = require('express');
const app = express();
const config = require('config');
const router = require('./app/core/router');<% if (options.templateEngine === 'twig') { %>
const twig = require('./app/templating/twig/engine');<% } else { %>
const hbs = require('./app/templating/hbs/engine');<% } %>
const compression = require('compression');
const bodyParser = require('body-parser');

<% if (options.templateEngine === 'twig') { %>
twig.cache(false);
<% } else { %>
// partials
require('./app/templating/hbs/partials')(hbs);
<% } %>

// compress all requests
app.use(compression());

// translations
require('./app/core/i18n')(app);

// Loads custom project routes
require('./app/core/routeLoader')(app);

app.use(router);
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', config.get('nitro.viewFileExtension'));
app.set('views', config.get('nitro.basePath') + config.get('nitro.viewDirectory'));

<% if (options.templateEngine === 'twig') { %>
app.engine(config.get('nitro.viewFileExtension'), twig.renderWithLayout);
<% } else { %>
app.engine(config.get('nitro.viewFileExtension'), hbs.__express);
<% } %>

require('./app/core/listen')(app);
<|endoftext|>


<commit_before>google.load('visualization', '1', {packages:['orgchart']});
google.setOnLoadCallback( function() {
    $( document ).ready( function() {
        initChart();
        setClickHandler(_updateFromIri);
        $( document ).on( 'updateFromIri', _updateChartFromIri);
        _updateFromIri( "http://dot.rural/sepake/UKEOFOrganisation#Scottish%20Environment%20Protection%20Agency" );
    });
});

function _updateFromIri(iri) {
    $( document ).trigger( 'updateFromIri', iri );
  }

function _updateChartFromIri(event, iri) {
    sparql("ownerchart",
            [
            "SELECT ?owner ?ownerlabel ?owned ?ownedlabel WHERE {",
            "  {",
            "    BIND (<--IRI--> AS ?owner) .",
            "    {?owner <owns> ?owned} .",
            "    {?owner rdfs:label ?ownerlabel} .",
            "    {?owned rdfs:label ?ownedlabel} .",
            "  } UNION {",
            "    BIND (<--IRI--> AS ?focus) .",
            "    {?owner <owns> ?focus} .",
            "    {?owner <owns> ?owned} .",
            "    {?owner rdfs:label ?ownerlabel} .",
            "    {?owned rdfs:label ?ownedlabel} .",
            "  }",
            "}",
            "ORDER BY ?ownerlabel ?ownedlabel",
            //TODO Add paging
           ],
           iri,
           _updateChartFromJson
    );
}

function _updateChartFromJson(response) {
    removeAllNodesFromChart();
    $.each(response.results.bindings, function(index, binding){
      values = _valuesOfSparqlBinding(binding);
      //Add owned always
      addNodeToChart(values.owned, values.ownedlabel, values.owner, 'owns');
      //Add owner if not there
      addNodeToChartIfNotThere(values.owner, values.ownerlabel, '', '');
    });
    updateChart();
}

//TODO: Wrap this functionality as an object http://www.phpied.com/3-ways-to-define-a-javascript-class/
var tbl;
var chart;
var clickHandler = function( id ){};//Dummy click-handler
function initChart() {
    //Initialize tbl (internal data table drawn on the chart) and chart
    tbl = new google.visualization.DataTable();
    tbl.addColumn('string', 'UrlAndLabel');
    tbl.addColumn('string', 'ParentUrl');
    tbl.addColumn('string', 'ToolTip');//Not used but specified by orgchart
    chart = new google.visualization.OrgChart(document.getElementById('chartPanel'));//TODO: replace chart_panel by parameter
    //Get a call to selectHandler() when chart is clicked
    google.visualization.events.addListener(chart, 'select', selectHandler);
}
function setClickHandler( callback ){
  clickHandler = callback;
}
function selectHandler() {
  var rowIndex = chart.getSelection()[0].row;//This may work badly if more than one node is selected
  var rowId = tbl.getValue(rowIndex, 0);
  clickHandler( rowId );
}
function updateChart() {
    chart.draw(tbl, {allowHtml:true, size:'large'});
}
function addNodeToChartIfNotThere( id, label, parentId, relation) {
  if ($.inArray( id, tbl.getDistinctValues(0)) === -1) {
    addNodeToChart( id, label, parentId, relation);
  }
}
function addNodeToChart( id, label, parentId, _relation) {
  tbl.addRow(
    [ { v: id, //v is the URL that child nodes can point to
        f: '
' + label + '
'},
        parentId,
        ""//No tooltip
    ]);
}
function removeAllNodesFromChart() {
  tbl.removeRows(0, tbl.getNumberOfRows());
}
<commit_msg>Optimize query For #28-gae-with-triple-store<commit_after>google.load('visualization', '1', {packages:['orgchart']});
google.setOnLoadCallback( function() {
    $( document ).ready( function() {
        initChart();
        setClickHandler(_updateFromIri);
        $( document ).on( 'updateFromIri', _updateChartFromIri);
        _updateFromIri( "http://dot.rural/sepake/UKEOFOrganisation#Scottish%20Environment%20Protection%20Agency" );
    });
});

function _updateFromIri(iri) {
    $( document ).trigger( 'updateFromIri', iri );
  }

function _updateChartFromIri(event, iri) {
    sparql("ownerchart",
            [
            "SELECT ?owner ?ownerlabel ?owned ?ownedlabel WHERE {",
            "  {",
            "    BIND (<--IRI--> AS ?owner) .",
            "    {?owner rdfs:label ?ownerlabel} .",
            "    {?owner <owns> ?owned} .",
            "    {?owned rdfs:label ?ownedlabel} .",
            "  } UNION {",
            "    BIND (<--IRI--> AS ?focus) .",
            "    {?owner <owns> ?focus} .",
            "    {?owner <owns> ?owned} .",
            "    {?owner rdfs:label ?ownerlabel} .",
            "    {?owned rdfs:label ?ownedlabel} .",
            "  }",
            "}",
            "ORDER BY ?ownerlabel ?ownedlabel",
            //TODO Add paging
           ],
           iri,
           _updateChartFromJson
    );
}

function _updateChartFromJson(response) {
    removeAllNodesFromChart();
    $.each(response.results.bindings, function(index, binding){
      values = _valuesOfSparqlBinding(binding);
      //Add owned always
      addNodeToChart(values.owned, values.ownedlabel, values.owner, 'owns');
      //Add owner if not there
      addNodeToChartIfNotThere(values.owner, values.ownerlabel, '', '');
    });
    updateChart();
}

//TODO: Wrap this functionality as an object http://www.phpied.com/3-ways-to-define-a-javascript-class/
var tbl;
var chart;
var clickHandler = function( id ){};//Dummy click-handler
function initChart() {
    //Initialize tbl (internal data table drawn on the chart) and chart
    tbl = new google.visualization.DataTable();
    tbl.addColumn('string', 'UrlAndLabel');
    tbl.addColumn('string', 'ParentUrl');
    tbl.addColumn('string', 'ToolTip');//Not used but specified by orgchart
    chart = new google.visualization.OrgChart(document.getElementById('chartPanel'));//TODO: replace chart_panel by parameter
    //Get a call to selectHandler() when chart is clicked
    google.visualization.events.addListener(chart, 'select', selectHandler);
}
function setClickHandler( callback ){
  clickHandler = callback;
}
function selectHandler() {
  var rowIndex = chart.getSelection()[0].row;//This may work badly if more than one node is selected
  var rowId = tbl.getValue(rowIndex, 0);
  clickHandler( rowId );
}
function updateChart() {
    chart.draw(tbl, {allowHtml:true, size:'large'});
}
function addNodeToChartIfNotThere( id, label, parentId, relation) {
  if ($.inArray( id, tbl.getDistinctValues(0)) === -1) {
    addNodeToChart( id, label, parentId, relation);
  }
}
function addNodeToChart( id, label, parentId, _relation) {
  tbl.addRow(
    [ { v: id, //v is the URL that child nodes can point to
        f: '
' + label + '
'},
        parentId,
        ""//No tooltip
    ]);
}
function removeAllNodesFromChart() {
  tbl.removeRows(0, tbl.getNumberOfRows());
}
<|endoftext|>


<commit_before>'use strict';

var Backbone = require("backbone");
require(['lodash'], function(_) {});

var multiplication = {
  name: 'multiplication',
  sign: '*',
  apply(inputs){
    var product = _.reduce(inputs, function(product, n) { return product * n; })
    return product;
  }
}

var addition = {
  name: 'addition',
  sign: '+',
  apply(inputs){
    var sum = _.reduce(inputs, function(sum, n) { return sum + n; });
    return sum;
  }
}

var efunctions = {
  'multiplication': multiplication,
  'addition': addition
}

class Enode extends Backbone.Model{
  defaults(){
    return {
      foo: 'sillybar'
    }
  }
  setup(){
  }
  initialize(attributes){
    this.id = attributes.pid;
    this.inputEdges = [];
    this.outputEdges = [];

    //if (this.get('nodeType') === 'function'){ MakeFunction(this) }
    //if (this.get('nodeType') === 'estimate'){ MakeEstimate(this) }
    //if (this.get('nodeType') === 'dependent'){ MakeDependent(this) }
    this.setup()
  }
  inputValues(){
    return _.map(this.inputs(), function(i){ return i.value})
  }
  outputs(){
    return _.map(this.outputEdges, function(e) {return e.outputNode})
  }
  allOutputs(){
    var outputs = this.outputs()
    furtherOutputs = _.map(outputs, function(e){return e.allOutputs()})
    return _.flatten([outputs, furtherOutputs])
  }
  inputs(){
    return _.map(this.inputEdges, function(e) {return e.inputNode})
  }
  addInputEdge(inputEdge){
    this.inputEdges.push(inputEdge)
  }
  addOutputEdge(outputEdge){
    this.outputEdges.push(outputEdge)
  }
  toString(indent){
    //indent = indent || 0
    //var pid = this.get('pid')
    //var nodeType = this.get('nodeType')
    //var outputs = _.map(this.outputs(), function(e){return e.toString(indent + 1)})
    //var out_s = ""
    //if (outputs.length > 0){ //var out_s = ' outputs => \n' + outputs.joint('\n')
    //}
    //sstring = (Array(indent*3).join('.')) + "([" + pid + nodeType + "]" + out_s + ")"
    return 'test'
  }
  toCytoscape() {
    var e = {}
    e.nodeId = this.id
    e.nodeType = this.attributes.nodeType
    _.merge(e, this.attributes)
    e.id = "n" + this.id // Nodes need letters for cytoscape
    e.name = this.toCytoscapeName()
    return {data: e};
  }
}

class EstimateNode extends Enode{
  ttype(){
    return 'estimate'
  }
  toCytoscapeName(){
    return this.attributes.name
  }
}

  //node.value = null
class DependentNode extends Enode{
  propogate(){
    this.outputs().forEach( e => console.log(e.id) )
  }
  updateValue(n){
    this.value = n;
    this.propogate()
  }
  toCytoscapeName(){
    return this.attributes.name
  }
}

class FunctionNode extends Enode{
  defaults(){
    return {
      "functionType": 'addition'
    }
  }
  efunction(){
    var functionType = this.get('functionType')
    return efunctions[functionType]
  }
  dependent(){
    return this.outputs()[0]
  }
  run(){
    result = this._run_math()
    this.dependent().updateValue(result)
  }
  run_math(){
    inputValues = this.inputValues()
    return this.efunction().apply(inputValues)
  }
  toCytoscapeName(){
    return this.efunction().sign
  }
  setup(){
    //if (this.get('outputIds')){
    //var inp = this.id
    //var out = this.get('outputIds')
    //var foo = this.collection.graph.edges.add({0:inp, 1:out})
  }
}

var NodeCollection = Backbone.Collection.extend({
    model: function(attrs, options) {
      switch (attrs.nodeType){
        case 'estimate':
          return new EstimateNode(attrs, options)
        case 'dependent':
          return new DependentNode(attrs, options)
        case 'function':
          return new FunctionNode(attrs, options)
        default:
          return new Enode(attrs, options)
      }
    },
    url: '/foo/bar',
    initialize(collection, graph){
      this.graph = graph;
    },
    toCytoscape() {
      var nodes = _.map(this.models, function(d){
        return d.toCytoscape();
      });
      return nodes;
    }
});

module.exports = NodeCollection;
<commit_msg>fixed var<commit_after>'use strict';

var Backbone = require("backbone");
require(['lodash'], function(_) {});

var multiplication = {
  name: 'multiplication',
  sign: '*',
  apply(inputs){
    var product = _.reduce(inputs, function(product, n) { return product * n; })
    return product;
  }
}

var addition = {
  name: 'addition',
  sign: '+',
  apply(inputs){
    var sum = _.reduce(inputs, function(sum, n) { return sum + n; });
    return sum;
  }
}

var efunctions = {
  'multiplication': multiplication,
  'addition': addition
}

class Enode extends Backbone.Model{
  defaults(){
    return {
      foo: 'sillybar'
    }
  }
  setup(){
  }
  initialize(attributes){
    this.id = attributes.pid;
    this.inputEdges = [];
    this.outputEdges = [];

    //if (this.get('nodeType') === 'function'){ MakeFunction(this) }
    //if (this.get('nodeType') === 'estimate'){ MakeEstimate(this) }
    //if (this.get('nodeType') === 'dependent'){ MakeDependent(this) }
    this.setup()
  }
  inputValues(){
    return _.map(this.inputs(), function(i){ return i.value})
  }
  outputs(){
    return _.map(this.outputEdges, function(e) {return e.outputNode})
  }
  allOutputs(){
    var outputs = this.outputs()
    var furtherOutputs = _.map(outputs, function(e){return e.allOutputs()})
    return _.flatten([outputs, furtherOutputs])
  }
  inputs(){
    return _.map(this.inputEdges, function(e) {return e.inputNode})
  }
  addInputEdge(inputEdge){
    this.inputEdges.push(inputEdge)
  }
  addOutputEdge(outputEdge){
    this.outputEdges.push(outputEdge)
  }
  toString(indent){
    //indent = indent || 0
    //var pid = this.get('pid')
    //var nodeType = this.get('nodeType')
    //var outputs = _.map(this.outputs(), function(e){return e.toString(indent + 1)})
    //var out_s = ""
    //if (outputs.length > 0){ //var out_s = ' outputs => \n' + outputs.joint('\n')
    //}
    //sstring = (Array(indent*3).join('.')) + "([" + pid + nodeType + "]" + out_s + ")"
    return 'test'
  }
  toCytoscape() {
    var e = {}
    e.nodeId = this.id
    e.nodeType = this.attributes.nodeType
    _.merge(e, this.attributes)
    e.id = "n" + this.id // Nodes need letters for cytoscape
    e.name = this.toCytoscapeName()
    return {data: e};
  }
}

class EstimateNode extends Enode{
  ttype(){
    return 'estimate'
  }
  toCytoscapeName(){
    return this.attributes.name
  }
}

  //node.value = null
class DependentNode extends Enode{
  propogate(){
    this.outputs().forEach( e => console.log(e.id) )
  }
  updateValue(n){
    this.value = n;
    this.propogate()
  }
  toCytoscapeName(){
    return this.attributes.name
  }
}

class FunctionNode extends Enode{
  defaults(){
    return {
      "functionType": 'addition'
    }
  }
  efunction(){
    var functionType = this.get('functionType')
    return efunctions[functionType]
  }
  dependent(){
    return this.outputs()[0]
  }
  run(){
    result = this._run_math()
    this.dependent().updateValue(result)
  }
  run_math(){
    inputValues = this.inputValues()
    return this.efunction().apply(inputValues)
  }
  toCytoscapeName(){
    return this.efunction().sign
  }
  setup(){
    //if (this.get('outputIds')){
    //var inp = this.id
    //var out = this.get('outputIds')
    //var foo = this.collection.graph.edges.add({0:inp, 1:out})
  }
}

var NodeCollection = Backbone.Collection.extend({
    model: function(attrs, options) {
      switch (attrs.nodeType){
        case 'estimate':
          return new EstimateNode(attrs, options)
        case 'dependent':
          return new DependentNode(attrs, options)
        case 'function':
          return new FunctionNode(attrs, options)
        default:
          return new Enode(attrs, options)
      }
    },
    url: '/foo/bar',
    initialize(collection, graph){
      this.graph = graph;
    },
    toCytoscape() {
      var nodes = _.map(this.models, function(d){
        return d.toCytoscape();
      });
      return nodes;
    }
});

module.exports = NodeCollection;
<|endoftext|>


<commit_before>import React from 'react';
import Arena from './Arena';
import PlayerTank from './PlayerTank';
import EnemyTank from './EnemyTank';
import { colors } from '../../simulation/constants';

class BattleScene extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      characters: [],
    };

    this.characterId = props.characterId;
    this.role = props.role;
    this.playerId = props.playerId
    this.socket = props.socket;
    this.socket.emit('requestCharacters');
    this.socket.on('shotFired', projectileData => {
      const projectile = document.createElement('a-entity');
      projectile.setAttribute('mixin', 'projectile');
      projectile.setAttribute('position', projectileData.position);
      projectile.setAttribute('velocity', projectileData.velocity);
      document.querySelector('#scene').appendChild(projectile);
    });
    this.socket.on('characterHit', hitData => {
      console.log('Someone was hit!', hitData);
      // TODO: Update health bars
    });
    this.socket.on('characterDestroyed', hitData => {
      // TODO: Update lives ui
      // TODO: Render death and respawn
      if(hitData.characterId === this.characterId) {
        console.log('You were destroyed!');
      } else {
        console.log(hitData.characterId, 'was destroyed!');
      }
    });
  }

  renderCharacters () {
    this.characters = [];
    for (var characterId in this.props.characters) {
      this.characters.push(this.props.characters[characterId]);
    }
    return this.characters.map(character => {
      const position = [
        character.position.x,
        character.position.y, // used to be hard coded to TANK_RADIUS
        character.position.z
      ].join(' ');

      if (character.characterId === this.characterId) {
        return (
          <PlayerTank key={character.characterId}
          position={position}
          material={`color: ${colors[character.characterId]}`}
          role={this.role}
          characterId={character.characterId}/>
        )
      } else {
        return (
          <EnemyTank key={character.characterId}
          position={position}
          material={`color: ${colors[character.characterId]}`}
          characterId={character.characterId}/>
        )
      }
    });
  }

  render () {
    return (
      <a-entity>

        <a-sky color='blue' />

        <Arena wallHeight={8}>
          {this.renderCharacters.call(this)}
        </Arena>

      </a-entity>
    )
  }
}

module.exports = BattleScene;
<commit_msg>Add comments to battlescene with potential death-handling code<commit_after>import React from 'react';
import Arena from './Arena';
import PlayerTank from './PlayerTank';
import EnemyTank from './EnemyTank';
import { colors } from '../../simulation/constants';

class BattleScene extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      characters: [],
    };

    this.characterId = props.characterId;
    this.role = props.role;
    this.playerId = props.playerId
    this.socket = props.socket;

    this.socket.emit('requestCharacters');

    this.socket.on('shotFired', projectileData => {
      const projectile = document.createElement('a-entity');
      projectile.setAttribute('mixin', 'projectile');
      projectile.setAttribute('position', projectileData.position);
      projectile.setAttribute('velocity', projectileData.velocity);
      document.querySelector('#scene').appendChild(projectile);
    });

    this.socket.on('characterHit', hitData => {
      console.log('Someone was hit!', hitData);
      // TODO: Update health bars
    });

    this.socket.on('characterDestroyed', hitData => {
      const deathEvent = new CustomEvent('characterDestroyed', {
       characterId: hitData.characterId
      });
      window.dispatchEvent(deathEvent);
      // TODO: Update lives ui
      // TODO: Render death and respawn
      if(hitData.characterId === this.characterId) {
        console.log('You were destroyed!');
        // const camera = document.querySelector('#camera');
        // const blackPlane = document.createElement('a-plane');
        // blackPlane.setAttribute('position', '0 0 -0.2');
        // camera.appendChild(blackPlane);
      } else {
        console.log(hitData.characterId, 'was destroyed!');
        // Or trigger event on the scene which will be picked up by aframe components?
      }
    });
  }

  renderCharacters () {
    this.characters = [];
    for (var characterId in this.props.characters) {
      this.characters.push(this.props.characters[characterId]);
    }
    return this.characters.map(character => {
      const position = [
        character.position.x,
        character.position.y, // used to be hard coded to TANK_RADIUS
        character.position.z
      ].join(' ');

      if (character.characterId === this.characterId) {
        return (
          <PlayerTank key={character.characterId}
          position={position}
          material={`color: ${colors[character.characterId]}`}
          role={this.role}
          characterId={character.characterId}/>
        )
      } else {
        return (
          <EnemyTank key={character.characterId}
          position={position}
          material={`color: ${colors[character.characterId]}`}
          characterId={character.characterId}/>
        )
      }
    });
  }

  render () {
    return (
      <a-entity>

        <a-sky color='blue' />

        <Arena wallHeight={8}>
          {this.renderCharacters.call(this)}
        </Arena>

      </a-entity>
    )
  }
}

module.exports = BattleScene;
<|endoftext|>


<commit_before>"use strict";

function soma(numeroA, numeroB){
    return numeroA + numeroB;
}
function subtrair(numeroA, numeroB){
    return numeroA - numeroB;
}
function multiplicar(numeroA, numeroB){
    return numeroA * numeroB;
}
function dividir(numeroA, numeroB){
    return numeroA / numeroB;
}

function ativarBotao(){

}

window.onload = function(){
    var botaoSOMAR = document.getElementById("somar"),
        botaoSUBTRAIR = document.getElementById("subtrair"),
        botaoMULTIPLICAR = document.getElementById("multiplicar"),
        botaoDIVIDIR = document.getElementById("dividir");

    var campoA = document.getElementById("numeroA"),
        campoA = document.getElementById("numeroA");

    botaoSOMAR.addEventListener("click",function(){
        var numeroA = Number(campoA.value),
            numeroB = Number(campoB.value);
        document.getElementById("resultado").innerHTML = soma(numeroA,numeroB;
    });

};

<commit_msg>Para unificar o metodo do botão<commit_after>"use strict";

function soma(numeroA, numeroB) {
    return numeroA + numeroB;
}
function subtrair(numeroA, numeroB) {
    return numeroA - numeroB;
}
function multiplicar(numeroA, numeroB) {
    return numeroA * numeroB;
}
function dividir(numeroA, numeroB) {
    return numeroA / numeroB;
}

function ativarBotao($botao,$metodo) {
    $botao.addEventListener("click", function () {
        var numeroA = Number(campoA.value),
            numeroB = Number(campoB.value);

        document.getElementById("resultado").innerHTML = $metodo(numeroA, numeroB);
    });

}

window.onload = function () {
    var botaoSOMAR = document.getElementById("somar"),
        botaoSUBTRAIR = document.getElementById("subtrair"),
        botaoMULTIPLICAR = document.getElementById("multiplicar"),
        botaoDIVIDIR = document.getElementById("dividir");

    var campoA = document.getElementById("campoA"),
        campoB = document.getElementById("campoB");

    ativarBotao(botaoSOMAR,soma);
    ativarBotao(botaoSUBTRAIR,subtrair);
    ativarBotao(botaoMULTIPLICAR,multiplicar);
    ativarBotao(botaoDIVIDIR,dividir);
};

<|endoftext|>


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

/*global angular */
'use strict';

function PlatformService($q, packaging) {

  function getFirstDayOfWeek(){
    return $q(function(resolve, reject) {
      if (packaging.endsWith('cordova') && navigator && navigator.globalization){
        navigator.globalization.getFirstDayOfWeek(function(fdow){
          if (fdow === 1){
            resolve(0);
          }else{
            resolve(1);
          }
        }, function(error){
          reject(error);
        });
      }else{
        // Our best bet is to guess the start day from the time format
        if (getLocaleBasedTimeFormat() === '12h'){
          resolve(0);
        }else{
          resolve(1);
        }
      }
    });
  }

  function getTimeFormat(){
    return $q(function(resolve, reject) {
      if (packaging.endsWith('cordova') && navigator && navigator.globalization){
        navigator.globalization.getFirstDayOfWeek(function(format){
          resolve(format);
        }, function(error){
          reject(error);
        });
      }else{
        // Our best bet is to use toLocaleTimeString. It does not work in Chrome, but what can you do
        resolve(getLocaleBasedTimeFormat());
      }
    });
  }

  function getLocaleBasedTimeFormat() {
    // Our best bet is to use toLocaleTimeString. It does not work in Chrome, but what can you do
    var localeTimeString = new Date().toLocaleTimeString();
    if (localeTimeString.indexOf('AM') !== -1 || localeTimeString.indexOf('PM') !== -1){
      return '12h';
    }else{
      return '24h';
    }
  }

  function setInboxId(inboxId){
    return $q(function(resolve, reject) {
      if (window.AppGroupsUserDefaults){
        var options = {
              key: "inboxId",
              value: inboxId,
              suite: "group.org.extendedmind"};
        window.AppGroupsUserDefaults.save(options, function(){
          resolve();
        }, function(){
          reject('error saving');
        });
      }else{
        reject('invalid configuration');
      }
    });
  }

  function openLinkExternal(url){
    return $q(function(resolve, reject) {
      if (packaging.endsWith('cordova') && cordova && cordova.InAppBrowser){
        resolve(cordova.InAppBrowser.open(url, '_system', 'location=yes'));
      }else if (packaging.endsWith('electron') && typeof require !== 'undefined' && require){
        resolve(require('remote').require('shell').openExternal(url));
      }else{
        reject('invalid configuration');
      }
    });
  }

  function isSupported(name){
    if (name){
      switch (name) {
        case 'timeFormat':
        return true;

        case 'firstDayOfWeek':
        return true;

        case 'keyboardShortcuts':
        return !packaging.endsWith('cordova');

        case 'setInboxId':
        return packaging === 'ios-cordova';

        case 'openLinkExternal':
        return packaging.endsWith('cordova') || packaging.endsWith('electron');

        case 'immediateSearch':
        return !packaging.endsWith('cordova');

        case 'extendedLogin':
        return packaging.endsWith('cordova') || packaging.endsWith('electron');
      }
    }
  }

  return {
    isSupported: isSupported,
    getFeatureValue: function(featureName) {
      return $q(function(resolve, reject) {
        if (isSupported(featureName)){
          switch (featureName) {
            case 'timeFormat':
            resolve(getTimeFormat());
            break;
            case 'firstDayOfWeek':
            resolve(getFirstDayOfWeek());
            break;
          }
        }else{
          reject('not supported');
        }
      });
    },
    setFeatureValue: function(featureName, featureValue){
      return $q(function(resolve, reject) {
        if (isSupported(featureName)){
          switch (featureName) {
            case 'setInboxId':
            resolve(setInboxId(featureValue));
            break;
          }
        }else{
          reject('not supported');
        }
      });
    },
    doAction: function(actionName, actionValue){
      return $q(function(resolve, reject) {
        if (isSupported(actionName)){
          switch (actionName) {
            case 'openLinkExternal':
            resolve(openLinkExternal(actionValue));
            break;
          }
        }else{
          reject('not supported');
        }
      });
    }
  };
}
PlatformService['$inject'] = ['$q', 'packaging'];
angular.module('em.base').factory('PlatformService', PlatformService);
<commit_msg>Fixed opening external link on desktop. Bug caused by API change in Electron.<commit_after>/* Copyright 2013-2016 Extended Mind Technologies Oy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*global angular */
'use strict';

function PlatformService($q, packaging) {

  function getFirstDayOfWeek(){
    return $q(function(resolve, reject) {
      if (packaging.endsWith('cordova') && navigator && navigator.globalization){
        navigator.globalization.getFirstDayOfWeek(function(fdow){
          if (fdow === 1){
            resolve(0);
          }else{
            resolve(1);
          }
        }, function(error){
          reject(error);
        });
      }else{
        // Our best bet is to guess the start day from the time format
        if (getLocaleBasedTimeFormat() === '12h'){
          resolve(0);
        }else{
          resolve(1);
        }
      }
    });
  }

  function getTimeFormat(){
    return $q(function(resolve, reject) {
      if (packaging.endsWith('cordova') && navigator && navigator.globalization){
        navigator.globalization.getFirstDayOfWeek(function(format){
          resolve(format);
        }, function(error){
          reject(error);
        });
      }else{
        // Our best bet is to use toLocaleTimeString. It does not work in Chrome, but what can you do
        resolve(getLocaleBasedTimeFormat());
      }
    });
  }

  function getLocaleBasedTimeFormat() {
    // Our best bet is to use toLocaleTimeString. It does not work in Chrome, but what can you do
    var localeTimeString = new Date().toLocaleTimeString();
    if (localeTimeString.indexOf('AM') !== -1 || localeTimeString.indexOf('PM') !== -1){
      return '12h';
    }else{
      return '24h';
    }
  }

  function setInboxId(inboxId){
    return $q(function(resolve, reject) {
      if (window.AppGroupsUserDefaults){
        var options = {
              key: "inboxId",
              value: inboxId,
              suite: "group.org.extendedmind"};
        window.AppGroupsUserDefaults.save(options, function(){
          resolve();
        }, function(){
          reject('error saving');
        });
      }else{
        reject('invalid configuration');
      }
    });
  }

  function openLinkExternal(url){
    return $q(function(resolve, reject) {
      if (packaging.endsWith('cordova') && cordova && cordova.InAppBrowser){
        resolve(cordova.InAppBrowser.open(url, '_system', 'location=yes'));
      }else if (packaging.endsWith('electron') && typeof require !== 'undefined' && require){
        resolve(require('electron').shell.openExternal(url));
      }else{
        reject('invalid configuration');
      }
    });
  }

  function isSupported(name){
    if (name){
      switch (name) {
        case 'timeFormat':
        return true;

        case 'firstDayOfWeek':
        return true;

        case 'keyboardShortcuts':
        return !packaging.endsWith('cordova');

        case 'setInboxId':
        return packaging === 'ios-cordova';

        case 'openLinkExternal':
        return packaging.endsWith('cordova') || packaging.endsWith('electron');

        case 'immediateSearch':
        return !packaging.endsWith('cordova');

        case 'extendedLogin':
        return packaging.endsWith('cordova') || packaging.endsWith('electron');
      }
    }
  }

  return {
    isSupported: isSupported,
    getFeatureValue: function(featureName) {
      return $q(function(resolve, reject) {
        if (isSupported(featureName)){
          switch (featureName) {
            case 'timeFormat':
            resolve(getTimeFormat());
            break;
            case 'firstDayOfWeek':
            resolve(getFirstDayOfWeek());
            break;
          }
        }else{
          reject('not supported');
        }
      });
    },
    setFeatureValue: function(featureName, featureValue){
      return $q(function(resolve, reject) {
        if (isSupported(featureName)){
          switch (featureName) {
            case 'setInboxId':
            resolve(setInboxId(featureValue));
            break;
          }
        }else{
          reject('not supported');
        }
      });
    },
    doAction: function(actionName, actionValue){
      return $q(function(resolve, reject) {
        if (isSupported(actionName)){
          switch (actionName) {
            case 'openLinkExternal':
            resolve(openLinkExternal(actionValue));
            break;
          }
        }else{
          reject('not supported');
        }
      });
    }
  };
}
PlatformService['$inject'] = ['$q', 'packaging'];
angular.module('em.base').factory('PlatformService', PlatformService);
<|endoftext|>


<commit_before>var watch = require('watch');
var fs = require('fs');
var directoryObj = loadTimesaver() || {};
watchSuperDirectory('/Users/nathanaelsmith/PhpstormProjects');
var count = 0;

var excluded = /.idea/g;
var excluded2 = /.git/g;

function loadTimesaver() {

	try {
		var data = fs.readFileSync('/tmp/timesaver.json');
	} catch (e) {
		return false;
	}
	try {
		parsedData = JSON.parse(data);
		return parsedData;
	} catch(e) {
		return false;
	}

}

function watchSuperDirectory(dir) {
	watch.watchTree(dir, function (f, curr, prev) {
		if (typeof f === 'object' && curr === null && prev === null) {
			console.log('Listening on ' + dir);
		} else if (excluded.test(f) || excluded2.test(f)) {
			return;
		} else if (prev === null) {
			//we added a new file
		} else {
			handleTimePassed(f, curr, prev);
		}

	});

}

function handleTimePassed(f, curr, prev) {
	var site =  f.split('/')[4];
	console.log('You\'re currently in ' + site);

	console.log('File changed: ' + f);

	if ( directoryObj[site] === undefined){
		directoryObj[site] = {};
	}
	var currentObj = directoryObj[site];

	count = currentObj.count || 0;

	pastCountKey = count - 1;

	pastTime = currentObj['mtime' + pastCountKey];

	pastTime = new Date(pastTime);

	currentObj['mtime' + count] = new Date();

	difference = ((new Date()) - pastTime) / 60000;

	if (!currentObj.count) {
		currentObj.count = 0;
	}

	currentObj.count++;

	addTototal(currentObj, difference);

}

function addTototal(currentObj, difference) {
	if (currentObj.timeSpent === undefined) {
		currentObj.timeSpent = 0;
	}
	if (difference < 10) {
		console.log('Change made within interval. Time will be saved');
		currentObj.timeSpent += difference;
		console.log('Total time spent ' + currentObj.timeSpent);

		fs.writeFile('/tmp/timesaver.json', JSON.stringify(directoryObj), function(err) {
			if (err) throw err;
			console.info('Writing out');
			console.log('===================');
		});

	} else {
		console.log('You haven\'t been working here for a while');
		return;
	}
}<commit_msg>only track current days time<commit_after>var watch = require('watch');
var fs = require('fs');
var directoryObj = loadTimesaver() || {};
watchSuperDirectory('/Users/nathanaelsmith/PhpstormProjects');
var count = 0;

var excluded = /.idea/g;
var excluded2 = /.git/g;

function loadTimesaver() {

	try {
		var data = fs.readFileSync('/tmp/timesaver.json');
	} catch (e) {
		return false;
	}
	try {
		parsedData = JSON.parse(data);
		if (parsedData.currentDay === (new Date()).getDay()) {
			return parsedData
		} else {
			return false;
		}
	} catch(e) {
		return false;
	}

}

function watchSuperDirectory(dir) {
	watch.watchTree(dir, function (f, curr, prev) {
		if (typeof f === 'object' && curr === null && prev === null) {
			console.log('Listening on ' + dir);
		} else if (excluded.test(f) || excluded2.test(f)) {
			return;
		} else if (prev === null) {
			//we added a new file
		} else {
			handleTimePassed(f, curr, prev);
		}

	});

}

function handleTimePassed(f, curr, prev) {
	var site =  f.split('/')[4];
	console.log('You\'re currently in ' + site);

	console.log('File changed: ' + f);

	directoryObj.currentDay = (new Date()).getDay();

	if ( directoryObj[site] === undefined){
		directoryObj[site] = {};
	}
	var currentObj = directoryObj[site];

	count = currentObj.count || 0;

	pastCountKey = count - 1;

	pastTime = currentObj['mtime' + pastCountKey];

	pastTime = new Date(pastTime);

	currentObj['mtime' + count] = new Date();

	difference = ((new Date()) - pastTime) / 60000;

	if (!currentObj.count) {
		currentObj.count = 0;
	}

	currentObj.count++;

	addTototal(currentObj, difference);

}

function addTototal(currentObj, difference) {
	if (currentObj.timeSpent === undefined) {
		currentObj.timeSpent = 0;
	}
	if (difference < 10) {
		console.log('Change made within interval. Time will be saved');
		currentObj.timeSpent += difference;
		console.log('Total time spent ' + currentObj.timeSpent);

		fs.writeFile('/tmp/timesaver.json', JSON.stringify(directoryObj), function(err) {
			if (err) throw err;
			console.info('Writing out');
			console.log('===================');
		});

	} else {
		console.log('You haven\'t been working here for a while');
		return;
	}
}<|endoftext|>


<commit_before>const _ = require('lodash');
const j = require('../../lib/transform');
const crypto = require('crypto');

const Generator = require('../../lib/generator');
const OAUTH2_STRATEGY_MAPPINGS = {
  google: 'passport-google-oauth20',
  facebook: 'passport-facebook',
  github: 'passport-github'
};

module.exports = class AuthGenerator extends Generator {
  prompting() {
    this.checkPackage();

    const prompts = [{
      type: 'checkbox',
      name: 'strategies',
      message: 'What authentication providers do you want to use? Other PassportJS strategies not in this list can still be configured manually.',
      default: 'providers',
      choices: [{
        name: 'Username + Password (Local)',
        value: 'local'
      }, {
        name: 'Google',
        value: 'google'
      }, {
        name: 'Facebook',
        value: 'facebook'
      }, {
        name: 'GitHub',
        value: 'github'
      }]
    }, {
      name: 'entity',
      message: 'What is the name of the user (entity) service?',
      default: 'users'
    }];

    return this.prompt(prompts).then(props => {
      this.props = Object.assign(this.props, props);
    });
  }

  _transformCode(code) {
    const ast = j(code);
    const appDeclaration = ast.findDeclaration('app');
    const configureServices = ast.findConfigure('services');
    const requireCall = 'const authentication = require(\'./authentication\');';

    if (appDeclaration.length === 0) {
      throw new Error('Could not find \'app\' variable declaration in app.js to insert database configuration. Did you modify app.js?');
    }

    if (configureServices.length === 0) {
      throw new Error('Could not find .configure(services) call in app.js after which to insert database configuration. Did you modify app.js?');
    }

    appDeclaration.insertBefore(requireCall);
    configureServices.insertBefore('app.configure(authentication);');

    return ast.toSource();
  }

  _writeConfiguration(context) {
    const config = Object.assign({}, this.defaultConfig);

    config.authentication = {
      secret: crypto.randomBytes(256).toString('hex'),
      strategies: [ 'jwt' ],
      path: '/authentication',
      service: context.kebabEntity,
      jwt: {
        header: { type: 'access' },
        audience: 'https://yourdomain.com',
        subject: 'anonymous',
        issuer: 'feathers',
        algorithm: 'HS256',
        expiresIn: '1d'
      }
    };

    if (context.strategies.indexOf('local') !== -1) {
      config.authentication.strategies.push('local');
      config.authentication.local = {
        entity: 'user',
        usernameField: 'email',
        passwordField: 'password'
      };
    }

    let includesOAuth = false;

    context.strategies.forEach(strategy => {
      if (OAUTH2_STRATEGY_MAPPINGS[strategy]) {
        const strategyConfig = {
          clientID: `your ${strategy} client id`,
          clientSecret: `your ${strategy} client secret`,
          successRedirect: '/'
        };
        includesOAuth = true;

        if (strategy === 'facebook') {
          strategyConfig.scope = ['public_profile', 'email'];
          strategyConfig.profileFields = ['id', 'displayName', 'first_name', 'last_name', 'email', 'gender', 'profileUrl', 'birthday', 'picture', 'permissions'];
        }

        if (strategy === 'google') {
          strategyConfig.scope = ['profile openid email'];
        }

        config.authentication[strategy] = strategyConfig;
      }
    });

    if (includesOAuth) {
      config.authentication.cookie = {
        enabled: true,
        name: 'feathers-jwt',
        httpOnly: false,
        secure: false
      };
    }

    this.conflicter.force = true;
    this.fs.writeJSON(
      this.destinationPath('config', 'default.json'),
      config
    );
  }

  writing() {
    const dependencies = [
      'feathers-authentication',
      'feathers-authentication-hooks',
      'feathers-authentication-jwt'
    ];
    const context = Object.assign({
      kebabEntity: _.kebabCase(this.props.entity),
      camelEntity: _.camelCase(this.props.entity),
      oauthProviders: []
    }, this.props);

    // Set up strategies and add dependencies
    this.props.strategies.forEach(strategy => {
      const oauthProvider = OAUTH2_STRATEGY_MAPPINGS[strategy];

      if (oauthProvider) {
        dependencies.push('feathers-authentication-oauth2');
        dependencies.push(oauthProvider);
        context.oauthProviders.push({
          name: strategy,
          strategyName: `${_.upperFirst(strategy)}Strategy`,
          module: oauthProvider
        });
      } else {
        dependencies.push(`feathers-authentication-${strategy}`);
      }
    });

    // Create the users service
    this.composeWith(require.resolve('../service'), {
      props: {
        name: context.entity,
        path: `/${context.kebabEntity}`,
        authentication: context
      }
    });

    // If the file doesn't exist yet, add it to the app.js
    if (!this.fs.exists(this.destinationPath(this.libDirectory, 'authentication.js'))) {
      const appjs = this.destinationPath(this.libDirectory, 'app.js');

      this.conflicter.force = true;
      this.fs.write(appjs, this._transformCode(
        this.fs.read(appjs).toString()
      ));
    }

    this.fs.copyTpl(
      this.templatePath('authentication.js'),
      this.destinationPath(this.libDirectory, 'authentication.js'),
      context
    );

    this._writeConfiguration(context);
    this._packagerInstall(dependencies, {
      save: true
    });
  }
};
<commit_msg>Check local authentication by default (#245)<commit_after>const _ = require('lodash');
const j = require('../../lib/transform');
const crypto = require('crypto');

const Generator = require('../../lib/generator');
const OAUTH2_STRATEGY_MAPPINGS = {
  google: 'passport-google-oauth20',
  facebook: 'passport-facebook',
  github: 'passport-github'
};

module.exports = class AuthGenerator extends Generator {
  prompting() {
    this.checkPackage();

    const prompts = [{
      type: 'checkbox',
      name: 'strategies',
      message: 'What authentication providers do you want to use? Other PassportJS strategies not in this list can still be configured manually.',
      default: 'providers',
      choices: [{
        name: 'Username + Password (Local)',
        value: 'local',
        checked: true
      }, {
        name: 'Google',
        value: 'google'
      }, {
        name: 'Facebook',
        value: 'facebook'
      }, {
        name: 'GitHub',
        value: 'github'
      }]
    }, {
      name: 'entity',
      message: 'What is the name of the user (entity) service?',
      default: 'users'
    }];

    return this.prompt(prompts).then(props => {
      this.props = Object.assign(this.props, props);
    });
  }

  _transformCode(code) {
    const ast = j(code);
    const appDeclaration = ast.findDeclaration('app');
    const configureServices = ast.findConfigure('services');
    const requireCall = 'const authentication = require(\'./authentication\');';

    if (appDeclaration.length === 0) {
      throw new Error('Could not find \'app\' variable declaration in app.js to insert database configuration. Did you modify app.js?');
    }

    if (configureServices.length === 0) {
      throw new Error('Could not find .configure(services) call in app.js after which to insert database configuration. Did you modify app.js?');
    }

    appDeclaration.insertBefore(requireCall);
    configureServices.insertBefore('app.configure(authentication);');

    return ast.toSource();
  }

  _writeConfiguration(context) {
    const config = Object.assign({}, this.defaultConfig);

    config.authentication = {
      secret: crypto.randomBytes(256).toString('hex'),
      strategies: [ 'jwt' ],
      path: '/authentication',
      service: context.kebabEntity,
      jwt: {
        header: { type: 'access' },
        audience: 'https://yourdomain.com',
        subject: 'anonymous',
        issuer: 'feathers',
        algorithm: 'HS256',
        expiresIn: '1d'
      }
    };

    if (context.strategies.indexOf('local') !== -1) {
      config.authentication.strategies.push('local');
      config.authentication.local = {
        entity: 'user',
        usernameField: 'email',
        passwordField: 'password'
      };
    }

    let includesOAuth = false;

    context.strategies.forEach(strategy => {
      if (OAUTH2_STRATEGY_MAPPINGS[strategy]) {
        const strategyConfig = {
          clientID: `your ${strategy} client id`,
          clientSecret: `your ${strategy} client secret`,
          successRedirect: '/'
        };
        includesOAuth = true;

        if (strategy === 'facebook') {
          strategyConfig.scope = ['public_profile', 'email'];
          strategyConfig.profileFields = ['id', 'displayName', 'first_name', 'last_name', 'email', 'gender', 'profileUrl', 'birthday', 'picture', 'permissions'];
        }

        if (strategy === 'google') {
          strategyConfig.scope = ['profile openid email'];
        }

        config.authentication[strategy] = strategyConfig;
      }
    });

    if (includesOAuth) {
      config.authentication.cookie = {
        enabled: true,
        name: 'feathers-jwt',
        httpOnly: false,
        secure: false
      };
    }

    this.conflicter.force = true;
    this.fs.writeJSON(
      this.destinationPath('config', 'default.json'),
      config
    );
  }

  writing() {
    const dependencies = [
      'feathers-authentication',
      'feathers-authentication-hooks',
      'feathers-authentication-jwt'
    ];
    const context = Object.assign({
      kebabEntity: _.kebabCase(this.props.entity),
      camelEntity: _.camelCase(this.props.entity),
      oauthProviders: []
    }, this.props);

    // Set up strategies and add dependencies
    this.props.strategies.forEach(strategy => {
      const oauthProvider = OAUTH2_STRATEGY_MAPPINGS[strategy];

      if (oauthProvider) {
        dependencies.push('feathers-authentication-oauth2');
        dependencies.push(oauthProvider);
        context.oauthProviders.push({
          name: strategy,
          strategyName: `${_.upperFirst(strategy)}Strategy`,
          module: oauthProvider
        });
      } else {
        dependencies.push(`feathers-authentication-${strategy}`);
      }
    });

    // Create the users service
    this.composeWith(require.resolve('../service'), {
      props: {
        name: context.entity,
        path: `/${context.kebabEntity}`,
        authentication: context
      }
    });

    // If the file doesn't exist yet, add it to the app.js
    if (!this.fs.exists(this.destinationPath(this.libDirectory, 'authentication.js'))) {
      const appjs = this.destinationPath(this.libDirectory, 'app.js');

      this.conflicter.force = true;
      this.fs.write(appjs, this._transformCode(
        this.fs.read(appjs).toString()
      ));
    }

    this.fs.copyTpl(
      this.templatePath('authentication.js'),
      this.destinationPath(this.libDirectory, 'authentication.js'),
      context
    );

    this._writeConfiguration(context);
    this._packagerInstall(dependencies, {
      save: true
    });
  }
};
<|endoftext|>


<commit_before>import React from 'react';
import { Provider } from 'react-redux';
import { Router, Route, IndexRedirect } from 'react-router';
import { anchorate } from 'anchorate';
import { persistStore } from 'redux-persist';

import { requireAuthentication } from './shared/components/AuthenticatedComponent';

import appScreen from './screens/app';
import aboutScreen from './screens/app/screens/about';
import translateScreen from './screens/app/screens/translate';
import listsScreen from './screens/app/screens/lists';
import grammarScreen from './screens/app/screens/grammar';
import finishScreen from './screens/app/screens/finish';
import homeScreen from './screens/app/screens/home';
import loginScreen from './screens/app/screens/login';
import logoutScreen from './screens/app/screens/logout';
import playScreen from './screens/app/screens/play';
import selectScreen from './screens/app/screens/select';

function onUpdate() {
  anchorate(); // To have href's that can scroll to page sections
}

export default class AppProvider extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      rehydrated: false,
      persistor: null
    };
  }

  componentWillMount() {
    // Redux store purging logic (aka "has project.json version changed?")
    // For now, we let security reducer determine purging decision for all reducers
    this.setState({
      persistor: persistStore(this.props.store, { blacklist: [] }, (err, state) => {
        if (state.security.purgeNeeded) {
          this.state.persistor.purge().then(this.setState({ rehydrated: true }));
        } else {
          this.setState({ rehydrated: true });
        }
      }) });
  }

  render() {
    if (this.state.rehydrated) {
      return (<Provider store={this.props.store}>
        <Router onUpdate={onUpdate} history={this.props.history}>
          <Route path="/" component={appScreen}>
            <IndexRedirect to="home" />
            <Route path="login" component={loginScreen} />
            <Route path="logout" component={logoutScreen} />
            <Route path="play/:type" component={requireAuthentication(playScreen)} />
            <Route path="select/:type" component={requireAuthentication(selectScreen)} />
            <Route path="translate" component={requireAuthentication(translateScreen)} />
            <Route path="grammar" component={requireAuthentication(grammarScreen)} />
            {/* <Route path="lists" component={requireAuthentication(listsScreen)} />*/}
            <Route path="finish/:type" component={requireAuthentication(finishScreen)} />
            <Route path="home" component={requireAuthentication(homeScreen)} />
            <Route path="about" component={aboutScreen} />
          </Route>
        </Router>
      </Provider>);
    }
    return null;
  }
}
<commit_msg>fix purgeNeeded evaluation crash on first load<commit_after>import React from 'react';
import { Provider } from 'react-redux';
import { Router, Route, IndexRedirect } from 'react-router';
import { anchorate } from 'anchorate';
import { persistStore } from 'redux-persist';

import { requireAuthentication } from './shared/components/AuthenticatedComponent';

import appScreen from './screens/app';
import aboutScreen from './screens/app/screens/about';
import translateScreen from './screens/app/screens/translate';
import listsScreen from './screens/app/screens/lists';
import grammarScreen from './screens/app/screens/grammar';
import finishScreen from './screens/app/screens/finish';
import homeScreen from './screens/app/screens/home';
import loginScreen from './screens/app/screens/login';
import logoutScreen from './screens/app/screens/logout';
import playScreen from './screens/app/screens/play';
import selectScreen from './screens/app/screens/select';

function onUpdate() {
  anchorate(); // To have href's that can scroll to page sections
}

export default class AppProvider extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      rehydrated: false,
      persistor: null
    };
  }

  componentWillMount() {
    // Redux store purging logic (aka "has project.json version changed?")
    // For now, we let security reducer determine purging decision for all reducers
    this.setState({
      persistor: persistStore(this.props.store, { blacklist: [] }, (err, state) => {
        if (state.security && state.security.purgeNeeded) {
          this.state.persistor.purge().then(this.setState({ rehydrated: true }));
        } else {
          this.setState({ rehydrated: true });
        }
      }) });
  }

  render() {
    if (this.state.rehydrated) {
      return (<Provider store={this.props.store}>
        <Router onUpdate={onUpdate} history={this.props.history}>
          <Route path="/" component={appScreen}>
            <IndexRedirect to="home" />
            <Route path="login" component={loginScreen} />
            <Route path="logout" component={logoutScreen} />
            <Route path="play/:type" component={requireAuthentication(playScreen)} />
            <Route path="select/:type" component={requireAuthentication(selectScreen)} />
            <Route path="translate" component={requireAuthentication(translateScreen)} />
            <Route path="grammar" component={requireAuthentication(grammarScreen)} />
            {/* <Route path="lists" component={requireAuthentication(listsScreen)} />*/}
            <Route path="finish/:type" component={requireAuthentication(finishScreen)} />
            <Route path="home" component={requireAuthentication(homeScreen)} />
            <Route path="about" component={aboutScreen} />
          </Route>
        </Router>
      </Provider>);
    }
    return null;
  }
}
<|endoftext|>


<commit_before>import Constants from '../constants/constants';

const HeightSource = {
  post: function (data) {
    return $.ajax({
        method: "POST",
        url: Constants["SERVER_URL"] + "height",
        data: { height: data.height },
        'beforeSend': function(xhr) {
            if (localStorage.getItem('userToken')) {
              xhr.setRequestHeader('Authorization',
                    'Bearer ' + localStorage.getItem('userToken'));
            }
        },
        crossDomain: true
    })
  }
};

export default HeightSource;
<commit_msg>[client] Fixed a typo<commit_after>import Constants from '../constants/constants';

const HeightSource = {
  post: function (data) {
    return $.ajax({
        method: "POST",
        url: Constants["SERVER_URL"] + "/height",
        data: { height: data.height },
        'beforeSend': function(xhr) {
            if (localStorage.getItem('userToken')) {
              xhr.setRequestHeader('Authorization',
                    'Bearer ' + localStorage.getItem('userToken'));
            }
        },
        crossDomain: true
    })
  }
};

export default HeightSource;
<|endoftext|>