<commit_before>// Load in dependencies
var rocambole = require('rocambole');
var rocamboleToken = require('rocambole-token');

// Define a helper for creating a generic token
exports.createToken = function (options) {
return {
    type: options.type, // e.g. Keyword, Whitespace
    value: options.value, // e.g. 'var', ' '
    root: options.root || null, // e.g. Program node
    next: null,
    prev: null
  };
};

// Define helper for cloning a token chain
// DEV: The first and last nodes will lack a previous and next node respectively
exports.cloneTokenChain = function (tokens, options) {
  // For each of the tokens
  var newTokens = [];
  tokens.forEach(function copyToken (token, index) {
    // Clone our token
    var newToken = exports.createToken({
      type: token.type, // e.g. Keyword, Whitespace
      value: token.value, // e.g. 'var', ' '
      root: options.root // e.g. Program node
    });

    // If there is a previous token, attach to it
    if (index > 0) {
      var lastToken = newTokens[index - 1];
      lastToken.next = newToken;
      newToken.prev = lastToken;
    }

    // Save our tokens
    newTokens.push(newToken);
  });

  // Return our new tokens
  return newTokens;
};

// Handle setting of options
var options;
exports.setOptions = function (_options) {
  options = _options;
};

// Define our transform function
exports._transformNode = function (node) {
  // If the token is not a variable declaration (e.g. `var`, `let`), exit early
  // https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Parser_API
  // interface VariableDeclaration <: Declaration {
  //     type: "VariableDeclaration";
  //     declarations: [ VariableDeclarator ];
  //     kind: "var" | "let" | "const";
  // }
  // interface VariableDeclarator <: Node {
  //   type: "VariableDeclarator";
  //   id: Pattern;
  //   init: Expression | null;
  // }
  if (node.type !== 'VariableDeclaration') {
    return node;
  }

  // If we are inside of a loop, do nothing (e.g. `for`, `while`, `do ... while`)
  // DEV: Technically, a while/dowhile can't have a `var` but this is for good measure
  var parentType = node.parent ? node.parent.type : '';
  if (parentType.match(/WhileStatement|DoWhileStatement|ForStatement|ForInStatement/)) {
    return node;
  }

  // Determine the terminating character
  // Example: `var foo = bar;`
  //   varDeclaration = {type: VariableDeclaration, declarations: [...], kind: 'var'}
  //   declarators[*] = {type: VariableDeclarator, id: {type: Identifier, name: 'foo'}, init: {type: Literal, value: 'bar'}}
  var varDeclaration = node;
  var declarators = varDeclaration.declarations;

  // Find the head and tail of the var declaration for reuse among its declaration clones
  // e.g. `var hello = 'world', goodbye = 'moon';` -> ['var', ' '] = starting tokens; ['hello = world'] = declaration; ...; [';'] = endToken
  var startingTokens = [];
  rocamboleToken.eachInBetween(varDeclaration.startToken, declarators[0].startToken.prev, function saveToken (token) {
    startingTokens.push(token);
  });
  // Determine whether we use automatic semicolon insertion or not
  var endingSemicolonToken = rocamboleToken.findNext(varDeclaration.endToken, function findStatementTerminator (token) {
    return rocamboleToken.isSemiColon(token) || rocamboleToken.isBr(token);
  });
  if (rocamboleToken.isBr(endingSemicolonToken)) {
    endingSemicolonToken = null;
  }

  // Additionally, find the whitespace tokens before our `var` started (e.g. all indents/whitespace)
  var preStartingTokens = [];
  var token = varDeclaration.startToken.prev;
  while (token) {
    // If the token is whitespace or an indent, save it
    // https://github.com/millermedeiros/rocambole-token/blob/fc03674b38f288dc545db0a5b2bdfd2d96cab170/is.js#L19-L25
    if (token.type === 'WhiteSpace' || token.type === 'Indent') {
      preStartingTokens.unshift(token);
      token = token.prev;
    // Otherwise, stop
    // DEV: We ignore line breaks because this could be the start of a program
    //   Also, line breaks can lead to weird edge cases so we keep it consistent/predictable with a single one
    } else {
      break;
    }
  }

  // Generate a `var` for each of the declarators
  // e.g. `var hello = 'world', goodbye = 'moon';` -> `var hello = 'world'; var goodbye = 'moon';`
  var declarations = declarators.map(function generateDeclaration (declarator, index) {
    // DEV: A brief refresher on nodes and tokens
    //   Nodes are the AST representation of parts of a program (e.g. Identifier, VariableDeclaration)
    //   Tokens are the actual chunks of code these represent (e.g. Keyword, WhiteSpace)
    //   Tokens can be present without there being a node related to them
    //   Nodes have a prev (previous node on the same level), next (next node on the same level),
    //     parent (node containing our node), and sometimes something like a `body` key where they declare child nodes
    //     `body` varies from node type to node type
    //   Tokens don't have levels but are one giant chain
    //   Tokens have next (next token to render), prev (previous token to render),
    //     root (root node of the entire token chain -- i.e. a Program node)
    //   Nodes also have startToken and endToken which are the tokens that a node will start/end on
    //     (e.g. `var` is the start token for a VariableDeclaration)
    //   The only attachment from tokens to nodes is via `range` but this is brittle in rocambole so avoid it

    // Generate a new declaration similar to the original
    // Example: `var hello = 'world', goodbye = 'moon';` should use `var` and have a trailing semicolon `;`
    // https://github.com/millermedeiros/rocambole/blob/a3d0d63d58b769d13bad288aca32c6e2f7766542/rocambole.js#L69-L74
    var declaration = {
      type: varDeclaration.type, // should always be `VariableDeclaration`
      declarations: [declarator],
      kind: varDeclaration.kind, // (e.g. `var`, `let`)
      toString: varDeclaration.toString
      // prev: bound later
      // next: bound later
      // startToken: bound later
      // endToken: bound later
    };
  });

  // Set up linkages for nodes
  // DEV: None of these changes will affect the token chain
  //   However, each `node.toString()` is more/less impractical as there are no tokens bound to declarations
  declarations.forEach(function connectNodes (declaration, index) {
    // Attach declaration as the declarator's parent node
    var declarator = declaration.declarations[0];
    declarator.parent = declaration;

    // If this is the first node, connect to var declaration's previous node
    if (index === 0) {
      var varDeclarationPrevNode = varDeclaration.prev;
      if (varDeclarationPrevNode) {
        declaration.prev = varDeclarationPrevNode;
        varDeclarationPrevNode.next = declaration;
      }
    // Otherwise, connect to the last declaration
    } else {
      var lastDeclarationNode = declarations[index - 1];
      declaration.prev = lastDeclarationNode;
      lastDeclarationNode.next = declaration;
    }

    // If this is the last node, connect it to var declaration's next node
    if (index === declarations.length - 1) {
      var varDeclarationNextNode = varDeclaration.next;
      if (varDeclarationNextNode) {
        declaration.next = varDeclarationNextNode;
        varDeclarationNextNode.prev = declaration;
      }
    // Otherwise, do nothing as we will connect to the next node via the previous if/else
    } else {
      // Do nothing
    }

    // In all cases, save this var declaration's parent node as this declaration node's parent
    declaration.parent = varDeclaration.parent;
  });

  // Swap the declarations in the `body` of the parent block statement
  // e.g. `BlockStatement.body = [{orig VariableDeclaration}, some other expressions]`
  //     -> `BlockStatement.body = [{new VariableDeclaration}, {another new VariableDeclaration}, some other expressions]`
  var varDeclarationParentNode = varDeclaration.parent;
  var varDeclarationParentBodyIndex = varDeclarationParentNode.body.indexOf(varDeclaration);
  varDeclarationParentNode.body.splice(varDeclarationParentBodyIndex, 1, declarations);

  // // Copy the token chains for our varDeclaration onto the current declaration
  // var newStartingTokens = exports.cloneTokenChain(startingTokens, {
  //   root: varDeclaration.startToken.root /* Always Program node */
  // });
  // var newEndingTokens = exports.cloneTokenChain(endingTokens, {
  //   root: varDeclaration.endToken.root /* Always Program node */
  // });

  // // Attach declarator's starts/ends to our declaration
  // //   Handle node
  // declarator.parent = declaration;
  // //   Handle tokens
  // // DEV: There is always a starting token since we need a `var`
  // declarator.startToken.prev = newStartingTokens[newStartingTokens.length - 1];
  // newStartingTokens[newStartingTokens.length - 1].next = declarator.startToken;
  // // If there are ending tokens (e.g. `;`), then use them
  // if (newEndingTokens.length) {
  //   declarator.endToken.next = newEndingTokens[0];
  //   newEndingTokens[0].prev = declarator.endToken;
  // }

  // // Attach declaration tokens
  // declaration.startToken = newStartingTokens[0];
  // // If there are ending tokens (e.g. `;`), then use them
  // if (newEndingTokens.length) {
  //   declaration.endToken = newEndingTokens[newEndingTokens.length - 1];
  // // Otherwise, use the same end token as the declarator
  // } else {
  //   declaration.endToken = declarator.endToken;
  // }

  // // If this is the first declaration, replace the previous node/token of the original declaration
  // if (index === 0) {
  //   // Replace nodes
  //   var varDeclarationPrevNode = varDeclaration.prev;
  //   if (varDeclarationPrevNode) {
  //     varDeclarationPrevNode.next = declaration;
  //     declaration.prev = varDeclarationPrevNode;
  //   }

  //   // Replace tokens
  //   // https://github.com/millermedeiros/rocambole-token/blob/fc03674b38f288dc545db0a5b2bdfd2d96cab170/remove.js#L10-L23
  //   var varDeclarationPrevToken = varDeclaration.startToken.prev;
  //   if (varDeclarationPrevToken) {
  //     varDeclarationPrevToken.next = declaration.startToken;
  //     declaration.startToken.prev = varDeclarationPrevToken;
  //   } else if (varDeclaration.startToken.root) {
  //     var varDeclarationRootNode = varDeclaration.startToken.root;
  //     varDeclarationRootNode.startToken = declaration.startToken;
  //   }
  // // Otherwise, connect this to the previous declaration
  // } else {
  //   // Attach nodes
  //   var lastDeclaration = declarations[index - 1];
  //   lastDeclaration.next = declaration;
  //   declaration.prev = lastDeclaration;

  //   // If there are prestarting tokens (e.g. whitespace before a `var`), then build/attach them now
  //   var linkingStartToken = declaration.startToken;
  //   var linkingEndToken = declaration.startToken;
  //   if (preStartingTokens.length) {
  //     var newPreStartingTokens = exports.cloneTokenChain(preStartingTokens, {
  //       root: varDeclaration.startToken.prev.root /* Always Program node*/
  //     });
  //     linkingStartToken = newPreStartingTokens[0];
  //     linkingEndToken = newPreStartingTokens[newPreStartingTokens.length - 1];
  //     linkingEndToken.next = declaration.startToken;
  //     declaration.startToken.prev = linkingEndToken;
  //   }

  //   // If there's a newline between declarators, then inject a newline between indentation and the last declaration
  //   if (lineBreakTokenBetweenDeclarators) {
  //     var lineBreakToken = exports.createToken({
  //       type: lineBreakTokenBetweenDeclarators.type, // e.g. 'LineBreak'
  //       value: lineBreakTokenBetweenDeclarators.value, // e.g. '\n', '\r\n'
  //       root: lineBreakTokenBetweenDeclarators.root // e.g. Program node
  //     });
  //     lineBreakToken.next = linkingStartToken;
  //     linkingStartToken.prev = lineBreakToken;
  //     linkingStartToken = lineBreakToken;
  //   }

  //   // Attach tokens
  //   lastDeclaration.endToken.next = linkingStartToken;
  //   linkingEndToken.prev = lastDeclaration.endToken;
  // }

  // // If this is the last declaration, replace the next node/token of the original declaration
  // // DEV: There is no otherwise case as we take care of that when linking to "previous" declarations
  // if (index === declarators.length - 1) {
  //   // Replace nodes
  //   var varDeclarationNextNode = varDeclaration.next;
  //   if (varDeclarationNextNode) {
  //     varDeclarationNextNode.prev = declaration;
  //     declaration.next = varDeclarationNextNode;
  //   }

  //   // Replace tokens
  //   // https://github.com/millermedeiros/rocambole-token/blob/fc03674b38f288dc545db0a5b2bdfd2d96cab170/remove.js#L10-L23
  //   var varDeclarationNextToken = varDeclaration.endToken.next;
  //   if (varDeclarationNextToken) {
  //     varDeclarationNextToken.prev = declaration.endToken;
  //     declaration.endToken.next = varDeclarationNextToken;
  //   } else if (varDeclaration.endToken.root) {
  //     var varDeclarationRootNode = varDeclaration.endToken.root;
  //     varDeclarationRootNode.endToken = declaration.endToken;
  //   }
  // }

  console.log('FINAL', node.parent.toString());

  // Return the updated node
  return node;
};

// Export our transformation
// https://github.com/millermedeiros/esformatter/tree/v0.4.3#transformbeforeast
exports.transform = function (ast) {
  rocambole.moonwalk(ast, exports._transformNode);
};
<commit_msg>Making progress on script<commit_after>// Load in dependencies
var rocambole = require('rocambole');
var rocamboleToken = require('rocambole-token');

// Define a helper for creating a generic token
exports.createToken = function (options) {
return {
    type: options.type, // e.g. Keyword, Whitespace
    value: options.value, // e.g. 'var', ' '
    root: options.root || null, // e.g. Program node
    next: null,
    prev: null
  };
};

// Define helper for cloning a token chain
// DEV: The first and last nodes will lack a previous and next node respectively
exports.cloneTokenChain = function (tokens, options) {
  // For each of the tokens
  var newTokens = [];
  tokens.forEach(function copyToken (token, index) {
    // Clone our token
    var newToken = exports.createToken({
      type: token.type, // e.g. Keyword, Whitespace
      value: token.value, // e.g. 'var', ' '
      root: options.root // e.g. Program node
    });

    // If there is a previous token, attach to it
    if (index > 0) {
      var lastToken = newTokens[index - 1];
      lastToken.next = newToken;
      newToken.prev = lastToken;
    }

    // Save our tokens
    newTokens.push(newToken);
  });

  // Return our new tokens
  return newTokens;
};

// Handle setting of options
var options;
exports.setOptions = function (_options) {
  options = _options;
};

// Define our transform function
exports._transformNode = function (node) {
  // If the token is not a variable declaration (e.g. `var`, `let`), exit early
  // https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Parser_API
  // interface VariableDeclaration <: Declaration {
  //     type: "VariableDeclaration";
  //     declarations: [ VariableDeclarator ];
  //     kind: "var" | "let" | "const";
  // }
  // interface VariableDeclarator <: Node {
  //   type: "VariableDeclarator";
  //   id: Pattern;
  //   init: Expression | null;
  // }
  if (node.type !== 'VariableDeclaration') {
    return node;
  }

  // If we are inside of a loop, do nothing (e.g. `for`, `while`, `do ... while`)
  // DEV: Technically, a while/dowhile can't have a `var` but this is for good measure
  var parentType = node.parent ? node.parent.type : '';
  if (parentType.match(/WhileStatement|DoWhileStatement|ForStatement|ForInStatement/)) {
    return node;
  }

  // Determine the terminating character
  // Example: `var foo = bar;`
  //   varDeclaration = {type: VariableDeclaration, declarations: [...], kind: 'var'}
  //   declarators[*] = {type: VariableDeclarator, id: {type: Identifier, name: 'foo'}, init: {type: Literal, value: 'bar'}}
  var varDeclaration = node;
  var declarators = varDeclaration.declarations;

  // Find the head and tail of the var declaration for reuse among its declaration clones
  // e.g. `var hello = 'world', goodbye = 'moon';` -> ['var', ' '] = starting tokens; ['hello = world'] = declaration; ...; [';'] = endToken
  var startingTokens = [];
  rocamboleToken.eachInBetween(varDeclaration.startToken, declarators[0].startToken.prev, function saveToken (token) {
    startingTokens.push(token);
  });
  // Determine whether we use automatic semicolon insertion or not
  var endingSemicolonToken = rocamboleToken.findNext(varDeclaration.endToken, function findStatementTerminator (token) {
    return rocamboleToken.isSemiColon(token) || rocamboleToken.isBr(token);
  });
  if (rocamboleToken.isBr(endingSemicolonToken)) {
    endingSemicolonToken = null;
  }

  // Additionally, find the whitespace tokens before our `var` started (e.g. all indents/whitespace)
  var preStartingTokens = [];
  var token = varDeclaration.startToken.prev;
  while (token) {
    // If the token is whitespace or an indent, save it
    // https://github.com/millermedeiros/rocambole-token/blob/fc03674b38f288dc545db0a5b2bdfd2d96cab170/is.js#L19-L25
    if (token.type === 'WhiteSpace' || token.type === 'Indent') {
      preStartingTokens.unshift(token);
      token = token.prev;
    // Otherwise, stop
    // DEV: We ignore line breaks because this could be the start of a program
    //   Also, line breaks can lead to weird edge cases so we keep it consistent/predictable with a single one
    } else {
      break;
    }
  }

  // Generate a `var` for each of the declarators
  // e.g. `var hello = 'world', goodbye = 'moon';` -> `var hello = 'world'; var goodbye = 'moon';`
  var declarations = declarators.map(function generateDeclaration (declarator, index) {
    // DEV: A brief refresher on nodes and tokens
    //   Nodes are the AST representation of parts of a program (e.g. Identifier, VariableDeclaration)
    //   Tokens are the actual chunks of code these represent (e.g. Keyword, WhiteSpace)
    //   Tokens can be present without there being a node related to them
    //   Nodes have a prev (previous node on the same level), next (next node on the same level),
    //     parent (node containing our node), and sometimes something like a `body` key where they declare child nodes
    //     `body` varies from node type to node type
    //   Tokens don't have levels but are one giant chain
    //   Tokens have next (next token to render), prev (previous token to render),
    //     root (root node of the entire token chain -- i.e. a Program node)
    //   Nodes also have startToken and endToken which are the tokens that a node will start/end on
    //     (e.g. `var` is the start token for a VariableDeclaration)
    //   The only attachment from tokens to nodes is via `range` but this is brittle in rocambole so avoid it

    // Generate a new declaration similar to the original
    // Example: `var hello = 'world', goodbye = 'moon';` should use `var` and have a trailing semicolon `;`
    // https://github.com/millermedeiros/rocambole/blob/a3d0d63d58b769d13bad288aca32c6e2f7766542/rocambole.js#L69-L74
    var declaration = {
      type: varDeclaration.type, // should always be `VariableDeclaration`
      declarations: [declarator],
      kind: varDeclaration.kind, // (e.g. `var`, `let`)
      toString: varDeclaration.toString
      // prev: bound later
      // next: bound later
      // startToken: bound later
      // endToken: bound later
    };
  });

  // Set up linkages for nodes
  // DEV: None of these changes will affect the token chain
  //   However, each `node.toString()` is more/less impractical as there are no tokens bound to declarations
  declarations.forEach(function connectNodes (declaration, index) {
    // Attach declaration as the declarator's parent node
    var declarator = declaration.declarations[0];
    declarator.parent = declaration;

    // If this is the first node, connect to var declaration's previous node
    if (index === 0) {
      var varDeclarationPrevNode = varDeclaration.prev;
      if (varDeclarationPrevNode) {
        declaration.prev = varDeclarationPrevNode;
        varDeclarationPrevNode.next = declaration;
      }
    // Otherwise, connect to the last declaration
    } else {
      var lastDeclarationNode = declarations[index - 1];
      declaration.prev = lastDeclarationNode;
      lastDeclarationNode.next = declaration;
    }

    // If this is the last node, connect it to var declaration's next node
    if (index === declarations.length - 1) {
      var varDeclarationNextNode = varDeclaration.next;
      if (varDeclarationNextNode) {
        declaration.next = varDeclarationNextNode;
        varDeclarationNextNode.prev = declaration;
      }
    // Otherwise, do nothing as we will connect to the next node via the previous if/else
    } else {
      // Do nothing
    }

    // In all cases, save this var declaration's parent node as this declaration node's parent
    declaration.parent = varDeclaration.parent;
  });

  // Swap the declarations in the `body` of the parent block statement
  // e.g. `BlockStatement.body = [{orig VariableDeclaration}, some other expressions]`
  //     -> `BlockStatement.body = [{new VariableDeclaration}, {another new VariableDeclaration}, some other expressions]`
  var varDeclarationParentNode = varDeclaration.parent;
  var varDeclarationParentBodyIndex = varDeclarationParentNode.body.indexOf(varDeclaration);
  varDeclarationParentNode.body.splice(varDeclarationParentBodyIndex, 1, declarations);

  // Handle token bindings (aka the annoying/hard part)
  declarations.forEach(function defineAndAttachTokens (declaration, index) {
    // DEV: We have a few linkages to perform:
    //   Example: HEAD; var a = 1, b = 2; TAIL
    //     VariableDeclaration tokens = ['var', ' ', 'a', ' ', '=', ..., ';']
    //     VariableDeclarator tokens = ['a', ' ', '=', ..., '1']
    //   We need to: Link FIRST VariableDeclaration to HEAD
    //   We need to: Link each VariableDeclaration start to VariableDeclarator start
    //   We need to: Link each VariableDeclaration end to VariableDeclarator end
    //   We need to  Insert terminating content for each VariableDeclaration between VariableDeclaration's (e.g. `;\n  `)
    //   We need to: Link LAST VariableDeclaration to TAIL
    // Define our starting tokens (e.g. `['var', ' ']`)
    var declarator = declaration.declarations[0];
    var newStartingTokens = exports.cloneTokenChain(startingTokens, {
      root: varDeclaration.startToken.root /* Always Program node */
    });
    // DEV: This is always defined as we always need a `var` keyword
    declaration.startToken = newStartingTokens[0];

    // FIRST STEP: Link FIRST VariableDeclaration to HEAD
    // If there is a previous token, overwrite previous/next bindings
    var varDeclarationPrevToken = varDeclaration.startToken.prev;
    if (varDeclarationPrevToken) {
      varDeclarationPrevToken.next = declaration.startToken;
      declaration.startToken.prev = varDeclarationPrevToken;
    // Otherwise, we are at the start of the program so update the Program node to consider this token to be the start
    } else {
      declaration.root.startToken = declaration.startToken;
    }

    // SECOND STEP: Link each VariableDeclaration start to VariableDeclarator start
    // Connect the declaration's ending start token to our declarator's tokens
  });
  // var newEndingTokens = exports.cloneTokenChain(endingTokens, {
  //   root: varDeclaration.endToken.root /* Always Program node */
  // });

  // // Attach declarator's starts/ends to our declaration
  // //   Handle node
  // declarator.parent = declaration;
  // //   Handle tokens
  // // DEV: There is always a starting token since we need a `var`
  // declarator.startToken.prev = newStartingTokens[newStartingTokens.length - 1];
  // newStartingTokens[newStartingTokens.length - 1].next = declarator.startToken;
  // // If there are ending tokens (e.g. `;`), then use them
  // if (newEndingTokens.length) {
  //   declarator.endToken.next = newEndingTokens[0];
  //   newEndingTokens[0].prev = declarator.endToken;
  // }

  // // Attach declaration tokens
  // declaration.startToken = newStartingTokens[0];
  // // If there are ending tokens (e.g. `;`), then use them
  // if (newEndingTokens.length) {
  //   declaration.endToken = newEndingTokens[newEndingTokens.length - 1];
  // // Otherwise, use the same end token as the declarator
  // } else {
  //   declaration.endToken = declarator.endToken;
  // }

  // // If this is the first declaration, replace the previous node/token of the original declaration
  // if (index === 0) {
  //   // Replace nodes
  //   var varDeclarationPrevNode = varDeclaration.prev;
  //   if (varDeclarationPrevNode) {
  //     varDeclarationPrevNode.next = declaration;
  //     declaration.prev = varDeclarationPrevNode;
  //   }

  //   // Replace tokens
  //   // https://github.com/millermedeiros/rocambole-token/blob/fc03674b38f288dc545db0a5b2bdfd2d96cab170/remove.js#L10-L23
  //   var varDeclarationPrevToken = varDeclaration.startToken.prev;
  //   if (varDeclarationPrevToken) {
  //     varDeclarationPrevToken.next = declaration.startToken;
  //     declaration.startToken.prev = varDeclarationPrevToken;
  //   } else if (varDeclaration.startToken.root) {
  //     var varDeclarationRootNode = varDeclaration.startToken.root;
  //     varDeclarationRootNode.startToken = declaration.startToken;
  //   }
  // // Otherwise, connect this to the previous declaration
  // } else {
  //   // Attach nodes
  //   var lastDeclaration = declarations[index - 1];
  //   lastDeclaration.next = declaration;
  //   declaration.prev = lastDeclaration;

  //   // If there are prestarting tokens (e.g. whitespace before a `var`), then build/attach them now
  //   var linkingStartToken = declaration.startToken;
  //   var linkingEndToken = declaration.startToken;
  //   if (preStartingTokens.length) {
  //     var newPreStartingTokens = exports.cloneTokenChain(preStartingTokens, {
  //       root: varDeclaration.startToken.prev.root /* Always Program node*/
  //     });
  //     linkingStartToken = newPreStartingTokens[0];
  //     linkingEndToken = newPreStartingTokens[newPreStartingTokens.length - 1];
  //     linkingEndToken.next = declaration.startToken;
  //     declaration.startToken.prev = linkingEndToken;
  //   }

  //   // If there's a newline between declarators, then inject a newline between indentation and the last declaration
  //   if (lineBreakTokenBetweenDeclarators) {
  //     var lineBreakToken = exports.createToken({
  //       type: lineBreakTokenBetweenDeclarators.type, // e.g. 'LineBreak'
  //       value: lineBreakTokenBetweenDeclarators.value, // e.g. '\n', '\r\n'
  //       root: lineBreakTokenBetweenDeclarators.root // e.g. Program node
  //     });
  //     lineBreakToken.next = linkingStartToken;
  //     linkingStartToken.prev = lineBreakToken;
  //     linkingStartToken = lineBreakToken;
  //   }

  //   // Attach tokens
  //   lastDeclaration.endToken.next = linkingStartToken;
  //   linkingEndToken.prev = lastDeclaration.endToken;
  // }

  // // If this is the last declaration, replace the next node/token of the original declaration
  // // DEV: There is no otherwise case as we take care of that when linking to "previous" declarations
  // if (index === declarators.length - 1) {
  //   // Replace nodes
  //   var varDeclarationNextNode = varDeclaration.next;
  //   if (varDeclarationNextNode) {
  //     varDeclarationNextNode.prev = declaration;
  //     declaration.next = varDeclarationNextNode;
  //   }

  //   // Replace tokens
  //   // https://github.com/millermedeiros/rocambole-token/blob/fc03674b38f288dc545db0a5b2bdfd2d96cab170/remove.js#L10-L23
  //   var varDeclarationNextToken = varDeclaration.endToken.next;
  //   if (varDeclarationNextToken) {
  //     varDeclarationNextToken.prev = declaration.endToken;
  //     declaration.endToken.next = varDeclarationNextToken;
  //   } else if (varDeclaration.endToken.root) {
  //     var varDeclarationRootNode = varDeclaration.endToken.root;
  //     varDeclarationRootNode.endToken = declaration.endToken;
  //   }
  // }

  console.log('FINAL', node.parent.toString());

  // Return the updated node
  return node;
};

// Export our transformation
// https://github.com/millermedeiros/esformatter/tree/v0.4.3#transformbeforeast
exports.transform = function (ast) {
  rocambole.moonwalk(ast, exports._transformNode);
};
<|endoftext|>


<commit_before>// Load in dependencies
var rocambole = require('rocambole');

// TODO: This comment is *wrong*
// DEV: We use `tokenBefore` to update tokens (e.g. break down
//   vars) before they are fully parsed (e.g. `VariableDeclaration`)
// https://github.com/millermedeiros/esformatter/tree/v0.4.3#tokenbeforetoken

// TODO: How do we deal with `range`?

exports.transform = function (ast) {
  rocambole.moonwalk(ast, function (node) {
  // If the token is a variable declaration (e.g. `var`, `let`)
  // https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Parser_API
  // interface VariableDeclaration <: Declaration {
  //     type: "VariableDeclaration";
  //     declarations: [ VariableDeclarator ];
  //     kind: "var" | "let" | "const";
  // }
  if (node.type === 'VariableDeclaration') {
    // TODO: If we are inside of a loop, do nothing
    // Generate a `var` for each of the declarators
    var varDeclaration = node;
    var declarators = varDeclaration.declarations;
    var declarations = declarators.map(function generateDeclaration (declarator, index) {
      // Generate a new delcaration similar to the original
      // Example: `var`` ` ... `;` (i.e. `var` <-> ` ` <-> ... <-> `;`)
      var declaration = {
        type: varDeclaration.type, // should always be `VariableDeclaration`
        declarations: [declarator],
          // link to declaration's tokens
        kind: varDeclaration.kind, // (e.g. `var`, `let`)
        // prev: connect to `declarations[i - 1]` or if first, original var's `prev`
        // next: connect to `declarations[i + 1]` or if last, original var's `next`
        startToken: {
          type: varDeclaration.startToken.type, // should always be `Keyword`
          value: varDeclaration.startToken.value, // (e.g. `var`, `let`)
          // prev: connect to `declarations[i - 1].endToken` or if first, original var's `startToken.prev`
          next: {
            type: varDeclaration.startToken.next.type, // should be `WhiteSpace`
            value: varDeclaration.startToken.next.value, // (e.g. ` `)
            // prev: set later to `declaration.startToken`
            next: declarator.startToken
              // update `next.prev` later
          }
        },
        endToken: {
          type: varDeclaration.endToken.type, // (e.g. `Punctuation`, `LineBreak`)
          value: varDeclaration.endToken.value, // (e.g. `;`, '\n')
          prev: declarator.endToken
            // update `prev.next` later
          // next: connect to `declarator[i + 1].startToken` or if last, original var's `endToken.next`
        }
      };
      declaration.startToken.next.prev = declaration.startToken;

      // Handle link backs
      if (declaration.startToken.next.next) {
        declaration.startToken.next.next.prev = declaration.startToken.next;
      }
      if (declarator.endToken.prev) {
        declarator.endToken.prev.next = declarator.endToken;
      }

      // Return the declaration
      return declaration;
    });

    // Connect all of our declarations
    // Example: `Leading code` <-> `var ... ;` <-> `var ... ;` <-> `Trailing code`
    var varDeclarationStartToken = varDeclaration.startToken;
    var varDeclarationEndToken = varDeclaration.endToken;
    var lenMinusOne = declarations.length - 1;
    declarations.forEach(function connectDeclaration (declaration, index) {
      // If we are the first item, connect to `varDeclaration's` predecessor
      if (index === 0) {
        declaration.prev = varDeclaration.prev;
        declaration.startToken.prev = varDeclarationStartToken.prev;
      // Otherwise, connect to the previous declaration
      } else {
        declaration.prev = declarations[index - 1];
        declaration.startToken.prev = declarations[index - 1].endToken;
      }

      // Handle link backs
      if (declaration.prev) {
        declaration.prev.next = declaration;
      }
      if (declaration.startToken.prev) {
        declaration.startToken.prev.next = declaration.startToken;
      }

      // If we are the last item, connect to `varDeclaration's` successor
      if (index === lenMinusOne) {
        declaration.next = varDeclaration.next;
        declaration.endToken.next = varDeclarationEndToken.next;
      // Otherwise, connect to the next declaration
      } else {
        // DEV: Since the terminator could be `;` or `\n`, we handle whitespace later
        declaration.next = declarations[index + 1];
        declaration.endToken.next = declarations[index + 1].startToken;
      }

      // Handle link backs
      if (declaration.next) {
        declaration.next.prev = declaration;
      }
      if (declaration.endToken.next) {
        declaration.endToken.next.prev = declaration.endToken;
      }
    });

    // Connect all of our declarator's tokens
    declarators.forEach(function connectDeclarator (declarator, index) {
      // DEV: This is the whitespace character
      declarator.startToken.prev = declarations[index].startToken.next;
      declarator.endToken.next = declarations[index].endToken;
    });

    // If we have been working with semicolons, correct our indentation
    if (varDeclaration.endToken.value === ';') {
      // For each of the declarations
      declarations.forEach(function indentDeclaration (declaration, index) {
        // If we are the first element, do nothing (line break should already exist)
        if (index === 0) {
          return;
        }

        // Add a line break
        var varStartToken = declaration.startToken;
        declaration.startToken = {
          type: 'LineBreak',
          value: '\n',
          prev: varStartToken.prev,
          next: varStartToken
        };

        // Handle link backs
        if (declaration.startToken.prev) {
          declaration.startToken.prev.next = declaration.startToken;
        }

        // If the original `var` has indentation, add indentation
        if (varDeclaration.startToken.prev && varDeclaration.startToken.prev.type === 'Indent') {
          // Add indentation after the line break and before the `var`
          declaration.startToken.next = {
            type: varDeclaration.startToken.prev.type,
            value: varDeclaration.startToken.prev.value,
            prev: declaration.startToken,
            next: varStartToken
              // prev: declaration.startToken.next
          };
          varStartToken.prev = declaration.startToken.next;
        }
      });
    }

    // Overwrite `node` with our first declaration
    node = declarations[0];
  }

  // Return the updated node
  return node;
  });
};
<commit_msg>Indented everything<commit_after>// Load in dependencies
var rocambole = require('rocambole');

// TODO: This comment is *wrong*
// DEV: We use `tokenBefore` to update tokens (e.g. break down
//   vars) before they are fully parsed (e.g. `VariableDeclaration`)
// https://github.com/millermedeiros/esformatter/tree/v0.4.3#tokenbeforetoken

// TODO: How do we deal with `range`?

exports.transform = function (ast) {
  rocambole.moonwalk(ast, function (node) {
    // If the token is a variable declaration (e.g. `var`, `let`)
    // https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Parser_API
    // interface VariableDeclaration <: Declaration {
    //     type: "VariableDeclaration";
    //     declarations: [ VariableDeclarator ];
    //     kind: "var" | "let" | "const";
    // }
    if (node.type === 'VariableDeclaration') {
      // TODO: If we are inside of a loop, do nothing
      // Generate a `var` for each of the declarators
      var varDeclaration = node;
      var declarators = varDeclaration.declarations;
      var declarations = declarators.map(function generateDeclaration (declarator, index) {
        // Generate a new delcaration similar to the original
        // Example: `var`` ` ... `;` (i.e. `var` <-> ` ` <-> ... <-> `;`)
        var declaration = {
          type: varDeclaration.type, // should always be `VariableDeclaration`
          declarations: [declarator],
            // link to declaration's tokens
          kind: varDeclaration.kind, // (e.g. `var`, `let`)
          // prev: connect to `declarations[i - 1]` or if first, original var's `prev`
          // next: connect to `declarations[i + 1]` or if last, original var's `next`
          startToken: {
            type: varDeclaration.startToken.type, // should always be `Keyword`
            value: varDeclaration.startToken.value, // (e.g. `var`, `let`)
            // prev: connect to `declarations[i - 1].endToken` or if first, original var's `startToken.prev`
            next: {
              type: varDeclaration.startToken.next.type, // should be `WhiteSpace`
              value: varDeclaration.startToken.next.value, // (e.g. ` `)
              // prev: set later to `declaration.startToken`
              next: declarator.startToken
                // update `next.prev` later
            }
          },
          endToken: {
            type: varDeclaration.endToken.type, // (e.g. `Punctuation`, `LineBreak`)
            value: varDeclaration.endToken.value, // (e.g. `;`, '\n')
            prev: declarator.endToken
              // update `prev.next` later
            // next: connect to `declarator[i + 1].startToken` or if last, original var's `endToken.next`
          }
        };
        declaration.startToken.next.prev = declaration.startToken;

        // Handle link backs
        if (declaration.startToken.next.next) {
          declaration.startToken.next.next.prev = declaration.startToken.next;
        }
        if (declarator.endToken.prev) {
          declarator.endToken.prev.next = declarator.endToken;
        }

        // Return the declaration
        return declaration;
      });

      // Connect all of our declarations
      // Example: `Leading code` <-> `var ... ;` <-> `var ... ;` <-> `Trailing code`
      var varDeclarationStartToken = varDeclaration.startToken;
      var varDeclarationEndToken = varDeclaration.endToken;
      var lenMinusOne = declarations.length - 1;
      declarations.forEach(function connectDeclaration (declaration, index) {
        // If we are the first item, connect to `varDeclaration's` predecessor
        if (index === 0) {
          declaration.prev = varDeclaration.prev;
          declaration.startToken.prev = varDeclarationStartToken.prev;
        // Otherwise, connect to the previous declaration
        } else {
          declaration.prev = declarations[index - 1];
          declaration.startToken.prev = declarations[index - 1].endToken;
        }

        // Handle link backs
        if (declaration.prev) {
          declaration.prev.next = declaration;
        }
        if (declaration.startToken.prev) {
          declaration.startToken.prev.next = declaration.startToken;
        }

        // If we are the last item, connect to `varDeclaration's` successor
        if (index === lenMinusOne) {
          declaration.next = varDeclaration.next;
          declaration.endToken.next = varDeclarationEndToken.next;
        // Otherwise, connect to the next declaration
        } else {
          // DEV: Since the terminator could be `;` or `\n`, we handle whitespace later
          declaration.next = declarations[index + 1];
          declaration.endToken.next = declarations[index + 1].startToken;
        }

        // Handle link backs
        if (declaration.next) {
          declaration.next.prev = declaration;
        }
        if (declaration.endToken.next) {
          declaration.endToken.next.prev = declaration.endToken;
        }
      });

      // Connect all of our declarator's tokens
      declarators.forEach(function connectDeclarator (declarator, index) {
        // DEV: This is the whitespace character
        declarator.startToken.prev = declarations[index].startToken.next;
        declarator.endToken.next = declarations[index].endToken;
      });

      // If we have been working with semicolons, correct our indentation
      if (varDeclaration.endToken.value === ';') {
        // For each of the declarations
        declarations.forEach(function indentDeclaration (declaration, index) {
          // If we are the first element, do nothing (line break should already exist)
          if (index === 0) {
            return;
          }

          // Add a line break
          var varStartToken = declaration.startToken;
          declaration.startToken = {
            type: 'LineBreak',
            value: '\n',
            prev: varStartToken.prev,
            next: varStartToken
          };

          // Handle link backs
          if (declaration.startToken.prev) {
            declaration.startToken.prev.next = declaration.startToken;
          }

          // If the original `var` has indentation, add indentation
          if (varDeclaration.startToken.prev && varDeclaration.startToken.prev.type === 'Indent') {
            // Add indentation after the line break and before the `var`
            declaration.startToken.next = {
              type: varDeclaration.startToken.prev.type,
              value: varDeclaration.startToken.prev.value,
              prev: declaration.startToken,
              next: varStartToken
                // prev: declaration.startToken.next
            };
            varStartToken.prev = declaration.startToken.next;
          }
        });
      }

      // Overwrite `node` with our first declaration
      node = declarations[0];
    }

    // Return the updated node
    return node;
  });
};
<|endoftext|>


<commit_before>( function(){
    var autoload = {

        /***************************
         * DatePicker - Default CSS selector is .ink-datepicker
         ***************************/
         'Close_1': '.ink-dismiss',

        /***************************
         * DatePicker - Default CSS selector is .ink-datepicker
         ***************************/
         'DatePicker_1': '.ink-datepicker',

        /***************************
         * Gallery - Default CSS selector is ul.ink-gallery-source
         ***************************/
         'Gallery_1': 'ul.ink-gallery-source',

        /***************************
         * Modal - Default CSS selector is .ink-modal
         ***************************/
         'Modal_1': '.ink-modal',

        /***************************
         * ProgressBar - Default CSS selector is .ink-progress-bar
         ***************************/
         'ProgressBar_1': '.ink-progress-bar',

        /***************************
         * SortableList - Default CSS selector is .ink-sortable-list
         ***************************/
         'SortableList_1': '.ink-sortable-list',

        /***************************
         * Spy - Default CSS selector is *[data-spy="true"]
         ***************************/
         'Spy_1': '*[data-spy="true"]',

        /***************************
         * Sticky - Default CSS selector is .ink-navigation.sticky
         ***************************/
         'Sticky_1': '.ink-navigation.sticky',

        /***************************
         * Table - Default CSS selector is .ink-table
         ***************************/
         'Table_1': '.ink-table',

        /***************************
         * Tabs - Default CSS selector is .ink-tabs
         ***************************/
         'Tabs_1': '.ink-tabs',

        /***************************
         * TreeView - Default CSS selector is .ink-tree-view
         ***************************/
         'TreeView_1': '.ink-tree-view',

        /***************************
         * Toggle - Default CSS selector is .toggle
         ***************************/
         'Toggle_1': '.toggle'

    };

    window.siteInkInstances = {};
    Ink.requireModules(['Ink.Dom.Selector_1', 'Ink.Dom.Loaded_1', 'Ink.Util.Array_1', 'Ink.UI.SmoothScroller_1'],function( Selector, Loaded, InkArray, Scroller ){
        for( var module in autoload ){
            siteInkInstances[module] = [];
            (function(mod){
                Ink.requireModules( ['Ink.UI.' + mod ], function( component ) {
                    InkArray.each( Selector.select( autoload[mod] ), function( element ){
                        siteInkInstances[mod].push( new component(element) );
                    });
                });
            })(module);
        }
        Scroller.init();
    });
})();
<commit_msg>Improved autoload.js<commit_after>( function(){
    var autoload = {

        /***************************
         * DatePicker - Default CSS selector is .ink-datepicker
         ***************************/
         'Close_1': '.ink-dismiss',

        /***************************
         * DatePicker - Default CSS selector is .ink-datepicker
         ***************************/
         'DatePicker_1': '.ink-datepicker',

        /***************************
         * Gallery - Default CSS selector is ul.ink-gallery-source
         ***************************/
         'Gallery_1': 'ul.ink-gallery-source',

        /***************************
         * Modal - Default CSS selector is .ink-modal
         ***************************/
         'Modal_1': '.ink-modal',

        /***************************
         * ProgressBar - Default CSS selector is .ink-progress-bar
         ***************************/
         'ProgressBar_1': '.ink-progress-bar',

        /***************************
         * SortableList - Default CSS selector is .ink-sortable-list
         ***************************/
         'SortableList_1': '.ink-sortable-list',

        /***************************
         * Spy - Default CSS selector is *[data-spy="true"]
         ***************************/
         'Spy_1': '*[data-spy="true"]',

        /***************************
         * Sticky - Default CSS selector is .ink-navigation.sticky
         ***************************/
         'Sticky_1': '.ink-navigation.sticky',

        /***************************
         * Table - Default CSS selector is .ink-table
         ***************************/
         'Table_1': '.ink-table',

        /***************************
         * Tabs - Default CSS selector is .ink-tabs
         ***************************/
         'Tabs_1': '.ink-tabs',

        /***************************
         * TreeView - Default CSS selector is .ink-tree-view
         ***************************/
         'TreeView_1': '.ink-tree-view',

        /***************************
         * Toggle - Default CSS selector is .toggle
         ***************************/
         'Toggle_1': '.toggle'

    };

    window.siteInkInstances = {};
    Ink.requireModules(['Ink.Dom.Selector_1', 'Ink.Dom.Loaded_1', 'Ink.Util.Array_1', 'Ink.UI.SmoothScroller_1'],function( Selector, Loaded, InkArray, Scroller ){
        Loaded.run(function(){
            for( var module in autoload ){
                siteInkInstances[module] = [];
                (function(mod){
                    var elements = Selector.select( autoload[mod] );
                    if( elements.length ){
                        try{
                            Ink.requireModules( ['Ink.UI.' + mod ], function( component ) {
                                InkArray.each(elements, function( element ){
                                    siteInkInstances[mod].push( new component(element) );
                                });
                            });
                        } catch( e ){}
                    }
                })(module);
            }
            Scroller.init();
        })
    });
})();
<|endoftext|>


<commit_before>function initMap() {
    // INIT BASIC MAP
    var mapOptions = {
        zoom: 14,
        center: new google.maps.LatLng(39.7384303,-104.9888331),
        styles: [{"elementType":"geometry","stylers":[{"hue":"#ff4400"},{"saturation":-68},{"lightness":-4},{"gamma":0.72}]},{"featureType":"road","elementType":"labels.icon"},{"featureType":"landscape.man_made","elementType":"geometry","stylers":[{"hue":"#0077ff"},{"gamma":3.1}]},{"featureType":"water","stylers":[{"hue":"#00ccff"},{"gamma":0.44},{"saturation":-33}]},{"featureType":"poi.park","stylers":[{"hue":"#44ff00"},{"saturation":-23}]},{"featureType":"water","elementType":"labels.text.fill","stylers":[{"hue":"#007fff"},{"gamma":0.77},{"saturation":65},{"lightness":99}]},{"featureType":"poi.business", stylers: [ {visibility: "off" }]},
        {"featureType":"water","elementType":"labels.text.stroke","stylers":[{"gamma":0.11},{"weight":5.6},{"saturation":99},{"hue":"#0091ff"},{"lightness":-86}]},{"featureType":"transit.line","elementType":"geometry","stylers":[{"lightness":-48},{"hue":"#ff5e00"},{"gamma":1.2},{"saturation":-23}]},{"featureType":"transit","elementType":"labels.text.stroke","stylers":[{"saturation":-64},{"hue":"#ff9100"},{"lightness":16},{"gamma":0.47},{"weight":2.7}]}]
    }; <!-- TO CHANGE STYLE, USE SNAZZY MAPS AND COPY+PASTE ABOVE -->

    var mapElement = document.getElementById('map-canvas');
    var map = new google.maps.Map(mapElement, mapOptions);
    google.maps.event.addListener(map, 'click', function() { $("#popupModal").closeModal(c); });

    initSearchBox(map);
    initLegend(map);
    plotBuildings(map);
} // END MAP INITIALIZATION
		<commit_msg>Removed old map styling; restored default gmaps styles<commit_after>function initMap() {
    // INIT BASIC MAP
    var mapOptions = {
        zoom: 14,
        center: new google.maps.LatLng(39.7384303,-104.9888331),
        // styles: [{"elementType":"geometry","stylers":[{"hue":"#ff4400"},{"saturation":-68},{"lightness":-4},{"gamma":0.72}]},{"featureType":"road","elementType":"labels.icon"},{"featureType":"landscape.man_made","elementType":"geometry","stylers":[{"hue":"#0077ff"},{"gamma":3.1}]},{"featureType":"water","stylers":[{"hue":"#00ccff"},{"gamma":0.44},{"saturation":-33}]},{"featureType":"poi.park","stylers":[{"hue":"#44ff00"},{"saturation":-23}]},{"featureType":"water","elementType":"labels.text.fill","stylers":[{"hue":"#007fff"},{"gamma":0.77},{"saturation":65},{"lightness":99}]},{"featureType":"poi.business", stylers: [ {visibility: "off" }]},
        // {"featureType":"water","elementType":"labels.text.stroke","stylers":[{"gamma":0.11},{"weight":5.6},{"saturation":99},{"hue":"#0091ff"},{"lightness":-86}]},{"featureType":"transit.line","elementType":"geometry","stylers":[{"lightness":-48},{"hue":"#ff5e00"},{"gamma":1.2},{"saturation":-23}]},{"featureType":"transit","elementType":"labels.text.stroke","stylers":[{"saturation":-64},{"hue":"#ff9100"},{"lightness":16},{"gamma":0.47},{"weight":2.7}]}]
    }; <!-- TO CHANGE STYLE, USE SNAZZY MAPS AND COPY+PASTE ABOVE -->

    var mapElement = document.getElementById('map-canvas');
    var map = new google.maps.Map(mapElement, mapOptions);
    google.maps.event.addListener(map, 'click', function() { $("#popupModal").closeModal(c); });

    initSearchBox(map);
    initLegend(map);
    plotBuildings(map);
} // END MAP INITIALIZATION
		<|endoftext|>


<commit_before>//
//   Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing,
//   software distributed under the License is distributed on an "AS
//   IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
//   express or implied.  See the License for the specific language
//   governing permissions and limitations under the License.
//

'use strict';

var assert = require('assert'),
    redisModule = require('./redis'),
    sendRedis = redisModule.createClient(),
    rcvRedis = redisModule.createClient(),
    co = require('co'),
    log = require('./log');

exports.createEndPoint = function(name) {
    return new Courier(name);
};

function Courier(name) {
    this.name = name;
    this.handlers = {};

    log.info('New Courier instance created.');
}

Courier.prototype.start = function() {
    co(function*() {
        while (1) {
            var result = yield rcvRedis.brpop('inbox:' + this.name, 0);
            var msg = JSON.parse(result[1]);
            var handler = this.handlers[msg.type];
            log.info('MSG RCVD [' + msg.__sender + ' -> ' + this.name + '] DATA: ' + result[1]);

            assert(handler, this.name + ': Missing message handler for: ' + msg.type);

            if (isGeneratorFunction(handler)) {
                /*jshint -W083 */
                co(function*() {
                    yield handler(msg);
                })();
            } else {
                // Normal function
                handler(msg);
            }
        }
    }).call(this);
};

Courier.prototype.send = function(dest, msg) {
    var data = convert(msg, this.name, dest);

    co(function*() {
        yield sendRedis.lpush('inbox:' + dest, data);
    })();
};

Courier.prototype.on = function(type, callback) {
    this.handlers[type] = callback;
};

Courier.prototype.noop = function() {
    return null;
};

function convert(msg, sender, dest) {
    if (typeof msg === 'string') {
        msg = { type: msg };
    }
    msg.__sender = sender;
    msg = JSON.stringify(msg);

    log.info('MSG SENT [' + sender + ' -> ' + dest + '] DATA:' + msg);
    return msg;
}

function isGeneratorFunction(obj) {
    return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction';
}
<commit_msg>Avoid double logging of Courier messages<commit_after>//
//   Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing,
//   software distributed under the License is distributed on an "AS
//   IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
//   express or implied.  See the License for the specific language
//   governing permissions and limitations under the License.
//

'use strict';

var assert = require('assert'),
    redisModule = require('./redis'),
    sendRedis = redisModule.createClient(),
    rcvRedis = redisModule.createClient(),
    co = require('co'),
    log = require('./log');

exports.createEndPoint = function(name) {
    return new Courier(name);
};

function Courier(name) {
    this.name = name;
    this.handlers = {};

    log.info('New Courier instance created.');
}

Courier.prototype.start = function() {
    co(function*() {
        while (1) {
            var result = yield rcvRedis.brpop('inbox:' + this.name, 0);
            var msg = JSON.parse(result[1]);
            var handler = this.handlers[msg.type];
            log.info('MSG RCVD [' + msg.__sender + ' → ' + this.name + '] DATA: ' + result[1]);

            assert(handler, this.name + ': Missing message handler for: ' + msg.type);

            if (isGeneratorFunction(handler)) {
                /*jshint -W083 */
                co(function*() {
                    yield handler(msg);
                })();
            } else {
                // Normal function
                handler(msg);
            }
        }
    }).call(this);
};

Courier.prototype.send = function(dest, msg) {
    var data = convert(msg, this.name);

    co(function*() {
        yield sendRedis.lpush('inbox:' + dest, data);
    })();
};

Courier.prototype.on = function(type, callback) {
    this.handlers[type] = callback;
};

Courier.prototype.noop = function() {
    return null;
};

function convert(msg, sender) {
    if (typeof msg === 'string') {
        msg = { type: msg };
    }
    msg.__sender = sender;
    msg = JSON.stringify(msg);

    // log.info('MSG SENT [' + sender + ' -> ' + dest + '] DATA:' + msg);
    return msg;
}

function isGeneratorFunction(obj) {
    return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction';
}
<|endoftext|>


<commit_before>/* @flow */

import {Emitter, CompositeDisposable} from 'atom'
import FileDiffViewModel from './file-diff-view-model'
import CommitBoxViewModel from './commit-box-view-model'
import PushPullViewModel from './push-pull-view-model'

import type {Disposable} from 'atom'
import type GitStore from './git-store'
import type FileDiff from './file-diff'

export default class FileListViewModel {
  gitStore: GitStore;
  selectedIndex: number;
  emitter: Emitter;
  commitBoxViewModel: CommitBoxViewModel;
  pushPullViewModel: PushPullViewModel;
  subscriptions: CompositeDisposable;

  constructor (gitStore: GitStore) {
    this.gitStore = gitStore
    this.selectedIndex = 0
    this.emitter = new Emitter()
    this.subscriptions = new CompositeDisposable()
    this.commitBoxViewModel = new CommitBoxViewModel(gitStore)
    this.pushPullViewModel = new PushPullViewModel(gitStore)

    this.gitStore.onDidUpdate(() => this.emitUpdateEvent())
  }

  destroy () {
    this.subscriptions.dispose()
  }

  onDidUpdate (callback: Function): Disposable {
    return this.emitter.on('did-update', callback)
  }

  emitUpdateEvent () {
    this.emitter.emit('did-update')
  }

  onSelectionChanged (callback: Function): Disposable {
    return this.emitter.on('selection-changed', callback)
  }

  emitSelectionChangedEvent () {
    this.emitter.emit('selection-changed')
  }

  getGitStore (): GitStore {
    return this.gitStore
  }

  getSelectedIndex (): number {
    return this.selectedIndex
  }

  setSelectedIndex (index: number) {
    this.selectedIndex = index
    this.emitSelectionChangedEvent()
  }

  getSelectedFile (): FileDiff {
    return this.getFileAtIndex(this.selectedIndex)
  }

  openSelectedFileDiff (): Promise<void> {
    return this.gitStore.openFileDiff(this.getSelectedFile())
  }

  getFileAtIndex (index: number): FileDiff {
    return this.gitStore.getFiles()[index]
  }

  getDiffForPathName (name: string): FileDiff {
    return this.getGitStore().getOrCreateFileFromPathName(name)
  }

  openFile (): Promise<void> {
    return this.gitStore.openFile(this.getSelectedFile())
  }

  moveSelectionUp () {
    this.setSelectedIndex(Math.max(this.selectedIndex - 1, 0))
  }

  moveSelectionDown () {
    const filesLengthIndex = this.gitStore.getFiles().length - 1
    this.setSelectedIndex(Math.min(this.selectedIndex + 1, filesLengthIndex))
  }

  toggleFileStageStatus (file: FileDiff): Promise<void> {
    const stage = file.getStageStatus() === 'unstaged'
    return this.gitStore.stageFile(file, stage)
  }

  toggleSelectedFilesStageStatus (): Promise<void> {
    const file = this.getSelectedFile()
    return this.toggleFileStageStatus(file)
  }

  getFileDiffViewModels (): Array<FileDiffViewModel> {
    return this.gitStore.getFiles().map(fileDiff => new FileDiffViewModel(fileDiff))
  }
}
<commit_msg>Pass the token through.<commit_after>/* @flow */

import {Emitter, CompositeDisposable} from 'atom'
import FileDiffViewModel from './file-diff-view-model'
import CommitBoxViewModel from './commit-box-view-model'
import PushPullViewModel from './push-pull-view-model'

import type {Disposable} from 'atom'
import type GitStore from './git-store'
import type FileDiff from './file-diff'

export default class FileListViewModel {
  gitStore: GitStore;
  selectedIndex: number;
  emitter: Emitter;
  commitBoxViewModel: CommitBoxViewModel;
  pushPullViewModel: PushPullViewModel;
  subscriptions: CompositeDisposable;

  constructor (gitStore: GitStore) {
    this.gitStore = gitStore
    this.selectedIndex = 0
    this.emitter = new Emitter()
    this.subscriptions = new CompositeDisposable()
    this.commitBoxViewModel = new CommitBoxViewModel(gitStore)
    this.pushPullViewModel = new PushPullViewModel(gitStore)

    this.gitStore.onDidUpdate(() => this.emitUpdateEvent())
  }

  destroy () {
    this.subscriptions.dispose()
  }

  onDidUpdate (callback: Function): Disposable {
    return this.emitter.on('did-update', callback)
  }

  emitUpdateEvent () {
    this.emitter.emit('did-update')
  }

  onSelectionChanged (callback: Function): Disposable {
    return this.emitter.on('selection-changed', callback)
  }

  emitSelectionChangedEvent () {
    this.emitter.emit('selection-changed')
  }

  getGitStore (): GitStore {
    return this.gitStore
  }

  getSelectedIndex (): number {
    return this.selectedIndex
  }

  setSelectedIndex (index: number) {
    this.selectedIndex = index
    this.emitSelectionChangedEvent()
  }

  getSelectedFile (): FileDiff {
    return this.getFileAtIndex(this.selectedIndex)
  }

  openSelectedFileDiff (): Promise<void> {
    return this.gitStore.openFileDiff(this.getSelectedFile())
  }

  getFileAtIndex (index: number): FileDiff {
    return this.gitStore.getFiles()[index]
  }

  getDiffForPathName (name: string): FileDiff {
    return this.getGitStore().getOrCreateFileFromPathName(name)
  }

  openFile (): Promise<void> {
    return this.gitStore.openFile(this.getSelectedFile())
  }

  moveSelectionUp () {
    this.setSelectedIndex(Math.max(this.selectedIndex - 1, 0))
  }

  moveSelectionDown () {
    const filesLengthIndex = this.gitStore.getFiles().length - 1
    this.setSelectedIndex(Math.min(this.selectedIndex + 1, filesLengthIndex))
  }

  toggleFileStageStatus (file: FileDiff): Promise<void> {
    const stage = file.getStageStatus() === 'unstaged'
    return this.gitStore.stageFile(file, stage)
  }

  toggleSelectedFilesStageStatus (): Promise<void> {
    const file = this.getSelectedFile()
    return this.toggleFileStageStatus(file)
  }

  getFileDiffViewModels (): Array<FileDiffViewModel> {
    return this.gitStore.getFiles().map(fileDiff => new FileDiffViewModel(fileDiff))
  }

  setToken (t: string) {
    this.pushPullViewModel.setToken(t)
  }
}
<|endoftext|>


<commit_before>/*
Nom de l'application: netVIEWork
Description: affichage dynamique des réseaux enterés
Autheurs: KAICHOUH-ZAROUGUI-PETIT
*/
//déclaration des variables globales
var layer;
var reseau_p;
var reseau = [];
var s_reseau = [];
var ancien_layer;
var coche_d = 1;
var coche_q = 1;
var val_diam = [];
var premiere = true;
var legend;
var map;
var x = 0;
var div = document.getElementById('div');
var titre_l = document.getElementById('titre_l');
//définition des plages de couleurs pour les sous réseaux
var couleurs = ['#046380', '#21177D', '#7E3300', '#5A5E6B', '#FCDC12', '#DB0073' /* ,'','','','','','','','' */ ];
//déclaration de la légende

var legend;
window.onload = function() { //au chargement de la page
    //ne pas afficher la légende du diamètre et de qualité au chargement de la page
    document.getElementById('leg_diam').style.display = "none";
    document.getElementById('leg_qual').style.display = "none";
    document.getElementById('option_q1').style.display = "none";
    document.getElementById('option_q2').style.display = "none";
    document.getElementById('text_q').style.fontWeight = "bold";
    document.getElementById('text_d').style.fontWeight = "bold";
    //définir la légende de qualité
    document.getElementById('leg_qual').innerHTML += '
' + '
Niveau de qualité

';
    document.getElementById('leg_qual').innerHTML += '
 ' + ' Bonne

';
    document.getElementById('leg_qual').innerHTML += '
 ' + 'Avec défaut

';
    //définir la légende de qualité
    document.getElementById('leg_diam').innerHTML += '
' + '
Diamètre

';
    var n_layer;

    map = L.map("map", { //délclaration de la carte
        center: new L.LatLng(49.1811, -0.3712),
        zoom: 16, //niveau de zoom initial
        fullscreenControl: true, //activer le mode plein ecran
        fullscreenControlOptions: {
            position: 'topleft'
        }

    });

    //fonction de chargement des données du géoportail
    //key:la clé développement du géoportail
    //format:le format du résultat fourni
    //layer: la couche du géoportail à charger
    function geopUrl(key, layer, format) {
        return "http://wxs.ign.fr/" + key + "/wmts?LAYER=" + layer +
            "&EXCEPTIONS=text/xml&FORMAT=" + (format ? format : "image/jpeg") +
            "&SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetTile&STYLE=normal" +
            "&TILEMATRIXSET=PM&TILEMATRIX={z}&TILECOL={x}&TILEROW={y}";
    }
    //chargement de l'orthophoto du géoportail
    var ortho = L.tileLayer(geopUrl('7ytqc987zmmjr5g5r3gs1r7p', "ORTHOIMAGERY.ORTHOPHOTOS"), {
        attribution: '© IGN-France',
        maxZoom: 18
    });
    //chargement de la carte de base du géoportail
    var carte = L.tileLayer(geopUrl('7ytqc987zmmjr5g5r3gs1r7p', "GEOGRAPHICALGRIDSYSTEMS.MAPS"), {
        attribution: '© IGN-France',
        maxZoom: 18
    });

    carte.addTo(map); //la carte de base comme vue initiale
    //définir les couches de bases
    var baseLayers = {
        "fond de carte": carte,
        "orthophoto": ortho,
        'sans fond': L.tileLayer(''),
    };

    //ajout des couches de base à la carte

    var controlLayers = L.control.layers(baseLayers).addTo(map);

    //ajouter la legende

    legend = L.control({
        position: 'bottomright'
    });
    legend.onAdd = function(map) {

        titre_l.innerHTML += /* '
' + */ ' ' +
            'Légende';

        return div;
    };
    legend.addTo(map);

    //	Récupérer tous les réseaux(fichiers.geojson) du chemain indiqué
    var xhr = new XMLHttpRequest();

    xhr.open("GET", "fichiers.php", true);

    xhr.send();

    xhr.addEventListener('readystatechange', function(e) {
        if (xhr.readyState == 4 && xhr.status == 200) {
            b = JSON.parse(xhr.responseText);

            for (var j = 0; j < b.length; j++) {

                (function(j) {
					//Récupérer les sous réseaux
                    var result = b[j].indexOf('Reseau_principal');
                    if (result == -1) {
                        var chemin = "donnees/" + b[j] + ".geojson";
                        var color = choisir_couleur();
                        //Récupérer le réseau et définir son style
                        layer = $.getJSON(chemin, function(data) {
                            reseau[j] = L.geoJson(data, {
                                style: {
                                    "color": color,
                                    "weight": 3,
                                    "opacity": 1
                                },

                                onEachFeature: function(feature, layer) {
                                    //afficher les poup au survol des tronçons du sous réseau
                                    layer.bindPopup("Location: " + feature.properties.location + "
Matériel:" + feature.properties.material + "
Diamètre:" + feature.properties.diameter + "
Qualité:" + feature.properties.Qualite)
                                    layer.on('mouseover', function() {
                                        ancien_layer = layer;
                                        layer.openPopup();
                                        layer.setStyle({
                                            color: '#666',

                                        });
                                    });
                                    layer.on('mouseout', function() {
                                        layer.closePopup();
                                        layer.setStyle({
                                            color: ancien_layer.options.style.color,
                                        });

                                    });

                                }

                            })

                            infoslegende.innerHTML += '
<input class="cb" id=' + j + ' type="checkbox" value=""onclick="activer(event,reseau[' + j + '],' + j + ' )"> ' + b[j] + '

';
                            s_reseau.push(reseau[j]);
                        });
                    } else {
                        //chargement du réseau principal
                        layer = $.getJSON("donnees/Reseau_principal.geojson", function(data) {

                            reseau_p = L.geoJson(data, {
                                    style: {
                                        "color": '#FFA500',
                                        "weight": 6,
                                        "opacity": 1

                                    },
									 //afficher les poup au survol des tronçons du réseau
                                    onEachFeature: function(feature, layer) {
                                        layer.bindPopup("Matériel: " + feature.properties.MATERIAU + "
Diamètre:" + feature.properties.DIAMETRE)
                                        layer.on('mouseover', function() {
                                            ancien_layer = layer;
                                            layer.openPopup();
                                            layer.setStyle({
                                                color: '#666',

                                            });
                                        });
                                        layer.on('mouseout', function() {
                                            layer.closePopup();
                                            layer.setStyle({
                                                color: ancien_layer.options.style.color,
                                            });

                                        });

                                    }
                                })
                            //zommer la carte sur le réseau principal
                            map.fitBounds(reseau_p.getBounds());
                            infoslegende.innerHTML += '
<input class="cb" id=' + j + ' type="checkbox" value=""onclick="activer(event,reseau_p,' + j + '  )"> ' + b[j] + '

';

                        });

                    }
                })(j);

            }
        }
    });

}

//fonction d'activation des couches

function activer(event, reseau, j) {

    (function(ev, res) {

        if (document.getElementById(j).checked) {

            res.addTo(map);
            if (res == reseau_p) reseau_p.bringToBack();

        } else {

            map.removeLayer(res);

        }

    })(event, reseau)
}
//fonction qui récupère les diamètres de tous les réseaux
function getdiametre(d) {
    if (!contains.call(val_diam, d) & d != null & d != 0) {
        //récupérer tous les diamètres dans un tableau val_diam
        val_diam.push(d);
    }
    return d / 100;

}
//fonction qui retourne le style de trait selon la qualité du tronçon
function getdash(q) {
    if (q == "Bonne") return '';

    else return '4';

}

//affichage dynamique selon le diamètre
function affichage_dynamique_diam(ev) {

    if (coche_d == 1) { //lors de l'activation du checkbox diamètre
        if (document.getElementById('qual').checked) {
            document.getElementById('text_d').style.color = "black";
            document.getElementById('text_q').style.color = "black";
        } else document.getElementById('text_q').style.color = "#808080";
        document.getElementById('leg_diam').style.display = "block";

        reseau_p.eachLayer(function(reseau_p) {
            diametreValue = reseau_p.feature.properties.DIAMETRE;

            var diametre = getdiametre(diametreValue);

            reseau_p.setStyle({

                weight: diametre

            });
        });
        for (var i = 0; i < s_reseau.length; i++) {
            var ss_reseau = s_reseau[i];
            s_reseau[i].eachLayer(function(ss_reseau) {
                diametreValue = ss_reseau.feature.properties.DIAMETRE;

                var diametre = getdiametre(diametreValue);

                ss_reseau.setStyle({

                    weight: diametre

                });
            });
        }

        coche_d = 0;
        if (premiere) {
            //trier le tableau des diamètres
            val_diam.sort(compare);

            for (var i = 0; i < val_diam.length; i++) {
                //afficher les diamètres dans la légende
                document.getElementById('leg_diam').innerHTML += '
 ' + ' Diamètre:' + val_diam[i] + 'm

';
            }
        }
        premiere = false;
    } else {
		//remettre le style initial en décochant
        reseau_p.setStyle({

            weight: 6

        });
        for (var i = 0; i < s_reseau.length; i++) {
            s_reseau[i].setStyle({

                weight: 2

            });
        }

        coche_d = 1;
        //enlever la legnende
        document.getElementById('leg_diam').style.display = "none";
        if (document.getElementById('qual').checked) document.getElementById('text_d').style.color = "#808080";
        else document.getElementById('text_q').style.color = "black";

    }

}

//vérifier si un tableu contient un élément
var contains = function(needle) {
    var findNaN = needle !== needle;
    var indexOf;

    if (!findNaN && typeof Array.prototype.indexOf === 'function') {
        indexOf = Array.prototype.indexOf;
    } else {
        indexOf = function(needle) {
            var i = -1,
                index = -1;

            for (i = 0; i < this.length; i++) {
                var item = this[i];

                if ((findNaN && item !== item) || item === needle) {
                    index = i;
                    break;
                }
            }

            return index;
        };
    }

    return indexOf.call(this, needle) > -1;
};
//fonction utilisé pour le tri
function compare(x, y) {
    return x - y;
}
//affichage dynamique selon la qualité
function affichage_dynamique_qual(ev) {
    if (coche_q == 1) {
        if (document.getElementById('diam').checked) {
            document.getElementById('text_q').style.color = "black";
            document.getElementById('text_d').style.color = "black";
        } else document.getElementById('text_d').style.color = "#808080";
        document.getElementById('leg_qual').style.display = "block";
        document.getElementById('option_q1').style.display = "block";
        document.getElementById('option_q2').style.display = "block";
        for (var i = 0; i < s_reseau.length; i++) {
            var ss_reseau = s_reseau[i];

            ss_reseau.eachLayer(function(ss_reseau) {
                qualiteValue = ss_reseau.feature.properties.Qualite;

                var dash = getdash(qualiteValue);

                ss_reseau.setStyle({

                    dashArray: dash

                });
            });
        }

        coche_q = 0;
    } else {
        for (var i = 0; i < s_reseau.length; i++) {
			//Remettre le style initial en décochant

            s_reseau[i].setStyle({

                dashArray: ''

            });
        }

        coche_q = 1;
		//Enlever la légende de qualité

        document.getElementById('leg_qual').style.display = "none";
        document.getElementById('option_q1').style.display = "none";
        document.getElementById('option_q2').style.display = "none";
        if (document.getElementById('diam').checked) document.getElementById('text_q').style.color = "#808080";
        else document.getElementById('text_d').style.color = "black";
    }
}

//fonction qui permet de choisir les couleurs pour les sous réseaux

function choisir_couleur() {
    couleur = couleurs[x];
    x++
    return couleur;
}
//fonction qui déplie la légende
function ouvrirFermerSpoiler(elem) {
    if ($(elem).attr('id') === "infoslegende") {
        if (elem.style.display == 'none') {
            elem.style.display = 'block';
            titre_l.innerHTML = /* '
' + */ ' ' +
                'Légende';
        } else {
            elem.style.display = 'none';
            titre_l.innerHTML = /* '
' + */ ' ' +
                'Légende';
        }
    } else {
        if (elem.style.display == 'none') {
            elem.style.display = 'block';
        } else {
            elem.style.display = 'none';

        }
    }

}<commit_msg>version finale de l'application<commit_after>/*
Nom de l'application: netVIEWork
Description: affichage dynamique des réseaux enterrés
Auteurs: KAICHOUH-ZAROUGUI-PETIT
*/
//déclaration des variables globales
var layer;
var reseau_p;
var reseau = [];
var s_reseau = [];
var ancien_layer;
var coche_d = 1;
var coche_q = 1;
var val_diam = [];
var premiere = true;
var legend;
var map;
var x = 0;
var div = document.getElementById('div');
var titre_l = document.getElementById('titre_l');
//définition des plages de couleurs pour les sous réseaux
var couleurs = ['#046380', '#21177D', '#7E3300', '#5A5E6B', '#FCDC12', '#DB0073' /* ,'','','','','','','','' */ ];
//déclaration de la légende

var legend;
window.onload = function() { //au chargement de la page
    //ne pas afficher la légende du diamètre et de qualité au chargement de la page
    document.getElementById('leg_diam').style.display = "none";
    document.getElementById('leg_qual').style.display = "none";
    document.getElementById('option_q1').style.display = "none";
    document.getElementById('option_q2').style.display = "none";
    document.getElementById('text_q').style.fontWeight = "bold";
    document.getElementById('text_d').style.fontWeight = "bold";
    //définir la légende de qualité
    document.getElementById('leg_qual').innerHTML += '
' + '
Niveau de qualité

';
    document.getElementById('leg_qual').innerHTML += '
 ' + ' Bonne

';
    document.getElementById('leg_qual').innerHTML += '
 ' + 'Avec défaut

';
    //définir la légende de qualité
    document.getElementById('leg_diam').innerHTML += '
' + '
Diamètre

';
    var n_layer;

    map = L.map("map", { //délclaration de la carte
        center: new L.LatLng(49.1811, -0.3712),
        zoom: 16, //niveau de zoom initial
        fullscreenControl: true, //activer le mode plein ecran
        fullscreenControlOptions: {
            position: 'topleft'
        }

    });

    //fonction de chargement des données du géoportail
    //key:la clé développement du géoportail
    //format:le format du résultat fourni
    //layer: la couche du géoportail à charger
    function geopUrl(key, layer, format) {
        return "http://wxs.ign.fr/" + key + "/wmts?LAYER=" + layer +
            "&EXCEPTIONS=text/xml&FORMAT=" + (format ? format : "image/jpeg") +
            "&SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetTile&STYLE=normal" +
            "&TILEMATRIXSET=PM&TILEMATRIX={z}&TILECOL={x}&TILEROW={y}";
    }
    //chargement de l'orthophoto du géoportail
    var ortho = L.tileLayer(geopUrl('7ytqc987zmmjr5g5r3gs1r7p', "ORTHOIMAGERY.ORTHOPHOTOS"), {
        attribution: '© IGN-France',
        maxZoom: 18
    });
    //chargement de la carte de base du géoportail
    var carte = L.tileLayer(geopUrl('7ytqc987zmmjr5g5r3gs1r7p', "GEOGRAPHICALGRIDSYSTEMS.MAPS"), {
        attribution: '© IGN-France',
        maxZoom: 18
    });

    carte.addTo(map); //la carte de base comme vue initiale
    //définir les couches de bases
    var baseLayers = {
        "fond de carte": carte,
        "orthophoto": ortho,
        'sans fond': L.tileLayer(''),
    };

    //ajout des couches de base à la carte

    var controlLayers = L.control.layers(baseLayers).addTo(map);

    //ajouter la legende

    legend = L.control({
        position: 'bottomright'
    });
    legend.onAdd = function(map) {

        titre_l.innerHTML += /* '
' + */ ' ' +
            'Légende';

        return div;
    };
    legend.addTo(map);

    //	Récupérer tous les réseaux(fichiers.geojson) du chemain indiqué
    var xhr = new XMLHttpRequest();

    xhr.open("GET", "fichiers.php", true);

    xhr.send();

    xhr.addEventListener('readystatechange', function(e) {
        if (xhr.readyState == 4 && xhr.status == 200) {
            b = JSON.parse(xhr.responseText);

            for (var j = 0; j < b.length; j++) {

                (function(j) {
					//Récupérer les sous réseaux
                    var result = b[j].indexOf('Reseau_principal');
                    if (result == -1) {
                        var chemin = "donnees/" + b[j] + ".geojson";
                        var color = choisir_couleur();
                        //Récupérer le réseau et définir son style
                        layer = $.getJSON(chemin, function(data) {
                            reseau[j] = L.geoJson(data, {
                                style: {
                                    "color": color,
                                    "weight": 3,
                                    "opacity": 1
                                },

                                onEachFeature: function(feature, layer) {
                                    //afficher les poup au survol des tronçons du sous réseau
                                    layer.bindPopup("Location: " + feature.properties.location + "
Matériel:" + feature.properties.material + "
Diamètre:" + feature.properties.diameter + "
Qualité:" + feature.properties.Qualite)
                                    layer.on('mouseover', function() {
                                        ancien_layer = layer;
                                        layer.openPopup();
                                        layer.setStyle({
                                            color: '#666',

                                        });
                                    });
                                    layer.on('mouseout', function() {
                                        layer.closePopup();
                                        layer.setStyle({
                                            color: ancien_layer.options.style.color,
                                        });

                                    });

                                }

                            })

                            infoslegende.innerHTML += '
<input class="cb" id=' + j + ' type="checkbox" value=""onclick="activer(event,reseau[' + j + '],' + j + ' )"> ' + b[j] + '

';
                            s_reseau.push(reseau[j]);
                        });
                    } else {
                        //chargement du réseau principal
                        layer = $.getJSON("donnees/Reseau_principal.geojson", function(data) {

                            reseau_p = L.geoJson(data, {
                                    style: {
                                        "color": '#FFA500',
                                        "weight": 6,
                                        "opacity": 1

                                    },
									 //afficher les poup au survol des tronçons du réseau
                                    onEachFeature: function(feature, layer) {
                                        layer.bindPopup("Matériel: " + feature.properties.MATERIAU + "
Diamètre:" + feature.properties.DIAMETRE)
                                        layer.on('mouseover', function() {
                                            ancien_layer = layer;
                                            layer.openPopup();
                                            layer.setStyle({
                                                color: '#666',

                                            });
                                        });
                                        layer.on('mouseout', function() {
                                            layer.closePopup();
                                            layer.setStyle({
                                                color: ancien_layer.options.style.color,
                                            });

                                        });

                                    }
                                })
                            //zommer la carte sur le réseau principal
                            map.fitBounds(reseau_p.getBounds());
                            infoslegende.innerHTML += '
<input class="cb" id=' + j + ' type="checkbox" value=""onclick="activer(event,reseau_p,' + j + '  )"> ' + b[j] + '

';

                        });

                    }
                })(j);

            }
        }
    });

}

//fonction d'activation des couches

function activer(event, reseau, j) {

    (function(ev, res) {

        if (document.getElementById(j).checked) {

            res.addTo(map);
            if (res == reseau_p) reseau_p.bringToBack();

        } else {

            map.removeLayer(res);

        }

    })(event, reseau)
}
//fonction qui récupère les diamètres de tous les réseaux
function getdiametre(d) {
    if (!contains.call(val_diam, d) & d != null & d != 0) {
        //récupérer tous les diamètres dans un tableau val_diam
        val_diam.push(d);
    }
    return d / 100;

}
//fonction qui retourne le style de trait selon la qualité du tronçon
function getdash(q) {
    if (q == "Bonne") return '';

    else return '4';

}

//affichage dynamique selon le diamètre
function affichage_dynamique_diam(ev) {

    if (coche_d == 1) { //lors de l'activation du checkbox diamètre
        if (document.getElementById('qual').checked) {
            document.getElementById('text_d').style.color = "black";
            document.getElementById('text_q').style.color = "black";
        } else document.getElementById('text_q').style.color = "#808080";
        document.getElementById('leg_diam').style.display = "block";

        reseau_p.eachLayer(function(reseau_p) {
            diametreValue = reseau_p.feature.properties.DIAMETRE;

            var diametre = getdiametre(diametreValue);

            reseau_p.setStyle({

                weight: diametre

            });
        });
        for (var i = 0; i < s_reseau.length; i++) {
            var ss_reseau = s_reseau[i];
            s_reseau[i].eachLayer(function(ss_reseau) {
                diametreValue = ss_reseau.feature.properties.DIAMETRE;

                var diametre = getdiametre(diametreValue);

                ss_reseau.setStyle({

                    weight: diametre

                });
            });
        }

        coche_d = 0;
        if (premiere) {
            //trier le tableau des diamètres
            val_diam.sort(compare);

            for (var i = 0; i < val_diam.length; i++) {
                //afficher les diamètres dans la légende
                document.getElementById('leg_diam').innerHTML += '
 ' + ' Diamètre:' + val_diam[i] + 'm

';
            }
        }
        premiere = false;
    } else {
		//remettre le style initial en décochant
        reseau_p.setStyle({

            weight: 6

        });
        for (var i = 0; i < s_reseau.length; i++) {
            s_reseau[i].setStyle({

                weight: 2

            });
        }

        coche_d = 1;
        //enlever la legnende
        document.getElementById('leg_diam').style.display = "none";
        if (document.getElementById('qual').checked) document.getElementById('text_d').style.color = "#808080";
        else document.getElementById('text_q').style.color = "black";

    }

}

//vérifier si un tableu contient un élément
var contains = function(needle) {
    var findNaN = needle !== needle;
    var indexOf;

    if (!findNaN && typeof Array.prototype.indexOf === 'function') {
        indexOf = Array.prototype.indexOf;
    } else {
        indexOf = function(needle) {
            var i = -1,
                index = -1;

            for (i = 0; i < this.length; i++) {
                var item = this[i];

                if ((findNaN && item !== item) || item === needle) {
                    index = i;
                    break;
                }
            }

            return index;
        };
    }

    return indexOf.call(this, needle) > -1;
};
//fonction utilisé pour le tri
function compare(x, y) {
    return x - y;
}
//affichage dynamique selon la qualité
function affichage_dynamique_qual(ev) {
    if (coche_q == 1) {
        if (document.getElementById('diam').checked) {
            document.getElementById('text_q').style.color = "black";
            document.getElementById('text_d').style.color = "black";
        } else document.getElementById('text_d').style.color = "#808080";
        document.getElementById('leg_qual').style.display = "block";
        document.getElementById('option_q1').style.display = "block";
        document.getElementById('option_q2').style.display = "block";
        for (var i = 0; i < s_reseau.length; i++) {
            var ss_reseau = s_reseau[i];

            ss_reseau.eachLayer(function(ss_reseau) {
                qualiteValue = ss_reseau.feature.properties.Qualite;

                var dash = getdash(qualiteValue);

                ss_reseau.setStyle({

                    dashArray: dash

                });
            });
        }

        coche_q = 0;
    } else {
        for (var i = 0; i < s_reseau.length; i++) {
			//Remettre le style initial en décochant

            s_reseau[i].setStyle({

                dashArray: ''

            });
        }

        coche_q = 1;
		//Enlever la légende de qualité

        document.getElementById('leg_qual').style.display = "none";
        document.getElementById('option_q1').style.display = "none";
        document.getElementById('option_q2').style.display = "none";
        if (document.getElementById('diam').checked) document.getElementById('text_q').style.color = "#808080";
        else document.getElementById('text_d').style.color = "black";
    }
}

//fonction qui permet de choisir les couleurs pour les sous réseaux

function choisir_couleur() {
    couleur = couleurs[x];
    x++
    return couleur;
}
//fonction qui déplie la légende
function ouvrirFermerSpoiler(elem) {
    if ($(elem).attr('id') === "infoslegende") {
        if (elem.style.display == 'none') {
            elem.style.display = 'block';
            titre_l.innerHTML = /* '
' + */ ' ' +
                'Légende';
        } else {
            elem.style.display = 'none';
            titre_l.innerHTML = /* '
' + */ ' ' +
                'Légende';
        }
    } else {
        if (elem.style.display == 'none') {
            elem.style.display = 'block';
        } else {
            elem.style.display = 'none';

        }
    }

}<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

'use strict';

const {EventEmitter} = require('events');

class BatchProcessorMock {

  constructor(_, processBatch) {
    this._processBatch = processBatch;
    this._queue = [];
    BatchProcessorMock.mocks.emit('new', this);
  }

  queue(item, callback) {
    this._queue.push([item, callback]);
  }

  flush(callback) {
    const {_queue} = this;
    this._queue = [];
    process.nextTick(() => {
      this._processBatch(_queue.map(pair => pair[0]), (error, res) => {
        _queue.forEach((pair, i) => pair[1](error, res && res[i]));
        callback();
      });
    });
  }

}

BatchProcessorMock.mocks = new EventEmitter();

module.exports = BatchProcessorMock;
<commit_msg>packager: simplify ScribeLogger-test<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

'use strict';

const {EventEmitter} = require('events');

class BatchProcessorMock {

  constructor(_, processBatch) {
    this._processBatch = processBatch;
    this._queue = [];
    BatchProcessorMock.mocks.emit('new', this);
  }

  queue(item, callback) {
    this._queue.push([item, callback]);
  }

  flushMock() {
    const {_queue} = this;
    this._queue = [];
    process.nextTick(() => {
      this._processBatch(_queue.map(pair => pair[0]), (error, res) => {
        _queue.forEach((pair, i) => pair[1](error, res && res[i]));
      });
    });
  }

}

BatchProcessorMock.mocks = new EventEmitter();

module.exports = BatchProcessorMock;
<|endoftext|>


<commit_before>let Player = require("./player");
let Feld = require("./feld");

module.exports = class Schiffeversenken {
  constructor(options) {
    this.options = options || {};
    this.players = [];
    this.winner;
    this.whoseTurn;
    this.started = false;
  }

  addPlayer(id) {
    if (Object.keys(this.players).length < 2) {
      this.players[id] = new Player(id);
      this.getPlayerById(id).feld = new Feld(this.options);
    }
  }

  getPlayerById(id) {
    return this.players[id];
  }

  getOpponent(p) {
    let id = p.id;
    let keys = Object.keys(this.players);
    for (let k of keys) {
      if (k !== id) {
        return this.getPlayerById(k);
      }
    }
    return "Fehler";
  }

  startTheGame() {
    let keys = Object.keys(this.players);

    if (keys.length !== 2) {
      return {
        status: "fail",
        reason: "Es müssen genau 2 Spieler im Spiel sein."
      }
    }

    for (let k of keys) {
      if (this.players[k].feld.ships.length === 0) {
        return {
          status: "fail",
          reason: "Beide Spieler müssen ihre Schiffe platziert haben."
        }
      }
    }

    this.whoseTurn = keys[Math.floor(Math.random() * 2)];
    this.started = true;

    return {
      status: "success"
    }
  }

  shoot(sourceID, pos) {
    let source = this.getPlayerById(sourceID);
    let goal = this.getOpponent(this.getPlayerById(sourceID));
    if (this.winner !== undefined) {
      return {
        status: "fail",
        reason: "Das Spiel ist bereits vorrüber."
      }
    }

    if (!this.started) {
      return {
        status: "fail",
        reason: "Das Spiel hat noch nicht begonnen."
      }
    }

    if (sourceID !== this.whoseTurn) {
      return {
        status: "fail",
        reason: "Du bist nicht an der Reihe!"
      }
    }

    if (source.feld.hasAlreadyBeenHit(pos)) {
      return {
        status: "fail",
        reason: "Du hast an dieser Stelle bereits ein Schiff getroffen!"
      }
    }

    if (!goal.feld.isShipAt(pos)) {
      if (!source.feld.hasAlreadyBeenMissed(pos)) {
        source.feld.misses.push(pos);
      }
      this.whoseTurn = this.getOpponent(source).id;
      return {
        status: "fail",
        reason: "Nicht getroffen"
      }
    }

    source.feld.hits.push(pos);

    let res = {
      status: "hit"
    };
    if (source.feld.SHIPPOSCOUNTER === source.feld.hits.length) {
      res.gameOver = true;
      this.winner = source.id;
    } else {
      if (!source.feld.SAMEPLAYERSTURNAFTERHIT) {
        this.whoseTurn = this.getOpponent(source).id;
      }
    }
    return res;

  }

};<commit_msg>Nutze null statt undefined<commit_after>let Player = require("./player");
let Feld = require("./feld");

module.exports = class Schiffeversenken {
  constructor(options) {
    this.options = options || {};
    this.players = [];
    this.winner = null;
    this.whoseTurn;
    this.started = false;
  }

  addPlayer(id) {
    if (Object.keys(this.players).length < 2) {
      this.players[id] = new Player(id);
      this.getPlayerById(id).feld = new Feld(this.options);
    }
  }

  getPlayerById(id) {
    return this.players[id];
  }

  getOpponent(p) {
    let id = p.id;
    let keys = Object.keys(this.players);
    for (let k of keys) {
      if (k !== id) {
        return this.getPlayerById(k);
      }
    }
    return "Fehler";
  }

  startTheGame() {
    let keys = Object.keys(this.players);

    if (keys.length !== 2) {
      return {
        status: "fail",
        reason: "Es müssen genau 2 Spieler im Spiel sein."
      }
    }

    for (let k of keys) {
      if (this.players[k].feld.ships.length === 0) {
        return {
          status: "fail",
          reason: "Beide Spieler müssen ihre Schiffe platziert haben."
        }
      }
    }

    this.whoseTurn = keys[Math.floor(Math.random() * 2)];
    this.started = true;

    return {
      status: "success"
    }
  }

  shoot(sourceID, pos) {
    let source = this.getPlayerById(sourceID);
    let goal = this.getOpponent(this.getPlayerById(sourceID));
    if (this.winner !== null) {
      return {
        status: "fail",
        reason: "Das Spiel ist bereits vorrüber."
      }
    }

    if (!this.started) {
      return {
        status: "fail",
        reason: "Das Spiel hat noch nicht begonnen."
      }
    }

    if (sourceID !== this.whoseTurn) {
      return {
        status: "fail",
        reason: "Du bist nicht an der Reihe!"
      }
    }

    if (source.feld.hasAlreadyBeenHit(pos)) {
      return {
        status: "fail",
        reason: "Du hast an dieser Stelle bereits ein Schiff getroffen!"
      }
    }

    if (!goal.feld.isShipAt(pos)) {
      if (!source.feld.hasAlreadyBeenMissed(pos)) {
        source.feld.misses.push(pos);
      }
      this.whoseTurn = this.getOpponent(source).id;
      return {
        status: "fail",
        reason: "Nicht getroffen"
      }
    }

    source.feld.hits.push(pos);

    let res = {
      status: "hit"
    };
    if (source.feld.SHIPPOSCOUNTER === source.feld.hits.length) {
      res.gameOver = true;
      this.winner = source.id;
    } else {
      if (!source.feld.SAMEPLAYERSTURNAFTERHIT) {
        this.whoseTurn = this.getOpponent(source).id;
      }
    }
    return res;

  }

};<|endoftext|>