<commit_before>/*
 * Copyright 2012 Andrey “A.I.” Sitnik <andrey@sitnik.ru>,
 * sponsored by Evil Martians.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

;(function () {
    "use strict";

    var defined = function(variable) {
        return ('undefined' != typeof(variable));
    };

    var self = Visibility;

    var timers = {

      // Run callback every `interval` milliseconds if page is visible and
      // every `hiddenInterval` milliseconds if page is hidden.
      //
      //   Visibility.every(60 * 1000, 5 * 60 * 1000, function () {
      //       checkNewMails();
      //   });
      //
      // You can skip `hiddenInterval` and callback will be called only if
      // page is visible.
      //
      //   Visibility.every(1000, function () {
      //       updateCountdown();
      //   });
      //
      // It is analog of `setInterval(callback, interval)` but use visibility
      // state.
      //
      // It return timer ID, that you can use in `Visibility.stop(id)` to stop
      // timer (`clearInterval` analog).
      // Warning: timer ID is different from interval ID from `setInterval`,
      // so don’t use it in `clearInterval`.
      //
      // On change state from hidden to visible timers will be execute.
      //
      // If you include jQuery Chrono plugin before Visibility.js, you could
      // use Chrono’s syntax sugar in interval arguments:
      //
      //   Visibility.every('second', function () {
      //       updateCountdown();
      //   });
      //   Visibility.every('1 minute', '5 minutes', function () {
      //       checkNewMails();
      //   });
      every: function (interval, hiddenInterval, callback) {
          self._initTimers();

          if ( !defined(callback) ) {
              callback = hiddenInterval;
              hiddenInterval = null;
          }
          self._lastTimer += 1;
          var number = self._lastTimer;
          self._timers[number] = ({
              interval:       interval,
              hiddenInterval: hiddenInterval,
              callback:       callback
          });
          self._runTimer(number, false);

          if ( self.isSupported() ) {
              self._setListener();
          }
          return number;
      },

      // Stop timer from `every` method by it ID (`every` method return it).
      //
      //   slideshow = Visibility.every(5 * 1000, function () {
      //       changeSlide();
      //   });
      //   $('.stopSlideshow').click(function () {
      //       Visibility.stop(slideshow);
      //   });
      stop: function(id) {
          var timer = self._timers[id]
          if ( !defined(timer) ) {
              return false;
          }
          self._stopTimer(id);
          delete self._timers[id];
          return timer;
      },

      // Last timer number.
      _lastTimer: -1,

      // Callbacks and intervals added by `every` method.
      _timers: { },

      // Is setInterval method detected and listener is binded.
      _timersInitialized: false,

      // Initialize variables on page loading.
      _initTimers: function () {
          if ( self._timersInitialized ) {
              return;
          }
          self._timersInitialized = true;

          if ( defined(window.jQuery) && defined(jQuery.every) ) {
              self._setInterval = self._chronoInterval;
          } else {
              self._setInterval = self._originalInterval;
          }
          self.change(function () {
              Visibility._timersStopRun()
          });
      },

      // Set interval directly by `setInterval` function without any syntax
      // sugar.
      _originalInterval: function (callback, interval) {
          return setInterval(callback, interval);
      },

      // Set interval by jQuery Chrono plugin. Add syntax sugar to `interval`
      // and `hiddenInterval` arguments, such as "1 second" and others.
      //
      // It will be automatically set to `_setInterval` on loading if
      // you include jQuery Chrono plugin before Visibility.js.
      _chronoInterval: function (callback, internal) {
          return jQuery.every(internal, callback);
      },

      // Set interval by `setInterval`. Allow to change function for tests or
      // syntax sugar in `interval` arguments.
      //
      // Function will be automatically set in `_init` method (which will be
      // call on script loading). So you must include jQuery Chrono plugin
      // before Visibility.js.
      _setInterval: null,

      // Try to run timer from every method by it’s ID. It will be use
      // `interval` or `hiddenInterval` depending on visibility state.
      // If page is hidden and `hiddenInterval` is null,
      // it will not run timer.
      //
      // Argument `now` say, that timers must be execute now too.
      _runTimer: function (id, now) {
          var interval,
              timer = self._timers[id];
          if ( self.hidden() ) {
              if ( null === timer.hiddenInterval ) {
                  return;
              }
              interval = timer.hiddenInterval;
          } else {
              interval = timer.interval;
          }
          if ( now ) {
              timer.callback.call(window);
          }
          timer.id = self._setInterval(timer.callback, interval);
      },

      // Stop timer from `every` method by it’s ID.
      _stopTimer: function (id) {
          var timer = self._timers[id];
          clearInterval(timer.id);
          delete timer.id;
      },

      // Listener for `visibilitychange` event.
      _timersStopRun: function (event) {
          var isHidden = self.hidden(),
              hiddenBefore = self._hiddenBefore;

          if ( (isHidden && !hiddenBefore) || (!isHidden && hiddenBefore) ) {
              for ( var i in self._timers ) {
                  self._stopTimer(i);
                  self._runTimer(i, !isHidden);
              }
          }
      }

    };

    for ( var prop in timers ) {
        Visibility[prop] = timers[prop];
    }

})();
<commit_msg>Fix compression for timers file<commit_after>/*
 * Copyright 2012 Andrey “A.I.” Sitnik <andrey@sitnik.ru>,
 * sponsored by Evil Martians.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

;(function () {
    "use strict";

    var defined = function(variable) {
        return ('undefined' != typeof(variable));
    };

    var self = Visibility;

    var timers = {

      // Run callback every `interval` milliseconds if page is visible and
      // every `hiddenInterval` milliseconds if page is hidden.
      //
      //   Visibility.every(60 * 1000, 5 * 60 * 1000, function () {
      //       checkNewMails();
      //   });
      //
      // You can skip `hiddenInterval` and callback will be called only if
      // page is visible.
      //
      //   Visibility.every(1000, function () {
      //       updateCountdown();
      //   });
      //
      // It is analog of `setInterval(callback, interval)` but use visibility
      // state.
      //
      // It return timer ID, that you can use in `Visibility.stop(id)` to stop
      // timer (`clearInterval` analog).
      // Warning: timer ID is different from interval ID from `setInterval`,
      // so don’t use it in `clearInterval`.
      //
      // On change state from hidden to visible timers will be execute.
      //
      // If you include jQuery Chrono plugin before Visibility.js, you could
      // use Chrono’s syntax sugar in interval arguments:
      //
      //   Visibility.every('second', function () {
      //       updateCountdown();
      //   });
      //   Visibility.every('1 minute', '5 minutes', function () {
      //       checkNewMails();
      //   });
      every: function (interval, hiddenInterval, callback) {
          self._initTimers();

          if ( !defined(callback) ) {
              callback = hiddenInterval;
              hiddenInterval = null;
          }
          self._lastTimer += 1;
          var number = self._lastTimer;
          self._timers[number] = ({
              interval:       interval,
              hiddenInterval: hiddenInterval,
              callback:       callback
          });
          self._runTimer(number, false);

          if ( self.isSupported() ) {
              self._setListener();
          }
          return number;
      },

      // Stop timer from `every` method by it ID (`every` method return it).
      //
      //   slideshow = Visibility.every(5 * 1000, function () {
      //       changeSlide();
      //   });
      //   $('.stopSlideshow').click(function () {
      //       Visibility.stop(slideshow);
      //   });
      stop: function(id) {
          var timer = self._timers[id]
          if ( !defined(timer) ) {
              return false;
          }
          self._stopTimer(id);
          delete self._timers[id];
          return timer;
      },

      // Last timer number.
      _lastTimer: -1,

      // Callbacks and intervals added by `every` method.
      _timers: { },

      // Is setInterval method detected and listener is binded.
      _timersInitialized: false,

      // Initialize variables on page loading.
      _initTimers: function () {
          if ( self._timersInitialized ) {
              return;
          }
          self._timersInitialized = true;

          if ( defined(window.jQuery) && defined(jQuery.every) ) {
              self._setInterval = self._chronoInterval;
          } else {
              self._setInterval = self._originalInterval;
          }
          self.change(function () {
              self._timersStopRun()
          });
      },

      // Set interval directly by `setInterval` function without any syntax
      // sugar.
      _originalInterval: function (callback, interval) {
          return setInterval(callback, interval);
      },

      // Set interval by jQuery Chrono plugin. Add syntax sugar to `interval`
      // and `hiddenInterval` arguments, such as "1 second" and others.
      //
      // It will be automatically set to `_setInterval` on loading if
      // you include jQuery Chrono plugin before Visibility.js.
      _chronoInterval: function (callback, internal) {
          return jQuery.every(internal, callback);
      },

      // Set interval by `setInterval`. Allow to change function for tests or
      // syntax sugar in `interval` arguments.
      //
      // Function will be automatically set in `_init` method (which will be
      // call on script loading). So you must include jQuery Chrono plugin
      // before Visibility.js.
      _setInterval: null,

      // Try to run timer from every method by it’s ID. It will be use
      // `interval` or `hiddenInterval` depending on visibility state.
      // If page is hidden and `hiddenInterval` is null,
      // it will not run timer.
      //
      // Argument `now` say, that timers must be execute now too.
      _runTimer: function (id, now) {
          var interval,
              timer = self._timers[id];
          if ( self.hidden() ) {
              if ( null === timer.hiddenInterval ) {
                  return;
              }
              interval = timer.hiddenInterval;
          } else {
              interval = timer.interval;
          }
          if ( now ) {
              timer.callback.call(window);
          }
          timer.id = self._setInterval(timer.callback, interval);
      },

      // Stop timer from `every` method by it’s ID.
      _stopTimer: function (id) {
          var timer = self._timers[id];
          clearInterval(timer.id);
          delete timer.id;
      },

      // Listener for `visibilitychange` event.
      _timersStopRun: function (event) {
          var isHidden = self.hidden(),
              hiddenBefore = self._hiddenBefore;

          if ( (isHidden && !hiddenBefore) || (!isHidden && hiddenBefore) ) {
              for ( var i in self._timers ) {
                  self._stopTimer(i);
                  self._runTimer(i, !isHidden);
              }
          }
      }

    };

    for ( var prop in timers ) {
        Visibility[prop] = timers[prop];
    }

})();
<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var cordova = require('cordova'),
    exec = require('cordova/exec'),
    channel = cordova.require("cordova/channel");

/*
 * Define native implementations ( there is no native layer, so need to make sure the proxies are there )
*/

require('cordova/plugin/windows8/DeviceProxy');
require('cordova/plugin/windows8/NetworkStatusProxy');
require('cordova/plugin/windows8/AccelerometerProxy');
require('cordova/plugin/windows8/CameraProxy');
require('cordova/plugin/windows8/CaptureProxy');
require('cordova/plugin/windows8/CompassProxy');
require('cordova/plugin/windows8/FileProxy');

require('cordova/plugin/windows8/FileTransferProxy');
require('cordova/plugin/windows8/MediaProxy');
require('cordova/plugin/windows8/NotificationProxy');

module.exports = {
    id: "windows8",
    initialize:function() {

        var onWinJSReady = function () {
            var app = WinJS.Application;
            var checkpointHandler = function checkpointHandler() {
                cordova.fireDocumentEvent('pause');
            };

            var resumingHandler = function resumingHandler() {
                cordova.fireDocumentEvent('resume');
            };

            app.addEventListener("checkpoint", checkpointHandler);
            Windows.UI.WebUI.WebUIApplication.addEventListener("resuming", resumingHandler, false);
            app.start();
        };

        if (!window.WinJS) {
            // <script src="//Microsoft.WinJS.1.0/js/base.js"></script>
            var scriptElem = document.createElement("script");
            scriptElem.src = "//Microsoft.WinJS.1.0/js/base.js";
            scriptElem.addEventListener("load", onWinJSReady);
            document.head.appendChild(scriptElem);

            console.log("added WinJS ... ");
        }
    },
    objects: {
        cordova: {
            path: 'cordova',
            children: {
                commandProxy: {
                    path: 'cordova/commandProxy'
                }
            }
        },
        navigator: {
            children: {
                device: {

                    children: {
                        capture: {
                            path: "cordova/plugin/capture"
                        }
                    }
                },
                console: {
                    path: "cordova/plugin/windows8/console"
                }
            }
        },
        FileReader: {
            path: 'cordova/plugin/FileReader'
        },
        File: {
            path: 'cordova/plugin/File'
        }
    },
    merges: {
        MediaFile: {
            path: "cordova/plugin/windows8/MediaFile"
        },
        navigator: {
            children: {
                geolocation: {
                    path: 'cordova/plugin/windows8/geolocation'
                }
            }
        }
    }
};
<commit_msg>fix whitespace issue, issue if WinJS already present<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var cordova = require('cordova'),
    exec = require('cordova/exec'),
    channel = cordova.require("cordova/channel");

/*
 * Define native implementations ( there is no native layer, so need to make sure the proxies are there )
*/

require('cordova/plugin/windows8/DeviceProxy');
require('cordova/plugin/windows8/NetworkStatusProxy');
require('cordova/plugin/windows8/AccelerometerProxy');
require('cordova/plugin/windows8/CameraProxy');
require('cordova/plugin/windows8/CaptureProxy');
require('cordova/plugin/windows8/CompassProxy');
require('cordova/plugin/windows8/FileProxy');

require('cordova/plugin/windows8/FileTransferProxy');
require('cordova/plugin/windows8/MediaProxy');
require('cordova/plugin/windows8/NotificationProxy');

module.exports = {
    id: "windows8",
    initialize:function() {

        var onWinJSReady = function () {
            var app = WinJS.Application;
            var checkpointHandler = function checkpointHandler() {
                cordova.fireDocumentEvent('pause');
            };

            var resumingHandler = function resumingHandler() {
                cordova.fireDocumentEvent('resume');
            };

            app.addEventListener("checkpoint", checkpointHandler);
            Windows.UI.WebUI.WebUIApplication.addEventListener("resuming", resumingHandler, false);
            app.start();
        };

        if (!window.WinJS) {
            // <script src="//Microsoft.WinJS.1.0/js/base.js"></script>
            var scriptElem = document.createElement("script");
            scriptElem.src = "//Microsoft.WinJS.1.0/js/base.js";
            scriptElem.addEventListener("load", onWinJSReady);
            document.head.appendChild(scriptElem);

            console.log("added WinJS ... ");
        }
        else {
            onWinJSReady();
        }
    },
    objects: {
        cordova: {
            path: 'cordova',
            children: {
                commandProxy: {
                    path: 'cordova/commandProxy'
                }
            }
        },
        navigator: {
            children: {
                device: {
                    children: {
                        capture: {
                            path: "cordova/plugin/capture"
                        }
                    }
                },
                console: {
                    path: "cordova/plugin/windows8/console"
                }
            }
        },
        FileReader: {
            path: 'cordova/plugin/FileReader'
        },
        File: {
            path: 'cordova/plugin/File'
        }
    },
    merges: {
        MediaFile: {
            path: "cordova/plugin/windows8/MediaFile"
        }
    }
};
<|endoftext|>


<commit_before>var heapModule = require('./binaryHeap.js');
const DISTANCE_PROP = 1;
const COST_PROP = DISTANCE_PROP;
const CONNECTED_BY_PROP = 2;

class WeightedGraph
{
  constructor(file)
  {
    this.load = false;

    this.loadGraphAsList(file);
  }

  loadGraphAsList(file)
  {
    console.time('loadList');

    var nVertex = parseFloat(file[0]);

    this.nVertex = nVertex;
    this.nEdges = file.length - 2;
    this.degrees = new Array(nVertex + 1);
    this.averageDegree = (2 * this.nEdges)/this.nVertex;
    this.list = new Array(nVertex + 1);

    for (var i = 1; i < nVertex + 1; i++) {
      this.list[i] = new Array();
    }

    for (var i = 1; i <= this.nEdges; i++)
    {
      var vertex = file[i].split(" ");
      var vertex0 = parseFloat(vertex[0]);
      var vertex1 = parseFloat(vertex[1]);
      var weight = parseFloat(vertex[2]);

      if (weight < 0) {
        throw new Error('Not supported negative weight in edge ' + file[i]);
      }

      this.list[vertex0].push([vertex1, weight]);
      this.list[vertex1].push([vertex0, weight]);

      //for each edge, add 1 on deegre of each vertex of this edge
      if(typeof   this.degrees[vertex0] == "undefined")
      {
        this.degrees[vertex0] = 1;
      }
      else
      {
        this.degrees[vertex0]++;
      }
      if(typeof   this.degrees[vertex1] == "undefined")
      {
        this.degrees[vertex1] = 1;
      }
      else
      {
        this.degrees[vertex1]++;
      }
    }
    console.timeEnd('loadList');
  }

  /**
   * search by dijkstra
   *
   * return array of [index of this vertex, distance from origin, vertex connecting this one, position in heap ]
   */
  search(origin)
  {
    var vertices = new Array(this.nVertex + 1);

    var heap = new heapModule.BinaryHeap(function(a) {
      return a[DISTANCE_PROP];
    });

    var infiniteDistance = Infinity;

    var vertex;
    for (var i = 1, limit = vertices.length; i < limit; i++) {
      vertex = [i, infiniteDistance, null, null];
      vertices[i] = vertex;
      heap.push(vertex);
    }
    vertices[origin][DISTANCE_PROP] = 0;

    // format of heap's items: [index, distance]
    heap.bubbleUpItem(vertices[origin]);

    var u;
    var v;
    var uDistance;
    var vWeight;
    var neighbors;
    var connectedBy;
    var position;
    while(heap.size() != 0)
    {
      [u, uDistance, connectedBy, position] = heap.pop();

      neighbors = this.list[u];

      for (var i = 0, iLimit = neighbors.length; i < iLimit; i++) {
        [v, vWeight] = neighbors[i];

        if(vertices[v][DISTANCE_PROP] > vertices[u][DISTANCE_PROP] + vWeight)
        {
          vertices[v][DISTANCE_PROP] = vertices[u][DISTANCE_PROP] + vWeight;
          vertices[v][CONNECTED_BY_PROP] = u;

          heap.bubbleUpItem(vertices[v]);
        }
      }
    }
    return vertices;
  }

  mst()
  {
    var graph = this.list;
    this.minTree = new Array(this.nVertex + 1);

    var heap = new heapModule.BinaryHeap(function(a) {
      return a[DISTANCE_PROP];
    });

    //define all vertex with null father and infinity cost
    var vertex;
    for (var i = 1; i < this.minTree.length; i++)
    {
      vertex = {};
      vertex.index = i;
      vertex[COST_PROP] = Infinity;
      vertex.father = null;
      vertex.connected = false;
      vertex.neighbors = [];
      vertex.degree = 0;
      this.minTree[i] = vertex;
      heap.push(vertex);

    }

    //define origin
    var origin = Math.floor((Math.random() * this.nVertex) + 1 );
    //console.log(origin);
    //set 0 for the cost of origin
    this.minTree[origin][COST_PROP] = 0;
    this.minTree[origin].degree = -1;
    //put the minimum cost in the root of heap
    heap.bubbleUpItem( this.minTree[origin]);

    var uVertex = {}
    var uNeighbors;
    var vIndex;
    var vCost;
    while(heap.size() != 0)
    {
      uVertex = heap.pop();
      uVertex.degree ++;
      if(uVertex.father != null)
      {
        this.minTree[uVertex.father].degree ++;
      }
      uVertex.connected = true;
      uNeighbors = graph[uVertex.index];
      for(i = 0; i <uNeighbors.length; i++)
      {
        [vIndex, vCost] = uNeighbors[i];
        var neighbor = this.minTree[vIndex];
        if(neighbor[COST_PROP] > vCost && !neighbor.connected )
        {
          if(heap.size() !=0)
          {
            this.minTree[vIndex].father = uVertex.index;
            this.minTree[vIndex][COST_PROP] = vCost;

            if(this.minTree[vIndex].index != uVertex.father)
            {
              this.minTree[vIndex].neighbors.push(uVertex.index);
              uVertex.neighbors.push(vIndex);
                heap.bubbleUpItem( this.minTree[vIndex]);
            }
            else
            {
              var index = this.minTree[vIndex].neighbors.indexof(uVertex.index);
              this.minTree[vIndex].neighbors.splice(index,1);
              var uIndex =uVertex.neighbors.indexof(vIndex);
              uVertex.neighbors.splice(uIndex,1);
            }
          }
        }
      }
    }

  }

  writeMSTInFile()
  {

  }

  getMeanDistance()
  {
    var nVertexAccounted = 0;
    var totalDistanceAccounted = 0;

    var vertices;
    var origin;
    for (var i = 1, iLimit = this.nVertex; i < iLimit; i++) {
      origin = i;
      vertices = this.search(origin);
      for (var j = 1, jLimit = vertices.length; j < jLimit; j++) {
        if(vertices[j][DISTANCE_PROP] != 0 && vertices[j][DISTANCE_PROP] != Infinity)
        {
          nVertexAccounted++;
          totalDistanceAccounted += vertices[j][DISTANCE_PROP];
        }
      }
    }

    return totalDistanceAccounted / nVertexAccounted;
  }
}

exports.WeightedGraph = WeightedGraph;
<commit_msg>Create method to load a graph contains euclidian distance of a vertex in bidimensional grade<commit_after>var heapModule = require('./binaryHeap.js');
const DISTANCE_PROP = 1;
const COST_PROP = DISTANCE_PROP;
const CONNECTED_BY_PROP = 2;

class WeightedGraph
{
  constructor(file)
  {
    this.load = false;

    this.loadGraphAsList(file);
  }

  constructor(file, type)
  {
    this.load = false;

    if(this.type == 0)
    {
      this.loadGraphAsMatrix(file);
    }

    if (this.type == 1)
    {
      this.loadGraphAsList(file);
    }
  }

  loadGraphAsMatrix(file)
  {
    console.time('loadMatrix');
    var nVertex = parseInt(file[0]);

    this.nVertex = nVertex;
    this.nEdges = nVertex * (nVertex - 1)/2;
    this.matrix = new Array(nVertex + 1);

    for (var i = 1; i < this.matrix.length; i++)
    {
      this.matrix[i] = new Array(nVertex + 1);
    }

    for (var iVertex = 1; iVertex <= this.nVertex; iVertex++)
    {
      var vertex = {};
      var coordenates = file[iVertex].split(" ");
      vertex.coordenateX = parseInt(coordenates[0]);
      vertex.coordenateY = parseInt(coordenates[1]);
      for( var iNextVertex = iVertex + 1; iNextVertex < this.nVertex; iNextVertex++)
      {
        var nextVertex = {};
        var coordenatesNextVertex = file[iNextVertex].split(" ");
        nextVertex.coordenateX = parseInt(coordenates[0]);
        nextVertex.coordenateY = parseInt(coordenates[1]);

        var distance = getDistance(vertex, nextVertex);
        this.matrix[iVertex][iNextVertex] = distance;
        this.matrix[iNextVertex][iVertex] = distance;
      }
    }
    console.timeEnd('loadMatrix');
  }

  loadGraphAsList(file)
  {
    console.time('loadList');

    var nVertex = parseFloat(file[0]);

    this.nVertex = nVertex;
    this.nEdges = file.length - 2;
    this.degrees = new Array(nVertex + 1);
    this.averageDegree = (2 * this.nEdges)/this.nVertex;
    this.list = new Array(nVertex + 1);

    for (var i = 1; i < nVertex + 1; i++) {
      this.list[i] = new Array();
    }

    for (var i = 1; i <= this.nEdges; i++)
    {
      var vertex = file[i].split(" ");
      var vertex0 = parseFloat(vertex[0]);
      var vertex1 = parseFloat(vertex[1]);
      var weight = parseFloat(vertex[2]);

      if (weight < 0) {
        throw new Error('Not supported negative weight in edge ' + file[i]);
      }

      this.list[vertex0].push([vertex1, weight]);
      this.list[vertex1].push([vertex0, weight]);

      //for each edge, add 1 on deegre of each vertex of this edge
      if(typeof   this.degrees[vertex0] == "undefined")
      {
        this.degrees[vertex0] = 1;
      }
      else
      {
        this.degrees[vertex0]++;
      }
      if(typeof   this.degrees[vertex1] == "undefined")
      {
        this.degrees[vertex1] = 1;
      }
      else
      {
        this.degrees[vertex1]++;
      }
    }
    console.timeEnd('loadList');
  }

  /**
   * search by dijkstra
   *
   * return array of [index of this vertex, distance from origin, vertex connecting this one, position in heap ]
   */
  search(origin)
  {
    var vertices = new Array(this.nVertex + 1);

    var heap = new heapModule.BinaryHeap(function(a) {
      return a[DISTANCE_PROP];
    });

    var infiniteDistance = Infinity;

    var vertex;
    for (var i = 1, limit = vertices.length; i < limit; i++) {
      vertex = [i, infiniteDistance, null, null];
      vertices[i] = vertex;
      heap.push(vertex);
    }
    vertices[origin][DISTANCE_PROP] = 0;

    // format of heap's items: [index, distance]
    heap.bubbleUpItem(vertices[origin]);

    var u;
    var v;
    var uDistance;
    var vWeight;
    var neighbors;
    var connectedBy;
    var position;
    while(heap.size() != 0)
    {
      [u, uDistance, connectedBy, position] = heap.pop();

      neighbors = this.list[u];

      for (var i = 0, iLimit = neighbors.length; i < iLimit; i++) {
        [v, vWeight] = neighbors[i];

        if(vertices[v][DISTANCE_PROP] > vertices[u][DISTANCE_PROP] + vWeight)
        {
          vertices[v][DISTANCE_PROP] = vertices[u][DISTANCE_PROP] + vWeight;
          vertices[v][CONNECTED_BY_PROP] = u;

          heap.bubbleUpItem(vertices[v]);
        }
      }
    }
    return vertices;
  }

  mst()
  {
    var graph = this.list;
    this.minTree = new Array(this.nVertex + 1);

    var heap = new heapModule.BinaryHeap(function(a) {
      return a[DISTANCE_PROP];
    });

    //define all vertex with null father and infinity cost
    var vertex;
    for (var i = 1; i < this.minTree.length; i++)
    {
      vertex = {};
      vertex.index = i;
      vertex[COST_PROP] = Infinity;
      vertex.father = null;
      vertex.connected = false;
      vertex.neighbors = [];
      vertex.degree = 0;
      this.minTree[i] = vertex;
      heap.push(vertex);

    }

    //define origin
    var origin = Math.floor((Math.random() * this.nVertex) + 1 );
    //console.log(origin);
    //set 0 for the cost of origin
    this.minTree[origin][COST_PROP] = 0;
    this.minTree[origin].degree = -1;
    //put the minimum cost in the root of heap
    heap.bubbleUpItem( this.minTree[origin]);

    var uVertex = {}
    var uNeighbors;
    var vIndex;
    var vCost;
    while(heap.size() != 0)
    {
      uVertex = heap.pop();
      uVertex.degree ++;
      if(uVertex.father != null)
      {
        this.minTree[uVertex.father].degree ++;
      }
      uVertex.connected = true;
      uNeighbors = graph[uVertex.index];
      for(i = 0; i <uNeighbors.length; i++)
      {
        [vIndex, vCost] = uNeighbors[i];
        var neighbor = this.minTree[vIndex];
        if(neighbor[COST_PROP] > vCost && !neighbor.connected )
        {
          if(heap.size() !=0)
          {
            this.minTree[vIndex].father = uVertex.index;
            this.minTree[vIndex][COST_PROP] = vCost;

            if(this.minTree[vIndex].index != uVertex.father)
            {
              this.minTree[vIndex].neighbors.push(uVertex.index);
              uVertex.neighbors.push(vIndex);
                heap.bubbleUpItem( this.minTree[vIndex]);
            }
            else
            {
              var index = this.minTree[vIndex].neighbors.indexof(uVertex.index);
              this.minTree[vIndex].neighbors.splice(index,1);
              var uIndex =uVertex.neighbors.indexof(vIndex);
              uVertex.neighbors.splice(uIndex,1);
            }
          }
        }
      }
    }

  }

  writeMSTInFile()
  {

  }

  getDistance(vertex, nextVertex)
  {
    // right-angled triangle
    return Math.sqrt(
      (vertex.coordenateX - nextVertex.coordenateX)**2
      + (vertex.coordenateY - nextVertex.coordenateY)**2
    );
  }

  getMeanDistance()
  {
    var nVertexAccounted = 0;
    var totalDistanceAccounted = 0;

    var vertices;
    var origin;
    for (var i = 1, iLimit = this.nVertex; i < iLimit; i++) {
      origin = i;
      vertices = this.search(origin);
      for (var j = 1, jLimit = vertices.length; j < jLimit; j++) {
        if(vertices[j][DISTANCE_PROP] != 0 && vertices[j][DISTANCE_PROP] != Infinity)
        {
          nVertexAccounted++;
          totalDistanceAccounted += vertices[j][DISTANCE_PROP];
        }
      }
    }

    return totalDistanceAccounted / nVertexAccounted;
  }
}

exports.WeightedGraph = WeightedGraph;
<|endoftext|>


<commit_before>/* Python 'tuple' type */

var tuple = __inherit(object);

tuple.__name__ = 'tuple';
tuple.prototype.__class__ = tuple;
tuple.prototype.MARK = "tuple";

tuple.prototype.__init__ = function(seq) {

    if (arguments.length > 1) {
        throw new py_builtins.TypeError("tuple() takes at most 1 argument (" + arguments.length + " given)");
    } else if (!defined(seq)) {
        this._items = [];
        this._len = 0;
    } else {
        this._items = copy(iter.__call__(seq));
        this._len = -1;
    }
};

tuple.prototype.__str__ = function () {
    if (this.__len__() == 1) {
        return str.__call__("(" + this._items[0] + ",)");
    } else {
        return str.__call__("(" + this._items.join(", ") + ")");
    }
};

tuple.prototype.__eq__ = function (other) {
    if (other.__class__ == this.__class__) {
        if (len(this) != len(other))
            return false;
        for (var i = 0; i < len(this); i++) {
            // TODO: use __eq__ here as well:
            if (this._items[i] != other._items[i])
                return false;
        }
        return true;
        // This doesn't take into account hash collisions:
        //return hash(this) == hash(other)
    } else
        return false;
};

tuple.prototype.toString = function () {
    return js(this.__str__());
};

tuple.prototype._js_ = function () {
    var items = [];

    iterate(iter.__call__(this), function(item) {
        items.push(js(item));
    });

    return items;
};

tuple.prototype.__hash__ = function () {
    var value = 0x345678;
    var length = this.__len__();

    for (var index in this._items) {
        value = ((1000003*value) & 0xFFFFFFFF) ^ hash(this._items[index]);
        value = value ^ length;
    }

    if (value == -1) {
        value = -2;
    }

    return value;
};

tuple.prototype.__len__ = function() {
    if (this._len == -1) {
        var count = 0;

        for (var index in this._items) {
            count += 1;
        }

        this._len = count;
        return count;
    } else
        return this._len;
};

tuple.prototype.__iter__ = function() {
    return iter.__call__(this._items);
};

tuple.prototype.__contains__ = function(item) {
    for (var index in this._items) {
        if (py_builtins.eq(item, this._items[index])) {
            return true;
        }
    }

    return false;
};

tuple.prototype.__getitem__ = function(index) {
    var seq;
    if (isinstance(index, slice)) {
        var s = index;
        var inds = s.indices(len(this));
        var start = inds.__getitem__(0);
        var stop = inds.__getitem__(1);
        var step = inds.__getitem__(2);
        seq = [];
        for (var i = start; i < stop; i += step) {
            seq.push(this.__getitem__(i));
        }
        return this.__class__.__call__(seq);
    } else if ((index >= 0) && (index < len(this)))
        return this._items[index];
    else if ((index < 0) && (index >= -len(this)))
        return this._items[index+len(this)];
    else
        throw new py_builtins.IndexError("list assignment index out of range");
};

tuple.prototype.__setitem__ = function(index, value) {
    throw new py_builtins.TypeError("'tuple' object doesn't support item assignment");
};

tuple.prototype.__delitem__ = function(index) {
    throw new py_builtins.TypeError("'tuple' object doesn't support item deletion");
};

tuple.prototype.count = function(value) {
    var count = 0;

    for (var index in this._items) {
        if (value == this._items[index]) {
            count += 1;
        }
    }

    return count;
};

tuple.prototype.index = function(value, start, end) {
    if (!defined(start)) {
        start = 0;
    }

    for (var i = start; !defined(end) || (start < end); i++) {
        var _value = this._items[i];

        if (!defined(_value)) {
            break;
        }

        if (_value == value) {
            return i;
        }
    }

    throw new py_builtins.ValueError("tuple.index(x): x not in list");
};

<commit_msg> * Changed all methods of tuple to Function-style<commit_after>/* Python 'tuple' type */

var tuple = __inherit(object);

tuple.__name__ = 'tuple';
tuple.prototype.__class__ = tuple;
tuple.prototype.MARK = "tuple";

tuple.prototype.__init__ = function(seq) {

    if (arguments.length > 1) {
        throw new py_builtins.TypeError("tuple() takes at most 1 argument (" + arguments.length + " given)");
    } else if (!defined(seq)) {
        this._items = [];
        this._len = 0;
    } else {
        this._items = copy(iter.__call__(seq));
        this._len = -1;
    }
};

tuple.prototype.__str__ = function () {
    if (this.__len__() == 1) {
        return str.__call__("(" + this._items[0] + ",)");
    } else {
        return str.__call__("(" + this._items.join(", ") + ")");
    }
};

tuple.prototype.__eq__ = function (other) {
    if (other.__class__ == this.__class__) {
        if (len(this) != len(other))
            return false;
        for (var i = 0; i < len(this); i++) {
            // TODO: use __eq__ here as well:
            if (this._items[i] != other._items[i])
                return false;
        }
        return true;
        // This doesn't take into account hash collisions:
        //return hash(this) == hash(other)
    } else
        return false;
};

tuple.prototype.toString = function () {
    return js(this.__str__());
};

tuple.prototype._js_ = function () {
    var items = [];

    iterate(iter.__call__(this), function(item) {
        items.push(js(item));
    });

    return items;
};

tuple.prototype.__hash__ = function () {
    var value = 0x345678;
    var length = this.__len__();

    for (var index in this._items) {
        value = ((1000003*value) & 0xFFFFFFFF) ^ hash(this._items[index]);
        value = value ^ length;
    }

    if (value == -1) {
        value = -2;
    }

    return value;
};

tuple.prototype.__len__ = function() {
    if (this._len == -1) {
        var count = 0;

        for (var index in this._items) {
            count += 1;
        }

        this._len = count;
        return count;
    } else
        return this._len;
};

tuple.prototype.__iter__ = function() {
    return iter.__call__(this._items);
};

tuple.prototype.__contains__ = function(item) {
    for (var index in this._items) {
        if (py_builtins.eq(item, this._items[index])) {
            return true;
        }
    }

    return false;
};

tuple.prototype.__getitem__ = function(index) {
    var seq;
    if (isinstance.__call__(index, slice)) {
        var s = index;
        var inds = s.indices(len(this));
        var start = inds.__getitem__(0);
        var stop = inds.__getitem__(1);
        var step = inds.__getitem__(2);
        seq = [];
        for (var i = start; i < stop; i += step) {
            seq.push(this.__getitem__(i));
        }
        return this.__class__.__call__(seq);
    } else if ((index >= 0) && (index < len(this)))
        return this._items[index];
    else if ((index < 0) && (index >= -len(this)))
        return this._items[index+len(this)];
    else
        throw new py_builtins.IndexError("list assignment index out of range");
};

tuple.prototype.__setitem__ = function(index, value) {
    throw new py_builtins.TypeError("'tuple' object doesn't support item assignment");
};

tuple.prototype.__delitem__ = function(index) {
    throw new py_builtins.TypeError("'tuple' object doesn't support item deletion");
};

tuple.prototype.count = Function(function(value) {
    var count = 0;

    for (var index in this._items) {
        if (value == this._items[index]) {
            count += 1;
        }
    }

    return count;
});

tuple.prototype.index = Function(function(value, start, end) {
    if (!defined(start)) {
        start = 0;
    }

    for (var i = start; !defined(end) || (start < end); i++) {
        var _value = this._items[i];

        if (!defined(_value)) {
            break;
        }

        if (_value == value) {
            return i;
        }
    }

    throw new py_builtins.ValueError("tuple.index(x): x not in list");
});

<|endoftext|>


<commit_before>/* Python 'float' type */

var _float = __inherit(number, "float");

var __py2js_float = _float;

_float.prototype.__init__ = function(i) {
    this._obj = parseFloat(i);
};

_float.prototype._isnumeric_float = true;

_float.prototype.__float__ = function () {
    return this;
};

_float.prototype.__str__ = function () {
    if (this._obj.toString().indexOf(".") === -1) {
        return str.__call__(this._obj + ".0");
    } else {
        return str.__call__(this._obj);
    }
};

_float.prototype.__repr__ = _float.prototype.__str__;

_float.prototype.__hash__ = function () {
    return this._obj;
};

_float.prototype.__div__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot divide number and non-number");
    if (x._obj === 0)
        throw py_builtins.ZeroDivisionError.__call__("float division by zero");
    return _float.__call__((0.0 + this._obj) / (0.0 + x._obj));
};

_float.prototype.__pow__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot exponentiate number and non-number");
    return _float.__call__(Math.pow(this._obj, x._obj));
};

_float.prototype.__floordiv__ = _float.prototype.__div__;
_float.prototype.__ifloordiv__ = _float.prototype.__div__;

<commit_msg> + Added license header to 29-type-float.js<commit_after>/**
  Copyright 2011 Christian Iversen <ci@sikkerhed.org>

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
**/

var _float = __inherit(number, "float");

var __py2js_float = _float;

_float.prototype.__init__ = function(i) {
    this._obj = parseFloat(i);
};

_float.prototype._isnumeric_float = true;

_float.prototype.__float__ = function () {
    return this;
};

_float.prototype.__str__ = function () {
    if (this._obj.toString().indexOf(".") === -1) {
        return str.__call__(this._obj + ".0");
    } else {
        return str.__call__(this._obj);
    }
};

_float.prototype.__repr__ = _float.prototype.__str__;

_float.prototype.__hash__ = function () {
    return this._obj;
};

_float.prototype.__div__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot divide number and non-number");
    if (x._obj === 0)
        throw py_builtins.ZeroDivisionError.__call__("float division by zero");
    return _float.__call__((0.0 + this._obj) / (0.0 + x._obj));
};

_float.prototype.__pow__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot exponentiate number and non-number");
    return _float.__call__(Math.pow(this._obj, x._obj));
};

_float.prototype.__floordiv__ = _float.prototype.__div__;
_float.prototype.__ifloordiv__ = _float.prototype.__div__;

<|endoftext|>


<commit_before>(function recallBootstrap(window) {
  // LT Requires
  var lt = window.lt;
  var path = require('path');
  var fs = require('fs');
  var gui = require('nw.gui');
  var appWindow = gui.Window.get();

  if(!lt.user_plugins) {
    lt.user_plugins = {};
  }

  // Local Requires
  if (fs.existsSync(path.join(lt.objs.plugins.user_plugins_dir, 'Recall'))){
    var localRoot = path.join(lt.objs.plugins.user_plugins_dir, 'Recall'); //When installed through the plugin manager, the Recall folder is created with an upper case
  }
  else
  {
    var localRoot = path.join(lt.objs.plugins.user_plugins_dir, 'recall'); //When recalled is manually cloned from the repository, the recall folder is created with a lower case
  }

  var ltrap = require(path.join(localRoot, 'node_modules', 'ltrap'))(window, localRoot);
  var ignore = ltrap.ignore;
  var _ = ltrap.require('underscore');

  var recall = lt.user_plugins.recall || {};
  if(recall.initialized) {
    return recall;
  }
  lt.user_plugins.recall = recall;
  recall.initialized = true;

  // Mapping of workspace names to workspace paths. This will eventually be user configurable.
  recall.workspaces = {
    'default': path.join(localRoot, 'workspaces', 'default.json')
  };

  /*\
  |*| Gets the contents of the active workspace in LT.
  \*/
  recall.getWorkspace = function() {
    var contents = {
        protocol: 0,
        tabs: ltrap.getTabs(),
        lastActive: ltrap.getActiveFile()
      };

    return contents;
  };

  recall.setWorkspace = function(workspace) {
  }

  /*\
  |*| Loads the given contents into the active workspace in LT.
  \*/
  recall.setWorkspace = function(contents) {
    for(var i = 0; i < contents.tabs.length; i++) {
      var tabset = contents.tabs[i];
      if(i !== 0) {
        ltrap.command('tabset.new');
        ltrap.command('tabset.next');
      }

      _.each(tabset, _.partial(ltrap.command, 'open-path'));
    }
  };

  /*\
  |*| Writes the active workspace to the specified file in the workspaces map.
  |*| @NOTE: Synchronous due to an issue within LT exiting before async events finish pumping.
  \*/
  recall.save = function(workspace) {
    var wsPath = recall.workspaces[workspace];
    ignore(_.partial(fs.mkdirSync, path.dirname(wsPath)), 'EEXIST'); // If the directory exists we're good.
    ignore(_.partial(fs.unlinkSync, wsPath), 'ENOENT'); // If the file doesn't already exist we're good.
    fs.writeFileSync(wsPath, JSON.stringify(recall.getWorkspace()));
  };

  /*\
  |*| Reads the specified workspace file into the active workspace.
  \*/
  recall.load = function(workspace) {
    fs.readFile(recall.workspaces[workspace], function(err, data) {
      if(err) {
        if(err.code === 'ENOENT') {
          return;
        }
        throw err;
      }

      // @TODO: Consider if this can be better handled when erroring.
      recall.setWorkspace(JSON.parse(data));
    });
  };

  // Bind events.
  // @TODO: Configure these as default behaviors instead of hardcoded events.
  recall.load('default');

  appWindow.on('close', function(event) {
    recall.save('default');
  });
})(window);
<commit_msg>Cleans up localRoot detection<commit_after>(function recallBootstrap(window) {
  // LT Requires
  var lt = window.lt;
  var path = require('path');
  var fs = require('fs');
  var gui = require('nw.gui');
  var appWindow = gui.Window.get();

  if(!lt.user_plugins) {
    lt.user_plugins = {};
  }

  // Local Requires
  // When installed through the plugin manager, the Recall folder is created with an upper case.
  // When recall is manually cloned from the repository, the recall folder is created with a lower case.
  var localRoot = path.join(lt.objs.plugins.user_plugins_dir, 'Recall');
  if(!fs.existsSync(localRoot)) {
    var localRoot = path.join(lt.objs.plugins.user_plugins_dir, 'recall');
  }

  var ltrap = require(path.join(localRoot, 'node_modules', 'ltrap'))(window, localRoot);
  var ignore = ltrap.ignore;
  var _ = ltrap.require('underscore');

  var recall = lt.user_plugins.recall || {};
  if(recall.initialized) {
    return recall;
  }
  lt.user_plugins.recall = recall;
  recall.initialized = true;

  // Mapping of workspace names to workspace paths. This will eventually be user configurable.
  recall.workspaces = {
    'default': path.join(localRoot, 'workspaces', 'default.json')
  };

  /*\
  |*| Gets the contents of the active workspace in LT.
  \*/
  recall.getWorkspace = function() {
    var contents = {
        protocol: 0,
        tabs: ltrap.getTabs(),
        lastActive: ltrap.getActiveFile()
      };

    return contents;
  };

  recall.setWorkspace = function(workspace) {
  }

  /*\
  |*| Loads the given contents into the active workspace in LT.
  \*/
  recall.setWorkspace = function(contents) {
    for(var i = 0; i < contents.tabs.length; i++) {
      var tabset = contents.tabs[i];
      if(i !== 0) {
        ltrap.command('tabset.new');
        ltrap.command('tabset.next');
      }

      _.each(tabset, _.partial(ltrap.command, 'open-path'));
    }
  };

  /*\
  |*| Writes the active workspace to the specified file in the workspaces map.
  |*| @NOTE: Synchronous due to an issue within LT exiting before async events finish pumping.
  \*/
  recall.save = function(workspace) {
    var wsPath = recall.workspaces[workspace];
    ignore(_.partial(fs.mkdirSync, path.dirname(wsPath)), 'EEXIST'); // If the directory exists we're good.
    ignore(_.partial(fs.unlinkSync, wsPath), 'ENOENT'); // If the file doesn't already exist we're good.
    fs.writeFileSync(wsPath, JSON.stringify(recall.getWorkspace()));
  };

  /*\
  |*| Reads the specified workspace file into the active workspace.
  \*/
  recall.load = function(workspace) {
    fs.readFile(recall.workspaces[workspace], function(err, data) {
      if(err) {
        if(err.code === 'ENOENT') {
          return;
        }
        throw err;
      }

      // @TODO: Consider if this can be better handled when erroring.
      recall.setWorkspace(JSON.parse(data));
    });
  };

  // Bind events.
  // @TODO: Configure these as default behaviors instead of hardcoded events.
  recall.load('default');

  appWindow.on('close', function(event) {
    recall.save('default');
  });
})(window);
<|endoftext|>


<commit_before>var http = require('http');
var fs = require('fs-extra');
var utils= require('./utils');

address=process.argv[process.argv.length - 4];
port=process.argv[process.argv.length - 3];
sharedDir=process.argv[process.argv.length -2];
destDir=process.argv[process.argv.length - 1];

var copyFile = function(file, sha1) {
  var src = sharedDir + '/' + file;
  utils.calcHash(src, function(err, calcHash) {
    if (err) {
      console.log('[-] Unable to calculate checksum ' + JSON.stringify(err));
      return;
    }
    if (sha1 != calcHash) {
      console.log('[-] File Version Missmatch');
    }
    var dst = destDir + '/' + file;
    console.log('[.] Coping File ' + src + ' to ' + dst);
    fs.copy(src, dst, function(err) {
      if (err) {
        console.log('[-] ' + err);
      } else {
        console.log('[+] File ' + src + ' copied to ' + dst);
      }
    });
  });
}

var mkDir = function(dir) {
  var dst = destDir + '/' + dir;
  fs.mkdirs(dst, function(err) {
    if (err) {
      console.log('[-] Unable to create ' + dst + ' directory');
    } else {
      console.log('[+] Directory ' + dst + ' created');
    }
  });
}

var unlink = function(file, type) {
  var dst = destDir + '/' + file;
  fs.remove(dst, function(err) {
    if (err) {
      console.log('[-] Unabled to create ' + dst + ' ' + type);
    } else {
      console.log('[+] ' + type + ' ' + dst + ' unlinked');
    }
  });
}

var eventDispatch = {
  'add': function(event, file, sha1) {
    console.log('[.] add event received for ' + sharedDir + '/' + file );
    copyFile(file, sha1);
  },
  'unlink': function(event, file, sha1) {
    console.log('[.] unlink event receiced for ' + sharedDir + '/' + file);
    unlink(file, 'File');
  },
  'change': function(event, file, sha1) {
    console.log('[.] change event received for ' + sharedDir + '/' + file);
    copyFile(file, sha1);
  },
  'addDir': function(event, dir, sha1) {
    console.log('[.] addDir event received for  ' + sharedDir + '/' + dir);
    mkDir(dir);
  },
  'unlinkDir': function(event, dir, sha1) {
    console.log('[.] unlinkDir event received for ' + sharedDir + '/' + dir);
    unlink(dir, 'Directory');
  },
  'default': function(event, file, sha1) {
    console.log('[-] unknown event received ' + event + ' on ' + file);
  },
};

//Clean destDirecotry first
fs.remove(destDir, function(err) {
  if (err) {
    console.log(err);
    return 1;
  }
  fs.copy(sharedDir, destDir, function(err) {
    if (err) {
      console.log(err);
      return 1;
    }
    http.createServer(function(request,response){
      var req = "";

      request.on('data', function(chunk) {
        req+=chunk
      });

      request.on('end', function() {
        var reqObj = JSON.parse(req);
        var dispatchKey = reqObj["event"];

        if (!(dispatchKey in eventDispatch)) {
          dispatchKey = 'default';
        }

        eventDispatch[dispatchKey](reqObj['event'], reqObj['file'], reqObj['checkSum']);
      });

      response.writeHead(200, {'Content-Type': 'application/json'});
      response.write(JSON.stringify({code: 200, message: 'Hello'}));
      response.end();
    }).listen(port, address);

    console.log("Server is listening to http://" + address + ":" + port);
  });
})
<commit_msg>added proper http response codes in remote module<commit_after>var http = require('http');
var fs = require('fs-extra');
var utils= require('./utils');

var SUCCESS_CODE=200;
var ERROR_CODE=406;

address=process.argv[process.argv.length - 4];
port=process.argv[process.argv.length - 3];
sharedDir=process.argv[process.argv.length -2];
destDir=process.argv[process.argv.length - 1];

var respond = function(responseObject, code, message) {
  responseObject.writeHead(code, {'Content-Type': 'application/json'});
  responseObject.write(JSON.stringify({code: code, message: message}));
  responseObject.end();
}

var copyFile = function(file, sha1, responseObject) {
  var src = sharedDir + '/' + file;
  utils.calcHash(src, function(err, calcHash) {
    if (err) {
      console.log('[-] Unable to calculate checksum ' + JSON.stringify(err));
      respond(responseObject, ERROR_CODE, 'unabled to calculate checksum for ' + file);
      return;
    }
    if (sha1 != calcHash) {
      console.log('[-] File Version Missmatch');
      respond(responseObject, ERROR_CODE, 'file version missmatch for ' + file);
      return;
    }
    var dst = destDir + '/' + file;
    console.log('[.] Coping File ' + src + ' to ' + dst);
    fs.copy(src, dst, function(err) {
      if (err) {
        console.log('[-] ' + err);
        respond(responseObject, ERROR_CODE, JSON.stringify(err));
        return;
      }

      console.log('[+] File ' + src + ' copied to ' + dst);
      respond(responseObject, SUCCESS_CODE, 'File ' + src + ' copied to ' + dst);
    });
  });
}

var mkDir = function(dir, responseObject) {
  var dst = destDir + '/' + dir;
  fs.mkdirs(dst, function(err) {
    if (err) {
      console.log('[-] Unable to create ' + dst + ' directory');
      respond(responseObject, ERROR_CODE, 'unabled to create ' + dst + ' directory');
    } else {
      console.log('[+] Directory ' + dst + ' created');
      respond(responseObject, SUCCESS_CODE, 'directory ' + dst + ' created');
    }
  });
}

var unlink = function(file, type, responseObject) {
  var dst = destDir + '/' + file;
  fs.remove(dst, function(err) {
    if (err) {
      console.log('[-] Unabled to unlink ' + dst + ' ' + type);
      respond(responseObject, ERROR_CODE, 'unabled to unlink ' + dst + ' ' + type);
    } else {
      console.log('[+] ' + type + ' ' + dst + ' unlinked');
      respond(responseObject, SUCCESS_CODE, type + ' ' + dst + ' unlinked');
    }
  });
}

var eventDispatch = {
  'add': function(event, file, sha1, responseObject) {
    console.log('[.] add event received for ' + sharedDir + '/' + file );
    copyFile(file, sha1, responseObject);
  },
  'unlink': function(event, file, sha1, responseObject) {
    console.log('[.] unlink event receiced for ' + sharedDir + '/' + file);
    unlink(file, 'File', responseObject);
  },
  'change': function(event, file, sha1, responseObject) {
    console.log('[.] change event received for ' + sharedDir + '/' + file);
    copyFile(file, sha1, responseObject);
  },
  'addDir': function(event, dir, sha1, responseObject) {
    console.log('[.] addDir event received for  ' + sharedDir + '/' + dir);
    mkDir(dir, responseObject);
  },
  'unlinkDir': function(event, dir, sha1, responseObject) {
    console.log('[.] unlinkDir event received for ' + sharedDir + '/' + dir);
    unlink(dir, 'Directory', responseObject);
  },
  'default': function(event, file, sha1, responseObject) {
    console.log('[-] unknown event received ' + event + ' on ' + file);
    respond(responseObject, 406, 'unkownd event');
  },
};

//Clean destDirecotry first
fs.remove(destDir, function(err) {
  if (err) {
    console.log(err);
    return 1;
  }
  fs.copy(sharedDir, destDir, function(err) {
    if (err) {
      console.log('[-] ' + err);
      return 1;
    }
    http.createServer(function(request, response){
      var req = "";

      request.on('data', function(chunk) {
        req+=chunk
      });

      request.on('end', function() {
        var reqObj = JSON.parse(req);
        var dispatchKey = reqObj["event"];

        if (!(dispatchKey in eventDispatch)) {
          dispatchKey = 'default';
        }

        eventDispatch[dispatchKey](reqObj['event'], reqObj['file'], reqObj['checkSum'], response);
      });

    }).listen(port, address);

    console.log("[.] Server is listening to http://" + address + ":" + port);
  });
})
<|endoftext|>


<commit_before>
var TheGraph = require('./index');
var React = require('react');
var ReactDOM = require('react-dom');

var darkTheme = require('./themes/the-graph-dark.css');
var lightTheme = require('./themes/the-graph-light.css');

// Generate some graph contents programatically
function addNode(graph) {
  var id = Math.round(Math.random()*100000).toString(36);
  var component = Math.random() > 0.5 ? 'basic' : 'basic';
  var metadata = {
    label: component,
    x: Math.round(Math.random()*800),
    y: Math.round(Math.random()*600)
  };
  var newNode = graph.addNode(id, component, metadata);
  return newNode;
};
function addEdge(graph, outNodeID) {
  var nodes = graph.nodes;
  var len = nodes.length;
  if ( len<1 ) { return; }
  var node1 = outNodeID || nodes[Math.floor(Math.random()*len)].id;
  var node2 = nodes[Math.floor(Math.random()*len)].id;
  var port1 = 'out' + Math.floor(Math.random()*3);
  var port2 = 'in' + Math.floor(Math.random()*12);
  var meta = { route: Math.floor(Math.random()*10) };
  var newEdge = graph.addEdge(node1, port1, node2, port2, meta);
  return newEdge;
};

function getTestData() {
    var componentLibrary = {
        basic: {
          name: 'basic',
          description: 'basic demo component',
          icon: 'eye',
          inports: [
            {'name': 'in0', 'type': 'all'},
            {'name': 'in1', 'type': 'all'},
            {'name': 'in2', 'type': 'all'}
          ],
          outports: [
            {'name': 'out', 'type': 'all'}
          ]
        },
    };
    var graph = new TheGraph.fbpGraph.Graph();
    addNode(graph);
    addNode(graph);
    addNode(graph);
    addNode(graph);
    addNode(graph);
    addEdge(graph);
    addEdge(graph);
    addEdge(graph);
    addEdge(graph);
    return { graph: graph, library: componentLibrary };
}

function applyStyleManual(element) {
    var style = getComputedStyle(element);
    var transferToAttribute = [

    ]
    var transferToStyle = [
        'fill',
        'stroke',
        'stroke-width',
        'opacity',
        'text-anchor',
        'font-size',
        'visibility',
    ]

    transferToAttribute.forEach(function (name) {
        var s = style.getPropertyValue(name);
        if (s) {
            element.setAttribute(name, s);
        }
    });
    transferToStyle.forEach(function (name) {
        var s = style.getPropertyValue(name);
        if (s) {
            element.style[name] = s;
        }
    });
}

// FIXME: background is missing
// FIXME: icons are broken
function applyStyle(tree) {
    var all = tree.getElementsByTagName("*")

    for (var i=0; i<all.length; i++) {
        applyStyleManual(all[i]);
    }
    return tree;
}

function renderImage(svgNode, options, callback) {
    if (!options) { options = {}; }
    options.format |= 'png';

    console.log('ss', svgNode)
    if (svgNode.tagName.toLowerCase() != 'svg') {
        return callback(new Error('renderImage input must be SVG, got ' + svgNode.tagName));
    }

    // FIXME: make copy
    //svgNode = svgNode.cloneNode(true, true);

    // Note: alternative to inlining style is to inject the CSS file into SVG file?
    // https://stackoverflow.com/questions/18434094/how-to-style-svg-with-external-css
    var withStyle = applyStyle(svgNode);

    var serializer = new XMLSerializer();
    var svgData = serializer.serializeToString(withStyle);

    if (options.format == 'svg') {
        return callback(null, svgData);
    }

    var DOMURL = window.URL || window.webkitURL || window;

    var img = new Image();
    var svg = new Blob([svgData], {type: 'image/svg+xml'});
    var svgUrl = DOMURL.createObjectURL(svg);

    var canvas = document.createElement('canvas');
    canvas.width = svgNode.getAttribute('width');
    canvas.height = svgNode.getAttribute('height');
    console.log('s', canvas)

    // TODO: allow resizing?
    // TODO: support background
    var ctx = canvas.getContext('2d');
    img.onerror = function(err) {
        return callback(err);
    }
    img.onload = function() {
        ctx.drawImage(img, 0, 0);
        DOMURL.revokeObjectURL(svgUrl);
        return callback(null, canvas.toDataURL(options.format))
    }
    //console.log('loading image', svgUrl);
    img.src = svgUrl;

    //document.body.appendChild(img)
}

function libraryFromGraph(graph) {
    return {}; // FIXME: implement
}

function removeAllChildren(n) {
    while (n.firstChild) {
        n.removeChild(n.firstChild);
    }
}

function renderGraph(graph, options) {
    //options.library = libraryFromGraph(graph);
    options.theme = 'the-graph-dark';

    // FIXME: also load CSS stylesheet

    // FIXME: Set zoom-level, width,height so that whole graph shows with all info
    // TODO: allow to specify maxWidth/maxHeight

    var props = {
        readonly: true,
        width: 1200,
        height: 600,
        graph: graph,
        library: options.library,
    };
    //console.log('render', props);

    var wrapper = document.createElement('div');
    wrapper.className = options.theme;
    wrapper.width = props.width;
    wrapper.height = props.height;

    // FIXME: bundle CSS and load from string
    var cssElement = document.createElement('link');
    cssElement.type = 'text/css';
    cssElement.rel = 'stylesheet';
    cssElement.href = '../themes/the-graph-dark.css';

    // FIXME: find a less intrusive way
    var container = document.body;

    removeAllChildren(document.head);
    document.head.appendChild(cssElement);
    removeAllChildren(container);
    container.appendChild(wrapper);

    var element = React.createElement(TheGraph.App, props);
    ReactDOM.render(element, wrapper);

    var svgElement = wrapper.children[0].getElementsByTagName('svg')[0];
    return svgElement;
}

function waitForStyleLoad(callback) {
    setTimeout(callback, 500); // XXX: hacky
}

function testInteractive() {
    // TEMP: testing
    //var svgNode = document.getElementById('editor').children[0].getElementsByTagName('svg')[0];

    var testData = getTestData();
    var svgNode = renderGraph(testData.graph, { library: testData.library });

    waitForStyleLoad(function() {
        var options = {};
        renderImage(svgNode, options, function(err, imageUrl) {
            if (err) {
                console.error('image render error', err);
                return;
            }
            imageUrl = imageUrl.replace("image/png", "image/octet-stream"); // avoid browser complaining about unsupported
            window.location.href = imageUrl;
        })
    });
}
module.exports = {
    testInteractive: testInteractive,
}

window.jsJobRun = function(inputdata, options, callback) {
    // FIXME: respect input/options

    var testData = getTestData();
    var svgNode = renderGraph(testData.graph, { library: testData.library });

    waitForStyleLoad(function() {
        var options = {};
        renderImage(svgNode, options, function(err, imageUrl) {
            // FIXME: decode and unpack the data?
            return callback(err, imageUrl);
        })
    });
};

<commit_msg>fix style loading in phantomjs<commit_after>
var TheGraph = require('./index');
var React = require('react');
var ReactDOM = require('react-dom');

var darkTheme = require('./themes/the-graph-dark.css');
var lightTheme = require('./themes/the-graph-light.css');

// Generate some graph contents programatically
function addNode(graph) {
  var id = Math.round(Math.random()*100000).toString(36);
  var component = Math.random() > 0.5 ? 'basic' : 'basic';
  var metadata = {
    label: component,
    x: Math.round(Math.random()*800),
    y: Math.round(Math.random()*600)
  };
  var newNode = graph.addNode(id, component, metadata);
  return newNode;
};
function addEdge(graph, outNodeID) {
  var nodes = graph.nodes;
  var len = nodes.length;
  if ( len<1 ) { return; }
  var node1 = outNodeID || nodes[Math.floor(Math.random()*len)].id;
  var node2 = nodes[Math.floor(Math.random()*len)].id;
  var port1 = 'out' + Math.floor(Math.random()*3);
  var port2 = 'in' + Math.floor(Math.random()*12);
  var meta = { route: Math.floor(Math.random()*10) };
  var newEdge = graph.addEdge(node1, port1, node2, port2, meta);
  return newEdge;
};

function getTestData() {
    var componentLibrary = {
        basic: {
          name: 'basic',
          description: 'basic demo component',
          icon: 'eye',
          inports: [
            {'name': 'in0', 'type': 'all'},
            {'name': 'in1', 'type': 'all'},
            {'name': 'in2', 'type': 'all'}
          ],
          outports: [
            {'name': 'out', 'type': 'all'}
          ]
        },
    };
    var graph = new TheGraph.fbpGraph.Graph();
    addNode(graph);
    addNode(graph);
    addNode(graph);
    addNode(graph);
    addNode(graph);
    addEdge(graph);
    addEdge(graph);
    addEdge(graph);
    addEdge(graph);
    return { graph: graph, library: componentLibrary };
}

function applyStyleManual(element) {
    var style = getComputedStyle(element);
    var transferToAttribute = [

    ]
    var transferToStyle = [
        'fill',
        'stroke',
        'stroke-width',
        'opacity',
        'text-anchor',
        'font-size',
        'visibility',
    ]

    transferToAttribute.forEach(function (name) {
        var s = style.getPropertyValue(name);
        if (s) {
            element.setAttribute(name, s);
        }
    });
    transferToStyle.forEach(function (name) {
        var s = style.getPropertyValue(name);
        if (s) {
            element.style[name] = s;
        }
    });
}

// FIXME: background is missing
// FIXME: icons are broken
function applyStyle(tree) {
    var all = tree.getElementsByTagName("*")

    for (var i=0; i<all.length; i++) {
        applyStyleManual(all[i]);
    }
    return tree;
}

function renderImage(svgNode, options, callback) {
    if (!options) { options = {}; }
    options.format |= 'png';

    console.log('ss', svgNode)
    if (svgNode.tagName.toLowerCase() != 'svg') {
        return callback(new Error('renderImage input must be SVG, got ' + svgNode.tagName));
    }

    // FIXME: make copy
    //svgNode = svgNode.cloneNode(true, true);

    // Note: alternative to inlining style is to inject the CSS file into SVG file?
    // https://stackoverflow.com/questions/18434094/how-to-style-svg-with-external-css
    var withStyle = applyStyle(svgNode);

    var serializer = new XMLSerializer();
    var svgData = serializer.serializeToString(withStyle);

    if (options.format == 'svg') {
        return callback(null, svgData);
    }

    var DOMURL = window.URL || window.webkitURL || window;

    var img = new Image();
    var svg = new Blob([svgData], {type: 'image/svg+xml'});
    var svgUrl = DOMURL.createObjectURL(svg);

    var canvas = document.createElement('canvas');
    canvas.width = svgNode.getAttribute('width');
    canvas.height = svgNode.getAttribute('height');
    console.log('s', canvas)

    // TODO: allow resizing?
    // TODO: support background
    var ctx = canvas.getContext('2d');
    img.onerror = function(err) {
        return callback(err);
    }
    img.onload = function() {
        ctx.drawImage(img, 0, 0);
        DOMURL.revokeObjectURL(svgUrl);
        return callback(null, canvas.toDataURL(options.format))
    }
    //console.log('loading image', svgUrl);
    img.src = svgUrl;

    //document.body.appendChild(img)
}

function libraryFromGraph(graph) {
    return {}; // FIXME: implement
}

function removeAllChildren(n) {
    while (n.firstChild) {
        n.removeChild(n.firstChild);
    }
}

function renderGraph(graph, options) {
    //options.library = libraryFromGraph(graph);
    options.theme = 'the-graph-dark';

    // FIXME: also load CSS stylesheet

    // FIXME: Set zoom-level, width,height so that whole graph shows with all info
    // TODO: allow to specify maxWidth/maxHeight

    var props = {
        readonly: true,
        width: 1200,
        height: 600,
        graph: graph,
        library: options.library,
    };
    //console.log('render', props);

    var wrapper = document.createElement('div');
    wrapper.className = options.theme;
    wrapper.width = props.width;
    wrapper.height = props.height;

    // FIXME: find a less intrusive way
    var container = document.body;
    removeAllChildren(container);
    container.appendChild(wrapper);

    var element = React.createElement(TheGraph.App, props);
    ReactDOM.render(element, wrapper);

    var svgElement = wrapper.children[0].getElementsByTagName('svg')[0];
    return svgElement;
}

function waitForStyleLoad(callback) {
    // FIXME: check properly, https://gist.github.com/cvan/8a188df72a95a35888b70e5fda80450d
    setTimeout(callback, 500);
}

function testInteractive() {
    // TEMP: testing
    //var svgNode = document.getElementById('editor').children[0].getElementsByTagName('svg')[0];

    var testData = getTestData();
    var svgNode = renderGraph(testData.graph, { library: testData.library });

    waitForStyleLoad(function() {
        var options = {};
        renderImage(svgNode, options, function(err, imageUrl) {
            if (err) {
                console.error('image render error', err);
                return;
            }
            imageUrl = imageUrl.replace("image/png", "image/octet-stream"); // avoid browser complaining about unsupported
            window.location.href = imageUrl;
        })
    });
}
module.exports = {
    testInteractive: testInteractive,
}

window.jsJobRun = function(inputdata, options, callback) {
    // FIXME: respect input/options

    var testData = getTestData();
    var svgNode = renderGraph(testData.graph, { library: testData.library });

    waitForStyleLoad(function() {

        var options = {};
        renderImage(svgNode, options, function(err, imageUrl) {
            // FIXME: decode and unpack the data?
            return callback(err, imageUrl);
        })
    });
};

<|endoftext|>


<commit_before>var elements = {};
var fs = require('fs');
function renderDataPoint(service, dataPoint, forPopup) {
  var text = fs.readFileSync('points/'+dataPoint+'.json').toString();
  var obj, badge, icon, sign, score;
  try {
    obj = JSON.parse(text);
  } catch(e) {
    console.log(e);
    console.log('Could not load data for data point '+dataPoint+', sorry! Refreshing the page might sometimes help.');
    die();
    return;
  }
  if(obj.tosdr.point == 'good') {
    badge = 'badge-success';
    icon = 'thumbs-up';
    sign = '+';
  } else if(obj.tosdr.point == 'mediocre') {
    badge = 'badge-warning';
    icon = 'thumbs-down';
    sign = '-';
  } else if(obj.tosdr.point == 'alert') {
    badge = 'badge-important';
    icon = 'remove';
    sign = '×';
  } else if(obj.tosdr.point == 'not bad') {
    badge = 'badge-neutral';
    icon = 'arrow-right';
    sign = '→';
  } else {
    badge = '';
    icon = 'question-sign';
    sign = '?';
  }
  if(forPopup) {
    return {
        id: dataPoint,
        score: obj.tosdr.score,
        text: '

'+sign+' '+obj.name+' Discussion '+(obj.source?'':'')+'

'
          +obj.tosdr.tldr+'

'
      };
  } else {
    return {
        id: dataPoint,
        score: obj.tosdr.score,
        text: ''
          +''+sign+' '+obj.name
      };
  }
}
function getServiceObject(name) {
  var text = fs.readFileSync('services/'+name+'.json').toString();
  var obj;
  try {
    obj = JSON.parse(text);
  } catch(e) {
    console.log(e);
    console.log('Could not load data for '+name+', sorry! Refreshing the page might sometimes help.');
    die();
  }
  if(obj) {
    return obj;
  } else {
    die('no obj in services/'+name+'.json');
  }
}
function getRatingText(className) {
    var ratingText = {
      0: "We haven't sufficiently reviewed the terms yet. Please contribute to our group: Get involved.",
      "false": "We haven't sufficiently reviewed the terms yet. Please contribute to our group: Get involved.",
      "A": "The terms of service treat you fairly, respect your rights and follows the best practices.",
      "B": "The terms of services are fair towards the user but they could be improved.",
      "C": "The terms of service are okay but some issues need your consideration.",
      "D": "The terms of service are very uneven or there are some important issues that need your attention.",
      "E": "The terms of service raise very serious concerns."
    };
  return ratingText[className];
}
function renderDetails(name, points, toslinks, obj) {
  console.log('renderDetails '+name);
  console.log(points);
  console.log(toslinks);
  console.log(obj);
  var header = '
'+obj.name+'';
  var rating;
  if(!obj.tosdr) {
    obj.tosdr = {rated: false};
  }
  if(obj.tosdr.rated) {
    rating = '
Class '+obj.tosdr.rated+'

';
  } else {
    rating = '
No Class Yet

';
  }
  var renderables=[];
  for(var i in points) {
    renderables.push(renderDataPoint(name, points[i], false));
  }
  renderables.sort(function(a, b) {
    return (b.score - a.score);
  });
  var issues = '

';
  for(var i=0; i<renderables.length; i++) {
    issues += '
'
      +renderables[i].text
      +'
';
  }
  issues += '
'
    +' Expand'
    +(toslinks.terms ? '  Read the full terms':'')
    +'
';
  var search = [name];
  if(obj.keywords) {
    for(var j=0; j<obj.keywords.length; j++) {
      search.push(obj.keywords[j]);
    }
  }
  if(obj.related) {
    for(var j=0; j<obj.related.length; j++) {
      search.push(obj.related[j]);
    }
  }
  if(obj.name) {
    for(var j=0; j<obj.name.length; j++) {
      search.push(obj.name[j]);
    }
  }
  if(obj.url) {
    for(var j=0; j<obj.url.length; j++) {
      search.push(obj.url[j]);
    }
  }
  if(obj.parent) {
    for(var j=0; j<obj.parent.length; j++) {
      search.push(obj.parent[j]);
    }
  }
  return '
'
          +header+rating+issues
          +'
';
}
function isEmpty(map) {
  for(var key in map) {
    if (map.hasOwnProperty(key)) {
      return false;
    }
  }
  return true;
}
function renderPopup(name, obj, points, links) {
  console.log('rendering popup for '+name);
  console.log(obj);
  console.log(points);
  console.log(links);
  var longName = obj.name,
    domain = obj.url,
    verdict = obj.tosdr.rated,
    ratingText = getRatingText(obj.tosdr.rated);
  var headerHtml = '
<button data-dismiss="modal" class="close" type="button">×</button>'
    +''
    +'
'+longName+'  '+domain+'

 ';
  var classHtml = '
'
    +(verdict?'Class '+verdict:'No Class Yet')+'
'+ratingText+'

';
  var renderables=[];
  for(var i in points) {
    renderables.push(renderDataPoint(name, points[i], true));
  }
  renderables.sort(function(a, b) {
    return (b.score - a.score);
  });
  var pointsHtml = '';
  for(var i=0; i<renderables.length; i++) {
    pointsHtml += '
'
      //+renderables[i].score+' '
      +renderables[i].text
      +'
';
  }
  var footerHtml = '
Close Link to ToS;DR for '+longName+'
';
  var bodyHtml = '
'+classHtml+'

'+pointsHtml+'

';
  if(isEmpty(links)) {
    bodyHtml += '
Help us find the Terms »
';
  } else {
    bodyHtml += '

Read the Terms

';
    for(var i in links) {
      bodyHtml += '
'+(links[i].name ? links[i].name : i)+'
';
    }
    bodyHtml+='

';
  }
  bodyHtml+='
';
  return headerHtml+bodyHtml+footerHtml;
}
function go() {
  var text = fs.readFileSync('index/services.json').toString();
  var servicesList = '', popups = '';
  try {
    var services = JSON.parse(text);
  } catch(e) {
    console.log('services.json file not readable');
  }
  console.log(services);
  var last, lastObj;
  for(var i in services) {
    var obj = getServiceObject(i);
    if(last) {
      servicesList += renderDetails(last, services[last].points, services[last].links, lastObj)
            +renderDetails(i, services[i].points, services[i].links, obj);
      last=undefined;
    } else {
      last = i;
      lastObj = obj;
    }
    popups +=
      '
'
      +renderPopup(i, obj, services[i].points, services[i].links)
      +'
';
    //renderPopup(name, obj.name, obj.url, obj.tosdr.rated, ratingText[obj.tosdr.rated], points, toslinks);
    //for(var i=0; i<points.length; i++) {
    //  renderDataPoint(name, points[i]);
    //}
  }
  if(last) {
    servicesList += '
'
          +renderDetails(last, services[i].points, services[i].links, lastObj)
      +'
';
  }
  fs.writeFileSync('index.html',
    fs.readFileSync('index-prefix.html').toString()
	  +'
'
    +servicesList
	  +'

'
    +popups
    +'
'
    +fs.readFileSync('index-suffix.html').toString()
  );
}
go();
<commit_msg>newlines in render<commit_after>var elements = {};
var fs = require('fs');
function renderDataPoint(service, dataPoint, forPopup) {
  var text = fs.readFileSync('points/'+dataPoint+'.json').toString();
  var obj, badge, icon, sign, score;
  try {
    obj = JSON.parse(text);
  } catch(e) {
    console.log(e);
    console.log('Could not load data for data point '+dataPoint+', sorry! Refreshing the page might sometimes help.');
    die();
    return;
  }
  if(obj.tosdr.point == 'good') {
    badge = 'badge-success';
    icon = 'thumbs-up';
    sign = '+';
  } else if(obj.tosdr.point == 'mediocre') {
    badge = 'badge-warning';
    icon = 'thumbs-down';
    sign = '-';
  } else if(obj.tosdr.point == 'alert') {
    badge = 'badge-important';
    icon = 'remove';
    sign = '×';
  } else if(obj.tosdr.point == 'not bad') {
    badge = 'badge-neutral';
    icon = 'arrow-right';
    sign = '→';
  } else {
    badge = '';
    icon = 'question-sign';
    sign = '?';
  }
  if(forPopup) {
    return {
        id: dataPoint,
        score: obj.tosdr.score,
        text: '

'+sign+' '+obj.name+' Discussion '+(obj.source?'':'')+'

'
          +obj.tosdr.tldr+'

'
      };
  } else {
    return {
        id: dataPoint,
        score: obj.tosdr.score,
        text: ''
          +''+sign+' '+obj.name
      };
  }
}
function getServiceObject(name) {
  var text = fs.readFileSync('services/'+name+'.json').toString();
  var obj;
  try {
    obj = JSON.parse(text);
  } catch(e) {
    console.log(e);
    console.log('Could not load data for '+name+', sorry! Refreshing the page might sometimes help.');
    die();
  }
  if(obj) {
    return obj;
  } else {
    die('no obj in services/'+name+'.json');
  }
}
function getRatingText(className) {
    var ratingText = {
      0: "We haven't sufficiently reviewed the terms yet. Please contribute to our group: Get involved.",
      "false": "We haven't sufficiently reviewed the terms yet. Please contribute to our group: Get involved.",
      "A": "The terms of service treat you fairly, respect your rights and follows the best practices.",
      "B": "The terms of services are fair towards the user but they could be improved.",
      "C": "The terms of service are okay but some issues need your consideration.",
      "D": "The terms of service are very uneven or there are some important issues that need your attention.",
      "E": "The terms of service raise very serious concerns."
    };
  return ratingText[className];
}
function renderDetails(name, points, toslinks, obj) {
  console.log('renderDetails '+name);
  console.log(points);
  console.log(toslinks);
  console.log(obj);
  var header = '
'+obj.name+'';
  var rating;
  if(!obj.tosdr) {
    obj.tosdr = {rated: false};
  }
  if(obj.tosdr.rated) {
    rating = '
Class '+obj.tosdr.rated+'

';
  } else {
    rating = '
No Class Yet

';
  }
  var renderables=[];
  for(var i in points) {
    renderables.push(renderDataPoint(name, points[i], false));
  }
  renderables.sort(function(a, b) {
    return (b.score - a.score);
  });
  var issues = '

';
  for(var i=0; i<renderables.length; i++) {
    issues += '
'
      +renderables[i].text
      +'
';
  }
  issues += '
'
    +' Expand'
    +(toslinks.terms ? '  Read the full terms':'')
    +'
';
  var search = [name];
  if(obj.keywords) {
    for(var j=0; j<obj.keywords.length; j++) {
      search.push(obj.keywords[j]);
    }
  }
  if(obj.related) {
    for(var j=0; j<obj.related.length; j++) {
      search.push(obj.related[j]);
    }
  }
  if(obj.name) {
    for(var j=0; j<obj.name.length; j++) {
      search.push(obj.name[j]);
    }
  }
  if(obj.url) {
    for(var j=0; j<obj.url.length; j++) {
      search.push(obj.url[j]);
    }
  }
  if(obj.parent) {
    for(var j=0; j<obj.parent.length; j++) {
      search.push(obj.parent[j]);
    }
  }
  return '
'
          +header+rating+issues
          +'
';
}
function isEmpty(map) {
  for(var key in map) {
    if (map.hasOwnProperty(key)) {
      return false;
    }
  }
  return true;
}
function renderPopup(name, obj, points, links) {
  console.log('rendering popup for '+name);
  console.log(obj);
  console.log(points);
  console.log(links);
  var longName = obj.name,
    domain = obj.url,
    verdict = obj.tosdr.rated,
    ratingText = getRatingText(obj.tosdr.rated);
  var headerHtml = '
<button data-dismiss="modal" class="close" type="button">×</button>'
    +''
    +'
'+longName+'  '+domain+'

\n';
  var classHtml = '
'
    +(verdict?'Class '+verdict:'No Class Yet')+'
'+ratingText+'

\n';
  var renderables=[];
  for(var i in points) {
    renderables.push(renderDataPoint(name, points[i], true));
  }
  renderables.sort(function(a, b) {
    return (b.score - a.score);
  });
  var pointsHtml = '';
  for(var i=0; i<renderables.length; i++) {
    pointsHtml += '
'
      //+renderables[i].score+' '
      +renderables[i].text
      +'
\n';
  }
  var footerHtml = '
Close Link to ToS;DR for '+longName+'
\n';
  var bodyHtml = '
'+classHtml+'

'+pointsHtml+'

\n';
  if(isEmpty(links)) {
    bodyHtml += '
Help us find the Terms »
\n';
  } else {
    bodyHtml += '

Read the Terms

\n';
    for(var i in links) {
      bodyHtml += '
'+(links[i].name ? links[i].name : i)+'
\n';
    }
    bodyHtml+='

\n';
  }
  bodyHtml+='
';
  return headerHtml+bodyHtml+footerHtml;
}
function go() {
  var text = fs.readFileSync('index/services.json').toString();
  var servicesList = '', popups = '';
  try {
    var services = JSON.parse(text);
  } catch(e) {
    console.log('services.json file not readable');
  }
  console.log(services);
  var last, lastObj;
  for(var i in services) {
    var obj = getServiceObject(i);
    if(obj.alexa >= 1000000) {
      continue;
    }
    if(last) {
      servicesList += renderDetails(last, services[last].points, services[last].links, lastObj)
            +renderDetails(i, services[i].points, services[i].links, obj);
      last=undefined;
    } else {
      last = i;
      lastObj = obj;
    }
    popups +=
      '
'
      +renderPopup(i, obj, services[i].points, services[i].links)
      +'
';
    //renderPopup(name, obj.name, obj.url, obj.tosdr.rated, ratingText[obj.tosdr.rated], points, toslinks);
    //for(var i=0; i<points.length; i++) {
    //  renderDataPoint(name, points[i]);
    //}
  }
  if(last) {
    servicesList += '
'
          +renderDetails(last, services[i].points, services[i].links, lastObj)
      +'
';
  }
  fs.writeFileSync('index.html',
    fs.readFileSync('index-prefix.html').toString()
	  +'
'
    +servicesList
	  +'

'
    +popups
    +'
'
    +fs.readFileSync('index-suffix.html').toString()
  );
}
go();
<|endoftext|>


<commit_before>var h = require('virtual-dom/h')

module.exports = Render

function Render(state) {
    var buffer = state.helpMode ?
        state.helpBuffer : state.mainBuffer

    var footerLoc = buffer.lines.length - buffer.index
    footerLoc = footerLoc < state.height ?
        footerLoc : state.height

    return h('screen', [
        h('section', textLines(state, buffer)),
        footer(buffer, footerLoc),
        h('cursor', {
            x: buffer.footer.length + 1,
            y: footerLoc
        })
    ])

    /*
    charm.push()
    charm.cursor(false)
    for (var i = 0; i < state.height; i++) {
        charm.position(1, i)
        charm.erase('end')
        charm.write(buffer.lines[buffer.index + i - 1] || '')
    }
    charm.cursor(true)
    charm.pop()
    */

    /*
    charm.push()
    charm.position(1, state.height)
    charm.erase('end')
    charm.pop()
    */

    /*
    charm.push()
    charm.position(1, footerLoc)
    charm.erase('end')
    charm.foreground('black')
    charm.background('white')
    charm.write(buffer.footer)
    */

    /*
    charm.pop()
    charm.position(buffer.footer.length + 1, footerLoc)
    charm.display('reset')
    */
}

function footer(buffer, footerLoc) {
    return h('line', {
        x: 1,
        y: footerLoc,
        foreground: 'black',
        background: 'white'
    }, buffer.footer)
}

function textLines(state, buffer) {
    var offset = buffer.index

    return range(state.height + 1).map(function (index) {
        if (index === 0 || index === state.height) {
            return h('line', { x: 1, y: index }, '')
        } else {
            var text = buffer.lines[offset + index - 1] || ''
            return h('line', { x: 1, y: index }, text)
        }
    })
}

function range(end) {
    var arr = []
    for (var i = 0; i < end; i++) {
        arr[i] = i;
    }
    return arr
}
<commit_msg>remove procedural code in comments<commit_after>var h = require('virtual-dom/h')

module.exports = Render

function Render(state) {
    var buffer = state.helpMode ?
        state.helpBuffer : state.mainBuffer

    var footerLoc = buffer.lines.length - buffer.index
    footerLoc = footerLoc < state.height ?
        footerLoc : state.height

    return h('screen', [
        h('section', textLines(state, buffer)),
        footer(buffer, footerLoc),
        h('cursor', {
            x: buffer.footer.length + 1,
            y: footerLoc
        })
    ])
}

function footer(buffer, footerLoc) {
    return h('line', {
        x: 1,
        y: footerLoc,
        foreground: 'black',
        background: 'white'
    }, buffer.footer)
}

function textLines(state, buffer) {
    var offset = buffer.index

    return range(state.height + 1).map(function (index) {
        if (index === 0 || index === state.height) {
            return h('line', { x: 1, y: index }, '')
        } else {
            var text = buffer.lines[offset + index - 1] || ''
            return h('line', { x: 1, y: index }, text)
        }
    })
}

function range(end) {
    var arr = []
    for (var i = 0; i < end; i++) {
        arr[i] = i;
    }
    return arr
}
<|endoftext|>