<commit_before>'use babel'

time_last_lint = new Date().getTime()
lint_waiting = false

CompositeDisposable = require('atom').CompositeDisposable;

module.exports = {
  config: {
    execPath: {
      title: "GCC Executable Path",
      description: "Note for Windows/Mac OS X users: please ensure that GCC is in your ```$PATH``` otherwise the linter might not work. If your path contains spaces, it needs to be enclosed in double quotes.",
      type: "string",
      default: "/usr/bin/g++",
      order : 1
    },
    gccDefaultCFlags: {
      title: "C Flags",
      description: "Supports the use of escaped characters",
      type: "string",
      default: "-c -Wall",
      order : 2
    },
    gccDefaultCppFlags: {
      title: "C++ Flags",
      description: "Supports the use of escaped characters",
      type: "string",
      default: "-c -Wall -std=c++11",
      order : 3
    },
    gccIncludePaths: {
      title: "GCC Include Paths",
      description: "Enter your include paths as a comma-separated list. Paths starting with ```.``` or ```..``` are expanded relative to the project root path and paths starting with a ```-``` are expanded relative to the path of the active file. If any of your paths contain spaces, they need to be enclosed in double quotes. To expand a directory recursively, add ```/*``` to the end of the path",
      type: "string",
      default: " ",
      order : 4
    },
    gccErrorLimit: {
      title: "GCC Error Limit",
      description: "To completely remove `-fmax-errors`, simply enter `-1` here.",
      type: "integer",
      default: 0,
      order : 5
    },
    gccSuppressWarnings: {
      title: "Suppress GCC Warnings",
      type: "boolean",
      default: false,
      order : 6
    },
    gccErrorString: {
        title: "String GCC prepends to errors",
        type: "string",
        default: "error",
        order: 7
    },
    gccWarningString: {
        title: "String GCC prepends to warnings",
        type: "string",
        default: "warning",
        order: 8
    },
    gccNoteString: {
        title: "String GCC prepends to notes",
        type: "string",
        default: "note",
        order: 9
    },
    gccLintOnTheFly: {
      title: "Lint on-the-fly",
      description: "Please ensure any auto-saving packages are disabled before using this feature",
      type: "boolean",
      default: false,
      order : 10
    },
    gccLintOnTheFlyInterval: {
      title: "Lint on-the-fly Interval",
      description: "Time interval (in ms) between linting",
      type: "integer",
      default: 300,
      order : 11
    },
    gccDebug: {
      title: "Show Debugging Messages",
      description: "Please read the linter-gcc wiki [here](https://github.com/hebaishi/linter-gcc/wiki) before reporting any issues.",
      type: "boolean",
      default: false,
      order : 12
    },
    compileCommandsFile: {
      title: "Compile commands file",
      description: "Path to cmake compile_commands.json",
      type: "string",
      default: "./build/compile_commands.json",
      order : 13
    }
  },

  messages: {},
  linter_gcc: undefined,

  temp_file : {
    "C++": require("tempfile")(".cpp"),
    "C": require("tempfile")(".c")
  },

  lint: function(editor, linted_file, real_file){
    const helpers=require("atom-linter");
    const regex = `(?<file>.+):(?<line>\\d+):(?<col>\\d+):\\s*\\w*\\s*(?<type>(${atom.config.get("linter-gcc.gccErrorString")}|${atom.config.get("linter-gcc.gccWarningString")}|${atom.config.get("linter-gcc.gccNoteString")}))\\s*:\\s*(?<message>.*)`
    command = require("./utility").buildCommand(editor, linted_file);
    return helpers.exec(command.binary, command.args, {stream: "stderr"}).then(output => {
      msgs = helpers.parse(output, regex)
      msgs.forEach(function(entry){
        if (entry.filePath === module.exports.temp_file["C"] || entry.filePath === module.exports.temp_file["C++"]){
          entry.filePath = real_file;
        }
        if (entry.type ===`${atom.config.get("linter-gcc.gccWarningString")}`)
            entry.type = "warning";
        else if (entry.type ===`${atom.config.get("linter-gcc.gccErrorString")}`)
            entry.type = "error";
        else if (entry.type ===`${atom.config.get("linter-gcc.gccNoteString")}`)
            entry.type = "note";
      })
      if (msgs.length == 0 && output.indexOf("error") != -1){
        msgs = [{
          type: 'error',
          text: output,
          filePath: real_file
        }];
      }
      module.exports.messages[real_file] = msgs;
      // console.log(msgs)
      if (typeof module.exports.linter_gcc != "undefined"){
        module.exports.linter_gcc.setMessages(require("./utility").flattenHash(module.exports.messages))
      }
      return msgs;
    })
  },

  activate: function() {
    this.subscriptions = new CompositeDisposable()
    if(!atom.packages.getLoadedPackages("linter")) {
    atom.notifications.addError(
      "Linter package not found.",
      {
        detail: "Please install the `linter` package in your Settings view."
      }
    );
    }
    require("atom-package-deps").install("linter-gcc");
    time_last_lint = new Date().getTime()
    lint_waiting = false
  },
  deactivate: function() {
    this.subscriptions.dispose()
  },
  consumeLinter: function(indieRegistry) {
    module.exports.linter_gcc = indieRegistry.register({
      name: 'GCC'
    })

    subs = this.subscriptions;
    utility = require("./utility")
    lintOnTheFly = function() {
      editor = utility.getValidEditor(atom.workspace.getActiveTextEditor());
      if (!editor) return;
      if (atom.config.get("linter-gcc.gccLintOnTheFly") == false) return;
      if (lint_waiting) return;
      lint_waiting = true
      interval = atom.config.get("linter-gcc.gccLintOnTheFlyInterval")
      time_now = new Date().getTime()
      timeout = interval - (time_now - time_last_lint);
      setTimeout(
        function() {
          time_last_lint = new Date().getTime()
          lint_waiting = false
          grammar_type = utility.grammarType(editor.getGrammar().name)
          filename = String(module.exports.temp_file[grammar_type])
          require('fs-extra').outputFileSync(filename, editor.getText());
          module.exports.lint(editor, filename, editor.getPath());
        },
        timeout
      );
    };

    lintOnSave = function(){
      editor = utility.getValidEditor(atom.workspace.getActiveTextEditor());
      if (!editor) return;
      if (atom.config.get("linter-gcc.gccLintOnTheFly") == true) return;
      real_file = editor.getPath();
      module.exports.lint(editor, real_file, real_file);
    };

    cleanupMessages = function(){
      editor_hash = {};
      atom.workspace.getTextEditors().forEach( function(entry){
        try{
          path = entry.getPath()
        } catch(err){
        }
        editor_hash[entry.getPath()] = 1;
      });
      for (var file in module.exports.messages){
        if (!editor_hash.hasOwnProperty(file)){
          delete module.exports.messages[file]
        }
      }
      module.exports.linter_gcc.setMessages(JSON.parse(JSON.stringify(require("./utility").flattenHash(module.exports.messages))));
    };

    subs.add(module.exports.linter_gcc)

    atom.workspace.observeTextEditors(function(editor) {
      subs.add(editor.onDidSave(lintOnSave))
      subs.add(editor.onDidStopChanging(lintOnTheFly))
      subs.add(editor.onDidDestroy(cleanupMessages))
    })
  }
}
<commit_msg>Change default executable path<commit_after>'use babel'

time_last_lint = new Date().getTime()
lint_waiting = false

CompositeDisposable = require('atom').CompositeDisposable;

module.exports = {
  config: {
    execPath: {
      title: "GCC Executable Path",
      description: "Note for Windows/Mac OS X users: please ensure that GCC is in your ```$PATH``` otherwise the linter might not work. If your path contains spaces, it needs to be enclosed in double quotes.",
      type: "string",
      default: "g++",
      order : 1
    },
    gccDefaultCFlags: {
      title: "C Flags",
      description: "Supports the use of escaped characters",
      type: "string",
      default: "-c -Wall",
      order : 2
    },
    gccDefaultCppFlags: {
      title: "C++ Flags",
      description: "Supports the use of escaped characters",
      type: "string",
      default: "-c -Wall -std=c++11",
      order : 3
    },
    gccIncludePaths: {
      title: "GCC Include Paths",
      description: "Enter your include paths as a comma-separated list. Paths starting with ```.``` or ```..``` are expanded relative to the project root path and paths starting with a ```-``` are expanded relative to the path of the active file. If any of your paths contain spaces, they need to be enclosed in double quotes. To expand a directory recursively, add ```/*``` to the end of the path",
      type: "string",
      default: " ",
      order : 4
    },
    gccErrorLimit: {
      title: "GCC Error Limit",
      description: "To completely remove `-fmax-errors`, simply enter `-1` here.",
      type: "integer",
      default: 0,
      order : 5
    },
    gccSuppressWarnings: {
      title: "Suppress GCC Warnings",
      type: "boolean",
      default: false,
      order : 6
    },
    gccErrorString: {
        title: "String GCC prepends to errors",
        type: "string",
        default: "error",
        order: 7
    },
    gccWarningString: {
        title: "String GCC prepends to warnings",
        type: "string",
        default: "warning",
        order: 8
    },
    gccNoteString: {
        title: "String GCC prepends to notes",
        type: "string",
        default: "note",
        order: 9
    },
    gccLintOnTheFly: {
      title: "Lint on-the-fly",
      description: "Please ensure any auto-saving packages are disabled before using this feature",
      type: "boolean",
      default: false,
      order : 10
    },
    gccLintOnTheFlyInterval: {
      title: "Lint on-the-fly Interval",
      description: "Time interval (in ms) between linting",
      type: "integer",
      default: 300,
      order : 11
    },
    gccDebug: {
      title: "Show Debugging Messages",
      description: "Please read the linter-gcc wiki [here](https://github.com/hebaishi/linter-gcc/wiki) before reporting any issues.",
      type: "boolean",
      default: false,
      order : 12
    },
    compileCommandsFile: {
      title: "Compile commands file",
      description: "Path to cmake compile_commands.json",
      type: "string",
      default: "./build/compile_commands.json",
      order : 13
    }
  },

  messages: {},
  linter_gcc: undefined,

  temp_file : {
    "C++": require("tempfile")(".cpp"),
    "C": require("tempfile")(".c")
  },

  lint: function(editor, linted_file, real_file){
    const helpers=require("atom-linter");
    const regex = `(?<file>.+):(?<line>\\d+):(?<col>\\d+):\\s*\\w*\\s*(?<type>(${atom.config.get("linter-gcc.gccErrorString")}|${atom.config.get("linter-gcc.gccWarningString")}|${atom.config.get("linter-gcc.gccNoteString")}))\\s*:\\s*(?<message>.*)`
    command = require("./utility").buildCommand(editor, linted_file);
    return helpers.exec(command.binary, command.args, {stream: "stderr"}).then(output => {
      msgs = helpers.parse(output, regex)
      msgs.forEach(function(entry){
        if (entry.filePath === module.exports.temp_file["C"] || entry.filePath === module.exports.temp_file["C++"]){
          entry.filePath = real_file;
        }
        if (entry.type ===`${atom.config.get("linter-gcc.gccWarningString")}`)
            entry.type = "warning";
        else if (entry.type ===`${atom.config.get("linter-gcc.gccErrorString")}`)
            entry.type = "error";
        else if (entry.type ===`${atom.config.get("linter-gcc.gccNoteString")}`)
            entry.type = "note";
      })
      if (msgs.length == 0 && output.indexOf("error") != -1){
        msgs = [{
          type: 'error',
          text: output,
          filePath: real_file
        }];
      }
      module.exports.messages[real_file] = msgs;
      // console.log(msgs)
      if (typeof module.exports.linter_gcc != "undefined"){
        module.exports.linter_gcc.setMessages(require("./utility").flattenHash(module.exports.messages))
      }
      return msgs;
    })
  },

  activate: function() {
    this.subscriptions = new CompositeDisposable()
    if(!atom.packages.getLoadedPackages("linter")) {
    atom.notifications.addError(
      "Linter package not found.",
      {
        detail: "Please install the `linter` package in your Settings view."
      }
    );
    }
    require("atom-package-deps").install("linter-gcc");
    time_last_lint = new Date().getTime()
    lint_waiting = false
  },
  deactivate: function() {
    this.subscriptions.dispose()
  },
  consumeLinter: function(indieRegistry) {
    module.exports.linter_gcc = indieRegistry.register({
      name: 'GCC'
    })

    subs = this.subscriptions;
    utility = require("./utility")
    lintOnTheFly = function() {
      editor = utility.getValidEditor(atom.workspace.getActiveTextEditor());
      if (!editor) return;
      if (atom.config.get("linter-gcc.gccLintOnTheFly") == false) return;
      if (lint_waiting) return;
      lint_waiting = true
      interval = atom.config.get("linter-gcc.gccLintOnTheFlyInterval")
      time_now = new Date().getTime()
      timeout = interval - (time_now - time_last_lint);
      setTimeout(
        function() {
          time_last_lint = new Date().getTime()
          lint_waiting = false
          grammar_type = utility.grammarType(editor.getGrammar().name)
          filename = String(module.exports.temp_file[grammar_type])
          require('fs-extra').outputFileSync(filename, editor.getText());
          module.exports.lint(editor, filename, editor.getPath());
        },
        timeout
      );
    };

    lintOnSave = function(){
      editor = utility.getValidEditor(atom.workspace.getActiveTextEditor());
      if (!editor) return;
      if (atom.config.get("linter-gcc.gccLintOnTheFly") == true) return;
      real_file = editor.getPath();
      module.exports.lint(editor, real_file, real_file);
    };

    cleanupMessages = function(){
      editor_hash = {};
      atom.workspace.getTextEditors().forEach( function(entry){
        try{
          path = entry.getPath()
        } catch(err){
        }
        editor_hash[entry.getPath()] = 1;
      });
      for (var file in module.exports.messages){
        if (!editor_hash.hasOwnProperty(file)){
          delete module.exports.messages[file]
        }
      }
      module.exports.linter_gcc.setMessages(JSON.parse(JSON.stringify(require("./utility").flattenHash(module.exports.messages))));
    };

    subs.add(module.exports.linter_gcc)

    atom.workspace.observeTextEditors(function(editor) {
      subs.add(editor.onDidSave(lintOnSave))
      subs.add(editor.onDidStopChanging(lintOnTheFly))
      subs.add(editor.onDidDestroy(cleanupMessages))
    })
  }
}
<|endoftext|>


<commit_before>;(function($$){ 'use strict';

  // search, spanning trees, etc
  $$.fn.eles({

    // do a breadth first search from the nodes in the collection
    // from pseudocode on wikipedia
    breadthFirstSearch: function( roots, fn, directed ){
      directed = arguments.length === 1 && !$$.is.fn(fn) ? fn : directed;
      fn = $$.is.fn(fn) ? fn : function(){};
      var cy = this._private.cy;
      var v = $$.is.string(roots) ? this.filter(roots) : roots;
      var Q = [];
      var connectedEles = [];
      var id2depth = {};
      var V = {};
      var j = 0;
      var found;
      var nodes = this.nodes();
      var edges = this.edges();

      // enqueue v
      for( var i = 0; i < v.length; i++ ){
        if( v[i].isNode() ){
          Q.unshift( v[i] );
          V[ v[i].id() ] = true;

          connectedEles.push( v[i] );
          id2depth[ v[i].id() ] = 0;
        }
      }

      while( Q.length !== 0 ){
        var v = Q.shift();
        var depth = id2depth[ v.id() ];
        var ret = fn.call(v, j++, depth);

        if( ret === true ){
          found = v;
          break;
        }

        if( ret === false ){
          break;
        }

        var vwEdges = v.connectedEdges(directed ? function(){ return this.data('source') === v.id(); } : undefined).intersect( edges );
        for( var i = 0; i < vwEdges.length; i++ ){
          var e = vwEdges[i];
          var w = e.connectedNodes(function(){ return this.id() !== v.id(); }).intersect( nodes );

          if( w.length !== 0 && !V[ w.id() ] ){
            w = w[0];

            Q.push( w );
            V[ w.id() ] = true;

            id2depth[ w.id() ] = id2depth[ v.id() ] + 1;

            connectedEles.push( w );
            connectedEles.push( e );
          }
        }

      }

      return {
        path: new $$.Collection( cy, connectedEles, { unique: true } ),
        found: new $$.Collection( cy, found, { unique: true } )
      };
    },

    // do a depth first search on the nodes in the collection
    // from pseudocode on wikipedia (iterative impl)
    depthFirstSearch: function( roots, fn, directed ){
      directed = arguments.length === 1 && !$$.is.fn(fn) ? fn : directed;
      fn = $$.is.fn(fn) ? fn : function(){};
      var cy = this._private.cy;
      var v = $$.is.string(roots) ? this.filter(roots) : roots;
      var S = [];
      var connectedNodes = [];
      var connectedBy = {};
      var id2depth = {};
      var discovered = {};
      var j = 0;
      var found;
      var edges = this.edges();
      var nodes = this.nodes();

      // push v
      for( var i = 0; i < v.length; i++ ){
        if( v[i].isNode() ){
          S.push( v[i] );

          connectedNodes.push( v[i] );
          id2depth[ v[i].id() ] = 0;
        }
      }

      while( S.length !== 0 ){
        var v = S.pop();

        if( !discovered[ v.id() ] ){
          discovered[ v.id() ] = true;

          var depth = id2depth[ v.id() ];

          var ret = fn.call(v, j++, depth);

          if( ret === true ){
            found = v;
            break;
          }

          if( ret === false ){
            break;
          }

          var vwEdges = v.connectedEdges(directed ? function(){ return this.data('source') === v.id(); } : undefined).intersect( edges );

          for( var i = 0; i < vwEdges.length; i++ ){
            var e = vwEdges[i];
            var w = e.connectedNodes(function(){ return this.id() !== v.id(); }).intersect( nodes );

            if( w.length !== 0 && !discovered[ w.id() ] ){
              w = w[0];

              S.push( w );

              id2depth[ w.id() ] = id2depth[ v.id() ] + 1;

              connectedNodes.push( w );
              connectedBy[ w.id() ] = e;
            }
          }
        }
      }

      var connectedEles = [];

      for( var i = 0; i < connectedNodes.length; i++ ){
        var node = connectedNodes[i];
        var edge = connectedBy[ node.id() ];

        if( edge ){
          connectedEles.push( edge );
        }

        connectedEles.push( node );
      }

      return {
        path: new $$.Collection( cy, connectedEles, { unique: true } ),
        found: new $$.Collection( cy, found, { unique: true } )
      };
    },

    // kruskal's algorithm (finds min spanning tree, assuming undirected graph)
    // implemented from pseudocode from wikipedia
    kruskal: function( weightFn ){
      weightFn = $$.is.fn(weightFn) ? weightFn : function(){ return 1; }; // if not specified, assume each edge has equal weight (1)

      function findSet(ele){
        for( var i = 0; i < forest.length; i++ ){
          var eles = forest[i];

          if( eles.anySame(ele) ){
            return {
              eles: eles,
              index: i
            };
          }
        }
      }

      var A = new $$.Collection(this._private.cy, []);
      var forest = [];
      var nodes = this.nodes();

      for( var i = 0; i < nodes.length; i++ ){
        forest.push( nodes[i].collection() );
      }

      var edges = this.edges();
      var S = edges.toArray().sort(function(a, b){
        var weightA = weightFn.call(a);
        var weightB = weightFn.call(b);

        return weightA - weightB;
      });

      for(var i = 0; i < S.length; i++){
        var edge = S[i];
        var u = edge.source()[0];
        var v = edge.target()[0];
        var setU = findSet(u);
        var setV = findSet(v);

        if( setU.index !== setV.index ){
          A = A.add( edge );

          // combine forests for u and v
          forest[ setU.index ] = setU.eles.add( setV.eles );
          forest.splice( setV.index, 1 );
        }
      }

      return nodes.add( A );

    },

    dijkstra: function( root, weightFn, directed ){
      var cy = this._private.cy;
      directed = !$$.is.fn(weightFn) ? weightFn : directed;
      weightFn = $$.is.fn(weightFn) ? weightFn : function(){ return 1; }; // if not specified, assume each edge has equal weight (1)

      var source = $$.is.string(root) ? this.filter(root)[0] : root[0];
      var dist = {};
      var prev = {};
      var knownDist = {};

      var edges = this.edges().filter(function(){ return !this.isLoop(); });
      var nodes = this.nodes();
      var Q = [];

      for( var i = 0; i < nodes.length; i++ ){
        dist[ nodes[i].id() ] = nodes[i].id() === source.id() ? 0 : Infinity;
        Q.push( nodes[i] );
      }

      var valueFn = function(node) {
        return dist[ node.id() ];
      };

      Q = new $$.Collection(cy, Q);

      var heap = $$.Minheap(cy, Q, valueFn);

      var distBetween = function(u, v){
        var uvs = ( directed ? u.edgesTo(v) : u.edgesWith(v) ).intersect(edges);
        var smallestDistance = Infinity;
        var smallestEdge;

        for( var i = 0; i < uvs.length; i++ ){
          var edge = uvs[i];
          var weight = weightFn.call(edge);

          if( weight < smallestDistance || !smallestEdge ){
            smallestDistance = weight;
            smallestEdge = edge;
          }
        }

        return {
          edge: smallestEdge,
          dist: smallestDistance
        };
      };

      while(heap.size() > 0){
        var smallestEl = heap.pop(),
        smalletsDist = smallestEl.value,
        uid = smallestEl.id,
        u = cy.getElementById(uid);

        knownDist[uid] = smalletsDist;

        if( smalletsDist === Math.Infinite ){
          break;
        }

        var neighbors = u.neighborhood().intersect(nodes);
        for( var i = 0; i < neighbors.length; i++ ){
          var v = neighbors[i];
          var vid = v.id();
          var vDist = distBetween(u, v);

          var alt = smalletsDist + vDist.dist;

          if( alt < heap.getValueById(vid) ){
            heap.edit(vid, alt);
            prev[ vid ] = {
              node: u,
              edge: vDist.edge
            };
          }
        } // for
      } // while

      return {
        distanceTo: function(node){
          var target = $$.is.string(node) ? nodes.filter(node)[0] : node[0];

          return knownDist[ target.id() ];
        },

        pathTo: function(node){
          var target = $$.is.string(node) ? nodes.filter(node)[0] : node[0];
          var S = [];
          var u = target;

          S.unshift( target );

          while( prev[ u.id() ] ){
            var p = prev[ u.id() ];

            S.unshift( p.edge );
            S.unshift( p.node );

            u = p.node;
          }

          return new $$.Collection( cy, S );
        }
      };
    }
  });

  // nice, short mathemathical alias
  $$.elesfn.bfs = $$.elesfn.breadthFirstSearch;
  $$.elesfn.dfs = $$.elesfn.depthFirstSearch;

})( cytoscape );<commit_msg>#dijkstra throws error if root/target element doesn't exist #550<commit_after>;(function($$){ 'use strict';

  // search, spanning trees, etc
  $$.fn.eles({

    // do a breadth first search from the nodes in the collection
    // from pseudocode on wikipedia
    breadthFirstSearch: function( roots, fn, directed ){
      directed = arguments.length === 1 && !$$.is.fn(fn) ? fn : directed;
      fn = $$.is.fn(fn) ? fn : function(){};
      var cy = this._private.cy;
      var v = $$.is.string(roots) ? this.filter(roots) : roots;
      var Q = [];
      var connectedEles = [];
      var id2depth = {};
      var V = {};
      var j = 0;
      var found;
      var nodes = this.nodes();
      var edges = this.edges();

      // enqueue v
      for( var i = 0; i < v.length; i++ ){
        if( v[i].isNode() ){
          Q.unshift( v[i] );
          V[ v[i].id() ] = true;

          connectedEles.push( v[i] );
          id2depth[ v[i].id() ] = 0;
        }
      }

      while( Q.length !== 0 ){
        var v = Q.shift();
        var depth = id2depth[ v.id() ];
        var ret = fn.call(v, j++, depth);

        if( ret === true ){
          found = v;
          break;
        }

        if( ret === false ){
          break;
        }

        var vwEdges = v.connectedEdges(directed ? function(){ return this.data('source') === v.id(); } : undefined).intersect( edges );
        for( var i = 0; i < vwEdges.length; i++ ){
          var e = vwEdges[i];
          var w = e.connectedNodes(function(){ return this.id() !== v.id(); }).intersect( nodes );

          if( w.length !== 0 && !V[ w.id() ] ){
            w = w[0];

            Q.push( w );
            V[ w.id() ] = true;

            id2depth[ w.id() ] = id2depth[ v.id() ] + 1;

            connectedEles.push( w );
            connectedEles.push( e );
          }
        }

      }

      return {
        path: new $$.Collection( cy, connectedEles, { unique: true } ),
        found: new $$.Collection( cy, found, { unique: true } )
      };
    },

    // do a depth first search on the nodes in the collection
    // from pseudocode on wikipedia (iterative impl)
    depthFirstSearch: function( roots, fn, directed ){
      directed = arguments.length === 1 && !$$.is.fn(fn) ? fn : directed;
      fn = $$.is.fn(fn) ? fn : function(){};
      var cy = this._private.cy;
      var v = $$.is.string(roots) ? this.filter(roots) : roots;
      var S = [];
      var connectedNodes = [];
      var connectedBy = {};
      var id2depth = {};
      var discovered = {};
      var j = 0;
      var found;
      var edges = this.edges();
      var nodes = this.nodes();

      // push v
      for( var i = 0; i < v.length; i++ ){
        if( v[i].isNode() ){
          S.push( v[i] );

          connectedNodes.push( v[i] );
          id2depth[ v[i].id() ] = 0;
        }
      }

      while( S.length !== 0 ){
        var v = S.pop();

        if( !discovered[ v.id() ] ){
          discovered[ v.id() ] = true;

          var depth = id2depth[ v.id() ];

          var ret = fn.call(v, j++, depth);

          if( ret === true ){
            found = v;
            break;
          }

          if( ret === false ){
            break;
          }

          var vwEdges = v.connectedEdges(directed ? function(){ return this.data('source') === v.id(); } : undefined).intersect( edges );

          for( var i = 0; i < vwEdges.length; i++ ){
            var e = vwEdges[i];
            var w = e.connectedNodes(function(){ return this.id() !== v.id(); }).intersect( nodes );

            if( w.length !== 0 && !discovered[ w.id() ] ){
              w = w[0];

              S.push( w );

              id2depth[ w.id() ] = id2depth[ v.id() ] + 1;

              connectedNodes.push( w );
              connectedBy[ w.id() ] = e;
            }
          }
        }
      }

      var connectedEles = [];

      for( var i = 0; i < connectedNodes.length; i++ ){
        var node = connectedNodes[i];
        var edge = connectedBy[ node.id() ];

        if( edge ){
          connectedEles.push( edge );
        }

        connectedEles.push( node );
      }

      return {
        path: new $$.Collection( cy, connectedEles, { unique: true } ),
        found: new $$.Collection( cy, found, { unique: true } )
      };
    },

    // kruskal's algorithm (finds min spanning tree, assuming undirected graph)
    // implemented from pseudocode from wikipedia
    kruskal: function( weightFn ){
      weightFn = $$.is.fn(weightFn) ? weightFn : function(){ return 1; }; // if not specified, assume each edge has equal weight (1)

      function findSet(ele){
        for( var i = 0; i < forest.length; i++ ){
          var eles = forest[i];

          if( eles.anySame(ele) ){
            return {
              eles: eles,
              index: i
            };
          }
        }
      }

      var A = new $$.Collection(this._private.cy, []);
      var forest = [];
      var nodes = this.nodes();

      for( var i = 0; i < nodes.length; i++ ){
        forest.push( nodes[i].collection() );
      }

      var edges = this.edges();
      var S = edges.toArray().sort(function(a, b){
        var weightA = weightFn.call(a);
        var weightB = weightFn.call(b);

        return weightA - weightB;
      });

      for(var i = 0; i < S.length; i++){
        var edge = S[i];
        var u = edge.source()[0];
        var v = edge.target()[0];
        var setU = findSet(u);
        var setV = findSet(v);

        if( setU.index !== setV.index ){
          A = A.add( edge );

          // combine forests for u and v
          forest[ setU.index ] = setU.eles.add( setV.eles );
          forest.splice( setV.index, 1 );
        }
      }

      return nodes.add( A );

    },

    dijkstra: function( root, weightFn, directed ){
      var cy = this._private.cy;
      directed = !$$.is.fn(weightFn) ? weightFn : directed;
      weightFn = $$.is.fn(weightFn) ? weightFn : function(){ return 1; }; // if not specified, assume each edge has equal weight (1)

      var source = $$.is.string(root) ? this.filter(root).eq(0) : root.eq(0);
      var dist = {};
      var prev = {};
      var knownDist = {};

      var edges = this.edges().filter(function(){ return !this.isLoop(); });
      var nodes = this.nodes();
      var Q = [];

      for( var i = 0; i < nodes.length; i++ ){
        dist[ nodes[i].id() ] = nodes[i].same( source ) ? 0 : Infinity;
        Q.push( nodes[i] );
      }

      var valueFn = function(node) {
        return dist[ node.id() ];
      };

      Q = new $$.Collection(cy, Q);

      var heap = $$.Minheap(cy, Q, valueFn);

      var distBetween = function(u, v){
        var uvs = ( directed ? u.edgesTo(v) : u.edgesWith(v) ).intersect(edges);
        var smallestDistance = Infinity;
        var smallestEdge;

        for( var i = 0; i < uvs.length; i++ ){
          var edge = uvs[i];
          var weight = weightFn.call(edge);

          if( weight < smallestDistance || !smallestEdge ){
            smallestDistance = weight;
            smallestEdge = edge;
          }
        }

        return {
          edge: smallestEdge,
          dist: smallestDistance
        };
      };

      while(heap.size() > 0){
        var smallestEl = heap.pop(),
        smalletsDist = smallestEl.value,
        uid = smallestEl.id,
        u = cy.getElementById(uid);

        knownDist[uid] = smalletsDist;

        if( smalletsDist === Math.Infinite ){
          break;
        }

        var neighbors = u.neighborhood().intersect(nodes);
        for( var i = 0; i < neighbors.length; i++ ){
          var v = neighbors[i];
          var vid = v.id();
          var vDist = distBetween(u, v);

          var alt = smalletsDist + vDist.dist;

          if( alt < heap.getValueById(vid) ){
            heap.edit(vid, alt);
            prev[ vid ] = {
              node: u,
              edge: vDist.edge
            };
          }
        } // for
      } // while

      return {
        distanceTo: function(node){
          var target = $$.is.string(node) ? nodes.filter(node).eq(0) : node.eq(0);

          return knownDist[ target.id() ];
        },

        pathTo: function(node){
          var target = $$.is.string(node) ? nodes.filter(node).eq(0) : node.eq(0);
          var S = [];
          var u = target;

          if( target.length > 0 ){
            S.unshift( target );

            while( prev[ u.id() ] ){
              var p = prev[ u.id() ];

              S.unshift( p.edge );
              S.unshift( p.node );

              u = p.node;
            }
          }

          return new $$.Collection( cy, S );
        }
      };
    }
  });

  // nice, short mathemathical alias
  $$.elesfn.bfs = $$.elesfn.breadthFirstSearch;
  $$.elesfn.dfs = $$.elesfn.depthFirstSearch;

})( cytoscape );<|endoftext|>


<commit_before>'use strict';

var cheerio = require('cheerio');
var postcss = require('postcss');
var cssWhat = require('css-what');
var Hashids = require('hashids');

var stringify = require('./css-what/stringify');

var ALPHABET = 'abcdefghijklmnopqrstuvwxyz';
var VERSION = require('../package.json').version;
var LOOKUP_DELIMITER = '=';

function HTMLUglify(config) {
  this.version = VERSION;

  config = config || {};

  var salt = config.salt || 'use the force harry';
  this.hashids = new Hashids(salt, 0, ALPHABET);
  this.whitelist = config.whitelist || [];
}

HTMLUglify.prototype.determinePointer = function(type, value, lookups) {
  var lookupKey = [type, value].join(LOOKUP_DELIMITER);
  var existingPointer = lookups[lookupKey];

  if (existingPointer) {
    return existingPointer;
  }

  var counter = Object.keys(lookups).length;
  var pointer = this.hashids.encode(counter);
  return pointer;
};

HTMLUglify.prototype.isWhitelisted = function(type, value) {
  if (type === 'class') {
    value = '.' + value;
  }
  if (type === 'id') {
    value = '#' + value;
  }

  return this.whitelist.indexOf(value) >= 0;
};

HTMLUglify.prototype.pointerizeClass = function($element, lookups) {
  var _this = this;
  var value = $element.attr('class');

  if (value && !this.isWhitelisted('class', value)) {
    var splitClasses = value.split(/\s+/);
    splitClasses.forEach(function(value) {
      var pointer = _this.determinePointer('class', value, lookups);

      $element.removeClass(value);
      $element.addClass(pointer);

      _this.populateLookups('class', value, pointer, lookups);
    });
  }
};

HTMLUglify.prototype.pointerizeIdAndFor = function(type, $element, lookups) {
  var value = $element.attr(type);

  if (value && !this.isWhitelisted('id', value)) {
    var pointer = this.determinePointer('id', value, lookups);

    $element.attr(type, pointer);
    this.populateLookups('id', value, pointer, lookups); // always set to id for lookups
  }
};

HTMLUglify.prototype.populateLookups = function(type, value, pointer, lookups) {
  var key = [type, value].join(LOOKUP_DELIMITER);
  lookups[key] = pointer;
};

HTMLUglify.prototype.rewriteElements = function($, lookups) {
  var _this = this;

  lookups = lookups || {};

  $('*[id]').each(function() {
    _this.pointerizeIdAndFor('id', $(this), lookups);
  });

  $('*[for]').each(function() {
    _this.pointerizeIdAndFor('for', $(this), lookups);
  });

  $('*[class]').each(function() {
    _this.pointerizeClass($(this), lookups);
  });

  return $;
};

HTMLUglify.prototype.processRules = function(rules, lookups) {
  var _this = this;

  rules.forEach(function(rule) {
    // go deeper inside media rule to find css rules
    if (rule.type === 'atrule' && rule.name === 'media') {
      _this.processRules(rule.nodes, lookups);
    } else if (rule.type === 'rule') {
      var subselectors = cssWhat(rule.selector).map(function(select) {
        return select.map(function(token) {
          var value = token.value;
          var keyLookup;

          if (token.type === 'attribute') {
            if (token.name === 'class') {
              // Handle .something and class=something
              keyLookup = ['class', value].join(LOOKUP_DELIMITER);
            } else if (token.name === 'id' || token.name === 'for') {
              // Handle #something and id=something and for=something
              keyLookup = ['id', value].join(LOOKUP_DELIMITER);
            }

            var pointer = lookups[keyLookup];
            if (pointer) {
              token.value = pointer;
            }
          }

          return token;
        });
      });

      rule.selector = stringify(subselectors);
    }
  });
};

HTMLUglify.prototype.rewriteStyles = function($, lookups) {
  var _this = this;

  lookups = lookups || {};

  $('style').each(function() {
    var $style = $(this);
    var ast = postcss.parse($style.text(), { safe: true });
    _this.processRules(ast.nodes, lookups);
    $style.text(ast.toString());
  });

  return $;
};

HTMLUglify.prototype.process = function(html) {
  var lookups = {};

  var $ = cheerio.load(html);
  $ = this.rewriteElements($, lookups);
  $ = this.rewriteStyles($, lookups);

  return $.html();
};

module.exports = HTMLUglify;
<commit_msg>Use a switch statement"<commit_after>'use strict';

var cheerio = require('cheerio');
var postcss = require('postcss');
var cssWhat = require('css-what');
var Hashids = require('hashids');

var stringify = require('./css-what/stringify');

var ALPHABET = 'abcdefghijklmnopqrstuvwxyz';
var VERSION = require('../package.json').version;
var LOOKUP_DELIMITER = '=';

function HTMLUglify(config) {
  this.version = VERSION;

  config = config || {};

  var salt = config.salt || 'use the force harry';
  this.hashids = new Hashids(salt, 0, ALPHABET);
  this.whitelist = config.whitelist || [];
}

HTMLUglify.prototype.determinePointer = function(type, value, lookups) {
  var lookupKey = [type, value].join(LOOKUP_DELIMITER);
  var existingPointer = lookups[lookupKey];

  if (existingPointer) {
    return existingPointer;
  }

  var counter = Object.keys(lookups).length;
  var pointer = this.hashids.encode(counter);
  return pointer;
};

HTMLUglify.prototype.isWhitelisted = function(type, value) {
  switch(type) {
    case 'class':
      value = ['.', value].join('');
      break;
    case 'id':
      value = ['#', value].join('');
      break;
    default:
      value;
  }

  return this.whitelist.indexOf(value) >= 0;
};

HTMLUglify.prototype.pointerizeClass = function($element, lookups) {
  var _this = this;
  var value = $element.attr('class');

  if (value && !this.isWhitelisted('class', value)) {
    var splitClasses = value.split(/\s+/);
    splitClasses.forEach(function(value) {
      var pointer = _this.determinePointer('class', value, lookups);

      $element.removeClass(value);
      $element.addClass(pointer);

      _this.populateLookups('class', value, pointer, lookups);
    });
  }
};

HTMLUglify.prototype.pointerizeIdAndFor = function(type, $element, lookups) {
  var value = $element.attr(type);

  if (value && !this.isWhitelisted('id', value)) {
    var pointer = this.determinePointer('id', value, lookups);

    $element.attr(type, pointer);
    this.populateLookups('id', value, pointer, lookups); // always set to id for lookups
  }
};

HTMLUglify.prototype.populateLookups = function(type, value, pointer, lookups) {
  var key = [type, value].join(LOOKUP_DELIMITER);
  lookups[key] = pointer;
};

HTMLUglify.prototype.rewriteElements = function($, lookups) {
  var _this = this;

  lookups = lookups || {};

  $('*[id]').each(function() {
    _this.pointerizeIdAndFor('id', $(this), lookups);
  });

  $('*[for]').each(function() {
    _this.pointerizeIdAndFor('for', $(this), lookups);
  });

  $('*[class]').each(function() {
    _this.pointerizeClass($(this), lookups);
  });

  return $;
};

HTMLUglify.prototype.processRules = function(rules, lookups) {
  var _this = this;

  rules.forEach(function(rule) {
    // go deeper inside media rule to find css rules
    if (rule.type === 'atrule' && rule.name === 'media') {
      _this.processRules(rule.nodes, lookups);
    } else if (rule.type === 'rule') {
      var subselectors = cssWhat(rule.selector).map(function(select) {
        return select.map(function(token) {
          var value = token.value;
          var keyLookup;

          if (token.type === 'attribute') {
            if (token.name === 'class') {
              // Handle .something and class=something
              keyLookup = ['class', value].join(LOOKUP_DELIMITER);
            } else if (token.name === 'id' || token.name === 'for') {
              // Handle #something and id=something and for=something
              keyLookup = ['id', value].join(LOOKUP_DELIMITER);
            }

            var pointer = lookups[keyLookup];
            if (pointer) {
              token.value = pointer;
            }
          }

          return token;
        });
      });

      rule.selector = stringify(subselectors);
    }
  });
};

HTMLUglify.prototype.rewriteStyles = function($, lookups) {
  var _this = this;

  lookups = lookups || {};

  $('style').each(function() {
    var $style = $(this);
    var ast = postcss.parse($style.text(), { safe: true });
    _this.processRules(ast.nodes, lookups);
    $style.text(ast.toString());
  });

  return $;
};

HTMLUglify.prototype.process = function(html) {
  var lookups = {};

  var $ = cheerio.load(html);
  $ = this.rewriteElements($, lookups);
  $ = this.rewriteStyles($, lookups);

  return $.html();
};

module.exports = HTMLUglify;
<|endoftext|>


<commit_before>'use strict';

var util = require('./util');

exports = module.exports = boil;

// ## boil(path [, options])
// > normalize a path
//
// arguments
//  - path, type `string`
//  - options, type `object` holding all extra information
//
// throws error if the `path` is not supported
//
// --
// api.private
// --

util.boilRE = /([^\/ ]*\/[^\/ ]*|[^\. ]+\.)/g;

function boil(path, o){
  if(typeof path !== 'string'){
    throw new TypeError('argument should be a  `string`');
  }

  o = o || {};

  o.url = (path.match(/[^\/ ]*\/\S*/g) || '')[0];
  o.path = path.replace(/[ ]+/g, ' ').trim();

  if(o.url){
    o.path = o.path.replace(o.url, o.url.replace(/\/?\?[^!=: ]+/g, '') || '/');
  }

  o.argv = o.path.replace(util.boilRE, '$& ').trim().split(/[ ]+/);

  return o;
}
<commit_msg>take into account only hashes as well as querystrings<commit_after>'use strict';

var util = require('./util');

exports = module.exports = boil;

// ## boil(path [, options])
// > normalize a path
//
// arguments
//  - path, type `string`
//  - options, type `object` holding all extra information
//
// throws error if the `path` is not supported
//
// --
// api.private
// --

util.urlRE = /\/?[?#][^!=:][^ ]+/g;
util.boilRE = /([^\/ ]*\/[^\/ ]*|[^\. ]+\.)/g;

function boil(path, o){
  if(typeof path !== 'string'){
    throw new TypeError('argument should be a  `string`');
  }

  o = o || {};
  o.url = (path.match(/[^\/ ]*\/\S*/g) || '')[0];
  o.path = path.replace(/[ ]+/g, ' ').trim();

  if(o.url){
    o.path = o.path.replace(o.url, o.url.replace(util.urlRE, '') || '/');
  }

  o.argv = o.path.replace(util.boilRE, '$& ').trim().split(/[ ]+/);

  return o;
}
<|endoftext|>


<commit_before>'use strict';

var jsdom = require('jsdom');
var fs = require('fs');

var Context = function () {
    // We provide an empty DOM that allows some basic parts of AngularJS to work,
    // but we're not actually expecting to render an app in here... it just gives
    // us an anchor document so we can do things like call document.createElement
    // when using jqLite/jQuery.
    var document = jsdom.jsdom(
        null,
        null,
        {
            // Don't do anything with external resources, since we're not actually
            // trying to emulate a browser here, just a DOM.
            FetchExternalResources: false,
            ProcessExternalResources: false,
            SkipExternalResources: false
        }
    );
    var window = document.parentWindow;
    // 'window' has already been contextified by jsdom, so we can just use it.
    var rawContext = window;

    var runFiles = function (filenames, callback) {
        var loadedCount = 0;
        var firstError;
        var sources = [];
        sources.length = filenames.length;

        var runSources = function () {
            if (firstError) {
                callback(false, firstError);
            }
            else {
                // now run the sources in the correct order
                try {
                    for (var i = 0; i < sources.length; i++) {
                        rawContext.run(sources[i], filenames[i]);
                    }
                }
                catch (err) {
                    firstError = err;
                    callback(false, err);
                }
            }
            if (! firstError) {
                callback(true);
            }
        };

        var makeLoadHandler = function (i) {
            return function (err, data) {
                loadedCount++;
                if (err) {
                    if (! firstError) {
                        firstError = err;
                    }
                }
                else {
                    sources[i] = data;
                }
                if (loadedCount === filenames.length) {
                    // we've got everything loaded, so now run them
                    runSources();
                }
            };
        };

        for (var i = 0; i < filenames.length; i++) {
            fs.readFile(
                filenames[i],
                'utf8',
                makeLoadHandler(i)
            );
        }

    };

    return {
        run: function (source, filename) {
            rawContext.run(source, filename);
        },

        runFile: function (fileName, callback) {
            runFiles([fileName], callback);
            fs.readFile(
                fileName,
                'utf8',
                function (err, data) {
                    if (err) {
                        callback(undefined, err);
                    }
                    else {
                        callback(rawContext.run(data, fileName));
                    }
                }
            );
        },

        runFiles: runFiles,

        hasAngular: function () {
            return typeof rawContext.angular === 'object';
        },

        getAngular: function () {
            return rawContext.angular;
        },

        hasRequire: function () {
            return typeof rawContext.require === 'object';
        },

        getRequire: function () {
            return rawContext.require;
        },

        module: function () {
            return rawContext.angular.module.apply(
                rawContext.angular.module,
                arguments
            );
        },

        injector: function (modules) {
            return rawContext.angular.injector(modules);
        },

        bootstrap: function (element, modules) {
            return rawContext.angular.bootstrap(element, modules);
        },

        element: function (param) {
            return rawContext.angular.element(param);
        },

        dispose: function () {
            window.close();
        }
    };
};

exports.Context = Context;
<commit_msg>The jsdom feature options need to be in a "features" sub-object.<commit_after>'use strict';

var jsdom = require('jsdom');
var fs = require('fs');

var Context = function () {
    // We provide an empty DOM that allows some basic parts of AngularJS to work,
    // but we're not actually expecting to render an app in here... it just gives
    // us an anchor document so we can do things like call document.createElement
    // when using jqLite/jQuery.
    var document = jsdom.jsdom(
        null,
        null,
        {
            features: {
                // Don't do anything with external resources, since we're not actually
                // trying to emulate a browser here, just a DOM.
                FetchExternalResources: false,
                ProcessExternalResources: false,
                SkipExternalResources: false
            }
        }
    );
    var window = document.parentWindow;
    // 'window' has already been contextified by jsdom, so we can just use it.
    var rawContext = window;

    var runFiles = function (filenames, callback) {
        var loadedCount = 0;
        var firstError;
        var sources = [];
        sources.length = filenames.length;

        var runSources = function () {
            if (firstError) {
                callback(false, firstError);
            }
            else {
                // now run the sources in the correct order
                try {
                    for (var i = 0; i < sources.length; i++) {
                        rawContext.run(sources[i], filenames[i]);
                    }
                }
                catch (err) {
                    firstError = err;
                    callback(false, err);
                }
            }
            if (! firstError) {
                callback(true);
            }
        };

        var makeLoadHandler = function (i) {
            return function (err, data) {
                loadedCount++;
                if (err) {
                    if (! firstError) {
                        firstError = err;
                    }
                }
                else {
                    sources[i] = data;
                }
                if (loadedCount === filenames.length) {
                    // we've got everything loaded, so now run them
                    runSources();
                }
            };
        };

        for (var i = 0; i < filenames.length; i++) {
            fs.readFile(
                filenames[i],
                'utf8',
                makeLoadHandler(i)
            );
        }

    };

    return {
        run: function (source, filename) {
            rawContext.run(source, filename);
        },

        runFile: function (fileName, callback) {
            runFiles([fileName], callback);
            fs.readFile(
                fileName,
                'utf8',
                function (err, data) {
                    if (err) {
                        callback(undefined, err);
                    }
                    else {
                        callback(rawContext.run(data, fileName));
                    }
                }
            );
        },

        runFiles: runFiles,

        hasAngular: function () {
            return typeof rawContext.angular === 'object';
        },

        getAngular: function () {
            return rawContext.angular;
        },

        hasRequire: function () {
            return typeof rawContext.require === 'object';
        },

        getRequire: function () {
            return rawContext.require;
        },

        module: function () {
            return rawContext.angular.module.apply(
                rawContext.angular.module,
                arguments
            );
        },

        injector: function (modules) {
            return rawContext.angular.injector(modules);
        },

        bootstrap: function (element, modules) {
            return rawContext.angular.bootstrap(element, modules);
        },

        element: function (param) {
            return rawContext.angular.element(param);
        },

        dispose: function () {
            window.close();
        }
    };
};

exports.Context = Context;
<|endoftext|>


<commit_before>// vim: set ts=2 sw=2:
"use strict";

let the_physics = new Physics();
let the_longcat = new LongCat(document.querySelector('.longcat'), the_physics);
let sections = setupSections();

function setupSections() {
  const allSections = document.querySelectorAll('.section');
  let sections = [];

  sections[0] = new WallSection(allSections[0], the_physics);
  sections[1] = new EarthSection(allSections[1], the_physics);
  sections[2] = new Section(allSections[2], the_physics);  // street
  sections[3] = new BuildingsSection(allSections[3], the_physics);
  sections[4] = new Section(allSections[4], the_physics); // clouds

  return sections;
}

window.requestAnimationFrame = window.requestAnimationFrame
                            || window.mozRequestAnimationFrame
                            || window.webkitRequestAnimationFrame
                            || window.msRequestAnimationFrame
                            || function(cb) { window.setTimeout(cb, 1000/60); };

const score_els = document.querySelectorAll('.score__number');

// Rather use window.performance if it's available.
// It has sub-millisecond precision, while Date.now only has milliseconds.
const rtc = window.performance || Date;
let t0 = rtc.now();

function mainloop() {
  let t = rtc.now();
  let dt = 0.001*(t - t0);  // from milliseconds to seconds

  // When the tab gets hidden, this animate loop is not called, which is good
  // as it pauses the game. But when the tab gets visible again, the dt is huge:
  // as large as the tab was hidden. We don't want this, as it undoes the pause.
  // so we only update on small dt.
  if (dt < 0.5) {
    dt = the_physics.update(dt);
    the_longcat.update(dt);

    sections.forEach(section => {
      section.update(dt);
    });

    // Update the titlebar according to the score.
    document.title = `Longcat is lo${'o'.repeat(the_physics.score)}ng!`

    // Update the score itself.
    score_els.forEach(el => { el.innerHTML = the_physics.score.toFixed(1); })
  }

  // For the next timestep.
  t0 = t;
  window.requestAnimationFrame(mainloop);
}
window.requestAnimationFrame(mainloop);

function raise_longcat(ev) {
  // Avoid stuff like drag/drop selection etc.
  ev.preventDefault();

  the_physics.speedup();
}

// A click raises the longcat!
window.addEventListener('mousedown', raise_longcat);
window.addEventListener('touchstart', raise_longcat);

// Some cheats for testing
window.addEventListener('keyup', (ev) => {
  ev.preventDefault();
  if (ev.key == 'ArrowUp') {
    the_physics.g = 0;
    the_physics.vy += 0.01;
  } else if (ev.key == 'ArrowDown') {
    the_physics.g = 0;
    the_physics.vy -= 0.01;
  } else if (ev.key == ' ') {
    the_physics.g = 0;
    the_physics.vy = 0;
    the_physics.a = 0;
  }
  console.log(ev.key)
})

window.addEventListener('keydown', (ev) => { ev.preventDefault(); });
<commit_msg>Fix: score_els has no method foreach,<commit_after>// vim: set ts=2 sw=2:
"use strict";

let the_physics = new Physics();
let the_longcat = new LongCat(document.querySelector('.longcat'), the_physics);
let sections = setupSections();

function setupSections() {
  const allSections = document.querySelectorAll('.section');
  let sections = [];

  sections[0] = new WallSection(allSections[0], the_physics);
  sections[1] = new EarthSection(allSections[1], the_physics);
  sections[2] = new Section(allSections[2], the_physics);  // street
  sections[3] = new BuildingsSection(allSections[3], the_physics);
  sections[4] = new Section(allSections[4], the_physics); // clouds

  return sections;
}

window.requestAnimationFrame = window.requestAnimationFrame
                            || window.mozRequestAnimationFrame
                            || window.webkitRequestAnimationFrame
                            || window.msRequestAnimationFrame
                            || function(cb) { window.setTimeout(cb, 1000/60); };

const score_els = document.querySelector('.score__number');

// Rather use window.performance if it's available.
// It has sub-millisecond precision, while Date.now only has milliseconds.
const rtc = window.performance || Date;
let t0 = rtc.now();

function mainloop() {
  let t = rtc.now();
  let dt = 0.001*(t - t0);  // from milliseconds to seconds

  // When the tab gets hidden, this animate loop is not called, which is good
  // as it pauses the game. But when the tab gets visible again, the dt is huge:
  // as large as the tab was hidden. We don't want this, as it undoes the pause.
  // so we only update on small dt.
  if (dt < 0.5) {
    dt = the_physics.update(dt);
    the_longcat.update(dt);

    sections.forEach(section => {
      section.update(dt);
    });

    // Update the titlebar according to the score.
    document.title = `Longcat is lo${'o'.repeat(the_physics.score)}ng!`

    // Update the score itself.
    score_els.innerHTML = the_physics.score.toFixed(1);
  }

  // For the next timestep.
  t0 = t;
  window.requestAnimationFrame(mainloop);
}
window.requestAnimationFrame(mainloop);

function raise_longcat(ev) {
  // Avoid stuff like drag/drop selection etc.
  ev.preventDefault();

  the_physics.speedup();
}

// A click raises the longcat!
window.addEventListener('mousedown', raise_longcat);
window.addEventListener('touchstart', raise_longcat);

// Some cheats for testing
window.addEventListener('keyup', (ev) => {
  ev.preventDefault();
  if (ev.key == 'ArrowUp') {
    the_physics.g = 0;
    the_physics.vy += 0.01;
  } else if (ev.key == 'ArrowDown') {
    the_physics.g = 0;
    the_physics.vy -= 0.01;
  } else if (ev.key == ' ') {
    the_physics.g = 0;
    the_physics.vy = 0;
    the_physics.a = 0;
  }
  console.log(ev.key)
})

window.addEventListener('keydown', (ev) => { ev.preventDefault(); });
<|endoftext|>


<commit_before>"use strict";

var xmlrpc = require('xmlrpc')
  , moment = require('moment');

module.exports = function (host, port, user, pass, options) {
  var defaults = options || {};
  var client = xmlrpc.createClient({
    host: host,
    port: port,
    path: '/',
    basic_auth: {
      user: user,
      pass: pass
    }
  });

  var callMethod = function(options, cb) {
    options = options || {};
    options.args = options.args || [];
    if(options.json === undefined)
      options.json = true;

    client.methodCall(options.method, options.args, function(error, value) {
      if(error) throw error;
      if(options.json) return cb(JSON.parse(value));
      return cb(value);
    });
  };

  var fromBase64 = function(value) {
    return new Buffer(value, 'base64').toString();
  };

  var toBase64 = function(value) {
    return new Buffer(value).toString('base64');
  };

  var fromUnix = function(value) {
    return moment.unix(parseInt(value, 10)).toDate();
  };

  return {
    addresses: {
      list: function(cb) {
        callMethod({ method: 'listAddresses' }, cb);
      },
      createRandom: function (label, cb) {
        callMethod({ method: 'createRandomAddress', args: [toBase64(label)], json: false }, cb);
      },
      createDeterministic: function(passphrase, cb) {
        callMethod({ method: 'createDeterministicAddresses', args: [toBase64(passphrase), 1, 0, 0, false, 1, 1] }, function(value) {
          if(value.addresses.length > 0) {
            return cb(value.addresses[0]);
          }
          return cb(null);
        });
      },
      getDeterministic: function (passphrase, cb) {
        callMethod({ method: 'getDeterministicAddress', args: [toBase64(passphrase), 3, 1], json: false }, cb);
      },
    },
    messages: {
      inbox: {
        list: function(cb) {
          callMethod({method: 'getAllInboxMessages' }, function(value) {
            var messages = value.inboxMessages;
            for(var i = 0; i < messages.length; ++i) {
              messages[i].subject = fromBase64(messages[i].subject);
              messages[i].message = fromBase64(messages[i].message);
              messages[i].receivedTime = fromUnix(messages[i].receivedTime);
            }
            cb(messages);
          });
        },
        single: function(messageId, cb) {
          callMethod({
            method: 'getInboxMessageById',
            args: [messageId]
          }, function(value) {
            var message = value.inboxMessage[0];
            message.subject = fromBase64(message.subject);
            message.message = fromBase64(message.message);
            message.receivedTime = fromUnix(message.receivedTime);
            cb(message);
          });
        },
      },
      sent: {
        list: function(cb) {
          callMethod({method: 'getAllSentMessages' }, function(value) {
            var messages = value.sentMessages;
            for(var i = 0; i < messages.length; ++i) {
              messages[i].subject = fromBase64(messages[i].subject);
              messages[i].message = fromBase64(messages[i].message);
              messages[i].lastActionTime = fromUnix(messages[i].lastActionTime);
            }
            cb(messages);
          });
        },
        single: function(messageId, cb) {
          callMethod({
            method: 'getSentMessageById',
            args: [messageId]
          }, function(value) {
            var message = value.inboxMessage[0];
            message.subject = fromBase64(message.subject);
            message.message = fromBase64(message.message);
            message.lastActionTime = fromUnix(message.lastActionTime);
            cb(message);
          });
        },
      },
      moveToTrash: function(messageId, cb) {
        callMethod({
          method: 'trashMessage',
          args: [messageId]
        }, function(value) {
            console.log(messgeId, value);
            var message;
            cb(message);
        });
      },
      send: function(toAddress, fromAddress, subject, message, cb) {
        callMethod({
          method: 'sendMessage',
          args: [toAddress, fromAddress, toBase64(subject), toBase64(message)],
          json: false
        }, cb);
      },
      broadcast: function(fromAddress, subject, message, cb) {
        callMethod({
          method: 'sendBroadcast',
          args: [fromAddress, toBase64(subject), toBase64(message)],
          json: false
        }, cb);
      },
      status: function(messageId, cb) {
        callMethod({
          method: 'getStatus',
          args: [messageId],
          json: false
        }, cb);
      }
    },
    subscriptions: {
      subscribe: function(address, label, cb) {
        console.log('subscriptions.subscribe has not been implemented');
      },
      unsubscribe: function(address, cb) {
        console.log('subscriptions.unsubscribe has not been implemented');
      }
    },
    test: {
      add: function(a, b, cb) {
        callMethod({ method: 'add', args: [a, b], json: false }, cb);
      },
      hello: function(word, word2, cb) {
        callMethod({ method: 'helloWorld', args: [word, word2], json: false }, cb);
      },
    },
  };
}<commit_msg>implement moveToTrash<commit_after>"use strict";

var xmlrpc = require('xmlrpc')
  , moment = require('moment');

module.exports = function (host, port, user, pass, options) {
  var defaults = options || {};
  var client = xmlrpc.createClient({
    host: host,
    port: port,
    path: '/',
    basic_auth: {
      user: user,
      pass: pass
    }
  });

  var callMethod = function(options, cb) {
    options = options || {};
    options.args = options.args || [];
    if(options.json === undefined)
      options.json = true;

    client.methodCall(options.method, options.args, function(error, value) {
      if(error) throw error;
      if(options.json) return cb(JSON.parse(value));
      return cb(value);
    });
  };

  var fromBase64 = function(value) {
    return new Buffer(value, 'base64').toString();
  };

  var toBase64 = function(value) {
    return new Buffer(value).toString('base64');
  };

  var fromUnix = function(value) {
    return moment.unix(parseInt(value, 10)).toDate();
  };

  return {
    addresses: {
      list: function(cb) {
        callMethod({ method: 'listAddresses' }, cb);
      },
      createRandom: function (label, cb) {
        callMethod({ method: 'createRandomAddress', args: [toBase64(label)], json: false }, cb);
      },
      createDeterministic: function(passphrase, cb) {
        callMethod({ method: 'createDeterministicAddresses', args: [toBase64(passphrase), 1, 0, 0, false, 1, 1] }, function(value) {
          if(value.addresses.length > 0) {
            return cb(value.addresses[0]);
          }
          return cb(null);
        });
      },
      getDeterministic: function (passphrase, cb) {
        callMethod({ method: 'getDeterministicAddress', args: [toBase64(passphrase), 3, 1], json: false }, cb);
      },
    },
    messages: {
      inbox: {
        list: function(cb) {
          callMethod({method: 'getAllInboxMessages' }, function(value) {
            var messages = value.inboxMessages;
            for(var i = 0; i < messages.length; ++i) {
              messages[i].subject = fromBase64(messages[i].subject);
              messages[i].message = fromBase64(messages[i].message);
              messages[i].receivedTime = fromUnix(messages[i].receivedTime);
            }
            cb(messages);
          });
        },
        single: function(messageId, cb) {
          callMethod({
            method: 'getInboxMessageById',
            args: [messageId]
          }, function(value) {
            var message = value.inboxMessage[0];
            message.subject = fromBase64(message.subject);
            message.message = fromBase64(message.message);
            message.receivedTime = fromUnix(message.receivedTime);
            cb(message);
          });
        },
      },
      sent: {
        list: function(cb) {
          callMethod({method: 'getAllSentMessages' }, function(value) {
            var messages = value.sentMessages;
            for(var i = 0; i < messages.length; ++i) {
              messages[i].subject = fromBase64(messages[i].subject);
              messages[i].message = fromBase64(messages[i].message);
              messages[i].lastActionTime = fromUnix(messages[i].lastActionTime);
            }
            cb(messages);
          });
        },
        single: function(messageId, cb) {
          callMethod({
            method: 'getSentMessageById',
            args: [messageId]
          }, function(value) {
            var message = value.inboxMessage[0];
            message.subject = fromBase64(message.subject);
            message.message = fromBase64(message.message);
            message.lastActionTime = fromUnix(message.lastActionTime);
            cb(message);
          });
        },
      },
      moveToTrash: function(messageId, cb) {
        callMethod({
            method: 'trashMessage',
            args: [messageId],
            json: false
        }, function(value) {
            cb(value);
        });
      },
      send: function(toAddress, fromAddress, subject, message, cb) {
        callMethod({
          method: 'sendMessage',
          args: [toAddress, fromAddress, toBase64(subject), toBase64(message)],
          json: false
        }, cb);
      },
      broadcast: function(fromAddress, subject, message, cb) {
        callMethod({
          method: 'sendBroadcast',
          args: [fromAddress, toBase64(subject), toBase64(message)],
          json: false
        }, cb);
      },
      status: function(messageId, cb) {
        callMethod({
          method: 'getStatus',
          args: [messageId],
          json: false
        }, cb);
      }
    },
    subscriptions: {
      subscribe: function(address, label, cb) {
        console.log('subscriptions.subscribe has not been implemented');
      },
      unsubscribe: function(address, cb) {
        console.log('subscriptions.unsubscribe has not been implemented');
      }
    },
    test: {
      add: function(a, b, cb) {
        callMethod({ method: 'add', args: [a, b], json: false }, cb);
      },
      hello: function(word, word2, cb) {
        callMethod({ method: 'helloWorld', args: [word, word2], json: false }, cb);
      },
    },
  };
}<|endoftext|>


<commit_before>/**
 * @file
 * @copyright (c) 2013 Stephan Brenner
 * @license   This project is released under the MIT License.
 *
 * This file implements a Node.js module for initiating socket.io connections
 * through a proxy server.
 */

(function(){
    var http = require('http');
    var https = require('https');
    var url = require('url');
    var io = require('socket.io-client');

    var tunnelPort = 61423;
    var tunnelServer;
    var initialized = false;

    exports.connect = function(destinationUrl, options) {
        var destination = url.parse(destinationUrl);
        if (!destination.port) {
            destination.port = destination.protocol === 'https:' ? 443 : 80;
        }

        if (!initialized) exports.init();

        if (typeof tunnelServer === 'undefined') return io.connect(destinationUrl, options);   // Direct connection

        options = options || {};
        options['force new connection'] = true;   // Allows one tunnel server to handle multiple destinations

        return io.connect('http://localhost:' + tunnelPort + '/' +
            '?protocol=' + destination.protocol.replace(':', '')  +
            '&hostname=' + destination.hostname +
            '&port=' + destination.port, options);
    };

    exports.init = function(proxyUrl) {
        initialized = true;

        if (typeof tunnelServer !== 'undefined') {
            tunnelServer.close();
            tunnelServer = undefined;
        }

        if (typeof proxyUrl === 'undefined') {
            if (process.env.http_proxy) {
                proxyUrl = process.env.http_proxy;
            } else {
                console.log('Direct connection (no proxy defined)');
                return;
            }
        }

        var proxy = url.parse(proxyUrl, true);

        tunnelServer = http.createServer(function (request, response) {
            var requestUrl = url.parse(request.url, true);
            var hostname = requestUrl.query.hostname;
            var port = requestUrl.query.port;

            var options = {
                hostname: typeof proxy !== 'undefined' ? proxy.hostname : hostname,
                port: typeof proxy !== 'undefined' ? proxy.port : port,
                path: requestUrl.pathname + '?t=' + requestUrl.query.t,
                method: request.method,
                headers: {
                    'Host': hostname + ':' + port
                }
            };

            var proxy_request = requestUrl.query.protocol === 'http'
                ? http.request(options)
                : https.request(options);

            proxy_request.addListener('response', function (proxy_response) {
                proxy_response.addListener('data', function (chunk) { response.write(chunk, 'binary'); });
                proxy_response.addListener('end', function () { response.end(); });
                response.writeHead(proxy_response.statusCode, proxy_response.headers);
            });

            request.addListener('data', function (chunk) { proxy_request.write(chunk, 'binary'); });
            request.addListener('end', function () { proxy_request.end(); });
        });

        tunnelServer.listen(tunnelPort);
        console.log('Proxy: ' + proxyUrl);
    };
})();
<commit_msg>listen to errors to prevent uncaught exceptions<commit_after>/**
 * @file
 * @copyright (c) 2013 Stephan Brenner
 * @license   This project is released under the MIT License.
 *
 * This file implements a Node.js module for initiating socket.io connections
 * through a proxy server.
 */

(function(){
    var http = require('http');
    var https = require('https');
    var url = require('url');
    var io = require('socket.io-client');

    var tunnelPort = 61423;
    var tunnelServer;
    var initialized = false;

    exports.connect = function(destinationUrl, options) {
        var destination = url.parse(destinationUrl);
        if (!destination.port) {
            destination.port = destination.protocol === 'https:' ? 443 : 80;
        }

        if (!initialized) exports.init();

        if (typeof tunnelServer === 'undefined') return io.connect(destinationUrl, options);   // Direct connection

        options = options || {};
        options['force new connection'] = true;   // Allows one tunnel server to handle multiple destinations

        return io.connect('http://localhost:' + tunnelPort + '/' +
            '?protocol=' + destination.protocol.replace(':', '')  +
            '&hostname=' + destination.hostname +
            '&port=' + destination.port, options);
    };

    exports.init = function(proxyUrl) {
        initialized = true;

        if (typeof tunnelServer !== 'undefined') {
            tunnelServer.close();
            tunnelServer = undefined;
        }

        if (typeof proxyUrl === 'undefined') {
            if (process.env.http_proxy) {
                proxyUrl = process.env.http_proxy;
            } else {
                console.log('Direct connection (no proxy defined)');
                return;
            }
        }

        var proxy = url.parse(proxyUrl, true);

        tunnelServer = http.createServer(function (request, response) {
            var requestUrl = url.parse(request.url, true);
            var hostname = requestUrl.query.hostname;
            var port = requestUrl.query.port;

            var options = {
                hostname: typeof proxy !== 'undefined' ? proxy.hostname : hostname,
                port: typeof proxy !== 'undefined' ? proxy.port : port,
                path: requestUrl.pathname + '?t=' + requestUrl.query.t,
                method: request.method,
                headers: {
                    'Host': hostname + ':' + port
                }
            };

            var proxy_request = requestUrl.query.protocol === 'http'
                ? http.request(options)
                : https.request(options);

            proxy_request.addListener('response', function (proxy_response) {
                proxy_response.addListener('data', function (chunk) { response.write(chunk, 'binary'); });
                proxy_response.addListener('end', function () { response.end(); });
                response.writeHead(proxy_response.statusCode, proxy_response.headers);
            });

            proxy_request.on('error', function(err) {
               console.log('Error: found error in socket.io-proxy - error is: ' + err);
               console.log(err.stack);
            });

            request.addListener('data', function (chunk) { proxy_request.write(chunk, 'binary'); });
            request.addListener('end', function () { proxy_request.end(); });
        });

        tunnelServer.listen(tunnelPort);
        console.log('Proxy: ' + proxyUrl);
    };
})();
<|endoftext|>


<commit_before>'use strict';

var utils = require('./utils');
var vow = require('vow');

/**
 * Шаблончики для разных БЕМ сущностей.
 *
 * @type {Object}
 */
var patterns = {
    block: /^([a-z\-]+)$/i,
    elem: /^([a-z\-]+)(__[a-z\-]+)$/i,
    elemMod: /^([a-z\-]+)(__[a-z\-]+)(_[a-z\-]+)(_[a-z\-]+)?$/i,
    mod: /^([a-z\-]+)(_[a-z\-]+)(_[a-z\-]+)?$/i
};

/**
 * Список технологий, используемый для создания файлов.
 *
 * @type {array}
 */
var techs = [
    'bemhtml',
    'css',
    'deps',
    'js'
];

/**
 * Создает файл для соответствующей технологии.
 *
 * @param  {string}  dir
 * @param  {string}  name
 * @param  {string}  tech
 * @return {promise}
 */
function createTech(dir, name, tech) {
    return function () {
        var filePath = tech === 'deps' ?
            utils.resolve(dir, name + '.deps.js') :
            utils.resolve(dir, name + '.' + tech);

        return utils.exists(filePath)
            .then(function (exist) {
                if (exist) {
                    return;
                }

                return utils.write(filePath, '');
            });
    };
}

/**
 * Формирует путь до БЕМ сущности.
 *
 * @param  {object} target
 * @return {string}
 */
function parseDirs(target) {
    // блок
    if (patterns.block.exec(target.base)) {
        return utils.resolve(target.dir, RegExp.$1);
    // модификатор блока
    } else if (patterns.mod.exec(target.base)) {
        return utils.resolve(target.dir, RegExp.$1, RegExp.$2);
    // элемент блока
    } else if (patterns.elem.exec(target.base)) {
        return utils.resolve(target.dir, RegExp.$1, RegExp.$2);
    // модификатор элемента
    } else if (patterns.elemMod.exec(target.base)) {
        return utils.resolve(target.dir, RegExp.$1, RegExp.$2, RegExp.$3);
    }

    throw {
        description: 'Unknown type of argument',
        parsedirs: target.base
    };
}

/**
 * Создает БЕМ сущность.
 *
 * @param  {string}  filePath
 * @param  {boolean} bemhtml
 * @param  {boolean} css
 * @param  {boolean} deps
 * @param  {boolean} js
 * @return {promise}
 */
module.exports = function (filePath) {
    var target = utils.parsePath(filePath);
    var dir = parseDirs(target);
    var promise = vow.resolve();

    promise.then(utils.mkdir(dir));

    var ln = arguments.length;
    for (var a = 1; a < ln; ++a) {
        if (!arguments[a]) {
            continue;
        }

        var tech = techs[a - 1];
        promise.then(createTech(dir, target.base, tech));
    }

    return promise;
};
<commit_msg>Поправил ошибки и добавил числа в регулярки<commit_after>'use strict';

var utils = require('./utils');
var vow = require('vow');

/**
 * Шаблончики для разных БЕМ сущностей.
 *
 * @type {Object}
 */
var patterns = {
    block: /^([a-z\-0-9]+)$/i,
    elem: /^([a-z\-0-9]+)(__[a-z\-0-9]+)$/i,
    elemMod: /^([a-z\-0-9]+)(__[a-z\-0-9]+)(_[a-z\-0-9]+)(_[a-z\-0-9]+)?$/i,
    mod: /^([a-z\-0-9]+)(_[a-z\-0-9]+)(_[a-z\-0-9]+)?$/i
};

/**
 * Список технологий, используемый для создания файлов.
 *
 * @type {array}
 */
var techs = [
    'bemhtml',
    'css',
    'deps',
    'js'
];

/**
 * Создает файл для соответствующей технологии.
 *
 * @param  {string}  dir
 * @param  {string}  name
 * @param  {string}  tech
 * @return {promise}
 */
function createTech(dir, name, tech) {
    return function () {
        var filePath = tech === 'deps' ?
            utils.resolve(dir, name + '.deps.js') :
            utils.resolve(dir, name + '.' + tech);

        return utils.exists(filePath)
            .then(function (exist) {
                if (exist) {
                    return;
                }

                return utils.write(filePath, '');
            });
    };
}

/**
 * Формирует путь до БЕМ сущности.
 *
 * @param  {object} target
 * @return {string}
 */
function parseDirs(target) {
    // блок
    if (patterns.block.exec(target.base)) {
        return utils.resolve(target.dir, RegExp.$1);
    // модификатор блока
    } else if (patterns.mod.exec(target.base)) {
        return utils.resolve(target.dir, RegExp.$1, RegExp.$2);
    // элемент блока
    } else if (patterns.elem.exec(target.base)) {
        return utils.resolve(target.dir, RegExp.$1, RegExp.$2);
    // модификатор элемента
    } else if (patterns.elemMod.exec(target.base)) {
        return utils.resolve(target.dir, RegExp.$1, RegExp.$2, RegExp.$3);
    }

    throw new SyntaxError('Unknown type of argument: "' + target.base + '"');
}

/**
 * Создает БЕМ сущность.
 *
 * @param  {string}  filePath
 * @param  {boolean} bemhtml
 * @param  {boolean} css
 * @param  {boolean} deps
 * @param  {boolean} js
 * @return {promise}
 */
module.exports = function (filePath) {
    var target = utils.parsePath(filePath);
    var dir = parseDirs(target);
    var promise = vow.resolve();

    promise.then(utils.mkdir(dir));

    var ln = arguments.length;
    for (var a = 1; a < ln; ++a) {
        if (!arguments[a]) {
            continue;
        }

        var tech = techs[a - 1];
        promise.then(createTech(dir, target.base, tech));
    }

    return promise;
};
<|endoftext|>


<commit_before>var fs = require('fs')
var pump = require('pump')
var dialog = require('electron').dialog
var userConfig = require('./user-config')
var exportGeoJson = require('osm-p2p-geojson')

module.exports = function (app) {
  var template = [
    {
      label: 'Archivo',
      submenu: [
        {
          label: 'Importar Configuración...',
          click: function (item, focusedWindow) {
            dialog.showOpenDialog({
              title: 'Selecionar archivo de configuración',
              filters: [{name: 'Mapeo Settings', extensions: ['mapeosettings']}],
              properties: ['openFile']
            }, function (filenames) {
              if (!filenames) return
              userConfig.importSettings(focusedWindow, filenames[0], onError)
              function onError (err) {
                if (!err) return
                dialog.showErrorBox(
                  'No pudo importar configuración',
                  'No pudo importar configuración por un error: ' + err
                )
              }
            })
          }
        },
        {
          label: 'Export as GeoJSON..',
          click: function (item, focusedWindow) {
            dialog.showSaveDialog({
              title: 'Save As..',
              defaultPath: 'export.geojson',
              filters: [{name: 'GeoJSON', extensions: ['geojson']}]
            }, function (filename) {
              if (!filename) return
              var bbox = [-Infinity, -Infinity, Infinity, Infinity]
              var out = fs.createWriteStream(filename)
              var ex = exportGeoJson(app.osm, {bbox: bbox})
              pump(ex, out, function (err) {
                if (err) {
                  dialog.showErrorBox('Error', 'Failed to export: ' + err)
                } else {
                  dialog.showMessageBox({
                    message: 'Export complete!',
                    buttons: ['OK']
                  })
                }
              })
            })
          },
          visible: true
        }
      ]
    },
    {
      label: 'Edición',
      submenu: [
        {
          label: 'Deshacer',
          accelerator: 'CmdOrCtrl+Z',
          role: 'undo',
          visible: false
        },
        {
          label: 'Rehacer',
          accelerator: 'Shift+CmdOrCtrl+Z',
          role: 'redo',
          visible: false
        },
        {
          type: 'separator'
        },
        {
          label: 'Cortar',
          accelerator: 'CmdOrCtrl+X',
          role: 'cut'
        },
        {
          label: 'Copiar',
          accelerator: 'CmdOrCtrl+C',
          role: 'copy'
        },
        {
          label: 'Pegar',
          accelerator: 'CmdOrCtrl+V',
          role: 'paste'
        },
        {
          label: 'Seleccionar todo',
          accelerator: 'CmdOrCtrl+A',
          role: 'selectall'
        }
      ]
    },
    {
      label: 'Visualización',
      submenu: [
        {
          label: 'Volver a cargar página',
          accelerator: 'CmdOrCtrl+R',
          click: function (item, focusedWindow) {
            if (focusedWindow) {
              focusedWindow.reload()
            }
          },
          visible: false
        },
        {
          label: 'Usar pantalla completa',
          accelerator: (function () {
            if (process.platform === 'darwin') {
              return 'Ctrl+Command+F'
            } else {
              return 'F11'
            }
          })(),
          click: function (item, focusedWindow) {
            if (focusedWindow) {
              focusedWindow.setFullScreen(!focusedWindow.isFullScreen())
            }
          }
        },
        {
          label: 'Abrir herramientas de desarrollo',
          accelerator: (function () {
            if (process.platform === 'darwin') {
              return 'Alt+Command+I'
            } else {
              return 'Ctrl+Shift+I'
            }
          })(),
          click: function (item, focusedWindow) {
            if (focusedWindow) {
              focusedWindow.toggleDevTools()
            }
          },
          visible: true
        },
        {
          label: 'Zoom a los datos',
          click: function (item, focusedWindow) {
            focusedWindow.webContents.send('zoom-to-data-request')
          },
          visible: true
        }
      ]
    },
    {
      label: 'Ventana',
      role: 'window',
      submenu: [
        {
          label: 'Minimizar',
          accelerator: 'CmdOrCtrl+M',
          role: 'minimize'
        },
        {
          label: 'Cerrar',
          accelerator: 'CmdOrCtrl+W',
          role: 'close'
        }
      ]
    },
    {
      label: 'Ayuda',
      role: 'help',
      submenu: [
      ]
    }
  ]

  if (process.platform === 'darwin') {
    var name = require('electron').app.getName()
    template.unshift({
      label: name,
      submenu: [
        {
          label: 'Acerca de ' + name,
          role: 'about'
        },
        {
          type: 'separator'
        },
        {
          label: 'Servicios',
          role: 'services',
          submenu: []
        },
        {
          type: 'separator'
        },
        {
          label: 'Ocultar ' + name,
          accelerator: 'Command+H',
          role: 'hide'
        },
        {
          label: 'Ocultar otros',
          accelerator: 'Command+Alt+H',
          role: 'hideothers'
        },
        {
          label: 'Mostrar todo',
          role: 'unhide'
        },
        {
          type: 'separator'
        },
        {
          label: 'Salir de ' + name,
          accelerator: 'Command+Q',
          click: function () { app.quit() }
        }
      ]
    })
    // Window menu.
    template[3].submenu.push(
      {
        type: 'separator'
      },
      {
        label: 'Traer todo al frente',
        role: 'front'
      }
    )
  }
  return template
}
<commit_msg>Translation attempts.<commit_after>var fs = require('fs')
var pump = require('pump')
var dialog = require('electron').dialog
var userConfig = require('./user-config')
var exportGeoJson = require('osm-p2p-geojson')

module.exports = function (app) {
  var template = [
    {
      label: 'Archivo',
      submenu: [
        {
          label: 'Importar Configuración...',
          click: function (item, focusedWindow) {
            dialog.showOpenDialog({
              title: 'Selecionar archivo de configuración',
              filters: [{name: 'Mapeo Settings', extensions: ['mapeosettings']}],
              properties: ['openFile']
            }, function (filenames) {
              if (!filenames) return
              userConfig.importSettings(focusedWindow, filenames[0], onError)
              function onError (err) {
                if (!err) return
                dialog.showErrorBox(
                  'No pudo importar configuración',
                  'No pudo importar configuración por un error: ' + err
                )
              }
            })
          }
        },
        {
          label: 'Export as GeoJSON..',
          click: function (item, focusedWindow) {
            dialog.showSaveDialog({
              title: 'Guardar como..',
              defaultPath: 'export.geojson',
              filters: [{name: 'GeoJSON', extensions: ['geojson']}]
            }, function (filename) {
              if (!filename) return
              var bbox = [-Infinity, -Infinity, Infinity, Infinity]
              var out = fs.createWriteStream(filename)
              var ex = exportGeoJson(app.osm, {bbox: bbox})
              pump(ex, out, function (err) {
                if (err) {
                  dialog.showErrorBox('Error', 'Error al exportar' + err)
                } else {
                  dialog.showMessageBox({
                    message: 'Exportación completa!',
                    buttons: ['OK']
                  })
                }
              })
            })
          },
          visible: true
        }
      ]
    },
    {
      label: 'Edición',
      submenu: [
        {
          label: 'Deshacer',
          accelerator: 'CmdOrCtrl+Z',
          role: 'undo',
          visible: false
        },
        {
          label: 'Rehacer',
          accelerator: 'Shift+CmdOrCtrl+Z',
          role: 'redo',
          visible: false
        },
        {
          type: 'separator'
        },
        {
          label: 'Cortar',
          accelerator: 'CmdOrCtrl+X',
          role: 'cut'
        },
        {
          label: 'Copiar',
          accelerator: 'CmdOrCtrl+C',
          role: 'copy'
        },
        {
          label: 'Pegar',
          accelerator: 'CmdOrCtrl+V',
          role: 'paste'
        },
        {
          label: 'Seleccionar todo',
          accelerator: 'CmdOrCtrl+A',
          role: 'selectall'
        }
      ]
    },
    {
      label: 'Visualización',
      submenu: [
        {
          label: 'Volver a cargar página',
          accelerator: 'CmdOrCtrl+R',
          click: function (item, focusedWindow) {
            if (focusedWindow) {
              focusedWindow.reload()
            }
          },
          visible: false
        },
        {
          label: 'Usar pantalla completa',
          accelerator: (function () {
            if (process.platform === 'darwin') {
              return 'Ctrl+Command+F'
            } else {
              return 'F11'
            }
          })(),
          click: function (item, focusedWindow) {
            if (focusedWindow) {
              focusedWindow.setFullScreen(!focusedWindow.isFullScreen())
            }
          }
        },
        {
          label: 'Abrir herramientas de desarrollo',
          accelerator: (function () {
            if (process.platform === 'darwin') {
              return 'Alt+Command+I'
            } else {
              return 'Ctrl+Shift+I'
            }
          })(),
          click: function (item, focusedWindow) {
            if (focusedWindow) {
              focusedWindow.toggleDevTools()
            }
          },
          visible: true
        },
        {
          label: 'Zoom a los datos',
          click: function (item, focusedWindow) {
            focusedWindow.webContents.send('zoom-to-data-request')
          },
          visible: true
        }
      ]
    },
    {
      label: 'Ventana',
      role: 'window',
      submenu: [
        {
          label: 'Minimizar',
          accelerator: 'CmdOrCtrl+M',
          role: 'minimize'
        },
        {
          label: 'Cerrar',
          accelerator: 'CmdOrCtrl+W',
          role: 'close'
        }
      ]
    },
    {
      label: 'Ayuda',
      role: 'help',
      submenu: [
      ]
    }
  ]

  if (process.platform === 'darwin') {
    var name = require('electron').app.getName()
    template.unshift({
      label: name,
      submenu: [
        {
          label: 'Acerca de ' + name,
          role: 'about'
        },
        {
          type: 'separator'
        },
        {
          label: 'Servicios',
          role: 'services',
          submenu: []
        },
        {
          type: 'separator'
        },
        {
          label: 'Ocultar ' + name,
          accelerator: 'Command+H',
          role: 'hide'
        },
        {
          label: 'Ocultar otros',
          accelerator: 'Command+Alt+H',
          role: 'hideothers'
        },
        {
          label: 'Mostrar todo',
          role: 'unhide'
        },
        {
          type: 'separator'
        },
        {
          label: 'Salir de ' + name,
          accelerator: 'Command+Q',
          click: function () { app.quit() }
        }
      ]
    })
    // Window menu.
    template[3].submenu.push(
      {
        type: 'separator'
      },
      {
        label: 'Traer todo al frente',
        role: 'front'
      }
    )
  }
  return template
}
<|endoftext|>


<commit_before>/*
 * @name: mock.js
 * @description:
 * @author: wondger@gmail.com
 * @date: 2014-01-11
 * @param:
 * @todo:
 * @changelog:
 */
var fs = require("fs");
var path = require("path");
var util = require("util");
var DATAPATH;

module.exports = exports = function(options) {
    DATAPATH = options && options.path;
    return function(api) {
        var file = path.join(DATAPATH, api + ".js");
        if (fs.existsSync(file)) {
            return require(file);
        }
        else {
            util.debug(file);
            return {
                success: false,
                message: "404"
            }
        }
    };
};
<commit_msg>mock require everytime<commit_after>/*
 * @name: mock.js
 * @description:
 * @author: wondger@gmail.com
 * @date: 2014-01-11
 * @param:
 * @todo:
 * @changelog:
 */
var fs = require("fs");
var path = require("path");
var util = require("util");
var DATAPATH;

module.exports = exports = function(options) {
    DATAPATH = options && options.path;
    return function(api) {
        var file = path.join(DATAPATH, api + ".js");
        if (fs.existsSync(file)) {
            require.cache[file] = null;
            return require(file);
        }
        else {
            util.debug(file);
            return {
                success: false,
                message: "404"
            }
        }
    };
};
<|endoftext|>


<commit_before>'use strict';

var usage = require('usage'),
    psTree = require('ps-tree'),
    step = require('step'),
    exec = require('child_process').exec,
    _ = require('underscore'),
    lxc = require('lxc'),
    sprintf = require('sprintf').sprintf;

var core = {};

var parseLxcPs = function(stdout) {
  var processes = stdout.split(/\n/);
  var params = [];

  for (var i=0; i<processes.length; i++) {
    params = processes[i].split(/\s+/);      // CONTAINER PID TTY TIME CMD

    if (params[4] == "init") {
      console.log(params[1]);
      return params[1];
    }
  };
};

core.cpuUsage = function (program) {
  var containerName = program.name;
  var cpuUsageValue = 0.0;

  console.log("Target container: " + program.name);

  step(
    function() {
      var lxcPs = "lxc-ps --name=" + program.name;
      var child = exec(lxcPs, this);
    },
    function(err, stdout, stderr) {
      var containerInitPid = parseLxcPs(stdout);
      console.log("INIT:" + containerInitPid);
      psTree(containerInitPid, this);
    },
    function(err, children) {

      var displayUsage = _.after(children.length, function(){
        console.log("Processes:" + children.length);
        console.log("CPU usage:" + cpuUsageValue);
      });

      _.each(children, function(target) {
        var pid = target.PID;

        usage.lookup(pid, function(err, result) {
          if (!err) {
            var oneUsageCpu = parseFloat(result.cpu);

            if (program.verbose) {
              console.log(sprintf("PID:%s\tCPU:%5.2f\n", pid, oneUsageCpu));
            }

            cpuUsageValue += oneUsageCpu;
            displayUsage();
          }
        });

      });
    }
  );
};

module.exports = core;

<commit_msg>出力フォーマット修正<commit_after>'use strict';

var usage = require('usage'),
    psTree = require('ps-tree'),
    step = require('step'),
    exec = require('child_process').exec,
    _ = require('underscore'),
    lxc = require('lxc'),
    sprintf = require('sprintf').sprintf;

var core = {};

var parseLxcPs = function(stdout) {
  var processes = stdout.split(/\n/);
  var params = [];

  for (var i=0; i<processes.length; i++) {
    params = processes[i].split(/\s+/);      // CONTAINER PID TTY TIME CMD

    if (params[4] == "init") {
      console.log(params[1]);
      return params[1];
    }
  };
};

core.cpuUsage = function (program) {
  var containerName = program.name;
  var cpuUsageValue = 0.0;

  console.log("Target container: " + program.name);

  step(
    function() {
      var lxcPs = "lxc-ps --name=" + program.name;
      var child = exec(lxcPs, this);
    },
    function(err, stdout, stderr) {
      var containerInitPid = parseLxcPs(stdout);
      console.log("INIT:" + containerInitPid);
      psTree(containerInitPid, this);
    },
    function(err, children) {

      var displayUsage = _.after(children.length, function(){
        console.log("Processes:" + children.length);
        console.log(sprintf("CPU usage:%5.2f", cpuUsageValue);
      });

      _.each(children, function(target) {
        var pid = target.PID;

        usage.lookup(pid, function(err, result) {
          if (!err) {
            var oneUsageCpu = parseFloat(result.cpu);

            if (program.verbose) {
              console.log(sprintf("PID:%s\tCPU:%5.2f", pid, oneUsageCpu));
            }

            cpuUsageValue += oneUsageCpu;
            displayUsage();
          }
        });

      });
    }
  );
};

module.exports = core;

<|endoftext|>


<commit_before>function step(curr, goal, speed) {
	speed = speed || 100;

	var distanceX = Math.abs(curr.x - goal.x);
	var distanceY = Math.abs(curr.y - goal.y);

	var directionX = distanceX / distanceY;
	var directionY = distanceY / distanceX;

	var stepX = Math.min(Math.min(speed, speed * directionX), distanceX);
	var stepY = Math.min(Math.min(speed, speed * directionY), distanceY);

	var newX = goal.x > curr.x ? curr.x + stepX : curr.x - stepX;
	var newY = goal.y > curr.y ? curr.y + stepY : curr.y - stepY;
	var newD = curr.d;

	if (goal.x > curr.x) {
		newD = 'r';
	} else if (goal.x < curr.x) {
		newD = 'l';
	}

	curr.assign({ x: newX, y: newY, d: newD });
}

function move(moving) {
	for (var id in moving) {
		var dPos = moving[id].dim;
		var gPos = moving[id].goal;
		var speed = moving[id].speed;

		step(dPos, gPos, speed);

		if (dPos.x.is(gPos.x) && dPos.y.is(gPos.y)) {
			delete moving[id];
		}
	}
}

module.exports = move;<commit_msg>@christopherobin helped me with the math :)<commit_after>function step(curr, goal, speed) {
	speed = speed || 100;

	var distanceX = goal.x - curr.x;
	var distanceY = goal.y - curr.y;

	var angle = Math.atan2(distanceY, distanceX);

	var stepX = speed * Math.cos(angle);
	var stepY = speed * Math.sin(angle);

	var newX = curr.x + (distanceX > 0 ? Math.min(stepX, distanceX) : Math.max(stepX, distanceX));
	var newY = curr.y + (distanceY > 0 ? Math.min(stepY, distanceY) : Math.max(stepY, distanceY));
	var newD = curr.d;

	if (goal.x > curr.x) {
		newD = 'r';
	} else if (goal.x < curr.x) {
		newD = 'l';
	}

	curr.assign({ x: newX, y: newY, d: newD });
}

function move(moving) {
	for (var id in moving) {
		var dPos = moving[id].dim;
		var gPos = moving[id].goal;
		var speed = moving[id].speed;

		step(dPos, gPos, speed);

		if (dPos.x.is(gPos.x) && dPos.y.is(gPos.y)) {
			delete moving[id];
		}
	}
}

module.exports = move;<|endoftext|>