<commit_before>// ==UserScript==
// @name         Waze Map Editor - Utils
// @namespace    http://tampermonkey.net/
// @version      1.0.2
// @description  set of utils to speed development
// @author       Delfim Machado - dbcm@profundos.org
// @match        https://beta.waze.com/*editor/*
// @match        https://www.waze.com/*editor/*
// @exclude      https://www.waze.com/*user/*editor/*
// @grant        none
// ==/UserScript==

/*

reusable code for all WME tools i'm building

*/

(function(root) {
    "use strict";

    var face = {
        'meh': '¯\_(ツ)_/¯',
        'angry': '(⋟﹏⋞)',
        'happy': '⎦˚◡˚⎣'
    };

    var WMEutils = function(options) {
        this.init(options);
    };

    WMEutils.prototype.init = function(opt) {
        this._VERSION = 0.1;

        opt = opt || {};

        this.debug = opt.debug;

        this.app = opt.app || 'DUH';
        this.uid = opt.uid || '___';
        this.version = opt.version || '0.0.666';
    };

    /*
    	o
    	{
    		id: "blame",
    		name: "bl",
    		title: 'blame plugin : ¯\\_(ツ)_/¯  [last 10 days]',
    		desc: 'i blame you all',
    		content: menu
    	}
    */
    WMEutils.prototype.addTab = function(o) {
        var self = this;

        // while testing and developing...
        var mdk = function(id) {
            try {
                document.getElementById(id).remove();
            } catch (e) {
                console.log("X");
            };
        }

        if (document.getElementById("t" + o.id)) {
            return;
        };

        var addon = document.createElement('div');
        addon.innerHTML += '

' + o.title + '

';
        addon.innerHTML += o.content;
        addon.innerHTML += '

';

        var navTabs = document.getElementsByClassName("nav nav-tabs")[0];
        var tabContent = document.getElementsByClassName("tab-content")[0];

        var newtab = document.createElement('li');
        newtab.id = "t" + o.id;
        newtab.innerHTML = '' + o.name + '';
        //mdk("t" + o.id);
        navTabs.appendChild(newtab);

        addon.id = "sidepanel-" + o.id;
        addon.className = "tab-pane";
        //mdk("sidepanel-" + o.id);
        tabContent.appendChild(addon);

    };

    /*
    	f = ARRAY of functions
    */
    WMEutils.prototype.loopSegments = function(f) {
        for (var segId in Waze.model.segments.objects) {
            var seg = Waze.model.segments.get(segId);

            if (!this.isOnScreen(seg)) {
                continue;
            }

            if (!this.canEdit(seg)) {
                continue;
            }

            for (var i = 0; i < f.length; i++) {
                if (f[i])
                    f[i](seg);
            }
        }
    }

    /*
    	f = ARRAY of functions
    */
    WMEutils.prototype.loopVenues = function(f) {
            for (var venId in Waze.model.venues.objects) {
                var ven = Waze.model.venues.get(venId);

                if (!this.isOnScreen(ven)) {
                    continue;
                }

                if (!this.canEdit(ven)) {
                    continue;
                }

                for (var i = 0; i < f.length; i++) {
                    if (f[i])
                        f[i](ven);
                }
            }
        }
        /*
        	if the object visible
        */
    WMEutils.prototype.isOnScreen = function(obj) {
        if (obj.geometry) {
            return (Waze.map.getExtent().intersectsBounds(obj.geometry.getBounds()));
        }
        return false;
    }

    /*
    	can i edit this object
    */
    WMEutils.prototype.canEdit = function(obj) {
        if (obj.type === 'segment')
            return obj.isAllowed(obj.PERMISSIONS.EDIT_GEOMETRY) || obj.hasClosures() || obj.isUpdated();
        if (obj.type === 'venue')
            return obj.isAllowed(obj.PERMISSIONS.EDIT_GEOMETRY) || obj.isUpdated();
    };

    /*
    	is this object in Portugal
    */
    WMEutils.prototype.isPortugal = function(obj) {
        var att = obj.attributes;
        var street = Waze.model.streets.get(att.primaryStreetID);
        var city = segment.model.cities.get(street.cityID);
        var countryId = city.countryID;

        return countryId === 181;
    }

    /*
    	return a random color
    */
    WMEutils.prototype.rColor = function() {
        var letters = '0123456789ABCDEF';
        var color = '#';
        for (var i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }

    /*
        obj = must be a segment OBJ
    */
    WMEutils.prototype.isDrivable = function(obj) {
        if (obj.type === 'segment') {
            var drivable = [1, 2, 3, 4, 6, 7, 8, 17, 15, 20];

            if (drivable.includes(obj.attributes.roadType)) {
                return true;
            }
        };
        return false;
    };

    /*
        obj = object to highlight, can be and segment or a place (landmark/venue)
        color = highlight color
        bgColor = background color, if null, defaults to color
    */
    WMEutils.prototype.highlightObject = function(obj, color, bgColor) {
        return new OpenLayers.Feature.Vector(obj.geometry.clone(), {}, {
            strokeColor: color,
            strokeDashstyle: "none",
            strokeLinecap: "round",
            strokeWidth: 30,
            strokeOpacity: 0.5,
            fill: true,
            fillColor: bgColor || color,
            fillOpacity: 0.2
        });
    };

    /*
    	options stuff
    */
    WMEutils.prototype.loadOptions = function() {
        var self = this;

        return JSON.parse(localStorage.getItem(self.uid + "_options"));
    }
    WMEutils.prototype.saveOptions = function(options) {
        var self = this;

        return localStorage.setItem(self.uid + "_options", JSON.stringify(options));
    }

    /*
    	log stuff
    */
    WMEutils.prototype.log = function(msg) {
        var self = this;

        var now = Date.now();
        console.log("[" + this.app + "] " + now + " : " + msg);
    }

    /*
    	returns true if you are using beta editor
    */
    WMEutils.prototype.onBeta = function() {
        return -1 !== window.location.href.indexOf("beta");
    }

    /*
    	add menu layer

        section = [issues, places, road, display]
        name = layer name
        uid = internal id
        callback = function() {...}
        layer = OL Layer
    */
    WMEutils.prototype.addMenuLayer = function(o) {
        // from WME Street View Availability
        var roadGroupSelector = document.getElementById('layer-switcher-group_' + o.section);
        if (roadGroupSelector !== null) {
            var roadGroup = roadGroupSelector.parentNode.parentNode.querySelector('.children');
            var toggler = document.createElement('li');
            var togglerContainer = document.createElement('div');
            togglerContainer.className = 'controls-container toggler';
            var checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.id = 'layer-switcher-item_' + o.uid;
            checkbox.className = 'toggle';
            checkbox.checked = true;
            checkbox.addEventListener('click', function(e) {
                o.layer.setVisibility(e.target.checked);
            });
            togglerContainer.appendChild(checkbox);
            var label = document.createElement('label');
            label.htmlFor = checkbox.id;
            var labelText = document.createElement('span');
            labelText.className = 'label-text';
            labelText.appendChild(document.createTextNode(o.name));
            label.appendChild(labelText);
            togglerContainer.appendChild(label);
            toggler.appendChild(togglerContainer);
            roadGroup.appendChild(toggler);
        }
    };

    root.WMEutils = WMEutils;
})(window);
<commit_msg>WMEutils.prototype.loopNodes support<commit_after>// ==UserScript==
// @name         Waze Map Editor - Utils
// @namespace    http://tampermonkey.net/
// @version      1.0.3
// @description  set of utils to speed development
// @author       Delfim Machado - dbcm@profundos.org
// @match        https://beta.waze.com/*editor/*
// @match        https://www.waze.com/*editor/*
// @exclude      https://www.waze.com/*user/*editor/*
// @grant        none
// ==/UserScript==

/*

reusable code for all WME tools i'm building

*/

(function(root) {
    "use strict";

    var face = {
        'meh': '¯\_(ツ)_/¯',
        'angry': '(⋟﹏⋞)',
        'happy': '⎦˚◡˚⎣'
    };

    var WMEutils = function(options) {
        this.init(options);
    };

    WMEutils.prototype.init = function(opt) {
        this._VERSION = 0.1;

        opt = opt || {};

        this.debug = opt.debug;

        this.app = opt.app || 'DUH';
        this.uid = opt.uid || '___';
        this.version = opt.version || '0.0.666';
    };

    /*
    	o
    	{
    		id: "blame",
    		name: "bl",
    		title: 'blame plugin : ¯\\_(ツ)_/¯  [last 10 days]',
    		desc: 'i blame you all',
    		content: menu
    	}
    */
    WMEutils.prototype.addTab = function(o) {
        var self = this;

        // while testing and developing...
        var mdk = function(id) {
            try {
                document.getElementById(id).remove();
            } catch (e) {
                console.log("X");
            };
        }

        if (document.getElementById("t" + o.id)) {
            return;
        };

        var addon = document.createElement('div');
        addon.innerHTML += '

' + o.title + '

';
        addon.innerHTML += o.content;
        addon.innerHTML += '

';

        var navTabs = document.getElementsByClassName("nav nav-tabs")[0];
        var tabContent = document.getElementsByClassName("tab-content")[0];

        var newtab = document.createElement('li');
        newtab.id = "t" + o.id;
        newtab.innerHTML = '' + o.name + '';
        //mdk("t" + o.id);
        navTabs.appendChild(newtab);

        addon.id = "sidepanel-" + o.id;
        addon.className = "tab-pane";
        //mdk("sidepanel-" + o.id);
        tabContent.appendChild(addon);

    };

    /*
    	f = ARRAY of functions
    */
    WMEutils.prototype.loopSegments = function(f) {
        for (var segId in Waze.model.segments.objects) {
            var seg = Waze.model.segments.get(segId);

            if (!this.isOnScreen(seg)) {
                continue;
            }

            if (!this.canEdit(seg)) {
                continue;
            }

            for (var i = 0; i < f.length; i++) {
                if (f[i])
                    f[i](seg);
            }
        }
    }

    /*
    	f = ARRAY of functions
    */
    WMEutils.prototype.loopVenues = function(f) {
        for (var venId in Waze.model.venues.objects) {
            var ven = Waze.model.venues.get(venId);

            if (!this.isOnScreen(ven)) {
                continue;
            }

            if (!this.canEdit(ven)) {
                continue;
            }

            for (var i = 0; i < f.length; i++) {
                if (f[i])
                    f[i](ven);
            }
        }
    };

    /*
    	f = ARRAY of functions
    */
    WMEutils.prototype.loopNodes = function(f) {
        for (var nodId in Waze.model.nodes.objects) {
            var nod = Waze.model.nodes.get(nodId);

            if (!this.isOnScreen(nod)) {
                continue;
            }

            if (!this.canEdit(nod)) {
                continue;
            }

            for (var i = 0; i < f.length; i++) {
                if (f[i])
                    f[i](nod);
            }
        }
    };

    /*
    	if the object visible
    */
    WMEutils.prototype.isOnScreen = function(obj) {
        if (obj.geometry) {
            return (Waze.map.getExtent().intersectsBounds(obj.geometry.getBounds()));
        }
        return false;
    }

    /*
    	can i edit this object
    */
    WMEutils.prototype.canEdit = function(obj) {
        if (obj.type === 'segment')
            return obj.isAllowed(obj.PERMISSIONS.EDIT_GEOMETRY) || obj.hasClosures() || obj.isUpdated();
        if (obj.type === 'venue')
            return obj.isAllowed(obj.PERMISSIONS.EDIT_GEOMETRY) || obj.isUpdated();
        if (obj.type === 'node')
            return obj.areConnectionsEditable() || obj.isUpdated();
    };

    /*
    	is this object in Portugal
    */
    WMEutils.prototype.isPortugal = function(obj) {
        var att = obj.attributes;
        var street = Waze.model.streets.get(att.primaryStreetID);
        var city = segment.model.cities.get(street.cityID);
        var countryId = city.countryID;

        return countryId === 181;
    }

    /*
    	return a random color
    */
    WMEutils.prototype.rColor = function() {
        var letters = '0123456789ABCDEF';
        var color = '#';
        for (var i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }

    /*
        obj = must be a segment OBJ
    */
    WMEutils.prototype.isDrivable = function(obj) {
        if (obj.type === 'segment') {
            var drivable = [1, 2, 3, 4, 6, 7, 8, 17, 15, 20];

            if (drivable.includes(obj.attributes.roadType)) {
                return true;
            }
        };
        return false;
    };

    /*
        obj = object to highlight, can be and segment or a place (landmark/venue)
        color = highlight color
        bgColor = background color, if null, defaults to color
    */
    WMEutils.prototype.highlightObject = function(obj, color, bgColor) {
        return new OpenLayers.Feature.Vector(obj.geometry.clone(), {}, {
            strokeColor: color,
            strokeDashstyle: "none",
            strokeLinecap: "round",
            strokeWidth: 30,
            strokeOpacity: 0.5,
            fill: true,
            fillColor: bgColor || color,
            fillOpacity: 0.2,
            pointRadius: 6,
            fontColor: 'white',
            labelOutlineColor: color,
            labelOutlineWidth: 4,
            labelAlign: 'left',
            label: null
        });
    };

    /*
    	options stuff
    */
    WMEutils.prototype.loadOptions = function() {
        var self = this;

        return JSON.parse(localStorage.getItem(self.uid + "_options"));
    }
    WMEutils.prototype.saveOptions = function(options) {
        var self = this;

        return localStorage.setItem(self.uid + "_options", JSON.stringify(options));
    }

    /*
    	log stuff
    */
    WMEutils.prototype.log = function(msg) {
        var self = this;

        var now = Date.now();
        console.log("[" + this.app + "] " + now + " : " + msg);
    }

    /*
    	returns true if you are using beta editor
    */
    WMEutils.prototype.onBeta = function() {
        return -1 !== window.location.href.indexOf("beta");
    }

    /*
    	add menu layer

        section = [issues, places, road, display]
        name = layer name
        uid = internal id
        callback = function() {...}
        layer = OL Layer
    */
    WMEutils.prototype.addMenuLayer = function(o) {
        // from WME Street View Availability
        var roadGroupSelector = document.getElementById('layer-switcher-group_' + o.section);
        if (roadGroupSelector !== null) {
            var roadGroup = roadGroupSelector.parentNode.parentNode.querySelector('.children');
            var toggler = document.createElement('li');
            var togglerContainer = document.createElement('div');
            togglerContainer.className = 'controls-container toggler';
            var checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.id = 'layer-switcher-item_' + o.uid;
            checkbox.className = 'toggle';
            checkbox.checked = true;
            checkbox.addEventListener('click', function(e) {
                o.layer.setVisibility(e.target.checked);
            });
            togglerContainer.appendChild(checkbox);
            var label = document.createElement('label');
            label.htmlFor = checkbox.id;
            var labelText = document.createElement('span');
            labelText.className = 'label-text';
            labelText.appendChild(document.createTextNode(o.name));
            label.appendChild(labelText);
            togglerContainer.appendChild(label);
            toggler.appendChild(togglerContainer);
            roadGroup.appendChild(toggler);
        }
    };

    root.WMEutils = WMEutils;
})(window);
<|endoftext|>


<commit_before>//# require=d3,leaflet

function update(data) {
  tick = null;
  show(data.toList({ typed: false }));
}

/**
 * Created by osoken on 2016/05/16.
 */

// map handler
!(function(d3,L)
{
  var map = {};
  var tracking = true;
  var zoom = 2;
  var mapLayer = null;
  var svgLayer = null;
  var pathLayer = null;
  var plotLayer = null;
  var infoLayer = null;
  var selection = null;
  var margin = 100;

  map.init = function(s)
  {

    selection = s;
    selection.style('height', root.clientHeight+'px');
    selection.style('width', root.clientWidth+'px');
    var point = [0, 0];
    mapLayer = L.map(selection.attr('id')).setView(point, zoom);

    var tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
      attribution : '© OpenStreetMap contributors'
    }).addTo(mapLayer);

    svgLayer = d3.select(mapLayer.getPanes().overlayPane).append("svg");

    plotLayer = svgLayer.append('g');
    timeLayer = svgLayer.append('g');
    mapLayer.on("viewreset", map.reset);
    d3.rebind(map, mapLayer, 'on');
    map.reset();
  }

  map.projectPoint = function(lat, lng)
  {
    if (lng===void 0)
    {
      return mapLayer.latLngToLayerPoint(lat);
    }
    return mapLayer.latLngToLayerPoint(new L.LatLng(lat, lng));
  }
  map.invertPoint = function(x, y)
  {
    if (y===void 0)
    {
      return mapLayer.layerPointToLatLng(x);
    }
    return mapLayer.layerPointToLatLng(new L.point(x,y));
  }
  map.getBounds = function() {
    return mapLayer.getBounds();
  }
  map.svg = function()
  {
    return svgLayer;
  }
  map.plotLayer = function()
  {
    return plotLayer;
  }
  map.timeLayer = function()
  {
    return timeLayer;
  }
  map.bound = function()
  {
    var bounds = plotLayer.node().getBBox();

    return {x:bounds.x-margin,y:bounds.y-margin,width:bounds.width+2*margin,height:bounds.height+2*margin};
  }
  map.reset = function()
  {
    var bounds = map.getBounds();
    var topLeft = map.projectPoint(bounds.getNorthWest());
    var bottomRight = map.projectPoint(bounds.getSouthEast());

    svgLayer.attr("width", bottomRight.x - topLeft.x)
      .attr("height", bottomRight.y - topLeft.y)
      .style("left", topLeft.x + "px")
      .style("top", topLeft.y + "px");
    timeLayer.selectAll('line').attr('opacity', function(d) {
      return (bounds.getWest() <= d.longitude && d.longitude <= bounds.getEast() &&
             bounds.getSouth() <= d.latitude && d.latitude <= bounds.getNorth())? 1.0: 0.08;
    });
    plotLayer.attr('transform', 'translate('+ -topLeft.x + ',' + -topLeft.y + ')');
  }
  this.map = map;
}(d3,L));

map.init(d3.select(root).append('div').attr('id','map-container'))
var tick = null;

function show(data)
{
  if (data.length == 0)
  {
    return;
  }

  var width = root.clientWidth;
  var height = root.clientHeight;

  var margin = {left: 20, bottom: 60, top: 0, right: 20};
  var padding = {left: 10, bottom: 20, top: 10, right: 10};

  var panelHeight = 40;
  var panelWidth = width - margin.left - margin.right;
  var graphHeight = panelHeight - padding.left - padding.right;
  var graphWidth = panelWidth - padding.top - padding.bottom;

  var timeFormat = d3.time.format('%Y-%m-%dT%H:%M:%S.%LZ');
  var timeDispFormat = d3.time.format('%Y/%m/%d %H:%M:%S');

  var timeDispFunc = function(d) {
    return timeDispFormat(d.time);
  }

  var timeFormat = d3.time.format('%Y-%m-%dT%H:%M:%S.%LZ');
  var timeDispFormat = d3.time.format('%Y/%m/%d(%a) %H:%M:%S');

  var timeDispFunc = function(d) {
    return timeDispFormat(d.time);
  }

  var colored = function(lng) {
    return d3.hsl((lng<0)?(360+lng):lng, 1.0, 0.5);
  }

  var timeScale = d3.time.scale();
  var graphXScale = d3.time.scale().range([0, graphWidth]);
  var graphYScale = d3.scale.linear().range([0, graphHeight]);

  var drag = d3.behavior.drag();

  var getMouseX = function(event) {
    if (event.offsetX != null) {
      getMouseX = function(event) {return event.offsetX;};
      return event.offsetX;
    }
    if (event.layerX != null) {
      getMouseX = function(event) {return event.layerX;};
      return event.layerX;
    }
    getMouseX = function(event) {return event.x;}
    return event.x;
  }

  drag.on('dragstart', function() {
    d3.event.sourceEvent.stopPropagation();
  }).on('dragend', function() {
    d3.event.sourceEvent.stopPropagation();
  }).on('drag', function() {
    d3.event.sourceEvent.stopPropagation();
  });

  var tick = null;

  data.forEach(function(d) {
    d.time = timeFormat.parse(d.time);
    d.latitude = +d.latitude;
    d.longitude = +d.longitude;
    d.color = colored(d.longitude);
  });

  timeScale.domain(d3.extent(data, function(d){return d.time;}));
  graphXScale.domain(d3.extent(data, function(d){return d.time;}));
  graphYScale.domain([0, 1]);

  var svgLayer = map.svg();
  var plotLayer = map.plotLayer();
  var uiHeight = 100;
  var timeLayer = map.timeLayer().attr('transform', 'translate('+margin.left+','+(height - margin.bottom - panelHeight)+')');

  var showAll = null;

  var startAnim = function(t0, dt) {
    if (showAll != null) {
      clearTimeout(showAll);
      showAll = null;
    }
    if (tick != null) {
      tick = null;
    }
    plotLayer.selectAll('circle').transition().duration(0).attr('opacity', 0.0);
    var t1 = timeScale.domain()[1];
    var tc = t0;
    textLabel.text(timeDispFormat(tc))
      .transition().duration(0)
      .attr({'opacity': 0.8});
    indicator.transition().duration(0).attr('opacity', 0.8);
    var lastTime = new Date().getTime();
    tick = function() {
      if ( t1 < tc ) {
        tick = null;
        if (showAll != null) {
          clearTimeout(showAll);
          showAll = null;
        }
        showAll = setTimeout(function() {
          textLabel.transition().duration(0).attr('opasity', 0.0).text('');
          plotLayer.selectAll('circle').transition().duration(2000)
            .attr('opacity', 0.8);
          showAll = null;
          indicator.transition().attr('opacity', 0.0);
        }, 2000);
        return;
      }
      indicator.moveTo(tc);
      textLabel.text(timeDispFormat(tc));
      var currentTime = new Date().getTime();
      delta = (currentTime - lastTime) * dt;
      plotLayer.selectAll('circle').filter(function(d) {
        return tc < d.time && (new Date(tc.getTime()+delta) >= d.time);
      }).attr('opacity', 0.8).transition().delay(1000).attr('opacity', 0.0);
      tc = new Date(tc.getTime() + delta);
      lastTime = currentTime;
      setTimeout(tick, 10);
    }
    tick();
  };

  timeLayer.selectAll('rect').remove();
  timeLayer.append('rect').attr({x:0, y:0, width: panelWidth, height: panelHeight})
    .style({fill: 'rgba(255,255,255,0.2)'});
  var textLabel = timeLayer.append('text')
    .attr({
      x:0,
      y: -8,
      'text-anchor': 'start',
      'font-size': 64,
      'opacity': 0.0,
      fill: '#000',
      stroke: 'none'
    }).text('');
  timeLayer.selectAll('g').remove();
  var graphLayer = timeLayer.append('g')
    .attr('transform', 'translate('+padding.left+','+padding.top+')');
  graphLayer.selectAll('line')
    .data(data).enter().append('line')
    .style({stroke: function(d) {return d.color;}, fill: 'none', 'stroke-width': 1})
    .attr({x1: function(d){return graphXScale(d.time);},
           x2: function(d){return graphXScale(d.time);},
           y1: graphHeight,
           y2: function(d){return 0;},
           opacity: 0.4
    });
  var indicator = graphLayer.append('rect')
    .attr({
      x: -4,
      y: -8,
      width: 8,
      height: graphHeight + 16,
      fill: 'none',
      stroke: '#000',
      'stroke-width': 3,
      opacity: 0.0
    });
  indicator.moveTo = function(t){
    indicator.attr('x', graphXScale(t) - 8);
  };
  graphLayer.append('rect')
    .attr({
      x: -padding.left,
      y: -padding.top,
      width: panelWidth,
      height: panelHeight
    })
    .style({fill: 'rgba(0,0,0,0)', stroke: 'none'})
    .on('click', function() {
      d3.event.preventDefault();
      d3.event.stopPropagation();
      startAnim(graphXScale.invert(
        Math.min(
          Math.max(
            0,
            getMouseX(d3.event) - margin.left - padding.left
          ),
          graphWidth
        )
      ), (timeScale.domain()[1].getTime() - timeScale.domain()[0].getTime())/30000);
    }).call(drag);

  var updatePosition = function(d)
  {
    d.pos = map.projectPoint(d.latitude, d.longitude);
    d3.select(this).attr( {cx: d.pos.x, cy: d.pos.y } );
  }

  var reset = function()
  {
    var bounds = map.getBounds();
    var topLeft = map.projectPoint(bounds.getNorthWest());
    var bottomRight = map.projectPoint(bounds.getSouthEast());

    svgLayer.attr("width", bottomRight.x - topLeft.x)
      .attr("height", bottomRight.y - topLeft.y)
      .style("left", topLeft.x + "px")
      .style("top", topLeft.y + "px");
    graphLayer.selectAll('line').attr('opacity', function(d) {
      return (bounds.getWest() <= d.longitude && d.longitude <= bounds.getEast() &&
             bounds.getSouth() <= d.latitude && d.latitude <= bounds.getNorth())? 0.4: 0;
    });
    plotLayer.attr('transform', 'translate('+ -topLeft.x + ',' + -topLeft.y + ')');
    plotLayer.selectAll('circle').each(updatePosition);
  }

  plotLayer.selectAll('circle').remove();
  plotLayer.selectAll('circle').data(data).enter().append('circle')
    .attr({opacity: 0.75, r: 4, fill: function(d) {return d.color;}, stroke: 'rgba(255,255,255,0.1)', 'stroke-width': 3})
    .each(updatePosition);
  map.on('move', reset);
}
<commit_msg>change animation speed<commit_after>//# require=d3,leaflet

function update(data) {
  tick = null;
  show(data.toList({ typed: false }));
}

/**
 * Created by osoken on 2016/05/16.
 */

// map handler
!(function(d3,L)
{
  var map = {};
  var tracking = true;
  var zoom = 2;
  var mapLayer = null;
  var svgLayer = null;
  var pathLayer = null;
  var plotLayer = null;
  var infoLayer = null;
  var selection = null;
  var margin = 100;

  map.init = function(s)
  {

    selection = s;
    selection.style('height', root.clientHeight+'px');
    selection.style('width', root.clientWidth+'px');
    var point = [0, 0];
    mapLayer = L.map(selection.attr('id')).setView(point, zoom);

    var tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
      attribution : '© OpenStreetMap contributors'
    }).addTo(mapLayer);

    svgLayer = d3.select(mapLayer.getPanes().overlayPane).append("svg");

    plotLayer = svgLayer.append('g');
    timeLayer = svgLayer.append('g');
    mapLayer.on("viewreset", map.reset);
    d3.rebind(map, mapLayer, 'on');
    map.reset();
  }

  map.projectPoint = function(lat, lng)
  {
    if (lng===void 0)
    {
      return mapLayer.latLngToLayerPoint(lat);
    }
    return mapLayer.latLngToLayerPoint(new L.LatLng(lat, lng));
  }
  map.invertPoint = function(x, y)
  {
    if (y===void 0)
    {
      return mapLayer.layerPointToLatLng(x);
    }
    return mapLayer.layerPointToLatLng(new L.point(x,y));
  }
  map.getBounds = function() {
    return mapLayer.getBounds();
  }
  map.svg = function()
  {
    return svgLayer;
  }
  map.plotLayer = function()
  {
    return plotLayer;
  }
  map.timeLayer = function()
  {
    return timeLayer;
  }
  map.bound = function()
  {
    var bounds = plotLayer.node().getBBox();

    return {x:bounds.x-margin,y:bounds.y-margin,width:bounds.width+2*margin,height:bounds.height+2*margin};
  }
  map.reset = function()
  {
    var bounds = map.getBounds();
    var topLeft = map.projectPoint(bounds.getNorthWest());
    var bottomRight = map.projectPoint(bounds.getSouthEast());

    svgLayer.attr("width", bottomRight.x - topLeft.x)
      .attr("height", bottomRight.y - topLeft.y)
      .style("left", topLeft.x + "px")
      .style("top", topLeft.y + "px");
    timeLayer.selectAll('line').attr('opacity', function(d) {
      return (bounds.getWest() <= d.longitude && d.longitude <= bounds.getEast() &&
             bounds.getSouth() <= d.latitude && d.latitude <= bounds.getNorth())? 1.0: 0.08;
    });
    plotLayer.attr('transform', 'translate('+ -topLeft.x + ',' + -topLeft.y + ')');
  }
  this.map = map;
}(d3,L));

map.init(d3.select(root).append('div').attr('id','map-container'))
var tick = null;

function show(data)
{
  if (data.length == 0)
  {
    return;
  }

  var width = root.clientWidth;
  var height = root.clientHeight;

  var margin = {left: 20, bottom: 60, top: 0, right: 20};
  var padding = {left: 10, bottom: 20, top: 10, right: 10};

  var panelHeight = 40;
  var panelWidth = width - margin.left - margin.right;
  var graphHeight = panelHeight - padding.left - padding.right;
  var graphWidth = panelWidth - padding.top - padding.bottom;

  var timeFormat = d3.time.format('%Y-%m-%dT%H:%M:%S.%LZ');
  var timeDispFormat = d3.time.format('%Y/%m/%d %H:%M:%S');

  var timeDispFunc = function(d) {
    return timeDispFormat(d.time);
  }

  var timeFormat = d3.time.format('%Y-%m-%dT%H:%M:%S.%LZ');
  var timeDispFormat = d3.time.format('%Y/%m/%d(%a) %H:%M:%S');

  var timeDispFunc = function(d) {
    return timeDispFormat(d.time);
  }

  var colored = function(lng) {
    return d3.hsl((lng<0)?(360+lng):lng, 1.0, 0.5);
  }

  var timeScale = d3.time.scale();
  var graphXScale = d3.time.scale().range([0, graphWidth]);
  var graphYScale = d3.scale.linear().range([0, graphHeight]);

  var drag = d3.behavior.drag();

  var getMouseX = function(event) {
    if (event.offsetX != null) {
      getMouseX = function(event) {return event.offsetX;};
      return event.offsetX;
    }
    if (event.layerX != null) {
      getMouseX = function(event) {return event.layerX;};
      return event.layerX;
    }
    getMouseX = function(event) {return event.x;}
    return event.x;
  }

  drag.on('dragstart', function() {
    d3.event.sourceEvent.stopPropagation();
  }).on('dragend', function() {
    d3.event.sourceEvent.stopPropagation();
  }).on('drag', function() {
    d3.event.sourceEvent.stopPropagation();
  });

  var tick = null;

  data.forEach(function(d) {
    d.time = timeFormat.parse(d.time);
    d.latitude = +d.latitude;
    d.longitude = +d.longitude;
    d.color = colored(d.longitude);
  });

  timeScale.domain(d3.extent(data, function(d){return d.time;}));
  graphXScale.domain(d3.extent(data, function(d){return d.time;}));
  graphYScale.domain([0, 1]);

  var svgLayer = map.svg();
  var plotLayer = map.plotLayer();
  var uiHeight = 100;
  var timeLayer = map.timeLayer().attr('transform', 'translate('+margin.left+','+(height - margin.bottom - panelHeight)+')');

  var showAll = null;

  var startAnim = function(t0, dt) {
    if (showAll != null) {
      clearTimeout(showAll);
      showAll = null;
    }
    if (tick != null) {
      tick = null;
    }
    plotLayer.selectAll('circle').transition().duration(0).attr('opacity', 0.0);
    var t1 = timeScale.domain()[1];
    var tc = t0;
    textLabel.text(timeDispFormat(tc))
      .transition().duration(0)
      .attr({'opacity': 0.8});
    indicator.transition().duration(0).attr('opacity', 0.8);
    var lastTime = new Date().getTime();
    tick = function() {
      if ( t1 < tc ) {
        tick = null;
        if (showAll != null) {
          clearTimeout(showAll);
          showAll = null;
        }
        showAll = setTimeout(function() {
          textLabel.transition().duration(0).attr('opasity', 0.0).text('');
          plotLayer.selectAll('circle').transition().duration(2000)
            .attr('opacity', 0.8);
          showAll = null;
          indicator.transition().attr('opacity', 0.0);
        }, 2000);
        return;
      }
      indicator.moveTo(tc);
      textLabel.text(timeDispFormat(tc));
      var currentTime = new Date().getTime();
      delta = (currentTime - lastTime) * dt;
      plotLayer.selectAll('circle').filter(function(d) {
        return tc < d.time && (new Date(tc.getTime()+delta) >= d.time);
      }).attr('opacity', 0.8).transition().delay(1000).attr('opacity', 0.0);
      tc = new Date(tc.getTime() + delta);
      lastTime = currentTime;
      setTimeout(tick, 10);
    }
    tick();
  };

  timeLayer.selectAll('rect').remove();
  timeLayer.append('rect').attr({x:0, y:0, width: panelWidth, height: panelHeight})
    .style({fill: 'rgba(255,255,255,0.2)'});
  var textLabel = timeLayer.append('text')
    .attr({
      x:0,
      y: -8,
      'text-anchor': 'start',
      'font-size': 64,
      'opacity': 0.0,
      fill: '#000',
      stroke: 'none'
    }).text('');
  timeLayer.selectAll('g').remove();
  var graphLayer = timeLayer.append('g')
    .attr('transform', 'translate('+padding.left+','+padding.top+')');
  graphLayer.selectAll('line')
    .data(data).enter().append('line')
    .style({stroke: function(d) {return d.color;}, fill: 'none', 'stroke-width': 1})
    .attr({x1: function(d){return graphXScale(d.time);},
           x2: function(d){return graphXScale(d.time);},
           y1: graphHeight,
           y2: function(d){return 0;},
           opacity: 0.4
    });
  var indicator = graphLayer.append('rect')
    .attr({
      x: -4,
      y: -8,
      width: 8,
      height: graphHeight + 16,
      fill: 'none',
      stroke: '#000',
      'stroke-width': 3,
      opacity: 0.0
    });
  indicator.moveTo = function(t){
    indicator.attr('x', graphXScale(t) - 8);
  };
  graphLayer.append('rect')
    .attr({
      x: -padding.left,
      y: -padding.top,
      width: panelWidth,
      height: panelHeight
    })
    .style({fill: 'rgba(0,0,0,0)', stroke: 'none'})
    .on('click', function() {
      d3.event.preventDefault();
      d3.event.stopPropagation();
      startAnim(graphXScale.invert(
        Math.min(
          Math.max(
            0,
            getMouseX(d3.event) - margin.left - padding.left
          ),
          graphWidth
        )
      ), (timeScale.domain()[1].getTime() - timeScale.domain()[0].getTime())/60000);
    }).call(drag);

  var updatePosition = function(d)
  {
    d.pos = map.projectPoint(d.latitude, d.longitude);
    d3.select(this).attr( {cx: d.pos.x, cy: d.pos.y } );
  }

  var reset = function()
  {
    var bounds = map.getBounds();
    var topLeft = map.projectPoint(bounds.getNorthWest());
    var bottomRight = map.projectPoint(bounds.getSouthEast());

    svgLayer.attr("width", bottomRight.x - topLeft.x)
      .attr("height", bottomRight.y - topLeft.y)
      .style("left", topLeft.x + "px")
      .style("top", topLeft.y + "px");
    graphLayer.selectAll('line').attr('opacity', function(d) {
      return (bounds.getWest() <= d.longitude && d.longitude <= bounds.getEast() &&
             bounds.getSouth() <= d.latitude && d.latitude <= bounds.getNorth())? 0.4: 0;
    });
    plotLayer.attr('transform', 'translate('+ -topLeft.x + ',' + -topLeft.y + ')');
    plotLayer.selectAll('circle').each(updatePosition);
  }

  plotLayer.selectAll('circle').remove();
  plotLayer.selectAll('circle').data(data).enter().append('circle')
    .attr({opacity: 0.75, r: 4, fill: function(d) {return d.color;}, stroke: 'rgba(255,255,255,0.1)', 'stroke-width': 3})
    .each(updatePosition);
  map.on('move', reset);
}
<|endoftext|>


<commit_before>import React from "react";
import Home from "./Home";
import "./normalize.css";
import "./main.css";

React.render(Home(), document.getElementById("react-root"));
<commit_msg>add CSS<commit_after>import "./normalize.css";
import "./main.css";
import "./components/AboutSite/AboutSite.css";
import "./components/AppBar/AppBar.css";
import "./components/Arthor/Arthor.css";
import "./components/Article/Article.css";
import "./components/Author/Author.css";
import "./components/Columns/Columns.css";
import "./components/Comments/Comments.css";
import "./components/List/List.css";
import "./components/Social/Social.css";
import "./components/Tabs/Tabs.css";
import "./components/Tags/Tags.css";
<|endoftext|>


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

kunstmaanbundles.pagepartEditor = function (window) {

    var events = {
        add: [],
        edit: [],
        delete: []
    };

    var init, addPagePart, editPagePart, deletePagePart, movePagePartUp, movePagePartDown, subscribeToEvent, unSubscribeToEvent, executeEvent, reInit, reOrder;

    init = function () {
        var $body = $('body');

        // Add
        $body.on('change', '.js-add-pp-select', function () {
            addPagePart($(this));
        });

        // Edit
        $body.on('click', '.js-edit-pp-btn', function () {
            editPagePart($(this));
        });

        // Del
        $body.on('click', '.js-delete-pp-btn', function () {
            deletePagePart($(this));
        });

        // Move up
        $body.on('click', '.js-move-up-pp-btn', function () {
            movePagePartUp($(this));
        });

        // Move down
        $body.on('click', '.js-move-down-pp-btn', function () {
            movePagePartDown($(this));
        });

        $body.on('click', '.js-resize-pp-view-btn', function () {
            resizePagePartView($(this));
        });

        $body.on('click', '.js-resize-all-pp', function (e) {
            resizeAllRegionPp($(this));

            e.preventDefault();
        });
    };

    // Add
    addPagePart = function ($select) {
        if (!$select.val()) {
            return false;
        }

        var $targetContainer = $select.closest('.js-pp-container'),
            requestUrl = $select.data('url');

        // Get necessary data
        var pageClassName = $targetContainer.data('pageclassname'),
            pageId = $targetContainer.data('pageid'),
            context = $targetContainer.data('context'),
            ppType = $select.val();

        // Set Loading
        kunstmaanbundles.appLoading.addLoading();

        // Ajax Request
        $.ajax({
            url: requestUrl,
            data: {
                'pageclassname': pageClassName,
                'pageid': pageId,
                'context': context,
                'type': ppType
            },
            async: true,
            success: function (data) {
                // Add PP
                var firstSelect = $select.hasClass('js-add-pp-select--first');
                var elem;
                if (firstSelect) {
                    elem = $('#parts-' + context).prepend(data);
                } else {
                    elem = $select.closest('.js-sortable-item').after(data);
                }

                // Create a temporary node of the new PP
                var $temp = $('<div>');
                $temp.append(data);

                var uniqueModules = [];

                // Check if some javascript needs to be reinitialised for this PP
                $temp.find('*[data-reinit-js]').each(function () {
                    // Get modules from data attribute
                    var modules = $(this).data('reinit-js');

                    if (modules) {
                        for (var i = 0; i < modules.length; i++) {
                            // Check if there really is a module with the given name and it if has a public reInit function
                            if (typeof kunstmaanbundles[modules[i]] === 'object' && typeof kunstmaanbundles[modules[i]].reInit === 'function') {
                                // prevent duplicate modules
                                if ($.inArray(modules[i], uniqueModules) === -1) {
                                    uniqueModules.push(modules[i]);
                                }
                            }
                        }
                    }
                });

                for (var i = 0; i < uniqueModules.length; i++) {
                    kunstmaanbundles[uniqueModules[i]].reInit();
                }

                // Remove Loading
                kunstmaanbundles.appLoading.removeLoading();

                // Enable leave-page modal
                kunstmaanbundles.checkIfEdited.edited();

                // Reinit custom selects
                kunstmaanbundles.advancedSelect.init();

                // Reset ajax-modals
                kunstmaanbundles.ajaxModal.resetAjaxModals();

                executeEvent('add')
            }
        });

        // Reset select
        $select.val('');
    };

    // Edit
    editPagePart = function ($btn) {
        var $targetId = $btn.data('target-id');

        // Enable "leave page" modal
        kunstmaanbundles.checkIfEdited.edited();

        // Show edit view and hide preview
        $('#' + $targetId + '-edit-view').removeClass('pp__view__block--hidden');
        $('#' + $targetId + '-preview-view').addClass('pp__view__block--hidden');

        // Add edit active class
        var $container = $('#pp-' + $targetId);
        $container.addClass('pp--edit-active');

        // Reinit custom selects
        kunstmaanbundles.advancedSelect.init();

        // Set Active Edit
        window.activeEdit = $targetId;

        executeEvent('edit', $container);
    };

    // Delete
    deletePagePart = function ($btn) {
        var $targetId = $btn.data('target-id'),
            $container = $('#' + $targetId + '-pp-container');

        // Enable "leave page" modal
        kunstmaanbundles.checkIfEdited.edited();

        // Slideup and empty container
        $container.velocity('slideUp', {
            duration: 300
        });

        $container.empty();

        // Check is-deleted checkbox
        $('#' + $targetId + '-is-deleted').prop('checked', true);

        // Hide delete modal
        $('#delete-pagepart-modal-' + $targetId).modal('hide');
        $('body').removeClass('modal-open');
        executeEvent('delete', $container);
    };

    // Move up
    movePagePartUp = function ($btn) {
        var $targetId = $btn.data('target-id');

        var $currentPp = $btn.parents('#' + $targetId + '-pp-container');
        var $previousPp = $currentPp.prevAll('.sortable-item:first');

        // ReInit the modules. This is needed for a known bug in CKEDITOR. When moving a element with a ckeditor in
        // The DOM, the ckeditor needs to be reinitialized.
        reInit($currentPp);
        if ($previousPp.length) {
            $($previousPp).before($currentPp);
            // Update display order.
            reOrder($currentPp.parent());
            // Enable "leave page" modal
            kunstmaanbundles.checkIfEdited.edited();
        }

        $currentPp.velocity('scroll', {
            duration: 500,
            offset: -200,
            easing: 'ease-in-out'
        });

        // Set Active Edit
        window.activeEdit = $targetId;
    };

    // Move down
    movePagePartDown = function ($btn) {
        var $targetId = $btn.data('target-id');

        var $currentPp = $btn.parents('#' + $targetId + '-pp-container');
        var $nextPp = $currentPp.nextAll('.sortable-item:first');
        // ReInit the modules. This is needed for a known bug in CKEDITOR. When moving a element with a ckeditor in
        // The DOM, the ckeditor needs to be reinitialized.
        reInit($currentPp);
        if ($nextPp.length) {
            $($nextPp).after($currentPp);
            // Update display order.
            reOrder($currentPp.parent());
            // Enable "leave page" modal
            kunstmaanbundles.checkIfEdited.edited();
        }

        $currentPp.velocity('scroll', {
            duration: 500,
            offset: -200,
            easing: 'ease-in-out'
        });

        // Set Active Edit
        window.activeEdit = $targetId;
    };

    //Resize
    resizePagePartView = function ($btn) {
        var $targetId = $btn.data('target-id');

        var $parentEl = $("#" + $targetId);
        var $target = $('#' + $targetId + '-preview-view');
        var $resizeTarget = $target.parent();

        $resizeTarget.toggleClass('action--maximize');
        $btn.toggleClass('pp__actions__action--resize-max');

        if ($resizeTarget.hasClass('action--maximize')) {
            $btn.find('i').removeClass('fa-minus').addClass('fa-plus');
            $resizeTarget.velocity({"height": "7rem"}, {duration: 400, easing: 'ease-in-out'});
        } else {
            $btn.find('i').removeClass('fa-plus').addClass('fa-minus');
            $resizeTarget.velocity({"height": "100%"}, {duration: 400, easing: 'ease-in-out'});
        }

    };

    resizeAllRegionPp = function ($btn) {
        var $target = $btn.data('target');

        var $parentEl = $("#" + $target);
        var $resizeTargets = $parentEl.find('.pp__view');

        if($btn.hasClass('region__actions__min')) {
            $parentEl.velocity({"height": "11.8rem"}, {duration: 400, easing: 'ease-in-out'});
            $parentEl.addClass('action--maximize');
        }else if($btn.hasClass('region__actions__max')) {
            $parentEl.velocity({"height": "100%"}, {duration: 400, easing: 'ease-in-out'});
            $parentEl.removeClass('action--maximize');
        }
    };

    // subsribe to an event.
    subscribeToEvent = function (eventName, callBack) {
        if (!events.hasOwnProperty(eventName)) {
            throw new Error("PagePartEditor: I cannot let you subscribe to the unknown event named: " + eventName);
        }
        events[eventName].push(callBack);
    };
    unSubscribeToEvent = function (eventName, callback) {
        if (!events.hasOwnProperty(eventName)) {
            throw new Error("PagePartEditor: I cannot let you unSubscribe to the unknown event named: " + eventName);
        }
        events = events.filter(function (cb) {
            return cb !== callback
        });
    };
    executeEvent = function (eventName, target) {
        events[eventName].forEach(function (cb) {
            cb({target: target})
        })
    };
    reInit = function($el) {
        $el.find('*[data-reinit-js]').each(function() {
            // Get modules from data attribute
            var modules = $(this).data('reinit-js');

            if (modules) {
                for (var i = 0; i < modules.length; i++) {
                    // Check if there really is a module with the given name and it if has a public reInit function
                    if (typeof kunstmaanbundles[modules[i]] === 'object' && typeof kunstmaanbundles[modules[i]].reInit === 'function') {
                        kunstmaanbundles[modules[i]].reInit();
                    }
                }
            }
        });
    };
    reOrder = function($container) {
        var i = 0;
        $container.children('.sortable-item:visible').each(function() {
            var $sortEl = $(this).find('#' + $(this).data('sortkey'));
            $sortEl.val(i++);
        });
    };
    return {
        init: init,
        subscribeToEvent: subscribeToEvent,
        unSubscribeToEvent: unSubscribeToEvent
    };

}(window);
<commit_msg>Prevent duplicate reinits<commit_after>var kunstmaanbundles = kunstmaanbundles || {};

kunstmaanbundles.pagepartEditor = function (window) {

    var events = {
        add: [],
        edit: [],
        delete: []
    };

    var init, addPagePart, editPagePart, deletePagePart, movePagePartUp, movePagePartDown, subscribeToEvent, unSubscribeToEvent, executeEvent, reInit, reOrder;

    init = function () {
        var $body = $('body');

        // Add
        $body.on('change', '.js-add-pp-select', function () {
            addPagePart($(this));
        });

        // Edit
        $body.on('click', '.js-edit-pp-btn', function () {
            editPagePart($(this));
        });

        // Del
        $body.on('click', '.js-delete-pp-btn', function () {
            deletePagePart($(this));
        });

        // Move up
        $body.on('click', '.js-move-up-pp-btn', function () {
            movePagePartUp($(this));
        });

        // Move down
        $body.on('click', '.js-move-down-pp-btn', function () {
            movePagePartDown($(this));
        });

        $body.on('click', '.js-resize-pp-view-btn', function () {
            resizePagePartView($(this));
        });

        $body.on('click', '.js-resize-all-pp', function (e) {
            resizeAllRegionPp($(this));

            e.preventDefault();
        });
    };

    // Add
    addPagePart = function ($select) {
        if (!$select.val()) {
            return false;
        }

        var $targetContainer = $select.closest('.js-pp-container'),
            requestUrl = $select.data('url');

        // Get necessary data
        var pageClassName = $targetContainer.data('pageclassname'),
            pageId = $targetContainer.data('pageid'),
            context = $targetContainer.data('context'),
            ppType = $select.val();

        // Set Loading
        kunstmaanbundles.appLoading.addLoading();

        // Ajax Request
        $.ajax({
            url: requestUrl,
            data: {
                'pageclassname': pageClassName,
                'pageid': pageId,
                'context': context,
                'type': ppType
            },
            async: true,
            success: function (data) {
                // Add PP
                var firstSelect = $select.hasClass('js-add-pp-select--first');
                var elem;
                if (firstSelect) {
                    elem = $('#parts-' + context).prepend(data);
                } else {
                    elem = $select.closest('.js-sortable-item').after(data);
                }

                // Create a temporary node of the new PP
                var $temp = $('<div>');
                $temp.append(data);

                // Check if some javascript needs to be reinitialised for this PP
                reInit($temp);

                // Remove Loading
                kunstmaanbundles.appLoading.removeLoading();

                // Enable leave-page modal
                kunstmaanbundles.checkIfEdited.edited();

                // Reinit custom selects
                kunstmaanbundles.advancedSelect.init();

                // Reset ajax-modals
                kunstmaanbundles.ajaxModal.resetAjaxModals();

                executeEvent('add')
            }
        });

        // Reset select
        $select.val('');
    };

    // Edit
    editPagePart = function ($btn) {
        var $targetId = $btn.data('target-id');

        // Enable "leave page" modal
        kunstmaanbundles.checkIfEdited.edited();

        // Show edit view and hide preview
        $('#' + $targetId + '-edit-view').removeClass('pp__view__block--hidden');
        $('#' + $targetId + '-preview-view').addClass('pp__view__block--hidden');

        // Add edit active class
        var $container = $('#pp-' + $targetId);
        $container.addClass('pp--edit-active');

        // Reinit custom selects
        kunstmaanbundles.advancedSelect.init();

        // Set Active Edit
        window.activeEdit = $targetId;

        executeEvent('edit', $container);
    };

    // Delete
    deletePagePart = function ($btn) {
        var $targetId = $btn.data('target-id'),
            $container = $('#' + $targetId + '-pp-container');

        // Enable "leave page" modal
        kunstmaanbundles.checkIfEdited.edited();

        // Slideup and empty container
        $container.velocity('slideUp', {
            duration: 300
        });

        $container.empty();

        // Check is-deleted checkbox
        $('#' + $targetId + '-is-deleted').prop('checked', true);

        // Hide delete modal
        $('#delete-pagepart-modal-' + $targetId).modal('hide');
        $('body').removeClass('modal-open');
        executeEvent('delete', $container);
    };

    // Move up
    movePagePartUp = function ($btn) {
        var $targetId = $btn.data('target-id');

        var $currentPp = $btn.parents('#' + $targetId + '-pp-container');
        var $previousPp = $currentPp.prevAll('.sortable-item:first');

        // ReInit the modules. This is needed for a known bug in CKEDITOR. When moving a element with a ckeditor in
        // The DOM, the ckeditor needs to be reinitialized.
        reInit($currentPp);
        if ($previousPp.length) {
            $($previousPp).before($currentPp);
            // Update display order.
            reOrder($currentPp.parent());
            // Enable "leave page" modal
            kunstmaanbundles.checkIfEdited.edited();
        }

        $currentPp.velocity('scroll', {
            duration: 500,
            offset: -200,
            easing: 'ease-in-out'
        });

        // Set Active Edit
        window.activeEdit = $targetId;
    };

    // Move down
    movePagePartDown = function ($btn) {
        var $targetId = $btn.data('target-id');

        var $currentPp = $btn.parents('#' + $targetId + '-pp-container');
        var $nextPp = $currentPp.nextAll('.sortable-item:first');
        // ReInit the modules. This is needed for a known bug in CKEDITOR. When moving a element with a ckeditor in
        // The DOM, the ckeditor needs to be reinitialized.
        reInit($currentPp);
        if ($nextPp.length) {
            $($nextPp).after($currentPp);
            // Update display order.
            reOrder($currentPp.parent());
            // Enable "leave page" modal
            kunstmaanbundles.checkIfEdited.edited();
        }

        $currentPp.velocity('scroll', {
            duration: 500,
            offset: -200,
            easing: 'ease-in-out'
        });

        // Set Active Edit
        window.activeEdit = $targetId;
    };

    //Resize
    resizePagePartView = function ($btn) {
        var $targetId = $btn.data('target-id');

        var $parentEl = $("#" + $targetId);
        var $target = $('#' + $targetId + '-preview-view');
        var $resizeTarget = $target.parent();

        $resizeTarget.toggleClass('action--maximize');
        $btn.toggleClass('pp__actions__action--resize-max');

        if ($resizeTarget.hasClass('action--maximize')) {
            $btn.find('i').removeClass('fa-minus').addClass('fa-plus');
            $resizeTarget.velocity({"height": "7rem"}, {duration: 400, easing: 'ease-in-out'});
        } else {
            $btn.find('i').removeClass('fa-plus').addClass('fa-minus');
            $resizeTarget.velocity({"height": "100%"}, {duration: 400, easing: 'ease-in-out'});
        }

    };

    resizeAllRegionPp = function ($btn) {
        var $target = $btn.data('target');

        var $parentEl = $("#" + $target);
        var $resizeTargets = $parentEl.find('.pp__view');

        if($btn.hasClass('region__actions__min')) {
            $parentEl.velocity({"height": "11.8rem"}, {duration: 400, easing: 'ease-in-out'});
            $parentEl.addClass('action--maximize');
        }else if($btn.hasClass('region__actions__max')) {
            $parentEl.velocity({"height": "100%"}, {duration: 400, easing: 'ease-in-out'});
            $parentEl.removeClass('action--maximize');
        }
    };

    // subsribe to an event.
    subscribeToEvent = function (eventName, callBack) {
        if (!events.hasOwnProperty(eventName)) {
            throw new Error("PagePartEditor: I cannot let you subscribe to the unknown event named: " + eventName);
        }
        events[eventName].push(callBack);
    };
    unSubscribeToEvent = function (eventName, callback) {
        if (!events.hasOwnProperty(eventName)) {
            throw new Error("PagePartEditor: I cannot let you unSubscribe to the unknown event named: " + eventName);
        }
        events = events.filter(function (cb) {
            return cb !== callback
        });
    };
    executeEvent = function (eventName, target) {
        events[eventName].forEach(function (cb) {
            cb({target: target})
        })
    };
    reInit = function($el) {
        var uniqueModules = [];

        $el.find('*[data-reinit-js]').each(function() {
            // Get modules from data attribute
            var modules = $(this).data('reinit-js');

            if (modules) {
                for (var i = 0; i < modules.length; i++) {
                    // Check if there really is a module with the given name and it if has a public reInit function
                    if (typeof kunstmaanbundles[modules[i]] === 'object' && typeof kunstmaanbundles[modules[i]].reInit === 'function') {
                        // prevent duplicate modules
                        if ($.inArray(modules[i], uniqueModules) === -1) {
                            uniqueModules.push(modules[i]);
                            kunstmaanbundles[modules[i]].reInit();
                        }
                    }
                }
            }
        });
    };
    reOrder = function($container) {
        var i = 0;
        $container.children('.sortable-item:visible').each(function() {
            var $sortEl = $(this).find('#' + $(this).data('sortkey'));
            $sortEl.val(i++);
        });
    };
    return {
        init: init,
        subscribeToEvent: subscribeToEvent,
        unSubscribeToEvent: unSubscribeToEvent
    };

}(window);
<|endoftext|>


<commit_before>const Issue = require('../issues/issue')

function createIssueForEmpty(file) {
  const size = typeof window !== 'undefined' ? file.size : file.stats.size
  return size <= 0 && new Issue({ code: 99, file: file })
}
function clearNonIssues(x) {
  return x instanceof Issue
}

/**
 * validateMisc
 *
 * takes a list of files and returns an issue for each file
 */
module.exports = function validateMisc(miscFiles) {
  return Promise.resolve(
    miscFiles.map(createIssueForEmpty).filter(clearNonIssues),
  )
}
<commit_msg>make 0KB admissible exceptions for certain CTF files<commit_after>const Issue = require('../issues/issue')

function createIssueForEmpty(file) {
  const size = typeof window !== 'undefined' ? file.size : file.stats.size
  var failSizeRequirement = size <= 0
  // Exception misc files that can be valid although size==0
  // E.g., BadChannels and bad.segments in CTF data format (MEG modality)
  const exceptionMiscs = ['BadChannels', 'bad.segments']
  if (exceptionMiscs.indexOf(file.name) > -1) {
    failSizeRequirement = false
  }

  return failSizeRequirement && new Issue({ code: 99, file: file })
}
function clearNonIssues(x) {
  return x instanceof Issue
}

/**
 * validateMisc
 *
 * takes a list of files and returns an issue for each file
 */
module.exports = function validateMisc(miscFiles) {
  return Promise.resolve(
    miscFiles.map(createIssueForEmpty).filter(clearNonIssues),
  )
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

var MaxCDN = require('../');
var maxcdn = new MaxCDN(process.env.ALIAS, process.env.KEY, process.env.SECRET);

/***
 * Get account information.
 */
maxcdn.get('account.json', function(err, results) {
    if (err) {
        // error handling
        console.trace(err);
    } else {
        // print results
        console.log('account.json\n%s\n',results);
    }
});

/***
 * Get account address information.
 */
maxcdn.get('account.json/address', function(err, results) {
    if (err) {
        // error handling
        console.trace(err);
    } else {
        // print results
        console.log('account.json/address\n%s\n',results);
    }
});

maxcdn.get('reports/stats.json/hourly', function(err, results) {
    if (err) {
        // error handling
        console.trace(err);
    } else {
        // print results
        console.log('reports/stats.json/hourly summary\n%s\n',
                        results.data.summart);
    }
});

// vim: ft=javascript ai sw=4 sts=4 et:
<commit_msg>Fixing some example errors.<commit_after>#!/usr/bin/env node

var MaxCDN = require('../');
var maxcdn = new MaxCDN(process.env.ALIAS, process.env.KEY, process.env.SECRET);

/***
 * Get account information.
 */
maxcdn.get('account.json', function(err, results) {
    console.log('GET account.json')
    if (err) {
        // error handling
        console.trace(err);
    } else {
        // print results
        console.dir(results);
    }
});

/***
 * Get account address information.
 */
maxcdn.get('account.json/address', function(err, results) {
    console.log('account.json/address');
    if (err) {
        // error handling
        console.trace(err);
    } else {
        // print results
        console.dir(results);
    }
});

maxcdn.get('reports/stats.json/hourly', function(err, results) {
    console.log('reports/stats.json/hourly summary');
    if (err) {
        // error handling
        console.trace(err);
    } else {
        // print results
        console.dir(results.data.summary);
    }
});

// vim: ft=javascript ai sw=4 sts=4 et:
<|endoftext|>


<commit_before>define(['src/util/util', './printServerFactory', './printProcessors'], function (
  Util,
  printServerFactory,
  processors
) {
  class Printer {
    constructor(printer, printServer, opts) {
      this.url = String(printServer.url);
      this.id = String(printer.id);
      this.printServer = printServerFactory(printServer, opts);
    }

    async print(printFormat, data) {
      if (!processors[printFormat.processor]) {
        throw new Error('processor does not exist');
      }
      data = processData(printFormat, data);
      const printData = await processors[String(printFormat.processor)].call(
        null,
        printFormat,
        data
      );
      if (printData === null) return null;
      return this.printServer.print(this.id, printData);
    }
  }

  function processData(printFormat, data) {
    switch (printFormat.type) {
      case 'sample': {
        const result = {};
        if (data.$content && data.$content) {
          result.entry = data;
          result.uuidShort = data._id.substring(0, 12);
          result.b64Short = Util.hexToBase64(result.uuidShort);
          result.id = data.$id.join(' ');
          if (data.$content.general) {
            if (data.$content.general.description) {
              result.line1 = data.$content.general.description.substring(0, 60);
              result.line2 = data.$content.general.description.substring(
                60,
                120
              );
            } else {
              result.line1 = '';
              result.line2 = '';
            }
            result.molfile = String(data.$content.general.molfile);
          }
        }
        if (data.molfile) {
          Object.assign(result, data, {
            molfile: String(data.molfile)
          });
        }
        return result;
      }
      case 'location':
      default:
        return data;
    }
  }

  Printer.processData = processData;

  return Printer;
});
<commit_msg>expose getPrintData Instance<commit_after>define(['src/util/util', './printServerFactory', './printProcessors'], function (
  Util,
  printServerFactory,
  processors
) {
  class Printer {
    constructor(printer, printServer, opts) {
      this.url = String(printServer.url);
      this.id = String(printer.id);
      this.printServer = printServerFactory(printServer, opts);
    }

    async print(printFormat, data) {
      const printData = await getPrintData(printFormat, data);
      if (printData === null) return null;
      return this.printServer.print(this.id, printData);
    }
  }

  async function getPrintData(printFormat, data) {
    if (!processors[printFormat.processor]) {
      throw new Error('processor does not exist');
    }
    data = processData(printFormat, data);
    return processors[String(printFormat.processor)].call(
      null,
      printFormat,
      data
    );
  }

  function processData(printFormat, data) {
    switch (printFormat.type) {
      case 'sample': {
        const result = {};
        if (data.$content && data.$content) {
          result.entry = data;
          result.uuidShort = data._id.substring(0, 12);
          result.b64Short = Util.hexToBase64(result.uuidShort);
          result.id = data.$id.join(' ');
          if (data.$content.general) {
            if (data.$content.general.description) {
              result.line1 = data.$content.general.description.substring(0, 60);
              result.line2 = data.$content.general.description.substring(
                60,
                120
              );
            } else {
              result.line1 = '';
              result.line2 = '';
            }
            result.molfile = String(data.$content.general.molfile);
          }
        }
        if (data.molfile) {
          Object.assign(result, data, {
            molfile: String(data.molfile)
          });
        }
        return result;
      }
      case 'location':
        return data;
      default:
        return data;
    }
  }

  Printer.processData = processData;
  Printer.getPrintData = getPrintData;

  return Printer;
});
<|endoftext|>


<commit_before>/*jshint node:true*/
/* global require, module */
var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');

module.exports = function(defaults) {
  var app = new EmberAddon(defaults, {
    // Add options here
  });

  /*
    This build file specifes the options for the dummy test app of this
    addon, located in `/tests/dummy`
    This build file does *not* influence how the addon or the app using it
    behave. You most likely want to be modifying `./index.js` or app's build file
  */

  return app.toTree();
};
<commit_msg>adds velocity options<commit_after>/*jshint node:true*/
/* global require, module */
var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');

module.exports = function(defaults) {
  var app = new EmberAddon(defaults, {
    velocityOptions: {
      enabled: true,
      ui: false
    }
  });

  /*
    This build file specifes the options for the dummy test app of this
    addon, located in `/tests/dummy`
    This build file does *not* influence how the addon or the app using it
    behave. You most likely want to be modifying `./index.js` or app's build file
  */

  return app.toTree();
};
<|endoftext|>


<commit_before>"use strict";
/**
 * Webpack frontend test (w/ coverage) configuration.
 */
var _ = require("lodash");
var testCfg = require("./webpack.config.test");

module.exports = _.merge({}, testCfg, {
  module: {
    preLoaders: [
      // Manually instrument client code for code coverage.
      // https://github.com/deepsweet/isparta-loader handles ES6 + normal JS.
      {
        test: /src\/.*\.jsx?$/,
        exclude: /(test|node_modules)\//,
        loader: "isparta?{ babel: { stage: 1 } }"
      }
    ]
  }
});
<commit_msg>Fix babel stage in coverage config<commit_after>"use strict";
/**
 * Webpack frontend test (w/ coverage) configuration.
 */
var _ = require("lodash");
var testCfg = require("./webpack.config.test");

module.exports = _.merge({}, testCfg, {
  module: {
    preLoaders: [
      // Manually instrument client code for code coverage.
      // https://github.com/deepsweet/isparta-loader handles ES6 + normal JS.
      {
        test: /src\/.*\.jsx?$/,
        exclude: /(test|node_modules)\//,
        loader: "isparta?{ babel: { stage: 0 } }"
      }
    ]
  }
});
<|endoftext|>


<commit_before>class ComposeError extends Error {
    constructor(message) {
        super();
        this.message = message;
    }

    toString() {
        return this.message;
    }
}

class Combinator extends Arrow {
    constructor(type, arrows) {
        super(type);
        this.arrows = arrows;
    }

    toString() {
        return this.constructor.name + "(" + this.arrows.map(a => a.toString()).join(", ") + ") :: " + this.type.toString();
    }

    isAsync() {
        return this.arrows.some(a => a.isAsync());
    }

    equals(that) {
        if (this.constructor === that.constructor) {
            return this.arrows.length === that.arrows.length && this.arrows.every((a, i) => a.equals(that.arrows[i]));
        }

        return false;
    }
}

class NamedArrow extends Combinator {
    constructor(name, a, args) {
        ensureArrow(a);

        super(_construct(() => {
            return a.type;
        }), [a]);

        this.name = format(name, (args || []).map(a => a.toString()));
    }

    toString() {
        return this.name + " :: " + this.arrows[0].type.toString();
    }

    call(x, p, k, h) {
        this.arrows[0].call(x, p, k, h);
    }

    isAsync() {
        return this.arrows[0].isAsync();
    }
}

class NoEmitCombinator extends Combinator {
    constructor(a) {
        ensureArrow(a);

        super(_construct(() => {
            return a.type;
        }), [a]);
    }

    toString() {
        return "noemit(" + this.arrows[0].toString() + ") :: " + this.type.toString();
    }

    call(x, p, k, h) {
        let quiet = new Progress(false);
        p.addCanceler(() => quiet.cancel());

        this.arrows[0].call(x, quiet, z => {
            p.advance();

            setTimeout(() => {
                k(z);
            }, 0);
        }, h);
    }

    isAsync() {
        return true;
    }
}

class SeqCombinator extends Combinator {
    constructor(arrows) {
        arrows = getNonNullArrows(arrows);

        super(_construct(() => {
            let sty = sanitizeTypes(arrows);

            try {
                let len = sty.length - 1;

                let arg = sty[0].arg;
                let out = sty[len].out;
                let ncs = new ConstraintSet([]);
                let err = sty[0].errors;

                sty.forEach((t, i) => {
                    ncs = ncs.concat(t.constraints);
                    err = err.concat(t.errors);

                    if (i != 0) {
                        ncs = ncs.add(new Constraint(sty[i - 1].out, t.arg));
                    }
                });

                return new ArrowType(arg, out, ncs, err);
            } catch (err) {
                let message;
                let location = getLocation(err.stack);

                if (location) {
                    message = "Unable to seq arrows at: " + location;
                } else {
                    message = "Unable to seq arrows";
                }

                throw new ComposeError(message + "\n\tInput => Seq(" + sty.join(", ") + ")\n\tError => " + err);
            }
        }), arrows);
    }

    toString() {
        return "seq(" + this.arrows.map(a => a.toString()).join(", ") + ") :: " + this.type.toString();
    }

    call(x, p, k, h) {
        const rec = (y, [head, ...tail]) => {
            if (head === undefined) {
                k(y);
            } else {
                head.call(y, p, z => rec(z, tail), h);
            }
        };

        rec(x, this.arrows);
    }
}

class AllCombinator extends Combinator {
    constructor(arrows) {
        arrows = getNonNullArrows(arrows);

        super(_construct(() => {
            let sty = sanitizeTypes(arrows);

            try {
                let arg = [];
                let out = [];
                let ncs = new ConstraintSet([]);
                let err = [];

                sty.forEach((t, i) => {
                    arg.push(t.arg);
                    out.push(t.out);

                    ncs = ncs.concat(t.constraints);
                    err = err.concat(t.errors);
                });

                return new ArrowType(new TupleType(arg), new TupleType(out), ncs, err);
            } catch (err) {
                let message;
                let location = getLocation(err.stack);

                if (location) {
                    message = "Unable to all arrows at: " + location;
                } else {
                    message = "Unable to all arrows";
                }

                throw new ComposeError(message + "\n\tInput => All(" + sty.join(", ") + ")\n\tError => " + err);
            }
        }), arrows);
    }

    toString() {
        return "all(" + this.arrows.map(a => a.toString()).join(", ") + ") :: " + this.type.toString();
    }

    call(x, p, k, h) {
        let numFinished = 0;
        let callResults = this.arrows.map(x => null);

        this.arrows.forEach((a, i) => {
            a.call(x[i], p, y => {
                callResults[i] = y;

                // Once results array is finished, continue
                if (++numFinished == this.arrows.length) {
                    k(callResults);
                }
            }, h);
        });
    }
}

class AnyCombinator extends Combinator {
    constructor(arrows) {
        arrows = getNonNullArrows(arrows);

        super(_construct(() => {
            let sty = sanitizeTypes(arrows);

            try {
                let arg = ParamType.fresh();
                let out = ParamType.fresh();
                let ncs = new ConstraintSet([]);
                let err = [];

                sty.forEach((t, i) => {
                    ncs = ncs.concat(t.constraints);
                    err = err.concat(t.errors);

                    ncs = ncs.add(new Constraint(arg, t.arg));
                    ncs = ncs.add(new Constraint(t.out, out));
                });

                return new ArrowType(arg, out, ncs, err);
            } catch (err) {
                let message;
                let location = getLocation(err.stack);

                if (location) {
                    message = "Unable to any arrows at: " + location;
                } else {
                    message = "Unable to any arrows";
                }

                throw new ComposeError(message + "\n\tInput => Any(" + sty.join(", ") + ")\n\tError => " + err);
            }
        }), arrows);
    }

    toString() {
        return "any(" + this.arrows.map(a => a.toString()).join(", ") + ") :: " + this.type.toString();
    }

    call(x, p, k, h) {
        // Note: This must be done at execution time instead of construction
        // time because a recursive arrow may present itself as falsely async.

        if (!this.arrows.every(a => a.isAsync())) {
            throw new Error("Any combinator requires asynchronous arrow arguments");
        }

        let progress = this.arrows.map(() => new Progress(true));

        // If combinator is canceled, cancel all children
        p.addCanceler(() => progress.forEach(p => p.cancel()));

        this.arrows.forEach((a, i) => {
            // When arrow[i] progresses, cancel others
            progress[i].addObserver(() => {
                p.advance();

                progress.forEach((p, j) => {
                    if (j != i) {
                        p.cancel();
                    }
                });
            });

            // TODO - clone value
            // Kick off execution synchronously
            a.call(x, progress[i], k, h);
        });
    }

    isAsync() {
        return true;
    }
}

class TryCombinator extends Combinator {
    constructor(a, s, f) {
        super(_construct(() => {
            let sta = sanitizeTypes([a])[0];
            let sts = sanitizeTypes([s])[0];
            let stf = sanitizeTypes([f])[0];

            try {
                let arg = sta.arg;
                let out = ParamType.fresh();
                let ncs = new ConstraintSet([]);
                let err = [];

                ncs = ncs.concat(sta.constraints);
                ncs = ncs.concat(sts.constraints);
                ncs = ncs.concat(stf.constraints);
                ncs = ncs.add(new Constraint(sta.out, sts.arg));
                ncs = ncs.add(new Constraint(sts.out, out));
                ncs = ncs.add(new Constraint(stf.out, out));

                sta.errors.forEach((e, i) => {
                    ncs = ncs.add(new Constraint(e, stf.arg));
                });

                err = err.concat(sts.errors);
                err = err.concat(stf.errors);

                return new ArrowType(arg, out, ncs, err);
            } catch (err) {
                let message;
                let location = getLocation(err.stack);

                if (location) {
                    message = "Unable to try arrows at: " + location;
                } else {
                    message = "Unable to try arrows";
                }

                throw new ComposeError(message + "\n\tInput => Try(" + [sta, sts, stf].join(", ") + ")\n\tError => " + err);
            }
        }), [a, s, f]);
    }

    toString() {
        return "try(" + this.arrows.map(a => a.toString()).join(", ") + ") :: " + this.type.toString();
    }

    call(x, p, k, h) {
        // Invoke original error callback "h" if either
        // callback creates an error value. This allows
        // nesting of error callbacks.

        let branch = new Progress(true);
        p.addCanceler(() => branch.cancel());
        branch.addObserver(() => p.advance());

        this.arrows[0].call(x, branch,
            y => this.arrows[1].call(y, p, k, h),
            z => {
                branch.cancel();
                this.arrows[2].call(z, p, k, h);
            }
        );
    }

    isAsync() {
        return (this.arrows[0].isAsync() || this.arrows[1].isAsync()) && this.arrows[2].isAsync();
    }
}

//
// Fix-Point Combinator
//

Arrow.fix = function(ctor) {
    let arg = ParamType.fresh(true);
    let out = ParamType.fresh(true);

    let p = new ProxyArrow(arg, out);
    let a = ctor(p);
    p.freeze(a);

    if (!(a instanceof Arrow)) {
        throw new Error("Fix constructor must return an arrow");
    }

    let t = a.type.toString();

    let map = {};
    descendants(arg).forEach(d => map[d.id] = arg);
    descendants(out).forEach(d => map[d.id] = out);

    arg.noreduce = false;
    out.noreduce = false;
    a.type.substitute(map);

    a.type.constraints = a.type.constraints.add(new Constraint(a.type.arg, arg));
    a.type.constraints = a.type.constraints.add(new Constraint(arg, a.type.arg));
    a.type.constraints = a.type.constraints.add(new Constraint(a.type.out, out));
    a.type.constraints = a.type.constraints.add(new Constraint(out, a.type.out));

    try {
        a.type.resolve();
    } catch (err) {
        let message;
        let location = getLocation(err.stack);

        if (location) {
            message = "Unable to fix arrow at: " + location;
        } else {
            message = "Unable to fix arrow";
        }

        throw new ComposeError(message + "\n\tInput => Fix(" + t + ")\n\tError => " + err);
    }

    return a;
};

class ProxyArrow extends Arrow {
    constructor(arg, out) {
        super(_construct(() => {
            return new ArrowType(arg, out);
        }));

        this.arrow = null;
    }

    toString() {
        if (this.arrow != null) {
            return "omega :: " + this.arrow.type.toString();
        }

        return "omega :: ???";
    }

    freeze(arrow) {
        this.arrow = arrow;
    }

    call(x, p, k, h) {
        return this.ensureFrozen(a => a.call(x, p, k, h));
    }

    equals(that) {
        return this.ensureFrozen(a => a.equals(that));
    }

    isAsync() {
        return this.ensureFrozen(a => a.isAsync());
    }

    ensureFrozen(f) {
        if (this.arrow != null) {
            return f(this.arrow);
        }

        throw new Error("Proxy not frozen");
    }
}

function getNonNullArrows(arrows) {
    let filtered = getNonNullElems(arrows);
    filtered.forEach(ensureArrow);
    return filtered;
}

function getNonNullElems(arrows) {
    let filtered = arrows.filter(a => a != null);
    if (filtered.length == 0) {
        throw new ComposeError("Combinator contains no non-null arguments.");
    }

    return filtered
}

function ensureArrow(arrow) {
    if (!(arrow instanceof Arrow)) {
        throw new ComposeError(`Passed non-arrow (${JSON.stringify(arrow)}) to combinator`);
    }
}

function descendants(param) {
    let children = [param];
    for (let child of param.children) {
        for (let descendant of descendants(child)) {
            children.push(descendant);
        }
    }

    return children;
}

function format(format, args) {
    return format.replace(/{(\d+)}/g, function(match, number) {
        return typeof args[number] != "undefined" ? args[number] : match;
    });
}
<commit_msg>Prevent stuck in infinite loop when isAsync() is called on recursive arrow.<commit_after>class ComposeError extends Error {
    constructor(message) {
        super();
        this.message = message;
    }

    toString() {
        return this.message;
    }
}

class Combinator extends Arrow {
    constructor(type, arrows) {
        super(type);
        this.arrows = arrows;
    }

    toString() {
        return this.constructor.name + "(" + this.arrows.map(a => a.toString()).join(", ") + ") :: " + this.type.toString();
    }

    isAsync() {
        return this.arrows.some(a => a.isAsync());
    }

    equals(that) {
        if (this.constructor === that.constructor) {
            return this.arrows.length === that.arrows.length && this.arrows.every((a, i) => a.equals(that.arrows[i]));
        }

        return false;
    }
}

class NamedArrow extends Combinator {
    constructor(name, a, args) {
        ensureArrow(a);

        super(_construct(() => {
            return a.type;
        }), [a]);

        this.name = format(name, (args || []).map(a => a.toString()));
    }

    toString() {
        return this.name + " :: " + this.arrows[0].type.toString();
    }

    call(x, p, k, h) {
        this.arrows[0].call(x, p, k, h);
    }

    isAsync() {
        return this.arrows[0].isAsync();
    }
}

class NoEmitCombinator extends Combinator {
    constructor(a) {
        ensureArrow(a);

        super(_construct(() => {
            return a.type;
        }), [a]);
    }

    toString() {
        return "noemit(" + this.arrows[0].toString() + ") :: " + this.type.toString();
    }

    call(x, p, k, h) {
        let quiet = new Progress(false);
        p.addCanceler(() => quiet.cancel());

        this.arrows[0].call(x, quiet, z => {
            p.advance();

            setTimeout(() => {
                k(z);
            }, 0);
        }, h);
    }

    isAsync() {
        return true;
    }
}

class SeqCombinator extends Combinator {
    constructor(arrows) {
        arrows = getNonNullArrows(arrows);

        super(_construct(() => {
            let sty = sanitizeTypes(arrows);

            try {
                let len = sty.length - 1;

                let arg = sty[0].arg;
                let out = sty[len].out;
                let ncs = new ConstraintSet([]);
                let err = sty[0].errors;

                sty.forEach((t, i) => {
                    ncs = ncs.concat(t.constraints);
                    err = err.concat(t.errors);

                    if (i != 0) {
                        ncs = ncs.add(new Constraint(sty[i - 1].out, t.arg));
                    }
                });

                return new ArrowType(arg, out, ncs, err);
            } catch (err) {
                let message;
                let location = getLocation(err.stack);

                if (location) {
                    message = "Unable to seq arrows at: " + location;
                } else {
                    message = "Unable to seq arrows";
                }

                throw new ComposeError(message + "\n\tInput => Seq(" + sty.join(", ") + ")\n\tError => " + err);
            }
        }), arrows);
    }

    toString() {
        return "seq(" + this.arrows.map(a => a.toString()).join(", ") + ") :: " + this.type.toString();
    }

    call(x, p, k, h) {
        const rec = (y, [head, ...tail]) => {
            if (head === undefined) {
                k(y);
            } else {
                head.call(y, p, z => rec(z, tail), h);
            }
        };

        rec(x, this.arrows);
    }
}

class AllCombinator extends Combinator {
    constructor(arrows) {
        arrows = getNonNullArrows(arrows);

        super(_construct(() => {
            let sty = sanitizeTypes(arrows);

            try {
                let arg = [];
                let out = [];
                let ncs = new ConstraintSet([]);
                let err = [];

                sty.forEach((t, i) => {
                    arg.push(t.arg);
                    out.push(t.out);

                    ncs = ncs.concat(t.constraints);
                    err = err.concat(t.errors);
                });

                return new ArrowType(new TupleType(arg), new TupleType(out), ncs, err);
            } catch (err) {
                let message;
                let location = getLocation(err.stack);

                if (location) {
                    message = "Unable to all arrows at: " + location;
                } else {
                    message = "Unable to all arrows";
                }

                throw new ComposeError(message + "\n\tInput => All(" + sty.join(", ") + ")\n\tError => " + err);
            }
        }), arrows);
    }

    toString() {
        return "all(" + this.arrows.map(a => a.toString()).join(", ") + ") :: " + this.type.toString();
    }

    call(x, p, k, h) {
        let numFinished = 0;
        let callResults = this.arrows.map(x => null);

        this.arrows.forEach((a, i) => {
            a.call(x[i], p, y => {
                callResults[i] = y;

                // Once results array is finished, continue
                if (++numFinished == this.arrows.length) {
                    k(callResults);
                }
            }, h);
        });
    }
}

class AnyCombinator extends Combinator {
    constructor(arrows) {
        arrows = getNonNullArrows(arrows);

        super(_construct(() => {
            let sty = sanitizeTypes(arrows);

            try {
                let arg = ParamType.fresh();
                let out = ParamType.fresh();
                let ncs = new ConstraintSet([]);
                let err = [];

                sty.forEach((t, i) => {
                    ncs = ncs.concat(t.constraints);
                    err = err.concat(t.errors);

                    ncs = ncs.add(new Constraint(arg, t.arg));
                    ncs = ncs.add(new Constraint(t.out, out));
                });

                return new ArrowType(arg, out, ncs, err);
            } catch (err) {
                let message;
                let location = getLocation(err.stack);

                if (location) {
                    message = "Unable to any arrows at: " + location;
                } else {
                    message = "Unable to any arrows";
                }

                throw new ComposeError(message + "\n\tInput => Any(" + sty.join(", ") + ")\n\tError => " + err);
            }
        }), arrows);
    }

    toString() {
        return "any(" + this.arrows.map(a => a.toString()).join(", ") + ") :: " + this.type.toString();
    }

    call(x, p, k, h) {
        // Note: This must be done at execution time instead of construction
        // time because a recursive arrow may present itself as falsely async.

        if (!this.arrows.every(a => a.isAsync())) {
            throw new Error("Any combinator requires asynchronous arrow arguments");
        }

        let progress = this.arrows.map(() => new Progress(true));

        // If combinator is canceled, cancel all children
        p.addCanceler(() => progress.forEach(p => p.cancel()));

        this.arrows.forEach((a, i) => {
            // When arrow[i] progresses, cancel others
            progress[i].addObserver(() => {
                p.advance();

                progress.forEach((p, j) => {
                    if (j != i) {
                        p.cancel();
                    }
                });
            });

            // TODO - clone value
            // Kick off execution synchronously
            a.call(x, progress[i], k, h);
        });
    }

    isAsync() {
        return true;
    }
}

class TryCombinator extends Combinator {
    constructor(a, s, f) {
        super(_construct(() => {
            let sta = sanitizeTypes([a])[0];
            let sts = sanitizeTypes([s])[0];
            let stf = sanitizeTypes([f])[0];

            try {
                let arg = sta.arg;
                let out = ParamType.fresh();
                let ncs = new ConstraintSet([]);
                let err = [];

                ncs = ncs.concat(sta.constraints);
                ncs = ncs.concat(sts.constraints);
                ncs = ncs.concat(stf.constraints);
                ncs = ncs.add(new Constraint(sta.out, sts.arg));
                ncs = ncs.add(new Constraint(sts.out, out));
                ncs = ncs.add(new Constraint(stf.out, out));

                sta.errors.forEach((e, i) => {
                    ncs = ncs.add(new Constraint(e, stf.arg));
                });

                err = err.concat(sts.errors);
                err = err.concat(stf.errors);

                return new ArrowType(arg, out, ncs, err);
            } catch (err) {
                let message;
                let location = getLocation(err.stack);

                if (location) {
                    message = "Unable to try arrows at: " + location;
                } else {
                    message = "Unable to try arrows";
                }

                throw new ComposeError(message + "\n\tInput => Try(" + [sta, sts, stf].join(", ") + ")\n\tError => " + err);
            }
        }), [a, s, f]);
    }

    toString() {
        return "try(" + this.arrows.map(a => a.toString()).join(", ") + ") :: " + this.type.toString();
    }

    call(x, p, k, h) {
        // Invoke original error callback "h" if either
        // callback creates an error value. This allows
        // nesting of error callbacks.

        let branch = new Progress(true);
        p.addCanceler(() => branch.cancel());
        branch.addObserver(() => p.advance());

        this.arrows[0].call(x, branch,
            y => this.arrows[1].call(y, p, k, h),
            z => {
                branch.cancel();
                this.arrows[2].call(z, p, k, h);
            }
        );
    }

    isAsync() {
        return (this.arrows[0].isAsync() || this.arrows[1].isAsync()) && this.arrows[2].isAsync();
    }
}

//
// Fix-Point Combinator
//

Arrow.fix = function(ctor) {
    let arg = ParamType.fresh(true);
    let out = ParamType.fresh(true);

    let p = new ProxyArrow(arg, out);
    let a = ctor(p);
    p.freeze(a);

    if (!(a instanceof Arrow)) {
        throw new Error("Fix constructor must return an arrow");
    }

    let t = a.type.toString();

    let map = {};
    descendants(arg).forEach(d => map[d.id] = arg);
    descendants(out).forEach(d => map[d.id] = out);

    arg.noreduce = false;
    out.noreduce = false;
    a.type.substitute(map);

    a.type.constraints = a.type.constraints.add(new Constraint(a.type.arg, arg));
    a.type.constraints = a.type.constraints.add(new Constraint(arg, a.type.arg));
    a.type.constraints = a.type.constraints.add(new Constraint(a.type.out, out));
    a.type.constraints = a.type.constraints.add(new Constraint(out, a.type.out));

    try {
        a.type.resolve();
    } catch (err) {
        let message;
        let location = getLocation(err.stack);

        if (location) {
            message = "Unable to fix arrow at: " + location;
        } else {
            message = "Unable to fix arrow";
        }

        throw new ComposeError(message + "\n\tInput => Fix(" + t + ")\n\tError => " + err);
    }

    return a;
};

class ProxyArrow extends Arrow {
    constructor(arg, out) {
        super(_construct(() => {
            return new ArrowType(arg, out);
        }));

        this.arrow = null;
    }

    toString() {
        if (this.arrow != null) {
            return "omega :: " + this.arrow.type.toString();
        }

        return "omega :: ???";
    }

    freeze(arrow) {
        this.arrow = arrow;
    }

    call(x, p, k, h) {
        return this.ensureFrozen(a => a.call(x, p, k, h));
    }

    equals(that) {
        return this.ensureFrozen(a => a.equals(that));
    }

    isAsync() {
        if (this._isAsync === undefined) {
          this._isAsync = false;
          this._isAsync = this.ensureFrozen(a => a.isAsync());
        }
        return this._isAsync;
    }

    ensureFrozen(f) {
        if (this.arrow != null) {
            return f(this.arrow);
        }

        throw new Error("Proxy not frozen");
    }
}

function getNonNullArrows(arrows) {
    let filtered = getNonNullElems(arrows);
    filtered.forEach(ensureArrow);
    return filtered;
}

function getNonNullElems(arrows) {
    let filtered = arrows.filter(a => a != null);
    if (filtered.length == 0) {
        throw new ComposeError("Combinator contains no non-null arguments.");
    }

    return filtered
}

function ensureArrow(arrow) {
    if (!(arrow instanceof Arrow)) {
        throw new ComposeError(`Passed non-arrow (${JSON.stringify(arrow)}) to combinator`);
    }
}

function descendants(param) {
    let children = [param];
    for (let child of param.children) {
        for (let descendant of descendants(child)) {
            children.push(descendant);
        }
    }

    return children;
}

function format(format, args) {
    return format.replace(/{(\d+)}/g, function(match, number) {
        return typeof args[number] != "undefined" ? args[number] : match;
    });
}
<|endoftext|>


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

const requestUrl = 'http://localhost:8000/return-status/';
const interval = 50;

const makeDummyCall = () => setTimeout(() => {
  const code = 200 + Math.random() * 399;
  request.get(`${requestUrl}${code}`);
  makeDummyCall();
}, interval);

makeDummyCall();
<commit_msg>Fix decimal status code<commit_after>const request = require('request');

const requestUrl = 'http://localhost:8000/return-status/';
const interval = 50;

const makeDummyCall = () => setTimeout(() => {
  const code = parseInt(200 + Math.random() * 399);
  request.get(`${requestUrl}${code}`);
  makeDummyCall();
}, interval);

makeDummyCall();
<|endoftext|>