<commit_before>// ==UserScript==
// @name        Rate Bot
// @description Rating bot for BestEverAlbums.com
// @namespace   kaffeinition@gmail.com
// @include     http://www.besteveralbums.com/*
// @version     1.186
// @grant       none
// @icon        http://i58.tinypic.com/21cw5lu.png
// ==/UserScript==

var cssLabel = "font-size: 9px;";

var album_page = false;
var artist_page = false;
var track_page = false;
var chart_page = false;

var track_num = 0;
var album_num = 0;

var rating = -1;

///////ETC
function resetLabel(){
  document.getElementsByClassName("objectinteractionpanel")[0].getElementsByTagName("label")[0].innerHTML = "rate everything";
  document.getElementsByClassName("objectinteractionpanel")[0].getElementsByTagName("label")[0].style.cssText = cssLabel;
}

/*function isNumber(event) {///http://stackoverflow.com/questions/20682707/how-to-allow-numbers-backspace-delete-left-and-right-arrow-keys-in-the-html-t
  var key = window.event ? event.keyCode : event.which;

  if (event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39) {
      return true;
  }
  else if ( key < 48 || key > 57 ) {
      return false;
  }
  else return true;
};*/
///////

window.onload = function () {
  var page_id = window.location.href;
  page_id = page_id.substr((page_id.lastIndexOf("?") + 1), 1);
  if(page_id === "a"){
    album_page = true;
    track_num = document.getElementsByClassName('tracks') [0].getElementsByTagName('tbody') [0].getElementsByTagName('tr') .length;
  }else if(page_id === "b"){
    artist_page = true;
    track_num = document.getElementsByClassName('tracks') [0].getElementsByTagName('tbody') [0].getElementsByTagName('tr') .length;
    album_num = document.getElementsByClassName("chart")[0].getElementsByClassName("user").length;
  }else if(page_id === "c"){
    chart_page = true;
    album_num = document.getElementsByClassName("chart")[0].getElementsByClassName("user").length;
  }else if(page_id === "t"){
    track_page = true;
  }
  //console.log("this far");

  var first_pass = document.getElementsByClassName("objectinteractionpanel")[0];
  var second_pass = first_pass.children;
  var third_pass = second_pass[0].children;

  var new_td = document.createElement("td");
  var button_label = document.createElement("label");
  var button = document.createElement("input");
  var rate = document.createElement('input');
  button.setAttribute("type", "button");
  button.setAttribute("value", "Rate-Bot");
  rate.setAttribute("id", "rate-amount");
  rate.setAttribute("type", "text");
  rate.setAttribute("value", "100");
  rate.setAttribute("maxlength", "3");
  //rate.setAttribute("onkeypress", "return isNumber(event);");
  //rate.addEventListener("keypress", function(){return isNumber(event);});
  rate.addEventListener("focus", function(){resetLabel();}, true);

  button_label.innerHTML = "rate everything";
  third_pass[0].appendChild(new_td);
  var where = third_pass[0].getElementsByTagName("td")[0];

  where.appendChild(button_label).style.cssText = cssLabel;
  where.appendChild(rate).style.cssText = "width:20px;font-size:10px;";
  where.appendChild(button).addEventListener("click", function(){
    rating = document.getElementsByClassName("objectinteractionpanel")[0].getElementsByTagName("input")[0].value;
    if(rating <= 100){
      if(album_page)
      {
        album_page_rate(track_num)
        //console.log("album page rate");
      }
    if(artist_page)
      {
        artist_page_rate(track_num, album_num);
        //console.log("artist page rate");
      }
    if(chart_page)
      {
        chart_page_rate(album_num);
        //console.log("chart page rate");
      }
    if(track_page)
      {
        track_page_rate();
        //console.log("track page rate");
      }
    }else{
      button_label.innerHTML = "must be <= 100";
      button_label.style.cssText += "color:red;";
    }
  });
};

///////RUNNING SHIT
function album_page_rate(track_num){
  rate_album();
  rate_tracks(track_num);
}

function artist_page_rate(track_num, album_num){
  rate_albums(album_num);
  rate_tracks(track_num);
  rate_band();
}

function chart_page_rate(album_num){
  rate_albums(album_num);
  rate_chart();
}

function track_page_rate(){
  rate_track();
}
////////

////////TRACK
function rate_tracks(track_num){
  for (var i = 0; i < track_num; i++) {
    var track_id = document.getElementsByClassName('tracks') [0].getElementsByTagName('tbody') [0].getElementsByTagName('tr') [i].getElementsByClassName('user') [0].getAttribute('id');
    var real_id = track_id.split('_');
    track_id = real_id[2];
    var objecttype = 'track';
    var rate = rating.toString();
    createRequest();
    var url = 'AJAXRate.php?oid=' + track_id + '&o=' + objecttype + '&r=' + rate;
    request.open('GET', url, true);
    request.onreadystatechange = updatePage;
    request.send(null);
  }
}

function rate_track(){
  var track_id = document.getElementsByClassName("objectinteractionpanel")[0].getElementsByTagName("ul")[0].getAttribute('id');
  var real_id = track_id.split('_');
  track_id = real_id[2];
  var objecttype = 'track';
  var rate = rating.toString();
  createRequest();
  var url = 'AJAXRate.php?oid=' + track_id + '&o=' + objecttype + '&r=' + rate;
  request.open('GET', url, true);
  request.onreadystatechange = updatePage;
  request.send(null);
}
///////

///////ALBUM
function rate_albums(album_num){
  for (var i = 0; i < album_num; i++) {
    var album_id = document.getElementsByClassName("chart")[0].getElementsByClassName("user")[i].getAttribute('id');
    var real_id = album_id.split('_');
    album_id = real_id[2];
    var objecttype = 'album';
    var rate = rating.toString();
    createRequest();
    var url = 'AJAXRate.php?oid=' + album_id + '&o=' + objecttype + '&r=' + rate;
    request.open('GET', url, true);
    request.onreadystatechange = updatePage;
    request.send(null);
  }
}

function rate_album(){
  var album_id = document.getElementsByClassName("objectinteractionpanel")[0].getElementsByTagName("ul")[0].getAttribute('id');
  var real_id = album_id.split('_');
  album_id = real_id[2];
  var objecttype = 'album';
  var rate = rating.toString();
  createRequest();
  var url = 'AJAXRate.php?oid=' + album_id + '&o=' + objecttype + '&r=' + rate;
  request.open('GET', url, true);
  request.onreadystatechange = updatePage;
  request.send(null);
}
///////

///////CHART
function rate_chart(){
  var chart_id = document.getElementsByClassName("objectinteractionpanel")[0].getElementsByTagName("ul")[0].getAttribute('id');
  var real_id = chart_id.split('_');
  chart_id = real_id[2];
  var objecttype = 'chart';
  var rate = rating.toString();
  createRequest();
  var url = 'AJAXRate.php?oid=' + chart_id + '&o=' + objecttype + '&r=' + rate;
  request.open('GET', url, true);
  request.onreadystatechange = updatePage;
  request.send(null);
}
///////

///////BAND
function rate_band(){
  var band_id = document.getElementsByClassName("objectinteractionpanel")[0].getElementsByTagName("ul")[0].getAttribute('id');
  var real_id = band_id.split('_');
  band_id = real_id[2];
  var objecttype = 'band';
  var rate = rating.toString();
  createRequest();
  var url = 'AJAXRate.php?oid=' + band_id + '&o=' + objecttype + '&r=' + rate;
  request.open('GET', url, true);
  request.onreadystatechange = updatePage;
  request.send(null);
}
///////
<commit_msg>fixed stupid versioning<commit_after>// ==UserScript==
// @name        Rate Bot
// @description Rating bot for BestEverAlbums.com
// @namespace   kaffeinition@gmail.com
// @include     http://www.besteveralbums.com/*
// @version     1.2
// @grant       none
// @icon        http://i58.tinypic.com/21cw5lu.png
// ==/UserScript==

var cssLabel = "font-size: 9px;";

var album_page = false;
var artist_page = false;
var track_page = false;
var chart_page = false;

var track_num = 0;
var album_num = 0;

var rating = -1;

///////ETC
function resetLabel(){
  document.getElementsByClassName("objectinteractionpanel")[0].getElementsByTagName("label")[0].innerHTML = "rate everything";
  document.getElementsByClassName("objectinteractionpanel")[0].getElementsByTagName("label")[0].style.cssText = cssLabel;
}

/*function isNumber(event) {///http://stackoverflow.com/questions/20682707/how-to-allow-numbers-backspace-delete-left-and-right-arrow-keys-in-the-html-t
  var key = window.event ? event.keyCode : event.which;

  if (event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39) {
      return true;
  }
  else if ( key < 48 || key > 57 ) {
      return false;
  }
  else return true;
};*/
///////

window.onload = function () {
  var page_id = window.location.href;
  page_id = page_id.substr((page_id.lastIndexOf("?") + 1), 1);
  if(page_id === "a"){
    album_page = true;
    track_num = document.getElementsByClassName('tracks') [0].getElementsByTagName('tbody') [0].getElementsByTagName('tr') .length;
  }else if(page_id === "b"){
    artist_page = true;
    track_num = document.getElementsByClassName('tracks') [0].getElementsByTagName('tbody') [0].getElementsByTagName('tr') .length;
    album_num = document.getElementsByClassName("chart")[0].getElementsByClassName("user").length;
  }else if(page_id === "c"){
    chart_page = true;
    album_num = document.getElementsByClassName("chart")[0].getElementsByClassName("user").length;
  }else if(page_id === "t"){
    track_page = true;
  }
  //console.log("this far");

  var first_pass = document.getElementsByClassName("objectinteractionpanel")[0];
  var second_pass = first_pass.children;
  var third_pass = second_pass[0].children;

  var new_td = document.createElement("td");
  var button_label = document.createElement("label");
  var button = document.createElement("input");
  var rate = document.createElement('input');
  button.setAttribute("type", "button");
  button.setAttribute("value", "Rate-Bot");
  rate.setAttribute("id", "rate-amount");
  rate.setAttribute("type", "text");
  rate.setAttribute("value", "100");
  rate.setAttribute("maxlength", "3");
  //rate.setAttribute("onkeypress", "return isNumber(event);");
  //rate.addEventListener("keypress", function(){return isNumber(event);});
  rate.addEventListener("focus", function(){resetLabel();}, true);

  button_label.innerHTML = "rate everything";
  third_pass[0].appendChild(new_td);
  var where = third_pass[0].getElementsByTagName("td")[0];

  where.appendChild(button_label).style.cssText = cssLabel;
  where.appendChild(rate).style.cssText = "width:20px;font-size:10px;";
  where.appendChild(button).addEventListener("click", function(){
    rating = document.getElementsByClassName("objectinteractionpanel")[0].getElementsByTagName("input")[0].value;
    if(rating <= 100){
      if(album_page)
      {
        album_page_rate(track_num)
        //console.log("album page rate");
      }
    if(artist_page)
      {
        artist_page_rate(track_num, album_num);
        //console.log("artist page rate");
      }
    if(chart_page)
      {
        chart_page_rate(album_num);
        //console.log("chart page rate");
      }
    if(track_page)
      {
        track_page_rate();
        //console.log("track page rate");
      }
    }else{
      button_label.innerHTML = "must be <= 100";
      button_label.style.cssText += "color:red;";
    }
  });
};

///////RUNNING SHIT
function album_page_rate(track_num){
  rate_album();
  rate_tracks(track_num);
}

function artist_page_rate(track_num, album_num){
  rate_albums(album_num);
  rate_tracks(track_num);
  rate_band();
}

function chart_page_rate(album_num){
  rate_albums(album_num);
  rate_chart();
}

function track_page_rate(){
  rate_track();
}
////////

////////TRACK
function rate_tracks(track_num){
  for (var i = 0; i < track_num; i++) {
    var track_id = document.getElementsByClassName('tracks') [0].getElementsByTagName('tbody') [0].getElementsByTagName('tr') [i].getElementsByClassName('user') [0].getAttribute('id');
    var real_id = track_id.split('_');
    track_id = real_id[2];
    var objecttype = 'track';
    var rate = rating.toString();
    createRequest();
    var url = 'AJAXRate.php?oid=' + track_id + '&o=' + objecttype + '&r=' + rate;
    request.open('GET', url, true);
    request.onreadystatechange = updatePage;
    request.send(null);
  }
}

function rate_track(){
  var track_id = document.getElementsByClassName("objectinteractionpanel")[0].getElementsByTagName("ul")[0].getAttribute('id');
  var real_id = track_id.split('_');
  track_id = real_id[2];
  var objecttype = 'track';
  var rate = rating.toString();
  createRequest();
  var url = 'AJAXRate.php?oid=' + track_id + '&o=' + objecttype + '&r=' + rate;
  request.open('GET', url, true);
  request.onreadystatechange = updatePage;
  request.send(null);
}
///////

///////ALBUM
function rate_albums(album_num){
  for (var i = 0; i < album_num; i++) {
    var album_id = document.getElementsByClassName("chart")[0].getElementsByClassName("user")[i].getAttribute('id');
    var real_id = album_id.split('_');
    album_id = real_id[2];
    var objecttype = 'album';
    var rate = rating.toString();
    createRequest();
    var url = 'AJAXRate.php?oid=' + album_id + '&o=' + objecttype + '&r=' + rate;
    request.open('GET', url, true);
    request.onreadystatechange = updatePage;
    request.send(null);
  }
}

function rate_album(){
  var album_id = document.getElementsByClassName("objectinteractionpanel")[0].getElementsByTagName("ul")[0].getAttribute('id');
  var real_id = album_id.split('_');
  album_id = real_id[2];
  var objecttype = 'album';
  var rate = rating.toString();
  createRequest();
  var url = 'AJAXRate.php?oid=' + album_id + '&o=' + objecttype + '&r=' + rate;
  request.open('GET', url, true);
  request.onreadystatechange = updatePage;
  request.send(null);
}
///////

///////CHART
function rate_chart(){
  var chart_id = document.getElementsByClassName("objectinteractionpanel")[0].getElementsByTagName("ul")[0].getAttribute('id');
  var real_id = chart_id.split('_');
  chart_id = real_id[2];
  var objecttype = 'chart';
  var rate = rating.toString();
  createRequest();
  var url = 'AJAXRate.php?oid=' + chart_id + '&o=' + objecttype + '&r=' + rate;
  request.open('GET', url, true);
  request.onreadystatechange = updatePage;
  request.send(null);
}
///////

///////BAND
function rate_band(){
  var band_id = document.getElementsByClassName("objectinteractionpanel")[0].getElementsByTagName("ul")[0].getAttribute('id');
  var real_id = band_id.split('_');
  band_id = real_id[2];
  var objecttype = 'band';
  var rate = rating.toString();
  createRequest();
  var url = 'AJAXRate.php?oid=' + band_id + '&o=' + objecttype + '&r=' + rate;
  request.open('GET', url, true);
  request.onreadystatechange = updatePage;
  request.send(null);
}
///////
<|endoftext|>


<commit_before>function AppViewModel(dataModel) {
    // Private state
    var self = this;

    // Private operations
    function cleanUpLocation() {
        window.location.hash = "";

        if (typeof (history.pushState) !== "undefined") {
            history.pushState("", document.title, location.pathname);
        }
    }
    // Data
    self.Views = {
        Loading: {} // Other views are added dynamically by app.addViewModel(...).
    };
    self.dataModel = dataModel;

    // UI state
    self.view = ko.observable(self.Views.Loading);

    self.loading = ko.computed(function () {
        return self.view() === self.Views.Loading;
    });

    // UI operations

    // Other navigateToX functions are added dynamically by app.addViewModel(...).

    // Other operations
    self.addViewModel = function (options) {
        var viewItem = new options.factory(self, dataModel),
            navigator;

        // Add view to AppViewModel.Views enum (for example, app.Views.Home).
        self.Views[options.name] = viewItem;

        // Add binding member to AppViewModel (for example, app.home);
        self[options.bindingMemberName] = ko.computed(function () {
            if (!dataModel.getAccessToken()) {
                // The following code looks for a fragment in the URL to get the access token which will be
                // used to call the protected Web API resource
                var fragment = common.getFragment();

                if (fragment.access_token) {
                    // returning with access token, restore old hash, or at least hide token
                    window.location.hash = fragment.state || '';
                    dataModel.setAccessToken(fragment.access_token);
                } else {
                    // no token - so bounce to Authorize endpoint in AccountController to sign in or register
                    window.location = "/Account/Authorize?client_id=web&response_type=token&state=" + encodeURIComponent(window.location.hash);
                }
            }

            return self.Views[options.name];
        });

        if (typeof (options.navigatorFactory) !== "undefined") {
            navigator = options.navigatorFactory(self, dataModel);
        } else {
            navigator = function () {
                window.location.hash = options.bindingMemberName;
            };
        }

        // Add navigation member to AppViewModel (for example, app.NavigateToHome());
        self["navigateTo" + options.name] = navigator;
    };

    self.initialize = function () {
        Sammy().run();
    }
}

var app = new AppViewModel(new AppDataModel());
<commit_msg>Authentication: don't redirect to auth page<commit_after>function AppViewModel(dataModel) {
    // Private state
    var self = this;

    // Private operations
    function cleanUpLocation() {
        window.location.hash = "";

        if (typeof (history.pushState) !== "undefined") {
            history.pushState("", document.title, location.pathname);
        }
    }
    // Data
    self.Views = {
        Loading: {} // Other views are added dynamically by app.addViewModel(...).
    };
    self.dataModel = dataModel;

    // UI state
    self.view = ko.observable(self.Views.Loading);

    self.loading = ko.computed(function () {
        return self.view() === self.Views.Loading;
    });

    // UI operations

    // Other navigateToX functions are added dynamically by app.addViewModel(...).

    // Other operations
    self.addViewModel = function (options) {
        var viewItem = new options.factory(self, dataModel),
            navigator;

        // Add view to AppViewModel.Views enum (for example, app.Views.Home).
        self.Views[options.name] = viewItem;

        // Add binding member to AppViewModel (for example, app.home);
        self[options.bindingMemberName] = ko.computed(function () {
            return self.Views[options.name];
        });

        if (typeof (options.navigatorFactory) !== "undefined") {
            navigator = options.navigatorFactory(self, dataModel);
        } else {
            navigator = function () {
                window.location.hash = options.bindingMemberName;
            };
        }

        // Add navigation member to AppViewModel (for example, app.NavigateToHome());
        self["navigateTo" + options.name] = navigator;
    };

    self.initialize = function () {
        Sammy().run();
    }
}

var app = new AppViewModel(new AppDataModel());
<|endoftext|>


<commit_before>'use strict'

var _ = require ('lodash')
var d3 = require ('d3')
var React = require ('react')
var Layer = require ('react-layer')

var Tooltip = require ('component/Tooltip.jsx')

var browser = require ('util/browser')

var legend = require ('chart/renderer/legend')

var DEFAULTS = {
  aspect: 1,
  domain: _.noop,
  margin: {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0
  },
  onClick: _.noop,
  value: _.property ('properties.value'),
  yFormat: d => d3.format (Math.abs (d) < 1 ? '.4f' : 'n') (d),
  name: _.property ('properties.name')
}

function _calculateBounds (features) {
  var lat = _.property (1)
  var lng = _.property (0)

  if (features.length < 1) {
    return [[0, 0], [0, 0]]
  }

  var coordinates = _ (features).map (function (f) {
    if (f.geometry.type !== 'MultiPolygon') {
      return _.flatten (f.geometry.coordinates)
    }
  })
    .flatten ()
    .value ()

  var left = d3.min (coordinates, lng)
  var right = d3.max (coordinates, lng)
  var bottom = d3.min (coordinates, lat)
  var top = d3.max (coordinates, lat)

  return [[left, top], [right, bottom]]
}

function _calculateCenter (bounds) {
  var lat = bounds[1][1] + ((bounds[0][1] - bounds[1][1]) / 2)
  var lng = bounds[0][0] + ((bounds[1][0] - bounds[0][0]) / 2)

  return [lng, lat]
}

function ChoroplethMap () {
}

_.extend (ChoroplethMap.prototype, {
  defaults: DEFAULTS,

  initialize: function (el, data, options) {
    options = this._options = _.defaults ({}, options, DEFAULTS)

    var margin = options.margin

    var aspect = _.get (options, 'aspect', 1)
    this._width = _.get (options, 'width', el.clientWidth)
    this._height = _.get (options, 'height', this._width * aspect)

    var svg = this._svg = d3.select (el).append ('svg')
      .attr ('class', 'reds')
      .attr ('viewBox', '0 0 ' + this._width + ' ' + this._height)

    if (browser.isIE ()) {
      svg.attr ({
        'width': this._width,
        'height': this._height
      })
    }

    var g = svg.append ('g')
      .attr ('transform', 'translate(' + margin.left + ', ' + margin.top + ')')

    g.append ('g').attr ('class', 'data')
    g.append ('g').attr ('class', 'legend')

    svg.append('g').attr('class', 'bubbles')
    svg.append('g').attr('class', 'stripes')

    var lineWidth = 10
    var lineHeight = 10
    var lineInterval = 5

    var defs = svg.append ('defs')

    var pattern = defs.append ('pattern')
      .attr ({
      'id': 'stripe',
      'patternUnits': 'userSpaceOnUse',
      'width': lineWidth,
      'height': lineHeight
    })

    pattern.append ('line')
      .attr ({
      'x1': 0,
      'y1': 0,
      'x2': -lineInterval,
      'y2': lineHeight
    })

    pattern.append ('line')
      .attr ({
      'x1': lineInterval,
      'y1': 0,
      'x2': 0,
      'y2': lineHeight
    })

    pattern.append ('line')
      .attr ({
      'x1': 2*lineInterval,
      'y1': 0,
      'x2': lineInterval,
      'y2': lineHeight
    })

    pattern.selectAll ('line')
      .attr ({
      'stroke-linecap': 'square',
      'stroke-linejoin': 'miter',
      'stroke-width': 1,
    })

    this.update (data)
  },

  update: function (data, options) {
    options = _.assign (this._options, options)

    var margin = options.margin
    var w = this._width - margin.left - margin.right
    var h = this._height - margin.top - margin.bottom

    var svg = this._svg
    var g = svg.select ('.data')

    var features = _.reject (data, 'properties.isBorder')

    var bounds = _calculateBounds (features)
    var center = _calculateCenter (bounds)

    var projection = d3.geo.conicEqualArea ()
      .parallels ([bounds[1][1], bounds[0][1]])
      .rotate ([-center[0], 0])   // Rotate the globe so that the country is centered horizontally
      .center ([0, center[1]])    // Set the center of the projection so that the polygon is moved vertically into the center of the viewport
      .translate ([w / 2, h / 2]) // Translate to the center of the viewport
      .scale (1)

    var b = [projection (bounds[0]), projection (bounds[1])]
    var s = 1 / Math.max ((b[1][0] - b[0][0]) / w, (b[1][1] - b[0][1]) / h)

    projection.scale (s)

    var path = d3.geo.path ().projection (projection)

    var domain = options.domain (features)

    if (!_.isArray (domain)) {
      domain = d3.extent (features, options.value)
      domain[0] = Math.min (domain[0], 0)
    }

    var colorScale = d3.scale.quantize ()
      .domain (domain)
      .range ([
        '#FEE7DC',
        '#FABAA2',
        '#F58667',
        '#D95449',
        '#AF373E',
        '#2D2525'
      ])

    var location = g.selectAll ('.location')
      .data (features, function (d, i) {
        return _.get (d, 'properties.location_id', i)
      })

    location.enter ().append ('path')

    location.attr ({
      'd': path,
      'class': function (d) {
        var v = options.value (d)
        var classNames = ['location']

        if (_.isFinite (v)) {
          classNames.push ('clickable')
        }

        return classNames.join (' ')
      }
    })
      .style ('fill', function (d) {
      var v = options.value (d)
      return _.isFinite (v) ? colorScale (v) : '#fff'
    })
      .on ('click', function (d) {
      options.onClick (_.get (d, 'properties.location_id'))
    })
      .on ('mousemove', _.partial (this._onMouseMove, _, options))
      .on ('mouseout', this._onMouseOut)

    location.exit ().remove ()

    var ticks = _.map (
      colorScale.range (),
        c => _.map (colorScale.invertExtent (c), options.yFormat).join ('—')
    )

    if (_.every (colorScale.domain (), _.isNaN)) {
      svg.select ('.legend').selectAll ('*').remove ()
    } else {
      svg.select ('.legend')
        .call (legend ()
          .scale (d3.scale.ordinal ()
            .domain (ticks)
            .range (colorScale.range ()))
      )
        .attr ('transform', function () {
          var bbox = this.getBoundingClientRect ()
          return 'translate(' + (w - bbox.width) + ', ' + (h - bbox.height) + ')'
        })
    }

    if (!_.isUndefined(options.bubblesValue)) {
      var bubbles = svg.select('.bubbles').selectAll ('circle').data (features);

      bubbles.enter ().append ("circle")
      bubbles.attr ("transform", function (d) {
        return "translate(" + path.centroid (d) + ")"
      })
        .attr ("r", function (d) {
        var v = options.bubblesValue (d)
        if (v) {
          return options.radius (v)
        }
        return 0
      })
        .style ({
        'opacity': 0.5,
        'fill': '#D5EBF7',
        'stroke': '#FFFFFF'
      })

      bubbles.exit ().remove ()
    }

    if (!_.isUndefined(options.stripesValue)) {
      var stripe = svg.select('.stripes').selectAll ('.location')
        .data (features, function (d, i) {
        return _.get (d, 'properties.location_id', i)
      })

      stripe.enter ().append ('path')

      stripe.attr ({
        'd': path,
        'class': 'location'
      })
        .style ('fill', function (d) {
          var v = options.stripesValue (d)
          var lineColor = _.isFinite (options.value(d)) ? '#ffffff' : '#cccccc'
          svg.selectAll('line').style('stroke', lineColor)
          return _.isFinite (v) ? 'url(#stripe)' : '#fff'
        })
        .style ('opacity', function (d) {
          var v = options.stripesValue (d)
          return _.isFinite (v) ? 1 : 0
        })

      stripe.exit ().remove ()
    }
  },

  _onMouseMove: function (d, options) {
    var evt = d3.event

    var render = function () {
      return React.createElement (
        Tooltip,
        {left: evt.pageX + 2, top: evt.pageY + 2},
        options.name (d)
      )
    }

    if (this.layer) {
      this.layer._render = render
    } else {
      this.layer = new Layer (document.body, render)
    }

    this.layer.render ()
  },

  _onMouseOut: function () {
    if (this.layer) {
      this.layer.destroy ()
      this.layer = null
    }
  }
})

module.exports = ChoroplethMap
<commit_msg>standard choropleth.js<commit_after>'use strict'

var _ = require('lodash')
var d3 = require('d3')
var React = require('react')
var Layer = require('react-layer')

var Tooltip = require('component/Tooltip.jsx')

var browser = require('util/browser')

var legend = require('chart/renderer/legend')

var DEFAULTS = {
  aspect: 1,
  domain: _.noop,
  margin: {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0
  },
  onClick: _.noop,
  value: _.property('properties.value'),
  yFormat: d => d3.format(Math.abs(d) < 1 ? '.4f' : 'n')(d),
  name: _.property('properties.name')
}

function _calculateBounds (features) {
  var lat = _.property(1)
  var lng = _.property(0)

  if (features.length < 1) {
    return [[0, 0], [0, 0]]
  }

  var coordinates = _(features).map(function (f) {
    if (f.geometry.type !== 'MultiPolygon') {
      return _.flatten(f.geometry.coordinates)
    }
  })
    .flatten()
    .value()

  var left = d3.min(coordinates, lng)
  var right = d3.max(coordinates, lng)
  var bottom = d3.min(coordinates, lat)
  var top = d3.max(coordinates, lat)

  return [[left, top], [right, bottom]]
}

function _calculateCenter (bounds) {
  var lat = bounds[1][1] + ((bounds[0][1] - bounds[1][1]) / 2)
  var lng = bounds[0][0] + ((bounds[1][0] - bounds[0][0]) / 2)

  return [lng, lat]
}

function ChoroplethMap () {
}

_.extend(ChoroplethMap.prototype, {
  defaults: DEFAULTS,

  initialize: function (el, data, options) {
    options = this._options = _.defaults({}, options, DEFAULTS)

    var margin = options.margin

    var aspect = _.get(options, 'aspect', 1)
    this._width = _.get(options, 'width', el.clientWidth)
    this._height = _.get(options, 'height', this._width * aspect)

    var svg = this._svg = d3.select(el).append('svg')
      .attr('class', 'reds')
      .attr('viewBox', '0 0 ' + this._width + ' ' + this._height)

    if (browser.isIE()) {
      svg.attr({
        'width': this._width,
        'height': this._height
      })
    }

    var g = svg.append('g')
      .attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')')

    g.append('g').attr('class', 'data')
    g.append('g').attr('class', 'legend')

    svg.append('g').attr('class', 'bubbles')
    svg.append('g').attr('class', 'stripes')

    var lineWidth = 10
    var lineHeight = 10
    var lineInterval = 5

    var defs = svg.append('defs')

    var pattern = defs.append('pattern')
      .attr({
        'id': 'stripe',
        'patternUnits': 'userSpaceOnUse',
        'width': lineWidth,
        'height': lineHeight
      })

    pattern.append('line')
      .attr({
        'x1': 0,
        'y1': 0,
        'x2': -lineInterval,
        'y2': lineHeight
      })

    pattern.append('line')
      .attr({
        'x1': lineInterval,
        'y1': 0,
        'x2': 0,
        'y2': lineHeight
      })

    pattern.append('line')
      .attr({
        'x1': 2 * lineInterval,
        'y1': 0,
        'x2': lineInterval,
        'y2': lineHeight
      })

    pattern.selectAll('line')
      .attr({
        'stroke-linecap': 'square',
        'stroke-linejoin': 'miter',
        'stroke-width': 1
      })

    this.update(data)
  },

  update: function (data, options) {
    options = _.assign(this._options, options)

    var margin = options.margin
    var w = this._width - margin.left - margin.right
    var h = this._height - margin.top - margin.bottom

    var svg = this._svg
    var g = svg.select('.data')

    var features = _.reject(data, 'properties.isBorder')

    var bounds = _calculateBounds(features)
    var center = _calculateCenter(bounds)

    var projection = d3.geo.conicEqualArea()
      .parallels([bounds[1][1], bounds[0][1]])
      .rotate([-center[0], 0])   // Rotate the globe so that the country is centered horizontally
      .center([0, center[1]])    // Set the center of the projection so that the polygon is moved vertically into the center of the viewport
      .translate([w / 2, h / 2]) // Translate to the center of the viewport
      .scale(1)

    var b = [projection(bounds[0]), projection(bounds[1])]
    var s = 1 / Math.max((b[1][0] - b[0][0]) / w, (b[1][1] - b[0][1]) / h)

    projection.scale(s)

    var path = d3.geo.path().projection(projection)

    var domain = options.domain(features)

    if (!_.isArray(domain)) {
      domain = d3.extent(features, options.value)
      domain[0] = Math.min(domain[0], 0)
    }

    var colorScale = d3.scale.quantize()
      .domain(domain)
      .range([
        '#FEE7DC',
        '#FABAA2',
        '#F58667',
        '#D95449',
        '#AF373E',
        '#2D2525'
      ])

    var location = g.selectAll('.location')
      .data(features, function (d, i) {
        return _.get(d, 'properties.location_id', i)
      })

    location.enter().append('path')

    location.attr({
      'd': path,
      'class': function (d) {
        var v = options.value(d)
        var classNames = ['location']

        if (_.isFinite(v)) {
          classNames.push('clickable')
        }

        return classNames.join(' ')
      }
    })
      .style('fill', function (d) {
        var v = options.value(d)
        return _.isFinite(v) ? colorScale(v) : '#fff'
      })
      .on('click', function (d) {
        options.onClick(_.get(d, 'properties.location_id'))
      })
      .on('mousemove', _.partial(this._onMouseMove, _, options))
      .on('mouseout', this._onMouseOut)

    location.exit().remove()

    var ticks = _.map(
      colorScale.range(),
        c => _.map(colorScale.invertExtent(c), options.yFormat).join('—')
    )

    if (_.every(colorScale.domain(), _.isNaN)) {
      svg.select('.legend').selectAll('*').remove()
    } else {
      svg.select('.legend')
        .call(legend()
          .scale(d3.scale.ordinal()
            .domain(ticks)
            .range(colorScale.range()))
      )
        .attr('transform', function () {
          var bbox = this.getBoundingClientRect()
          return 'translate(' + (w - bbox.width) + ', ' + (h - bbox.height) + ')'
        })
    }

    if (!_.isUndefined(options.bubblesValue)) {
      var bubbles = svg.select('.bubbles').selectAll('circle').data(features)

      bubbles.enter().append('circle')
      bubbles.attr('transform', function (d) {
        return 'translate(' + path.centroid(d) + ')'
      })
        .attr('r', function (d) {
          var v = options.bubblesValue(d)
          if (v) {
            return options.radius(v)
          }
          return 0
        })
        .style({
          'opacity': 0.5,
          'fill': '#D5EBF7',
          'stroke': '#FFFFFF'
        })

      bubbles.exit().remove()
    }

    if (!_.isUndefined(options.stripesValue)) {
      var stripe = svg.select('.stripes').selectAll('.location')
        .data(features, function (d, i) {
          return _.get(d, 'properties.location_id', i)
        })

      stripe.enter().append('path')

      stripe.attr({
        'd': path,
        'class': 'location'
      })
        .style('fill', function (d) {
          var v = options.stripesValue(d)
          var lineColor = _.isFinite(options.value(d)) ? '#ffffff' : '#cccccc'
          svg.selectAll('line').style('stroke', lineColor)
          return _.isFinite(v) ? 'url(#stripe)' : '#fff'
        })
        .style('opacity', function (d) {
          var v = options.stripesValue(d)
          return _.isFinite(v) ? 1 : 0
        })

      stripe.exit().remove()
    }
  },

  _onMouseMove: function (d, options) {
    var evt = d3.event

    var render = function () {
      return React.createElement(
        Tooltip,
        {left: evt.pageX + 2, top: evt.pageY + 2},
        options.name(d)
      )
    }

    if (this.layer) {
      this.layer._render = render
    } else {
      this.layer = new Layer(document.body, render)
    }

    this.layer.render()
  },

  _onMouseOut: function () {
    if (this.layer) {
      this.layer.destroy()
      this.layer = null
    }
  }
})

module.exports = ChoroplethMap
<|endoftext|>


<commit_before>module.exports = {
  src: [
    //--[ MAIN ]--//
    'web/built/openorchestrabackoffice/js/orchestraLib.js',
    'web/built/openorchestrabackoffice/js/tinyMCE/tinyMceConf.js',
    'web/built/openorchestrabackoffice/js/tinyMCE/bbcode2htmlConfigurator.js',
    'web/built/openorchestrabackoffice/js/tinyMCE/html2bbcodeConfigurator.js',
    'web/built/openorchestrabackoffice/js/tinyMCE/loadHtml2bbcodeInternalLink.js',
    'web/built/openorchestrabackoffice/js/viewConfigurator.js',
    'web/built/openorchestrabackoffice/js/setUpCallAjax.js',
    'web/built/openorchestrabackoffice/js/OrchestraView.js',
    'web/built/openorchestrabackoffice/js/OrchestraModalView.js',
    'web/built/openorchestrabackoffice/js/addPrototype.js',
    'web/built/openorchestrabackoffice/js/modelBackbone.js',
    'web/built/openorchestrabackoffice/js/FullPageFormView.js',
    'web/built/openorchestrabackoffice/js/ContentTypeFormView.js',
    'web/built/openorchestrabackoffice/js/FullPagePanelView.js',
    'web/built/openorchestrabackoffice/js/createNew.js',
    'web/built/openorchestrabackoffice/js/page/BlocksPanelView.js',
    'web/built/openorchestrabackoffice/js/security.js',
    'web/built/openorchestrabackoffice/js/SmartConfirmView.js',
    'web/built/openorchestrabackoffice/js/AdminFormView.js',
    'web/built/openorchestrabackoffice/js/FlashBagView.js',
    'web/built/openorchestrabackoffice/js/DisplayApiErrorView.js',
    'web/built/openorchestrabackoffice/js/generateId.js',

    //--[ AJAX LOADER ]--//
    'web/built/openorchestrabackoffice/js/ajaxLoader/AjaxLoaderView.js',

    //--[ BACKBONE ROUTER ]--//
    'web/built/openorchestrabackoffice/js/backboneRouter.js',
    'web/built/openorchestrabackoffice/js/page/LoadNodeConfigurationRoute.js',
    'web/built/openorchestrabackoffice/js/page/LoadTemplateConfigurationRoute.js',
    'web/built/openorchestrabackoffice/js/table/LoadTableConfigurationRoute.js',
    'web/built/openorchestrabackoffice/js/dashboard/LoadDashboardConfigurationRoute.js',
    'web/built/openorchestrabackoffice/js/underscoreTemplateLoader.js',

    //--[ EXTEND VIEWS ]--//
    'web/built/openorchestrabackoffice/js/extendView/addArea.js',
    'web/built/openorchestrabackoffice/js/extendView/commonPage.js',
    'web/built/openorchestrabackoffice/js/extendView/generateId.js',
    'web/built/openorchestrabackoffice/js/extendView/showVideo.js',
    'web/built/openorchestrabackoffice/js/extendView/deleteTree.js',
    'web/built/openorchestrabackoffice/js/extendView/submitAdmin.js',
    'web/built/openorchestrabackoffice/js/extendView/contentTypeSelector.js',

    //--[ WIDGETS ]--//
    'web/built/openorchestrabackoffice/js/widget/widgetChannel.js',
    'web/built/openorchestrabackoffice/js/widget/duplicateChannel.js',
    'web/built/openorchestrabackoffice/js/widget/DuplicateView.js',
    'web/built/openorchestrabackoffice/js/widget/languageChannel.js',
    'web/built/openorchestrabackoffice/js/widget/LanguageView.js',
    'web/built/openorchestrabackoffice/js/widget/previewLinkChannel.js',
    'web/built/openorchestrabackoffice/js/widget/PreviewLinkView.js',
    'web/built/openorchestrabackoffice/js/widget/statusChannel.js',
    'web/built/openorchestrabackoffice/js/widget/StatusView.js',
    'web/built/openorchestrabackoffice/js/widget/versionChannel.js',
    'web/built/openorchestrabackoffice/js/widget/VersionSelectView.js',
    'web/built/openorchestrabackoffice/js/widget/VersionView.js',

    //--[ DASHBOARD ]--//
    'web/built/openorchestrabackoffice/js/dashboard/DashboardView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/abstract/AbstractWidgetListView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/abstract/AbstractWidgetNodeListView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/abstract/AbstractWidgetContentListView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/LastNodesView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/DraftNodesView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/LastContentsView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/DraftContentsView.js',

    //--[ PAGE ]--//
    'web/built/openorchestrabackoffice/js/page/makeSortable.js',
    'web/built/openorchestrabackoffice/js/page/AreaView.js',
    'web/built/openorchestrabackoffice/js/page/GSAreaView.js',
    'web/built/openorchestrabackoffice/js/page/BlockView.js',
    'web/built/openorchestrabackoffice/js/page/NodeView.js',
    'web/built/openorchestrabackoffice/js/page/NodeFormView.js',
    'web/built/openorchestrabackoffice/js/page/TemplateView.js',
    'web/built/openorchestrabackoffice/js/page/GSTemplateView.js',
    'web/built/openorchestrabackoffice/js/page/TemplateFormView.js',
    'web/built/openorchestrabackoffice/js/page/SubElementFormView.js',
    'web/built/openorchestrabackoffice/js/page/showNode.js',
    'web/built/openorchestrabackoffice/js/page/showTemplate.js',
    'web/built/openorchestrabackoffice/js/page/orderNode.js',
    'web/built/openorchestrabackoffice/js/page/PageConfigurationButtonView.js',
    'web/built/openorchestrabackoffice/js/page/viewportChannel.js',
    'web/built/openorchestrabackoffice/js/page/FieldOptionDefaultValueView.js',

    //--[ AREA FLEX ]--//
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexChannel.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexAddRowExtendView.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexFormView.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexFormRowView.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexView.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexToolbarView.js',

    //--[ TEMPLATE FLEX ]--//
      'web/built/openorchestrabackoffice/js/templateFlex/TemplateFlexFormView.js',
      'web/built/openorchestrabackoffice/js/templateFlex/TemplateFlexView.js',
      'web/built/openorchestrabackoffice/js/templateFlex/TemplateFlexRouter.js',

    //--[ TAB ]--//
    'web/built/openorchestrabackoffice/js/tab/TabView.js',
    'web/built/openorchestrabackoffice/js/tab/TabElementFormView.js',
    'web/built/openorchestrabackoffice/js/tab/tabViewFormLoader.js',

    //--[ DATATABLE ]--//
    'web/built/openorchestrabackoffice/js/dataTable/plugins/InputFullPagination.js',
    'web/built/openorchestrabackoffice/js/dataTable/header/searchField/*.js',
    'web/built/openorchestrabackoffice/js/dataTable/header/*.js',
    'web/built/openorchestrabackoffice/js/dataTable/*.js',

    //--[ TABLEVIEW ]--//
    'web/built/openorchestrabackoffice/js/table/TableOrchestraPagination.js',
    'web/built/openorchestrabackoffice/js/table/TableChannel.js',
    'web/built/openorchestrabackoffice/js/table/TableviewAction.js',
    'web/built/openorchestrabackoffice/js/table/TableviewRestoreAction.js',
    'web/built/openorchestrabackoffice/js/table/TableviewCollectionView.js',
    'web/built/openorchestrabackoffice/js/table/tableviewLoader.js',

    //--[ USER ]--//
    'web/built/openorchestrabackoffice/js/user/UserFormView.js',
    'web/built/openorchestrauseradmin/js/user/*.js',
<<<<<<< HEAD
<<<<<<< HEAD

=======

>>>>>>> refraich page after site creation
=======

>>>>>>> refraich page after site creation
    //--[ CONTENT TYPE ]--//
    'web/built/openorchestrabackoffice/js/contentType/TableviewCollectionView.js',
    'web/built/openorchestrabackoffice/js/contentType/TableViewAction.js',

    //--[ WEBSITE ]--//
    'web/built/openorchestrabackoffice/js/webSite/WebSiteFormView.js',

    //--[ GROUP TREE ]--//
    'web/built/openorchestrabackoffice/js/groupTree/*.js',

    //--[ INTERNAL LINK ]--//
    'web/built/openorchestrabackoffice/js/InternalLinkFormView.js',

    //--[ FORM BEHAVIOR ]--//
    'web/built/openorchestrabackoffice/js/formBehavior/AbstractFormBehavior.js',
    'web/built/openorchestrabackoffice/js/formBehavior/FormLibraryBehavior.js',
    'web/built/openorchestrabackoffice/js/formBehavior/ColorPicker.js',
    'web/built/openorchestrabackoffice/js/formBehavior/DatePicker.js',
    'web/built/openorchestrabackoffice/js/formBehavior/HelpText.js',
    'web/built/openorchestrabackoffice/js/formBehavior/NodeChoice.js',
    'web/built/openorchestrabackoffice/js/formBehavior/RefreshForm.js',
    'web/built/openorchestrabackoffice/js/formBehavior/RichText.js',
    'web/built/openorchestrabackoffice/js/formBehavior/TagCondition.js',
    'web/built/openorchestrabackoffice/js/formBehavior/TagCreator.js',
    'web/built/openorchestrabackoffice/js/formBehavior/ValidateHidden.js',

  ],
  dest: 'web/built/orchestra.js'
};
<commit_msg>refraich page after site creation<commit_after>module.exports = {
  src: [
    //--[ MAIN ]--//
    'web/built/openorchestrabackoffice/js/orchestraLib.js',
    'web/built/openorchestrabackoffice/js/tinyMCE/tinyMceConf.js',
    'web/built/openorchestrabackoffice/js/tinyMCE/bbcode2htmlConfigurator.js',
    'web/built/openorchestrabackoffice/js/tinyMCE/html2bbcodeConfigurator.js',
    'web/built/openorchestrabackoffice/js/tinyMCE/loadHtml2bbcodeInternalLink.js',
    'web/built/openorchestrabackoffice/js/viewConfigurator.js',
    'web/built/openorchestrabackoffice/js/setUpCallAjax.js',
    'web/built/openorchestrabackoffice/js/OrchestraView.js',
    'web/built/openorchestrabackoffice/js/OrchestraModalView.js',
    'web/built/openorchestrabackoffice/js/addPrototype.js',
    'web/built/openorchestrabackoffice/js/modelBackbone.js',
    'web/built/openorchestrabackoffice/js/FullPageFormView.js',
    'web/built/openorchestrabackoffice/js/ContentTypeFormView.js',
    'web/built/openorchestrabackoffice/js/FullPagePanelView.js',
    'web/built/openorchestrabackoffice/js/createNew.js',
    'web/built/openorchestrabackoffice/js/page/BlocksPanelView.js',
    'web/built/openorchestrabackoffice/js/security.js',
    'web/built/openorchestrabackoffice/js/SmartConfirmView.js',
    'web/built/openorchestrabackoffice/js/AdminFormView.js',
    'web/built/openorchestrabackoffice/js/FlashBagView.js',
    'web/built/openorchestrabackoffice/js/DisplayApiErrorView.js',
    'web/built/openorchestrabackoffice/js/generateId.js',

    //--[ AJAX LOADER ]--//
    'web/built/openorchestrabackoffice/js/ajaxLoader/AjaxLoaderView.js',

    //--[ BACKBONE ROUTER ]--//
    'web/built/openorchestrabackoffice/js/backboneRouter.js',
    'web/built/openorchestrabackoffice/js/page/LoadNodeConfigurationRoute.js',
    'web/built/openorchestrabackoffice/js/page/LoadTemplateConfigurationRoute.js',
    'web/built/openorchestrabackoffice/js/table/LoadTableConfigurationRoute.js',
    'web/built/openorchestrabackoffice/js/dashboard/LoadDashboardConfigurationRoute.js',
    'web/built/openorchestrabackoffice/js/underscoreTemplateLoader.js',

    //--[ EXTEND VIEWS ]--//
    'web/built/openorchestrabackoffice/js/extendView/addArea.js',
    'web/built/openorchestrabackoffice/js/extendView/commonPage.js',
    'web/built/openorchestrabackoffice/js/extendView/generateId.js',
    'web/built/openorchestrabackoffice/js/extendView/showVideo.js',
    'web/built/openorchestrabackoffice/js/extendView/deleteTree.js',
    'web/built/openorchestrabackoffice/js/extendView/submitAdmin.js',
    'web/built/openorchestrabackoffice/js/extendView/contentTypeSelector.js',

    //--[ WIDGETS ]--//
    'web/built/openorchestrabackoffice/js/widget/widgetChannel.js',
    'web/built/openorchestrabackoffice/js/widget/duplicateChannel.js',
    'web/built/openorchestrabackoffice/js/widget/DuplicateView.js',
    'web/built/openorchestrabackoffice/js/widget/languageChannel.js',
    'web/built/openorchestrabackoffice/js/widget/LanguageView.js',
    'web/built/openorchestrabackoffice/js/widget/previewLinkChannel.js',
    'web/built/openorchestrabackoffice/js/widget/PreviewLinkView.js',
    'web/built/openorchestrabackoffice/js/widget/statusChannel.js',
    'web/built/openorchestrabackoffice/js/widget/StatusView.js',
    'web/built/openorchestrabackoffice/js/widget/versionChannel.js',
    'web/built/openorchestrabackoffice/js/widget/VersionSelectView.js',
    'web/built/openorchestrabackoffice/js/widget/VersionView.js',

    //--[ DASHBOARD ]--//
    'web/built/openorchestrabackoffice/js/dashboard/DashboardView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/abstract/AbstractWidgetListView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/abstract/AbstractWidgetNodeListView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/abstract/AbstractWidgetContentListView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/LastNodesView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/DraftNodesView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/LastContentsView.js',
    'web/built/openorchestrabackoffice/js/dashboard/widget/DraftContentsView.js',

    //--[ PAGE ]--//
    'web/built/openorchestrabackoffice/js/page/makeSortable.js',
    'web/built/openorchestrabackoffice/js/page/AreaView.js',
    'web/built/openorchestrabackoffice/js/page/GSAreaView.js',
    'web/built/openorchestrabackoffice/js/page/BlockView.js',
    'web/built/openorchestrabackoffice/js/page/NodeView.js',
    'web/built/openorchestrabackoffice/js/page/NodeFormView.js',
    'web/built/openorchestrabackoffice/js/page/TemplateView.js',
    'web/built/openorchestrabackoffice/js/page/GSTemplateView.js',
    'web/built/openorchestrabackoffice/js/page/TemplateFormView.js',
    'web/built/openorchestrabackoffice/js/page/SubElementFormView.js',
    'web/built/openorchestrabackoffice/js/page/showNode.js',
    'web/built/openorchestrabackoffice/js/page/showTemplate.js',
    'web/built/openorchestrabackoffice/js/page/orderNode.js',
    'web/built/openorchestrabackoffice/js/page/PageConfigurationButtonView.js',
    'web/built/openorchestrabackoffice/js/page/viewportChannel.js',
    'web/built/openorchestrabackoffice/js/page/FieldOptionDefaultValueView.js',

    //--[ AREA FLEX ]--//
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexChannel.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexAddRowExtendView.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexFormView.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexFormRowView.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexView.js',
    'web/built/openorchestrabackoffice/js/areaFlex/AreaFlexToolbarView.js',

    //--[ TEMPLATE FLEX ]--//
      'web/built/openorchestrabackoffice/js/templateFlex/TemplateFlexFormView.js',
      'web/built/openorchestrabackoffice/js/templateFlex/TemplateFlexView.js',
      'web/built/openorchestrabackoffice/js/templateFlex/TemplateFlexRouter.js',

    //--[ TAB ]--//
    'web/built/openorchestrabackoffice/js/tab/TabView.js',
    'web/built/openorchestrabackoffice/js/tab/TabElementFormView.js',
    'web/built/openorchestrabackoffice/js/tab/tabViewFormLoader.js',

    //--[ DATATABLE ]--//
    'web/built/openorchestrabackoffice/js/dataTable/plugins/InputFullPagination.js',
    'web/built/openorchestrabackoffice/js/dataTable/header/searchField/*.js',
    'web/built/openorchestrabackoffice/js/dataTable/header/*.js',
    'web/built/openorchestrabackoffice/js/dataTable/*.js',

    //--[ TABLEVIEW ]--//
    'web/built/openorchestrabackoffice/js/table/TableOrchestraPagination.js',
    'web/built/openorchestrabackoffice/js/table/TableChannel.js',
    'web/built/openorchestrabackoffice/js/table/TableviewAction.js',
    'web/built/openorchestrabackoffice/js/table/TableviewRestoreAction.js',
    'web/built/openorchestrabackoffice/js/table/TableviewCollectionView.js',
    'web/built/openorchestrabackoffice/js/table/tableviewLoader.js',

    //--[ USER ]--//
    'web/built/openorchestrabackoffice/js/user/UserFormView.js',
    'web/built/openorchestrauseradmin/js/user/*.js',

    //--[ CONTENT TYPE ]--//
    'web/built/openorchestrabackoffice/js/contentType/TableviewCollectionView.js',
    'web/built/openorchestrabackoffice/js/contentType/TableViewAction.js',

    //--[ WEBSITE ]--//
    'web/built/openorchestrabackoffice/js/webSite/WebSiteFormView.js',

    //--[ GROUP TREE ]--//
    'web/built/openorchestrabackoffice/js/groupTree/*.js',

    //--[ INTERNAL LINK ]--//
    'web/built/openorchestrabackoffice/js/InternalLinkFormView.js',

    //--[ FORM BEHAVIOR ]--//
    'web/built/openorchestrabackoffice/js/formBehavior/AbstractFormBehavior.js',
    'web/built/openorchestrabackoffice/js/formBehavior/FormLibraryBehavior.js',
    'web/built/openorchestrabackoffice/js/formBehavior/ColorPicker.js',
    'web/built/openorchestrabackoffice/js/formBehavior/DatePicker.js',
    'web/built/openorchestrabackoffice/js/formBehavior/HelpText.js',
    'web/built/openorchestrabackoffice/js/formBehavior/NodeChoice.js',
    'web/built/openorchestrabackoffice/js/formBehavior/RefreshForm.js',
    'web/built/openorchestrabackoffice/js/formBehavior/RichText.js',
    'web/built/openorchestrabackoffice/js/formBehavior/TagCondition.js',
    'web/built/openorchestrabackoffice/js/formBehavior/TagCreator.js',
    'web/built/openorchestrabackoffice/js/formBehavior/ValidateHidden.js',

  ],
  dest: 'web/built/orchestra.js'
};
<|endoftext|>


<commit_before>
var webpack = require('webpack');
var nodeExternals = require('webpack-node-externals');

var helpers = require('../config/helpers');

module.exports = helpers.extend(
  'webpack.base.js',
  helpers.removePlugin.bind(null, null),
  helpers.removePlugin.bind(null, webpack.DllReferencePlugin),
  {
    target: 'node',
    entry: [
      'source-map-support/register',
      'hops-entry-point'
    ],
    output: {
      filename: 'bundle.js',
      libraryTarget: 'commonjs2'
    },
    devtool: '#inline-source-map',
    externals: [nodeExternals()],
    cache: {},
    // resolve: {
    //   mainFields: ['main']
    // },
    resolveLoader: {
      alias: {
        'style-loader': 'fake-style-loader',
        'style': 'fake-style-loader'
      }
    },
    extend: helpers.extend.bind(null, __filename)
  }
);
<commit_msg>fix node module resolution<commit_after>
var webpack = require('webpack');
var nodeExternals = require('webpack-node-externals');

var helpers = require('../config/helpers');

module.exports = helpers.extend(
  'webpack.base.js',
  helpers.removePlugin.bind(null, null),
  helpers.removePlugin.bind(null, webpack.DllReferencePlugin),
  {
    target: 'node',
    entry: [
      'source-map-support/register',
      'hops-entry-point'
    ],
    output: {
      filename: 'bundle.js',
      libraryTarget: 'commonjs2'
    },
    devtool: '#inline-source-map',
    externals: [nodeExternals()],
    cache: {},
    resolve: {
      mainFields: ['main']
    },
    resolveLoader: {
      alias: {
        'style-loader': 'fake-style-loader',
        'style': 'fake-style-loader'
      }
    },
    extend: helpers.extend.bind(null, __filename)
  }
);
<|endoftext|>


<commit_before>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    "underscore",
    "backbone",
    "jquery",
    "base/js/utils",
    "base/js/namespace",
    "services/kernels/comm"
], function (_, Backbone, $, utils, IPython, comm) {
    "use strict";
    //--------------------------------------------------------------------
    // WidgetManager class
    //--------------------------------------------------------------------
    var WidgetManager = function (comm_manager, notebook) {
        /**
         * Public constructor
         */
        WidgetManager._managers.push(this);

        // Attach a comm manager to the
        this.keyboard_manager = notebook.keyboard_manager;
        this.notebook = notebook;
        this.comm_manager = comm_manager;
        this.comm_target_name = 'ipython.widget';
        this._models = {}; /* Dictionary of model ids and model instance promises */

        // Register with the comm manager.
        this.comm_manager.register_target(this.comm_target_name, $.proxy(this._handle_comm_open, this));

        // Load the initial state of the widget manager if a load callback was
        // registered.
        if (WidgetManager._load_callback) {
            this.set_state(WidgetManager._load_callback.call(this));
        }

        // Setup state saving code.
        var that = this;
        this.notebook.events.on('notebook_saved.Notebook', function() {
            var save_callback = WidgetManager._save_callback;
            var options = WidgetManager._get_state_options;
            if (save_callback) {
                that.get_state(options).then(function(state) {
                    save_callback.call(that, state);
                }).catch(utils.reject('Could not call widget save state callback.', true));
            }
        });
    };

    //--------------------------------------------------------------------
    // Class level
    //--------------------------------------------------------------------
    WidgetManager._model_types = {}; /* Dictionary of model type names (target_name) and model types. */
    WidgetManager._view_types = {}; /* Dictionary of view names and view types. */
    WidgetManager._managers = []; /* List of widget managers */
    WidgetManager._load_callback = null;
    WidgetManager._save_callback = null;

    WidgetManager.register_widget_model = function (model_name, model_type) {
        // Registers a widget model by name.
        WidgetManager._model_types[model_name] = model_type;
    };

    WidgetManager.register_widget_view = function (view_name, view_type) {
        // Registers a widget view by name.
        WidgetManager._view_types[view_name] = view_type;
    };

    WidgetManager.set_state_callbacks = function (load_callback, save_callback, options) {
        // Registers callbacks for widget state persistence.
        WidgetManager._load_callback = load_callback;
        WidgetManager._save_callback = save_callback;
        WidgetManager._get_state_options = options;

        // Use the load callback to immediately load widget states.
        WidgetManager._managers.forEach(function(manager) {
            if (load_callback) {
                manager.set_state(load_callback.call(manager));
            }
        });
    };

    //--------------------------------------------------------------------
    // Instance level
    //--------------------------------------------------------------------
    WidgetManager.prototype.display_view = function(msg, model) {
        /**
         * Displays a view for a particular model.
         */
        var that = this;
        return new Promise(function(resolve, reject) {
            var cell = that.get_msg_cell(msg.parent_header.msg_id);
            if (cell === null) {
                reject(new Error("Could not determine where the display" +
                    " message was from.  Widget will not be displayed"));
            } else {
                return that.display_view_in_cell(cell, model)
                .catch(function(error) {
                    reject(new utils.WrappedError('View could not be displayed.', error));
                });
            }
        });
    };

    WidgetManager.prototype.display_view_in_cell = function(cell, model) {
        // Displays a view in a cell.
        var that = this;
        return new Promise(function(resolve, reject) {
            if (cell.display_widget_view) {
                cell.display_widget_view(that.create_view(model, {cell: cell}))
                .then(function(view) {
                    that._handle_display_view(view);
                    view.trigger('displayed');
                    resolve(view);
                }, function(error) {
                    reject(new utils.WrappedError('Could not create or display view', error));
                });
            } else {
                reject(new Error('Cell does not have a `display_widget_view` method'));
            }
        });
    };

    WidgetManager.prototype._handle_display_view = function (view) {
        /**
         * Have the IPython keyboard manager disable its event
         * handling so the widget can capture keyboard input.
         * Note, this is only done on the outer most widgets.
         */
        if (this.keyboard_manager) {
            this.keyboard_manager.register_events(view.$el);

            if (view.additional_elements) {
                for (var i = 0; i < view.additional_elements.length; i++) {
                    this.keyboard_manager.register_events(view.additional_elements[i]);
                }
            }
        }
    };

    WidgetManager.prototype.create_view = function(model, options) {
        /**
         * Creates a promise for a view of a given model
         *
         * Make sure the view creation is not out of order with
         * any state updates.
         */
        model.state_change = model.state_change.then(function() {

            return utils.load_class(model.get('_view_name'), model.get('_view_module'),
            WidgetManager._view_types).then(function(ViewType) {

                // If a view is passed into the method, use that view's cell as
                // the cell for the view that is created.
                options = options || {};
                if (options.parent !== undefined) {
                    options.cell = options.parent.options.cell;
                }
                // Create and render the view...
                var parameters = {model: model, options: options};
                var view = new ViewType(parameters);
                view.listenTo(model, 'destroy', view.remove);
                return Promise.resolve(view.render()).then(function() {return view;});
            }).catch(utils.reject("Couldn't create a view for model id '" + String(model.id) + "'", true));
        });
        model.views[utils.uuid()] = model.state_change;
        return model.state_change;
    };

    WidgetManager.prototype.get_msg_cell = function (msg_id) {
        var cell = null;
        // First, check to see if the msg was triggered by cell execution.
        if (this.notebook) {
            cell = this.notebook.get_msg_cell(msg_id);
        }
        if (cell !== null) {
            return cell;
        }
        // Second, check to see if a get_cell callback was defined
        // for the message.  get_cell callbacks are registered for
        // widget messages, so this block is actually checking to see if the
        // message was triggered by a widget.
        var kernel = this.comm_manager.kernel;
        if (kernel) {
            var callbacks = kernel.get_callbacks_for_msg(msg_id);
            if (callbacks && callbacks.iopub &&
                callbacks.iopub.get_cell !== undefined) {
                return callbacks.iopub.get_cell();
            }
        }

        // Not triggered by a cell or widget (no get_cell callback
        // exists).
        return null;
    };

    WidgetManager.prototype.callbacks = function (view) {
        /**
         * callback handlers specific a view
         */
        var callbacks = {};
        if (view && view.options.cell) {

            // Try to get output handlers
            var cell = view.options.cell;
            var handle_output = null;
            var handle_clear_output = null;
            if (cell.output_area) {
                handle_output = $.proxy(cell.output_area.handle_output, cell.output_area);
                handle_clear_output = $.proxy(cell.output_area.handle_clear_output, cell.output_area);
            }

            // Create callback dictionary using what is known
            var that = this;
            callbacks = {
                iopub : {
                    output : handle_output,
                    clear_output : handle_clear_output,

                    // Special function only registered by widget messages.
                    // Allows us to get the cell for a message so we know
                    // where to add widgets if the code requires it.
                    get_cell : function () {
                        return cell;
                    },
                },
            };
        }
        return callbacks;
    };

    WidgetManager.prototype.get_model = function (model_id) {
        /**
         * Get a promise for a model by model id.
         */
        return this._models[model_id];
    };

    WidgetManager.prototype._handle_comm_open = function (comm, msg) {
        /**
         * Handle when a comm is opened.
         */
        return this.create_model({
            model_name: msg.content.data.model_name,
            model_module: msg.content.data.model_module,
            comm: comm}).catch(utils.reject("Couldn't create a model.", true));
    };

    WidgetManager.prototype.create_model = function (options) {
        /**
         * Create and return a promise for a new widget model
         *
         * Minimally, one must provide the model_name and widget_class
         * parameters to create a model from Javascript.
         *
         * Example
         * --------
         * JS:
         * IPython.notebook.kernel.widget_manager.create_model({
         *      model_name: 'WidgetModel',
         *      widget_class: 'IPython.html.widgets.widget_int.IntSlider'})
         *      .then(function(model) { console.log('Create success!', model); },
         *      $.proxy(console.error, console));
         *
         * Parameters
         * ----------
         * options: dictionary
         *  Dictionary of options with the following contents:
         *      model_name: string
         *          Target name of the widget model to create.
         *      model_module: (optional) string
         *          Module name of the widget model to create.
         *      widget_class: (optional) string
         *          Target name of the widget in the back-end.
         *      comm: (optional) Comm
         *
         * Create a comm if it wasn't provided.
         */
        var comm = options.comm;
        if (!comm) {
            comm = this.comm_manager.new_comm('ipython.widget', {'widget_class': options.widget_class});
        }

        var that = this;
        var model_id = comm.comm_id;
        var model_promise =  utils.load_class(options.model_name, options.model_module, WidgetManager._model_types)
            .then(function(ModelType) {
                var widget_model = new ModelType(that, model_id, comm);
                widget_model.once('comm:close', function () {
                    delete that._models[model_id];
                });
                widget_model.name = options.model_name;
                widget_model.module = options.model_module;
                return widget_model;

            }, function(error) {
                delete that._models[model_id];
                var wrapped_error = new utils.WrappedError("Couldn't create model", error);
                return Promise.reject(wrapped_error);
            });
        this._models[model_id] = model_promise;
        return model_promise;
    };

    WidgetManager.prototype.get_state = function(options) {
        // Asynchronously get the state of the widget manager.
        //
        // This includes all of the widget models and the cells that they are
        // displayed in.
        //
        // Parameters
        // ----------
        // options: dictionary
        //  Dictionary of options with the following contents:
        //      only_displayed: (optional) boolean=false
        //          Only return models with one or more displayed views.
        //      not_alive: (optional) boolean=false
        //          Include models that have comms with severed connections.
        //
        // Returns
        // -------
        // Promise for a state dictionary
        var that = this;
        return utils.resolve_promises_dict(this._models).then(function(models) {
            var state = {};
            for (var model_id in models) {
                if (models.hasOwnProperty(model_id)) {
                    var model = models[model_id];

                    // If the model has one or more views defined for it,
                    // consider it displayed.
                    var displayed_flag = !(options && options.only_displayed) || Object.keys(model.views).length > 0;
                    var alive_flag = (options && options.not_alive) || model.comm_alive;
                    if (displayed_flag && alive_flag) {
                        state[model_id] = {
                            model_name: model.name,
                            model_module: model.module,
                            state: model.get_state(),
                            views: [],
                        };

                        // Get the views that are displayed *now*.
                        for (var id in model.views) {
                            if (model.views.hasOwnProperty(id)) {
                                var view = model.views[id];
                                var cell_index = that.notebook.find_cell_index(view.options.cell);
                                state[model_id].views.push(cell_index);
                            }
                        }
                    }
                }
            }
            return state;
        });
    };

    WidgetManager.prototype.set_state = function(state) {
        // Set the notebook's state.
        //
        // Reconstructs all of the widget models and attempts to redisplay the
        // widgets in the appropriate cells by cell index.

        // Get the kernel when it's available.
        var that = this;
        return this._get_connected_kernel().then(function(kernel) {

            // Recreate all the widget models for the given state and
            // display the views.
            that.all_views = [];
            var model_ids = Object.keys(state);
            for (var i = 0; i < model_ids.length; i++) {
                var model_id = model_ids[i];

                // Recreate a comm using the widget's model id (model_id == comm_id).
                var new_comm = new comm.Comm(kernel.widget_manager.comm_target_name, model_id);
                kernel.comm_manager.register_comm(new_comm);

                // Create the model using the recreated comm.  When the model is
                // created we don't know yet if the comm is valid so set_comm_alive
                // false.  Once we receive the first state push from the back-end
                // we know the comm is alive.
                var views = kernel.widget_manager.create_model({
                    comm: new_comm,
                    model_name: state[model_id].model_name,
                    model_module: state[model_id].model_module})
                .then(function(model) {

                    model.set_comm_alive(false);
                    var view_promise = Promise.resolve().then(function() {
                        return model.set_state(state[model.id].state);
                    }).then(function() {
                        model.request_state().then(function() {
                            model.set_comm_alive(true);
                        });

                        // Display the views of the model.
                        var views = [];
                        var model_views = state[model.id].views;
                        for (var j=0; j<model_views.length; j++) {
                            var cell_index = model_views[j];
                            var cell = that.notebook.get_cell(cell_index);
                            views.push(that.display_view_in_cell(cell, model));
                        }
                        return Promise.all(views);
                    });
                    return view_promise;
                });
                that.all_views.push(views);
            }
            return Promise.all(that.all_views);
        }).catch(utils.reject('Could not set widget manager state.', true));
    };

    WidgetManager.prototype._get_connected_kernel = function() {
        // Gets a promise for a connected kernel.
        var that = this;
        return new Promise(function(resolve, reject) {
            if (that.comm_manager &&
                that.comm_manager.kernel &&
                that.comm_manager.kernel.is_connected()) {

                resolve(that.comm_manager.kernel);
            } else {
                that.notebook.events.on('kernel_connected.Kernel', function(event, data) {
                    resolve(data.kernel);
                });
            }
        });
    };

    // Backwards compatibility.
    IPython.WidgetManager = WidgetManager;

    return {'WidgetManager': WidgetManager};
});
<commit_msg>Fix, only return views that are direct children of the cell<commit_after>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    "underscore",
    "backbone",
    "jquery",
    "base/js/utils",
    "base/js/namespace",
    "services/kernels/comm"
], function (_, Backbone, $, utils, IPython, comm) {
    "use strict";
    //--------------------------------------------------------------------
    // WidgetManager class
    //--------------------------------------------------------------------
    var WidgetManager = function (comm_manager, notebook) {
        /**
         * Public constructor
         */
        WidgetManager._managers.push(this);

        // Attach a comm manager to the
        this.keyboard_manager = notebook.keyboard_manager;
        this.notebook = notebook;
        this.comm_manager = comm_manager;
        this.comm_target_name = 'ipython.widget';
        this._models = {}; /* Dictionary of model ids and model instance promises */

        // Register with the comm manager.
        this.comm_manager.register_target(this.comm_target_name, $.proxy(this._handle_comm_open, this));

        // Load the initial state of the widget manager if a load callback was
        // registered.
        if (WidgetManager._load_callback) {
            this.set_state(WidgetManager._load_callback.call(this));
        }

        // Setup state saving code.
        var that = this;
        this.notebook.events.on('notebook_saved.Notebook', function() {
            var save_callback = WidgetManager._save_callback;
            var options = WidgetManager._get_state_options;
            if (save_callback) {
                that.get_state(options).then(function(state) {
                    save_callback.call(that, state);
                }).catch(utils.reject('Could not call widget save state callback.', true));
            }
        });
    };

    //--------------------------------------------------------------------
    // Class level
    //--------------------------------------------------------------------
    WidgetManager._model_types = {}; /* Dictionary of model type names (target_name) and model types. */
    WidgetManager._view_types = {}; /* Dictionary of view names and view types. */
    WidgetManager._managers = []; /* List of widget managers */
    WidgetManager._load_callback = null;
    WidgetManager._save_callback = null;

    WidgetManager.register_widget_model = function (model_name, model_type) {
        // Registers a widget model by name.
        WidgetManager._model_types[model_name] = model_type;
    };

    WidgetManager.register_widget_view = function (view_name, view_type) {
        // Registers a widget view by name.
        WidgetManager._view_types[view_name] = view_type;
    };

    WidgetManager.set_state_callbacks = function (load_callback, save_callback, options) {
        // Registers callbacks for widget state persistence.
        WidgetManager._load_callback = load_callback;
        WidgetManager._save_callback = save_callback;
        WidgetManager._get_state_options = options;

        // Use the load callback to immediately load widget states.
        WidgetManager._managers.forEach(function(manager) {
            if (load_callback) {
                manager.set_state(load_callback.call(manager));
            }
        });
    };

    //--------------------------------------------------------------------
    // Instance level
    //--------------------------------------------------------------------
    WidgetManager.prototype.display_view = function(msg, model) {
        /**
         * Displays a view for a particular model.
         */
        var that = this;
        return new Promise(function(resolve, reject) {
            var cell = that.get_msg_cell(msg.parent_header.msg_id);
            if (cell === null) {
                reject(new Error("Could not determine where the display" +
                    " message was from.  Widget will not be displayed"));
            } else {
                return that.display_view_in_cell(cell, model)
                .catch(function(error) {
                    reject(new utils.WrappedError('View could not be displayed.', error));
                });
            }
        });
    };

    WidgetManager.prototype.display_view_in_cell = function(cell, model) {
        // Displays a view in a cell.
        var that = this;
        return new Promise(function(resolve, reject) {
            if (cell.display_widget_view) {
                cell.display_widget_view(that.create_view(model, {cell: cell}))
                .then(function(view) {
                    that._handle_display_view(view);
                    view.trigger('displayed');
                    resolve(view);
                }, function(error) {
                    reject(new utils.WrappedError('Could not create or display view', error));
                });
            } else {
                reject(new Error('Cell does not have a `display_widget_view` method'));
            }
        });
    };

    WidgetManager.prototype._handle_display_view = function (view) {
        /**
         * Have the IPython keyboard manager disable its event
         * handling so the widget can capture keyboard input.
         * Note, this is only done on the outer most widgets.
         */
        if (this.keyboard_manager) {
            this.keyboard_manager.register_events(view.$el);

            if (view.additional_elements) {
                for (var i = 0; i < view.additional_elements.length; i++) {
                    this.keyboard_manager.register_events(view.additional_elements[i]);
                }
            }
        }
    };

    WidgetManager.prototype.create_view = function(model, options) {
        /**
         * Creates a promise for a view of a given model
         *
         * Make sure the view creation is not out of order with
         * any state updates.
         */
        model.state_change = model.state_change.then(function() {

            return utils.load_class(model.get('_view_name'), model.get('_view_module'),
            WidgetManager._view_types).then(function(ViewType) {

                // If a view is passed into the method, use that view's cell as
                // the cell for the view that is created.
                options = options || {};
                if (options.parent !== undefined) {
                    options.cell = options.parent.options.cell;
                }
                // Create and render the view...
                var parameters = {model: model, options: options};
                var view = new ViewType(parameters);
                view.listenTo(model, 'destroy', view.remove);
                return Promise.resolve(view.render()).then(function() {return view;});
            }).catch(utils.reject("Couldn't create a view for model id '" + String(model.id) + "'", true));
        });
        model.views[utils.uuid()] = model.state_change;
        return model.state_change;
    };

    WidgetManager.prototype.get_msg_cell = function (msg_id) {
        var cell = null;
        // First, check to see if the msg was triggered by cell execution.
        if (this.notebook) {
            cell = this.notebook.get_msg_cell(msg_id);
        }
        if (cell !== null) {
            return cell;
        }
        // Second, check to see if a get_cell callback was defined
        // for the message.  get_cell callbacks are registered for
        // widget messages, so this block is actually checking to see if the
        // message was triggered by a widget.
        var kernel = this.comm_manager.kernel;
        if (kernel) {
            var callbacks = kernel.get_callbacks_for_msg(msg_id);
            if (callbacks && callbacks.iopub &&
                callbacks.iopub.get_cell !== undefined) {
                return callbacks.iopub.get_cell();
            }
        }

        // Not triggered by a cell or widget (no get_cell callback
        // exists).
        return null;
    };

    WidgetManager.prototype.callbacks = function (view) {
        /**
         * callback handlers specific a view
         */
        var callbacks = {};
        if (view && view.options.cell) {

            // Try to get output handlers
            var cell = view.options.cell;
            var handle_output = null;
            var handle_clear_output = null;
            if (cell.output_area) {
                handle_output = $.proxy(cell.output_area.handle_output, cell.output_area);
                handle_clear_output = $.proxy(cell.output_area.handle_clear_output, cell.output_area);
            }

            // Create callback dictionary using what is known
            var that = this;
            callbacks = {
                iopub : {
                    output : handle_output,
                    clear_output : handle_clear_output,

                    // Special function only registered by widget messages.
                    // Allows us to get the cell for a message so we know
                    // where to add widgets if the code requires it.
                    get_cell : function () {
                        return cell;
                    },
                },
            };
        }
        return callbacks;
    };

    WidgetManager.prototype.get_model = function (model_id) {
        /**
         * Get a promise for a model by model id.
         */
        return this._models[model_id];
    };

    WidgetManager.prototype._handle_comm_open = function (comm, msg) {
        /**
         * Handle when a comm is opened.
         */
        return this.create_model({
            model_name: msg.content.data.model_name,
            model_module: msg.content.data.model_module,
            comm: comm}).catch(utils.reject("Couldn't create a model.", true));
    };

    WidgetManager.prototype.create_model = function (options) {
        /**
         * Create and return a promise for a new widget model
         *
         * Minimally, one must provide the model_name and widget_class
         * parameters to create a model from Javascript.
         *
         * Example
         * --------
         * JS:
         * IPython.notebook.kernel.widget_manager.create_model({
         *      model_name: 'WidgetModel',
         *      widget_class: 'IPython.html.widgets.widget_int.IntSlider'})
         *      .then(function(model) { console.log('Create success!', model); },
         *      $.proxy(console.error, console));
         *
         * Parameters
         * ----------
         * options: dictionary
         *  Dictionary of options with the following contents:
         *      model_name: string
         *          Target name of the widget model to create.
         *      model_module: (optional) string
         *          Module name of the widget model to create.
         *      widget_class: (optional) string
         *          Target name of the widget in the back-end.
         *      comm: (optional) Comm
         *
         * Create a comm if it wasn't provided.
         */
        var comm = options.comm;
        if (!comm) {
            comm = this.comm_manager.new_comm('ipython.widget', {'widget_class': options.widget_class});
        }

        var that = this;
        var model_id = comm.comm_id;
        var model_promise =  utils.load_class(options.model_name, options.model_module, WidgetManager._model_types)
            .then(function(ModelType) {
                var widget_model = new ModelType(that, model_id, comm);
                widget_model.once('comm:close', function () {
                    delete that._models[model_id];
                });
                widget_model.name = options.model_name;
                widget_model.module = options.model_module;
                return widget_model;

            }, function(error) {
                delete that._models[model_id];
                var wrapped_error = new utils.WrappedError("Couldn't create model", error);
                return Promise.reject(wrapped_error);
            });
        this._models[model_id] = model_promise;
        return model_promise;
    };

    WidgetManager.prototype.get_state = function(options) {
        // Asynchronously get the state of the widget manager.
        //
        // This includes all of the widget models and the cells that they are
        // displayed in.
        //
        // Parameters
        // ----------
        // options: dictionary
        //  Dictionary of options with the following contents:
        //      only_displayed: (optional) boolean=false
        //          Only return models with one or more displayed views.
        //      not_alive: (optional) boolean=false
        //          Include models that have comms with severed connections.
        //
        // Returns
        // -------
        // Promise for a state dictionary
        var that = this;
        return utils.resolve_promises_dict(this._models).then(function(models) {
            var state = {};
            for (var model_id in models) {
                if (models.hasOwnProperty(model_id)) {
                    var model = models[model_id];

                    // If the model has one or more views defined for it,
                    // consider it displayed.
                    var displayed_flag = !(options && options.only_displayed) || Object.keys(model.views).length > 0;
                    var alive_flag = (options && options.not_alive) || model.comm_alive;
                    if (displayed_flag && alive_flag) {
                        state[model_id] = {
                            model_name: model.name,
                            model_module: model.module,
                            state: model.get_state(),
                            views: [],
                        };

                        // Get the views that are displayed *now*.
                        for (var id in model.views) {
                            if (model.views.hasOwnProperty(id)) {
                                var view = model.views[id];
                                var cell = view.options.cell;

                                // Only store the cell reference if this view is a top level
                                // child of the cell.
                                if (cell.widget_views.indexOf(view) != -1) {
                                    var cell_index = that.notebook.find_cell_index(cell);
                                    state[model_id].views.push(cell_index);
                                }
                            }
                        }
                    }
                }
            }
            return state;
        });
    };

    WidgetManager.prototype.set_state = function(state) {
        // Set the notebook's state.
        //
        // Reconstructs all of the widget models and attempts to redisplay the
        // widgets in the appropriate cells by cell index.

        // Get the kernel when it's available.
        var that = this;
        return this._get_connected_kernel().then(function(kernel) {

            // Recreate all the widget models for the given state and
            // display the views.
            that.all_views = [];
            var model_ids = Object.keys(state);
            for (var i = 0; i < model_ids.length; i++) {
                var model_id = model_ids[i];

                // Recreate a comm using the widget's model id (model_id == comm_id).
                var new_comm = new comm.Comm(kernel.widget_manager.comm_target_name, model_id);
                kernel.comm_manager.register_comm(new_comm);

                // Create the model using the recreated comm.  When the model is
                // created we don't know yet if the comm is valid so set_comm_alive
                // false.  Once we receive the first state push from the back-end
                // we know the comm is alive.
                var views = kernel.widget_manager.create_model({
                    comm: new_comm,
                    model_name: state[model_id].model_name,
                    model_module: state[model_id].model_module})
                .then(function(model) {

                    model.set_comm_alive(false);
                    var view_promise = Promise.resolve().then(function() {
                        return model.set_state(state[model.id].state);
                    }).then(function() {
                        model.request_state().then(function() {
                            model.set_comm_alive(true);
                        });

                        // Display the views of the model.
                        var views = [];
                        var model_views = state[model.id].views;
                        for (var j=0; j<model_views.length; j++) {
                            var cell_index = model_views[j];
                            var cell = that.notebook.get_cell(cell_index);
                            views.push(that.display_view_in_cell(cell, model));
                        }
                        return Promise.all(views);
                    });
                    return view_promise;
                });
                that.all_views.push(views);
            }
            return Promise.all(that.all_views);
        }).catch(utils.reject('Could not set widget manager state.', true));
    };

    WidgetManager.prototype._get_connected_kernel = function() {
        // Gets a promise for a connected kernel.
        var that = this;
        return new Promise(function(resolve, reject) {
            if (that.comm_manager &&
                that.comm_manager.kernel &&
                that.comm_manager.kernel.is_connected()) {

                resolve(that.comm_manager.kernel);
            } else {
                that.notebook.events.on('kernel_connected.Kernel', function(event, data) {
                    resolve(data.kernel);
                });
            }
        });
    };

    // Backwards compatibility.
    IPython.WidgetManager = WidgetManager;

    return {'WidgetManager': WidgetManager};
});
<|endoftext|>


<commit_before>const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        use: "url-loader?limit=10000&mimetype=application/font-woff",
      },
      {
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        use: "file-loader",
      },
    ]
  },
};
<commit_msg>Webpack: fonts are working.<commit_after>const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        use: [
          {
            loader: "url-loader?limit=10000&mimetype=application/font-woff",
            options: {
              name: '[name].[ext]',
              outputPath: 'fonts/'
            }
          },
        ]
      },
      {
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[name].[ext]',
              outputPath: 'fonts/'
            }
          }
        ]
      },
    ]
  },
};
<|endoftext|>


<commit_before>'use strict';

let FLAGS = [
  {name: 'partitions',          description: 'number of partitions to give the topic',                            hasValue: true,  optional: false},
  {name: 'replication-factor',  description: 'number of replicas the topic should be created across',             hasValue: true,  optional: true},
  {name: 'retention-time',      description: 'The length of time messages in the topic should be retained for.',  hasValue: true,  optional: true},
  {name: 'compaction',          description: 'Whether to use compaction for this topic',                          hasValue: false, optional: true}
];
let DOT_WAITING_TIME = 200;

let cli = require('heroku-cli-util');
let co = require('co');
let HerokuKafkaClusters = require('./clusters.js').HerokuKafkaClusters;
let sleep = require('co-sleep');
let _ = require('underscore');

function extractFlags(contextFlags) {
  // This just ensures that we only ever get the flags we expect,
  // and don't get any additional keys out of the heroku cli flags object
  // (if there happen to be any).
  var out = {};
  _.each(FLAGS, function (flag) {
    if (contextFlags[flag.name] !== undefined) {
      out[flag.name] = contextFlags[flag.name];
    }
  });
  return out;
}

function* printWaitingDots() {
  yield sleep(DOT_WAITING_TIME);
  process.stdout.write('.');
  yield sleep(DOT_WAITING_TIME);
  process.stdout.write('.');
  yield sleep(DOT_WAITING_TIME);
  process.stdout.write('.');
}

function* createTopic (context, heroku) {
  if (context.args.CLUSTER) {
    process.stdout.write(`Creating ${context.args.TOPIC} on ${context.args.CLUSTER}`);
  } else {
    process.stdout.write(`Creating ${context.args.TOPIC}`);
  }
  var flags = extractFlags(context.flags);
  var creation = new HerokuKafkaClusters(heroku, process.env, context).createTopic(context.args.CLUSTER, context.args.TOPIC, flags);
  yield printWaitingDots();

  var err = yield creation;

  if (err) {
    process.stdout.write("\n");
    cli.error(err);
    process.exit(1);
  } else {
    process.stdout.write(' done.\n');
    process.stdout.write(`Use \`heroku kafka:topic ${context.args.TOPIC}\` to monitor your topic.\n`);
  }
}

module.exports = {
  topic: 'kafka',
  command: 'create',
  description: 'Creates a topic in Kafka',
  help: `
    Creates a topic in Kafka.

    Examples:

    $ heroku kafka:create page-visits --partitions 100
    $ heroku kafka:create HEROKU_KAFKA_BROWN_URL page-visits --partitions 100 --replication-factor 3 --retention-time 86400000 --compaction
`,
  needsApp: true,
  needsAuth: true,
  args: [
    {
      name: 'TOPIC',
      optional: false
    },
    {
      name: 'CLUSTER',
      optional: true
    }
  ],
  flags: FLAGS,
  run: cli.command(co.wrap(createTopic))
};
<commit_msg>Require confirmation when replication factor is 1<commit_after>'use strict';

let FLAGS = [
  {name: 'partitions',          description: 'number of partitions to give the topic',                            hasValue: true,  optional: false},
  {name: 'replication-factor',  description: 'number of replicas the topic should be created across',             hasValue: true,  optional: true},
  {name: 'retention-time',      description: 'The length of time messages in the topic should be retained for.',  hasValue: true,  optional: true},
  {name: 'compaction',          description: 'Whether to use compaction for this topic',                          hasValue: false, optional: true},
  {name: 'confirm',             description: 'Override the confirmation prompt. Needs the app name, or the command will fail.', hasValue: true, optional: true}
];
let DOT_WAITING_TIME = 200;

let cli = require('heroku-cli-util');
let co = require('co');
let HerokuKafkaClusters = require('./clusters.js').HerokuKafkaClusters;
let sleep = require('co-sleep');
let _ = require('underscore');

function extractFlags(contextFlags) {
  // This just ensures that we only ever get the flags we expect,
  // and don't get any additional keys out of the heroku cli flags object
  // (if there happen to be any).
  var out = {};
  _.each(FLAGS, function (flag) {
    if (contextFlags[flag.name] !== undefined) {
      out[flag.name] = contextFlags[flag.name];
    }
  });
  return out;
}

function* printWaitingDots() {
  yield sleep(DOT_WAITING_TIME);
  process.stdout.write('.');
  yield sleep(DOT_WAITING_TIME);
  process.stdout.write('.');
  yield sleep(DOT_WAITING_TIME);
  process.stdout.write('.');
}

function* createTopic (context, heroku) {
  var clusters = new HerokuKafkaClusters(heroku, process.env, context);
  var addon = yield clusters.addonForSingleClusterCommand(context.args.CLUSTER);
  if (addon) {
    if (context.flags['replication-factor'] === '1') {
      var confirmed = yield clusters.checkConfirmation(context, `
    !    WARNING: Dangerous Action
    !    This command will create a topic with no replication on the cluster: ${addon.name}, which is on ${context.app}
    !    Data written to this topic will be lost if any single broker suffers catastrophic failure.
    !
    !    To proceed, type "${context.app}" or re-run this command with --confirm ${context.app}
    `);

      if (confirmed) {
        console.log(`
    !    Proceeding to create a non-replicated topic...
    `);
        yield doCreation(context, heroku, clusters);
      } else {
        process.exit(1);
      }
    } else {
      yield doCreation(context, heroku, clusters);
    }
  } else {
    process.exit(1);
  }
}

function* doCreation(context, heroku, clusters) {
  if (context.args.CLUSTER) {
    process.stdout.write(`Creating ${context.args.TOPIC} on ${context.args.CLUSTER}`);
  } else {
    process.stdout.write(`Creating ${context.args.TOPIC}`);
  }
  var flags = extractFlags(context.flags);

  var creation = clusters.createTopic(context.args.CLUSTER, context.args.TOPIC, flags);
  yield printWaitingDots();

  var err = yield creation;

  if (err) {
    process.stdout.write("\n");
    cli.error(err);
    process.exit(1);
  } else {
    process.stdout.write(' done.\n');
    process.stdout.write(`Use \`heroku kafka:topic ${context.args.TOPIC}\` to monitor your topic.\n`);
  }
}

module.exports = {
  topic: 'kafka',
  command: 'create',
  description: 'Creates a topic in Kafka',
  help: `
    Creates a topic in Kafka.

    Examples:

    $ heroku kafka:create page-visits --partitions 100
    $ heroku kafka:create HEROKU_KAFKA_BROWN_URL page-visits --partitions 100 --replication-factor 3 --retention-time 86400000 --compaction
`,
  needsApp: true,
  needsAuth: true,
  args: [
    {
      name: 'TOPIC',
      optional: false
    },
    {
      name: 'CLUSTER',
      optional: true
    }
  ],
  flags: FLAGS,
  run: cli.command(co.wrap(createTopic))
};
<|endoftext|>


<commit_before>//id canal musica = 375842517566095360
module.exports = (client, message, args) => {
    let channel = client.channels.get('375842517566095360');
    //if (message.member.voiceChannel) {
    if (channel)
    {
      channel.join()
      .then(connection =>
      {
        message.reply('Eu conectei no canal com sucesso! Aproveite o som da rádio **Metal & Hardcore**! :musical_note:').then(msg => {
          msg.delete(60000)
        });
        connection.playArbitraryInput('http://www.my-radios.com/da/radio/live/16751/;?.mp3');
        //connection.playFile('./radio/anime01.pls');
      })
    .catch(console.log);
    }
    /*else { message.reply('Você precisa estar em um canal de voz para digitar o comando!');  }  */
    message.delete(60000);
};<commit_msg><commit_after>//id canal musica = 375842517566095360
module.exports = (client, message, args) => {
    let channel = client.channels.get('375842517566095360');
    //if (message.member.voiceChannel) {
    if (channel)
    {
      channel.join()
      .then(connection =>
      {
        message.reply('Eu conectei no canal com sucesso! Aproveite o som da rádio **Metal & Hardcore**! :musical_note:').then(msg => {
          msg.delete(60000)
        });
        connection.playArbitraryInput('http://bnr80smetal.radio.net/;?.mp3');
        //connection.playFile('./radio/anime01.pls');
      })
    .catch(console.log);
    }
    /*else { message.reply('Você precisa estar em um canal de voz para digitar o comando!');  }  */
    message.delete(60000);
};<|endoftext|>