<commit_before>(function(root) {

  'use strict';

  var availity = root.availity;

  availity.ui.constant('AV_UI_IDLE', {
    TEMPLATES: {
      BASE: 'ui/idle/idle-tpl.html',
      SESSION: 'ui/idle/idle-session-tpl.html',
      WARNING: 'ui/idle/idle-warning-tpl.html'
    }
  });

  availity.ui.provider('avIdleNotifier', function() {

    var sessionTemplate;
    var warningTemplate;
    var $scope;

    this.setSessionTemplate = function(template) {
      sessionTemplate = template;
    };

    this.setWarningTemplate = function(template) {
      warningTemplate = template;
    };

    this.$get = function(AV_IDLE, AV_UI_IDLE, $rootScope, AvModal, $document, $timeout) {

      var AvIdleNotifier = function() {
        this.listeners = [];
        this.modal = null;
      };

      var proto = AvIdleNotifier.prototype;

      proto.init = function() {

        $scope = $rootScope.$new(true);
        $scope.idle = {};

        this.initListeners();
      };

      proto.initListeners = function() {

        var self = this;
        var listener = null;

        // ACTIVATE
        listener = $rootScope.$on(AV_IDLE.EVENTS.ACTIVE, function() {
          self.showWarning();
        });
        this.listeners.push(listener);

        // INACTIVE
        listener = $rootScope.$on(AV_IDLE.EVENTS.INACTIVE, function() {
          self.hideWarning();
        });
        this.listeners.push(listener);

        // SESSION TIMEOUT
        listener = $rootScope.$on(AV_IDLE.EVENTS.SESSION_TIMEOUT_ACTIVE, function() {
          self.showSession();
        });
        this.listeners.push(listener);

      };

      proto.destroyListeners = function() {
        // turn off each listener => http://stackoverflow.com/a/14898795
        _.each(this.listeners, function(listener) {
          listener();
        });
      };

      proto.showWarning = function() {

        var self = this;

        if(this.modal !== null) {
          return;
        }

        $scope = $rootScope.$new(true);
        $scope.idle = {};
        $scope.idle.template = AV_UI_IDLE.TEMPLATES.WARNING;

        this.modal = new AvModal({
          show: true,
          scope: $scope,
          backdrop: 'static',
          template: AV_UI_IDLE.TEMPLATES.BASE
        });

        $document.on('click', function() {
          self.hideWarning();
          $rootScope.$broadcast(AV_IDLE.EVENTS.INACTIVE);
        });

      };

      proto.hideWarning = function() {
        this.disableBackDrop();

        if(this.modal) {
          this.modal.destroy();
        }

        this.modal = null;
      };

      proto.disableBackDrop = function() {
        $document.off('click');
      };

      proto.showSession = function() {
        var self = this;
        this.disableBackDrop();

        $timeout(function() {
          $scope.idle.template = AV_UI_IDLE.TEMPLATES.SESSION;
          $scope.idle.onSessionInactive = self.onSessionInactive;
        }, 0, true);

      };

      proto.onSessionInactive = function() {
        debugger;
        $rootScope.$broadcast(AV_IDLE.EVENTS.SESSION_TIMEOUT_INACTIVE);
      };

      return new AvIdleNotifier();

    };

  });

  availity.ui.run(function(avIdleNotifier) {
    avIdleNotifier.init();
  });

})(window);
<commit_msg>remove debugger<commit_after>(function(root) {

  'use strict';

  var availity = root.availity;

  availity.ui.constant('AV_UI_IDLE', {
    TEMPLATES: {
      BASE: 'ui/idle/idle-tpl.html',
      SESSION: 'ui/idle/idle-session-tpl.html',
      WARNING: 'ui/idle/idle-warning-tpl.html'
    }
  });

  availity.ui.provider('avIdleNotifier', function() {

    var sessionTemplate;
    var warningTemplate;
    var $scope;

    this.setSessionTemplate = function(template) {
      sessionTemplate = template;
    };

    this.setWarningTemplate = function(template) {
      warningTemplate = template;
    };

    this.$get = function(AV_IDLE, AV_UI_IDLE, $rootScope, AvModal, $document, $timeout) {

      var AvIdleNotifier = function() {
        this.listeners = [];
        this.modal = null;
      };

      var proto = AvIdleNotifier.prototype;

      proto.init = function() {

        $scope = $rootScope.$new(true);
        $scope.idle = {};

        this.initListeners();
      };

      proto.initListeners = function() {

        var self = this;
        var listener = null;

        // ACTIVATE
        listener = $rootScope.$on(AV_IDLE.EVENTS.ACTIVE, function() {
          self.showWarning();
        });
        this.listeners.push(listener);

        // INACTIVE
        listener = $rootScope.$on(AV_IDLE.EVENTS.INACTIVE, function() {
          self.hideWarning();
        });
        this.listeners.push(listener);

        // SESSION TIMEOUT
        listener = $rootScope.$on(AV_IDLE.EVENTS.SESSION_TIMEOUT_ACTIVE, function() {
          self.showSession();
        });
        this.listeners.push(listener);

      };

      proto.destroyListeners = function() {
        // turn off each listener => http://stackoverflow.com/a/14898795
        _.each(this.listeners, function(listener) {
          listener();
        });
      };

      proto.showWarning = function() {

        var self = this;

        if(this.modal !== null) {
          return;
        }

        $scope = $rootScope.$new(true);
        $scope.idle = {};
        $scope.idle.template = AV_UI_IDLE.TEMPLATES.WARNING;

        this.modal = new AvModal({
          show: true,
          scope: $scope,
          backdrop: 'static',
          template: AV_UI_IDLE.TEMPLATES.BASE
        });

        $document.on('click', function() {
          self.hideWarning();
          $rootScope.$broadcast(AV_IDLE.EVENTS.INACTIVE);
        });

      };

      proto.hideWarning = function() {
        this.disableBackDrop();

        if(this.modal) {
          this.modal.destroy();
        }

        this.modal = null;
      };

      proto.disableBackDrop = function() {
        $document.off('click');
      };

      proto.showSession = function() {
        var self = this;
        this.disableBackDrop();

        $timeout(function() {
          $scope.idle.template = AV_UI_IDLE.TEMPLATES.SESSION;
          $scope.idle.onSessionInactive = self.onSessionInactive;
        }, 0, true);

      };

      proto.onSessionInactive = function() {
        $rootScope.$broadcast(AV_IDLE.EVENTS.SESSION_TIMEOUT_INACTIVE);
      };

      return new AvIdleNotifier();

    };

  });

  availity.ui.run(function(avIdleNotifier) {
    avIdleNotifier.init();
  });

})(window);
<|endoftext|>


<commit_before>var Input = require('react-bootstrap').Input,
    React = require('react'),
    BaseWidget = require('../widgets/basewidget'),
    _ = require('lodash');

/**
 * WidgetRow
 *
 * WidgetRow is a React Component rendering a table row displaying widget
 * information.
 *
 * @widget: An object implementing the BaseWidget interface as defined in
 *   ../widgets/basewidget.js
 */
var WidgetRow = React.createClass({
  propTypes: {
    widget: React.PropTypes.instanceOf(BaseWidget).isRequired
  },

  render: function() {
    var rowStyle = {
      verticalAlign: 'middle',
      height: '16vh',
      width: '30vw'
    };

    var paths =
      this.props.widget.getHandledSources().map(function(source, i) {
        return
{source.path.replace(/\./g, '.' + String.fromCharCode(8203))} ({source.sourceId})

      });

    return (

          <Input type="checkbox" label="Visible"
            checked={this.props.widget.options.active}
            onChange={this.toggleActive} />

{this.props.widget.getType()}

          {paths}

            {this.props.widget.getReactElement()}

            {this.props.widget.getSettingsElement()}

    );
  },

  toggleActive: function() {
    this.props.widget.setActive(!this.props.widget.options.active);
  }
});

module.exports = WidgetRow;
<commit_msg>Fix key issue correctly<commit_after>var Input = require('react-bootstrap').Input,
    React = require('react'),
    BaseWidget = require('../widgets/basewidget'),
    _ = require('lodash');

/**
 * WidgetRow
 *
 * WidgetRow is a React Component rendering a table row displaying widget
 * information.
 *
 * @widget: An object implementing the BaseWidget interface as defined in
 *   ../widgets/basewidget.js
 */
var WidgetRow = React.createClass({
  propTypes: {
    widget: React.PropTypes.instanceOf(BaseWidget).isRequired
  },

  render: function() {
    var rowStyle = {
      verticalAlign: 'middle',
      height: '16vh',
      width: '30vw'
    };

    var paths =
      this.props.widget.getHandledSources().map(function(source, i) {
        return
{source.path.replace(/\./g, '.' + String.fromCharCode(8203))} ({source.sourceId})

      });
    return (

          <Input type="checkbox" label="Visible"
            checked={this.props.widget.options.active}
            onChange={this.toggleActive} />

{this.props.widget.getType()}

          {paths}

            {this.props.widget.getReactElement()}

            {this.props.widget.getSettingsElement()}

    );
  },

  toggleActive: function() {
    this.props.widget.setActive(!this.props.widget.options.active);
  }
});

module.exports = WidgetRow;
<|endoftext|>


<commit_before>/**
 * Adds methods to one object that proxy to another.
 */
function addProxyMethods(target, source, methods, chainable) {
  for (var i = 0, len = methods.length; i < len; i++) {
    var method = methods[i];
    target[method] = (function(method) {
      return function() {
        var result = source[method].apply(source, arguments);
        return chainable ? this : result;
      };
    })(method);
  }
}

module.exports = addProxyMethods;
<commit_msg>Remove unused addProxyMethods util<commit_after><|endoftext|>


<commit_before>var hivesvg, hiveTooltip;
function createHiveplot(data, container) {
    var width = 1200,
        height = 1000,
        innerRadius = 0.15*(height*0.9),
        outerRadius = 0.42*(height*0.9);

    var angleLineCore = d3.scale.ordinal()
                      .domain(d3.range(71))
                      .rangePoints([2 * Math.PI, 0]),
        radius = d3.scale.linear()
                  .range([innerRadius, outerRadius]),
        color = d3.scale.category10()
                  .domain(d3.range(20));

        var angle = function(e){
          // TODO optimize placement of TMs based on angle, but possibly also starting position
          //matching = [1.8, 2.8, 4.2, 5, 5.7, 6.8, 0.5];
          //return angleLineCore( matching[e] * 10);

          return angleLineCore( ((e+0.5) % 7) * 10);
        };
        var angleLine = function(e){
          return angleLineCore( (e+5) % 70 );
        };

    // create TM residue count
    // replace later with data.segments
    var TM_segments = ["TM1", "TM2", "TM3", "TM4", "TM5", "TM6", "TM7"];
    var resCount = [];
    for (var i = 0; i < 7; i++)
        resCount[i] = 0;
    var currentCount = resCount.slice(0);

    // count residues in each segment
    for (key in data.segment_map){
        var index = TM_segments.indexOf(data.segment_map[key]);
        if (index >= 0)
            resCount[index] += 1;
    }

    // x is TM number - 1 and y is ordered position in TM
    var nodes = [];
    var indexList = Object.assign({}, data.generic_map);
    for (residue in data.generic_map){
      // residue contains original number
      // data.generic_map[residue] contains GN
      var gn = data.generic_map[residue].split('x');
      var tm = gn[0];
      var position = gn[1];
      if (tm <= 7){
          currentCount[tm-1] += 1;
          // Reverse upward helices so EC in inside
          if ((tm % 2) == 1)
              nodes.push({x: tm-1, y: currentCount[tm-1], gn: data.generic_map[residue], number: residue});
          else
              nodes.push({x: tm-1, y: resCount[tm-1]-currentCount[tm-1]+1, gn: data.generic_map[residue], number: residue});
          indexList[residue] = nodes.length - 1;
      } else
          indexList[residue] = null;
    }

    // create links between nodes
    var links = [];
    for (contact in data.interactions){
        var pair = contact.split(',');
        var res1 = pair[0];
        var res2 = pair[1];
        // Create link if nodes will be drawn
        if (indexList[res1] != null && indexList[res2] != null) {
            // only is consecutive
            var tmDistance = Math.abs(nodes[indexList[res1]].x - nodes[indexList[res2]].x);
            if (tmDistance > 0) {
                if (tmDistance == 1 || tmDistance == 6)
                    links.push({source: nodes[indexList[res1]], target: nodes[indexList[res2]], consecutive: true, tmDistance: tmDistance});
                else
                    links.push({source: nodes[indexList[res1]], target: nodes[indexList[res2]], consecutive: false, tmDistance: tmDistance});
            }
        }
    }

    hiveTooltip = d3.select("body").append("div")
                  .style("display", "none")
                  .style("position", "absolute")
//                  .attr("class", "rounded")
                  .attr("id", "hiveTooltip");

    hivesvg = d3.select(container).append("svg")
        .attr("width", width)
        .attr("height", height)
      .append("g")
        .attr("transform", "translate(" + width/2 + "," + height/2 + ")");

    // draw lines based on length TM helix
    hivesvg.selectAll(".axis")
        .data(d3.range(7))
      .enter().append("line")
        .attr("class", "axis")
        .attr("transform", function(d) { return "rotate(" + degreesHP(angle(d)) + ")" })
        .attr("x1", innerRadius)
        .attr("x2", function(d) { return (outerRadius-innerRadius)/20*(resCount[d]+1)+innerRadius; });

    // draw links between nodes
    /*
    hivesvg.selectAll(".link")
        .data(links)
      .enter().append("path")
        .attr("class", "link")
        .attr("d", d3.hive.link()
          .angle(function(d) { return angle(d.x); })
          .radius(function(d) { return d.y*(outerRadius-innerRadius)/20+innerRadius; }))
        .style("stroke", function(d) { if (d.tmDistance == 6) return color(d.target.x); else return color(d.source.x); })
        .on("mouseover", linkMouseoverHP)
        .on("mouseout", mouseoutHP);*/
    var lineCore = d3.svg.line.radial()
        .interpolate( "bundle" )
        .tension( 0.85 )
        .radius(function(d) { return d.y*(outerRadius-innerRadius)/20+innerRadius; })
        .angle(function(d) { if (d.x < 0) d.x = 7 + d.x; return angleLine(Math.round(d.x*10)); });

    hivesvg.selectAll(".link")
        .data(links)
      .enter().append("path")
        .attr("class", "link")
        .attr("d", function(d, i) {
            var placer = 0.3;
            var margin = 10;
            if (d.tmDistance > 3)
                placer *= -1;
            var path = [d.source];
            path.push({x: d.source.x+placer, y: d.source.y});
            if (!d.consecutive) {
                var middle;
                var inside = true;
                if (d.tmDistance == 2 || d.tmDistance == 5)
                    inside = false;

                var via = 0;
                if (d.tmDistance > 3)
                    via = d.target.x + (7-d.tmDistance)/2;
                else
                    via = d.source.x + d.tmDistance/2;
                via = via % 7;

                // draw nice path outside or inside
                if (inside){
                    middle = {x: via, y: -1*margin/2};
                    path.push({x: middle.x - placer, y: middle.y + margin/3});
                    path.push(middle);
                    path.push({x: middle.x + placer, y: middle.y + margin/3});
                } else {
                    middle = {x: via, y: resCount[via] + margin };
                    path.push({x: middle.x - placer, y: middle.y - margin/2});
                    path.push(middle);
                    path.push({x: middle.x + placer, y: middle.y - margin/2});
                }
            }
            path.push({x: d.target.x-placer, y: d.target.y});
            path.push(d.target);

            return lineCore(path);
          })
        //.attr("d", d3.hive.link()
        //  .angle(function(d) { return angle(d.x); })
        //  .radius(function(d) { return d.y*(outerRadius-innerRadius)/20+innerRadius; }))
        .style("stroke", function(d) { if (d.tmDistance == 6) return color(d.target.x); else return color(d.source.x); })
        .on("mouseover", linkMouseoverHP)
        .on("mouseout", mouseoutHP);

    // draw nodes
    hivesvg.selectAll(".node")
        .data(nodes)
      .enter().append("circle")
        .attr("class", "node")
        .attr("transform", function(d) { return "rotate(" + degreesHP(angle(d.x)) + ")"; })
        .attr("cx", function(d) {return d.y*(outerRadius-innerRadius)/20+innerRadius; })
        .attr("r", 5)
        .style("fill", function(d) { return color(d.x); })
        .on("mouseover", nodeMouseoverHP)
        .on("mouseout", mouseoutHP)
// fix nice bootstrap tooltips
//        .each(function(d,i){ console.log("enable for "+d.gn);$(this).tooltip({title: d.gn + " (" + d.number + ")", html: false, placement: 'bottom', container: 'body'});});
}

// Based on Mike Bostock's example: https://bl.ocks.org/mbostock/2066415
// highlight link and connected nodes on mouseover
function linkMouseoverHP(d) {
  hivesvg.selectAll(".link")
    .classed("turnedOn", function(dl) {
      return dl === d;
    })
    .classed("turnedOff", function(dl) {
      return !(dl === d);
    })
  hivesvg.selectAll(".node")
    .classed("turnedOn", function(dl) {
      return dl === d.source || dl === d.target;
    })
}

// highlight node and connected links on mouseover
function nodeMouseoverHP(d) {
  hivesvg.selectAll(".link")
    .classed("turnedOn", function(dl) {
      return dl.source === d || dl.target === d;
    })
    .classed("turnedOff", function(dl) {
      return !(dl.source === d || dl.target === d)
    });
  d3.select(this)
    .classed("turnedOn", true);

  // show hiveTooltip
  hiveTooltip.style("display", "block")
               .style("left",(d3.event.pageX+20)+"px")
               .style("top",(d3.event.pageY+10)+"px")
               .html(d.gn + " (" + d.number + ")");
}

// clear highlighted nodes or links
function mouseoutHP() {
  hivesvg.selectAll(".turnedOn").classed("turnedOn", false);
  hivesvg.selectAll(".turnedOff").classed("turnedOff", false);
  // hide hiveTooltip
  hiveTooltip.style("display", "none");
}

function degreesHP(radians) {
  return radians / Math.PI * 180 - 90;
}
<commit_msg>Added support for H8 and cleaned up. In commented logs draft for WebCola support (to be removed after testing).<commit_after>var hivesvg, hiveTooltip;
function createHiveplot(data, container) {
    var width = 1200,
        height = 1000,
        innerRadius = 0.15*(height),
        outerRadius = 0.36*(height);

    var angleLineCore = d3.scale.ordinal()
                      .domain(d3.range(71))
                      .rangePoints([2 * Math.PI, 0]),
        radius = d3.scale.linear()
                  .range([innerRadius, outerRadius]),
        color = d3.scale.category10()
                  .domain(d3.range(10));

        var angle = function(e){
          // TODO optimize placement of TMs based on angle, but possibly also starting position
          if (e >= 6.5)
            e = 6.5 + (e-7.0);
          else if (e < 0){
            e += 7;
          }

          return angleLineCore( (e*10+18) % 70 );
        };

    // create TM residue count
    // replace later with data.segments
    var TM_segments = ["TM1", "TM2", "TM3", "TM4", "TM5", "TM6", "TM7", "H8"];
    var resCount = [];
    for (var i = 0; i < 8; i++)
        resCount[i] = 0;
    var currentCount = resCount.slice(0);

    // count residues in each segment
    for (key in data.segment_map){
        var index = TM_segments.indexOf(data.segment_map[key]);
        if (index >= 0)
            resCount[index] += 1;
    }

    // x is TM number - 1 and y is ordered position in TM
    var nodes = [];
    var indexList = Object.assign({}, data.generic_map);
          var last = -1;
    for (residue in data.generic_map){
      // residue contains original number
      // data.generic_map[residue] contains GN
      var gn = data.generic_map[residue].split('x');
      var tm = gn[0];
      var position = gn[1];
      if (tm <= 8){
          currentCount[tm-1] += 1;
          // Reverse upward helices so EC in inside
          if (tm == 8 || (tm % 2) == 1)
              nodes.push({x: tm-1, y: currentCount[tm-1], gn: data.generic_map[residue], number: residue});
          else
              nodes.push({x: tm-1, y: resCount[tm-1]-currentCount[tm-1]+1, gn: data.generic_map[residue], number: residue});
          indexList[residue] = nodes.length - 1;
          //console.log("{name: \"" + data.generic_map[residue] + "\", group:" + tm + "},");
//          if (last == tm)
//              console.log("{\"source\": " + (nodes.length - 2) + ", \"target\":" + (nodes.length - 1) + ", \"value\": 0},");
          last =  tm;
      } else
          indexList[residue] = null;
    }

    // create links between nodes
    var links = [];
    for (contact in data.interactions){
        var pair = contact.split(',');
        var res1 = pair[0];
        var res2 = pair[1];
        // Create link if nodes will be drawn
        if (indexList[res1] != null && indexList[res2] != null) {
            // only is consecutive
            var tmDistance = Math.abs(nodes[indexList[res1]].x - nodes[indexList[res2]].x);
            if (tmDistance > 0) {
                if (tmDistance == 1 || (tmDistance == 6 && nodes[indexList[res2]].x != 7) || tmDistance == 7)
                    links.push({source: nodes[indexList[res1]], target: nodes[indexList[res2]], consecutive: true, tmDistance: tmDistance});
                else
                    links.push({source: nodes[indexList[res1]], target: nodes[indexList[res2]], consecutive: false, tmDistance: tmDistance});
            }
//            console.log("{\"source\": " + (indexList[res1]) + ", \"target\":" + (indexList[res2]) + ", \"value\": 5},");
        }
    }

    hiveTooltip = d3.select("body").append("div")
                  .style("display", "none")
                  .style("position", "absolute")
//                  .attr("class", "rounded")
                  .attr("id", "hiveTooltip");

    hivesvg = d3.select(container).append("svg")
        .attr("width", width)
        .attr("height", height)
      .append("g")
        .attr("transform", "translate(" + width/2 + "," + height/2.2 + ")");

    // draw lines based on length TM helix
    hivesvg.selectAll(".axis")
        .data(d3.range(8))
      .enter().append("line")
        .attr("class", "axis")
        .attr("transform", function(d) { return "rotate(" + degreesHP(angle(d)) + ")" })
        .attr("x1", function(d) { if (d == 7) { return (resCount[0] * 1.2) * (outerRadius-innerRadius)/20+innerRadius; } else { return innerRadius; }})
        .attr("x2", function(d) { var extra = 0; if (d == 7){ extra = resCount[0] * 1.2}; return (outerRadius-innerRadius)/20*(extra+resCount[d]+1)+innerRadius; });
        //.attr("x2", function(d) { var extra = 0; if (d.x == 7){ extra = resCount[0] * 1.2}; return (outerRadius-innerRadius)/20*(resCount[d]+extra+1)+innerRadius; });

    // draw links between nodes
    /*
    hivesvg.selectAll(".link")
        .data(links)
      .enter().append("path")
        .attr("class", "link")
        .attr("d", d3.hive.link()
          .angle(function(d) { return angle(d.x); })
          .radius(function(d) { return d.y*(outerRadius-innerRadius)/20+innerRadius; }))
        .style("stroke", function(d) { if (d.tmDistance == 6) return color(d.target.x); else return color(d.source.x); })
        .on("mouseover", linkMouseoverHP)
        .on("mouseout", mouseoutHP);*/
    var lineCore = d3.svg.line.radial()
        .interpolate( "bundle" )
        .tension( 0.85 )
//        .radius(function(d) { return d.y*(outerRadius-innerRadius)/20+innerRadius; })
        .radius(function(d) { var extra = 0; if (d.x >= 6.5){ extra = resCount[0] * 1.2}; return (d.y+extra)*(outerRadius-innerRadius)/20+innerRadius; })
        .angle(function(d) { /*if (d.x < 0) d.x = 7 + d.x;*/ return angle(d.x); });

    hivesvg.selectAll(".link")
        .data(links)
      .enter().append("path")
        .attr("class", "link")
        .attr("d", function(d, i) {
            var placer = 0.3;
//            if (d.source.x == 7 || d.target.x == 7)
//                placer = placer/3;

            var margin = 10;
            if (d.tmDistance > 3)
                placer *= -1;
            var path = [d.source];
            path.push({x: d.source.x+placer, y: d.source.y});

            if (!d.consecutive) {
                var middle;
                var inside = true;
                if (d.tmDistance == 2 || d.tmDistance >= 5)
                    inside = false;

                var via = 0;
                if (d.tmDistance > 3)
                    //via = d.target.x + (7-d.tmDistance)/2;
                    via = d.source.x - (7-d.tmDistance)/2;
                else
                    via = d.source.x + d.tmDistance/2;
//                via = via % 7;

                // draw nice path outside or inside
                if (inside){
                    middle = {x: via, y: -1*margin/2};
                    path.push({x: middle.x - placer, y: middle.y + margin/3});
                    path.push(middle);
                    path.push({x: middle.x + placer, y: middle.y + margin/3});
                } else {
                    if (via == 0.5)
                      via = 0;
                    middle = {x: via, y: resCount[via] + margin };
                    path.push({x: middle.x - placer, y: middle.y - margin/2});
                    path.push(middle);
                    path.push({x: middle.x + placer, y: middle.y - margin/2});
                }
            }
            path.push({x: d.target.x-placer, y: d.target.y});
            path.push(d.target);

            return lineCore(path);
          })
        //.attr("d", d3.hive.link()
        //  .angle(function(d) { return angle(d.x); })
        //  .radius(function(d) { return d.y*(outerRadius-innerRadius)/20+innerRadius; }))
        .style("stroke", function(d) { if (d.tmDistance == 6) return color(d.target.x); else return color(d.source.x); })
        .on("mouseover", linkMouseoverHP)
        .on("mouseout", mouseoutHP);

    // draw nodes
    hivesvg.selectAll(".node")
        .data(nodes)
      .enter().append("circle")
        .attr("class", "node")
        .attr("transform", function(d) { return "rotate(" + degreesHP(angle(d.x)) + ")"; })
        .attr("cx", function(d) { var extra = 0; if (d.x == 7){ extra = resCount[0] * 1.2}; return (d.y+extra)*(outerRadius-innerRadius)/20+innerRadius; })
        .attr("r", 5)
        .style("fill", function(d) { return color(d.x); })
        .on("mouseover", nodeMouseoverHP)
        .on("mouseout", mouseoutHP)
// fix nice bootstrap tooltips
//        .each(function(d,i){ console.log("enable for "+d.gn);$(this).tooltip({title: d.gn + " (" + d.number + ")", html: false, placement: 'bottom', container: 'body'});});
}

// Based on Mike Bostock's example: https://bl.ocks.org/mbostock/2066415
// highlight link and connected nodes on mouseover
function linkMouseoverHP(d) {
  hivesvg.selectAll(".link")
    .classed("turnedOn", function(dl) {
      return dl === d;
    })
    .classed("turnedOff", function(dl) {
      return !(dl === d);
    })
  hivesvg.selectAll(".node")
    .classed("turnedOn", function(dl) {
      return dl === d.source || dl === d.target;
    })
}

// highlight node and connected links on mouseover
function nodeMouseoverHP(d) {
  hivesvg.selectAll(".link")
    .classed("turnedOn", function(dl) {
      return dl.source === d || dl.target === d;
    })
    .classed("turnedOff", function(dl) {
      return !(dl.source === d || dl.target === d)
    });
  d3.select(this)
    .classed("turnedOn", true);

  // show hiveTooltip
  hiveTooltip.style("display", "block")
               .style("left",(d3.event.pageX+20)+"px")
               .style("top",(d3.event.pageY+10)+"px")
               .html(d.gn + " (" + d.number + ")");
}

// clear highlighted nodes or links
function mouseoutHP() {
  hivesvg.selectAll(".turnedOn").classed("turnedOn", false);
  hivesvg.selectAll(".turnedOff").classed("turnedOff", false);
  // hide hiveTooltip
  hiveTooltip.style("display", "none");
}

function degreesHP(radians) {
  return radians / Math.PI * 180 - 90;
}
<|endoftext|>


<commit_before>$(function() {
  function ActionTriggerViewModel(parameters) {
    var self = this;

    self.loginState = parameters[0];
    self.printerState = parameters[1];
    self.control = parameters[2];

    self.showActionTriggerDialog = function(data) {
      //Need to figure out of this is only showing, or also some processing
      var actionTriggerDialog = $("#action_trigger_dialog");
      var actionTriggerDialogAck = $(".action_trigger_dialog_acknowledge", actionTriggerDialog);

      $(".action_trigger_title", actionTriggerDialog).text(data.trigger_title)
      $(".action_trigger_dialog_message", actionTriggerDialog).text(data.message);
      actionTriggerDialogAck.unbind("click");
      actionTriggerDialogAck.bind("click", function(e) {
        e.preventDefault();
        $("#action_trigger_dialog").modal("hide");
        //prob going to do some stuff here huh.
      });
      actionTriggerDialog.modal("show");

    }

    self.processActionTrigger = function(data) {

    }

    self.onDataUpdaterPluginMessage = function(plugin, data) {
      if (plugin != "actiontrigger") {
        return;
      }

      var messageType = data.type;
      var messageData = data.data;

      switch (messageType) {
        case "pause":
          //Call pause stuff
        case "resume":
          //Call resume stuff
        case "disconnect":
          //Call disconect stuff
        case "filament":
          //Call filament stuff
        case "door":
          self.showActionTriggerDialog(data);
      //Do nothing
      }
    }

  ADDITIONAL_VIEWMODELS.push([ActionTriggerViewModel, ["loginStateViewModel", "printerStateViewModel", "controlViewModel"], document.getElementById("action_trigger_dialog")]);
  }
})
<commit_msg>Wait wit! It actually works<commit_after>$(function() {
  function ActionTriggerViewModel(parameters) {
    var self = this;

    self.loginState = parameters[0];
    self.printerState = parameters[1];
    self.control = parameters[2];

    self.showActionTriggerDialog = function (data) {
      //Need to figure out of this is only showing, or also some processing
      var actionTriggerDialog = $("#action_trigger_dialog");
      var actionTriggerDialogAck = $(".action_trigger_dialog_acknowledge", actionTriggerDialog);

      $(".action_trigger_title", actionTriggerDialog).text(data.trigger_title)
      $(".action_trigger_dialog_message", actionTriggerDialog).text(data.message);
      actionTriggerDialogAck.unbind("click");
      actionTriggerDialogAck.bind("click", function (e) {
        e.preventDefault();
        $("#action_trigger_dialog").modal("hide");
        //prob going to do some stuff here huh.
      });
      actionTriggerDialog.modal("show");

    };

    self.processActionTrigger = function (data) {

    };

    self.onDataUpdaterPluginMessage = function (plugin, data) {
      if (plugin != "actiontrigger") {
        return;
      }

      var messageType = data.type;
      var messageData = data.data;

      switch (messageType) {
        case "pause":
        //Call pause stuff
        case "resume":
        //Call resume stuff
        case "disconnect":
        //Call disconect stuff
        case "filament":
        //Call filament stuff
        case "door":
          self.showActionTriggerDialog(data);
        //Do nothing
      }
    };

  }
  ADDITIONAL_VIEWMODELS.push([ActionTriggerViewModel, ["loginStateViewModel", "printerStateViewModel", "controlViewModel"], document.getElementById("action_trigger_dialog")]);
});
<|endoftext|>


<commit_before>'use strict';

/**
 * CSS selector of video element. It's common for both players.
 * @type {String}
 */
const videoSelector = '.html5-main-video';

const chapterNameSelector = '.html5-video-player .ytp-chapter-title-content';
const videoTitleSelector = '.html5-video-player .ytp-title-link';
const channelNameSelector = '#top-row .ytd-channel-name a';
const videoDescriptionSelector = '#meta-contents #description';

// Dummy category indicates an actual category is being fetched
const categoryPending = 'YT_DUMMY_CATEGORY_PENDING';
// Fallback value in case when we cannot fetch a category.
const categoryUnknown = 'YT_DUMMY_CATEGORY_UNKNOWN';

const categoryMusic = 'Music';
const categoryEntertainment = 'Entertainment';

/**
 * Array of categories allowed to be scrobbled.
 * @type {Array}
 */
const allowedCategories = [categoryUnknown];

/**
 * "Video Id=Category" map.
 * @type {Map}
 */
const categoryCache = new Map();

let currentVideoDescription = null;
let artistTrackFromDescription = null;

const trackInfoGetters = [
	getTrackInfoFromChapters,
	getTrackInfoFromDescription,
	getTrackInfoFromTitle,
];

readConnectorOptions();
setupEventListener();

Connector.playerSelector = '#content';

Connector.getTrackInfo = () => {
	const trackInfo = {};

	for (const getter of trackInfoGetters) {
		const currentTrackInfo = getter();
		if (!currentTrackInfo) {
			continue;
		}

		if (!trackInfo.artist) {
			trackInfo.artist = currentTrackInfo.artist;
		}

		if (!trackInfo.track) {
			trackInfo.track = currentTrackInfo.track;
		}

		if (!Util.isArtistTrackEmpty(trackInfo)) {
			break;
		}
	}

	return trackInfo;
};

Connector.getTimeInfo = () => {
	const videoElement = document.querySelector(videoSelector);
	if (videoElement && !areChaptersAvailable()) {
		let { currentTime, duration, playbackRate } = videoElement;

		currentTime /= playbackRate;
		duration /= playbackRate;

		return { currentTime, duration };
	}

	return null;
};

Connector.isPlaying = () => {
	return $('.html5-video-player').hasClass('playing-mode');
};

Connector.getUniqueID = () => {
	if (areChaptersAvailable()) {
		return null;
	}

	return getVideoId();
};

Connector.isScrobblingAllowed = () => {
	if ($('.ad-showing').length > 0) {
		return false;
	}

	// Workaround to prevent scrobbling the video opened in a background tab.
	if (!isVideoStartedPlaying()) {
		return false;
	}

	if (allowedCategories.length === 0) {
		return true;
	}

	const videoCategory = getVideoCategory();
	if (!videoCategory) {
		return false;
	}

	return allowedCategories.includes(videoCategory);
};

Connector.applyFilter(
	MetadataFilter.getYoutubeFilter().append({
		artist: removeLtrRtlChars,
		track: [removeLtrRtlChars, removeNumericPrefix],
	})
);

function setupEventListener() {
	$(videoSelector).on('timeupdate', Connector.onStateChanged);
}

function areChaptersAvailable() {
	return Util.getTextFromSelectors(chapterNameSelector);
}

function getVideoId() {
	/*
	 * ytd-watch-flexy element contains ID of a first played video
	 * if the miniplayer is visible, so we should check
	 * if URL of a current video in miniplayer is accessible.
	 */
	const miniPlayerVideoUrl = Util.getAttrFromSelectors(
		'ytd-miniplayer[active] [selected] a',
		'href'
	);
	if (miniPlayerVideoUrl) {
		return Util.getYtVideoIdFromUrl(miniPlayerVideoUrl);
	}

	return Util.getAttrFromSelectors('ytd-watch-flexy', 'video-id');
}

function getVideoCategory() {
	const videoId = getVideoId();

	if (!videoId) {
		return null;
	}

	if (categoryCache.has(videoId)) {
		return categoryCache.get(videoId);
	}

	/*
	 * Add dummy category for videoId to prevent
	 * fetching category multiple times.
	 */
	categoryCache.set(videoId, categoryPending);

	fetchCategoryName(videoId)
		.then((category) => {
			Util.debugLog(`Fetched category for ${videoId}: ${category}`);
			categoryCache.set(videoId, category);
		})
		.catch((err) => {
			Util.debugLog(
				`Failed to fetch category for ${videoId}: ${err}`,
				'warn'
			);
			categoryCache.set(videoId, categoryUnknown);
		});

	return null;
}

async function fetchCategoryName(videoId) {
	/*
	 * We cannot use `location.href`, since it could miss the video URL
	 * in case when YouTube mini player is visible.
	 */
	const videoUrl = `${location.origin}/watch?v=${videoId}`;

	try {
		/*
		 * Category info is not available via DOM API, so we should search it
		 * in a page source.
		 *
		 * But we cannot use `document.documentElement.outerHtml`, since it
		 * is not updated on video change.
		 */
		const response = await fetch(videoUrl);
		const rawHtml = await response.text();

		const categoryMatch = rawHtml.match(/"category":"(.+?)"/);
		if (categoryMatch !== null) {
			return categoryMatch[1];
		}
	} catch (e) {
		// Do nothing
	}

	return categoryUnknown;
}

/**
 * Asynchronously read connector options.
 */
async function readConnectorOptions() {
	if (await Util.getOption('YouTube', 'scrobbleMusicOnly')) {
		allowedCategories.push(categoryMusic);
	}
	if (await Util.getOption('YouTube', 'scrobbleEntertainmentOnly')) {
		allowedCategories.push(categoryEntertainment);
	}
	Util.debugLog(`Allowed categories: ${allowedCategories.join(', ')}`);
}

function getVideoDescription() {
	return Util.getTextFromSelectors(videoDescriptionSelector);
}

function getTrackInfoFromDescription() {
	const description = getVideoDescription();
	if (currentVideoDescription === description) {
		return artistTrackFromDescription;
	}

	currentVideoDescription = description;
	artistTrackFromDescription = Util.parseYtVideoDescription(description);

	return artistTrackFromDescription;
}

function getTrackInfoFromChapters() {
	const chapterName = Util.getTextFromSelectors(chapterNameSelector);
	const artistTrack = Util.splitArtistTrack(chapterName);
	if (!artistTrack.track) {
		artistTrack.track = chapterName;
	}
	return artistTrack;
}

function getTrackInfoFromTitle() {
	let { artist, track } = Util.processYtVideoTitle(
		Util.getTextFromSelectors(videoTitleSelector)
	);
	if (!artist) {
		artist = Util.getTextFromSelectors(channelNameSelector);
	}

	return { artist, track };
}

function removeLtrRtlChars(text) {
	return MetadataFilter.filterWithFilterRules(text, [
		{ source: /\u200e/g, target: '' },
		{ source: /\u200f/g, target: '' },
	]);
}

function removeNumericPrefix(text) {
	return text.replace(/^\d+\.\s/, '');
}

function isVideoStartedPlaying() {
	const videoElement = document.querySelector(videoSelector);
	return videoElement && videoElement.currentTime > 0;
}
<commit_msg>Fix youtube connector<commit_after>'use strict';

/**
 * CSS selector of video element. It's common for both players.
 * @type {String}
 */
const videoSelector = '.html5-main-video';

const chapterNameSelector = '.html5-video-player .ytp-chapter-title-content';
const videoTitleSelector = '.html5-video-player .ytp-title-link';
const channelNameSelector = '#top-row .ytd-channel-name a';
const videoDescriptionSelector = '#meta-contents #description';

// Dummy category indicates an actual category is being fetched
const categoryPending = 'YT_DUMMY_CATEGORY_PENDING';
// Fallback value in case when we cannot fetch a category.
const categoryUnknown = 'YT_DUMMY_CATEGORY_UNKNOWN';

const categoryMusic = 'Music';
const categoryEntertainment = 'Entertainment';

/**
 * Array of categories allowed to be scrobbled.
 * @type {Array}
 */
const allowedCategories = [];

/**
 * "Video Id=Category" map.
 * @type {Map}
 */
const categoryCache = new Map();

let currentVideoDescription = null;
let artistTrackFromDescription = null;

const trackInfoGetters = [
	getTrackInfoFromChapters,
	getTrackInfoFromDescription,
	getTrackInfoFromTitle,
];

readConnectorOptions();
setupEventListener();

Connector.playerSelector = '#content';

Connector.getTrackInfo = () => {
	const trackInfo = {};

	for (const getter of trackInfoGetters) {
		const currentTrackInfo = getter();
		if (!currentTrackInfo) {
			continue;
		}

		if (!trackInfo.artist) {
			trackInfo.artist = currentTrackInfo.artist;
		}

		if (!trackInfo.track) {
			trackInfo.track = currentTrackInfo.track;
		}

		if (!Util.isArtistTrackEmpty(trackInfo)) {
			break;
		}
	}

	return trackInfo;
};

Connector.getTimeInfo = () => {
	const videoElement = document.querySelector(videoSelector);
	if (videoElement && !areChaptersAvailable()) {
		let { currentTime, duration, playbackRate } = videoElement;

		currentTime /= playbackRate;
		duration /= playbackRate;

		return { currentTime, duration };
	}

	return null;
};

Connector.isPlaying = () => {
	return $('.html5-video-player').hasClass('playing-mode');
};

Connector.getUniqueID = () => {
	if (areChaptersAvailable()) {
		return null;
	}

	return getVideoId();
};

Connector.isScrobblingAllowed = () => {
	if ($('.ad-showing').length > 0) {
		return false;
	}

	// Workaround to prevent scrobbling the video opened in a background tab.
	if (!isVideoStartedPlaying()) {
		return false;
	}

	return isVideoCategoryAllowed();
};

Connector.applyFilter(
	MetadataFilter.getYoutubeFilter().append({
		artist: removeLtrRtlChars,
		track: [removeLtrRtlChars, removeNumericPrefix],
	})
);

function setupEventListener() {
	$(videoSelector).on('timeupdate', Connector.onStateChanged);
}

function areChaptersAvailable() {
	return Util.getTextFromSelectors(chapterNameSelector);
}

function getVideoId() {
	/*
	 * ytd-watch-flexy element contains ID of a first played video
	 * if the miniplayer is visible, so we should check
	 * if URL of a current video in miniplayer is accessible.
	 */
	const miniPlayerVideoUrl = Util.getAttrFromSelectors(
		'ytd-miniplayer[active] [selected] a',
		'href'
	);
	if (miniPlayerVideoUrl) {
		return Util.getYtVideoIdFromUrl(miniPlayerVideoUrl);
	}

	return Util.getAttrFromSelectors('ytd-watch-flexy', 'video-id');
}

function getVideoCategory() {
	const videoId = getVideoId();

	if (!videoId) {
		return null;
	}

	if (categoryCache.has(videoId)) {
		return categoryCache.get(videoId);
	}

	/*
	 * Add dummy category for videoId to prevent
	 * fetching category multiple times.
	 */
	categoryCache.set(videoId, categoryPending);

	fetchCategoryName(videoId)
		.then((category) => {
			Util.debugLog(`Fetched category for ${videoId}: ${category}`);
			categoryCache.set(videoId, category);
		})
		.catch((err) => {
			Util.debugLog(
				`Failed to fetch category for ${videoId}: ${err}`,
				'warn'
			);
			categoryCache.set(videoId, categoryUnknown);
		});

	return null;
}

async function fetchCategoryName(videoId) {
	/*
	 * We cannot use `location.href`, since it could miss the video URL
	 * in case when YouTube mini player is visible.
	 */
	const videoUrl = `${location.origin}/watch?v=${videoId}`;

	try {
		/*
		 * Category info is not available via DOM API, so we should search it
		 * in a page source.
		 *
		 * But we cannot use `document.documentElement.outerHtml`, since it
		 * is not updated on video change.
		 */
		const response = await fetch(videoUrl);
		const rawHtml = await response.text();

		const categoryMatch = rawHtml.match(/"category":"(.+?)"/);
		if (categoryMatch !== null) {
			return categoryMatch[1];
		}
	} catch (e) {
		// Do nothing
	}

	return categoryUnknown;
}

/**
 * Asynchronously read connector options.
 */
async function readConnectorOptions() {
	if (await Util.getOption('YouTube', 'scrobbleMusicOnly')) {
		allowedCategories.push(categoryMusic);
	}
	if (await Util.getOption('YouTube', 'scrobbleEntertainmentOnly')) {
		allowedCategories.push(categoryEntertainment);
	}
	Util.debugLog(`Allowed categories: ${allowedCategories.join(', ')}`);
}

function getVideoDescription() {
	return Util.getTextFromSelectors(videoDescriptionSelector);
}

function getTrackInfoFromDescription() {
	const description = getVideoDescription();
	if (currentVideoDescription === description) {
		return artistTrackFromDescription;
	}

	currentVideoDescription = description;
	artistTrackFromDescription = Util.parseYtVideoDescription(description);

	return artistTrackFromDescription;
}

function getTrackInfoFromChapters() {
	const chapterName = Util.getTextFromSelectors(chapterNameSelector);
	const artistTrack = Util.splitArtistTrack(chapterName);
	if (!artistTrack.track) {
		artistTrack.track = chapterName;
	}
	return artistTrack;
}

function getTrackInfoFromTitle() {
	let { artist, track } = Util.processYtVideoTitle(
		Util.getTextFromSelectors(videoTitleSelector)
	);
	if (!artist) {
		artist = Util.getTextFromSelectors(channelNameSelector);
	}

	return { artist, track };
}

function removeLtrRtlChars(text) {
	return MetadataFilter.filterWithFilterRules(text, [
		{ source: /\u200e/g, target: '' },
		{ source: /\u200f/g, target: '' },
	]);
}

function removeNumericPrefix(text) {
	return text.replace(/^\d+\.\s/, '');
}

function isVideoStartedPlaying() {
	const videoElement = document.querySelector(videoSelector);
	return videoElement && videoElement.currentTime > 0;
}

function isVideoCategoryAllowed() {
	if (allowedCategories.length === 0) {
		return true;
	}

	const videoCategory = getVideoCategory();
	if (!videoCategory) {
		return false;
	}

	return (
		allowedCategories.includes(videoCategory) ||
		videoCategory === categoryUnknown
	);
}
<|endoftext|>


<commit_before>import assert from 'assert';
import { hooks as auth } from 'feathers-authentication';
import { NotAuthenticated } from 'feathers-errors';
import fp from 'mostly-func';

const defaultOptions = {
  anonymous: true,
};

function getAccessToken(hook) {
  return fp.path(['headers', 'authorization'], hook.params) ||
         fp.path(['accessToken'], hook.data);
}

export default function authenticate(strategies, opts = {}, fields = '') {
  opts = fp.assign(defaultOptions, opts);
  assert(strategies, "The 'authenticate' hook requires one of your registered passport strategies.");

  const verifyIdentity = auth.authenticate(strategies);

  return async function(context) {
    const accessToken = getAccessToken(context);
    // verify and fetch user with $select fields
    const select = fields.split(',')
      .concat(fp.pathOr([], ['local', 'fields'], opts)).join(',');
    if (fields) {
      context.params = fp.assign(context.params, {
        $auth: {
          query: { $select: select }
        }
      });
    }
    return await verifyIdentity(context);
  };
}
<commit_msg>Fix get select fields in authenticate<commit_after>import assert from 'assert';
import { hooks as auth } from 'feathers-authentication';
import { NotAuthenticated } from 'feathers-errors';
import fp from 'mostly-func';

const defaultOptions = {
  anonymous: true,
};

function getAccessToken(hook) {
  return fp.path(['headers', 'authorization'], hook.params) ||
         fp.path(['accessToken'], hook.data);
}

export default function authenticate(strategies, opts = {}, fields) {
  opts = fp.assign(defaultOptions, opts);
  assert(strategies, "The 'authenticate' hook requires one of your registered passport strategies.");

  const verifyIdentity = auth.authenticate(strategies);

  return async function(context) {
    const accessToken = getAccessToken(context);
    // verify and fetch user with $select fields
    const select = fp.reject(fp.isNil, [fields, opts.local && opts.local.fields]).join(',');
    if (select) {
      context.params = fp.assign(context.params, {
        $auth: {
          query: { $select: select }
        }
      });
    }
    return await verifyIdentity(context);
  };
}
<|endoftext|>


<commit_before>/**
 * Created by tusharmathur on 6/25/15.
 */
var fs = require('fs'),
    _ = require('lodash'),
    request = require('request'),
    co = require('co');

var u = {
    async: function (onError, func) {
        var coFunc = co.wrap(func);
        return function () {
            try {
                coFunc.apply(null, arguments).catch(onError);
            } catch (e) {
                onError(e);
            }
        };
    },
    promisify: function (func) {
        var defer = Promise.defer(),
            handle = function (err, data) {
                if (err) {
                    defer.reject(err);
                } else {
                    defer.resolve(data);
                }
            };
        return _.restParam(function (args) {
            args.push(handle);
            func.apply(null, args);
            return defer.promise;
        })
    }
};

u.fsWrite = u.promisify(fs.write);
u.fsOpen = u.promisify(fs.open);
u.fsTruncate = u.promisify(fs.truncate);
u.fsRename = u.promisify(fs.rename);
u.requestHead = u.promisify(request.head);
u.writeMetaData = function (fd, metaBuffer, position) {
    return u.fsWrite(fd, metaBuffer, 0, metaBuffer.length, position);
};
u.getTotalBytesFromResponse = function (headResponse) {
    return parseInt(headResponse.headers['content-length'], 10);
};
u.createFileDescriptor = function (options) {
    return u.fsOpen(options.path, 'w+');
};
u.createMetaData = function (totalBytes, url, path, count) {
    var MAX_BUFFER = 512;
    var threads = _.fill(_.times(count), {});
    var data = {totalBytes, url, path, threads};
    return {
        toBuffer: function () {
            var metaBuffer = new Buffer(MAX_BUFFER);
            _.fill(metaBuffer, null);
            metaBuffer.write(JSON.stringify(data));
            return metaBuffer;
        },
        updatePosition: function (index, distance) {
            data.threads[index].position += distance;
            return this;
        },
        setRange: function (index, range) {
            var thread = data.threads[index];
            thread.start = range.start;
            thread.end = range.end;
            thread.position = range.start;
        }
    }
};
u.getThreadRange = function (count, index, total) {
    var bytesPerThread = Math.round(total / count),
        start = Math.floor(bytesPerThread * index),
        end = count - index === 1 ? total : start + bytesPerThread - 1;
    return {start, end}
};
module.exports = u;<commit_msg>meta function updated<commit_after>/**
 * Created by tusharmathur on 6/25/15.
 */
var fs = require('fs'),
    _ = require('lodash'),
    request = require('request'),
    co = require('co');

var u = {
    async: function (onError, func) {
        var coFunc = co.wrap(func);
        return function () {
            try {
                coFunc.apply(null, arguments).catch(onError);
            } catch (e) {
                onError(e);
            }
        };
    },
    promisify: function (func) {
        var defer = Promise.defer(),
            handle = function (err, data) {
                if (err) {
                    defer.reject(err);
                } else {
                    defer.resolve(data);
                }
            };
        return _.restParam(function (args) {
            args.push(handle);
            func.apply(null, args);
            return defer.promise;
        })
    }
};

u.fsWrite = u.promisify(fs.write);
u.fsOpen = u.promisify(fs.open);
u.fsTruncate = u.promisify(fs.truncate);
u.fsRename = u.promisify(fs.rename);
u.requestHead = u.promisify(request.head);
u.writeData = function (fd, buffer, position) {
    return u.fsWrite(fd, buffer, 0, buffer.length, position);
};
u.getTotalBytesFromResponse = function (headResponse) {
    return parseInt(headResponse.headers['content-length'], 10);
};
u.createFileDescriptor = function (options) {
    return u.fsOpen(options.path, 'w+');
};
u.createMetaData = function (totalBytes, url, path, count) {
    var MAX_BUFFER = 512;
    var threads = _.fill(_.times(count), {});
    var data = {totalBytes, url, path, threads};
    return {
        toBuffer: function () {
            var metaBuffer = new Buffer(MAX_BUFFER);
            _.fill(metaBuffer, null);
            metaBuffer.write(JSON.stringify(data));
            return metaBuffer;
        },
        thread: function (index) {
            var _this = this;
            return {
                getPosition: function () {
                    return data.threads[index].position;
                },
                updatePosition: function (distance) {
                    data.threads[index].position += distance;
                },
                setRange: function (range) {
                    var thread = data.threads[index];
                    thread.start = range.start;
                    thread.end = range.end;
                    thread.position = range.start;
                }
            }
        }

    }
};
u.getThreadRange = function (count, index, total) {
    var bytesPerThread = Math.round(total / count),
        start = Math.floor(bytesPerThread * index),
        end = count - index === 1 ? total : start + bytesPerThread - 1;
    return {start, end}
};
module.exports = u;<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { IndexLink } from 'react-router';
import { LinkContainer } from 'react-router-bootstrap';
import Navbar from 'react-bootstrap/lib/Navbar';
import Nav from 'react-bootstrap/lib/Nav';
import NavItem from 'react-bootstrap/lib/NavItem';
import Helmet from 'react-helmet';
import { isLoaded as isInfoLoaded, load as loadInfo } from 'redux/modules/info';
import { isLoaded as isAuthLoaded, load as loadAuth, logout } from 'redux/modules/auth';
import { InfoBar } from 'components';
import { push } from 'react-router-redux';
import config from '../../config';
import { asyncConnect } from 'redux-async-connect';
import cookie from 'react-cookie';

@asyncConnect([{
  promise: ({store: {dispatch, getState}}) => {
    const promises = [];

    if (!isInfoLoaded(getState())) {
      promises.push(dispatch(loadInfo()));
    }
    if (!isAuthLoaded(getState())) {
      promises.push(dispatch(loadAuth()));
    }

    return Promise.all(promises);
  }
}])

@connect((store) => {
  return {
    registerNewUserState: store.registerNewUser.user,
  };
})

export default class App extends Component {
    state = {
      loaded: 'display: "none"',
      userEmail: cookie.load('ck_email'),
      navExpanded: false
    }

    static propTypes = {
      children: PropTypes.object.isRequired,
      user: PropTypes.object,
      logout: PropTypes.func.isRequired,
      pushState: PropTypes.func.isRequired
    };

    static contextTypes = {
      store: PropTypes.object.isRequired
    };

    componentWillMount() {
      //this.setState({userEmail: cookie.load('ck_email')});
      setTimeout(function(){
        this.setState({ loaded: 'display: "inline-block"' });
      }, 1000);

      console.log("component componentDidMount ----------------");
    }

    componentWillReceiveProps(nextProps) {
      console.log("component componentWillReceiveProps ----------------");
      if (!this.props.user && nextProps.user) {
        // login
        this.props.pushState('/loginSuccess');
      } else if (this.props.user && !nextProps.user) {
        // logout
        this.props.pushState('/');
      }
    }

    onNavItemClick = () => {
      this.setState({ navExpanded: false });
    }
    onNavbarToggle = () => {
      this.setState({ navExpanded: ! this.state.navExpanded });
    }
    handleLogout = (event) => {
      event.preventDefault();
      this.props.logout();
    }

    render() {
      const styles = require('./App.scss');
      const {loaded, userEmail} = this.state;
      const { registerNewUserState } = this.props;

      var userIsRegistered = 0;
      if(userEmail !== undefined){
        userIsRegistered = 1;
      }
      if(registerNewUserState.email !== null){
        userIsRegistered = 1;
      }
      console.log('userIsRegistered: ' + userIsRegistered + ' ,cookie.load(ck_email): ' + userEmail + ', registerNewUserState.email: '+registerNewUserState.email);

      return (

          <Helmet {...config.app.head}/>

          <Navbar fixedTop expanded={ this.state.navExpanded } onToggle={ this.onNavbarToggle }>
            <Navbar.Header>
              <Navbar.Brand>
                <IndexLink to="/" activeStyle={{color: '#d52b1e'}}>

                    {config.app.title}

                </IndexLink>
              </Navbar.Brand>
              <Navbar.Toggle/>
            </Navbar.Header>

            <Navbar.Collapse>

                <LinkContainer to="/community">
                  <NavItem eventKey={1} onClick={ this.onNavItemClick }>Community</NavItem>
                </LinkContainer>
                { userIsRegistered === 1 ?
                <LinkContainer to="/registrieren0">
                  <NavItem eventKey={2} onClick={ this.onNavItemClick }>Mein Profil</NavItem>
                </LinkContainer>
                : null }
                { userIsRegistered === 2 ?
                <LinkContainer to="/registrieren">
                  <NavItem eventKey={3} onClick={ this.onNavItemClick }>Mitglied werden</NavItem>
                </LinkContainer>
                : null }
                <LinkContainer to="/kontakt">
                  <NavItem eventKey={4} onClick={ this.onNavItemClick }>Kontakt</NavItem>
                </LinkContainer>
                { userIsRegistered === 1 ?
                  <LinkContainer to="/registrieren1">
                    <NavItem eventKey={5} onClick={ this.onNavItemClick }>Logout</NavItem>
                  </LinkContainer>
                  : null }
                  { userIsRegistered === 2 ?
                  <LinkContainer to="/registrieren2">
                    <NavItem eventKey={6} onClick={ this.onNavItemClick }>Login</NavItem>
                  </LinkContainer>
                  : null }

            </Navbar.Collapse>
          </Navbar>

            {this.props.children}

          <InfoBar/>

            Copyright { new Date().getFullYear() } | Swiss React Community | React, Redux, Flux, React Native | Swiss-react.ch

      );
    }
  }
<commit_msg>loginEmail v3.6<commit_after>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { IndexLink } from 'react-router';
import { LinkContainer } from 'react-router-bootstrap';
import Navbar from 'react-bootstrap/lib/Navbar';
import Nav from 'react-bootstrap/lib/Nav';
import NavItem from 'react-bootstrap/lib/NavItem';
import Helmet from 'react-helmet';
import { isLoaded as isInfoLoaded, load as loadInfo } from 'redux/modules/info';
import { isLoaded as isAuthLoaded, load as loadAuth, logout } from 'redux/modules/auth';
import { InfoBar } from 'components';
import { push } from 'react-router-redux';
import config from '../../config';
import { asyncConnect } from 'redux-async-connect';
import cookie from 'react-cookie';

@asyncConnect([{
  promise: ({store: {dispatch, getState}}) => {
    const promises = [];

    if (!isInfoLoaded(getState())) {
      promises.push(dispatch(loadInfo()));
    }
    if (!isAuthLoaded(getState())) {
      promises.push(dispatch(loadAuth()));
    }

    return Promise.all(promises);
  }
}])

@connect((store) => {
  return {
    registerNewUserState: store.registerNewUser.user,
  };
})

export default class App extends Component {
    state = {
      loaded: 'display: "none"',
      userEmail: cookie.load('ck_email'),
      navExpanded: false
    }

    static propTypes = {
      children: PropTypes.object.isRequired,
      user: PropTypes.object,
      logout: PropTypes.func.isRequired,
      pushState: PropTypes.func.isRequired
    };

    static contextTypes = {
      store: PropTypes.object.isRequired
    };

    componentWillMount() {
      //this.setState({userEmail: cookie.load('ck_email')});
      this.setState({ loaded: 'display: "inline-block"' });
      console.log("component componentDidMount ----------------");
    }

    componentWillReceiveProps(nextProps) {
      console.log("component componentWillReceiveProps ----------------");
      if (!this.props.user && nextProps.user) {
        // login
        this.props.pushState('/loginSuccess');
      } else if (this.props.user && !nextProps.user) {
        // logout
        this.props.pushState('/');
      }
    }

    onNavItemClick = () => {
      this.setState({ navExpanded: false });
    }
    onNavbarToggle = () => {
      this.setState({ navExpanded: ! this.state.navExpanded });
    }
    handleLogout = (event) => {
      event.preventDefault();
      this.props.logout();
    }

    render() {
      const styles = require('./App.scss');
      const {loaded, userEmail} = this.state;
      const { registerNewUserState } = this.props;

      var userIsRegistered = 0;
      if(userEmail !== undefined){
        userIsRegistered = 1;
      }
      if(registerNewUserState.email !== null){
        userIsRegistered = 1;
      }
      console.log('userIsRegistered: ' + userIsRegistered + ' ,cookie.load(ck_email): ' + userEmail + ', registerNewUserState.email: '+registerNewUserState.email);

      return (

          <Helmet {...config.app.head}/>

          <Navbar fixedTop expanded={ this.state.navExpanded } onToggle={ this.onNavbarToggle }>
            <Navbar.Header>
              <Navbar.Brand>
                <IndexLink to="/" activeStyle={{color: '#d52b1e'}}>

                    {config.app.title}

                </IndexLink>
              </Navbar.Brand>
              <Navbar.Toggle/>
            </Navbar.Header>

            <Navbar.Collapse>

                <LinkContainer to="/community">
                  <NavItem eventKey={1} onClick={ this.onNavItemClick }>Community</NavItem>
                </LinkContainer>
                { userIsRegistered === 1 ?
                <LinkContainer to="/registrieren0">
                  <NavItem eventKey={2} onClick={ this.onNavItemClick }>Mein Profil</NavItem>
                </LinkContainer>
                : null }
                { userIsRegistered === 2 ?
                <LinkContainer to="/registrieren">
                  <NavItem eventKey={3} onClick={ this.onNavItemClick }>Mitglied werden</NavItem>
                </LinkContainer>
                : null }
                <LinkContainer to="/kontakt">
                  <NavItem eventKey={4} onClick={ this.onNavItemClick }>Kontakt</NavItem>
                </LinkContainer>
                { userIsRegistered === 1 ?
                  <LinkContainer to="/registrieren1">
                    <NavItem eventKey={5} onClick={ this.onNavItemClick }>Logout</NavItem>
                  </LinkContainer>
                  : null }
                  { userIsRegistered === 2 ?
                  <LinkContainer to="/registrieren2">
                    <NavItem eventKey={6} onClick={ this.onNavItemClick }>Login</NavItem>
                  </LinkContainer>
                  : null }

            </Navbar.Collapse>
          </Navbar>

            {this.props.children}

          <InfoBar/>

            Copyright { new Date().getFullYear() } | Swiss React Community | React, Redux, Flux, React Native | Swiss-react.ch

      );
    }
  }
<|endoftext|>


<commit_before>/* global $ */

(function (window, document, $) {
    'use strict';

    var FloatingMenu = function FloatingMenu (params) {
        this.init(params);
    };

    FloatingMenu.prototype.init = function (params) {
        this.$menu = $('
');
        $('body').append(this.$menu);
        this.bindEvents();
    };

    FloatingMenu.prototype.create = function (params) {
        var name = params.name || '(element)',
            posTop = params.posTop || 0,
            posLeft = params.posLeft || 0,
            menuHtml = this.newItem({name: name, is_header: true}),
            editList = [{
                value: 'Edit HTML',
                attrs: {
                    'operation': 'edit-html',
                    'data-toggle': 'modal',
                    'data-target':'#edit-html'
                }
            },{
                value: 'Edit Text',
                attrs: {
                    'operation': 'edit-text'
                }
            },{
                value: 'Edit Classes',
                attrs: {
                    'operation': 'edit-classes'
                }
            }, {
                value: 'Edit Style',
                attrs: {
                    'operation': 'edit-style'
                }
            }];

        menuHtml += this.newItem({name: 'Edit Element', operation: 'edit-element', items: editList });
        menuHtml += this.newItem({klass: 'divider'});
        menuHtml += this.newItem({name: 'Move and Resize', operation: 'move-and-resize'});
        menuHtml += this.newItem({name: 'Remove', operation: 'remove'});
        menuHtml += this.newItem({klass: 'divider'});
        menuHtml += this.newItem({name: 'Select Container', items: params.container});

        this.$menu.append(menuHtml);
        this.$menu.css({
            top: posTop - 10,
            left: posLeft + 10
        });
    };

    FloatingMenu.prototype.bindEvents = function () {
        this.$menu.on('click', 'li', function(e) {
            var $el = $(e.toElement).parent(),
                op = $el.data('operation');

            if (op) {
                var _event = new CustomEvent('floatingMenuItemClicked', {'detail': {'operation': op}});
                document.dispatchEvent(_event);
                console.log('Operation: ' + op);
            }

            // e.stopPropagation();
        });
    };

    FloatingMenu.prototype.open = function () {
        this.$menu.show();
    };

    FloatingMenu.prototype.close = function () {
        this.$menu.hide();
        this.$menu.empty();
    };

    FloatingMenu.prototype.newItem = function (params) {
        var $li = $('
');

        if (params.operation) {
            $li.attr('data-operation', params.operation);
        }

        if (params.is_header) {
            $li.addClass('dropdown-header')
               .append('(' + params.name + ')');
        } else if (params.name) {
            $li.append('' + params.name + '');
        }

        if (params.klass) {
            $li.addClass(params.klass);
        }

        if (params.items) {
            var $subMenu = $('
');

            for (var i=0; i<=params.items.length-1; i++) {
                var $_li = $('
');

                $_li.attr(params.items[i].attrs);

                $_li.append('' + params.items[i].value + '');
                $subMenu.append($_li);
            }

            $li.addClass('dropdown-submenu');
            $li.append($subMenu);
        }

        return $li.prop('outerHTML');
    }

    window.FloatingMenu = FloatingMenu;
})(window, document, $);<commit_msg>remove operation attr fromEdit Element option<commit_after>/* global $ */

(function (window, document, $) {
    'use strict';

    var FloatingMenu = function FloatingMenu (params) {
        this.init(params);
    };

    FloatingMenu.prototype.init = function (params) {
        this.$menu = $('
');
        $('body').append(this.$menu);
        this.bindEvents();
    };

    FloatingMenu.prototype.create = function (params) {
        var name = params.name || '(element)',
            posTop = params.posTop || 0,
            posLeft = params.posLeft || 0,
            menuHtml = this.newItem({name: name, is_header: true}),
            editList = [{
                value: 'Edit HTML',
                attrs: {
                    'operation': 'edit-html',
                    'data-toggle': 'modal',
                    'data-target':'#edit-html'
                }
            },{
                value: 'Edit Text',
                attrs: {
                    'operation': 'edit-text'
                }
            },{
                value: 'Edit Classes',
                attrs: {
                    'operation': 'edit-classes'
                }
            }, {
                value: 'Edit Style',
                attrs: {
                    'operation': 'edit-style'
                }
            }];

        menuHtml += this.newItem({name: 'Edit Element', items: editList });
        menuHtml += this.newItem({klass: 'divider'});
        menuHtml += this.newItem({name: 'Move and Resize', operation: 'move-and-resize'});
        menuHtml += this.newItem({name: 'Remove', operation: 'remove'});
        menuHtml += this.newItem({klass: 'divider'});
        menuHtml += this.newItem({name: 'Select Container', items: params.container});

        this.$menu.append(menuHtml);
        this.$menu.css({
            top: posTop - 10,
            left: posLeft + 10
        });
    };

    FloatingMenu.prototype.bindEvents = function () {
        this.$menu.on('click', 'li', function(e) {
            var $el = $(e.toElement).parent(),
                op = $el.data('operation');

            if (op) {
                var _event = new CustomEvent('floatingMenuItemClicked', {'detail': {'operation': op}});
                document.dispatchEvent(_event);
                console.log('Operation: ' + op);
            }

            // e.stopPropagation();
        });
    };

    FloatingMenu.prototype.open = function () {
        this.$menu.show();
    };

    FloatingMenu.prototype.close = function () {
        this.$menu.hide();
        this.$menu.empty();
    };

    FloatingMenu.prototype.newItem = function (params) {
        var $li = $('
');

        if (params.operation) {
            $li.attr('data-operation', params.operation);
        }

        if (params.is_header) {
            $li.addClass('dropdown-header')
               .append('(' + params.name + ')');
        } else if (params.name) {
            $li.append('' + params.name + '');
        }

        if (params.klass) {
            $li.addClass(params.klass);
        }

        if (params.items) {
            var $subMenu = $('
');

            for (var i=0; i<=params.items.length-1; i++) {
                var $_li = $('
');

                $_li.attr(params.items[i].attrs);

                $_li.append('' + params.items[i].value + '');
                $subMenu.append($_li);
            }

            $li.addClass('dropdown-submenu');
            $li.append($subMenu);
        }

        return $li.prop('outerHTML');
    }

    window.FloatingMenu = FloatingMenu;
})(window, document, $);<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Route, HashRouter, Redirect, Switch } from 'react-router-dom'
import { createBrowserHistory } from 'history';
import Full from '../Full/'
import Home from '../Home/'
import PropTypes from 'prop-types'
import { fetchProperties } from './../../actions.js'
import { serviceurl } from '../../config/serviceurl.js'
import { setCookie } from '../../utility'
import ReduxToastr from 'react-redux-toastr'
import Public from '../Public/';

const history = createBrowserHistory();

class App extends Component {
  state = {
    loading: true,
  }

  componentDidMount() {
    const { dispatch } = this.props
    var domain = window.location.host
    var split = domain.split('.')
    dispatch(fetchProperties(split[0]))
    .then(json => {
      var html = document.getElementsByTagName('html')[0];
      if(json){
        switch(json.properties.theme){
          case "1":
            html.style.setProperty("--primary", "#0066CC");
            html.style.setProperty("--lightblue", "#1A75D1");
            this.setState({
              loading: false
            })
            break;
          case "2":
            html.style.setProperty("--primary", "#4975A6");
            html.style.setProperty("--lightblue", "#5B83AF");
            this.setState({
              loading: false
            })
            break;
          default:
            html.style.setProperty("--primary", "#0066CC");
            html.style.setProperty("--lightblue", "#1A75D1");
            this.setState({
              loading: false
            })
            break;
        }
      }else{
        html.style.setProperty("--primary", "#0066CC");
        html.style.setProperty("--lightblue", "#1A75D1");
        this.setState({
          loading: false
        })
      }
    })
  }

  componentWillUnmount() {
    this.removeListener()
  }
  render() {
    return this.state.loading === true ?
Caricamento
 : (

        <HashRouter history={history}>
          <Switch>
            <Route path='/' exact component={Public} />
            <Route path='/home' exact component={Public} />
            <Route path='/missione' exact component={Public} />
            <Route path='/lineeguida' exact component={Public} />
            <Route path='/partecipa' exact component={Public} />
            <Route path='/data-applications' exact component={Public} />
            <Route path='/userstory/list' exact component={Public} />
            <Route path='/userstory/list/:id' exact component={Public} />
            <Route path='/team' exact component={Public} />
            <Route path='/notizie' exact component={Public} />
            <Route path='/notizie/:id' exact component={Public} />
            <Route path='/storie' exact component={Public} />
            <Route path='/team' exact component={Public} />
            <Route path='/search' exact component={Public} />
            <Route path='/dataset/list' exact component={Public} />
            <Route path='/dataset/:id' exact component={Public} />
            <Route path='/private' exact component={Home} />
            <Route path="/login" component={Home} />
            <Route path="/register" component={Home} />
            <Route path="/confirmregistration" component={Home} />
            <Route path="/requestreset" component={Home} />
            <Route path="/resetpwd" component={Home} />
            <Route path="/private/home" name="Home" component={Full} />
            <Route path="/private/prova" name="Home" component={Full} />
            <Route path="/private/dashboard" name="Dashboard" component={Full} />
            <Route path="/private/widget" name="Widget" component={Full} />
            <Route path="/private/ingestionwizzard" name="Ingestion" component={Full} />
            <Route exact path="/private/dataset" name="Dataset" component={Full} />
            <Route exact path="/private/dataset_old" name="Dataset" component={Full} />
            {<Route exact path="/private/search" name="Search" component={Full} />}
            <Route exact path="/private/dataset/:id" name="Dataset Detail" component={Full} />
            <Route path="/private/dashboard/manager" name="Dash" component={Full} />
            <Route path="/private/dashboard/list" name="Dash" component={Full} />
            <Route path="/private/userstory" name="Storie" component={Full} />
            <Route path="/private/profile" name="Profile" component={Full} />
            <Route path="/private/crea" name="Crea" component={Full} />
            <Route path="/private/settings" name="Settings" component={Full} />
            <Route path="/private/organizations" name="Organizations" component={Full} />
            <Route path="/private/users" name="Users" component={Full} />
          </Switch>
        </HashRouter>
        <ReduxToastr
          timeOut={6000}
          newestOnTop={true}
          preventDuplicates
          position="top-right"
          transitionIn="fadeIn"
          transitionOut="fadeOut"
          progressBar/>

    );
  }
}

App.propTypes = {
  loggedUser: PropTypes.object,
  dispatch: PropTypes.func.isRequired
}

function mapStateToProps(state) {
  const { loggedUser, authed } = state.userReducer['obj'] || {}
  return { loggedUser, authed }
}

export default connect(mapStateToProps)(App)
<commit_msg>Add semantics routes to App router<commit_after>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Route, HashRouter, Redirect, Switch } from 'react-router-dom'
import { createBrowserHistory } from 'history';
import Full from '../Full/'
import Home from '../Home/'
import PropTypes from 'prop-types'
import { fetchProperties } from './../../actions.js'
import { serviceurl } from '../../config/serviceurl.js'
import { setCookie } from '../../utility'
import ReduxToastr from 'react-redux-toastr'
import Public from '../Public/';

const history = createBrowserHistory();

class App extends Component {
  state = {
    loading: true,
  }

  componentDidMount() {
    const { dispatch } = this.props
    var domain = window.location.host
    var split = domain.split('.')
    dispatch(fetchProperties(split[0]))
    .then(json => {
      var html = document.getElementsByTagName('html')[0];
      if(json){
        switch(json.properties.theme){
          case "1":
            html.style.setProperty("--primary", "#0066CC");
            html.style.setProperty("--lightblue", "#1A75D1");
            this.setState({
              loading: false
            })
            break;
          case "2":
            html.style.setProperty("--primary", "#4975A6");
            html.style.setProperty("--lightblue", "#5B83AF");
            this.setState({
              loading: false
            })
            break;
          default:
            html.style.setProperty("--primary", "#0066CC");
            html.style.setProperty("--lightblue", "#1A75D1");
            this.setState({
              loading: false
            })
            break;
        }
      }else{
        html.style.setProperty("--primary", "#0066CC");
        html.style.setProperty("--lightblue", "#1A75D1");
        this.setState({
          loading: false
        })
      }
    })
  }

  componentWillUnmount() {
    this.removeListener()
  }
  render() {
    return this.state.loading === true ?
Caricamento
 : (

        <HashRouter history={history}>
          <Switch>
            <Route path='/' exact component={Public} />
            <Route path='/home' exact component={Public} />
            <Route path='/missione' exact component={Public} />
            <Route path='/lineeguida' exact component={Public} />
            <Route path='/partecipa' exact component={Public} />
            <Route path='/data-applications' exact component={Public} />
            <Route path='/userstory/list' exact component={Public} />
            <Route path='/userstory/list/:id' exact component={Public} />
            <Route path='/team' exact component={Public} />
            <Route path='/notizie' exact component={Public} />
            <Route path='/notizie/:id' exact component={Public} />
            <Route path='/storie' exact component={Public} />
            <Route path='/team' exact component={Public} />
            <Route path='/search' exact component={Public} />
            <Route path='/dataset/list' exact component={Public} />
            <Route path='/dataset/:id' exact component={Public} />
            <Route path='/private' exact component={Home} />
            <Route path="/login" component={Home} />
            <Route path="/register" component={Home} />
            <Route path="/confirmregistration" component={Home} />
            <Route path="/requestreset" component={Home} />
            <Route path="/resetpwd" component={Home} />
            <Route path="/private/home" name="Home" component={Full} />
            <Route path="/private/prova" name="Home" component={Full} />
            <Route path="/private/dashboard" name="Dashboard" component={Full} />
            <Route path="/private/widget" name="Widget" component={Full} />
            <Route path="/private/ingestionwizzard" name="Ingestion" component={Full} />
            <Route path="/private/ontologies" name="Ontologies" exact component={Full} />
            <Route path="/private/ontologies/:filter" name="Ontology" component={Full} />
            <Route path="/private/vocabularies" name="Vocabularies" exact component={Full} />
            <Route path="/private/vocabularies/:filter" name="Vocabulary" component={Full} />
            <Route exact path="/private/dataset" name="Dataset" component={Full} />
            <Route exact path="/private/dataset_old" name="Dataset" component={Full} />
            {<Route exact path="/private/search" name="Search" component={Full} />}
            <Route exact path="/private/dataset/:id" name="Dataset Detail" component={Full} />
            <Route path="/private/dashboard/manager" name="Dash" component={Full} />
            <Route path="/private/dashboard/list" name="Dash" component={Full} />
            <Route path="/private/userstory" name="Storie" component={Full} />
            <Route path="/private/profile" name="Profile" component={Full} />
            <Route path="/private/crea" name="Crea" component={Full} />
            <Route path="/private/settings" name="Settings" component={Full} />
            <Route path="/private/organizations" name="Organizations" component={Full} />
            <Route path="/private/users" name="Users" component={Full} />
          </Switch>
        </HashRouter>
        <ReduxToastr
          timeOut={6000}
          newestOnTop={true}
          preventDuplicates
          position="top-right"
          transitionIn="fadeIn"
          transitionOut="fadeOut"
          progressBar/>

    );
  }
}

App.propTypes = {
  loggedUser: PropTypes.object,
  dispatch: PropTypes.func.isRequired
}

function mapStateToProps(state) {
  const { loggedUser, authed } = state.userReducer['obj'] || {}
  return { loggedUser, authed }
}

export default connect(mapStateToProps)(App)
<|endoftext|>