<commit_before>
// stomp-server/connectionfactory.js -- Definition of the ConnectionFactory
// class

/*  Copyright 2010, Jason B. Alonso
 *
 *  This file is part of node-stomp-server.
 *
 *  Foobar is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Foobar is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with Foobar.  If not, see <http://www.gnu.org/licenses/>
 */

// Load modules
var events      = require('events'),
    Connection  = require('./connection').Connection,
    hashlib     = require('hashlib'),
    sys         = require('sys');

// Middleware structure: [{cbk: function(frame), ebk: function(frame)}...]
// recv_middleware
// send_middleware
function ConnectionFactory(bufferLimit) {
    var self = this;

    // Set the buffer limit
    if( bufferLimit == null )
        bufferLimit = 65536;

    // Initialize members
    this.bufferLimit = bufferLimit;
    this.recv_middleware = [];
    this.send_middleware = [];
    this._seed = hashlib.sha1((new Date()) + process.pid + Math.random());
    this.conn_counter = 0;

    // Extend EventEmitter
    events.EventEmitter.call(this);

    // Prepare the factory closure
    this.newConnection = function(stream) {
        return self._newConnection(stream);
    };
}
sys.inherits(ConnectionFactory, events.EventEmitter);

ConnectionFactory.prototype._newConnection = function(stream) {
    var self = this;

    // Construct a new Connection object
    var conn = new Connection(stream, this.bufferLimit);

    // Set the connection id
    conn._id = hashlib.sha1(this._seed + this.conn_counter);
    this.conn_counter++;

    // Configure event handlers
    conn.on('connect', function() { self.emit('connect', conn); });
    conn.on('secure', function() { self.emit('secure', conn); });
    conn.on('timeout', function() { self.emit('timeout', conn); });
    conn.on('close', function(had_error) { self.emit('close', conn, had_error); });
    conn.on('error', function(err) { console.log(err); console.log(err.stack); self.emit('error', conn, err); });
    conn.on('frame', function(frame_obj) {
            // Process frame for reception through middleware
            var layer, error_obj;
            for( layer = 0; layer < self.recv_middleware.length; layer++ ) {
                try {
                    if( frame_obj && self.recv_middleware[layer].cbk )
                        frame_obj = self.recv_middleware[layer].cbk.call(self, conn, frame_obj);
                    else if( error_obj && self.recv_middleware[layer].ebk )
                        frame_obj = self.recv_middleware[layer].ebk.call(self, conn, error_obj);
                    error_obj = null;
                } catch( err ) {
                    error_obj = err;
                    frame_obj = null;
                }
            }

            // Handle remains
            if( frame_obj ) self.emit('frame', conn, frame_obj);
            else if( error_obj ) self.emit('error', error_obj);
        });
};

ConnectionFactory.prototype.send_frame = function(conn, frame_obj) {
    // Process frame for transmission through middleware
    var layer, error_obj;
    for( layer = 0; layer < this.send_middleware.length; layer++ ) {
        try {
            if( frame_obj && this.send_middleware[layer].cbk )
                frame_obj = this.send_middleware[layer].cbk.call(this, conn, frame_obj);
            else if( error_obj && this.send_middleware[layer].ebk )
                frame_obj = this.send_middleware[layer].ebk.call(this, conn, error_obj);
            error_obj = null;
        } catch( err ) {
            error_obj = err;
            frame_obj = null;
        }
    }

    // Transmit the frame
    if( frame_obj ) conn.send(frame_obj);

    // Operation Complete!
};

// Export classes
module.exports.ConnectionFactory = ConnectionFactory;
<commit_msg>newConnection now returns a connection object<commit_after>
// stomp-server/connectionfactory.js -- Definition of the ConnectionFactory
// class

/*  Copyright 2010, Jason B. Alonso
 *
 *  This file is part of node-stomp-server.
 *
 *  Foobar is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Foobar is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with Foobar.  If not, see <http://www.gnu.org/licenses/>
 */

// Load modules
var events      = require('events'),
    Connection  = require('./connection').Connection,
    hashlib     = require('hashlib'),
    sys         = require('sys');

// Middleware structure: [{cbk: function(frame), ebk: function(frame)}...]
// recv_middleware
// send_middleware
function ConnectionFactory(bufferLimit) {
    var self = this;

    // Set the buffer limit
    if( bufferLimit == null )
        bufferLimit = 65536;

    // Initialize members
    this.bufferLimit = bufferLimit;
    this.recv_middleware = [];
    this.send_middleware = [];
    this._seed = hashlib.sha1((new Date()) + process.pid + Math.random());
    this.conn_counter = 0;

    // Extend EventEmitter
    events.EventEmitter.call(this);

    // Prepare the factory closure
    this.newConnection = function(stream) {
        return self._newConnection(stream);
    };
}
sys.inherits(ConnectionFactory, events.EventEmitter);

ConnectionFactory.prototype._newConnection = function(stream) {
    var self = this;

    // Construct a new Connection object
    var conn = new Connection(stream, this.bufferLimit);

    // Set the connection id
    conn._id = hashlib.sha1(this._seed + this.conn_counter);
    this.conn_counter++;

    // Configure event handlers
    conn.on('connect', function() { self.emit('connect', conn); });
    conn.on('secure', function() { self.emit('secure', conn); });
    conn.on('timeout', function() { self.emit('timeout', conn); });
    conn.on('close', function(had_error) { self.emit('close', conn, had_error); });
    conn.on('error', function(err) { console.log(err); console.log(err.stack); self.emit('error', conn, err); });
    conn.on('frame', function(frame_obj) {
            // Process frame for reception through middleware
            var layer, error_obj;
            for( layer = 0; layer < self.recv_middleware.length; layer++ ) {
                try {
                    if( frame_obj && self.recv_middleware[layer].cbk )
                        frame_obj = self.recv_middleware[layer].cbk.call(self, conn, frame_obj);
                    else if( error_obj && self.recv_middleware[layer].ebk )
                        frame_obj = self.recv_middleware[layer].ebk.call(self, conn, error_obj);
                    error_obj = null;
                } catch( err ) {
                    error_obj = err;
                    frame_obj = null;
                }
            }

            // Handle remains
            if( frame_obj ) self.emit('frame', conn, frame_obj);
            else if( error_obj ) self.emit('error', error_obj);
        });

    // Operation Complete!
    return conn;
};

ConnectionFactory.prototype.send_frame = function(conn, frame_obj) {
    // Process frame for transmission through middleware
    var layer, error_obj;
    for( layer = 0; layer < this.send_middleware.length; layer++ ) {
        try {
            if( frame_obj && this.send_middleware[layer].cbk )
                frame_obj = this.send_middleware[layer].cbk.call(this, conn, frame_obj);
            else if( error_obj && this.send_middleware[layer].ebk )
                frame_obj = this.send_middleware[layer].ebk.call(this, conn, error_obj);
            error_obj = null;
        } catch( err ) {
            error_obj = err;
            frame_obj = null;
        }
    }

    // Transmit the frame
    if( frame_obj ) conn.send(frame_obj);

    // Operation Complete!
};

// Export classes
module.exports.ConnectionFactory = ConnectionFactory;
<|endoftext|>


<commit_before>
/**
 * Walrus Framework
 * File maintained by: Nicolas Beauvais (E-Wok)
 * Created: 07:51 21/01/14.
 */

var Walrus = {};

(function (Walrus) {

    // walrus is a ninja
    'use strict';

    Walrus.catchLinks = function (event) {

        var elem,
            attributes,
            attribute,
            treeExplorer;

        elem = event.srcElement;
        treeExplorer = 1;

        for (treeExplorer; treeExplorer > 0; treeExplorer -= 1) {

            //handle body, html, document
            if (elem === null) { break; }

            //if we found a link
            if (elem.localName === 'a') {

                attributes = elem.attributes;

                for (attribute in attributes) {
                    if (attributes.hasOwnProperty(attribute)) {

                        attribute = attributes[attribute];
                        if (attribute.localName === 'href') {
                            if (Walrus.isntExternal(attribute.value)) {
                                Walrus.ajaxNavigation(event, attribute.value);
                                break;
                            } else { return; }

                        }
                        return;
                    }
                }

            } else {
                elem = elem.parentNode;
                treeExplorer += 1;
            }
        }

        event.preventDefault();
    };

    Walrus.isntExternal = function (url) {
        var local = location.href.replace(/^((https?:)?\/\/)?(www\.)?(\.)?/gi, '').split('/')[0];
        url = url.replace(/^((https?:)?\/\/)?(www\.)?(\.)?/gi, '').split('/')[0];
        return local === (url === '' ? local : url);
    };

    Walrus.ajaxNavigation = function (event, url) {
        var request = new XMLHttpRequest();
        request.open('GET', url, true);
        request.send();

        request.onload = function () {
            var resp,
                node,
                container,
                allChilds,
                i;

            document.getElementById('container').innerHTML = '';

            resp = this.response;
            node = document.createElement('div');
            node.innerHTML = resp;

            document.title = node.getElementsByTagName('title')[0].innerText;
            window.history.pushState({"html": resp.innerHTML, "pageTitle": document.title}, '', url);

            allChilds = node.childNodes;
            i = allChilds.length - 1;

            for (i; i > 0; i -= 1) {
                if (allChilds[i].id && allChilds[i].id === "container") { container = allChilds[i]; }
            }

            document.getElementById('container').innerHTML = container.innerHTML;
            Walrus.bootstrap();
            event.preventDefault();
        };
    };

    Walrus.checkLazy = function () {
        var nodes,
            nodesLength,
            request;

        nodes = Walrus.getByData('lazyload');
        nodesLength = nodes.length;

        if (nodesLength < 1) { return; }
        for (nodesLength; nodesLength > 0; nodesLength -= 1) {
            request = new XMLHttpRequest();
            request.open('GET', nodes[nodesLength - 1].data, true);
            request.send();

            request.onload = Walrus.appendLazy(nodes[nodesLength - 1].elem);
        }
    };

    Walrus.appendLazy = function (node) {

        var callback = function () {
            var data = this.response;
            node.innerHTML = data;
            node.removeAttribute('data-lazyload');
        };

        return callback;
    };

    Walrus.getByData = function (data) {
        var matches,
            allDom,
            i,
            node,
            nodeData;

        matches = [];
        allDom = document.getElementsByTagName("*");
        i = allDom.length - 1;

        for (i; i > 0; i -= 1) {
            node = allDom[i];
            if (node.getAttribute('data-' + data)) {
                nodeData = {};
                nodeData.elem = node;
                nodeData.data = node.getAttribute('data-' + data);
                matches.push(nodeData);
            }
        }

        return matches;
    };

    Walrus.config = {};

    /**
     * Walrus.js constructor.
     *
     * attributes:
     *
     * ajaxNavigation: true|false
     * lazyLoad: true|false
     *
     * @param {Object} config
     */
    Walrus.init = function (config) {

        Walrus.config = config;

        if (Walrus.config.ajaxNavigation) { document.onclick = Walrus.catchLinks; }

        window.onload = Walrus.bootstrap;
    };

    Walrus.bootstrap = function () {
        if (Walrus.config.lazyLoad) { Walrus.checkLazy(); }
    };

}(Walrus));
<commit_msg>Walrus.js: bug fix<commit_after>
/**
 * Walrus Framework
 * File maintained by: Nicolas Beauvais (E-Wok)
 * Created: 07:51 21/01/14.
 */

var Walrus = {};

(function (Walrus) {

    // walrus is a ninja
    'use strict';

    Walrus.catchLinks = function (event) {

        var elem,
            attributes,
            attribute,
            treeExplorer,
            isLink;

        elem = event.srcElement;
        treeExplorer = 1;
        isLink = false;

        for (treeExplorer; treeExplorer > 0; treeExplorer -= 1) {

            //handle body, html, document
            if (elem === null) { break; }

            //if we found a link
            if (elem.localName === 'a') {

                attributes = elem.attributes;

                for (attribute in attributes) {
                    if (attributes.hasOwnProperty(attribute)) {

                        attribute = attributes[attribute];
                        if (attribute.localName === 'href') {
                            isLink = true;
                            if (Walrus.isntExternal(attribute.value)) {
                                Walrus.ajaxNavigation(event, attribute.value);
                                break;
                            } else { return; }

                        }
                        return;
                    }
                }

            } else {
                elem = elem.parentNode;
                treeExplorer += 1;
            }
        }

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

    Walrus.isntExternal = function (url) {
        var local = location.href.replace(/^((https?:)?\/\/)?(www\.)?(\.)?/gi, '').split('/')[0];
        url = url.replace(/^((https?:)?\/\/)?(www\.)?(\.)?/gi, '').split('/')[0];
        return local === (url === '' ? local : url);
    };

    Walrus.ajaxNavigation = function (event, url) {
        var request = new XMLHttpRequest();
        request.open('GET', url, true);
        request.send();

        request.onload = function () {
            var resp,
                node,
                container,
                allChilds,
                i;

            document.getElementById('container').innerHTML = '';

            resp = this.response;
            node = document.createElement('div');
            node.innerHTML = resp;

            document.title = node.getElementsByTagName('title')[0].innerText;
            window.history.pushState({"html": resp.innerHTML, "pageTitle": document.title}, '', url);

            allChilds = node.childNodes;
            i = allChilds.length - 1;

            for (i; i > 0; i -= 1) {
                if (allChilds[i].id && allChilds[i].id === "container") { container = allChilds[i]; }
            }

            document.getElementById('container').innerHTML = container.innerHTML;
            Walrus.bootstrap();
            event.preventDefault();
        };
    };

    Walrus.checkLazy = function () {
        var nodes,
            nodesLength,
            request;

        nodes = Walrus.getByData('lazyload');
        nodesLength = nodes.length;

        if (nodesLength < 1) { return; }
        for (nodesLength; nodesLength > 0; nodesLength -= 1) {
            request = new XMLHttpRequest();
            request.open('GET', nodes[nodesLength - 1].data, true);
            request.send();

            request.onload = Walrus.appendLazy(nodes[nodesLength - 1].elem);
        }
    };

    Walrus.appendLazy = function (node) {

        var callback = function () {
            var data = this.response;
            node.innerHTML = data;
            node.removeAttribute('data-lazyload');
        };

        return callback;
    };

    Walrus.getByData = function (data) {
        var matches,
            allDom,
            i,
            node,
            nodeData;

        matches = [];
        allDom = document.getElementsByTagName("*");
        i = allDom.length - 1;

        for (i; i > 0; i -= 1) {
            node = allDom[i];
            if (node.getAttribute('data-' + data)) {
                nodeData = {};
                nodeData.elem = node;
                nodeData.data = node.getAttribute('data-' + data);
                matches.push(nodeData);
            }
        }

        return matches;
    };

    Walrus.config = {};

    /**
     * Walrus.js constructor.
     *
     * attributes:
     *
     * ajaxNavigation: true|false
     * lazyLoad: true|false
     *
     * @param {Object} config
     */
    Walrus.init = function (config) {

        Walrus.config = config;

        if (Walrus.config.ajaxNavigation) { document.onclick = Walrus.catchLinks; }

        window.onload = Walrus.bootstrap;
    };

    Walrus.bootstrap = function () {
        if (Walrus.config.lazyLoad) { Walrus.checkLazy(); }
    };

}(Walrus));
<|endoftext|>


<commit_before>(function() {
  "use strict";

  var i18n = window.c2cprofile.i18n;
  var mobile = $$('html')[0].hasClassName('mobile');

  // we don't use #elevation_profile_container_section_container
  var width = $('elevation_profile_container_tbg').getWidth();
  if (!mobile || window.innerWidth > 1000) {
    width -= 250;
    $$('.elevation_profile_controls')[0].addClassName('left');
  }

  var size = { width: width, height: 300 },
    margin = { top: 20, right: 20, bottom: 30, left: 50 },
    width = size.width - margin.left - margin.right,
    height = size.height - margin.top - margin.bottom;

  // d3.xml() is not working well with ie9 and ie10
  // so instead, we retrieve the text and use DOMParser on it
  d3.xhr(window.c2cprofile.track, "application/xml")
    // TODO progress events?
    //.on("progress", function() {
    //  console.log(d3.event.loaded);
    //})
    .on("error", function(error) {
      alert("Something went wrong (" + error + "). Please notify us");
    })
    .get(function(error, request) {
      var greatArc = d3.geo.greatArc();
      var mode = "distance";
      var data = [];
      var dtot = 0;
      var d;
      var duration;

      // hide loading div, displat regular ones
      $$('.elevation_profile_controls')[0].show();
      $$('.elevation_profile_loading')[0].hide();

      var parser = new DOMParser();
      var points = parser.parseFromString(request.responseText, 'text/xml')
                         .documentElement.getElementsByTagName("trkpt");

      try {
        // some files won't have time elements. We need to handle that
        var time_available = !!points[0].getElementsByTagName("time").length;

        // build data points from gpx information
        var startDate = time_available ? new Date((points[0].getElementsByTagName("time"))[0].textContent) : null;
        data.push({
          date: startDate,
          ele: +points[0].getElementsByTagName("ele")[0].textContent,
          d: 0,
          elapsed: time_available ? 0 : null
        });
        for (var i=1; i<points.length; i++) {
          d = greatArc.distance({
            source: [points[i].getAttribute("lon"), points[i].getAttribute("lat")],
            target: [points[i-1].getAttribute("lon"), points[i-1].getAttribute("lat")]
          }) * 6371;
          // it sometimes happen that SOME of the points don't have a <time>
          // In that case, we decide not to take time into account at all
          // FIXME could something better be done?
          time_available = time_available && !!points[i].getElementsByTagName("time").length;
          var date = time_available ? new Date(points[i].getElementsByTagName("time")[0].textContent) : null;
          data.push({
            date: date,
            ele: +points[i].getElementsByTagName("ele")[0].textContent,
            d: dtot + d,
            elapsed: time_available ? date - startDate : null,
          });
          dtot +=d;
        }

        if (!time_available) {
          $$('.xaxis-dimension')[0].hide();
        }
      } catch(err) {
        alert('Sorry, but something went wrong! Please contact us');
        return;
      }

      // Add an SVG element with the desired dimensions and margin
      var svg = d3.select("#elevation_profile").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

      // Scales and axes
      var x1 = d3.scale.linear()
        .range([0, width]);

      var y = d3.scale.linear()
        .range([height, 0]);

      var x1Axis = d3.svg.axis()
        .scale(x1)
        .orient("bottom");

      var yAxis = d3.svg.axis()
        .scale(y)
        .tickFormat(d3.format(".0f"))
        .orient("left");

      x1.domain(d3.extent(data, function(d) { return d.d; }))
        .nice();

      var yExtent = d3.extent(data, function(d) { return d.ele; });
      y.domain(yExtent)
        .nice();

      if (time_available) {
        var x2 = d3.time.scale()
          .range([0, width]);

        var x2Axis = d3.svg.axis()
          .scale(x2)
          .tickFormat(function(t) { // force display of elapsed time as hrs:mins. It is not datetime!
            return ~~(t/3600000) + ":" + d3.format("02d")(~~(t%3600000/60000));
          })
          .orient("bottom");

        x2.domain(d3.extent(data, function(d) { return d.elapsed; }))
          .nice(d3.time.hour);
      }

      svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)
      .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text(i18n.yLegend);

      svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(x1Axis)
      .append("text")
        .attr("x", size.width - margin.left - margin.right)
        .attr("dy", "-.71em")
        .attr("class", "x axis legend")
        .style("text-anchor", "end")
        .text(i18n.x1Legend);

      if (!mobile) {
        // horizontal line, but with same number of points
        // for eye-friendly transition
        var startline = d3.svg.line()
          .x(function(d) { return x1(d.d); })
          .y(function(d) { return y(yExtent[0]); });
      }

      // data lines
      var dLine = d3.svg.line()
        .x(function(d) { return x1(d.d); })
        .y(function(d) { return y(d.ele); });

      if (time_available) {
        var tLine = d3.svg.line()
          .x(function(d) { return x2(d.elapsed); })
          .y(function(d) { return y(d.ele); });
      }

      // display line path
      var line = svg.append("path")
        .datum(data)
        .attr("class", "line")
        .attr("d", mobile ? dLine : startline);

      if (!mobile) {
        line.transition()
          .duration(1000)
          .attr("d", dLine);

        // Display point information one hover
        var focusv = svg.append("line")
          .attr("class", "target")
          .attr("x1", 0)
          .attr("y1", 0)
          .attr("x2", 0)
          .attr("y2", size.height - margin.bottom - margin.top)
          .style("display", "none");

        var focush = svg.append("line")
          .attr("class", "target")
          .attr("x1", 0)
          .attr("y1", 0)
          .attr("x2", size.width - margin.right - margin.left)
          .attr("y2", 0)
          .style("display", "none");

        var focus = svg.append("circle")
          .attr("class", "circle")
          .attr("r", 4.5)
          .style("display", "none");

        var bubble = svg.append("text")
          .attr("x", (size.width - margin.left - margin.right) / 2)
          .attr("dy", "-.71em")
          .attr("class", "bubble")
          .style("text-anchor", "middle")
          .style("display", "none")
          .text("");

        svg.append("rect")
          .attr("class", "overlay")
          .attr("width", width)
          .attr("height", height)
        .on("mouseover", function() {
          focus.style("display", null);
          focush.style("display", null);
          focusv.style("display", null);
          bubble.style("display", null);
        })
        .on("mouseout", function() {
          focus.style("display", "none");
          focush.style("display", "none");
          focusv.style("display", "none");
          bubble.style("display", "none");
        })
        .on("mousemove", mousemove);
      }

      var bisectDistance = d3.bisector(function(d) { return d.d; }).left;
      var bisectDate = d3.bisector(function(d) { return d.elapsed; }).left;
      var formatDistance = d3.format(".2f");
      var formatDate = d3.time.format("%H:%M");
      var formatMinutes = d3.format("02d");

      function mousemove() {
        var bisect = (mode === "distance") ? bisectDistance : bisectDate;
        var x0 = (mode === "distance") ? x1.invert(d3.mouse(this)[0])
                                     : x2.invert(d3.mouse(this)[0]);
        var i = bisect(data, x0, 1, data.length - 1);
        var d0 = data[i - 1];
        var d1 = data[i];
        var d = (mode === "distance") ? (x0 - d0.d > d1.d - x0 ? d1 : d0)
                                      : (x0 - d0.elapsed > d1.elapsed - x0 ? d1 : d0);

        var dy = y(d.ele);
        var dx = (mode === "distance") ? x1(d.d) : x2(d.elapsed);

        focus.attr("transform", "translate(" + dx + "," + dy + ")");
        focush.attr("transform", "translate(0," + dy + ")");
        focusv.attr("transform", "translate(" + dx + ",0)");

        if (time_available) {
          var elapsed = d.elapsed/1000;
          bubble.text(i18n.elevation + " " + d.ele + i18n.meters + " / " + i18n.distance + " " + formatDistance(d.d) +
            i18n.kilometers + " / " + i18n.time + " " + formatDate(d.date) + " / " + i18n.duration + " " +
            ~~(elapsed/3600) + ":" +formatMinutes(~~(elapsed%3600/60)));
        } else {
          bubble.text(i18n.elevation + " " + d.ele + i18n.meters + " / " + i18n.distance + " " +
            formatDistance(d.d) + i18n.kilometers);
        }
      }

      // switch xAxis between distance and time
      if (time_available) {
        d3.selectAll("input[name=profile_mode]").on("change", function() {
          var nLine = (this.value === "distance") ? dLine : tLine;
          var axis = (this.value === "distance") ? x1Axis : x2Axis;
          var legend = (this.value === "distance") ? i18n.x1Legend : i18n.x2Legend;
          mode = this.value;

          if (mobile) {
            line.attr("d", nLine);
          } else {
            line.transition()
              .duration(1000)
              .attr("d", nLine);
          }

          d3.select(".x.axis")
            .call(axis)
          d3.select(".x.axis.legend")
            .text(legend);
        });
      }
    });

})()
<commit_msg>jshint<commit_after>(function() {

  var i18n = window.c2cprofile.i18n;
  var mobile = $$('html')[0].hasClassName('mobile');

  // we don't use #elevation_profile_container_section_container
  var width = $('elevation_profile_container_tbg').getWidth();
  if (!mobile || window.innerWidth > 1000) {
    width -= 250;
    $$('.elevation_profile_controls')[0].addClassName('left');
  }

  var size = { width: width, height: 300 };
  var margin = { top: 20, right: 20, bottom: 30, left: 50 };
  width = size.width - margin.left - margin.right;
  var height = size.height - margin.top - margin.bottom;

  // d3.xml() is not working well with ie9 and ie10
  // so instead, we retrieve the text and use DOMParser on it
  d3.xhr(window.c2cprofile.track, "application/xml")
    // TODO progress events?
    //.on("progress", function() {
    //  console.log(d3.event.loaded);
    //})
    .on("error", function(error) {
      alert("Something went wrong (" + error + "). Please notify us");
    })
    .get(function(error, request) {
      var greatArc = d3.geo.greatArc();
      var mode = "distance";
      var time_available;
      var data = [];
      var dtot = 0;
      var d;

      // hide loading div, displat regular ones
      $$('.elevation_profile_controls')[0].show();
      $$('.elevation_profile_loading')[0].hide();

      var parser = new DOMParser();
      var points = parser.parseFromString(request.responseText, 'text/xml')
                         .documentElement.getElementsByTagName("trkpt");

      try {
        // some files won't have time elements. We need to handle that
        time_available = !!points[0].getElementsByTagName("time").length;

        // build data points from gpx information
        var startDate = time_available ? new Date((points[0].getElementsByTagName("time"))[0].textContent) : null;
        data.push({
          date: startDate,
          ele: +points[0].getElementsByTagName("ele")[0].textContent,
          d: 0,
          elapsed: time_available ? 0 : null
        });
        for (var i=1; i<points.length; i++) {
          d = greatArc.distance({
            source: [points[i].getAttribute("lon"), points[i].getAttribute("lat")],
            target: [points[i-1].getAttribute("lon"), points[i-1].getAttribute("lat")]
          }) * 6371;
          // it sometimes happen that SOME of the points don't have a <time>
          // In that case, we decide not to take time into account at all
          // FIXME could something better be done?
          time_available = time_available && !!points[i].getElementsByTagName("time").length;
          var date = time_available ? new Date(points[i].getElementsByTagName("time")[0].textContent) : null;
          data.push({
            date: date,
            ele: +points[i].getElementsByTagName("ele")[0].textContent,
            d: dtot + d,
            elapsed: time_available ? date - startDate : null
          });
          dtot +=d;
        }

        if (!time_available) {
          $$('.xaxis-dimension')[0].hide();
        }
      } catch(err) {
        alert('Sorry, but something went wrong! Please contact us - ' + err);
        return;
      }

      // Add an SVG element with the desired dimensions and margin
      var svg = d3.select("#elevation_profile").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

      // Scales and axes
      var x1 = d3.scale.linear()
        .range([0, width]);

      var y = d3.scale.linear()
        .range([height, 0]);

      var x1Axis = d3.svg.axis()
        .scale(x1)
        .orient("bottom");

      var yAxis = d3.svg.axis()
        .scale(y)
        .tickFormat(d3.format(".0f"))
        .orient("left");

      x1.domain(d3.extent(data, function(d) { return d.d; }))
        .nice();

      var yExtent = d3.extent(data, function(d) { return d.ele; });
      y.domain(yExtent)
        .nice();

      if (time_available) {
        var x2 = d3.time.scale()
          .range([0, width]);

        var x2Axis = d3.svg.axis()
          .scale(x2)
          .tickFormat(function(t) { // force display of elapsed time as hrs:mins. It is not datetime!
            return ~~(t/3600000) + ":" + d3.format("02d")(~~(t%3600000/60000));
          })
          .orient("bottom");

        x2.domain(d3.extent(data, function(d) { return d.elapsed; }))
          .nice(d3.time.hour);
      }

      svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)
      .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text(i18n.yLegend);

      svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(x1Axis)
      .append("text")
        .attr("x", size.width - margin.left - margin.right)
        .attr("dy", "-.71em")
        .attr("class", "x axis legend")
        .style("text-anchor", "end")
        .text(i18n.x1Legend);

      var startLine;
      if (!mobile) {
        // horizontal line, but with same number of points
        // for eye-friendly transition
        startline = d3.svg.line()
          .x(function(d) { return x1(d.d); })
          .y(function() { return y(yExtent[0]); });
      }

      // data lines
      var dLine = d3.svg.line()
        .x(function(d) { return x1(d.d); })
        .y(function(d) { return y(d.ele); });

      if (time_available) {
        var tLine = d3.svg.line()
          .x(function(d) { return x2(d.elapsed); })
          .y(function(d) { return y(d.ele); });
      }

      // display line path
      var line = svg.append("path")
        .datum(data)
        .attr("class", "line")
        .attr("d", mobile ? dLine : startline);

      if (!mobile) {
        line.transition()
          .duration(1000)
          .attr("d", dLine);

        // Display point information one hover
        var focusv = svg.append("line")
          .attr("class", "target")
          .attr("x1", 0)
          .attr("y1", 0)
          .attr("x2", 0)
          .attr("y2", size.height - margin.bottom - margin.top)
          .style("display", "none");

        var focush = svg.append("line")
          .attr("class", "target")
          .attr("x1", 0)
          .attr("y1", 0)
          .attr("x2", size.width - margin.right - margin.left)
          .attr("y2", 0)
          .style("display", "none");

        var focus = svg.append("circle")
          .attr("class", "circle")
          .attr("r", 4.5)
          .style("display", "none");

        var bubble = svg.append("text")
          .attr("x", (size.width - margin.left - margin.right) / 2)
          .attr("dy", "-.71em")
          .attr("class", "bubble")
          .style("text-anchor", "middle")
          .style("display", "none")
          .text("");

        svg.append("rect")
          .attr("class", "overlay")
          .attr("width", width)
          .attr("height", height)
        .on("mouseover", function() {
          focus.style("display", null);
          focush.style("display", null);
          focusv.style("display", null);
          bubble.style("display", null);
        })
        .on("mouseout", function() {
          focus.style("display", "none");
          focush.style("display", "none");
          focusv.style("display", "none");
          bubble.style("display", "none");
        })
        .on("mousemove", mousemove);
      }

      var bisectDistance = d3.bisector(function(d) { return d.d; }).left;
      var bisectDate = d3.bisector(function(d) { return d.elapsed; }).left;
      var formatDistance = d3.format(".2f");
      var formatDate = d3.time.format("%H:%M");
      var formatMinutes = d3.format("02d");

      function mousemove() {
        var bisect = (mode === "distance") ? bisectDistance : bisectDate;
        var x0 = (mode === "distance") ? x1.invert(d3.mouse(this)[0])
                                     : x2.invert(d3.mouse(this)[0]);
        var i = bisect(data, x0, 1, data.length - 1);
        var d0 = data[i - 1];
        var d1 = data[i];
        var d = (mode === "distance") ? (x0 - d0.d > d1.d - x0 ? d1 : d0)
                                      : (x0 - d0.elapsed > d1.elapsed - x0 ? d1 : d0);

        var dy = y(d.ele);
        var dx = (mode === "distance") ? x1(d.d) : x2(d.elapsed);

        focus.attr("transform", "translate(" + dx + "," + dy + ")");
        focush.attr("transform", "translate(0," + dy + ")");
        focusv.attr("transform", "translate(" + dx + ",0)");

        if (time_available) {
          var elapsed = d.elapsed/1000;
          bubble.text(i18n.elevation + " " + d.ele + i18n.meters + " / " + i18n.distance + " " + formatDistance(d.d) +
            i18n.kilometers + " / " + i18n.time + " " + formatDate(d.date) + " / " + i18n.duration + " " +
            ~~(elapsed/3600) + ":" +formatMinutes(~~(elapsed%3600/60)));
        } else {
          bubble.text(i18n.elevation + " " + d.ele + i18n.meters + " / " + i18n.distance + " " +
            formatDistance(d.d) + i18n.kilometers);
        }
      }

      // switch xAxis between distance and time
      if (time_available) {
        d3.selectAll("input[name=profile_mode]").on("change", function() {
          var nLine = (this.value === "distance") ? dLine : tLine;
          var axis = (this.value === "distance") ? x1Axis : x2Axis;
          var legend = (this.value === "distance") ? i18n.x1Legend : i18n.x2Legend;
          mode = this.value;

          if (mobile) {
            line.attr("d", nLine);
          } else {
            line.transition()
              .duration(1000)
              .attr("d", nLine);
          }

          d3.select(".x.axis")
            .call(axis);
          d3.select(".x.axis.legend")
            .text(legend);
        });
      }
    });

})();
<|endoftext|>


<commit_before>var HDO = HDO || {};

(function (H, $) {
  var categoryId,
    partySlug = null,
    results,
    bodyName = "promisesBody",
    cache = {},
    lastPartyFilter = null;

  function getData(catId, partySlug, callback) {
    var promiseUrl;

    if (partySlug === '' || !partySlug || partySlug === "show-all") {
      promiseUrl = '/categories/' + catId + '/promises';
    } else {
      promiseUrl = '/categories/' + catId + '/promises/parties/' + partySlug;
    }

    if (cache[promiseUrl]) {
      callback(cache[promiseUrl]);
      return;
    }

    $("#spinner").show();

    $.ajax({
      url: promiseUrl,

      complete: function () {
        $("#spinner").hide();
      },

      success: function (data) {
        cache[promiseUrl] = data;
        callback(data);
      }
    });
  }

  function setResults(data) {
    results = data;
  }

  function getResults() {
    return results;
  }

  function showSpecificParty(catId, partyId) {
    var bodyElement = $('#' + bodyName);
    bodyElement.empty();

    lastPartyFilter = partyId;

    bodyElement.hide().append(results);
    bodyElement.find('div[data-party-slug!="' + partyId + '"]').hide();
    bodyElement.show();
  }

  function showAllPromisesInCategory(catId, partySlug) {
    getData(catId, partySlug, function (results) {
      setResults(results);
      $('#' + bodyName).html(results);
      if (lastPartyFilter) {
        showSpecificParty(catId, lastPartyFilter);
      }
    });
  }

  function showAllParties(catId) {
    lastPartyFilter = null;
    showAllPromisesInCategory(catId);
  }

  function removeActiveClass(divClass) {
    $(divClass).find('li').removeClass();
  }

  H.promiseWidget = {
    create: function (options) {
      var instance = Object.create(this);
      instance.options = options;

      return instance;
    },

    init: function () {
      var self = this;

      $(self.options.categoriesSelector).find('a').on('click', function (e) {

        categoryId = $(this).data('category-id');
        $(self.options.categoriesSelector).find('a').removeClass('active');
        $(this).addClass('active');

        if (self.options.partiesSelector !== null) {
          if (!lastPartyFilter) {
            removeActiveClass(self.options.partiesSelector);
            $('[data-party-slug="show-all"]').parent().addClass('active');
          }
        } else {
          partySlug = document.URL;
          partySlug = partySlug.substring(partySlug.lastIndexOf('/') + 1);
        }

        var target = $(self.options.targetSelector);
        target.empty().append('

');
        showAllPromisesInCategory(categoryId, partySlug);

        e.preventDefault();

      });

      $(self.options.partiesSelector).find('a').on('click', function (e) {
        removeActiveClass(self.options.partiesSelector, partySlug);

        partySlug = $(this).data('party-slug');

        if(partySlug.indexOf(',') >= 0) {
          $(this).parent().addClass('government-active');
        } else {
          $(this).parent().addClass(partySlug + '-active');
        }

        if (partySlug === 'show-all') {
          showAllParties(categoryId);
          $(this).parent().addClass('active');
        } else {
          showSpecificParty(categoryId, partySlug);
        }

        e.preventDefault();
      });
    } // end of init
  };
}(HDO, jQuery));<commit_msg>message when there are no promises<commit_after>var HDO = HDO || {};

(function (H, $) {
  var categoryId,
    partySlug = null,
    results,
    bodyName = "promisesBody",
    cache = {},
    lastPartyFilter = null;

  function getData(catId, partySlug, callback) {
    var promiseUrl;

    if (partySlug === '' || !partySlug || partySlug === "show-all") {
      promiseUrl = '/categories/' + catId + '/promises';
    } else {
      promiseUrl = '/categories/' + catId + '/promises/parties/' + partySlug;
    }

    if (cache[promiseUrl]) {
      callback(cache[promiseUrl]);
      return;
    }

    $("#spinner").show();

    $.ajax({
      url: promiseUrl,

      complete: function () {
        $("#spinner").hide();
      },

      success: function (data) {
        cache[promiseUrl] = data;
        callback(data);
      }
    });
  }

  function setResults(data) {
    results = data;
  }

  function getResults() {
    return results;
  }

  function showSpecificParty(catId, partyId) {
    var bodyElement = $('#' + bodyName);
    bodyElement.empty();

    lastPartyFilter = partyId;

    bodyElement.hide().append(results);
    bodyElement.find('div[data-party-slug!="' + partyId + '"]').hide();
    bodyElement.show();
  }

  function showAllPromisesInCategory(catId, partySlug) {
    getData(catId, partySlug, function (results) {
      setResults(results);
      if (results === '') {
        $('#' + bodyName).html("Ingen løfter i denne kategorien.");
      } else {
        $('#' + bodyName).html(results);
      }

      if (lastPartyFilter) {
        showSpecificParty(catId, lastPartyFilter);
      }
    });
  }

  function showAllParties(catId) {
    lastPartyFilter = null;
    showAllPromisesInCategory(catId);
  }

  function removeActiveClass(divClass) {
    $(divClass).find('li').removeClass();
  }

  H.promiseWidget = {
    create: function (options) {
      var instance = Object.create(this);
      instance.options = options;

      return instance;
    },

    init: function () {
      var self = this;

      $(self.options.categoriesSelector).find('a').on('click', function (e) {

        categoryId = $(this).data('category-id');
        $(self.options.categoriesSelector).find('a').removeClass('active');
        $(this).addClass('active');

        if (self.options.partiesSelector !== null) {
          if (!lastPartyFilter) {
            removeActiveClass(self.options.partiesSelector);
            $('[data-party-slug="show-all"]').parent().addClass('active');
          }
        } else {
          partySlug = document.URL;
          partySlug = partySlug.substring(partySlug.lastIndexOf('/') + 1);
        }

        var target = $(self.options.targetSelector);
        target.empty().append('

');
        showAllPromisesInCategory(categoryId, partySlug);

        e.preventDefault();

      });

      $(self.options.partiesSelector).find('a').on('click', function (e) {
        removeActiveClass(self.options.partiesSelector, partySlug);

        partySlug = $(this).data('party-slug');

        if(partySlug.indexOf(',') >= 0) {
          $(this).parent().addClass('government-active');
        } else {
          $(this).parent().addClass(partySlug + '-active');
        }

        if (partySlug === 'show-all') {
          showAllParties(categoryId);
          $(this).parent().addClass('active');
        } else {
          showSpecificParty(categoryId, partySlug);
        }

        e.preventDefault();
      });
    } // end of init
  };
}(HDO, jQuery));<|endoftext|>


<commit_before>/*eslint dot-notation:0*/
import {Origin} from 'aurelia-metadata';
import {TemplateRegistryEntry, Loader} from 'aurelia-loader';
import {TextTemplateLoader} from './text-template-loader';
import {PLATFORM} from 'aurelia-pal';

function ensureOriginOnExports(executed, name) {
  let target = executed;
  let key;
  let exportedValue;

  if (target.__useDefault) {
    target = target['default'];
  }

  Origin.set(target, new Origin(name, 'default'));

  for (key in target) {
    exportedValue = target[key];

    if (typeof exportedValue === 'function') {
      Origin.set(exportedValue, new Origin(name, key));
    }
  }

  return executed;
}

/**
* Represents a template loader.
*/
interface TemplateLoader {
  /**
  * Loads a template.
  * @param loader The loader that is requesting the template load.
  * @param entry The TemplateRegistryEntry to load and populate with a template.
  * @return A promise which resolves when the TemplateRegistryEntry is loaded with a template.
  */
  loadTemplate(loader: Loader, entry: TemplateRegistryEntry): Promise<any>;
}

/**
* A default implementation of the Loader abstraction which works with SystemJS, RequireJS and Dojo Loader.
*/
export class DefaultLoader extends Loader {
  /**
  * The name of the underlying native loader plugin used to load text.
  */
  textPluginName: string = 'text';

  /**
  * Creates an instance of the DefaultLoader.
  */
  constructor() {
    super();

    this.moduleRegistry = {};
    this.useTemplateLoader(new TextTemplateLoader());

    let that = this;

    this.addPlugin('template-registry-entry', {
      'fetch': function(address) {
        let entry = that.getOrCreateTemplateRegistryEntry(address);
        return entry.templateIsLoaded ? entry : that.templateLoader.loadTemplate(that, entry).then(x => entry);
      }
    });
  }

  /**
  * Instructs the loader to use a specific TemplateLoader instance for loading templates
  * @param templateLoader The instance of TemplateLoader to use for loading templates.
  */
  useTemplateLoader(templateLoader: TemplateLoader): void {
    this.templateLoader = templateLoader;
  }

  /**
  * Loads a collection of modules.
  * @param ids The set of module ids to load.
  * @return A Promise for an array of loaded modules.
  */
  loadAllModules(ids: string[]): Promise<any[]> {
    let loads = [];

    for (let i = 0, ii = ids.length; i < ii; ++i) {
      loads.push(this.loadModule(ids[i]));
    }

    return Promise.all(loads);
  }

  /**
  * Loads a template.
  * @param url The url of the template to load.
  * @return A Promise for a TemplateRegistryEntry containing the template.
  */
  loadTemplate(url: string): Promise<TemplateRegistryEntry> {
    return this._import(this.applyPluginToUrl(url, 'template-registry-entry'));
  }

  /**
  * Loads a text-based resource.
  * @param url The url of the text file to load.
  * @return A Promise for text content.
  */
  loadText(url: string): Promise<string> {
    return this._import(this.applyPluginToUrl(url, this.textPluginName));
  }
}

PLATFORM.Loader = DefaultLoader;

if (!PLATFORM.global.System || !PLATFORM.global.System.import) {
  if (PLATFORM.global.requirejs && requirejs.s && requirejs.s.contexts && requirejs.s.contexts._ && requirejs.s.contexts._.defined) {
    PLATFORM.eachModule = function(callback) {
      let defined = requirejs.s.contexts._.defined;
      for (let key in defined) {
        try {
          if (callback(key, defined[key])) return;
        } catch(e) {}
      }
    };
  } else {
    PLATFORM.eachModule = function(callback) {};
  }

  DefaultLoader.prototype._import = function(moduleId) {
    return new Promise((resolve, reject) => {
      require([moduleId], resolve, reject);
    });
  };

  DefaultLoader.prototype.loadModule = function(id) {
    let existing = this.moduleRegistry[id];
    if (existing !== undefined) {
      return Promise.resolve(existing);
    }

    return new Promise((resolve, reject) => {
      require([id], m => {
        this.moduleRegistry[id] = m;
        resolve(ensureOriginOnExports(m, id));
      }, reject);
    });
  };

  DefaultLoader.prototype.map = function(id, source) {};

  DefaultLoader.prototype.normalize = function(moduleId, relativeTo) {
    return Promise.resolve(moduleId);
  };

  DefaultLoader.prototype.normalizeSync = function(moduleId, relativeTo) {
    return moduleId;
  };

  DefaultLoader.prototype.applyPluginToUrl = function(url, pluginName) {
    return `${pluginName}!${url}`;
  };

  DefaultLoader.prototype.addPlugin = function(pluginName, implementation) {
    define(pluginName, [], {
      'load': function(name, req, onload) {
        let address = req.toUrl(name);
        let result = implementation.fetch(address);
        Promise.resolve(result).then(onload);
      }
    });
  };
} else {
  PLATFORM.eachModule = function(callback) {
    let modules = System._loader.modules;

    for (let key in modules) {
      try {
        if (callback(key, modules[key].module)) return;
      } catch(e) {}
    }
  };

  System.set('text', System.newModule({
    'translate': function(load) {
      return 'module.exports = "' + load.source
        .replace(/(["\\])/g, '\\$1')
        .replace(/[\f]/g, '\\f')
        .replace(/[\b]/g, '\\b')
        .replace(/[\n]/g, '\\n')
        .replace(/[\t]/g, '\\t')
        .replace(/[\r]/g, '\\r')
        .replace(/[\u2028]/g, '\\u2028')
        .replace(/[\u2029]/g, '\\u2029')
      + '";';
    }
  }));

  DefaultLoader.prototype._import = function(moduleId) {
    return System.import(moduleId);
  };

  DefaultLoader.prototype.loadModule = function(id) {
    let existing = this.moduleRegistry[id];
    if (existing !== undefined) {
      return Promise.resolve(existing);
    }

    return System.import(id).then(m => {
      this.moduleRegistry[id] = m;
      return ensureOriginOnExports(m, id);
    });
  };

  DefaultLoader.prototype.map = function(id, source) {
    System.map[id] = source;
  };

  DefaultLoader.prototype.normalizeSync = function(moduleId, relativeTo) {
    return System.normalizeSync(moduleId, relativeTo);
  };

  DefaultLoader.prototype.normalize = function(moduleId, relativeTo) {
    return System.normalize(moduleId, relativeTo);
  };

  DefaultLoader.prototype.applyPluginToUrl = function(url, pluginName) {
    return `${url}!${pluginName}`;
  };

  DefaultLoader.prototype.addPlugin = function(pluginName, implementation) {
    System.set(pluginName, System.newModule({
      'fetch': function(load, _fetch) {
        let result = implementation.fetch(load.address);
        return Promise.resolve(result).then(x => {
          load.metadata.result = x;
          return '';
        });
      },
      'instantiate': function(load) {
        return load.metadata.result;
      }
    }));
  };
}
<commit_msg>fix(index): properly normalize for systemjs<commit_after>/*eslint dot-notation:0*/
import {Origin} from 'aurelia-metadata';
import {TemplateRegistryEntry, Loader} from 'aurelia-loader';
import {TextTemplateLoader} from './text-template-loader';
import {PLATFORM} from 'aurelia-pal';

function ensureOriginOnExports(executed, name) {
  let target = executed;
  let key;
  let exportedValue;

  if (target.__useDefault) {
    target = target['default'];
  }

  Origin.set(target, new Origin(name, 'default'));

  for (key in target) {
    exportedValue = target[key];

    if (typeof exportedValue === 'function') {
      Origin.set(exportedValue, new Origin(name, key));
    }
  }

  return executed;
}

/**
* Represents a template loader.
*/
interface TemplateLoader {
  /**
  * Loads a template.
  * @param loader The loader that is requesting the template load.
  * @param entry The TemplateRegistryEntry to load and populate with a template.
  * @return A promise which resolves when the TemplateRegistryEntry is loaded with a template.
  */
  loadTemplate(loader: Loader, entry: TemplateRegistryEntry): Promise<any>;
}

/**
* A default implementation of the Loader abstraction which works with SystemJS, RequireJS and Dojo Loader.
*/
export class DefaultLoader extends Loader {
  /**
  * The name of the underlying native loader plugin used to load text.
  */
  textPluginName: string = 'text';

  /**
  * Creates an instance of the DefaultLoader.
  */
  constructor() {
    super();

    this.moduleRegistry = {};
    this.useTemplateLoader(new TextTemplateLoader());

    let that = this;

    this.addPlugin('template-registry-entry', {
      'fetch': function(address) {
        let entry = that.getOrCreateTemplateRegistryEntry(address);
        return entry.templateIsLoaded ? entry : that.templateLoader.loadTemplate(that, entry).then(x => entry);
      }
    });
  }

  /**
  * Instructs the loader to use a specific TemplateLoader instance for loading templates
  * @param templateLoader The instance of TemplateLoader to use for loading templates.
  */
  useTemplateLoader(templateLoader: TemplateLoader): void {
    this.templateLoader = templateLoader;
  }

  /**
  * Loads a collection of modules.
  * @param ids The set of module ids to load.
  * @return A Promise for an array of loaded modules.
  */
  loadAllModules(ids: string[]): Promise<any[]> {
    let loads = [];

    for (let i = 0, ii = ids.length; i < ii; ++i) {
      loads.push(this.loadModule(ids[i]));
    }

    return Promise.all(loads);
  }

  /**
  * Loads a template.
  * @param url The url of the template to load.
  * @return A Promise for a TemplateRegistryEntry containing the template.
  */
  loadTemplate(url: string): Promise<TemplateRegistryEntry> {
    return this._import(this.applyPluginToUrl(url, 'template-registry-entry'));
  }

  /**
  * Loads a text-based resource.
  * @param url The url of the text file to load.
  * @return A Promise for text content.
  */
  loadText(url: string): Promise<string> {
    return this._import(this.applyPluginToUrl(url, this.textPluginName));
  }
}

PLATFORM.Loader = DefaultLoader;

if (!PLATFORM.global.System || !PLATFORM.global.System.import) {
  if (PLATFORM.global.requirejs && requirejs.s && requirejs.s.contexts && requirejs.s.contexts._ && requirejs.s.contexts._.defined) {
    PLATFORM.eachModule = function(callback) {
      let defined = requirejs.s.contexts._.defined;
      for (let key in defined) {
        try {
          if (callback(key, defined[key])) return;
        } catch(e) {}
      }
    };
  } else {
    PLATFORM.eachModule = function(callback) {};
  }

  DefaultLoader.prototype._import = function(moduleId) {
    return new Promise((resolve, reject) => {
      require([moduleId], resolve, reject);
    });
  };

  DefaultLoader.prototype.loadModule = function(id) {
    let existing = this.moduleRegistry[id];
    if (existing !== undefined) {
      return Promise.resolve(existing);
    }

    return new Promise((resolve, reject) => {
      require([id], m => {
        this.moduleRegistry[id] = m;
        resolve(ensureOriginOnExports(m, id));
      }, reject);
    });
  };

  DefaultLoader.prototype.map = function(id, source) {};

  DefaultLoader.prototype.normalize = function(moduleId, relativeTo) {
    return Promise.resolve(moduleId);
  };

  DefaultLoader.prototype.normalizeSync = function(moduleId, relativeTo) {
    return moduleId;
  };

  DefaultLoader.prototype.applyPluginToUrl = function(url, pluginName) {
    return `${pluginName}!${url}`;
  };

  DefaultLoader.prototype.addPlugin = function(pluginName, implementation) {
    define(pluginName, [], {
      'load': function(name, req, onload) {
        let address = req.toUrl(name);
        let result = implementation.fetch(address);
        Promise.resolve(result).then(onload);
      }
    });
  };
} else {
  PLATFORM.eachModule = function(callback) {
    let modules = System._loader.modules;

    for (let key in modules) {
      try {
        if (callback(key, modules[key].module)) return;
      } catch(e) {}
    }
  };

  System.set('text', System.newModule({
    'translate': function(load) {
      return 'module.exports = "' + load.source
        .replace(/(["\\])/g, '\\$1')
        .replace(/[\f]/g, '\\f')
        .replace(/[\b]/g, '\\b')
        .replace(/[\n]/g, '\\n')
        .replace(/[\t]/g, '\\t')
        .replace(/[\r]/g, '\\r')
        .replace(/[\u2028]/g, '\\u2028')
        .replace(/[\u2029]/g, '\\u2029')
      + '";';
    }
  }));

  DefaultLoader.prototype._import = function(moduleId) {
    return System.import(moduleId);
  };

  DefaultLoader.prototype.loadModule = function(id) {
    return System.normalize(id).then(newId => {
      let existing = this.moduleRegistry[newId];
      if (existing !== undefined) {
        return Promise.resolve(existing);
      }

      return System.import(newId).then(m => {
        this.moduleRegistry[newId] = m;
        return ensureOriginOnExports(m, newId);
      });
    });
  };

  DefaultLoader.prototype.map = function(id, source) {
    System.map[id] = source;
  };

  DefaultLoader.prototype.normalizeSync = function(moduleId, relativeTo) {
    return System.normalizeSync(moduleId, relativeTo);
  };

  DefaultLoader.prototype.normalize = function(moduleId, relativeTo) {
    return System.normalize(moduleId, relativeTo);
  };

  DefaultLoader.prototype.applyPluginToUrl = function(url, pluginName) {
    return `${url}!${pluginName}`;
  };

  DefaultLoader.prototype.addPlugin = function(pluginName, implementation) {
    System.set(pluginName, System.newModule({
      'fetch': function(load, _fetch) {
        let result = implementation.fetch(load.address);
        return Promise.resolve(result).then(x => {
          load.metadata.result = x;
          return '';
        });
      },
      'instantiate': function(load) {
        return load.metadata.result;
      }
    }));
  };
}
<|endoftext|>


<commit_before>import React from 'react'
import { LinearGradient, Stop } from 'react-native-svg'
import { BarChart } from 'react-native-svg-charts'

class GradientBarExample extends React.PureComponent {

    render() {

        const {
                  fillColor         = 'rgb(134, 65, 244)',
                  fillColorNegative = 'rgb(239, 71, 71)',
              } = this.props

        const data    = [ 50, 10, 40, 95, -4, -24, 85, 91, 35, 53, -53, 24, 50, -20, -80 ]
        const barData = [
            {
                values: data,
                positive: {
                    fill: fillColor,
                    // other react-native-svg supported props
                },
                negative: {
                    fill: fillColorNegative,
                    // other react-native-svg supported props
                },
            },
        ]

        return (
            <BarChart
                style={ { height: 200 } }
                data={ barData }
                contentInset={ { top: 20, bottom: 20 } }
                renderGradient={ ({ id, value, fill }) => (
                    <LinearGradient id={ id } x1={ '0%' } y={ '0%' } x2={ '0%' } y2={ '100%' }>
                        <Stop offset={ '0%' } stopColor={ value > 0 ? fill : 'rgb(66, 194, 244)' }/>
                        <Stop offset={ '100%' } stopColor={ value < 0 ? fill : 'rgb(66, 194, 244)' }/>
                    </LinearGradient>
                ) }
                svg={ {
                    strokeWidth: 2,
                } }
            />
        )
    }

}

export default GradientBarExample
<commit_msg>fix bar gradient example<commit_after>import React from 'react'
import { LinearGradient, Stop, Defs } from 'react-native-svg'
import { BarChart } from 'react-native-svg-charts'

class GradientBarExample extends React.PureComponent {

    render() {

        const data    = [ 50, 10, 40, 95, -4, -24, 85, 91, 35, 53, -53, 24, 50, -20, -80 ]

        const Gradient = () => (
            <Defs key={'gradient'}>
                <LinearGradient id={'gradient'} x1={'0%'} y={'0%'} x2={'0%'} y2={'100%'}>
                    <Stop offset={'0%'} stopColor={'rgb(134, 65, 244)'}/>
                    <Stop offset={'100%'} stopColor={'rgb(66, 194, 244)'}/>
                </LinearGradient>
            </Defs>
        )

        return (
            <BarChart
                style={ { height: 200 } }
                data={ data }
                contentInset={ { top: 20, bottom: 20 } }
                extras={[ Gradient ]}
                svg={ {
                    strokeWidth: 2,
                    fill: 'url(#gradient)',
                } }
            />
        )
    }

}

export default GradientBarExample
<|endoftext|>


<commit_before>define(function (require, exports, moudle) {
    alifenxi.track("course_video_view", {
        "course_name": $('#c_course_name').html(),
        "resource_name" : $("#c-video-play-list .current-play .c-video-play-list-item-title ").html()
    });

    //分页
    var Pager = require('js/widget/pager');
    var commentBtn = $("#comment-submit");
    var commentArea = $("#user-comment-editor");
    var user_avator = ($('#ne_user_avator').val() - 0) || 1;
    var nickname = commentBtn.attr("data-nickname") || $('#ne_user_name').val();
    var userId = $('#ne_user_id').val();
    var courseid = commentBtn.attr("data-course-id");

    function addPage() {
        var page = new Pager({
            container: $('#video_pager'),
            sum: $('#comment_list').attr('data-num') - 0,
            count: 10,
            step: 10,
            showCount: false,
            start: 0,
            onChange: function (num, count) {
                drawComment(num + 1, count)
            }
        });
        page.init();
    };

    addPage();

    //加载评论
    function drawComment(num, count) {
        var tpl =
            ['<% comments.forEach(function(val){%>',
                '
',
                '
',
                '<div class="user-head-icon user-head-<%=val.avator||1%>">
',
                '
',
                '
',
                '<%=val.nickname%>',
                '

<%=val.comment%>

',
                '<% var d = new Date(val.updatetime).toLocaleDateString();%>',
                '<time class="comment-time"><%=val.updatetime%></time>',
                '
',
                '
',
                '<%})%>'].join("");
        $.get('/course/getcomment', {id: courseid, page: num, limit: count}, function (result) {
            if (result.errno == 0) {
                $('#comment_list').html(_.template(tpl, {comments: result.data}))
            }
        }, 'json')
    };
    //留下评论
    commentBtn.unbind("click").on("click", function (e) {
        var data = {};
        var userId = commentBtn.attr("data-user-id");
        data.comment = commentArea.val();
        data.id = courseid;
        if (data.comment.trim() == '') {
            return false;
        }

        $.post('/course/comment', data, 'json').done(function (res) {
            if (res.errno == 0) {
                var tmp = [
                    '
',
                    '
',
                    '

',
                    '
',
                    '
',
                    '', nickname, '',
                    '

', data.comment, '

',
                    '<time class="comment-time">刚刚</time>',
                    '
',
                    '
'
                ].join('');
                ALERT('提示', '评论成功！');
                $(tmp).prependTo('#comment_list');
                commentArea.val('');
            }
        });

    });

    //guanggao
    function showAQWERDF() {
        var entity = $("#c-video-view >.video-js .c-course-video-aqwerdf");

        if (entity.length == 0) {
            var html = $("#AQWERDF").html();
            $("#c-video-view >.video-js").append(html);
            var entity = $("#c-video-view >.video-js .c-course-video-aqwerdf");
        }
        if (entity.attr("data-ban") == "1") {
            //是否被ban
            return false;
        } else {
            entity.addClass("active");
        }

    }

    //
    function hideAQWERDF() {
        $("#c-video-view >.video-js .c-course-video-aqwerdf").removeClass("active");
    }

    var endList = (function () {
        var endList = $("#tmp-c-course-video-end-list").html();
        return {
            showEndList: function () {
                if ($("#c-video-view >.video-js .c-course-video-end-list").length > 0) {
                    $("#c-video-view >.video-js .c-course-video-end-list").addClass("active");
                } else {
                    $("#c-video-view >.video-js").append(endList);
                }
            },
            hideEndList: function () {
                $("#c-video-view >.video-js .c-course-video-end-list").removeClass("active");
            }
        }
    })();

    function addPreviousAndNext2ToolBar() {
        var html = $("#tool-bar-previous-next").html();
        $(html).insertAfter(".vjs-control-bar .vjs-remaining-time");
    }

    (function initPlayer() {
        //设置全屏
        var v = document.getElementById("really-cool-video");

        var h = document.documentElement.clientHeight - 60;
        v.setAttribute("height", h + "px");

        var player = videojs('really-cool-video', {}, function () {

            $(".container").removeClass("loading");
            addPreviousAndNext2ToolBar();
            //
            //bind

            bindVideoEvents();
        });

    })();

    function bindVideoEvents() {

        var video = $("video").eq(0);

        //事件
        video.on("ended", function (e) {
            endList.showEndList();

        }).on("play", function (e) {
            //hideAQWERDF();
            endList.hideEndList();

        }).on("pause", function (e) {
            //showAQWERDF();
        });

        $("video source").each(function(index,elem){
            $(this).on('error',function(e){
                //console.error($(e.target).attr("src"));
                alifenxi.track("course_load_error", {
                    "course_name": $('#c_course_name').html(),
                    "resource_name" : $(e.target).attr("src")
                });
            })
        });

        //videojs API绑定

    }

    bindVideoEvents();

});<commit_msg>add email for admin user<commit_after>define(function (require, exports, moudle) {
    alifenxi.track("course_video_view", {
        "course_name": $('#c_course_name').html(),
        "resource_name" : $("#c-video-play-list .current-play .c-video-play-list-item-title ").html()
    });

    //分页
    var Pager = require('js/widget/pager');
    var commentBtn = $("#comment-submit");
    var commentArea = $("#user-comment-editor");
    var user_avator = ($('#ne_user_avator').val() - 0) || 1;
    var nickname = commentBtn.attr("data-nickname") || $('#ne_user_name').val();
    var userId = $('#ne_user_id').val();
    var courseid = commentBtn.attr("data-course-id");

    function addPage() {
        var page = new Pager({
            container: $('#video_pager'),
            sum: $('#comment_list').attr('data-num') - 0,
            count: 10,
            step: 10,
            showCount: false,
            start: 0,
            onChange: function (num, count) {
                drawComment(num + 1, count)
            }
        });
        page.init();
    };

    addPage();

    //加载评论
    function drawComment(num, count) {
        var tpl =
            ['<% comments.forEach(function(val){%>',
                '
',
                '
',
                '<div class="user-head-icon user-head-<%=val.avator||1%>">
',
                '
',
                '
',
                '<%=val.nickname%>',
                '

<%=val.comment%>

',
                '<% var d = new Date(val.updatetime).toLocaleDateString();%>',
                '<time class="comment-time"><%=val.updatetime%></time>',
                '
',
                '
',
                '<%})%>'].join("");
        $.get('/course/getcomment', {id: courseid, page: num, limit: count}, function (result) {
            if (result.errno == 0) {
                $('#comment_list').html(_.template(tpl, {comments: result.data}))
            }
        }, 'json')
    };
    //留下评论
    commentBtn.unbind("click").on("click", function (e) {
        var data = {};
        var userId = commentBtn.attr("data-user-id");
        data.comment = commentArea.val();
        data.id = courseid;
        if (data.comment.trim() == '') {
            return false;
        }

        $.post('/course/comment', data, 'json').done(function (res) {
            if (res.errno == 0) {
                var tmp = [
                    '
',
                    '
',
                    '

',
                    '
',
                    '
',
                    '', nickname, '',
                    '

', data.comment, '

',
                    '<time class="comment-time">刚刚</time>',
                    '
',
                    '
'
                ].join('');
                ALERT('提示', '评论成功！');
                $(tmp).prependTo('#comment_list');
                commentArea.val('');
            }
        });

    });

    //guanggao
    function showAQWERDF() {
        var entity = $("#c-video-view >.video-js .c-course-video-aqwerdf");

        if (entity.length == 0) {
            var html = $("#AQWERDF").html();
            $("#c-video-view >.video-js").append(html);
            var entity = $("#c-video-view >.video-js .c-course-video-aqwerdf");
        }
        if (entity.attr("data-ban") == "1") {
            //是否被ban
            return false;
        } else {
            entity.addClass("active");
        }

    }

    //
    function hideAQWERDF() {
        $("#c-video-view >.video-js .c-course-video-aqwerdf").removeClass("active");
    }

    var endList = (function () {
        var endList = $("#tmp-c-course-video-end-list").html();
        return {
            showEndList: function () {
                if ($("#c-video-view >.video-js .c-course-video-end-list").length > 0) {
                    $("#c-video-view >.video-js .c-course-video-end-list").addClass("active");
                } else {
                    $("#c-video-view >.video-js").append(endList);
                }
            },
            hideEndList: function () {
                $("#c-video-view >.video-js .c-course-video-end-list").removeClass("active");
            }
        }
    })();

    function addPreviousAndNext2ToolBar() {
        var html = $("#tool-bar-previous-next").html();
        $(html).insertAfter(".vjs-control-bar .vjs-remaining-time");
    }

    (function initPlayer() {
        //设置全屏
        var v = document.getElementById("really-cool-video");

        var h = document.documentElement.clientHeight - 60;
        v.setAttribute("height", h + "px");

        var player = videojs('really-cool-video', {}, function () {

            $(".container").removeClass("loading");
            addPreviousAndNext2ToolBar();
            //
            //bind

            bindVideoEvents();
        });

    })();

    function bindVideoEvents() {

        var video = $("video").eq(0);

        //事件
        video.on("ended", function (e) {
            endList.showEndList();

        }).on("play", function (e) {
            //hideAQWERDF();
            endList.hideEndList();

        }).on("pause", function (e) {
            //showAQWERDF();
        });

        $("video source").each(function(index,elem){
            $(this).on('error',function(e){
                //console.error($(e.target).attr("src"));
                alifenxi.track("course_load_error", {
                    "course_name": $('#c_course_name').html(),
                    "resource_name" : $(e.target).attr("src"),
                    "username" : $('#signin_user').html()
                });
            })
        });

        //videojs API绑定

    }

    bindVideoEvents();

});<|endoftext|>


<commit_before>var updateRemainingCharacters = function (event) {
    var charLimit = event.target.maxLength;
    var presentCount = event.target.value.length;
    var totalChars = charLimit - presentCount;
    $('#app-total-chars').html(totalChars);
};

var disableSubmission = function () {
    $(".app-response-submission").attr("disabled", "disabled");
    $(".app-response-submission").css("display", "none");
    $(".back-btn").removeClass("hidden");
    $("#timeout_alert").html('
 Oops..! Your submission time has been expired..
')
    setTimeout(function () {
        $(".alert").alert('close')
    }, 5000);
};

var showRemainingTime = function () {
    var date = new Date();
    var remainingTimeElement = $("#app-remaining-time");
    var time = remainingTimeElement.html();
    date.setSeconds(time);
    remainingTimeElement
        .countdown(formatDate(date), function (event) {
            $(this).text(
                event.strftime('%H:%M:%S')
            );
            var remaining_time = remainingTimeElement.html();
            if (remaining_time === "00:00:00")
                disableSubmission();
        });
};

var formatDate = function (date) {
   var MMddyyyyFormat = [date.getMonth()+1,date.getDate(),date.getFullYear()].join('/');
   var hhmmssFormat = [date.getHours(),date.getMinutes(),date.getSeconds()].join(':');
   return [MMddyyyyFormat,hhmmssFormat].join(' ');
}

var showRemainingCharacters = function () {
    $('#text').on('input', updateRemainingCharacters);
};

var remove_flash_messages = function () {
    $(".alert").ready(function () {
        setTimeout(function () {
            $(".alert").alert('close')
        }, 4000);
    })
};

document.addEventListener("turbolinks:load", function () {
    showRemainingCharacters();
    showRemainingTime();
    remove_flash_messages();
    initializeTaggings();
    initializeReviewButtions();
});

var changeReviewButtonColor = function (responseId, removeClass, addClass) {
    var ele = $('#app-tag-review-btn-' + responseId);
    ele.removeClass(removeClass);
    ele.addClass(addClass);
};

var createAutoCompleteEngine = function(){
    var tags = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        prefetch: {
            url: '/tags.json',
            cache: false
        }
    });
    tags.initialize();
    return tags;
};

var initializeTagsInput = function(engine){
    var inputElement = $('.app-input-tag');
    inputElement.tagsinput({
        tagClass: function (item) {
            return 'app-tag-input-' + item.id;
        },
        itemValue: 'id',
        itemText: 'name',
        typeaheadjs: [
            {
                hint: false,
                highlight: false,
                minLength: false,
                searchOnFocus: true
            },
            {
                name: 'tags',
                displayKey: 'name',
                source: engine.ttAdapter()
            }
        ]
    });
    return inputElement;
};

var initializeTagInputHooks = function(inputElement){
    inputElement.on('itemAdded', function (event) {
        var tag_id = event.item.id;
        var tag_color = event.item.color;
        var ele = $('.app-tag-input-' + tag_id);
        ele.css('background-color', tag_color);
    });

    inputElement.on('beforeItemAdd', function (event) {
        if (event.options && event.options.preventBackendCall)
            return;
        var tagName = event.item.name;
        var responseId = $(event.target).attr('data-response-id');
        onTagAddition(tagName, responseId);
        changeReviewButtonColor($(event.target).attr('data-response-id'), 'app-tag-review-btn-green', 'app-tag-review-btn-blue')
    });

    inputElement.on('beforeItemRemove', function (event) {
        if (event.options && event.options.preventBackendCall)
            return;
        var responseId = $(event.target).attr('data-response-id');
        var tagName = event.item.name;
        onTagRemoval(tagName, responseId);
    });
}

var initializeTags = function () {
    var engine = createAutoCompleteEngine();
    var inputElement = initializeTagsInput(engine);
    initializeTagInputHooks(inputElement);
    $(".twitter-typeahead").css('display', 'inline');
};

var initializePreviousTags = function () {
    $('.app-input-tag').each(function (index, inputTag) {
        var ele = $(inputTag);
        var tags = JSON.parse(ele.attr('data-tags'));
        tags.forEach(function (tag) {
            ele.tagsinput('add', tag, {preventBackendCall: true});
        })
    })
};

var initializeTaggings = function () {
    initializeTags();
    initializePreviousTags();
};

var requester = function (url, method, data) {
    return $.ajax({
        url: url,
        type: method,
        data: data
    });
};

var onTagAddition = function (tagName, responseId) {
    var uri = 'create_tagging_by_tag_name';
    var method = 'POST';
    var url = '/responses/' + responseId + '/taggings/' + uri;
    var data = {tag_name: tagName};
    requester(url, method, data)
};

var onTagRemoval = function (tagName, responseId) {
    var uri = 'delete_tagging_by_tag_name';
    var method = 'DELETE';
    var self = $(this);
    var url = '/responses/' + responseId + '/taggings/' + uri;
    var data = {tag_name: tagName};
    requester(url, method, data);
};

var initializeReviewButtions = function () {
    $('.app-tag-review-btn').on('click', function () {
        var uri = 'review_taggings';
        var method = 'PUT';
        var self = $(this);
        var responseId = self.attr('data-response-id');
        var url = '/responses/' + responseId + '/taggings/' + uri;
        var data = {};
        requester(url, method, data);
        changeReviewButtonColor($(event.target).attr('data-response-id'), 'app-tag-review-btn-blue', 'app-tag-review-btn-green')
    });
};
<commit_msg>[Dharmenn] Initialize tags input only if app-response-section element is present<commit_after>var updateRemainingCharacters = function (event) {
    var charLimit = event.target.maxLength;
    var presentCount = event.target.value.length;
    var totalChars = charLimit - presentCount;
    $('#app-total-chars').html(totalChars);
};

var disableSubmission = function () {
    $(".app-response-submission").attr("disabled", "disabled");
    $(".app-response-submission").css("display", "none");
    $(".back-btn").removeClass("hidden");
    $("#timeout_alert").html('
 Oops..! Your submission time has been expired..
')
    setTimeout(function () {
        $(".alert").alert('close')
    }, 5000);
};

var showRemainingTime = function () {
    var date = new Date();
    var remainingTimeElement = $("#app-remaining-time");
    var time = remainingTimeElement.html();
    date.setSeconds(time);
    remainingTimeElement
        .countdown(formatDate(date), function (event) {
            $(this).text(
                event.strftime('%H:%M:%S')
            );
            var remaining_time = remainingTimeElement.html();
            if (remaining_time === "00:00:00")
                disableSubmission();
        });
};

var formatDate = function (date) {
   var MMddyyyyFormat = [date.getMonth()+1,date.getDate(),date.getFullYear()].join('/');
   var hhmmssFormat = [date.getHours(),date.getMinutes(),date.getSeconds()].join(':');
   return [MMddyyyyFormat,hhmmssFormat].join(' ');
}

var showRemainingCharacters = function () {
    $('#text').on('input', updateRemainingCharacters);
};

var remove_flash_messages = function () {
    $(".alert").ready(function () {
        setTimeout(function () {
            $(".alert").alert('close')
        }, 4000);
    })
};

document.addEventListener("turbolinks:load", function () {
    showRemainingCharacters();
    showRemainingTime();
    remove_flash_messages();
    initializeTaggings();
    initializeReviewButtions();
});

var changeReviewButtonColor = function (responseId, removeClass, addClass) {
    var ele = $('#app-tag-review-btn-' + responseId);
    ele.removeClass(removeClass);
    ele.addClass(addClass);
};

var createAutoCompleteEngine = function(){
    var tags = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        prefetch: {
            url: '/tags.json',
            cache: false
        }
    });
    tags.initialize();
    return tags;
};

var initializeTagsInput = function(engine){
    var inputElement = $('.app-input-tag');
    inputElement.tagsinput({
        tagClass: function (item) {
            return 'app-tag-input-' + item.id;
        },
        itemValue: 'id',
        itemText: 'name',
        typeaheadjs: [
            {
                hint: false,
                highlight: false,
                minLength: false,
                searchOnFocus: true
            },
            {
                name: 'tags',
                displayKey: 'name',
                source: engine.ttAdapter()
            }
        ]
    });
    return inputElement;
};

var initializeTagInputHooks = function(inputElement){
    inputElement.on('itemAdded', function (event) {
        var tag_id = event.item.id;
        var tag_color = event.item.color;
        var ele = $('.app-tag-input-' + tag_id);
        ele.css('background-color', tag_color);
    });

    inputElement.on('beforeItemAdd', function (event) {
        if (event.options && event.options.preventBackendCall)
            return;
        var tagName = event.item.name;
        var responseId = $(event.target).attr('data-response-id');
        onTagAddition(tagName, responseId);
        changeReviewButtonColor($(event.target).attr('data-response-id'), 'app-tag-review-btn-green', 'app-tag-review-btn-blue')
    });

    inputElement.on('beforeItemRemove', function (event) {
        if (event.options && event.options.preventBackendCall)
            return;
        var responseId = $(event.target).attr('data-response-id');
        var tagName = event.item.name;
        onTagRemoval(tagName, responseId);
    });
}

var initializeTags = function () {
    var engine = createAutoCompleteEngine();
    var inputElement = initializeTagsInput(engine);
    initializeTagInputHooks(inputElement);
    $(".twitter-typeahead").css('display', 'inline');
};

var initializePreviousTags = function () {
    $('.app-input-tag').each(function (index, inputTag) {
        var ele = $(inputTag);
        var tags = JSON.parse(ele.attr('data-tags'));
        tags.forEach(function (tag) {
            ele.tagsinput('add', tag, {preventBackendCall: true});
        })
    })
};

function hasResponseReviewSection() {
  return $('.app-response-review-section').length <= 0;
}

var initializeTaggings = function () {
    if(hasResponseReviewSection())
      return;
    initializeTags();
    initializePreviousTags();
};

var requester = function (url, method, data) {
    return $.ajax({
        url: url,
        type: method,
        data: data
    });
};

var onTagAddition = function (tagName, responseId) {
    var uri = 'create_tagging_by_tag_name';
    var method = 'POST';
    var url = '/responses/' + responseId + '/taggings/' + uri;
    var data = {tag_name: tagName};
    requester(url, method, data)
};

var onTagRemoval = function (tagName, responseId) {
    var uri = 'delete_tagging_by_tag_name';
    var method = 'DELETE';
    var self = $(this);
    var url = '/responses/' + responseId + '/taggings/' + uri;
    var data = {tag_name: tagName};
    requester(url, method, data);
};

var initializeReviewButtions = function () {
    $('.app-tag-review-btn').on('click', function () {
        var uri = 'review_taggings';
        var method = 'PUT';
        var self = $(this);
        var responseId = self.attr('data-response-id');
        var url = '/responses/' + responseId + '/taggings/' + uri;
        var data = {};
        requester(url, method, data);
        changeReviewButtonColor($(event.target).attr('data-response-id'), 'app-tag-review-btn-blue', 'app-tag-review-btn-green')
    });
};
<|endoftext|>


<commit_before>/*doc
---
title: Dividers
name: divider_react
categories:
- react_base_dividers
- react_all
---

npm install pui-react-dividers --save

## Props

Property | Required | Type | Default | Description
---------|----------|------|---------|------------
inverse | no | Boolean        | | Specifying this prop inverses the divider (you can also use InverseDivider)
size    | no | oneOf('large') | | Changes the size of the component

## Basic usage

Import the subcomponents:

```
import {Divider, InverseDivider} from 'pui-react-dividers';
```

Dividers draw horizontal lines between different content groupings.

```react_example_table
<Divider />

<Divider size="large" />
```

On a dark background, use these inverse dividers

```react_inverse_example_table
<div className="type-dark-11">
  I am some content
  <InverseDivider />
  Me too
</div>

<div className="type-dark-11">
  Here's some stuff above the divider
  <InverseDivider size="large" />
  Here's some stuff below the divider
</div>
```
*/
<commit_msg>chore(Styleguide): remove InverseDivider from documentation. People should just use the inverse prop on Divider<commit_after>/*doc
---
title: Dividers
name: divider_react
categories:
- react_base_dividers
- react_all
---

npm install pui-react-dividers --save

## Props

Property | Required | Type | Default | Description
---------|----------|------|---------|------------
inverse | no | Boolean        | | Specifying this prop inverses the divider
size    | no | oneOf('large') | | Changes the size of the component

## Basic usage

Import the subcomponents:

```
import {Divider} from 'pui-react-dividers';
```

Dividers draw horizontal lines between different content groupings.

```react_example_table
<Divider />

<Divider size="large" />
```

On a dark background, use these inverse dividers

```react_inverse_example_table
<div className="type-dark-11">
  I am some content
  <Divider inverse />
  Me too
</div>

<div className="type-dark-11">
  Here's some stuff above the divider
  <Divider inverse size="large" />
  Here's some stuff below the divider
</div>
```
*/
<|endoftext|>


<commit_before>let interpreter = require('./interpreter');
let fromNow = require('./from-now');
let ExtendableError = require('es6-error');

let interpolate = (string, context) => {
  return string.replace('/\${([^}]*)}/g', (text, expr) => {
    return interpreter.parse(expr, context);
  });
};

let deleteMarker = {};

class TemplateError extends ExtendableError {
  constructor(message) {
    super(message);
    this.message = message;
    this.name = 'Template Error';
  }
}

let constructs = {
  $eval: (template, context) => {
    if (!(typeof template['$eval'] === 'string')) {
      throw new TemplateError('$eval can evaluate string expressions only\n' + JSON.stringify(template, null, '\t'));
    }
    return interpreter.parse(template['$eval'], context);
  },
  $fromNow: (template, context) => {
    if (!(typeof ['$fromNow'] === 'string')) {
      throw new TemplateError('$fromNow can evaluate string expressions only\n' + JSON.stringify(template, null, '\t'));
    }
    return fromNow(template['fromNow']);
  },
  $if: (template, context) => {
    if (!(typeof template['$if'] === 'string')) {
      throw new TemplateError('$if can evaluate string expressions only\n' + JSON.stringify(template, null, '\t'));
    }
    if (interpreter.parse(template['$if'], context)) {
      return template.hasOwnProperty('then') ? render(template.then, context) : deleteMarker;
    } else {
      return template.hasOwnProperty('else') ? render(template.else, context) : deleteMarker;
    }
  },
  $switch: (template, context) => {
    if (!(typeof template['$switch'] === 'string')) {
      throw new TemplateError('$switch can evaluate string expressions only\n' + JSON.stringify(template, null, '\t'));
    }
    let c = interpreter.parse(template['$switch'], context);
    return template.hasOwnProperty(c) ? render(template[c], context) : deleteMarker;
  },
};

let render = (template, context) => {
  if (typeof template === 'number' || typeof template === 'boolean') {
    return template;
  }
  if (typeof template === 'string') {
    return interpolate(template, context);
  }
  if (template instanceof Array) {
    return template.map((v) => render(v, context)).filter((v) => v !== deleteMarker);
  }

  // check for multiple constructs
  let detectConstruct = false, prevConstruct;
  for (let construct of Object.keys(constructs)) {
    if (template.hasOwnProperty(construct)) {
      if (detectConstruct) {
        throw new TemplateError('only one construct allowed\n'
          + JSON.stringify(template, null, '\t'));
      } else {
        detectConstruct = true;
      }
    }
  }

  for (let construct of Object.keys(constructs)) {
    if (template.hasOwnProperty(construct)) {
      return constructs[construct](template, context);
    }
  }

  // clone object
  let result = {};
  for (let key of Object.keys(template)) {
    let value = render(template[key], context);
    if (value !== deleteMarker) {
      result[interpolate(key, context)] = value;
    }
  }
  return result;
};

//console.log(render({a: {$eval: '1 + 2', $if: 'true'}}, {}));

module.exports = (template, context = {}) => {
  let result = render(template, context);
  if (result === deleteMarker) {
    return undefined;
  }
  return result;
};
<commit_msg>$json implemented<commit_after>let interpreter = require('./interpreter');
let fromNow = require('./from-now');
let ExtendableError = require('es6-error');

class TemplateError extends ExtendableError {
  constructor(message) {
    super(message);
    this.message = message;
    this.name = 'Template Error';
  }
}

let interpolate = (string, context) => {
  return string.replace('/\${([^}]*)}/g', (text, expr) => {
    let v = interpreter.parse(expr, context);
    if (v instanceof Array || v instanceof Object) {
      throw new TemplateError('Cannot interpolate objects/arrays: '
        + text + ' <-- ' + expr);
    }
    return v;
  });
};

let deleteMarker = {};

let constructs = {
  $eval: (template, context) => {
    if (!(typeof template['$eval'] === 'string')) {
      throw new TemplateError('$eval can evaluate string expressions only\n' + JSON.stringify(template, null, '\t'));
    }
    return interpreter.parse(template['$eval'], context);
  },
  $fromNow: (template, context) => {
    if (!(typeof ['$fromNow'] === 'string')) {
      throw new TemplateError('$fromNow can evaluate string expressions only\n' + JSON.stringify(template, null, '\t'));
    }
    return fromNow(template['fromNow']);
  },
  $if: (template, context) => {
    if (!(typeof template['$if'] === 'string')) {
      throw new TemplateError('$if can evaluate string expressions only\n' + JSON.stringify(template, null, '\t'));
    }
    if (interpreter.parse(template['$if'], context)) {
      return template.hasOwnProperty('then') ? render(template.then, context) : deleteMarker;
    } else {
      return template.hasOwnProperty('else') ? render(template.else, context) : deleteMarker;
    }
  },
  $switch: (template, context) => {
    if (!(typeof template['$switch'] === 'string')) {
      throw new TemplateError('$switch can evaluate string expressions only\n' + JSON.stringify(template, null, '\t'));
    }
    let c = interpreter.parse(template['$switch'], context);
    return template.hasOwnProperty(c) ? render(template[c], context) : deleteMarker;
  },
  $json: (template, context) => {
    if (template['$json'] instanceof Array || template['$json'] instanceof Object) {
      return JSON.stringify(render(template['$json'], context));
    }
    return JSON.stringify(template['$json']);
  },
};

let render = (template, context) => {
  if (typeof template === 'number' || typeof template === 'boolean') {
    return template;
  }
  if (typeof template === 'string') {
    return interpolate(template, context);
  }
  if (template instanceof Array) {
    return template.map((v) => render(v, context)).filter((v) => v !== deleteMarker);
  }

  // check for multiple constructs
  let detectConstruct = false, prevConstruct;
  for (let construct of Object.keys(constructs)) {
    if (template.hasOwnProperty(construct)) {
      if (detectConstruct) {
        throw new TemplateError('only one construct allowed\n'
          + JSON.stringify(template, null, '\t'));
      } else {
        detectConstruct = true;
      }
    }
  }

  for (let construct of Object.keys(constructs)) {
    if (template.hasOwnProperty(construct)) {
      return constructs[construct](template, context);
    }
  }

  // clone object
  let result = {};
  for (let key of Object.keys(template)) {
    let value = render(template[key], context);
    if (value !== deleteMarker) {
      result[interpolate(key, context)] = value;
    }
  }
  return result;
};

//console.log(render({a: {$eval: '1 + 2', $if: 'true'}}, {}));

module.exports = (template, context = {}) => {
  let result = render(template, context);
  if (result === deleteMarker) {
    return undefined;
  }
  return result;
};
<|endoftext|>


<commit_before>var http = require('http')
var url = require('url')
var request = require('request')

const PORT = 3000

var params = process.argv
var destUrl = ''
var token = ''
var readOnly = false

// Parse CLI parameters
params.forEach(function (val, index, array) {
  switch (val) {
    case '--url':
      destUrl = params[index + 1]
    case '--token':
      token = params[index + 1]
    case '--read-only':
      readOnly = true
  }
})

const server = http.createServer(function(req, res) {
  if (req.method == 'GET') {
    proxyRequest(destUrl, req, function(err, body) {
      if (!err) {
        res.setHeader('Content-Type', 'application/json')
        res.write(JSON.stringify(body), null, 4)
        res.end()
      }
    })
  }
}).listen(PORT)

function proxyRequest(dest, req, callback) {
  return request(dest.replace(/\/$/, "") + req.url, function(err, res, body) {
    callback(err, body)
  })
}<commit_msg>Send JSON<commit_after>var http = require('http')
var url = require('url')
var request = require('request')

const PORT = 3000

var params = process.argv
var destUrl = ''
var token = ''
var readOnly = false

// Parse CLI parameters
params.forEach(function (val, index, array) {
  switch (val) {
    // URL to proxy to
    case '--url':
      destUrl = params[index + 1]
    // Token for request
    case '--token':
      token = params[index + 1]
    // Read only flag
    case '--read-only':
      readOnly = true
  }
})

const server = http.createServer(function(req, res) {
  if (req.method == 'GET') {
    proxyRequest(destUrl, req, function(err, body) {
      if (!err) {
        res.setHeader('Content-Type', 'application/json')
        res.write(body)
        res.end()
      }
    })
  }
}).listen(PORT)

function proxyRequest(dest, req, callback) {
  return request(dest.replace(/\/$/, "") + req.url, function(err, res, body) {
    callback(err, body)
  })
}<|endoftext|>