<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define('ace/mode/aql', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/aql_highlight_rules', 'ace/range'], function(require, exports, module) {

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var AqlHighlightRules = require("./aql_highlight_rules").AqlHighlightRules;
var Range = require("../range").Range;

var Mode = function() {
    this.$tokenizer = new Tokenizer(new AqlHighlightRules().getRules());
};
oop.inherits(Mode, TextMode);

(function() {

    this.toggleCommentLines = function(state, doc, startRow, endRow) {
        var outdent = true;
        var outentedRows = [];
        var re = /^(\s*)\/\//;

        for (var i=startRow; i<= endRow; i++) {
            if (!re.test(doc.getLine(i))) {
                outdent = false;
                break;
            }
        }

        if (outdent) {
            var deleteRange = new Range(0, 0, 0, 0);
            for (var i=startRow; i<= endRow; i++)
            {
                var line = doc.getLine(i);
                var m = line.match(re);
                deleteRange.start.row = i;
                deleteRange.end.row = i;
                deleteRange.end.column = m[0].length;
                doc.replace(deleteRange, m[1]);
            }
        }
        else {
            doc.indentRows(startRow, endRow, "//");
        }
    };

}).call(Mode.prototype);

exports.Mode = Mode;

});

define('ace/mode/aql_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var AqlHighlightRules = function() {

    var keywords = (
        "for|return|filter|sort|limit|let|collect|asc|desc|in|into|insert|update|remove|replace|options|with"
    );

    var builtinFunctions = (
        "(to_bool|to_number|to_string|to_list|is_null|is_bool|is_number|is_string|is_list|is_document|" +
        "concat|concat_separator|char_length|lower|upper|substring|left|right|trim|reverse|contains|" +
        "like|floor|ceil|round|abs|sqrt|rand|length|min|max|average|sum|median|variance_population|" +
        "variance_sample|first|last|unique|matches|merge|merge_recursive|has|attributes|unset|keep|" +
        "near|within|fulltext|paths|traversal|traversal_tree|edges|not_null|first_list|first_document|" +
        "flatten|length|min|max|sum|median|average|variance_sample|variance_population|"+
        "stddev_sample|stddev_population|unique|slice|reverse|first|last|nth|position|"+
        "has|attributes|merge|merge_recursive|document|matches|unset|keep|translate|"+
        "near|within|fulltext|paths|graph_paths|shortest_path|graph_shortest_path|graph_distance_to|"+
        "traversal|graph_traversal|traversal_tree|graph_traversal_tree|edges|graph_edges|"+
        "graph_vertices|neighbors|graph_neighbors|graph_common_neighbors|graph_common_properties|"+
        "graph_eccentricity|graph_betweenness|graph_closeness|graph_absolute_eccentricity|"+
        "graph_absolute_betweenness|graph_absolute_closeness|graph_diameter|graph_radius|date_now|"+
        "date_timestamp|date_iso8601|date_dayofweek|date_year|date_month|date_day|date_hour|"+
        "date_minute|date_second|date_millisecond|fail|passthru|sleep|collections|not_null|"+
        "first_list|first_document|parse_identifier|skiplist|current_user|current_database|"+
        "collections|document|stddev_population|stddev_sample|neighbors|union|union_distinct|intersection)"
    );

    var keywordMapper = this.createKeywordMapper({
        "support.function": builtinFunctions,
        "keyword": keywords,
        "constant.language": "null",
        "constant.language.boolean": "true|false"
    }, "identifier", true);

    this.$rules = {
        "start" : [ {
           token : "comment",
           regex : /\/\/.*$/
        }, {
            token : "comment",
            regex : /\/\*/,
            next : "comment_ml"
        }, {
            token : "string",           // " string
            regex : '".*?"'
        }, {
            token : "string",           // ' string
            regex : "'.*?'"
        }, {
            token : "string",           // ` string
            regex : "`.*?`"
        }, {
            token : "constant.numeric", // float
            regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
        }, {
            token : keywordMapper,
            regex : "[a-zA-Z_][a-zA-Z0-9_]*\\b"
        }, {
            token : "keyword.operator",
            regex : "\\+|\\-|\\/|\\/\\/|%|@>|<@|&&|\\||!|<|>|<=|=>|==|!=|="
        }, {
            token : "paren.lparen",
            regex : "[\\(\\{]"
        }, {
            token : "paren.rparen",
            regex : "[\\)\\}]"
        }, {
            token : "text",
            regex : "\\s+"
        } ],
        "comment_ml" : [ {
            token : "comment",
            regex : /\*\//,
            next : "start",
        }, {
          defaultToken : "comment"
        } ]
    };
};

oop.inherits(AqlHighlightRules, TextHighlightRules);

exports.AqlHighlightRules = AqlHighlightRules;
});

<commit_msg>added keywords<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define('ace/mode/aql', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/aql_highlight_rules', 'ace/range'], function(require, exports, module) {

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var AqlHighlightRules = require("./aql_highlight_rules").AqlHighlightRules;
var Range = require("../range").Range;

var Mode = function() {
    this.$tokenizer = new Tokenizer(new AqlHighlightRules().getRules());
};
oop.inherits(Mode, TextMode);

(function() {

    this.toggleCommentLines = function(state, doc, startRow, endRow) {
        var outdent = true;
        var outentedRows = [];
        var re = /^(\s*)\/\//;

        for (var i=startRow; i<= endRow; i++) {
            if (!re.test(doc.getLine(i))) {
                outdent = false;
                break;
            }
        }

        if (outdent) {
            var deleteRange = new Range(0, 0, 0, 0);
            for (var i=startRow; i<= endRow; i++)
            {
                var line = doc.getLine(i);
                var m = line.match(re);
                deleteRange.start.row = i;
                deleteRange.end.row = i;
                deleteRange.end.column = m[0].length;
                doc.replace(deleteRange, m[1]);
            }
        }
        else {
            doc.indentRows(startRow, endRow, "//");
        }
    };

}).call(Mode.prototype);

exports.Mode = Mode;

});

define('ace/mode/aql_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var AqlHighlightRules = function() {

    var keywords = (
        "for|return|filter|sort|limit|let|collect|asc|desc|in|into|insert|update|remove|replace|options|with|and|or|not"
    );

    var builtinFunctions = (
        "(to_bool|to_number|to_string|to_list|is_null|is_bool|is_number|is_string|is_list|is_document|" +
        "concat|concat_separator|char_length|lower|upper|substring|left|right|trim|reverse|contains|" +
        "like|floor|ceil|round|abs|sqrt|rand|length|min|max|average|sum|median|variance_population|" +
        "variance_sample|first|last|unique|matches|merge|merge_recursive|has|attributes|unset|keep|" +
        "near|within|fulltext|paths|traversal|traversal_tree|edges|not_null|first_list|first_document|" +
        "flatten|length|min|max|sum|median|average|variance_sample|variance_population|"+
        "stddev_sample|stddev_population|unique|slice|reverse|first|last|nth|position|"+
        "has|attributes|merge|merge_recursive|document|matches|unset|keep|translate|"+
        "near|within|fulltext|paths|graph_paths|shortest_path|graph_shortest_path|graph_distance_to|"+
        "traversal|graph_traversal|traversal_tree|graph_traversal_tree|edges|graph_edges|"+
        "graph_vertices|neighbors|graph_neighbors|graph_common_neighbors|graph_common_properties|"+
        "graph_eccentricity|graph_betweenness|graph_closeness|graph_absolute_eccentricity|"+
        "graph_absolute_betweenness|graph_absolute_closeness|graph_diameter|graph_radius|date_now|"+
        "date_timestamp|date_iso8601|date_dayofweek|date_year|date_month|date_day|date_hour|"+
        "date_minute|date_second|date_millisecond|fail|passthru|sleep|collections|not_null|"+
        "first_list|first_document|parse_identifier|skiplist|current_user|current_database|"+
        "collections|document|stddev_population|stddev_sample|neighbors|union|union_distinct|intersection)"
    );

    var keywordMapper = this.createKeywordMapper({
        "support.function": builtinFunctions,
        "keyword": keywords,
        "constant.language": "null",
        "constant.language.boolean": "true|false"
    }, "identifier", true);

    this.$rules = {
        "start" : [ {
           token : "comment",
           regex : /\/\/.*$/
        }, {
            token : "comment",
            regex : /\/\*/,
            next : "comment_ml"
        }, {
            token : "string",           // " string
            regex : '".*?"'
        }, {
            token : "string",           // ' string
            regex : "'.*?'"
        }, {
            token : "string",           // ` string
            regex : "`.*?`"
        }, {
            token : "constant.numeric", // float
            regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
        }, {
            token : keywordMapper,
            regex : "[a-zA-Z_][a-zA-Z0-9_]*\\b"
        }, {
            token : "keyword.operator",
            regex : "\\+|\\-|\\/|\\/\\/|%|@>|<@|&&|\\||!|<|>|<=|=>|==|!=|="
        }, {
            token : "paren.lparen",
            regex : "[\\(\\{]"
        }, {
            token : "paren.rparen",
            regex : "[\\)\\}]"
        }, {
            token : "text",
            regex : "\\s+"
        } ],
        "comment_ml" : [ {
            token : "comment",
            regex : /\*\//,
            next : "start",
        }, {
          defaultToken : "comment"
        } ]
    };
};

oop.inherits(AqlHighlightRules, TextHighlightRules);

exports.AqlHighlightRules = AqlHighlightRules;
});

<|endoftext|>


<commit_before>/* global require, module */

var EmberApp = require('ember-cli/lib/broccoli/ember-app');

var app = new EmberApp({
  name: require('./package.json').name,
  getEnvJSON: require('./config/environment')
});

// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.

app.import({
  development: 'vendor/ember-data/ember-data.js',
  production:  'vendor/ember-data/ember-data.prod.js'
}, {
  'ember-data': [
    'default'
  ]
});

app.import({
  development: 'vendor/d3/d3.js',
  production:  'vendor/d3/d3.min.js'
}, {
  'd3': [
    'default'
  ]
});

app.import('vendor/ic-ajax/dist/named-amd/main.js', {
  'ic-ajax': [
    'default',
    'defineFixture',
    'lookupFixture',
    'raw',
    'request',
  ]
});

app.import('vendor/foundation/js/foundation.js');

module.exports = app.toTree();
<commit_msg>API change<commit_after>/* global require, module */

var EmberApp = require('ember-cli/lib/broccoli/ember-app');

var app = new EmberApp({
  name: require('./package.json').name,
  getEnvJSON: require('./config/environment')
});

// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.

app.import({
  development: 'vendor/ember-data/ember-data.js',
  production:  'vendor/ember-data/ember-data.prod.js'
}, {
  exports: {
    'ember-data': ['default']
  }
});

app.import({
  development: 'vendor/d3/d3.js',
  production:  'vendor/d3/d3.min.js'
}, {
  exports: {
    'd3': ['default']
  }
});

app.import('vendor/ic-ajax/dist/named-amd/main.js', {
  exports: {
    'ic-ajax': ['default', 'defineFixture', 'lookupFixture', 'raw', 'request']
  }
});

app.import('vendor/foundation/js/foundation.js');

module.exports = app.toTree();
<|endoftext|>


<commit_before><commit_msg>Comment tweaks<commit_after><|endoftext|>


<commit_before>/*
 * This file contains all of the synchronous AJAX calls to our server.
 *
 *
 *
 * Copyright 2015 Eric Chen, Genji Noguchi, Justin Kim
 *
 */

Breadcrumbs.ajax = (function() {

    var createCrumb = function(data, url) {

        console.log("\n\nSending post request to " + Breadcrumbs.url + "/crumbs/new");
        console.log("Data: ");
        console.log(data);

        $.ajax({

            url: url+"/crumbs/new",
            data: {"crumb": data},
            dataType: 'JSON',
            type: 'POST',
            success: function(response) {
                console.log("Data returned: "+response);
                return response;
            },
            error: function() {
                console.log("Error in createCrumb");
            }

        });

    }

    var getCrumb = function(url, callback) {

        console.log(url);

		/*
        $.ajax({

            url: url,
            data: null,
            dataType: 'json',
            type: 'GET',
            success: function(resp) {
                console.log(resp);
                callback(resp);
            },
            error: function() {
                console.log("Error");
            }

        });
		*/

		callback({
			'crumbs': [
			{
				'latitude': 40.7244193 + (Math.random()*0.005)-0.01,
				'longitude': -73.7972479 + (Math.random()*0.005)-0.01,
				'message': "This is a test breadcrumb.",
				'user_id': 12345,
				'name': 'Juenjic Cheguchim'
			}
			]
		});

    }

    return {
        createCrumb: createCrumb,
        getCrumb: getCrumb
    };
}());
<commit_msg>Testing the ajax with real code.<commit_after>/*
 * This file contains all of the synchronous AJAX calls to our server.
 *
 *
 *
 * Copyright 2015 Eric Chen, Genji Noguchi, Justin Kim
 *
 */

Breadcrumbs.ajax = (function() {

    var createCrumb = function(data, url) {

        console.log("\n\nSending post request to " + Breadcrumbs.url + "/crumbs/new");
        console.log("Data: ");
        console.log(data);

        $.ajax({

            url: url+"/crumbs/new",
            data: {"crumb": data},
            dataType: 'JSON',
            type: 'POST',
            success: function(response) {
                console.log("Data returned: "+response);
                return response;
            },
            error: function() {
                console.log("Error in createCrumb");
            }

        });

    }

    var getCrumb = function(url, callback) {

        console.log(url);

        $.ajax({

            url: url,
            data: null,
            dataType: 'json',
            type: 'GET',
            success: function(resp) {
                console.log(resp);
                callback(resp);
            },
            error: function() {
                console.log("Error");
            }

        });

		/*
		callback({
			'crumbs': [
			{
				'latitude': 40.7244193 + (Math.random()*0.005)-0.01,
				'longitude': -73.7972479 + (Math.random()*0.005)-0.01,
				'message': "This is a test breadcrumb.",
				'user_id': 12345,
				'name': 'Juenjic Cheguchim'
			}
			]
		});
		*/

    }

    return {
        createCrumb: createCrumb,
        getCrumb: getCrumb
    };
}());
<|endoftext|>


<commit_before>

module.exports = function(grunt) {
	grunt.registerTask('export', 'export jenscript to directory, usage $ grunt export:/path/to/dir', function(exportDir) {
		  grunt.log.writeln('jenscript@export'+grunt.config('pkg').version);
		  if(exportDir !== undefined){
			  grunt.log.writeln('jenscript@'+grunt.config('pkg').version+' export --> '+exportDir);
			  grunt.config('exportDir',exportDir);
			  grunt.task.run(["copy:export"]);
		  }else{
			  //grunt.log.writeln('jenscript@export not export directory supplied');
			  grunt.fail.fatal("jenscript export directory should be supplied.")
		  }
	});
};<commit_msg>clean task<commit_after>

module.exports = function(grunt) {
	grunt.registerTask('export', 'export jenscript to directory, usage $ grunt export:/path/to/dir', function(exportDir) {
		  grunt.log.writeln('jenscript@export'+grunt.config('pkg').version);
		  var fs = require('fs');
		  if(exportDir !== undefined && fs.existsSync(exportDir)){
			  grunt.log.writeln('jenscript@'+grunt.config('pkg').version+' export --> '+exportDir);
			  grunt.config('exportDir',exportDir);
			  grunt.task.run(["copy:export"]);
		  }else{
			  grunt.fail.fatal("jenscript valid export directory should be supplied.")
		  }
	});
};<|endoftext|>


<commit_before>angular.module('lisp.communication', [])

  // Declaring the lisp service, which will contain all the functions we'll use to communicate with Lisp
  .factory('lispService', ['$http', '$q', function($http, $q) {
    var serviceInstance = {};

    // Info of all rlocs
    var listOfRlocs = {};
    // Donat un RLOC, té tot els EIDs que estan connectats
    var RLOCLinktedToEID = {};
    // Donat un EID, té tots els RLOCs als que està connectat
    var EidRLOC = {};
    // List with all vn-identifier
    var listOfVNI = [];
    // All Json info
    var Json = [];

    serviceInstance.getAllInfo = function(jsonObj) {
      //jsonObj has JSON response
      var virtualNetworks = jsonObj["mapping-database"]["virtual-network-identifier"];
      Json = virtualNetworks;
      for (var j=0; j<virtualNetworks.length; j++)
      {
        var vni = virtualNetworks[j]["vni"];
        listOfVNI.push(vni);
        var eids = virtualNetworks[j]["mapping"];
        for (var i = 0; i<eids.length; i++)
        {
          var eidInfo = eids[i]["mapping-record"]["eid"];
          var eid_uri =eids[i]["eid"];
          var mappingRecord = eids[i]["mapping-record"];
          var rlocs = mappingRecord["LocatorRecord"];
          var listEidRloc = [];
          for (var rlocIt = 0; rlocIt <rlocs.length; rlocIt++)
          {
            serviceInstance.addRlocToRlocList(rlocs[rlocIt]);
            listEidRloc.push(rlocs[rlocIt]["locator-id"]);
            serviceInstance.addRLOCToListRLOCLinktedToEID(rlocs[rlocIt],eid_uri);
          }
          EidRLOC[eids[i]["eid-uri"]] = listEidRloc;

          var typeIP = eids[i]["eid-uri"].split(":")[0];
        }
      }
    };

    serviceInstance.addRlocToRlocList = function(rloc){
      //check if rloc exists on listOfRlocs
      listOfRlocs[rloc["locator-id"]] = rloc;
    };

    serviceInstance.getRLOCsFromEID = function (eidUri)
    {

      return EidRLOC[eidUri];
    };

    serviceInstance.getAddressType = function (eidUri)
    {
      return "ietf-lisp-address-types:" + serviceInstance.getIPType(eidUri) + "-afi";
    };

    serviceInstance.getMappingEID = function (eidUri)
    {
      var addresType = serviceInstance.getAddressType(eidUri);
      var idType = serviceInstance.getIPType(eidUri);
      var ip = serviceInstance.getIP(eidUri);
    };

    serviceInstance.addRLOCToListRLOCLinktedToEID = function (rloc,eid)
    {
      //check if rloc exists on listOfRlocs
      if (RLOCLinktedToEID[rloc["locator-id"]] === undefined)
      {
        var aux = [];
      }
      else
      {
        var aux = RLOCLinktedToEID[rloc["locator-id"]];
      }
      aux.push(eid);
      RLOCLinktedToEID[rloc["locator-id"]] = aux;
    };

    serviceInstance.getEIDsFromRLOC = function (addressType, addressIP)
    {
      var EIDS = [];
      for (var i=0; i<Json.length; i++)
      {
        var mappingOfVNI = Json["mapping"];
        for (var j=0; j<mappingOfVNI.length;j++)
        {
          var locatorRecords = mappingOfVNI["LocatorRecord"];
          for (var z=0; z<locatorRecords.length;z++)
          {
            if (locatorRecords[z]["rloc"]["address-type"] == addressType)
            {
              var typeIP = addresType.split(":")[1].split("-")[0];
              if (locatorRecords[z]["rloc"][typeIP] == addressIP)
              {
                eids.push(mappingOfVNI[j]["eid-uri"])
              }
            }
          }
        }
      }
      return eids;
    };

    // First function to call: gets all the lisp database content and stores it in the service
    serviceInstance.initialize = function()
    {
      var deferred = $q.defer();
      var auth64 = btoa('admin:admin');

      $http({
            url: 'http://odl2.cba.upc.edu:8181/restconf/config/odl-mappingservice:mapping-database/',
            method: "GET",
            withCredentials: true,
            headers: {
                'Authorization': 'Basic '+ auth64
            }
        })
      .success(function(data) {

        serviceInstance.getAllInfo(data);
        deferred.resolve();

      }).error(function(msg, code) {

        deferred.reject(msg);

        console.log(msg);

      });

      return deferred.promise;

    };

    // Returns all EID contained in the service

    serviceInstance.getEidInfo = function(eidaddress){
      var EidInfo = {};
      for (var i=0; i<Json.length; i++)
      {
          var vni = Json[i]["vni"];
          var eids = Json[i]["mapping"];
          for (var j = 0; j<eids.length; j++)
          {
            var eid_uri = eids[j]["eid-uri"];
            var obj = new Object();
            if(eidaddress == getIP(eid_uri)){
              obj.xtr_id = eids[j]["mapping-record"]["xtr-id"];
              obj.address = serviceInstance.getIP(eid_uri);
              obj.address_type = serviceInstance.getIPType(eid_uri);
              obj.action = eids[j]["mapping-record"]["action"];
              EidInfo[vni] = obj;
            }

        }
      }
      return EidInfo;
    };

    serviceInstance.getAllVnIds = function() {
      return listOfVNI;
    };

    /* Function to get EIDs in VN
    ** Retun array with eid-uri of all EIDs in VN.
    ** Tip: Use getIPType and getIP functions to get info of eid-uri
    */
    serviceInstance.getEidsInVn = function(VnId)
    {
      var EIDinVN = [];
      for (var i=0; i<Json.length; i++)
      {
        if (Json[i]["vni"] == VnId)
        {
          var eids = Json[i]["mapping"];
          for (var i=0;i<eids.length;i++)
          {
            EIDinVN.push(eids[i]["eid-uri"]);
          }
        }
      }
      return EIDinVN;
    };

    serviceInstance.getAllEids = function()
    {
      var EidList = {};
      for (var i=0; i<Json.length; i++)
      {
          var eids = Json[i]["mapping"];
          var vni = Json[i]["vni"]
          var vectorEIds = new Object();
          for (var j = 0; j<eids.length; j++)
          {
            var obj = new Object();
            var eid_uri = eids[j]["eid-uri"];
            var xtr = eids[j]["mapping-record"]["xtr-id"];
            obj.vni = vni;
            obj.address = eid_uri;
            obj.xtr_id  = xtr;
            var rlocs = eids[j]["mapping-record"]["LocatorRecord"];
            var RLocAdr = [];
            for (var rlocIt = 0; rlocIt <rlocs.length; rlocIt++)
            {
              var typeIP = rlocs[rlocIt]["rloc"]["address-type"].split(":")[1].split("-")[0];
              RLocAdr.push(rlocs[rlocIt]["rloc"][typeIP]);
            }
            obj.rlocs = RLocAdr;
            vectorEIds.push(obj);
            if(j == (eids.length-1)) EidList[vni] = vectorEIds;
          }
        }
      return EidList;
    };

    serviceInstance.getIPType = function (eidUri)
    {
      return eidUri.split(":")[0];
    };

    serviceInstance.getIP = function (eidUri)
    {
      return eidUri.substring(eidUri.split(":")[0].length+1, eidUri.length);
    };

    serviceInstance.getRLOCs = function (vni, eid)
    {
      var rlocs = Json[vni]["mapping"][eid]["mapping-record"]["LocatorRecord"]
      var rloc_iterator;
      var rlocsOfEID;
      for (rloc_iterator = 0; rloc_iterator < rlocs.length; ++rloc_iterator)
      {
        rlocsOfEID.push(rlocs[rloc_iterator]);
      }
      return rlocsOfEID;
    };

    serviceInstance.getAllxtrids = function() {
      var vectorXTR = [];
      for (var i=0;i<Json.length;i++)
      {
        var eids = Json[i]["mapping"];
        for (var j = 0; j<eids.length; j++)
        {
          vectorXTR[eids[j]["xtr-id"]] = vectorXTR[eids[j]["xtr-id"]].push(getRLOCs(i,j))
        }
      }

      return vectorXTR;
    };

     serviceInstance.getXtridInfo = function(xtridAddress) {
         //info per definir
      return Info;
    };

    serviceInstance.getAllRlocs = function() {
      var ListRlocs = {};
      var RlocId;
      var RlocIp;
      for (var i=0; i<Json.length; i++)
      {
          var eids = Json[i]["mapping"];
          for (var j = 0; j<eids.length; j++)
          {
            var rlocs = mappingRecord["LocatorRecord"];
            for (var rlocIt = 0; rlocIt <rlocs.length; rlocIt++) {
              RlocId = rlocs[rlocIt]["locator-id"];
              RlocIp = rlocs[rlocIt]["rloc"][serviceInstance.getIPType(rlocs[rlocIt]["rloc"]["address-type"])];
              ListRlocs[RlocId].address = RlocIp;

          }
        }
      }

      return ListRlocs;
    };

    serviceInstance.getRlocInfo = function (RLOC_ID)
    {
      var obj = new Object();
      for (var i=0; i<Json.length; i++)
      {
          var eids = Json[i]["mapping"];
          for (var j = 0; j<eids.length; j++)
          {
            var rlocs = mappingRecord["LocatorRecord"];
            for (var rlocIt = 0; rlocIt <rlocs.length; rlocIt++) {
              if(RLOC_ID == rlocs[rlocIt]["locator-id"]){
                obj.id = rlocs[rlocIt]["locator-id"];
                obj.address = rlocs[rlocIt]["rloc"][serviceInstance.getIPType(rlocs[rlocIt]["rloc"]["address-type"])];
                obj.weight = rlocs[rlocIt]["weight"];
                obj.priority = rlocs[rlocIt]["priority"];
                obj.multicastweight = rlocs[rlocIt]["multicastWeight"];
                xtr_id = eids[j]["mapping-record"]["xtr-id"];
            }
          }
        }
      }
      return obj;
    };

    serviceInstance.getXTRInfo = function(action, xtrId)
    {
      var xtrInfo = [];
      var obj = new Object();
      for (var i=0; i<Json.length; i++)
      {
        obj.vni = Json[i]["vni"];
        obj.info = {}
        var eids = Json[i]["mapping"];
        switch(action)
        {
          case "EID":
            for (var j = 0; j<eids.length; j++)
            {
              var rlocs = eids["mapping-record"]["LocatorRecord"];
              for (var rlocIt=0; rlocIt<rlocs.length; rlocIt++)
              {
                var rlocIP = rlocs[rlocIt]["rloc"][serviceInstance.getIPType(rlocs[rlocIt]["rloc"]["address-type"])];
                obj.info[eids[j]["eid-uri"]].push(rlocIP);
              }
            }
            break;
          case "RLOC":
            for (var j = 0; j<eids.length; j++)
            {
              var rlocs = eids["mapping-record"]["LocatorRecord"];
              for (var rlocIt=0; rlocIt<rlocs.length; rlocIt++)
              {
                var rlocIP = rlocs[rlocIt]["rloc"][serviceInstance.getIPType(rlocs[rlocIt]["rloc"]["address-type"])];
                obj.info[rlocIP].push(eids[j]["eid-uri"]);
              }
            }
            break;
        }
        xtrInfo[i] = obj;
      }
      return xtrInfo;
    };

    return serviceInstance;
  }])
<commit_msg>get EidInfo RetardFail<commit_after>angular.module('lisp.communication', [])

  // Declaring the lisp service, which will contain all the functions we'll use to communicate with Lisp
  .factory('lispService', ['$http', '$q', function($http, $q) {
    var serviceInstance = {};

    // Info of all rlocs
    var listOfRlocs = {};
    // Donat un RLOC, té tot els EIDs que estan connectats
    var RLOCLinktedToEID = {};
    // Donat un EID, té tots els RLOCs als que està connectat
    var EidRLOC = {};
    // List with all vn-identifier
    var listOfVNI = [];
    // All Json info
    var Json = [];

    serviceInstance.getAllInfo = function(jsonObj) {
      //jsonObj has JSON response
      var virtualNetworks = jsonObj["mapping-database"]["virtual-network-identifier"];
      Json = virtualNetworks;
      for (var j=0; j<virtualNetworks.length; j++)
      {
        var vni = virtualNetworks[j]["vni"];
        listOfVNI.push(vni);
        var eids = virtualNetworks[j]["mapping"];
        for (var i = 0; i<eids.length; i++)
        {
          var eidInfo = eids[i]["mapping-record"]["eid"];
          var eid_uri =eids[i]["eid"];
          var mappingRecord = eids[i]["mapping-record"];
          var rlocs = mappingRecord["LocatorRecord"];
          var listEidRloc = [];
          for (var rlocIt = 0; rlocIt <rlocs.length; rlocIt++)
          {
            serviceInstance.addRlocToRlocList(rlocs[rlocIt]);
            listEidRloc.push(rlocs[rlocIt]["locator-id"]);
            serviceInstance.addRLOCToListRLOCLinktedToEID(rlocs[rlocIt],eid_uri);
          }
          EidRLOC[eids[i]["eid-uri"]] = listEidRloc;

          var typeIP = eids[i]["eid-uri"].split(":")[0];
        }
      }
    };

    serviceInstance.addRlocToRlocList = function(rloc){
      //check if rloc exists on listOfRlocs
      listOfRlocs[rloc["locator-id"]] = rloc;
    };

    serviceInstance.getRLOCsFromEID = function (eidUri)
    {

      return EidRLOC[eidUri];
    };

    serviceInstance.getAddressType = function (eidUri)
    {
      return "ietf-lisp-address-types:" + serviceInstance.getIPType(eidUri) + "-afi";
    };

    serviceInstance.getMappingEID = function (eidUri)
    {
      var addresType = serviceInstance.getAddressType(eidUri);
      var idType = serviceInstance.getIPType(eidUri);
      var ip = serviceInstance.getIP(eidUri);
    };

    serviceInstance.addRLOCToListRLOCLinktedToEID = function (rloc,eid)
    {
      //check if rloc exists on listOfRlocs
      if (RLOCLinktedToEID[rloc["locator-id"]] === undefined)
      {
        var aux = [];
      }
      else
      {
        var aux = RLOCLinktedToEID[rloc["locator-id"]];
      }
      aux.push(eid);
      RLOCLinktedToEID[rloc["locator-id"]] = aux;
    };

    serviceInstance.getEIDsFromRLOC = function (addressType, addressIP)
    {
      var EIDS = [];
      for (var i=0; i<Json.length; i++)
      {
        var mappingOfVNI = Json["mapping"];
        for (var j=0; j<mappingOfVNI.length;j++)
        {
          var locatorRecords = mappingOfVNI["LocatorRecord"];
          for (var z=0; z<locatorRecords.length;z++)
          {
            if (locatorRecords[z]["rloc"]["address-type"] == addressType)
            {
              var typeIP = addresType.split(":")[1].split("-")[0];
              if (locatorRecords[z]["rloc"][typeIP] == addressIP)
              {
                eids.push(mappingOfVNI[j]["eid-uri"])
              }
            }
          }
        }
      }
      return eids;
    };

    // First function to call: gets all the lisp database content and stores it in the service
    serviceInstance.initialize = function()
    {
      var deferred = $q.defer();
      var auth64 = btoa('admin:admin');

      $http({
            url: 'http://odl2.cba.upc.edu:8181/restconf/config/odl-mappingservice:mapping-database/',
            method: "GET",
            withCredentials: true,
            headers: {
                'Authorization': 'Basic '+ auth64
            }
        })
      .success(function(data) {

        serviceInstance.getAllInfo(data);
        deferred.resolve();

      }).error(function(msg, code) {

        deferred.reject(msg);

        console.log(msg);

      });

      return deferred.promise;

    };

    // Returns all EID contained in the service

    serviceInstance.getEidInfo = function(eidaddress){
      var EidInfo = {};
      var obj = new Object();
      for (var i=0; i<Json.length; i++)
      {
          var vni = Json[i]["vni"];
          var eids = Json[i]["mapping"];
          for (var j = 0; j<eids.length; j++)
          {
            var eid_uri = eids[j]["eid-uri"];

            if(eidaddress == getIP(eid_uri)){
              obj.xtr_id = eids[j]["mapping-record"]["xtr-id"];
              obj.address = serviceInstance.getIP(eid_uri);
              obj.address_type = serviceInstance.getIPType(eid_uri);
              obj.action = eids[j]["mapping-record"]["action"];
              EidInfo[vni] = obj;
              return EidInfo;
            }

        }
      }
    };

    serviceInstance.getAllVnIds = function() {
      return listOfVNI;
    };

    /* Function to get EIDs in VN
    ** Retun array with eid-uri of all EIDs in VN.
    ** Tip: Use getIPType and getIP functions to get info of eid-uri
    */
    serviceInstance.getEidsInVn = function(VnId)
    {
      var EIDinVN = [];
      for (var i=0; i<Json.length; i++)
      {
        if (Json[i]["vni"] == VnId)
        {
          var eids = Json[i]["mapping"];
          for (var i=0;i<eids.length;i++)
          {
            EIDinVN.push(eids[i]["eid-uri"]);
          }
        }
      }
      return EIDinVN;
    };

    serviceInstance.getAllEids = function()
    {
      var EidList = {};
      for (var i=0; i<Json.length; i++)
      {
          var eids = Json[i]["mapping"];
          var vni = Json[i]["vni"]
          var vectorEIds = new Object();
          for (var j = 0; j<eids.length; j++)
          {
            var obj = new Object();
            var eid_uri = eids[j]["eid-uri"];
            var xtr = eids[j]["mapping-record"]["xtr-id"];
            obj.vni = vni;
            obj.address = eid_uri;
            obj.xtr_id  = xtr;
            var rlocs = eids[j]["mapping-record"]["LocatorRecord"];
            var RLocAdr = [];
            for (var rlocIt = 0; rlocIt <rlocs.length; rlocIt++)
            {
              var typeIP = rlocs[rlocIt]["rloc"]["address-type"].split(":")[1].split("-")[0];
              RLocAdr.push(rlocs[rlocIt]["rloc"][typeIP]);
            }
            obj.rlocs = RLocAdr;
            vectorEIds.push(obj);
            if(j == (eids.length-1)) EidList[vni] = vectorEIds;
          }
        }
      return EidList;
    };

    serviceInstance.getIPType = function (eidUri)
    {
      return eidUri.split(":")[0];
    };

    serviceInstance.getIP = function (eidUri)
    {
      return eidUri.substring(eidUri.split(":")[0].length+1, eidUri.length);
    };

    serviceInstance.getRLOCs = function (vni, eid)
    {
      var rlocs = Json[vni]["mapping"][eid]["mapping-record"]["LocatorRecord"]
      var rloc_iterator;
      var rlocsOfEID;
      for (rloc_iterator = 0; rloc_iterator < rlocs.length; ++rloc_iterator)
      {
        rlocsOfEID.push(rlocs[rloc_iterator]);
      }
      return rlocsOfEID;
    };

    serviceInstance.getAllxtrids = function() {
      var vectorXTR = [];
      for (var i=0;i<Json.length;i++)
      {
        var eids = Json[i]["mapping"];
        for (var j = 0; j<eids.length; j++)
        {
          vectorXTR[eids[j]["xtr-id"]] = vectorXTR[eids[j]["xtr-id"]].push(getRLOCs(i,j))
        }
      }

      return vectorXTR;
    };

     serviceInstance.getXtridInfo = function(xtridAddress) {
         //info per definir
      return Info;
    };

    serviceInstance.getAllRlocs = function() {
      var ListRlocs = {};
      var RlocId;
      var RlocIp;
      for (var i=0; i<Json.length; i++)
      {
          var eids = Json[i]["mapping"];
          for (var j = 0; j<eids.length; j++)
          {
            var rlocs = mappingRecord["LocatorRecord"];
            for (var rlocIt = 0; rlocIt <rlocs.length; rlocIt++) {
              RlocId = rlocs[rlocIt]["locator-id"];
              RlocIp = rlocs[rlocIt]["rloc"][serviceInstance.getIPType(rlocs[rlocIt]["rloc"]["address-type"])];
              ListRlocs[RlocId].address = RlocIp;

          }
        }
      }

      return ListRlocs;
    };

    serviceInstance.getRlocInfo = function (RLOC_ID)
    {
      var obj = new Object();
      for (var i=0; i<Json.length; i++)
      {
          var eids = Json[i]["mapping"];
          for (var j = 0; j<eids.length; j++)
          {
            var rlocs = mappingRecord["LocatorRecord"];
            for (var rlocIt = 0; rlocIt <rlocs.length; rlocIt++) {
              if(RLOC_ID == rlocs[rlocIt]["locator-id"]){
                obj.id = rlocs[rlocIt]["locator-id"];
                obj.address = rlocs[rlocIt]["rloc"][serviceInstance.getIPType(rlocs[rlocIt]["rloc"]["address-type"])];
                obj.weight = rlocs[rlocIt]["weight"];
                obj.priority = rlocs[rlocIt]["priority"];
                obj.multicastweight = rlocs[rlocIt]["multicastWeight"];
                xtr_id = eids[j]["mapping-record"]["xtr-id"];
            }
          }
        }
      }
      return obj;
    };

    serviceInstance.getXTRInfo = function(action, xtrId)
    {
      var xtrInfo = [];
      var obj = new Object();
      for (var i=0; i<Json.length; i++)
      {
        obj.vni = Json[i]["vni"];
        obj.info = {}
        var eids = Json[i]["mapping"];
        switch(action)
        {
          case "EID":
            for (var j = 0; j<eids.length; j++)
            {
              var rlocs = eids["mapping-record"]["LocatorRecord"];
              for (var rlocIt=0; rlocIt<rlocs.length; rlocIt++)
              {
                var rlocIP = rlocs[rlocIt]["rloc"][serviceInstance.getIPType(rlocs[rlocIt]["rloc"]["address-type"])];
                obj.info[eids[j]["eid-uri"]].push(rlocIP);
              }
            }
            break;
          case "RLOC":
            for (var j = 0; j<eids.length; j++)
            {
              var rlocs = eids["mapping-record"]["LocatorRecord"];
              for (var rlocIt=0; rlocIt<rlocs.length; rlocIt++)
              {
                var rlocIP = rlocs[rlocIt]["rloc"][serviceInstance.getIPType(rlocs[rlocIt]["rloc"]["address-type"])];
                obj.info[rlocIP].push(eids[j]["eid-uri"]);
              }
            }
            break;
        }
        xtrInfo[i] = obj;
      }
      return xtrInfo;
    };

    return serviceInstance;
  }])
<|endoftext|>


<commit_before>/* FileSaver.js
 * A saveAs() FileSaver implementation.
 * 2011-08-02
 *
 * By Eli Grey, http://eligrey.com
 * License: X11/MIT
 *   See LICENSE.md
 */

/*global self */
/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
  plusplus: true */

/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */

var saveAs = saveAs || (function(view) {
	"use strict";
	var
		  doc = view.document
		  // only get URL when necessary in case BlobBuilder.js hasn't overridden it yet
		, get_URL = function() {
			return view.URL || view.webkitURL || view;
		}
		, URL = view.URL || view.webkitURL || view
		, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
		, can_use_save_link = "download" in save_link
		, click = function(node) {
			var event = doc.createEvent("MouseEvents");
			event.initMouseEvent(
				"click", true, false, view, 0, 0, 0, 0, 0
				, false, false, false, false, 0, null
			);
			return node.dispatchEvent(event); // false if event was cancelled
		}
		, webkit_req_fs = view.webkitRequestFileSystem
		, req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
		, throw_outside = function (ex) {
			(view.setImmediate || view.setTimeout)(function() {
				throw ex;
			}, 0);
		}
		, force_saveable_type = "application/octet-stream"
		, fs_min_size = 0
		, deletion_queue = []
		, process_deletion_queue = function() {
			var i = deletion_queue.length;
			while (i--) {
				var file = deletion_queue[i];
				if (typeof file === "string") { // file is an object URL
					URL.revokeObjectURL(file);
				} else { // file is a File
					file.remove();
				}
			}
			deletion_queue.length = 0; // clear queue
		}
		, dispatch = function(filesaver, event_types, event) {
			event_types = [].concat(event_types);
			var i = event_types.length;
			while (i--) {
				var listener = filesaver["on" + event_types[i]];
				if (typeof listener === "function") {
					try {
						listener.call(filesaver, event || filesaver);
					} catch (ex) {
						throw_outside(ex);
					}
				}
			}
		}
		, FileSaver = function(blob, name) {
			// First try a.download, then web filesystem, then object URLs
			var
				  filesaver = this
				, type = blob.type
				, blob_changed = false
				, object_url
				, target_view
				, get_object_url = function() {
					var object_url = get_URL().createObjectURL(blob);
					deletion_queue.push(object_url);
					return object_url;
				}
				, dispatch_all = function() {
					dispatch(filesaver, "writestart progress write writeend".split(" "));
				}
				// on any filesys errors revert to saving with object URLs
				, fs_error = function() {
					// don't create more object URLs than needed
					if (blob_changed || !object_url) {
						object_url = get_object_url(blob);
					}
					target_view.location.href = object_url;
					filesaver.readyState = filesaver.DONE;
					dispatch_all();
				}
				, abortable = function(func) {
					return function() {
						if (filesaver.readyState !== filesaver.DONE) {
							return func.apply(this, arguments);
						}
					};
				}
				, create_if_not_found = {create: true, exclusive: false}
				, slice
			;
			filesaver.readyState = filesaver.INIT;
			if (!name) {
				name = "download";
			}
			if (can_use_save_link) {
				object_url = get_object_url(blob);
				save_link.href = object_url;
				save_link.download = name;
				if (click(save_link)) {
					filesaver.readyState = filesaver.DONE;
					dispatch_all();
					return;
				}
			}
			// Object and web filesystem URLs have a problem saving in Google Chrome when
			// viewed in a tab, so I force save with application/octet-stream
			// http://code.google.com/p/chromium/issues/detail?id=91158
			if (view.chrome && type && type !== force_saveable_type) {
				slice = blob.slice || blob.webkitSlice;
				blob = slice.call(blob, 0, blob.size, force_saveable_type);
				blob_changed = true;
			}
			// Since I can't be sure that the guessed media type will trigger a download
			// in WebKit, I append .download to the filename.
			// https://bugs.webkit.org/show_bug.cgi?id=65440
			if (webkit_req_fs && name !== "download") {
				name += ".download";
			}
			if (type === force_saveable_type || webkit_req_fs) {
				target_view = view;
			} else {
				target_view = view.open();
			}
			if (!req_fs) {
				fs_error();
				return;
			}
			fs_min_size += blob.size;
			req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
				fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
					var save = function() {
						dir.getFile(name, create_if_not_found, abortable(function(file) {
							file.createWriter(abortable(function(writer) {
								writer.onwriteend = function(event) {
									target_view.location.href = file.toURL();
									deletion_queue.push(file);
									filesaver.readyState = filesaver.DONE;
									dispatch(filesaver, "writeend", event);
								};
								writer.onerror = function() {
									var error = writer.error;
									if (error.code !== error.ABORT_ERR) {
										fs_error();
									}
								};
								"writestart progress write abort".split(" ").forEach(function(event) {
									writer["on" + event] = filesaver["on" + event];
								});
								writer.write(blob);
								filesaver.abort = function() {
									writer.abort();
									filesaver.readyState = filesaver.DONE;
								};
								filesaver.readyState = filesaver.WRITING;
							}), fs_error);
						}), fs_error);
					};
					dir.getFile(name, {create: false}, abortable(function(file) {
						// delete file if it already exists
						file.remove();
						save();
					}), abortable(function(ex) {
						if (ex.code === ex.NOT_FOUND_ERR) {
							save();
						} else {
							fs_error();
						}
					}));
				}), fs_error);
			}), fs_error);
		}
		, FS_proto = FileSaver.prototype
		, saveAs = function(blob, name) {
			return new FileSaver(blob, name);
		}
	;
	FS_proto.abort = function() {
		var filesaver = this;
		filesaver.readyState = filesaver.DONE;
		dispatch(filesaver, "abort");
	};
	FS_proto.readyState = FS_proto.INIT = 0;
	FS_proto.WRITING = 1;
	FS_proto.DONE = 2;

	FS_proto.error =
	FS_proto.onwritestart =
	FS_proto.onprogress =
	FS_proto.onwrite =
	FS_proto.onabort =
	FS_proto.onerror =
	FS_proto.onwriteend =
		null;

	view.addEventListener("unload", process_deletion_queue, false);
	return saveAs;
}(self));<commit_msg>Added IE10 support<commit_after>/* FileSaver.js
 * A saveAs() FileSaver implementation.
 * 2012-12-11
 *
 * By Eli Grey, http://eligrey.com
 * License: X11/MIT
 *   See LICENSE.md
 */

/*global self */
/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
  plusplus: true */

/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */

var saveAs = saveAs
  || (navigator.msSaveOrOpenBlob && navigator.msSaveOrOpenBlob.bind(navigator))
  || (function(view) {
	"use strict";
	var
		  doc = view.document
		  // only get URL when necessary in case BlobBuilder.js hasn't overridden it yet
		, get_URL = function() {
			return view.URL || view.webkitURL || view;
		}
		, URL = view.URL || view.webkitURL || view
		, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
		, can_use_save_link = "download" in save_link
		, click = function(node) {
			var event = doc.createEvent("MouseEvents");
			event.initMouseEvent(
				"click", true, false, view, 0, 0, 0, 0, 0
				, false, false, false, false, 0, null
			);
			return node.dispatchEvent(event); // false if event was cancelled
		}
		, webkit_req_fs = view.webkitRequestFileSystem
		, req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
		, throw_outside = function (ex) {
			(view.setImmediate || view.setTimeout)(function() {
				throw ex;
			}, 0);
		}
		, force_saveable_type = "application/octet-stream"
		, fs_min_size = 0
		, deletion_queue = []
		, process_deletion_queue = function() {
			var i = deletion_queue.length;
			while (i--) {
				var file = deletion_queue[i];
				if (typeof file === "string") { // file is an object URL
					URL.revokeObjectURL(file);
				} else { // file is a File
					file.remove();
				}
			}
			deletion_queue.length = 0; // clear queue
		}
		, dispatch = function(filesaver, event_types, event) {
			event_types = [].concat(event_types);
			var i = event_types.length;
			while (i--) {
				var listener = filesaver["on" + event_types[i]];
				if (typeof listener === "function") {
					try {
						listener.call(filesaver, event || filesaver);
					} catch (ex) {
						throw_outside(ex);
					}
				}
			}
		}
		, FileSaver = function(blob, name) {
			// First try a.download, then web filesystem, then object URLs
			var
				  filesaver = this
				, type = blob.type
				, blob_changed = false
				, object_url
				, target_view
				, get_object_url = function() {
					var object_url = get_URL().createObjectURL(blob);
					deletion_queue.push(object_url);
					return object_url;
				}
				, dispatch_all = function() {
					dispatch(filesaver, "writestart progress write writeend".split(" "));
				}
				// on any filesys errors revert to saving with object URLs
				, fs_error = function() {
					// don't create more object URLs than needed
					if (blob_changed || !object_url) {
						object_url = get_object_url(blob);
					}
					target_view.location.href = object_url;
					filesaver.readyState = filesaver.DONE;
					dispatch_all();
				}
				, abortable = function(func) {
					return function() {
						if (filesaver.readyState !== filesaver.DONE) {
							return func.apply(this, arguments);
						}
					};
				}
				, create_if_not_found = {create: true, exclusive: false}
				, slice
			;
			filesaver.readyState = filesaver.INIT;
			if (!name) {
				name = "download";
			}
			if (can_use_save_link) {
				object_url = get_object_url(blob);
				save_link.href = object_url;
				save_link.download = name;
				if (click(save_link)) {
					filesaver.readyState = filesaver.DONE;
					dispatch_all();
					return;
				}
			}
			// Object and web filesystem URLs have a problem saving in Google Chrome when
			// viewed in a tab, so I force save with application/octet-stream
			// http://code.google.com/p/chromium/issues/detail?id=91158
			if (view.chrome && type && type !== force_saveable_type) {
				slice = blob.slice || blob.webkitSlice;
				blob = slice.call(blob, 0, blob.size, force_saveable_type);
				blob_changed = true;
			}
			// Since I can't be sure that the guessed media type will trigger a download
			// in WebKit, I append .download to the filename.
			// https://bugs.webkit.org/show_bug.cgi?id=65440
			if (webkit_req_fs && name !== "download") {
				name += ".download";
			}
			if (type === force_saveable_type || webkit_req_fs) {
				target_view = view;
			} else {
				target_view = view.open();
			}
			if (!req_fs) {
				fs_error();
				return;
			}
			fs_min_size += blob.size;
			req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
				fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
					var save = function() {
						dir.getFile(name, create_if_not_found, abortable(function(file) {
							file.createWriter(abortable(function(writer) {
								writer.onwriteend = function(event) {
									target_view.location.href = file.toURL();
									deletion_queue.push(file);
									filesaver.readyState = filesaver.DONE;
									dispatch(filesaver, "writeend", event);
								};
								writer.onerror = function() {
									var error = writer.error;
									if (error.code !== error.ABORT_ERR) {
										fs_error();
									}
								};
								"writestart progress write abort".split(" ").forEach(function(event) {
									writer["on" + event] = filesaver["on" + event];
								});
								writer.write(blob);
								filesaver.abort = function() {
									writer.abort();
									filesaver.readyState = filesaver.DONE;
								};
								filesaver.readyState = filesaver.WRITING;
							}), fs_error);
						}), fs_error);
					};
					dir.getFile(name, {create: false}, abortable(function(file) {
						// delete file if it already exists
						file.remove();
						save();
					}), abortable(function(ex) {
						if (ex.code === ex.NOT_FOUND_ERR) {
							save();
						} else {
							fs_error();
						}
					}));
				}), fs_error);
			}), fs_error);
		}
		, FS_proto = FileSaver.prototype
		, saveAs = function(blob, name) {
			return new FileSaver(blob, name);
		}
	;
	FS_proto.abort = function() {
		var filesaver = this;
		filesaver.readyState = filesaver.DONE;
		dispatch(filesaver, "abort");
	};
	FS_proto.readyState = FS_proto.INIT = 0;
	FS_proto.WRITING = 1;
	FS_proto.DONE = 2;

	FS_proto.error =
	FS_proto.onwritestart =
	FS_proto.onprogress =
	FS_proto.onwrite =
	FS_proto.onabort =
	FS_proto.onerror =
	FS_proto.onwriteend =
		null;

	view.addEventListener("unload", process_deletion_queue, false);
	return saveAs;
}(self));<|endoftext|>


<commit_before>{"text":"V2","color":"00cc33"}
<commit_msg>update for v1<commit_after>{"text":"V1","color":"0099cc"}
<|endoftext|>


<commit_before>var height = 300,
    width = 300,
    margin = {left: 10, right: 50, top: 15, bottom: 15};

var svg = d3.select('body')
  .append('svg')
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")

var numPoints = 20,
    squareSize = 50,
    radius = 5;

var circleY = d3.scale.linear()
      .domain([0, numPoints - 1])
      .range([0, height]),
    rect1Y = circleY.copy()
      .range([height*1/3 + 1, height*1/3 + squareSize - 1]),
    rect2Y = circleY.copy()
      .range([height*2/3 + 1, height*2/3 + squareSize - 1]);

svg.append('rect')
    .attr({x: width, y: height*1/3, width: squareSize, height: squareSize})
svg.append('rect')
    .attr({x: width, y: height*2/3, width: squareSize, height: squareSize})

var rect1Points = d3.range(numPoints).filter(function(d){
  return Math.random()*numPoints > d; });
rect1Y.domain([0, rect1Points.length - 1])
svg.selectAll('path')
    .data(rect1Points).enter()
  .append('path')
    .attr('d', function(d, i){
      var p1 = [0,      circleY(d) - radius],    //start [x, y] cord
          p2 = [width,  rect1Y(i)],              //end   [x, y] cord
          c1 = p1.slice(),                       //control point cord
          c2 = p2.slice();                       //control point cord

      //move both control points towards the middle
      c1[0] += width/3;
      c2[0] -= width/3;
      return ['M', p1, 'C', c1, ' ', c2, ' ', p2].join('');
    })
    .each(function(){
      var pathLength = this.getTotalLength();
      d3.select(this)
          .attr('stroke-dasharray', pathLength + ' ' + pathLength)
          .attr('stroke-dashoffset', pathLength)
    })
  .transition().duration(2000).delay(function(d){ return d/numPoints*2000; })
    .attr('stroke-dashoffset', 0);

var rect2Points = d3.range(numPoints).filter(function(d){
  return Math.random()*numPoints < d || !_.contains(rect1Points, d); });
rect2Y.domain([0, rect2Points.length - 1])
svg.selectAll('.rect2Path')
    .data(rect2Points).enter()
  .append('path')
    .attr('d', function(d, i){
      var p1 = [0,      circleY(d) + radius],        //start [x, y] cord
          p2 = [width,  rect2Y(i)],                  //end   [x, y] cord
          c1 = p1.slice(),                           //control point cord
          c2 = p2.slice();                           //control point cord

      //move both control point
      c1[0] += width/3;
      c2[0] -= width/3;

      return ['M', p1, 'C', c1, ' ', c2, ' ', p2].join('');
    })
    .each(function(){
      var pathLength = this.getTotalLength();
      d3.select(this)
          .attr('stroke-dasharray', pathLength + ' ' + pathLength)
          .attr('stroke-dashoffset', pathLength)
    })
  .transition().duration(2000).delay(function(d){ return d/numPoints*2000; })
    .attr('stroke-dashoffset', 0);

svg.selectAll('circle')
    .data(d3.range(numPoints)).enter()
  .append('circle')
    .attr('r', radius)
    .attr('cy', circleY)
    .on('mousemove', function(d){
      d3.selectAll('path').filter(function(e){ return d === e; })
          .each(function(){
            var path = this;
            svg.append('text')
                .text('$')
                .attr('dy', '.33em')
                .attr('text-align', 'end')
              .transition().duration(2000)
                .tween('position', function(){
                  var pathLength = path.getTotalLength();
                  return function(t){
                    var pos = path.getPointAtLength(t*pathLength);
                    d3.select(this)
                      .attr({x: pos.x, y: pos.y})
                  }
                })
              .transition()
                .style('opacity', 0)
                .remove();
          })
    })

//Simple quadratic bezier from p1 to p2
// var p1 = [30, 30],
//     p2 = [400, 250]
//     c1 = p1.slice(),
//     c2 = p2.slice();

// c1[0] += 250;
// c2[0] -= 250;

// svg.append('circle').attr({r: 10, cx: p1[0], cy: p1[1]})
// svg.append('circle').attr({r: 10, cx: p2[0], cy: p2[1]})

// pathStr = ['M', p1, 'C', c1, ' ', c2, ' ', p2].join('');

// svg.append('path')
//     .attr('d', pathStr);

//Cubic bezier
//"M" + p1.x + ' ' p1.y + "C" + p[1] + " " + p[2] + " " + p[3]
// var pathStr = ['M', p1.x, ',', p1.y, ' C', p2.x, ',', p2.y, ' ', 12, ',', 34, ' S400,300 400,200']
// .join('')

// pathStr = ['M', p1, 'C100,100 250,100 250,200 S400,300 ', p2].join('');<commit_msg>d3 timer<commit_after>var height = 300,
    width = 300,
    margin = {left: 10, right: 50, top: 15, bottom: 15};

var svg = d3.select('body')
  .append('svg')
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")

var numPoints = 20,
    squareSize = 50,
    radius = 5;

var circleY = d3.scale.linear()
      .domain([0, numPoints - 1])
      .range([0, height]),
    rect1Y = circleY.copy()
      .range([height*1/3 + 1, height*1/3 + squareSize - 1]),
    rect2Y = circleY.copy()
      .range([height*2/3 + 1, height*2/3 + squareSize - 1]);

svg.append('rect')
    .attr({x: width, y: height*1/3, width: squareSize, height: squareSize})
svg.append('rect')
    .attr({x: width, y: height*2/3, width: squareSize, height: squareSize})

var rect1Points = d3.range(numPoints).filter(function(d){
  return Math.random()*numPoints > d; });
rect1Y.domain([0, rect1Points.length - 1])
svg.selectAll('path')
    .data(rect1Points).enter()
  .append('path')
    .attr('d', function(d, i){
      var p1 = [0,      circleY(d) - radius],    //start [x, y] cord
          p2 = [width,  rect1Y(i)],              //end   [x, y] cord
          c1 = p1.slice(),                       //control point cord
          c2 = p2.slice();                       //control point cord

      //move both control points towards the middle
      c1[0] += width/3;
      c2[0] -= width/3;
      return ['M', p1, 'C', c1, ' ', c2, ' ', p2].join('');
    })
    .each(function(){
      var pathLength = this.getTotalLength();
      d3.select(this)
          .attr('stroke-dasharray', pathLength + ' ' + pathLength)
          .attr('stroke-dashoffset', pathLength)
    })
  .transition().duration(2000).delay(function(d){ return d/numPoints*2000; })
    .attr('stroke-dashoffset', 0);

var rect2Points = d3.range(numPoints).filter(function(d){
  return Math.random()*numPoints < d || !_.contains(rect1Points, d); });
rect2Y.domain([0, rect2Points.length - 1])
svg.selectAll('.rect2Path')
    .data(rect2Points).enter()
  .append('path')
    .attr('d', function(d, i){
      var p1 = [0,      circleY(d) + radius],        //start [x, y] cord
          p2 = [width,  rect2Y(i)],                  //end   [x, y] cord
          c1 = p1.slice(),                           //control point cord
          c2 = p2.slice();                           //control point cord

      //move both control point
      c1[0] += width/3;
      c2[0] -= width/3;

      return ['M', p1, 'C', c1, ' ', c2, ' ', p2].join('');
    })
    .each(function(){
      var pathLength = this.getTotalLength();
      d3.select(this)
          .attr('stroke-dasharray', pathLength + ' ' + pathLength)
          .attr('stroke-dashoffset', pathLength)
    })
  .transition().duration(2000).delay(function(d){ return d/numPoints*2000; })
    .attr('stroke-dashoffset', 0);

svg.selectAll('circle')
    .data(d3.range(numPoints)).enter()
  .append('circle')
    .attr('r', radius)
    .attr('cy', circleY)
    .on('mousemove', function(d){
      d3.selectAll('path').filter(function(e){ return d === e; })
          .each(function(){
            var path = this;
            var pos = path.getPointAtLength(0);
            svg.append('text')
                .text('$')
                .attr('dy', '.33em')
                .attr('text-align', 'end')
                .attr({x: pos.x, y: pos.y})
              .transition().duration(2000).ease('linear')
                .tween('position', function(){
                  var pathLength = path.getTotalLength();
                  return function(t){
                    var pos = path.getPointAtLength(t*pathLength);
                    d3.select(this)
                      .attr({x: pos.x, y: pos.y})
                  }
                })
              .transition().duration(1000)
                .attr('x', width + squareSize)
                .style('opacity', 0)
                .remove();
          })
    })

var lastT = 4000;
d3.timer(function(t){
  if (t < lastT ){ return; }
  lastT += 100;
  var selected = Math.floor(Math.random()*numPoints);
  var circle = svg.selectAll('circle').filter(function(d){ return d === selected; })

  circle.on('mousemove').call(circle.node(), selected)
})

//Simple quadratic bezier from p1 to p2
// var p1 = [30, 30],
//     p2 = [400, 250]
//     c1 = p1.slice(),
//     c2 = p2.slice();

// c1[0] += 250;
// c2[0] -= 250;

// svg.append('circle').attr({r: 10, cx: p1[0], cy: p1[1]})
// svg.append('circle').attr({r: 10, cx: p2[0], cy: p2[1]})

// pathStr = ['M', p1, 'C', c1, ' ', c2, ' ', p2].join('');

// svg.append('path')
//     .attr('d', pathStr);

//Cubic bezier
//"M" + p1.x + ' ' p1.y + "C" + p[1] + " " + p[2] + " " + p[3]
// var pathStr = ['M', p1.x, ',', p1.y, ' C', p2.x, ',', p2.y, ' ', 12, ',', 34, ' S400,300 400,200']
// .join('')

// pathStr = ['M', p1, 'C100,100 250,100 250,200 S400,300 ', p2].join('');<|endoftext|>


<commit_before>var spawn = require('child_process').spawn,
    http = require('http'),
    urlmod = require('url'),
    fs = require('fs');
var logLevel = 1;
var vidProc,
    player,
    vidProcLog = '',
    files = [],
    currFile = 0,
    playing = false;
var localAddress = '',
    remoteAddress = '',
    port = 3000,
    req,
    res;

// INIT ////////////////////////////////////

// standardized exit function
var exitFunction = function (code) {
    console.log('exiting vidcomm');
    if (code) console.log('exited with code '+code);
    if (vidProcLog.length) console.log(vidProcLog);
    // show cursor
    console.log('\033[?12l\033[?25h');
}

var echo = function (msg) {
    if (logLevel > 0) console.log(msg);
}

// HTTP SERVER /////////////////////////////

// find local ip address
var findLocalAddress = function () {
    echo('find local address');
    require('child_process').exec('ifconfig eth0 | grep \'inet addr:\' | cut -d: -f2 | awk \'{ print $1}\'', function (error, stdout, stderr) {
        if (stdout.search(/192\.168\.1\.\d+/) !== -1) {
            localAddress = stdout;
            echo(localAddress);
            startServer();
        } else {
            echo('couldn\'t find local ip address. letting server down.');
            playNextVideo();
        }
    });
}

// start local http server
var startServer = function () {
    echo('start server');
    http.createServer(function (req_, res_) {
        req = req_;
        res = res_;
        if (req.method === 'GET') {
            req.on('close', function() { echo('connection closed'); });
            req.on('data', function(data) { /* void */ });
            req.on('end', function() { parseRequest(); });
        } else {
            echo('error: no accepted HTTP method');
            respond('no');
        }
    }).listen(port, localAddress);
    echo('server running at http://'+localAddress+':'+port);
    // query remote server for status
    queryRemote('playing');
}

// parse incoming http requests
var parseRequest = function () {
    echo('parse request');
    var url = urlmod.parse(req.url);
    if (url.href) {
        var cmd = url.href.slice(1);
        echo(cmd);
        if (cmd === 'playing') respond(isPlaying());
        else if (cmd === 'ended') playNextVideo();
        else respond('bad command');
    } else {
        echo('bad url '+url);
        respond('error: bad url');
    }
}

// respond to remote http requests
var respond = function (data) {
    echo('respond '+ data);
    var headers = {
        'Content-Length': Buffer.byteLength(data),
        'Content-Type': 'text/plain; charset=utf-8',
        'Expires': (new Date(Date.now)).toUTCString()
    }
    res.writeHead(200, headers);
    res.end(data);
}

// REMOTE QUERIES //////////////////////////

// query remote server
var queryRemote = function (query) {
    echo('query remote '+ query);
    var url = 'http://'+remoteAddress+':'+port+'/'+query;
    http.get(url, function(res_) {
        res_.on('data', function (data) { parseServerResponse(data) });
    }).on('error', function(e) {
        echo(e);
    });
}

// parse remote server's response to query
var parseServerResponse = function (data) {
    echo('parse server response '+ data);
    if (data == 'no') {
        // remote is not playing, play local file
        echo('remote is not playing, play local file');
        playNextVideo();
    } else {
        echo('remote is playing, wait for remote message, so, do nothing');
        // wait for remote message, so, do nothing
    }
}

// VIDEO ///////////////////////////////////

// establish video playing status
var isPlaying = function () {
    if (playing) return 'yes';
    else return 'no';
}

// play video files
var playNextVideo = function () {
    // next file to play
    var filename = files[currFile++];
    // if it doesn't exist, reset filename to the first one
    if (!filename) filename = files[0];
    // play only if the file exists
    if (!filename) {
        console.log('vidcomm playback ended');
        exitFunction();
        process.exit(0);
    } else {
        playing = true;
        echo('play video '+filename);
        vidProc = (player === 'omxplayer') ? spawn('omxplayer', ['-o', 'local', filename]) : spawn('mplayer', ['-vm', filename]);
        vidProc.stdout.on('data', function (data) { vidProcLog += data; });
        vidProc.stderr.on('data', function (data) { vidProcLog += data; });
        vidProc.on('exit', function (code) {
            playing = false;
            echo(player+' exited with code '+code);
            queryRemote('ended');
        });
    }
}

// PROCESS /////////////////////////////////

// parse process' incoming arguments
var parseArgv = function () {
    echo('parse argv');
    var conf;
    files = [];

    // parse arguments
    if (process.argv.length < 3) {
        // no arguments case
        conf = 'vidcomm.conf';
    } else {
        process.argv.forEach(function (val, idx, arr) {
            if (val.search(/^\.*[^\.]+\.conf$/) !== -1) {
                // configuration file case
                conf = val;
                // readConf();
            } else if (val.search(/^\.*[^\.]+\.(mp4|m4v|mov)$/) !== -1) {
                // video filename case
                files.push(val);
            } else if (val.search(/192\.168\.1\.\d+/) !== -1) {
                // remote address case
                remoteAddress = val;
            }
        });
    }

    // if a configuration file was given
    if (conf) {
        var data = fs.readFileSync(conf, {encoding:'utf-8'});
        if (data.length) {
            data.split('\n').forEach(function (val, idx, arr) {
                if (val.search(/^\.*[^\.]+\.(mp4|m4v|mov)$/) !== -1) {
                    // video filename case
                    files.push(val);
                } else if (val.search(/192\.168\.1\.\d+/) !== -1) {
                    // remote address case
                    remoteAddress = val;
                }
            });
        }
    }

    // if video files were given
    if (files.length) {
        // clear terminal, move cursor to top left and hide it
        // console.log('\033[2J\033\033[H\033[?25l');

        // if a remote server address was given
        if (remoteAddress.length) {
            findLocalAddress();
        } else {
            playNextVideo();
        }
    }

    // failsafe
    if (!conf && !files.length) {
        exitFunction();
        process.exit(1);
    }
}

// check whether other vidcomm process is running on the system
var checkForDuplicates = function () {
    echo('check for duplicates');
    require('child_process').exec('ps aux | grep '+player+' | grep -v grep', function (error, stdout, stderr) {
        if (stdout.length) {
            console.log('a video player is already running on this machine.');
            console.log(stdout);
            exitFunction();
            process.exit(1);
        } else {
            echo('vidcomm starting.');
            parseArgv();
        }
    });
}

// handle ctrl-C gracefully
process.on('SIGINT', function () {
    console.log(' ');
    exitFunction();
    process.exit(1);
});

// START ///////////////////////////////////

// check which player is available on the system
require('child_process').exec('which omxplayer', function (error, stdout, stderr) {
    if (stdout[0] !== '/') {
        require('child_process').exec('which mplayer', function (error, stdout, stderr) {
            if (stdout[0] !== '/') {
                console.log('no video player available.');
                exitFunction();
                process.exit(1);
            } else {
                player = 'mplayer';
                echo('player is '+player);
                checkForDuplicates();
            }
        });
    } else {
        player = 'omxplayer';
        echo('player is '+player);
        checkForDuplicates();
    }
});<commit_msg>testing network error status<commit_after>var spawn = require('child_process').spawn,
    http = require('http'),
    urlmod = require('url'),
    fs = require('fs');
var logLevel = 1;
var vidProc,
    player,
    vidProcLog = '',
    files = [],
    currFile = 0,
    playing = false;
var localAddress = '',
    remoteAddress = '',
    port = 3000,
    req,
    res;

// INIT ////////////////////////////////////

// standardized exit function
var exitFunction = function (code) {
    console.log('exiting vidcomm');
    if (code) console.log('exited with code '+code);
    if (vidProcLog.length) console.log(vidProcLog);
    // show cursor
    console.log('\033[?12l\033[?25h');
}

var echo = function (msg) {
    if (logLevel > 0) console.log(msg);
}

// HTTP SERVER /////////////////////////////

// find local ip address
var findLocalAddress = function () {
    echo('find local address');
    require('child_process').exec('ifconfig eth0 | grep \'inet addr:\' | cut -d: -f2 | awk \'{ print $1}\'', function (error, stdout, stderr) {
        if (stdout.search(/192\.168\.1\.\d+/) !== -1) {
            localAddress = stdout;
            echo(localAddress);
            startServer();
        } else {
            echo('couldn\'t find local ip address. letting server down.');
            playNextVideo();
        }
    });
}

// start local http server
var startServer = function () {
    echo('start server');
    http.createServer(function (req_, res_) {
        req = req_;
        res = res_;
        if (req.method === 'GET') {
            req.on('close', function() { echo('connection closed'); });
            req.on('data', function(data) { /* void */ });
            req.on('end', function() { parseRequest(); });
        } else {
            echo('error: no accepted HTTP method');
            respond('no');
        }
    }).listen(port, localAddress);
    echo('server running at http://'+localAddress+':'+port);
    // query remote server for status
    queryRemote('playing');
}

// parse incoming http requests
var parseRequest = function () {
    echo('parse request');
    var url = urlmod.parse(req.url);
    if (url.href) {
        var cmd = url.href.slice(1);
        echo(cmd);
        if (cmd === 'playing') respond(isPlaying());
        else if (cmd === 'ended') playNextVideo();
        else respond('bad command');
    } else {
        echo('bad url '+url);
        respond('error: bad url');
    }
}

// respond to remote http requests
var respond = function (data) {
    echo('respond '+ data);
    var headers = {
        'Content-Length': Buffer.byteLength(data),
        'Content-Type': 'text/plain; charset=utf-8',
        'Expires': (new Date(Date.now)).toUTCString()
    }
    res.writeHead(200, headers);
    res.end(data);
}

// REMOTE QUERIES //////////////////////////

// query remote server
var queryRemote = function (query) {
    echo('query remote '+ query);
    var url = 'http://'+remoteAddress+':'+port+'/'+query;
    http.get(url, function(res_) {
        res_.on('data', function (data) { parseServerResponse(data) });
    }).on('error', function(e) {
        echo(e.code);
    });
}

// parse remote server's response to query
var parseServerResponse = function (data) {
    echo('parse server response '+ data);
    if (data == 'no') {
        // remote is not playing, play local file
        echo('remote is not playing, play local file');
        playNextVideo();
    } else {
        echo('remote is playing, wait for remote message, so, do nothing');
        // wait for remote message, so, do nothing
    }
}

// VIDEO ///////////////////////////////////

// establish video playing status
var isPlaying = function () {
    if (playing) return 'yes';
    else return 'no';
}

// play video files
var playNextVideo = function () {
    // next file to play
    var filename = files[currFile++];
    // if it doesn't exist, reset filename to the first one
    if (!filename) filename = files[0];
    // play only if the file exists
    if (!filename) {
        console.log('vidcomm playback ended');
        exitFunction();
        process.exit(0);
    } else {
        playing = true;
        echo('play video '+filename);
        vidProc = (player === 'omxplayer') ? spawn('omxplayer', ['-o', 'local', filename]) : spawn('mplayer', ['-vm', filename]);
        vidProc.stdout.on('data', function (data) { vidProcLog += data; });
        vidProc.stderr.on('data', function (data) { vidProcLog += data; });
        vidProc.on('exit', function (code) {
            playing = false;
            echo(player+' exited with code '+code);
            queryRemote('ended');
        });
    }
}

// PROCESS /////////////////////////////////

// parse process' incoming arguments
var parseArgv = function () {
    echo('parse argv');
    var conf;
    files = [];

    // parse arguments
    if (process.argv.length < 3) {
        // no arguments case
        conf = 'vidcomm.conf';
    } else {
        process.argv.forEach(function (val, idx, arr) {
            if (val.search(/^\.*[^\.]+\.conf$/) !== -1) {
                // configuration file case
                conf = val;
                // readConf();
            } else if (val.search(/^\.*[^\.]+\.(mp4|m4v|mov)$/) !== -1) {
                // video filename case
                files.push(val);
            } else if (val.search(/192\.168\.1\.\d+/) !== -1) {
                // remote address case
                remoteAddress = val;
            }
        });
    }

    // if a configuration file was given
    if (conf) {
        var data = fs.readFileSync(conf, {encoding:'utf-8'});
        if (data.length) {
            data.split('\n').forEach(function (val, idx, arr) {
                if (val.search(/^\.*[^\.]+\.(mp4|m4v|mov)$/) !== -1) {
                    // video filename case
                    files.push(val);
                } else if (val.search(/192\.168\.1\.\d+/) !== -1) {
                    // remote address case
                    remoteAddress = val;
                }
            });
        }
    }

    // if video files were given
    if (files.length) {
        // clear terminal, move cursor to top left and hide it
        // console.log('\033[2J\033\033[H\033[?25l');

        // if a remote server address was given
        if (remoteAddress.length) {
            findLocalAddress();
        } else {
            playNextVideo();
        }
    }

    // failsafe
    if (!conf && !files.length) {
        exitFunction();
        process.exit(1);
    }
}

// check whether other vidcomm process is running on the system
var checkForDuplicates = function () {
    echo('check for duplicates');
    require('child_process').exec('ps aux | grep '+player+' | grep -v grep', function (error, stdout, stderr) {
        if (stdout.length) {
            console.log('a video player is already running on this machine.');
            console.log(stdout);
            exitFunction();
            process.exit(1);
        } else {
            echo('vidcomm starting.');
            parseArgv();
        }
    });
}

// handle ctrl-C gracefully
process.on('SIGINT', function () {
    console.log(' ');
    exitFunction();
    process.exit(1);
});

// START ///////////////////////////////////

// check which player is available on the system
require('child_process').exec('which omxplayer', function (error, stdout, stderr) {
    if (stdout[0] !== '/') {
        require('child_process').exec('which mplayer', function (error, stdout, stderr) {
            if (stdout[0] !== '/') {
                console.log('no video player available.');
                exitFunction();
                process.exit(1);
            } else {
                player = 'mplayer';
                echo('player is '+player);
                checkForDuplicates();
            }
        });
    } else {
        player = 'omxplayer';
        echo('player is '+player);
        checkForDuplicates();
    }
});<|endoftext|>


<commit_before>window.GOVUK = window.GOVUK || {};
window.GOVUK.Modules = window.GOVUK.Modules || {};

(function (global, GOVUK) {
  'use strict';

  GOVUK.Modules.RemoveFilter = function () {
    var onChangeSuppressAnalytics = {
      type: "change",
      suppressAnalytics: true
    }

    this.start = function (element) {
      $(element).on('click', '[data-module="remove-filter-link"]', toggleFilter);
    };

    function toggleFilter(e) {
      e.preventDefault();
      e.stopPropagation();
      var $el = $(e.target);

      var removeFilterName = $el.data('name');
      var removeFilterValue = $el.data('value');
      var removeFilterLabel = $el.data('track-label');
      var removeFilterFacet = $el.data('facet');

      var $input = getInput(removeFilterName, removeFilterValue, removeFilterFacet);
      fireRemoveTagTrackingEvent(removeFilterLabel, removeFilterFacet);
      clearFacet($input, removeFilterValue, removeFilterFacet);
    }

    function clearFacet($input, removeFilterValue, removeFilterFacet) {
      var elementType = $input.prop('tagName');
      var inputType = $input.prop('type');
      var currentVal = $input.val();

      if (inputType == 'checkbox') {
        $input.prop("checked", false);
        $input.trigger(onChangeSuppressAnalytics);
      }
      else if (inputType == 'text' || inputType == 'search') {
        var haystack = ' ' + currentVal.trim() + ' ';
        var needle = ' ' + decodeEntities(removeFilterValue.toString()) + ' ';
        var newVal = haystack.replace(needle, ' ').replace(/  /g, ' ').trim();

        $input.val(newVal).trigger(onChangeSuppressAnalytics);
      }
      else if (elementType == 'OPTION') {
        $('#' + removeFilterFacet).val('').trigger(onChangeSuppressAnalytics);
      }
    }

    function getInput(removeFilterName, removeFilterValue, removeFilterFacet) {
      var selector = (!!removeFilterName) ? " input[name='" + removeFilterName + "']" : " [value='" + removeFilterValue + "']";

      return $('#' + removeFilterFacet).find(selector);
    }

    function fireRemoveTagTrackingEvent(filterValue, filterFacet) {
      var category = "facetTagRemoved";
      var action = filterFacet;
      var label = filterValue;

      GOVUK.analytics.trackEvent(
        category,
        action,
        { label: label }
      );
    }

    function decodeEntities(string) {
      return string
        .replace(/"/g, '"');
    }
  };
})(window, window.GOVUK);
<commit_msg>Add a comment explaining the needle removal<commit_after>window.GOVUK = window.GOVUK || {};
window.GOVUK.Modules = window.GOVUK.Modules || {};

(function (global, GOVUK) {
  'use strict';

  GOVUK.Modules.RemoveFilter = function () {
    var onChangeSuppressAnalytics = {
      type: "change",
      suppressAnalytics: true
    }

    this.start = function (element) {
      $(element).on('click', '[data-module="remove-filter-link"]', toggleFilter);
    };

    function toggleFilter(e) {
      e.preventDefault();
      e.stopPropagation();
      var $el = $(e.target);

      var removeFilterName = $el.data('name');
      var removeFilterValue = $el.data('value');
      var removeFilterLabel = $el.data('track-label');
      var removeFilterFacet = $el.data('facet');

      var $input = getInput(removeFilterName, removeFilterValue, removeFilterFacet);
      fireRemoveTagTrackingEvent(removeFilterLabel, removeFilterFacet);
      clearFacet($input, removeFilterValue, removeFilterFacet);
    }

    function clearFacet($input, removeFilterValue, removeFilterFacet) {
      var elementType = $input.prop('tagName');
      var inputType = $input.prop('type');
      var currentVal = $input.val();

      if (inputType == 'checkbox') {
        $input.prop("checked", false);
        $input.trigger(onChangeSuppressAnalytics);
      }
      else if (inputType == 'text' || inputType == 'search') {
        /* By padding the haystack with spaces, we can remove the
         * first instance of " $needle ", and this will catch it in
         * the middle of the haystack, at the ends, and when the
         * needle is the haystack; without needing to consider these
         * boundary conditions explicitly.
         *
         * The only caveat is that the matched needle needs replacing
         * with " ", to avoid merging adjacent keywords when it was in
         * the middle of the string, eg:
         *
         * needle = "beta"
         * haystack = "alpha beta gamma"
         *
         * Just removing " beta " from the haystack would result in
         * "alphagamma", which is wrong.
         */
        var haystack = ' ' + currentVal.trim() + ' ';
        var needle = ' ' + decodeEntities(removeFilterValue.toString()) + ' ';
        var newVal = haystack.replace(needle, ' ').replace(/  /g, ' ').trim();

        $input.val(newVal).trigger(onChangeSuppressAnalytics);
      }
      else if (elementType == 'OPTION') {
        $('#' + removeFilterFacet).val('').trigger(onChangeSuppressAnalytics);
      }
    }

    function getInput(removeFilterName, removeFilterValue, removeFilterFacet) {
      var selector = (!!removeFilterName) ? " input[name='" + removeFilterName + "']" : " [value='" + removeFilterValue + "']";

      return $('#' + removeFilterFacet).find(selector);
    }

    function fireRemoveTagTrackingEvent(filterValue, filterFacet) {
      var category = "facetTagRemoved";
      var action = filterFacet;
      var label = filterValue;

      GOVUK.analytics.trackEvent(
        category,
        action,
        { label: label }
      );
    }

    function decodeEntities(string) {
      return string
        .replace(/"/g, '"');
    }
  };
})(window, window.GOVUK);
<|endoftext|>