<commit_before>//
// manage layers, its order and when should be shown or hiden
//
cdb.admin.LayersPanel = cdb.ui.common.TabPane.extend({

    className: 'table_panel',
    animation_time: 300,

    initialize: function() {
        cdb.ui.common.TabPane.prototype.initialize.call(this);

        this.map = this.options.map;
        this.add_related_model(this.map);

        this.map.layers.bind('add', this._addLayer, this);
        this.map.layers.bind('reset', this._resetLayers, this);
        this._addLayers(this.map.layers);

        this.isOpen = true;
        this.activeWorkView = 'table';

        /* test */
        _.bindAll(this, 'manageLayers');
    },

    _resetLayers: function() {
        //clean all views
        this.removeTabs();
        this._addLayers(this.map.layers);
    },

    _addLayers: function(layers) {
        var self = this;
        layers.each(function(l) {
            self._addLayer(l)
        });
    },

    _addLayer: function(layer) {
        var self = this;
        if (layer.get('type') == 'CartoDB') {
            var addIt = function(t) {
                var v = new cdb.admin.LayerPanelView({
                    model: layer,
                    sqlView: self.options.sqlView,
                    table: t,
                    map: self.map,
                    user: self.options.user,
                    globalError: self.options.globalError
                });

                v.bind('toggle', self.toggle, self);
                v.bind('switchTo', self.switchTo, self);
                self.addTab(layer.cid, v);
                v.setActiveWorkView(self.activeWorkView);
                self.trigger('switch', v);

                self.switchTo(v);
                self.bindSort();
            };

            if (layer.get('table_name')) {
                var table = new cdb.admin.CartoDBTableMetadata({
                    id: layer.get('table_name')
                });
                table.fetch({
                    success: function() {
                        addIt(table)
                    }
                });
            } else {
                addIt(this.options.table);
            }

        }
    },

    show: function(modName) {
        var width = 600,
            event_name = 'showPanel';

        // Select the tab

        var mod = this.getActivePane()
        mod.tabs.activate(modName);
        mod.panels.active(modName);

        switch (modName) {
        case 'wizards_mod':
        case 'infowindow_mod':
            width = 450;
            event_name = 'narrowPanel';
        default:
        }

        // Show panel -> trigger
        cdb.god.trigger(event_name);

        this.isOpen = true;
        this.$el.animate({
            width: width,
            right: 0
        }, this.animation_time);
    },

    hide: function(modName) {
        var panel_width = this.$el.width();

        // Hide the tab
        var mod = this.getActivePane()
        //mod.tabs.deactivate(modName);

        // Hide panel -> trigger
        cdb.god.trigger("hidePanel");

        this.isOpen = false;
        this.$el.animate({
            right: 63 - panel_width
        }, this.animation_time);
    },

    bindSort: function() {
      this.$el
        .sortable('destroy')
        .sortable({
          axis:       "y",
          items:      "> .layer_panel",
          handle:     ".layer_info",
          contaiment: this.$el,
          opacity:    0.5,
          change:     this.manageLayers
        });
    },

    manageLayers: function() {
      var $active_layer = this.activePane.$el;

      // Move rest of panels
      this.$el.find('.layer_panel').removeClass('active');

      // Add active class
      $active_layer.addClass('active');

      // Set rest of layer_panels to height 60px
      // Decide later about compress them
      this.$el.find('.layer_panel').not('.layer_panel.active').css({
        height: 66
      })

      // Get previous siblings and calculate space
      var pre_size = $active_layer.prevAll('.layer_panel').size();
      var t_s = (pre_size == 0) ? 0 : (pre_size * 53);

      // Get next siblings and calculate space
      var next_size = $active_layer.nextAll('.layer_panel').size();
      var b_s = (next_size == 0) ? 0 : (next_size * 53);

      // Set available space for the active layer_space
      $active_layer.css({
        height: this.$el.height() - (t_s + b_s)
      })
    },

    switchTo: function(l) {
      // TESTING! - DON'T BE RUDE
      this.active(l.dataLayer.cid);
      this.trigger('switch', l);
      this.manageLayers();
    },

    toggle: function(modName) {
        // only hide if we click on active tab
        if (this.isOpen && modName == this.getActivePane()
            .panels.activeTab) {
            this.hide(modName);
        } else {
            this.show(modName);
        }
    },

    setActiveWorkView: function(workView) {
        this.hide();
        this.activeWorkView = workView;
        var p = this.getActivePane()
        if (p) {
            p.setActiveWorkView(workView);
        }
    }

});
<commit_msg>4 spaces -> 2 spaces<commit_after>//
// manage layers, its order and when should be shown or hiden
//
cdb.admin.LayersPanel = cdb.ui.common.TabPane.extend({

  className: 'table_panel',
  animation_time: 300,

  initialize: function() {
    cdb.ui.common.TabPane.prototype.initialize.call(this);

    this.map = this.options.map;
    this.add_related_model(this.map);

    this.map.layers.bind('add', this._addLayer, this);
    this.map.layers.bind('reset', this._resetLayers, this);
    this._addLayers(this.map.layers);

    this.isOpen = true;
    this.activeWorkView = 'table';

    /* test */
    _.bindAll(this, 'manageLayers');
  },

  _resetLayers: function() {
    //clean all views
    this.removeTabs();
    this._addLayers(this.map.layers);
  },

  _addLayers: function(layers) {
    var self = this;
    layers.each(function(l) {
        self._addLayer(l)
    });
  },

  _addLayer: function(layer) {
    var self = this;
    if (layer.get('type') == 'CartoDB') {
      var addIt = function(t) {
        var v = new cdb.admin.LayerPanelView({
            model: layer,
            sqlView: self.options.sqlView,
            table: t,
            map: self.map,
            user: self.options.user,
            globalError: self.options.globalError
        });

        v.bind('toggle', self.toggle, self);
        v.bind('switchTo', self.switchTo, self);
        self.addTab(layer.cid, v);
        v.setActiveWorkView(self.activeWorkView);
        self.trigger('switch', v);

        self.switchTo(v);
        self.bindSort();
      };

      if (layer.get('table_name')) {
        var table = new cdb.admin.CartoDBTableMetadata({
          id: layer.get('table_name')
        });
        table.fetch({
          success: function() {
              addIt(table)
          }
        });
      } else {
        addIt(this.options.table);
      }

    }
  },

  show: function(modName) {
    var width = 600,
        event_name = 'showPanel';

    // Select the tab

    var mod = this.getActivePane()
    mod.tabs.activate(modName);
    mod.panels.active(modName);

    switch (modName) {
    case 'wizards_mod':
    case 'infowindow_mod':
        width = 450;
        event_name = 'narrowPanel';
    default:
    }

    // Show panel -> trigger
    cdb.god.trigger(event_name);

    this.isOpen = true;
    this.$el.animate({
        width: width,
        right: 0
    }, this.animation_time);
  },

  hide: function(modName) {
    var panel_width = this.$el.width();

    // Hide the tab
    var mod = this.getActivePane()
    //mod.tabs.deactivate(modName);

    // Hide panel -> trigger
    cdb.god.trigger("hidePanel");

    this.isOpen = false;
    this.$el.animate({
        right: 63 - panel_width
    }, this.animation_time);
  },

  bindSort: function() {
    this.$el
      .sortable('destroy')
      .sortable({
        axis:       "y",
        items:      "> .layer_panel",
        handle:     ".layer_info",
        contaiment: this.$el,
        opacity:    0.5,
        change:     this.manageLayers
      });
  },

  manageLayers: function() {
    var $active_layer = this.activePane.$el;

    // Move rest of panels
    this.$el.find('.layer_panel').removeClass('active');

    // Add active class
    $active_layer.addClass('active');

    // Set rest of layer_panels to height 60px
    // Decide later about compress them
    this.$el.find('.layer_panel').not('.layer_panel.active').css({
      height: 66
    })

    // Get previous siblings and calculate space
    var pre_size = $active_layer.prevAll('.layer_panel').size();
    var t_s = (pre_size == 0) ? 0 : (pre_size * 53);

    // Get next siblings and calculate space
    var next_size = $active_layer.nextAll('.layer_panel').size();
    var b_s = (next_size == 0) ? 0 : (next_size * 53);

    // Set available space for the active layer_space
    $active_layer.css({
      height: this.$el.height() - (t_s + b_s)
    })
  },

  switchTo: function(l) {
    // TESTING! - DON'T BE RUDE
    this.active(l.dataLayer.cid);
    this.trigger('switch', l);
    this.manageLayers();
  },

  toggle: function(modName) {
    // only hide if we click on active tab
    if (this.isOpen && modName == this.getActivePane()
        .panels.activeTab) {
        this.hide(modName);
    } else {
        this.show(modName);
    }
  },

  setActiveWorkView: function(workView) {
    this.hide();
    this.activeWorkView = workView;
    var p = this.getActivePane()
    if (p) {
        p.setActiveWorkView(workView);
    }
  }

});
<|endoftext|>


<commit_before>var
    jQuery = jQuery,
    DO = DO;

(function ($) {
    "use strict";

	$.fn.extend({
        /*
         * @params = {url, sendData, process}
        */
        autocomplete: function (params, callback) {
            var
                found = [],
                self = $(this),
                domObjText,
                searchIndex,
                prevSliceTextNoSearch,
                sliceFound,
                remainderSliceTextNoSearch,
                spanSliceFound,
                copyng,
                ajax,
                xhr,
                jqObj,
                obj = {};

            if (params instanceof jQuery) {
                jqObj = params;

                self.on("keyup", function (e) {

                    jqObj.each(function (i, domObj) {

                        domObjText = domObj.textContent.trim();
                        searchIndex = domObjText.toLowerCase()
                            .search(self.val().toLowerCase());
                        if (searchIndex > -1) {

                            prevSliceTextNoSearch = domObjText
                                .slice(0, searchIndex);

                            sliceFound = domObjText.slice(prevSliceTextNoSearch
                                .length, prevSliceTextNoSearch.length +
                                    self.val().length);

                            remainderSliceTextNoSearch = domObjText
                                .slice(prevSliceTextNoSearch.length +
                                    sliceFound.length, domObjText.length);

                            spanSliceFound = $("");

                            copyng = $(domObj.cloneNode());
                            copyng.append(prevSliceTextNoSearch);
                            copyng.append(spanSliceFound);
                            spanSliceFound.addClass("do-ui-slice-found");
                            spanSliceFound.text(sliceFound);
                            copyng.append(remainderSliceTextNoSearch);

                            found.unshift(copyng);
                        }
                    });

                    if (callback) {
                        if (callback instanceof Function) {
                            callback(e, found);
                        }
                    }
                    found = [];
                });
            } else if (params instanceof Object) {
                self.on("keypress", function (e) {
                    params.initRemoteQuery(e, function(a) {
                        if (a instanceof jQuery) {
                            self.off("keypress");
                            self.autocomplete(a, callback);
                        }
                    });
                });
            }
        }

    });

}(jQuery));
<commit_msg>ajusta bug em autocomplete<commit_after>var
    jQuery = jQuery,
    DO = DO;

(function ($) {
    "use strict";

	$.fn.extend({
        /*
         * @params = {url, sendData, process}
        */
        autocomplete: function (params, callback) {
            var
                found = [],
                self = $(this),
                domObjText,
                searchIndex,
                prevSliceTextNoSearch,
                sliceFound,
                remainderSliceTextNoSearch,
                spanSliceFound,
                copyng,
                ajax,
                xhr,
                jqObj,
                obj = {};

            if (params instanceof jQuery) {
                jqObj = params;

                self.on("keyup", function (e) {

                    jqObj.each(function (i, domObj) {

                        domObjText = domObj.textContent.trim();
                        searchIndex = domObjText.toLowerCase()
                            .search(self.val().toLowerCase());
                        if (searchIndex > -1) {

                            prevSliceTextNoSearch = domObjText
                                .slice(0, searchIndex);

                            sliceFound = domObjText.slice(prevSliceTextNoSearch
                                .length, prevSliceTextNoSearch.length +
                                    self.val().length);

                            remainderSliceTextNoSearch = domObjText
                                .slice(prevSliceTextNoSearch.length +
                                    sliceFound.length, domObjText.length);

                            spanSliceFound = $("");

                            copyng = $(domObj.cloneNode());
                            copyng.append(prevSliceTextNoSearch);
                            copyng.append(spanSliceFound);
                            spanSliceFound.addClass("do-ui-slice-found");
                            spanSliceFound.text(sliceFound);
                            copyng.append(remainderSliceTextNoSearch);

                            found.unshift(copyng);
                        }
                    });

                    if (callback) {
                        if (callback instanceof Function) {
                            if (self.val()) {
                                callback(e, found);
                            } else {
                                callback(e, []);
                            }
                        }
                    }
                    found = [];
                });
            } else if (params instanceof Object) {
                self.on("keypress", function (e) {
                    params.initRemoteQuery(e, function (a) {
                        if (a instanceof jQuery) {
                            self.off("keypress");
                            self.autocomplete(a, callback);
                        }
                    });
                });
            }
        }

    });

}(jQuery));
<|endoftext|>


<commit_before>//= require ../support/jquery
//= require esphinx/support/object
//= require esphinx_ui

var
    jQuery,
    esPhinx;

(function ($module, $) {
    "use strict";

    var
        resolveArgs = function (jqObj, args) {
            if (args.addClass) {
                jqObj.addClass(args.addClass);
            }

            if (args.removeClass) {
                jqObj.addClass(args.removeClass);
            }
        },

        hide = function (jqObj, args) {
            // faltam testes para suporte a estilização. Talvez tenha de mapear as propriedades do css para ver se há transition, o tipo, caso tenha pegar os ms para usar no setTimeout
            jqObj.hide();

            if (args) {
                resolveArgs(jqObj, args);
            }
        },

        show = function (jqObj, args) {
            jqObj.show();

            if (args) {
                resolveArgs(jqObj, args);
            }
        },

        toggle = function (jqObj, args) {
            jqObj.css("position", "absolute");

            if (jqObj.is(":visible")) {
                hide(jqObj, args);
            }
            else {
                show(jqObj, args);
            }
        },

        // dar a oportunidade de informar as classes para o efeito
        closeAll = function (jqObj, args) {
            hide(jqObj, args);
        },

        resolveClass = function (className) {
            return '.' + className.replace(/ /, '.');
        };

    $module.extend({
        window: {
            tooltip: {

                // O próximo passo é testar se o evento é do mouse. Caso seja colocar um temporizador para desaparecer caso o ponteiro esteja fora do handler
                hideAll: function (e, tooltipId, args) {
                    var
                        target = $(e.target);

                    if (target.children(tooltipId).length === 0 && !target
                        .is(tooltipId)) {
                        closeAll(target.find(tooltipId), args);
                    }
                },

                tooltip: function () {

                    var
                        constructor = $module.window.tooltip.tooltip,
                        self,
                        handler,
                        tooltipId,
                        args;

                    if (!(this instanceof constructor)) {
                        return new constructor(arguments);
                    } else {
                        self = this;
                        args = arguments.flatten();
                        if (!handler) {
                            handler = args[0];
                        }

                        if (!tooltipId) {
                            tooltipId = args[1];
                        }
                    }

                    this.toggle = function (e, args) {
                        var
                            target = $(e.target),
                            tooltipTag = handler.find(tooltipId);

                        if (!target.is(resolveClass(tooltipTag
                            .attr("class")))) {
                            toggle(tooltipTag, args);
                        }
                    }

                    return self;
                }

            }
        }
    });

})(esPhinx.ui, jQuery);
<commit_msg>delete unnecessary code<commit_after>//= require ../support/jquery
//= require esphinx/support/object
//= require esphinx_ui

var
    jQuery,
    esPhinx;

(function ($module, $) {
    "use strict";

    var
        resolveArgs = function (jqObj, args) {
            if (args.addClass) {
                jqObj.addClass(args.addClass);
            }

            if (args.removeClass) {
                jqObj.addClass(args.removeClass);
            }
        },

        hide = function (jqObj, args) {
            // faltam testes para suporte a estilização. Talvez tenha de mapear as propriedades do css para ver se há transition, o tipo, caso tenha pegar os ms para usar no setTimeout
            jqObj.hide();

            if (args) {
                resolveArgs(jqObj, args);
            }
        },

        show = function (jqObj, args) {
            jqObj.show();

            if (args) {
                resolveArgs(jqObj, args);
            }
        },

        toggle = function (jqObj, args) {
            jqObj.css("position", "absolute");

            if (jqObj.is(":visible")) {
                hide(jqObj, args);
            }
            else {
                show(jqObj, args);
            }
        },

        // dar a oportunidade de informar as classes para o efeito
        closeAll = function (jqObj, args) {
            hide(jqObj, args);
        },

        resolveClass = function (className) {
            return '.' + className.replace(/ /, '.');
        };

    $module.extend({
        window: {
            tooltip: {

                // O próximo passo é testar se o evento é do mouse. Caso seja colocar um temporizador para desaparecer caso o ponteiro esteja fora do handler
                hideAll: function (e, tooltipId, args) {
                    var
                        target = $(e.target);

                    if (target.children(tooltipId).length === 0 && !target
                        .is(tooltipId)) {
                        closeAll(target.find(tooltipId), args);
                    }
                },

                tooltip: function () {

                    var
                        constructor = $module.window.tooltip.tooltip,
                        handler,
                        tooltipId,
                        args;

                    if (!(this instanceof constructor)) {
                        return new constructor(arguments);
                    } else {
                        args = arguments.flatten();
                        if (!handler) {
                            handler = args[0];
                        }

                        if (!tooltipId) {
                            tooltipId = args[1];
                        }
                    }

                    this.toggle = function (e, args) {
                        var
                            target = $(e.target),
                            tooltipTag = handler.find(tooltipId);

                        if (!target.is(resolveClass(tooltipTag
                            .attr("class")))) {
                            toggle(tooltipTag, args);
                        }
                    }

                    return this;
                }

            }
        }
    });

})(esPhinx.ui, jQuery);
<|endoftext|>


<commit_before>var rimraf = require("rimraf");
var mkdirp = require("mkdirp");
var async  = require("async");
var path   = require("path");
var fs     = require("fs");

function createLinkedDepFiles(src, dest, name, callback) {
  fs.writeFile(path.join(dest, "package.json"), JSON.stringify({
    name: name,
    version: require(path.join(src, "package.json")).version
  }, null, "  "), function (err) {
    if (err) return callback(err);

    fs.writeFile(
      path.join(dest, "index.js"),
      "module.exports = require(" + JSON.stringify(src) + ");",
      callback
    );
  });
}

function createLinkedDep(src, dest, name, callback) {
  rimraf(dest, function (err) {
    if (err) return callback(err);

    mkdirp(dest, function (err) {
      if (err) return callback(err);
      createLinkedDepFiles(src, dest, name, callback);
    });
  });
}

module.exports = function linkDependenciesForPackage(
  pkg,
  packages,
  packagesLoc,
  nodeModulesLoc,
  currentVersion,
  callback
) {
  async.each(packages, function (sub, done) {
    var ver = false;
    if (pkg.dependencies) ver = pkg.dependencies[sub.name];
    if (pkg.devDependencies && !ver) ver = pkg.devDependencies[sub.name];
    if (!ver) return done();

    // ensure that this is referring to a local package
    if (ver[0] !== "^" || ver[1] !== currentVersion[0]) return done();

    var linkSrc = path.join(packagesLoc, sub.folder);
    var linkDest = path.join(nodeModulesLoc, sub.name);

    createLinkedDep(linkSrc, linkDest, sub.name, done);
  }, callback);
}
<commit_msg>Symlink instead of creating files<commit_after>var rimraf = require("rimraf");
var async  = require("async");
var path   = require("path");
var fs     = require("fs");

function symlinkDep(src, dest, callback) {
  fs.symlink(src, dest, "dir", callback);
}

function createLinkedDep(src, dest, name, callback) {
  rimraf(dest, function (err) {
    if (err) return callback(err);
    symlinkDep(src, dest, callback);
  });
}

module.exports = function linkDependenciesForPackage(
  pkg,
  packages,
  packagesLoc,
  nodeModulesLoc,
  currentVersion,
  callback
) {
  async.each(packages, function (sub, done) {
    var ver = false;
    if (pkg.dependencies) ver = pkg.dependencies[sub.name];
    if (pkg.devDependencies && !ver) ver = pkg.devDependencies[sub.name];
    if (!ver) return done();

    // ensure that this is referring to a local package
    if (ver[0] !== "^" || ver[1] !== currentVersion[0]) return done();

    var linkSrc = path.join(packagesLoc, sub.folder);
    var linkDest = path.join(nodeModulesLoc, sub.name);

    createLinkedDep(linkSrc, linkDest, sub.name, done);
  }, callback);
}
<|endoftext|>


<commit_before>'use strict';

var Snap = require('snapsvg');

var forEach = require('lodash/collection/forEach'),
    domDelegate = require('min-dom/lib/delegate'),
    Renderer = require('../../draw/Renderer'),
    createLine = Renderer.createLine,
    updateLine = Renderer.updateLine;

var Snap = require('../../../vendor/snapsvg');

/**
 * A plugin that provides interaction events for diagram elements.
 *
 * It emits the following events:
 *
 *   * element.hover
 *   * element.out
 *   * element.click
 *   * element.dblclick
 *   * element.mousedown
 *
 * Each event is a tuple { element, gfx, originalEvent }.
 *
 * Canceling the event via Event#preventDefault() prevents the original DOM operation.
 *
 * @param {EventBus} eventBus
 */
function InteractionEvents(eventBus, elementRegistry, styles) {

  var HIT_STYLE = styles.cls('djs-hit', [ 'no-fill', 'no-border' ], {
    stroke: 'white',
    strokeWidth: 15
  });

  function fire(type, event) {
    var target = event.delegateTarget || event.target,
        gfx = target && new Snap(target),
        element = elementRegistry.get(gfx),
        defaultPrevented;

    if (!gfx || !element) {
      return;
    }

    defaultPrevented = eventBus.fire(type, { element: element, gfx: gfx, originalEvent: event });

    if (defaultPrevented) {
      event.preventDefault();
    }
  }

  var handlers = {};

  function mouseHandler(type) {

    var fn = handlers[type];

    if (!fn) {
      fn = handlers[type] = function(event) {
        // only indicate left mouse button=0 interactions
        if (!event.button) {
          fire(type, event);
        }
      };
    }

    return fn;
  }

  var bindings = {
    mouseover: 'element.hover',
    mouseout: 'element.out',
    click: 'element.click',
    dblclick: 'element.dblclick',
    mousedown: 'element.mousedown',
    mouseup: 'element.mouseup',
  };

  var elementSelector = 'svg, .djs-element';

  ///// event registration

  function registerEvent(node, event, localEvent) {
    var handler = mouseHandler(localEvent);
    handler.$delegate = domDelegate.bind(node, elementSelector, event, handler);
  }

  function unregisterEvent(node, event, localEvent) {
    domDelegate.unbind(node, event, mouseHandler(localEvent).$delegate);
  }

  function registerEvents(svg) {
    forEach(bindings, function(val, key) {
      registerEvent(svg.node, key, val);
    });
  }

  function unregisterEvents(svg) {
    forEach(bindings, function(val, key) {
      unregisterEvent(svg.node, key, val);
    });
  }

  eventBus.on('canvas.destroy', function(event) {
    unregisterEvents(event.svg);
  });

  eventBus.on('canvas.init', function(event) {
    registerEvents(event.svg);
  });

  eventBus.on([ 'shape.added', 'connection.added' ], function(event) {
    var element = event.element,
        gfx = event.gfx,
        hit,
        type;

    if (element.waypoints) {
      hit = createLine(element.waypoints);
      type = 'connection';
    } else {
      hit = Snap.create('rect', { x: 0, y: 0, width: element.width, height: element.height });
      type = 'shape';
    }

    hit.attr(HIT_STYLE).appendTo(gfx.node);
  });

  // update djs-hit on change

  eventBus.on('shape.changed', function(event) {

    var element = event.element,
        gfx = event.gfx,
        hit = gfx.select('.djs-hit');

    hit.attr({
      width: element.width,
      height: element.height
    });
  });

  eventBus.on('connection.changed', function(event) {

    var element = event.element,
        gfx = event.gfx,
        hit = gfx.select('.djs-hit');

    updateLine(hit, element.waypoints);
  });

  // API

  this.fire = fire;

  this.mouseHandler = mouseHandler;

  this.registerEvent = registerEvent;
  this.unregisterEvent = unregisterEvent;
}

InteractionEvents.$inject = [ 'eventBus', 'elementRegistry', 'styles' ];

module.exports = InteractionEvents;

/**
 * An event indicating that the mouse hovered over an element
 *
 * @event element.hover
 *
 * @type {Object}
 * @property {djs.model.Base} element
 * @property {Snap<Element>} gfx
 * @property {Event} originalEvent
 */

/**
 * An event indicating that the mouse has left an element
 *
 * @event element.out
 *
 * @type {Object}
 * @property {djs.model.Base} element
 * @property {Snap<Element>} gfx
 * @property {Event} originalEvent
 */

/**
 * An event indicating that the mouse has clicked an element
 *
 * @event element.click
 *
 * @type {Object}
 * @property {djs.model.Base} element
 * @property {Snap<Element>} gfx
 * @property {Event} originalEvent
 */

/**
 * An event indicating that the mouse has double clicked an element
 *
 * @event element.dblclick
 *
 * @type {Object}
 * @property {djs.model.Base} element
 * @property {Snap<Element>} gfx
 * @property {Event} originalEvent
 */

/**
 * An event indicating that the mouse has gone down on an element.
 *
 * @event element.mousedown
 *
 * @type {Object}
 * @property {djs.model.Base} element
 * @property {Snap<Element>} gfx
 * @property {Event} originalEvent
 */

/**
 * An event indicating that the mouse has gone up on an element.
 *
 * @event element.mouseup
 *
 * @type {Object}
 * @property {djs.model.Base} element
 * @property {Snap<Element>} gfx
 * @property {Event} originalEvent
 */<commit_msg>fix(interaction-events): correctly prevent default<commit_after>'use strict';

var Snap = require('snapsvg');

var forEach = require('lodash/collection/forEach'),
    domDelegate = require('min-dom/lib/delegate'),
    Renderer = require('../../draw/Renderer'),
    createLine = Renderer.createLine,
    updateLine = Renderer.updateLine;

var Snap = require('../../../vendor/snapsvg');

/**
 * A plugin that provides interaction events for diagram elements.
 *
 * It emits the following events:
 *
 *   * element.hover
 *   * element.out
 *   * element.click
 *   * element.dblclick
 *   * element.mousedown
 *
 * Each event is a tuple { element, gfx, originalEvent }.
 *
 * Canceling the event via Event#preventDefault() prevents the original DOM operation.
 *
 * @param {EventBus} eventBus
 */
function InteractionEvents(eventBus, elementRegistry, styles) {

  var HIT_STYLE = styles.cls('djs-hit', [ 'no-fill', 'no-border' ], {
    stroke: 'white',
    strokeWidth: 15
  });

  function fire(type, event) {
    var target = event.delegateTarget || event.target,
        gfx = target && new Snap(target),
        element = elementRegistry.get(gfx),
        defaultPrevented;

    if (!gfx || !element) {
      return;
    }

    defaultPrevented = !eventBus.fire(type, { element: element, gfx: gfx, originalEvent: event });

    if (defaultPrevented) {
      event.preventDefault();
    }
  }

  var handlers = {};

  function mouseHandler(type) {

    var fn = handlers[type];

    if (!fn) {
      fn = handlers[type] = function(event) {
        // only indicate left mouse button=0 interactions
        if (!event.button) {
          fire(type, event);
        }
      };
    }

    return fn;
  }

  var bindings = {
    mouseover: 'element.hover',
    mouseout: 'element.out',
    click: 'element.click',
    dblclick: 'element.dblclick',
    mousedown: 'element.mousedown',
    mouseup: 'element.mouseup',
  };

  var elementSelector = 'svg, .djs-element';

  ///// event registration

  function registerEvent(node, event, localEvent) {
    var handler = mouseHandler(localEvent);
    handler.$delegate = domDelegate.bind(node, elementSelector, event, handler);
  }

  function unregisterEvent(node, event, localEvent) {
    domDelegate.unbind(node, event, mouseHandler(localEvent).$delegate);
  }

  function registerEvents(svg) {
    forEach(bindings, function(val, key) {
      registerEvent(svg.node, key, val);
    });
  }

  function unregisterEvents(svg) {
    forEach(bindings, function(val, key) {
      unregisterEvent(svg.node, key, val);
    });
  }

  eventBus.on('canvas.destroy', function(event) {
    unregisterEvents(event.svg);
  });

  eventBus.on('canvas.init', function(event) {
    registerEvents(event.svg);
  });

  eventBus.on([ 'shape.added', 'connection.added' ], function(event) {
    var element = event.element,
        gfx = event.gfx,
        hit,
        type;

    if (element.waypoints) {
      hit = createLine(element.waypoints);
      type = 'connection';
    } else {
      hit = Snap.create('rect', { x: 0, y: 0, width: element.width, height: element.height });
      type = 'shape';
    }

    hit.attr(HIT_STYLE).appendTo(gfx.node);
  });

  // update djs-hit on change

  eventBus.on('shape.changed', function(event) {

    var element = event.element,
        gfx = event.gfx,
        hit = gfx.select('.djs-hit');

    hit.attr({
      width: element.width,
      height: element.height
    });
  });

  eventBus.on('connection.changed', function(event) {

    var element = event.element,
        gfx = event.gfx,
        hit = gfx.select('.djs-hit');

    updateLine(hit, element.waypoints);
  });

  // API

  this.fire = fire;

  this.mouseHandler = mouseHandler;

  this.registerEvent = registerEvent;
  this.unregisterEvent = unregisterEvent;
}

InteractionEvents.$inject = [ 'eventBus', 'elementRegistry', 'styles' ];

module.exports = InteractionEvents;

/**
 * An event indicating that the mouse hovered over an element
 *
 * @event element.hover
 *
 * @type {Object}
 * @property {djs.model.Base} element
 * @property {Snap<Element>} gfx
 * @property {Event} originalEvent
 */

/**
 * An event indicating that the mouse has left an element
 *
 * @event element.out
 *
 * @type {Object}
 * @property {djs.model.Base} element
 * @property {Snap<Element>} gfx
 * @property {Event} originalEvent
 */

/**
 * An event indicating that the mouse has clicked an element
 *
 * @event element.click
 *
 * @type {Object}
 * @property {djs.model.Base} element
 * @property {Snap<Element>} gfx
 * @property {Event} originalEvent
 */

/**
 * An event indicating that the mouse has double clicked an element
 *
 * @event element.dblclick
 *
 * @type {Object}
 * @property {djs.model.Base} element
 * @property {Snap<Element>} gfx
 * @property {Event} originalEvent
 */

/**
 * An event indicating that the mouse has gone down on an element.
 *
 * @event element.mousedown
 *
 * @type {Object}
 * @property {djs.model.Base} element
 * @property {Snap<Element>} gfx
 * @property {Event} originalEvent
 */

/**
 * An event indicating that the mouse has gone up on an element.
 *
 * @event element.mouseup
 *
 * @type {Object}
 * @property {djs.model.Base} element
 * @property {Snap<Element>} gfx
 * @property {Event} originalEvent
 */<|endoftext|>


<commit_before>apos.define('apostrophe-attachments', {

  afterConstruct: function(self) {
    self.addFieldType();
    self.addHandlers();
  },

  construct: function(self, options) {
    self.name = options.name;
    self.action = options.action;
    self.uploadsUrl = options.uploadsUrl || '';

    // Invoke with an attachment, options (such as minSize), and a callback.
    // Callback receives (err, crop). If no err, crop has coordinates and
    // can be stored as the crop property of the attachment (when there is
    // one and only one crop ever for this attachment), or stored as part
    // of a relationship to the doc containing the attachment; that part
    // is up to you.

    self.crop = function(attachment, options, callback) {

      var args = {
        action: self.action,
        attachment: attachment,
        cropped: function(crop) {
          return callback(null, crop);
        }
      };

      // If there is an existing crop of the attachment itself (not just a relationship),
      // omit that from the attachment object for purposes of cropping again, and move it to the options

      if (args.attachment.crop) {
        if (!args.crop) {
          args.crop = args.attachment.crop;
        }
        delete args.attachment.crop;
      }
      _.assign(args, options);
      apos.create('apostrophe-attachments-crop-editor', args);
    };

    // Invoke with an attachment, options (such as minSize), and a callback.
    // Callback receives (err, focalPoint). If no err, focalPoint has x and y
    // properties and can be stored as the focalPoint property of the attachment
    // (when there is one and only one focal point ever for this attachment), or
    // stored as part of a relationship to the doc containing the attachment; that part
    // is up to you.

    self.focalPoint = function(attachment, options, callback) {

      var args = {
        action: self.action,
        attachment: attachment,
        setFocalPoint: function(focalPoint) {
          return callback(null, focalPoint);
        }
      };

      // If there is an existing focal point for the attachment itself (not just a relationship),
      // omit that from the attachment object for purposes of editing again, and move it to the options

      if (args.attachment.focalPoint) {
        if (!args.focalPoint) {
          args.focalPoint = args.attachment.focalPoint;
        }
        delete args.attachment.focalPoint;
      }
      _.assign(args, options);
      apos.create('apostrophe-attachments-focal-point-editor', args);
    };

    self.addFieldType = function() {
      apos.schemas.addFieldType({
        name: self.name,
        populate: self.populate,
        convert: self.convert
      });
    };

    self.populate = function(object, name, $field, $el, field, callback) {
      var $fieldset = apos.schemas.findFieldset($el, name);
      self.updateExisting($fieldset, object[name], field);

      var $trashButton = $fieldset.find('[data-apos-trash]');

      // A bulk upload button is provided separately at the array level
      // if multipleUpload: true is set on an array schema field. -Tom

      var $uploaderButton = $fieldset.find('[data-apos-uploader-target]'),
          $input    = $fieldset.find('input[type="file"]');

      // configure button to fire input click
      $uploaderButton.on('click', function(){
        // input element gets replaced after each use, so we have to
        // find it each time we want to click it programmatically. -Tom
        $fieldset.find('input[type="file"]').click();
      });

      $trashButton.on('click', function() {
        self.updateExisting($fieldset, null, field);
        return false;
      });

      $input.fileupload({
        dataType: 'json',
        dropZone: $fieldset,
        maxNumberOfFiles: 1,
        url: self.action + '/upload',
        start: function (e) {
          busy(true);
        },
        // Even on an error we should note we're not spinning anymore
        always: function (e, data) {
          busy(false);
        },
        done: function (e, data) {
          if (data.result.status !== 'ok') {
            alert(data.result.status);
            return;
          }
          var file = data.result.file;
          self.updateExisting($fieldset, file, field);
        },
        add: function(e, data) {
          return data.submit();
        }
      });

      return setImmediate(callback);

      function busy(state) {
        $uploaderButton.attr('data-busy', state ? '1' : '0');
        apos.ui.busy($fieldset, !!state);
      }

    };

    self.convert = function(data, name, $field, $el, field, callback) {
      var $fieldset = apos.schemas.findFieldset($el, name);
      if ($fieldset.attr('data-busy') === '1') {
        // If upload is in progress stay busy until this upload
        // completes. Other file attachment fields may be doing
        // the same dance.
        setTimeout(function() {
          self.convert(data, name, $field, $el, field, callback);
        }, 100);
        return;
      }
      data[name] = $fieldset.find('[data-existing]').data('existing');
      if (field.required && (!data[name])) {
        return setImmediate(_.partial(callback, 'required'));
      }
      return setImmediate(callback);
    };

    self.addHandlers = function() {
      apos.ui.link('apos-crop', 'attachment', function($el, _id) {
        var $existing = $el.closest('[data-existing]');

        var attachment = $existing.data('existing');
        var field = $existing.data('field');
        var $fieldset = $el.closest('[data-name]');
        // TODO what about minSize, etc. in this context?
        var options = {};
        options.focalPoint = (field.hints && field.hints.focalPoint);
        options.minSize = (field.hints && field.hints.minSize);
        options.aspectRatio = (field.hints && field.hints.aspectRatio);
        self.crop(attachment, options, function(err, crop) {
          if (!err) {
            attachment.crop = crop;
            self.updateExisting($fieldset, attachment, field);
          }
        });
      });
      apos.ui.link('apos-focal-point', 'attachment', function($el, _id) {
        var $existing = $el.closest('[data-existing]');

        var attachment = $existing.data('existing');
        var field = $existing.data('field');
        var $fieldset = $el.closest('[data-name]');
        var options = {};
        options.focalPoint = (field.hints && field.hints.focalPoint);
        self.focalPoint(attachment, options, function(err, focalPoint) {
          if (!err) {
            attachment.focalPoint = focalPoint;
            self.updateExisting($fieldset, attachment, field);
          }
        });
      });
    };

    self.updateExisting = function($fieldset, info, field) {
      var $existing = $fieldset.find('[data-existing]');
      if (!info) {
        $existing.data('existing', null);
        $existing.hide();
        return;
      }
      $existing.data('existing', info);
      $existing.data('field', field);
      $existing.attr('data-existing', info._id);
      $existing.find('[data-name]').text(info.name);
      $existing.find('[data-link]').attr('href', self.url(info));
      $existing.alterClass('apos-extension-*', 'apos-extension-' + info.extension);
      var $preview = $existing.find('[data-preview]');
      if (info.group === 'images') {
        $preview.attr('src', self.url(info, { size: 'one-half', crop: info.crop, focalPoint: info.focalPoint }));
        $fieldset.find('[data-apos-crop-attachment]').show();
        $fieldset.find('[data-apos-focal-point-attachment]').show();
      } else {
        $preview.hide();
        $fieldset.find('[data-apos-crop-attachment]').hide();
        $fieldset.find('[data-apos-focal-point-attachment]').hide();
      }
      $existing.show();
      apos.emit('attachmentUpdated', {
        $fieldset: $fieldset,
        attachment: info,
        field: field
      });
    };

    apos.attachments = self;

  }
});
<commit_msg>do not pass focal point to apos.attachments.url, which cannot do anything useful with that<commit_after>apos.define('apostrophe-attachments', {

  afterConstruct: function(self) {
    self.addFieldType();
    self.addHandlers();
  },

  construct: function(self, options) {
    self.name = options.name;
    self.action = options.action;
    self.uploadsUrl = options.uploadsUrl || '';

    // Invoke with an attachment, options (such as minSize), and a callback.
    // Callback receives (err, crop). If no err, crop has coordinates and
    // can be stored as the crop property of the attachment (when there is
    // one and only one crop ever for this attachment), or stored as part
    // of a relationship to the doc containing the attachment; that part
    // is up to you.

    self.crop = function(attachment, options, callback) {

      var args = {
        action: self.action,
        attachment: attachment,
        cropped: function(crop) {
          return callback(null, crop);
        }
      };

      // If there is an existing crop of the attachment itself (not just a relationship),
      // omit that from the attachment object for purposes of cropping again, and move it to the options

      if (args.attachment.crop) {
        if (!args.crop) {
          args.crop = args.attachment.crop;
        }
        delete args.attachment.crop;
      }
      _.assign(args, options);
      apos.create('apostrophe-attachments-crop-editor', args);
    };

    // Invoke with an attachment, options (such as minSize), and a callback.
    // Callback receives (err, focalPoint). If no err, focalPoint has x and y
    // properties and can be stored as the focalPoint property of the attachment
    // (when there is one and only one focal point ever for this attachment), or
    // stored as part of a relationship to the doc containing the attachment; that part
    // is up to you.

    self.focalPoint = function(attachment, options, callback) {

      var args = {
        action: self.action,
        attachment: attachment,
        setFocalPoint: function(focalPoint) {
          return callback(null, focalPoint);
        }
      };

      // If there is an existing focal point for the attachment itself (not just a relationship),
      // omit that from the attachment object for purposes of editing again, and move it to the options

      if (args.attachment.focalPoint) {
        if (!args.focalPoint) {
          args.focalPoint = args.attachment.focalPoint;
        }
        delete args.attachment.focalPoint;
      }
      _.assign(args, options);
      apos.create('apostrophe-attachments-focal-point-editor', args);
    };

    self.addFieldType = function() {
      apos.schemas.addFieldType({
        name: self.name,
        populate: self.populate,
        convert: self.convert
      });
    };

    self.populate = function(object, name, $field, $el, field, callback) {
      var $fieldset = apos.schemas.findFieldset($el, name);
      self.updateExisting($fieldset, object[name], field);

      var $trashButton = $fieldset.find('[data-apos-trash]');

      // A bulk upload button is provided separately at the array level
      // if multipleUpload: true is set on an array schema field. -Tom

      var $uploaderButton = $fieldset.find('[data-apos-uploader-target]'),
          $input    = $fieldset.find('input[type="file"]');

      // configure button to fire input click
      $uploaderButton.on('click', function(){
        // input element gets replaced after each use, so we have to
        // find it each time we want to click it programmatically. -Tom
        $fieldset.find('input[type="file"]').click();
      });

      $trashButton.on('click', function() {
        self.updateExisting($fieldset, null, field);
        return false;
      });

      $input.fileupload({
        dataType: 'json',
        dropZone: $fieldset,
        maxNumberOfFiles: 1,
        url: self.action + '/upload',
        start: function (e) {
          busy(true);
        },
        // Even on an error we should note we're not spinning anymore
        always: function (e, data) {
          busy(false);
        },
        done: function (e, data) {
          if (data.result.status !== 'ok') {
            alert(data.result.status);
            return;
          }
          var file = data.result.file;
          self.updateExisting($fieldset, file, field);
        },
        add: function(e, data) {
          return data.submit();
        }
      });

      return setImmediate(callback);

      function busy(state) {
        $uploaderButton.attr('data-busy', state ? '1' : '0');
        apos.ui.busy($fieldset, !!state);
      }

    };

    self.convert = function(data, name, $field, $el, field, callback) {
      var $fieldset = apos.schemas.findFieldset($el, name);
      if ($fieldset.attr('data-busy') === '1') {
        // If upload is in progress stay busy until this upload
        // completes. Other file attachment fields may be doing
        // the same dance.
        setTimeout(function() {
          self.convert(data, name, $field, $el, field, callback);
        }, 100);
        return;
      }
      data[name] = $fieldset.find('[data-existing]').data('existing');
      if (field.required && (!data[name])) {
        return setImmediate(_.partial(callback, 'required'));
      }
      return setImmediate(callback);
    };

    self.addHandlers = function() {
      apos.ui.link('apos-crop', 'attachment', function($el, _id) {
        var $existing = $el.closest('[data-existing]');

        var attachment = $existing.data('existing');
        var field = $existing.data('field');
        var $fieldset = $el.closest('[data-name]');
        // TODO what about minSize, etc. in this context?
        var options = {};
        options.focalPoint = (field.hints && field.hints.focalPoint);
        options.minSize = (field.hints && field.hints.minSize);
        options.aspectRatio = (field.hints && field.hints.aspectRatio);
        self.crop(attachment, options, function(err, crop) {
          if (!err) {
            attachment.crop = crop;
            self.updateExisting($fieldset, attachment, field);
          }
        });
      });
      apos.ui.link('apos-focal-point', 'attachment', function($el, _id) {
        var $existing = $el.closest('[data-existing]');

        var attachment = $existing.data('existing');
        var field = $existing.data('field');
        var $fieldset = $el.closest('[data-name]');
        var options = {};
        options.focalPoint = (field.hints && field.hints.focalPoint);
        self.focalPoint(attachment, options, function(err, focalPoint) {
          if (!err) {
            attachment.focalPoint = focalPoint;
            self.updateExisting($fieldset, attachment, field);
          }
        });
      });
    };

    self.updateExisting = function($fieldset, info, field) {
      var $existing = $fieldset.find('[data-existing]');
      if (!info) {
        $existing.data('existing', null);
        $existing.hide();
        return;
      }
      $existing.data('existing', info);
      $existing.data('field', field);
      $existing.attr('data-existing', info._id);
      $existing.find('[data-name]').text(info.name);
      $existing.find('[data-link]').attr('href', self.url(info));
      $existing.alterClass('apos-extension-*', 'apos-extension-' + info.extension);
      var $preview = $existing.find('[data-preview]');
      if (info.group === 'images') {
        $preview.attr('src', self.url(info, { size: 'one-half', crop: info.crop }));
        $fieldset.find('[data-apos-crop-attachment]').show();
        $fieldset.find('[data-apos-focal-point-attachment]').show();
      } else {
        $preview.hide();
        $fieldset.find('[data-apos-crop-attachment]').hide();
        $fieldset.find('[data-apos-focal-point-attachment]').hide();
      }
      $existing.show();
      apos.emit('attachmentUpdated', {
        $fieldset: $fieldset,
        attachment: info,
        field: field
      });
    };

    apos.attachments = self;

  }
});
<|endoftext|>


<commit_before>"use strict";

const nacl = require("ecma-nacl");
const Constants = require("../../Constants");
const Utils = require("../../core/Utils");

class VoiceTransportBase {
  constructor(voicews, ssrc) {
    this.voicews = voicews;
    this.ssrc = ssrc;

    this.onAudioPacket = null;

    this.header = new Buffer(24);
    this.header.fill(0);
    this.header[0] = 0x80;
    this.header[1] = 0x78;
    this.header.writeUInt32BE(ssrc, 8);

    this.decryptionNonce = new Buffer(24);
    this.decryptionNonce.fill(0);

    this.reinitialize();

    this.readyState = Constants.ReadyState.CLOSED;
  }
  connecting() {
    return this.readyState == Constants.ReadyState.CONNECTING;
  }
  connected() {
    return this.readyState == Constants.ReadyState.OPEN;
  }
  _encrypt(packet, nonce) {
    if (this.voicews.mode != Constants.EncryptionModes.xsalsa20_poly1305)
      return packet;

    const packetView =
      new Uint8Array(Utils.createArrayBuffer(packet));
    const nonceView =
      new Uint8Array(Utils.createArrayBuffer(nonce));

    return nacl.secret_box.pack(packetView, nonceView, this.voicews.secret);
  }
  _decrypt(packet) {
    if (this.voicews.mode != Constants.EncryptionModes.xsalsa20_poly1305)
      return packet;

    const header = packet.slice(0, 12);

    if (packet.length < 12 + 16)
      return header;

    header.copy(this.decryptionNonce);

    const audioDataView =
      new Uint8Array(Utils.createArrayBuffer(packet.slice(12)));
    const nonceView =
      new Uint8Array(Utils.createArrayBuffer(this.decryptionNonce));

    const decrypted =
      nacl.secret_box.open(audioDataView, nonceView, this.voicews.secret);

    const decryptedPacket = new Buffer(packet.length - 16);
    header.copy(decryptedPacket);
    for (let i = 0; i < decrypted.length; i++) {
      decryptedPacket[12 + i] = decrypted[i];
    }
    return decryptedPacket;
  }
  mux(packet, sampleCount) {
    this.header.writeUInt16BE(this.sequence, 2);
    this.header.writeUInt32BE(this.timestamp, 4);

    packet = this._encrypt(packet, this.header);

    const rtpPacket = new Buffer(packet.length + 12);
    this.header.copy(rtpPacket, 0, 0, 12);
    for (let i = 0; i < packet.length; i++) {
      rtpPacket[12 + i] = packet[i];
    }

    //if (typeof this.xx == "undefined") {
    //  this.xx = new Date().getTime();
    //}
    //console.log("seq: "+this.sequence+", ts: "+this.timestamp+", d: "+(new Date().getTime() - this.xx));
    //this.xx = new Date().getTime();

    this.sequence++;
    this.timestamp += sampleCount;

    if (this.sequence >= 0xFFFF)
      this.sequence -= 0xFFFF;
    if (this.timestamp >= 0xFFFFFFFF)
      this.timestamp -= 0xFFFFFFFF;

    return rtpPacket;
  }
  demux(packet) {
    if (typeof this.onAudioPacket !== "function")
      return;

    try {
      packet = this._decrypt(packet);
    } catch (e) {
      return console.log(e.stack);
    }

    const seq = packet.readUInt16BE(2);
    const timestamp = packet.readUInt32BE(4);
    const ssrc = packet.readUInt32BE(8);
    const chunk = packet.slice(12);

    this.onAudioPacket({
      seq: seq,
      timestamp: timestamp,
      ssrc: ssrc,
      chunk: chunk
    });
  }
  reinitialize() {
    this.sequence = Math.round(Math.random() * 0xFFFF) - 1;
    this.timestamp = 0;
  }
}

module.exports = VoiceTransportBase;
<commit_msg>Minor refactoring<commit_after>"use strict";

const nacl = require("ecma-nacl");
const Constants = require("../../Constants");
const Utils = require("../../core/Utils");

class VoiceTransportBase {
  constructor(voicews, ssrc) {
    this.voicews = voicews;
    this.ssrc = ssrc;

    this.onAudioPacket = null;

    this.header = new Buffer(24);
    this.header.fill(0);
    this.header[0] = 0x80;
    this.header[1] = 0x78;
    this.header.writeUInt32BE(ssrc, 8);

    this.decryptionNonce = new Buffer(24);
    this.decryptionNonce.fill(0);

    this.reinitialize();

    this.readyState = Constants.ReadyState.CLOSED;
  }
  connecting() {
    return this.readyState == Constants.ReadyState.CONNECTING;
  }
  connected() {
    return this.readyState == Constants.ReadyState.OPEN;
  }
  _encrypt(packet, nonce) {
    if (this.voicews.mode != Constants.EncryptionModes.xsalsa20_poly1305)
      return packet;

    const packetView =
      new Uint8Array(Utils.createArrayBuffer(packet));
    const nonceView =
      new Uint8Array(Utils.createArrayBuffer(nonce));

    return nacl.secret_box.pack(packetView, nonceView, this.voicews.secret);
  }
  _decrypt(packet) {
    if (this.voicews.mode != Constants.EncryptionModes.xsalsa20_poly1305)
      return packet;

    const header = packet.slice(0, 12);

    if (packet.length < 12 + 16)
      return header;

    header.copy(this.decryptionNonce);

    const audioDataView =
      new Uint8Array(Utils.createArrayBuffer(packet.slice(12)));
    const nonceView =
      new Uint8Array(Utils.createArrayBuffer(this.decryptionNonce));

    const decrypted =
      nacl.secret_box.open(audioDataView, nonceView, this.voicews.secret);

    const decryptedPacket = new Buffer(packet.length - 16);
    header.copy(decryptedPacket);
    for (let i = 0; i < decrypted.length; i++) {
      decryptedPacket[12 + i] = decrypted[i];
    }
    return decryptedPacket;
  }
  mux(packet, sampleCount) {
    this.header.writeUInt16BE(this.sequence, 2);
    this.header.writeUInt32BE(this.timestamp, 4);

    packet = this._encrypt(packet, this.header);

    const rtpPacket = new Buffer(packet.length + 12);
    this.header.copy(rtpPacket, 0, 0, 12);
    for (let i = 0; i < packet.length; i++) {
      rtpPacket[12 + i] = packet[i];
    }

    //if (typeof this.xx == "undefined") {
    //  this.xx = new Date().getTime();
    //}
    //console.log("seq: "+this.sequence+", ts: "+this.timestamp+", d: "+(new Date().getTime() - this.xx));
    //this.xx = new Date().getTime();

    this.sequence++;
    this.timestamp += sampleCount;

    this.sequence %= 0xFFFF + 1;
    this.timestamp %= 0xFFFFFFFF + 1;

    return rtpPacket;
  }
  demux(packet) {
    if (typeof this.onAudioPacket !== "function")
      return;

    try {
      packet = this._decrypt(packet);
    } catch (e) {
      return console.log(e.stack);
    }

    const seq = packet.readUInt16BE(2);
    const timestamp = packet.readUInt32BE(4);
    const ssrc = packet.readUInt32BE(8);
    const chunk = packet.slice(12);

    this.onAudioPacket({
      seq: seq,
      timestamp: timestamp,
      ssrc: ssrc,
      chunk: chunk
    });
  }
  reinitialize() {
    this.sequence = Math.round(Math.random() * 0xFFFF) - 1;
    this.timestamp = 0;
  }
}

module.exports = VoiceTransportBase;
<|endoftext|>


<commit_before>'use strict';

var Node = require('../node');
var debug = require('../../util/debug')('analysis:data-observatory-multiple-measures');

var TYPE = 'data-observatory-multiple-measures';
var PARAMS = {
    source: Node.PARAM.NODE(Node.GEOMETRY.POINT, Node.GEOMETRY.POLYGON),
    numerators: Node.PARAM.ARRAY(Node.PARAM.STRING()),
    normalizations: Node.PARAM.ARRAY(Node.PARAM.STRING()),
    denominators: Node.PARAM.ARRAY(Node.PARAM.NULLABLE(Node.PARAM.STRING())),
    geom_ids: Node.PARAM.ARRAY(Node.PARAM.NULLABLE(Node.PARAM.STRING())),
    numerator_timespans: Node.PARAM.ARRAY(Node.PARAM.NULLABLE(Node.PARAM.STRING())),
    column_names: Node.PARAM.ARRAY(Node.PARAM.STRING())
};

var DataObservatoryMultipleMeasures = Node.create(TYPE, PARAMS, { cache: true, lazy: true,
    beforeCreate: function() {
        /* jshint maxcomplexity:8 */
        if (this.numerators.length === 0) {
            throw new Error('The numerators array cannot be empty');
        }

        if (this.numerators.length !== this.column_names.length) {
            throw new Error('The number of numerators=' + this.numerators.length +
                ' does not match the number of column_names=' + this.column_names.length);
        }

        if (this.normalizations.length === 0) {
            throw new Error('The normalizations array cannot be empty');
        }

        if (this.normalizations.length !== this.numerators.length) {
            throw new Error('The number of numerators=' + this.numerators.length +
                ' does not match the number of normalizations=' + this.normalizations.length);
        }

        if (this.denominators && this.denominators.length !== this.numerators.length) {
            throw new Error('The number of numerators=' + this.numerators.length +
                ' does not match the number of denominators=' + this.denominators.length);
        }

        if (this.geom_ids && this.geom_ids.length !== this.numerators.length) {
            throw new Error('The number of numerators=' + this.numerators.length +
                ' does not match the number of geom_ids=' + this.geom_ids.length);
        }

        if (this.numerator_timespans && this.numerator_timespans.length !== this.numerators.length) {
            throw new Error('The number of numerators=' + this.numerators.length +
                ' does not match the number of numerator_timespans=' + this.numerator_timespans.length);
        }
    }
});

module.exports = DataObservatoryMultipleMeasures;

DataObservatoryMultipleMeasures.prototype._composeObsMetaParams = function() {
    var params = this.numerators.map(function (numerator, index) {
        return {
            numer_id: numerator,
            denom_id: (this.denominators && this.denominators[index]) ?
                this.denominators[index] : null,
            normalization: this.normalizations[index],
            geom_id: (this.geom_ids && this.geom_ids[index]) ?
                this.geom_ids[index] : null,
            numer_timespan: (this.numerator_timespans && this.numerator_timespans[index]) ?
                this.numerator_timespans[index] : null
        };
    }.bind(this));

    return JSON.stringify(params);
};

DataObservatoryMultipleMeasures.prototype.sql = function() {
    var finalColumns = ['_source.*']
        .concat(this.column_names.map(function(columnName) {
            return '_data.' + columnName;
        })).join(', ');

    var sql = queryTemplate({
        source: this.source.getQuery(false),
        obsColumns: this.column_names.map(function (columnName, index) {
            return '(data->' + index + '->>\'value\')::Numeric AS ' + columnName;
        }).join(', '),
        obsMetaParams: this._composeObsMetaParams(),
        finalColumns: finalColumns
    });

    debug(sql);

    return sql;
};

var queryTemplate = Node.template([
    'WITH _source AS (',
    ' {{=it.source}}',
    '),',
    '_summary AS ( ',
    '  SELECT',
    '    ST_SetSRID(ST_Extent(the_geom), 4326) extent, ',
    '    count(*)::INT numgeoms',
    '  FROM _source',
    '  WHERE the_geom IS NOT NULL',
    '),',
    '_meta AS (',
    '  SELECT',
    '    cdb_dataservices_client._OBS_GetMeta_exception_safe(',
    '      extent,',
    '      (\'{{=it.obsMetaParams}}\')::JSON, 1, 1, numgeoms',
    '    ) as meta',
    '  FROM _summary',
    '),',
    '_data AS ( ',
    '  SELECT id AS __obs_id__, {{=it.obsColumns}}',
    '  FROM cdb_dataservices_client._OBS_GetData_exception_safe(',
    '    (SELECT ARRAY_AGG((the_geom, cartodb_id)::geomval) FROM _source WHERE the_geom IS NOT NULL),',
    '    (SELECT meta FROM _meta)',
    '  ) AS _camshaft_do_measure_analysis_data',
    ')',
    'SELECT {{=it.finalColumns}}',
    'FROM _source left join _data',
    'ON _source.cartodb_id = _data.__obs_id__'
].join('\n'));

var preCheckQueryTemplate = Node.template([
    'SELECT cdb_dataservices_client._OBS_PreCheck(\'{{=it.source}}\',',
    ' \'{{=it.obsMetaParams}}\'::json)'
].join(''));

DataObservatoryMultipleMeasures.prototype.preCheckQuery = function() {
    var sql = preCheckQueryTemplate({
        source: this.source.getQuery(false),
        obsMetaParams: this._composeObsMetaParams()
    });
    debug(sql);
    return sql;
};
<commit_msg>Going green: retrieve metadata to cast column to the correct type<commit_after>'use strict';

var Node = require('../node');
var debug = require('../../util/debug')('analysis:data-observatory-multiple-measures');

var TYPE = 'data-observatory-multiple-measures';
var PARAMS = {
    source: Node.PARAM.NODE(Node.GEOMETRY.POINT, Node.GEOMETRY.POLYGON),
    numerators: Node.PARAM.ARRAY(Node.PARAM.STRING()),
    normalizations: Node.PARAM.ARRAY(Node.PARAM.STRING()),
    denominators: Node.PARAM.ARRAY(Node.PARAM.NULLABLE(Node.PARAM.STRING())),
    geom_ids: Node.PARAM.ARRAY(Node.PARAM.NULLABLE(Node.PARAM.STRING())),
    numerator_timespans: Node.PARAM.ARRAY(Node.PARAM.NULLABLE(Node.PARAM.STRING())),
    column_names: Node.PARAM.ARRAY(Node.PARAM.STRING())
};

var DataObservatoryMultipleMeasures = Node.create(TYPE, PARAMS, { cache: true, lazy: true,
    beforeCreate: function() {
        /* jshint maxcomplexity:8 */
        if (this.numerators.length === 0) {
            throw new Error('The numerators array cannot be empty');
        }

        if (this.numerators.length !== this.column_names.length) {
            throw new Error('The number of numerators=' + this.numerators.length +
                ' does not match the number of column_names=' + this.column_names.length);
        }

        if (this.normalizations.length === 0) {
            throw new Error('The normalizations array cannot be empty');
        }

        if (this.normalizations.length !== this.numerators.length) {
            throw new Error('The number of numerators=' + this.numerators.length +
                ' does not match the number of normalizations=' + this.normalizations.length);
        }

        if (this.denominators && this.denominators.length !== this.numerators.length) {
            throw new Error('The number of numerators=' + this.numerators.length +
                ' does not match the number of denominators=' + this.denominators.length);
        }

        if (this.geom_ids && this.geom_ids.length !== this.numerators.length) {
            throw new Error('The number of numerators=' + this.numerators.length +
                ' does not match the number of geom_ids=' + this.geom_ids.length);
        }

        if (this.numerator_timespans && this.numerator_timespans.length !== this.numerators.length) {
            throw new Error('The number of numerators=' + this.numerators.length +
                ' does not match the number of numerator_timespans=' + this.numerator_timespans.length);
        }

        this.columnTypes = this.numerators.reduce((columnTypes, numeratorId, index) => {
            columnTypes[numeratorId] = {
                name: this.column_names[index],
                type: 'Numeric'
            };
            return columnTypes;
        }, {});
    },
    beforeCreateAsync: function(databaseService, callback) {
        const sql = columnTypesQueryTemplate({
            source: this.source.getQuery(false),
            obsMetaParams: this._composeObsMetaParams()
        });
        databaseService.run(sql, (err, result) => {
            if (err) {
                return callback(err);
            }

            const measures = (Array.isArray(result.rows) && result.rows[0]) || {};
            measures.meta = measures.meta || [];
            measures.meta.forEach(measureMetadata => {
                if (this.columnTypes.hasOwnProperty(measureMetadata.numer_id)) {
                    const type = (measureMetadata.numer_type.toLowerCase() === 'text') ? 'Text' : 'Numeric';
                    this.columnTypes[measureMetadata.numer_id].type = type;
                }
            });

            return callback(null);
        });
    }
});

module.exports = DataObservatoryMultipleMeasures;

DataObservatoryMultipleMeasures.prototype._composeObsMetaParams = function() {
    var params = this.numerators.map(function (numerator, index) {
        return {
            numer_id: numerator,
            denom_id: (this.denominators && this.denominators[index]) ?
                this.denominators[index] : null,
            normalization: this.normalizations[index],
            geom_id: (this.geom_ids && this.geom_ids[index]) ?
                this.geom_ids[index] : null,
            numer_timespan: (this.numerator_timespans && this.numerator_timespans[index]) ?
                this.numerator_timespans[index] : null
        };
    }.bind(this));

    return JSON.stringify(params);
};

DataObservatoryMultipleMeasures.prototype.sql = function() {
    var finalColumns = ['_source.*']
        .concat(this.column_names.map(function(columnName) {
            return '_data.' + columnName;
        })).join(', ');

    var sql = queryTemplate({
        source: this.source.getQuery(false),
        obsColumns: this.numerators.map((numeratorId, index) => {
            const type = this.columnTypes[numeratorId].type;
            const name = this.columnTypes[numeratorId].name;
            return `(data->${index}->>'value')::${type} AS ${name}`;
        }).join(', '),
        obsMetaParams: this._composeObsMetaParams(),
        finalColumns: finalColumns
    });

    debug(sql);

    return sql;
};

const metadataCTEemplate = `
    WITH _source AS (
        {{=it.source}}
    ),
    _summary AS (
        SELECT
            ST_SetSRID(ST_Extent(the_geom), 4326) extent,
            count(*)::INT numgeoms
        FROM _source
        WHERE the_geom IS NOT NULL
    ),
    _meta AS (
        SELECT
            cdb_dataservices_client._OBS_GetMeta_exception_safe(
                extent, ('{{=it.obsMetaParams}}')::JSON, 1, 1, numgeoms
            ) as meta
        FROM _summary
    )
`;

var queryTemplate = Node.template(`
    ${metadataCTEemplate},
    _data AS (
        SELECT id AS __obs_id__, {{=it.obsColumns}}
        FROM cdb_dataservices_client._OBS_GetData_exception_safe(
            (SELECT ARRAY_AGG((the_geom, cartodb_id)::geomval) FROM _source WHERE the_geom IS NOT NULL),
            (SELECT meta FROM _meta)
        ) AS _camshaft_do_measure_analysis_data
    )
    SELECT {{=it.finalColumns}}
    FROM _source left join _data
    ON _source.cartodb_id = _data.__obs_id__
`);

const columnTypesQueryTemplate = Node.template(`
    ${metadataCTEemplate}
    SELECT meta FROM _meta
`);

var preCheckQueryTemplate = Node.template([
    'SELECT cdb_dataservices_client._OBS_PreCheck(\'{{=it.source}}\',',
    ' \'{{=it.obsMetaParams}}\'::json)'
].join(''));

DataObservatoryMultipleMeasures.prototype.preCheckQuery = function() {
    var sql = preCheckQueryTemplate({
        source: this.source.getQuery(false),
        obsMetaParams: this._composeObsMetaParams()
    });
    debug(sql);
    return sql;
};
<|endoftext|>


<commit_before>'use strict';

var NS = {};

// MODULES //

var getKeys = require( 'object-keys' ).shim();
var isObject = require( '@stdlib/utils/is-plain-object' );
var hasOwnProp = require( '@stdlib/utils/has-own-property' );
var copy = require( '@stdlib/utils/copy' );
var Plot = require( '@stdlib/plot/plot' );
var Sparkline = require( '@stdlib/plot/sparklines/unicode/column' ); // FIXME: should be abstract interface

// FUNCTIONS //

/**
* Wraps the plot API to provide a REPL specific `plot` function.
*
* @private
* @returns {Plot} Plot instance
*/
function plot() {
	var opts;
	var x;
	var y;
	var h;

	// Check for an `options` argument...
	if ( arguments.length === 0 ) {
		x = [];
		y = [];
	}
	else if ( arguments.length === 1 ) {
		x = [];
		y = [];
		opts = arguments[ 0 ];
		if ( !isObject( opts ) ) {
			throw new TypeError( 'invalid input argument. `options` argument must be an object. Value: `' + opts + '`.' );
		}
	}
	else if ( arguments.length === 2 ) {
		x = arguments[ 0 ];
		y = arguments[ 1 ];
	}
	else {
		x = arguments[ 0 ];
		y = arguments[ 1 ];
		opts = arguments[ 2 ];
		if ( !isObject( opts ) ) {
			throw new TypeError( 'invalid input argument. `options` argument must be an object. Value: `' + opts + '`.' );
		}
	}
	// Check for rendering and view options; if not set, set to REPL defaults...
	if ( opts ) {
		opts = copy( opts );
		if ( !hasOwnProp( opts, 'autoRender' ) ) {
			opts.autoRender = false;
		}
		if ( !hasOwnProp( opts, 'autoView' ) ) {
			opts.autoView = false;
		}
		if ( !hasOwnProp( opts, 'viewer' ) ) {
			opts.viewer = 'window';
		}
		h = new Plot( x, y, opts );
	} else {
		opts = {
			'autoRender': false,
			'autoView': false,
			'viewer': 'window'
		};
		h = new Plot( x, y, opts );
	}
	return h;
} // end FUNCTION plot()

// MAIN //

NS.plot = plot;
NS.Plot = Plot;
NS.Sparkline = Sparkline; // TODO: move under abstract interface

// VARIABLES //

var KEYS = getKeys( NS );

// MAIN //

/**
* Assigns modules to a namespace.
*
* @private
* @param {Object} ns - namespace
* @returns {Object} input namespace
*
* @example
* var ns = {};
* assign( ns );
* // ns => {...}
*/
function assign( ns ) {
	var key;
	var i;
	for ( i = 0; i < KEYS.length; i++ ) {
		key = KEYS[ i ];
		ns[ key ] = NS[ key ];
	}
	return ns;
} // end FUNCTION assign()

// EXPORTS //

module.exports = assign;
<commit_msg>Fix lint errors<commit_after>'use strict';

// MODULES //

var getKeys = require( 'object-keys' ).shim();
var isObject = require( '@stdlib/utils/is-plain-object' );
var hasOwnProp = require( '@stdlib/utils/has-own-property' );
var copy = require( '@stdlib/utils/copy' );
var Plot = require( '@stdlib/plot/plot' );
var Sparkline = require( '@stdlib/plot/sparklines/unicode/column' ); // FIXME: should be abstract interface

// VARIABLES //

var NS = {};
var KEYS;

// FUNCTIONS //

/**
* Wraps the plot API to provide a REPL specific `plot` function.
*
* @private
* @returns {Plot} Plot instance
*/
function plot() {
	var opts;
	var x;
	var y;
	var h;

	// Check for an `options` argument...
	if ( arguments.length === 0 ) {
		x = [];
		y = [];
	}
	else if ( arguments.length === 1 ) {
		x = [];
		y = [];
		opts = arguments[ 0 ];
		if ( !isObject( opts ) ) {
			throw new TypeError( 'invalid input argument. `options` argument must be an object. Value: `' + opts + '`.' );
		}
	}
	else if ( arguments.length === 2 ) {
		x = arguments[ 0 ];
		y = arguments[ 1 ];
	}
	else {
		x = arguments[ 0 ];
		y = arguments[ 1 ];
		opts = arguments[ 2 ];
		if ( !isObject( opts ) ) {
			throw new TypeError( 'invalid input argument. `options` argument must be an object. Value: `' + opts + '`.' );
		}
	}
	// Check for rendering and view options; if not set, set to REPL defaults...
	if ( opts ) {
		opts = copy( opts );
		if ( !hasOwnProp( opts, 'autoRender' ) ) {
			opts.autoRender = false;
		}
		if ( !hasOwnProp( opts, 'autoView' ) ) {
			opts.autoView = false;
		}
		if ( !hasOwnProp( opts, 'viewer' ) ) {
			opts.viewer = 'window';
		}
		h = new Plot( x, y, opts );
	} else {
		opts = {
			'autoRender': false,
			'autoView': false,
			'viewer': 'window'
		};
		h = new Plot( x, y, opts );
	}
	return h;
} // end FUNCTION plot()

// MAIN //

NS.plot = plot;
NS.Plot = Plot;
NS.Sparkline = Sparkline; // TODO: move under abstract interface

KEYS = getKeys( NS );

/**
* Assigns modules to a namespace.
*
* @private
* @param {Object} ns - namespace
* @returns {Object} input namespace
*
* @example
* var ns = {};
* assign( ns );
* // ns => {...}
*/
function assign( ns ) {
	var key;
	var i;
	for ( i = 0; i < KEYS.length; i++ ) {
		key = KEYS[ i ];
		ns[ key ] = NS[ key ];
	}
	return ns;
} // end FUNCTION assign()

// EXPORTS //

module.exports = assign;
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var isObject = require( '@stdlib/utils/is-plain-object' );
var hasOwnProp = require( '@stdlib/utils/has-own-property' );
var isBoolean = require( '@stdlib/utils/is-boolean' ).isPrimitive;
var isFunction = require( '@stdlib/utils/is-function' );
var isPositiveInteger = require( '@stdlib/utils/is-positive-integer' ).isPrimitive;

// MAIN //

/**
* Validates function options.
*
* @private
* @param {Object} opts - destination object
* @param {Options} options - options to validate
* @param {number} [options.level] - merge level
* @param {boolean} [options.copy] - boolean indicating whether to deep copy merged values
* @param {(boolean|Function)} [options.override] - defines the merge strategy
* @param {boolean} [options.extend] - boolean indicating whether new properties can be added to the target object
* @returns {(Error|null)} error object or null
*/
function validate( opts, options ) {
	if ( !isObject( options ) ) {
		return new TypeError( 'invalid input argument. Options argument must be an object. Value: `' + options + '`.' );
	}
	if ( hasOwnProp( options, 'level' ) ) {
		opts.level = options.level;
		if ( !isPositiveInteger( opts.level ) ) {
			return new TypeError( 'invalid option. `level` option must be a positive integer. Option: `' + opts.level + '`.' );
		}
	}
	if ( hasOwnProp( options, 'copy' ) ) {
		opts.copy = options.copy;
		if ( !isBoolean( opts.copy ) )  {
			return new TypeError( 'invalid option. `copy` option must be a boolean primitive. Option: `' + opts.copy + '`.' );
		}
	}
	if ( hasOwnProp( options, 'override' ) ) {
		opts.override = options.override;
		if (
			!isBoolean( opts.override ) &&
			!isFunction( opts.override )
		) {
			return new TypeError( 'invalid option. `override` option must be either a boolean primitive or a function. Option: `' + opts.override + '`.' );
		}
	}
	if ( hasOwnProp( options, 'extend' ) ) {
		opts.extend = options.extend;
		if ( !isBoolean( opts.extend ) ) {
			return new TypeError( 'invalid option. `extend` option must be a boolean primitive. Option: `' + opts.extend + '`.' );
		}
	}
	return null;
} // end FUNCTION validate()

// EXPORTS //

module.exports = validate;
<commit_msg>Remove extra space<commit_after>'use strict';

// MODULES //

var isObject = require( '@stdlib/utils/is-plain-object' );
var hasOwnProp = require( '@stdlib/utils/has-own-property' );
var isBoolean = require( '@stdlib/utils/is-boolean' ).isPrimitive;
var isFunction = require( '@stdlib/utils/is-function' );
var isPositiveInteger = require( '@stdlib/utils/is-positive-integer' ).isPrimitive;

// MAIN //

/**
* Validates function options.
*
* @private
* @param {Object} opts - destination object
* @param {Options} options - options to validate
* @param {number} [options.level] - merge level
* @param {boolean} [options.copy] - boolean indicating whether to deep copy merged values
* @param {(boolean|Function)} [options.override] - defines the merge strategy
* @param {boolean} [options.extend] - boolean indicating whether new properties can be added to the target object
* @returns {(Error|null)} error object or null
*/
function validate( opts, options ) {
	if ( !isObject( options ) ) {
		return new TypeError( 'invalid input argument. Options argument must be an object. Value: `' + options + '`.' );
	}
	if ( hasOwnProp( options, 'level' ) ) {
		opts.level = options.level;
		if ( !isPositiveInteger( opts.level ) ) {
			return new TypeError( 'invalid option. `level` option must be a positive integer. Option: `' + opts.level + '`.' );
		}
	}
	if ( hasOwnProp( options, 'copy' ) ) {
		opts.copy = options.copy;
		if ( !isBoolean( opts.copy ) ) {
			return new TypeError( 'invalid option. `copy` option must be a boolean primitive. Option: `' + opts.copy + '`.' );
		}
	}
	if ( hasOwnProp( options, 'override' ) ) {
		opts.override = options.override;
		if (
			!isBoolean( opts.override ) &&
			!isFunction( opts.override )
		) {
			return new TypeError( 'invalid option. `override` option must be either a boolean primitive or a function. Option: `' + opts.override + '`.' );
		}
	}
	if ( hasOwnProp( options, 'extend' ) ) {
		opts.extend = options.extend;
		if ( !isBoolean( opts.extend ) ) {
			return new TypeError( 'invalid option. `extend` option must be a boolean primitive. Option: `' + opts.extend + '`.' );
		}
	}
	return null;
} // end FUNCTION validate()

// EXPORTS //

module.exports = validate;
<|endoftext|>


<commit_before>import React from 'react';

import { RaisedButton, SelectField, MenuItem } from 'material-ui';
import Select from 'react-select';

export const RequestActions = ({ onCancel, onSave, onChange, scenarios, mocked, selectedScenario }) => {

  const scenarioList = scenarios.map((scenario) => ({ label: scenario.name, value: scenario.id }));

  const saveButtonLabel = mocked ? 'Save' : 'Mock';

  return (

        <Select value={ selectedScenario }
                options={ scenarioList }
                onChange={ onChange }
                clearable={ false }/>

        <RaisedButton label="Cancel" secondary={ true } onClick={ onCancel }/>

        <RaisedButton label={ saveButtonLabel } primary={ true } onClick={ onSave }/>

  );
}
<commit_msg>fix request actions buttons positions<commit_after>import React from 'react';

import { RaisedButton, SelectField, MenuItem } from 'material-ui';
import Select from 'react-select';

export const RequestActions = ({ onCancel, onSave, onChange, scenarios, mocked, selectedScenario }) => {

  const scenarioList = scenarios.map((scenario) => ({ label: scenario.name, value: scenario.id }));

  const saveButtonLabel = mocked ? 'Save' : 'Mock';

  return (

        <Select value={ selectedScenario }
                options={ scenarioList }
                onChange={ onChange }
                clearable={ false }/>

            <RaisedButton label="Cancel" secondary={ true } onClick={ onCancel }/>

            <RaisedButton label={ saveButtonLabel } primary={ true } onClick={ onSave }/>

  );
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies
 */
var acl = require('acl');

// Using the memory backend
acl = new acl(new acl.memoryBackend());

/**
 * Invoke Films Permissions
 */
exports.invokeRolesPolicies = function () {
  acl.allow([{
    roles: ['admin'],
    allows: [{
      resources: '/api/films',
      permissions: '*'
    }, {
      resources: '/api/films/:filmId',
      permissions: '*'
    }, {
      resource: '/api/scrapper',
      permission: ['get', 'post']
    }]
  }, {
    roles: ['user'],
    allows: [{
      resources: '/api/films',
      permissions: ['get', 'post']
    }, {
      resources: '/api/films/:filmId',
      permissions: ['get']
    }]
  }, {
    roles: ['guest'],
    allows: [{
      resources: '/api/films',
      permissions: ['get']
    }, {
      resources: '/api/films/:filmId',
      permissions: ['get']
    }]
  }]);
};

/**
 * Check If Films Policy Allows
 */
exports.isAllowed = function (req, res, next) {
  var roles = (req.user) ? req.user.roles : ['guest'];

  // If an Film is being processed and the current user created it then allow any manipulation
  if (req.film && req.user && req.film.user && req.film.user.id === req.user.id) {
    return next();
  }

  // Check for user roles
  acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function (err, isAllowed) {
    if (err) {
      // An authorization error occurred
      return res.status(500).send('Unexpected authorization error');
    } else {
      if (isAllowed) {
        // Access granted! Invoke next middleware
        return next();
      } else {
        return res.status(403).json({
          message: 'User is not authorized'
        });
      }
    }
  });
};
<commit_msg>poprawka błędu acl<commit_after>'use strict';

/**
 * Module dependencies
 */
var acl = require('acl');

// Using the memory backend
acl = new acl(new acl.memoryBackend());

/**
 * Invoke Films Permissions
 */
exports.invokeRolesPolicies = function () {
  acl.allow([{
    roles: ['admin'],
    allows: [{
      resources: '/api/films',
      permissions: '*'
    }, {
      resources: '/api/films/:filmId',
      permissions: '*'
    }, {
      resources: '/api/scrapper',
      permissions: ['get', 'post']
    }]
  }, {
    roles: ['user'],
    allows: [{
      resources: '/api/films',
      permissions: ['get', 'post']
    }, {
      resources: '/api/films/:filmId',
      permissions: ['get']
    }]
  }, {
    roles: ['guest'],
    allows: [{
      resources: '/api/films',
      permissions: ['get']
    }, {
      resources: '/api/films/:filmId',
      permissions: ['get']
    }]
  }]);
};

/**
 * Check If Films Policy Allows
 */
exports.isAllowed = function (req, res, next) {
  var roles = (req.user) ? req.user.roles : ['guest'];

  // If an Film is being processed and the current user created it then allow any manipulation
  if (req.film && req.user && req.film.user && req.film.user.id === req.user.id) {
    return next();
  }

  // Check for user roles
  acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function (err, isAllowed) {
    if (err) {
      // An authorization error occurred
      return res.status(500).send('Unexpected authorization error');
    } else {
      if (isAllowed) {
        // Access granted! Invoke next middleware
        return next();
      } else {
        return res.status(403).json({
          message: 'User is not authorized'
        });
      }
    }
  });
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var acl = require('acl');

// Using the memory backend
acl = new acl(new acl.memoryBackend());

/**
 * Invoke Admin Permissions
 */
exports.invokeRolesPolicies = function () {
  acl.allow([{
    roles: ['admin', 'user'],
    allows: [{
      resources: '/api/users',
      permissions: '*'
    }, {
      resources: '/api/users/:userId',
      permissions: '*'
    }, {
      resources: '/api/games',
      permissions: '*'
    }, {
      resources: '/api/games/:gameId',
      permissions: '*'
    }]
  }]);
};

/**
 * Check If Admin Policy Allows
 */
exports.isAllowed = function (req, res, next) {
  var roles = (req.user) ? req.user.roles : ['guest'];

  // Check for user roles
  acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function (err, isAllowed) {
    if (err) {
      // An authorization error occurred.
      return res.status(500).send('Unexpected authorization error');
    } else {
      if (isAllowed) {
        // Access granted! Invoke next middleware
        return next();
      } else {
        return res.status(403).json({
          message: 'User is not authorized'
        });
      }
    }
  });
};
<commit_msg>fixed permission for game<commit_after>'use strict';

/**
 * Module dependencies.
 */
var acl = require('acl');

// Using the memory backend
acl = new acl(new acl.memoryBackend());

/**
 * Invoke Admin Permissions
 */
exports.invokeRolesPolicies = function () {
  acl.allow([{
    roles: ['admin', 'user'],
    allows: [{
      resources: '/api/users',
      permissions: '*'
    }, {
      resources: '/api/users/:userId',
      permissions: '*'
    }, {
      resources: '/api/games',
      permissions: '*'
    }, {
      resources: '/api/games/:gameID',
      permissions: '*'
    }]
  }]);
};

/**
 * Check If Admin Policy Allows
 */
exports.isAllowed = function (req, res, next) {
  var roles = (req.user) ? req.user.roles : ['guest'];

  // Check for user roles
  acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function (err, isAllowed) {
    if (err) {
      // An authorization error occurred.
      return res.status(500).send('Unexpected authorization error');
    } else {
      if (isAllowed) {
        // Access granted! Invoke next middleware
        return next();
      } else {
        return res.status(403).json({
          message: 'User is not authorized'
        });
      }
    }
  });
};
<|endoftext|>


<commit_before>var MongoClient = require('mongodb').MongoClient,
    assert = require('assert');
var exec = require('child_process').exec,
    execSync = require('child_process').execSync,
    fs = require('fs'),
    log4js = require('log4js'),
    logger = log4js.getLogger('Core'),
    config = require('config'),
    App = require('./class/app.js').App;

var accessDB = function(appVersion, outputDir, dest, htmlPath, newhtmlPATH, tempCommentPath) {
  var hostName = config.get('dbConfig.host'),
      portNumber = config.get('dbConfig.port'),
      dbName = config.get('dbConfig.db'),
      collectionName = config.get('dbConfig.collection');
  var mongoURL = 'mongodb://' + hostName + ':' + portNumber + '/' + dbName;

  MongoClient.connect(mongoURL, function(err, db) {
    assert.equal(null, err);
    logger.info("accessDB::Connected correctly to server for " + appVersion.name + "-" + appVersion.verc);

    var collection = db.collection(collectionName);
    findDoc(db, collection, appVersion, function(results) {
      if (results.length === 0) {
        insertDoc(db, collection, appVersion, function() {
          makenewCOMMAND = "mkdir -p " + appVersion.path;
          exec(makenewCOMMAND, function(error, stdout, stderr) {
            if (stderr) {
              logger.error("accessDB::Making new directory failed for " + appVersion.path);
              return logger.error("Core:accessDB::" + stderr);
            }
            logger.info("accessDB::Successfully made directory " + appVersion.path);
          });

          moveCOMMAND = "mv " + dest + ' ' + appVersion.path + appVersion.name + '-' + appVersion.verc + '.apk';
          exec(moveCOMMAND, function(error, stdout, stderr) {
            if (stderr) {
              logger.error("accessDB::Moving " + dest + " to " + appVersion.path + " failed");
              return logger.error("accessDB::" + stderr);
            }
            logger.info("accessDB::Moved APK to " + appVersion.path);
          });

          if (fs.existsSync(htmlPath)) {
            moveHTMLCOMMAND = "mv " + htmlPath + ' ' + newhtmlPATH + appVersion.name + '.html';
            exec(moveHTMLCOMMAND, function(error, stdout, stderr) {
              if (stderr) {
                return logger.error("accessDB::" + stderr);
              }
              logger.info("accessDB::" + stdout);

              if (tempCommentPath != null) {
                moveCommentCOMMAND = "mv " + tempCommentPath + ' ' + newhtmlPATH + appVersion.name + '-' + appVersion.verc + '.json5';
                exec(moveCommentCOMMAND, function(error, stdout, stderr) {
                  if (stderr) {
                    return logger.error("accessDB::" + stderr);
                  }
                  logger.info("accessDB::" + stdout);
                });
              }
            });
          }
          else {
            db.close();
            return logger.error("accessDB::" + htmlPath + " doesn't exist")
          }

          db.close();
        })
      }
      else {
        logger.warn("accessDB::APK already exists for " + appVersion.name + "-" + appVersion.verc);

        DELETEJSON = "rm " + tempCommentPath;
        try {
          var error, stderr, stdout = execSync(DELETEJSON);
          if (stderr) { logger.error("accessDB::" + stderr); }
          logger.debug("accessDB::Deleted JSON5: " + tempCommentPath);
        }
        catch (ex) {
          logger.error("accessDB::Deleting the JSON5 failed for " + tempCommentPath);
          return logger.error("accessDB::" + ex);
        }

        DELETEHTML = "rm " + htmlPath;
        exec(DELETEHTML, function(error, stdout, stderr) {
          if (stderr) {
            logger.error("accessDB::Deleting the HTML failed for " + appVersion.name + "-" + appVersion.verc)
            return logger.error("accessDB::" + stderr);
          }
          COMMAND = "rm " + dest;
          exec(COMMAND, function(error, stdout, stderr) {
            if (stderr) {
              logger.error("accessDB::Deleting the APK failed for " + appVersion.name + "-" + appVersion.verc);
              return logger.error("accessDB::" + stderr);
            }
          });
        });
        db.close();
      }
    })
  });
}
var insertDoc = function(db, collection, appVersion, callback) {
  collection.insert({'n': appVersion.name, 'vc': appVersion.verc, 'p': appVersion.path}, function(err, r) {
    assert.equal(err, null);
    callback();
  });
}

var findDoc = function(db, collection, appVersion, callback) {
  collection.find({'n': appVersion.name, 'vc': appVersion.verc }).toArray(function(err, docs) {
    assert.equal(err, null);
    callback(docs);
  });
}

module.exports = accessDB;
<commit_msg>More synchronous tasks<commit_after>var MongoClient = require('mongodb').MongoClient,
    assert = require('assert');
var exec = require('child_process').exec,
    execSync = require('child_process').execSync,
    fs = require('fs'),
    log4js = require('log4js'),
    logger = log4js.getLogger('Core'),
    config = require('config'),
    App = require('./class/app.js').App;

var accessDB = function(appVersion, outputDir, dest, htmlPath, newhtmlPATH, tempCommentPath) {
  var hostName = config.get('dbConfig.host'),
      portNumber = config.get('dbConfig.port'),
      dbName = config.get('dbConfig.db'),
      collectionName = config.get('dbConfig.collection');
  var mongoURL = 'mongodb://' + hostName + ':' + portNumber + '/' + dbName;

  MongoClient.connect(mongoURL, function(err, db) {
    assert.equal(null, err);
    logger.info("accessDB::Connected correctly to server for " + appVersion.name + "-" + appVersion.verc);

    var collection = db.collection(collectionName);
    findDoc(db, collection, appVersion, function(results) {
      if (results.length === 0) {
        insertDoc(db, collection, appVersion, function() {
          makenewCOMMAND = "mkdir -p " + appVersion.path;
          exec(makenewCOMMAND, function(error, stdout, stderr) {
            if (stderr) {
              logger.error("accessDB::Making new directory failed for " + appVersion.path);
              return logger.error("Core:accessDB::" + stderr);
            }
            logger.info("accessDB::Successfully made directory " + appVersion.path);
          });

          moveCOMMAND = "mv " + dest + ' ' + appVersion.path + appVersion.name + '-' + appVersion.verc + '.apk';
          try {
            var error, stderr, stdout = execSync(moveCOMMAND);
            if (stderr) { logger.error("accessDB::" + stderr); }

            logger.info("accessDB::Moved APK to " + appVersion.path);
          }
          catch (ex) {
            logger.error("accessDB::Moving " + dest + " to " + appVersion.path + " failed");
            return logger.error("accessDB::" + ex);
          }

          if (fs.existsSync(htmlPath)) {
            moveHTMLCOMMAND = "mv " + htmlPath + ' ' + newhtmlPATH + appVersion.name + '.html';
            exec(moveHTMLCOMMAND, function(error, stdout, stderr) {
              if (stderr) {
                return logger.error("accessDB::" + stderr);
              }

              if (tempCommentPath != null) {
                moveCommentCOMMAND = "mv " + tempCommentPath + ' ' + newhtmlPATH + appVersion.name + '-' + appVersion.verc + '.json5';
                exec(moveCommentCOMMAND, function(error, stdout, stderr) {
                  if (stderr) {
                    return logger.error("accessDB::" + stderr);
                  }
                });
              }
            });
          }
          else {
            db.close();
            return logger.error("accessDB::" + htmlPath + " doesn't exist")
          }

          db.close();
        })
      }
      else {
        logger.warn("accessDB::APK already exists for " + appVersion.name + "-" + appVersion.verc);

        DELETEJSON = "rm " + tempCommentPath;
        try {
          var error, stderr, stdout = execSync(DELETEJSON);
          if (stderr) { logger.error("accessDB::" + stderr); }
        }
        catch (ex) {
          logger.error("accessDB::Deleting the JSON5 failed for " + tempCommentPath);
          return logger.error("accessDB::" + ex);
        }

        DELETEHTML = "rm " + htmlPath;
        exec(DELETEHTML, function(error, stdout, stderr) {
          if (stderr) {
            logger.error("accessDB::Deleting the HTML failed for " + appVersion.name + "-" + appVersion.verc)
            return logger.error("accessDB::" + stderr);
          }
          COMMAND = "rm " + dest;
          exec(COMMAND, function(error, stdout, stderr) {
            if (stderr) {
              logger.error("accessDB::Deleting the APK failed for " + appVersion.name + "-" + appVersion.verc);
              return logger.error("accessDB::" + stderr);
            }
          });
        });
        db.close();
      }
    })
  });
}
var insertDoc = function(db, collection, appVersion, callback) {
  collection.insert({'n': appVersion.name, 'vc': appVersion.verc, 'p': appVersion.path}, function(err, r) {
    assert.equal(err, null);
    callback();
  });
}

var findDoc = function(db, collection, appVersion, callback) {
  collection.find({'n': appVersion.name, 'vc': appVersion.verc }).toArray(function(err, docs) {
    assert.equal(err, null);
    callback(docs);
  });
}

module.exports = accessDB;
<|endoftext|>


<commit_before>var pg = require('pg');

function connect(callback) {
  pg.connect(process.env.DATABASE_URL, function(error, client, done) {
    if(error) {
      console.log(error);
    } else {
      callback(client, done);
    }
  });
}

function perform_query(query, handler) {
  connect(function(client, done) {
    _recursive_queries(client, [[query, handler]], done);
  });
}

function perform_queries(queries) {
  connect(function(client, done) {
    _recursive_queries(client, queries, done);
  });
}

function perform_queries_async(queries) {
  var client = new pg.Client(process.env.DATABASE_URL);

  queries.forEach(function(q) {
    if((typeof q) === 'string') {
      q = [q, function(r) { return undefined; }];
    }

    console.log("queued a query: " + q[0]);
    client.query(q[0], function(err, result) {
      if(err) {
        console.log(err);
      } else {
        q[1](result);
      }
    });
  });

  client.on('drain', function() {
    console.log("drained");
    client.end();
  });

  client.connect();
}

function _recursive_queries(client, queries, done) {
  var q = queries.shift();

  var query
  var handler;

  if((typeof q) === 'string') {
    q = [q, function(r) { return undefined; }];
  }

  _query(client, q[0], function(result) {
    if(queries.length == 0) {
      done();
    } else {
      _recursive_queries(client, queries, done);
    }

    q[1](result);
  });
}

function _query(client, query, handler) {
  client.query(query, function(err, result) {
    if(err) {
      console.log(err);
    } else {
      handler(result);
    }
  });
}

exports.perform_query = perform_query;
exports.perform_queries = perform_queries;
exports.perform_queries_async = perform_queries_async;<commit_msg>Added reference to StackOverflow question about looping in db.js<commit_after>var pg = require('pg');

function connect(callback) {
  pg.connect(process.env.DATABASE_URL, function(error, client, done) {
    if(error) {
      console.log(error);
    } else {
      callback(client, done);
    }
  });
}

function perform_query(query, handler) {
  connect(function(client, done) {
    _recursive_queries(client, [[query, handler]], done);
  });
}

function perform_queries(queries) {
  connect(function(client, done) {
    _recursive_queries(client, queries, done);
  });
}

function perform_queries_async(queries) {
  var client = new pg.Client(process.env.DATABASE_URL);

  // http://stackoverflow.com/questions/20038825/asynchronous-database-queries-with-postgresql-in-node-not-working
  queries.forEach(function(q) {
    if((typeof q) === 'string') {
      q = [q, function(r) { return undefined; }];
    }

    console.log("queued a query: " + q[0]);
    client.query(q[0], function(err, result) {
      if(err) {
        console.log(err);
      } else {
        q[1](result);
      }
    });
  });

  client.on('drain', function() {
    console.log("drained");
    client.end();
  });

  client.connect();
}

function _recursive_queries(client, queries, done) {
  var q = queries.shift();

  var query
  var handler;

  if((typeof q) === 'string') {
    q = [q, function(r) { return undefined; }];
  }

  _query(client, q[0], function(result) {
    if(queries.length == 0) {
      done();
    } else {
      _recursive_queries(client, queries, done);
    }

    q[1](result);
  });
}

function _query(client, query, handler) {
  client.query(query, function(err, result) {
    if(err) {
      console.log(err);
    } else {
      handler(result);
    }
  });
}

exports.perform_query = perform_query;
exports.perform_queries = perform_queries;
exports.perform_queries_async = perform_queries_async;<|endoftext|>