<commit_before>(function($) {

  var intIntervalTime = 100;
  var pageurl = window.location.href;
  var pageData;

  //florence menu
  var florence_menu =
    '
' +
      '' +
        '
' +
            '
' +
              'Collections' +
            '
' +
            '
' +
              'Users and access' +
            '
' +
            '
' +
              'Publish' +
            '
' +
          '
' +
      '' +
    '
' +
    '
' +
      '' +
        '
' +
            '
' +
              'Browse' +
            '
' +
            '
' +
              'Create' +
            '
' +
            '
' +
              'Edit' +
            '
' +
            '
' +
              'Approve' +
            '
' +
          '
' +
      '' +
  '
' +
  '
' +
  '
';

  //florence browse menu

  //florence create menu

  //florence edit menu
  var florence_menu_edit =
  '
' +
    '' +
      '<input type="text" value="" placeholder="Publish owner" class="fl-panel--editor__publish-owner" />' +
      '<input type="text" value="" placeholder="Publish id (release name)" class="fl-panel--editor__publish-id" />' +
    '' +
    '<textarea class="fl-editor" name="fl-editor" cols="40" rows="5"></textarea>' +
    '' +
      '<button class="fl-panel--editor__nav__save">Save</button>' +
    '' +
  '
';

  //florence approve menu

  // URI simple parser
  var parser = document.createElement('a');
  parser.href = pageurl.replace("#!/", ""); //takes out #! from Angular.js
  parser.protocol; // => "http:"
  parser.hostname; // => "example.com"
  parser.port; // => "3000"
  parser.pathname; // => "/pathname/"
  parser.search; // => "?search=test"
  parser.hash; // => "#hash"
  parser.host; // => "example.com:3000"

  setupFlorence();

  function setupFlorence(){
    $('head').prepend('<link href="http://localhost:8081/css/main.min.css" rel="stylesheet" type="text/css">');
    var bodycontent = $('body').html();

    $('body').wrapInner('

');
    // $('body').wrapInner('

');
    $('body').prepend(florence_menu);

    $('.fl-main-menu__link').click(function() {
      setupFlorenceWorkspace($(this));
    });

  }

  function LoadPageDataIntoEditor(){

    // var pageurl = window.location.href;

    var pageurldata = pageurl.replace("#!", "data");

    $.ajax({
      url: pageurldata,
      dataType: 'json', // Notice! JSONP <-- P (lowercase)
      crossDomain: true,
      // jsonpCallback: 'callback',
      // type: 'GET',
      success: function(response) {
        // do stuff with json (in this case an array)
        // console.log("Success");
        var dataString = String(response);
        // pageType = data.level
        // console.log(response);
        $('.fl-editor').val(JSON.stringify(response, null, 2));
      },
      error: function() {
        console.log('No page data returned');
        $('.fl-editor').val('');
      }
    });
  }

  function convertPageJSONtoMarkdown(){}
  function saveUpdatedMarkdown(){}
  function watchForEditorChanges(){}

  function setupFlorenceWorkspace(caller){

    //console.log(caller.parent().attr('class'));
    // console.log($('.fl-panel--preview__inner').height())

    // setPreviewOverlayHeight();

    removePreviewColClasses();
    removeSubMenus();

    $('.fl-main-menu__link').removeClass('fl-main-menu__link--active');
    caller.addClass('fl-main-menu__link--active');

    $('.fl-panel--preview__inner').removeClass('fl-panel--preview__inner--active');
    $('.fl-panel--preview').addClass('col--7');
    $('.fl-panel--sub-menu').show();

    if (caller.parent().hasClass('fl-main-menu__item--browse')){
      //
    }

    else if (caller.parent().hasClass('fl-main-menu__item--create')){
      //
    }

    else if (caller.parent().hasClass('fl-main-menu__item--edit')){
      // $('.fl-panel--editor').show();
      // florence_menu_edit
      // fl-panel--sub-menu
      $('.fl-panel--sub-menu').html(florence_menu_edit);
      // console.log(florence_menu_edit);

      LoadPageDataIntoEditor();
      setInterval(checkEditPageLocation, intIntervalTime);
      $('.fl-panel--editor__nav__save').click(function() {
        if($('.fl-panel--editor__publish-owner').val().length != 0 && $('.fl-panel--editor__publish-id').val().length != 0){
          pageData = $('.fl-editor').val();
          updatePage();
          //console.log(parser.pathname);
        } else {
          alert('Publish owner and Publish id cannot be blank!');
        }

      });

    }

    if (caller.parent().hasClass('fl-main-menu__item--approve')){
      //
    }

    // else if (caller.parent().hasClass('fl-main-menu__item--publish')){
    //   //
    // }

    else {
      //
    }

  }

function removeSubMenus(){
  //$('.fl-panel--sub-menu').hide();
  $('.fl-panel--sub-menu').empty();
}

function removePreviewColClasses(){
  $('.fl-panel--preview').removeClass('col--4');
  $('.fl-panel--preview').removeClass('col--8');
}

function enablePreview(){
  $('.fl-panel--preview__inner').addClass('fl-panel--preview__inner--active');
}

function checkEditPageLocation() {
  if (pageurl != window.location.href) {
    pageurl = window.location.href;
    $(window.location).trigger("change", {
      newpage: LoadPageDataIntoEditor()
    });
  }
}

function updatePage() {

  /*--cookie stuff - to be moved into a sepperate function eventually--*/
  var owner = $('.fl-panel--editor__publish-owner').val();
  var release = $('.fl-panel--editor__publish-id').val();
  document.cookie = 'owner=' + owner;
  document.cookie = 'release=' + release;
  /*---*/

   $.ajax({
        url: "http://localhost:8081/data",
        type: "POST",
        data: JSON.stringify({
            json: pageData,
            id: parser.pathname
        }),
           xhrFields: {
               withCredentials: true
           },
           dataType: 'json', // Notice! JSONP <-- P (lowercase)
           crossDomain: true,
        contentType: "application/json; charset=utf-8"
    }).done(function () {
        console.log("Done!")
    }).fail(function (jqXHR, textStatus) {
        alert(textStatus);
    })
  }

})(jQuery);
<commit_msg>Adding save / approve / publish functionality.<commit_after>(function($) {

  var intIntervalTime = 100;
  var pageurl = window.location.href;
  var pageData;

    function getPathName() {
        var parsedUrl = window.location.href.split("#!/")[1];
        return parsedUrl;
    }

  //florence menu
  var florence_menu =
    '
' +
      '' +
        '
' +
            '
' +
              'Collections' +
            '
' +
            '
' +
              'Users and access' +
            '
' +
            '
' +
              'Publish' +
            '
' +
          '
' +
      '' +
    '
' +
    '
' +
      '' +
        '
' +
            '
' +
              'Browse' +
            '
' +
            '
' +
              'Create' +
            '
' +
            '
' +
              'Edit' +
            '
' +
            '
' +
              'Approve' +
            '
' +
          '
' +
      '' +
  '
' +
  '
' +
  '
';

  //florence browse menu

  //florence create menu

  //florence edit menu
  var florence_menu_edit =
  '
' +
    '' +
      '<input type="text" value="" placeholder="Publish owner" class="fl-panel--editor__publish-owner" />' +
      '<input type="text" value="" placeholder="Publish id (release name)" class="fl-panel--editor__publish-id" />' +
    '' +
    '<textarea class="fl-editor" name="fl-editor" cols="40" rows="5"></textarea>' +
    '' +
      '<button class="fl-panel--editor__nav__save">Save</button>' +
      '<button class="fl-panel--editor__nav__approve">Approve</button>' +
      '<button class="fl-panel--editor__nav__publish">Publish</button>' +
    '' +
  '
';

  setupFlorence();

  function setupFlorence(){
    $('head').prepend('<link href="http://localhost:8081/css/main.min.css" rel="stylesheet" type="text/css">');
    var bodycontent = $('body').html();

    $('body').wrapInner('

');
    // $('body').wrapInner('

');
    $('body').prepend(florence_menu);

    $('.fl-main-menu__link').click(function() {
      setupFlorenceWorkspace($(this));
    });

  }

    function save(collectionName, data) {

        // Create the collection
        $.ajax({
            url: "http://localhost:8082/collection",
            dataType: 'json',
            crossDomain: true,
            type: 'POST',
            data: JSON.stringify({name: collectionName}),
            success: function () {
                console.log("Collection created")
                openFileForEditing(collectionName, data);
            },
            error: function () {
                console.log('Error creating collection');
                openFileForEditing(collectionName, data);
            }
        });
    }

    function openFileForEditing(collectionName, data) {
        // Open the file for editing
        $.ajax({
            url: "http://localhost:8082/edit/" + collectionName,
            dataType: 'json',
            crossDomain: true,
            type: 'POST',
            data: JSON.stringify({uri: getPathName() + "/data.json"}),
            success: function () {
                console.log("File opened for editing");
                updateContent(collectionName, data);
            },
            error: function () {
                console.log('Error opening file for edit');
                updateContent(collectionName, data);
                console.log("update content called.");
            }
        });
    }

    function updateContent(collectionName, data) {
        // Update content
        $.ajax({
            url: "http://localhost:8082/content/" + collectionName + "?uri=" + getPathName() + "/data.json",
            dataType: 'json',
            crossDomain: true,
            type: 'POST',
            data: data,
            success: function (message) {
                console.log("Updating completed" + message);
            },
            error: function (error) {
                console.log(error);
            }
        });

        document.cookie = 'collection=' + collectionName;
    }

    function approve(collectionName) {

        // Open the file for editing
        $.ajax({
            url: "http://localhost:8082/approve/" + collectionName + "?uri=" + getPathName() + "/data.json",
            dataType: 'json',
            crossDomain: true,
            type: 'POST',
            success: function () {
                console.log("File approved!")
                alert("Your file is now approved");
            },
            error: function () {
                console.log('Error');
            }
        });
    }

    function publish(collectionName) {

        // Open the file for editing
        $.ajax({
            url: "http://localhost:8082/publish/" + collectionName,
            dataType: 'json',
            crossDomain: true,
            type: 'POST',
            success: function () {
                console.log("File published")
                document.cookie = 'collection=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
                alert("Published!");
            },
            error: function () {
                console.log('Error');
            }
        });
    }

    function LoadPageDataIntoEditor(){

    // var pageurl = window.location.href;

    var pageurldata = pageurl.replace("#!", "data");

    $.ajax({
      url: pageurldata,
      dataType: 'json', // Notice! JSONP <-- P (lowercase)
      crossDomain: true,
      // jsonpCallback: 'callback',
      // type: 'GET',
      success: function(response) {
        // do stuff with json (in this case an array)
        // console.log("Success");
        var dataString = String(response);
        // pageType = data.level
        // console.log(response);
        $('.fl-editor').val(JSON.stringify(response, null, 2));
      },
      error: function() {
        console.log('No page data returned');
        $('.fl-editor').val('');
      }
    });
  }

  function convertPageJSONtoMarkdown(){}
  function saveUpdatedMarkdown(){}
  function watchForEditorChanges(){}

  function setupFlorenceWorkspace(caller){

    //console.log(caller.parent().attr('class'));
    // console.log($('.fl-panel--preview__inner').height())

    // setPreviewOverlayHeight();

    removePreviewColClasses();
    removeSubMenus();

    $('.fl-main-menu__link').removeClass('fl-main-menu__link--active');
    caller.addClass('fl-main-menu__link--active');

    $('.fl-panel--preview__inner').removeClass('fl-panel--preview__inner--active');
    $('.fl-panel--preview').addClass('col--7');
    $('.fl-panel--sub-menu').show();

    if (caller.parent().hasClass('fl-main-menu__item--browse')){
      //
    }

    else if (caller.parent().hasClass('fl-main-menu__item--create')){
      //
    }

    else if (caller.parent().hasClass('fl-main-menu__item--edit')){
      // $('.fl-panel--editor').show();
      // florence_menu_edit
      // fl-panel--sub-menu
      $('.fl-panel--sub-menu').html(florence_menu_edit);
      // console.log(florence_menu_edit);

      LoadPageDataIntoEditor();
      setInterval(checkEditPageLocation, intIntervalTime);
      $('.fl-panel--editor__nav__save').click(function() {
        if($('.fl-panel--editor__publish-owner').val().length != 0 && $('.fl-panel--editor__publish-id').val().length != 0){
          pageData = $('.fl-editor').val();
          save("testCollection", pageData);
          //console.log(parser.pathname);
        } else {
          alert('Publish owner and Publish id cannot be blank!');
        }

      });

        $('.fl-panel--editor__nav__approve').click(function () {
            approve(collectionName);
        });
        $('.fl-panel--editor__nav__publish').click(function () {
            publish(collectionName);
        });

    }

    if (caller.parent().hasClass('fl-main-menu__item--approve')){
      //
    }

    // else if (caller.parent().hasClass('fl-main-menu__item--publish')){
    //   //
    // }

    else {
      //
    }

  }

function removeSubMenus(){
  //$('.fl-panel--sub-menu').hide();
  $('.fl-panel--sub-menu').empty();
}

function removePreviewColClasses(){
  $('.fl-panel--preview').removeClass('col--4');
  $('.fl-panel--preview').removeClass('col--8');
}

function enablePreview(){
  $('.fl-panel--preview__inner').addClass('fl-panel--preview__inner--active');
}

function checkEditPageLocation() {
  if (pageurl != window.location.href) {
    pageurl = window.location.href;
    $(window.location).trigger("change", {
      newpage: LoadPageDataIntoEditor()
    });
  }
}

})(jQuery);
<|endoftext|>


<commit_before>// Generate a pass file.

var applyImageMethods = require("./images");
var Crypto            = require("crypto");
var EventEmitter      = require("events").EventEmitter;
var execFile          = require("child_process").execFile;
var Stream            = require("stream");
var inherits          = require("util").inherits;
var File              = require("fs");
var HTTP              = require("http");
var HTTPS             = require("https");
var Path              = require("path");
var Zip               = require("./zip");

// Top-level pass fields.
var TOP_LEVEL           = [ "authenticationToken", "backgroundColor", "barcode", "description",
                            "foregroundColor", "labelColor", "locations", "logoText",
                            "organizationName", "relevantDate", "serialNumber",
                            "suppressStripShine", "webServiceURL"];
// These top level fields are required for a valid pass.
var REQUIRED_TOP_LEVEL  = [ "description", "organizationName", "passTypeIdentifier",
                            "serialNumber", "teamIdentifier" ];
// Pass structure keys.
var STRUCTURE_FIELDS    = [ "auxiliaryFields", "backFields", "headerFields",
                            "primaryFields", "secondaryFields" ];
// These images are required for a valid pass.
var REQUIRED_IMAGES     = [ "icon", "logo" ];

// Create a new pass.
//
// tempplate  - The template
// fields     - Pass fields (description, serialNumber, logoText)
function Pass(template, fields, images) {
  this.template = template;
  this.fields = cloneObject(fields);
  // Structure is basically reference to all the fields under a given style
  // key, e.g. if style is coupon then structure.primaryFields maps to
  // fields.coupon.primaryFields.
  var style = template.style;
  this.structure = this.fields[style];
  if (!this.structure)
    this.structure = this.fields[style] = {};
  this.images = cloneObject(images);
}

inherits(Pass, EventEmitter);
applyImageMethods(Pass);

// Accessor methods for top-level fields (description, serialNumber, logoText,
// etc).
//
// Call with an argument to set field and return self, call with no argument to
// get field value.
//
//   pass.description("Unbelievable discount");
//   console.log(pass.description());
TOP_LEVEL.forEach(function(key) {
  Pass.prototype[key] = function(value) {
    if (arguments.length === 0) {
      return this.fields[key];
    } else {
      this.fields[key] = value;
      return this;
    }
  };
});

// Accessor methods for structure fields (primaryFields, backFields, etc).
//
// For example:
//
//   pass.headerFields.add("time", "The Time", "10:00AM");
//   pass.backFields.add("url", "Web site", "http://example.com");
STRUCTURE_FIELDS.forEach(function(key) {
  Pass.prototype.__defineGetter__(key, function() {
    return new Fields(this, key);
  });
});

// Field accessors.
function Fields(pass, key) {
  this.pass = pass;
  this.key = key;
}

// Adds a field to the end of the list.
//
// You can call this method with three/four arguments:
// key      - Field key
// label    - Field label (optional)
// value    - Field value
// options  - Other field options (e.g. dateStyle)
//
// You can call this method with a single object that contains all field
// properties (key, label, etc).
//
// You can also call with an array of either one.
//
// Returns self.
Fields.prototype.add = function(key, label, value, options) {
  var field, k;
  if (arguments.length > 1) {
    this.remove(key);
    field = { key: key, value: value };
    if (label)
      field.label = label;
    if (options) {
      for (k in options)
        field[k] = options[k];
    }
    this.all().push(field);
  } else if (Array.isArray(arguments[0])) {
    var array = arguments[0];
    for (var i in array)
      this.add.call(this, array[i]);
  } else {
    var properties = arguments[0];
    key = properties.key;
    this.remove(key);
    field = {};
      for (k in properties)
        field[k] = properties[k];
    this.all().push(field);
  }
  return this;
};

// Returns a field.
//
// If field exists, returns an object with:
// key      - Field key
// label    - Field label (optional)
// value    - Field value
// Other field options (e.g. dateStyle)
Fields.prototype.get = function(key) {
  var fields = this.pass.structure[this.key];
  if (fields) {
    for (var i in fields) {
      var field = fields[i];
      if (field.key == key)
        return field;
    }
  }
  return null;
};

// Returns an array of all fields.
Fields.prototype.all = function() {
  var fields = this.pass.structure[this.key];
  if (!fields)
    this.pass.structure[this.key] = fields = [];
  return fields;
};

// Removes a given field.
Fields.prototype.remove = function(key) {
  var fields = this.pass.structure[this.key];
  if (fields) {
    for (var i in fields) {
      if (fields[i].key == key) {
        fields.splice(i, 1);
        break;
      }
    }
  }
  return this;
};

// Removes all fields.
Fields.prototype.clear = function() {
  this.pass.structure[this.key] = [];
  return this;
};

// Validate pass, throws error if missing a mandatory top-level field or image.
Pass.prototype.validate = function() {
  for (var i in REQUIRED_TOP_LEVEL) {
    var k1 = REQUIRED_TOP_LEVEL[i];
    if (!this.fields[k1])
      throw new Error("Missing field " + k1);
  }
  for (var j in REQUIRED_IMAGES) {
    var k2 = REQUIRED_IMAGES[j];
    if (!this.images[k2])
      throw new Error("Missing image " + k2 + ".png");
  }
};

// Returns the pass.json object (not a string).
Pass.prototype.getPassJSON = function() {
  var fields = cloneObject(this.fields);
  fields.formatVersion = 1;
  return fields;
};

// Pipe pass to a write stream.
//
// output - Write stream
Pass.prototype.pipe = function(output) {
  var self = this;
  var zip = new Zip(output);
  var lastError;

  zip.on("error", function(error) {
    lastError = error;
  });

  // Validate before attempting to create
  try {
    this.validate();
  } catch (error) {
    process.nextTick(function() {
      self.emit("error", error);
    });
    return;
  }

  // Construct manifest here
  var manifest = {};
  // Add file to zip and it's SHA to manifest
  function addFile(filename) {
    var file = zip.addFile(filename);
    var sha = new SHAWriteStream(manifest, filename, file);
    return sha;
  }

  // Create pass.json
  var passJson = new Buffer(JSON.stringify(this.getPassJSON()), "utf-8");
  addFile("pass.json").end(passJson, "utf8");

  var expecting = 0;
  for (var key in this.images) {
    var filename = key.replace(/2x$/, "@2x") + ".png";
    addImage(addFile(filename), this.images[key], function(error) {
      --expecting;
      if (error)
        lastError = error;
      if (expecting === 0)
        doneWithImages();
    });
    ++expecting;
  }

  function doneWithImages() {
    if (lastError) {
      zip.close();
      self.emit("error", lastError);
    } else {
      self.signZip(zip, manifest, function(error) {
        zip.close();
        zip.on("end", function() {
          self.emit("end");
        });
        zip.on("error", function(error) {
          self.emit("error", error);
        });
      });
    }
  }
};

// Use this to send pass as HTTP response.
//
// response - HTTP response
// callback - Called when done sending/error occurred
//
// Adds appropriate headers and pipes pass to response.
Pass.prototype.render = function(response, callback) {
  response.setHeader("Content-Type", "application/vnd.apple.pkpass");
  if (callback) {
    this.on("error", callback);
    this.on("end", callback);
  }
  this.pipe(response);
};

function addImage(file, source, callback) {
  if (typeof(source) == "string" || source instanceof String) {
    if (/^https?:/i.test(source)) {
      // URL
      var protocol = /^https:/i.test(source) ? HTTPS : HTTP;
      protocol.get(source, function(response) {
        if (response.statusCode == 200) {
          response.on("end", callback);
          response.pipe(file);
          response.resume();
        } else
          callback(new Error("Server returned " + response.statusCode + " for " + source));
      }).on("error", callback);
    } else {
      // Assume filename
      var stream = File.createReadStream(source);
      stream.pipe(file);
      file.on("close", callback);
    }
  } else if (source instanceof Buffer) {
    file.on("close", callback);
    file.write(source);
    file.end();
  } else if (typeof(source) == "function") {
    try {
      source(file);
      callback();
    } catch (error) {
      callback(error);
    }
  } else {
    // image is not a supported type
    callback(new Error("Cannot load image " + file.filename + ", must be String (filename), Buffer or function"));
  }
}

// Add manifest.json and signature files.
Pass.prototype.signZip = function(zip, manifest, callback) {
  var json = JSON.stringify(manifest);
  // Add manifest.json
  zip.addFile("manifest.json").end(json, "utf-8");
  // Create signature
  signManifest(this.template, json, function(error, signature) {
    if (!error) {
      // Write signature file
      zip.addFile("signature").end(signature);
    }
    callback(error);
  });
};

// Signs a manifest and returns the signature.
function signManifest(template, manifest, callback) {
  var identifier = template.passTypeIdentifier().replace(/^pass./, "");

  var args = [
    "smime",
    "-sign", "-binary",
    "-signer",    Path.resolve(template.keysPath, identifier + ".pem"),
    "-certfile",  Path.resolve(template.keysPath, "wwdr.pem"),
    "-passin",    "pass:" + template.password
  ];
  var sign = execFile("openssl", args, { stdio: "pipe" }, function(error, stdout, stderr) {
    if (error || stderr.trim()) {
      callback(new Error(stderr));
    } else {
      var signature = stdout.split(/\n\n/)[3];
      callback(null, new Buffer(signature, "base64"));
    }
  });
  sign.stdin.write(manifest);
  sign.stdin.end();
}

// Clone an object by copying all its properties and returning new object.
// If the argument is missing or null, returns a new object.
function cloneObject(object) {
  var clone = {};
  if (object) {
    for (var key in object)
      clone[key] = object[key];
  }
  return clone;
}

// -- Manifest output stream --

// A write stream that calculates SHA from the output and updates the manifest
// accordingly.
//
// manifest - Manifest object
// filename - Filename (manifest property to set)
// output   - Pipe to this output stream
function SHAWriteStream(manifest, filename, output) {
  this.output = output;
  this.manifest = manifest;
  this.filename = filename;
  this.sha = Crypto.createHash("sha1");
  output.on("close", this.emit.bind(this, "close"));
  output.on("error", this.emit.bind(this, "error"));
  var self = this;
  this.on("pipe", function(source) {
    source.on("data", self.write.bind(self));
    source.resume();
  });
}

inherits(SHAWriteStream, Stream);

SHAWriteStream.prototype.write = function(buffer, encoding) {
  this.output.write(buffer, encoding);
  this.sha.update(buffer, encoding);
  return true;
};

SHAWriteStream.prototype.end = function(buffer, encoding) {
  if (buffer)
    this.write(buffer, encoding);
  this.output.end();
  this.manifest[this.filename] = this.sha.digest("hex");
};

module.exports = Pass;
<commit_msg>Modified lib to also be able to use locals<commit_after>// Generate a pass file.

var applyImageMethods = require("./images");
var Crypto            = require("crypto");
var EventEmitter      = require("events").EventEmitter;
var execFile          = require("child_process").execFile;
var Stream            = require("stream");
var inherits          = require("util").inherits;
var File              = require("fs");
var HTTP              = require("http");
var HTTPS             = require("https");
var Path              = require("path");
var Zip               = require("./zip");
var async             = require("async");

// Top-level pass fields.
var TOP_LEVEL           = [ "authenticationToken", "backgroundColor", "barcode", "description",
                            "foregroundColor", "labelColor", "locations", "logoText",
                            "organizationName", "relevantDate", "serialNumber",
                            "suppressStripShine", "webServiceURL"];
// These top level fields are required for a valid pass.
var REQUIRED_TOP_LEVEL  = [ "description", "organizationName", "passTypeIdentifier",
                            "serialNumber", "teamIdentifier" ];
// Pass structure keys.
var STRUCTURE_FIELDS    = [ "auxiliaryFields", "backFields", "headerFields",
                            "primaryFields", "secondaryFields" ];
// These images are required for a valid pass.
var REQUIRED_IMAGES     = [ "icon", "logo" ];

// Create a new pass.
//
// tempplate  - The template
// fields     - Pass fields (description, serialNumber, logoText)
function Pass(template, fields, images) {
  this.template = template;
  this.fields = cloneObject(fields);
  // Structure is basically reference to all the fields under a given style
  // key, e.g. if style is coupon then structure.primaryFields maps to
  // fields.coupon.primaryFields.
  var style = template.style;
  this.structure = this.fields[style];
  if (!this.structure)
    this.structure = this.fields[style] = {};
  this.images = cloneObject(images);
}

inherits(Pass, EventEmitter);
applyImageMethods(Pass);

// Accessor methods for top-level fields (description, serialNumber, logoText,
// etc).
//
// Call with an argument to set field and return self, call with no argument to
// get field value.
//
//   pass.description("Unbelievable discount");
//   console.log(pass.description());
TOP_LEVEL.forEach(function(key) {
  Pass.prototype[key] = function(value) {
    if (arguments.length === 0) {
      return this.fields[key];
    } else {
      this.fields[key] = value;
      return this;
    }
  };
});

// Accessor methods for structure fields (primaryFields, backFields, etc).
//
// For example:
//
//   pass.headerFields.add("time", "The Time", "10:00AM");
//   pass.backFields.add("url", "Web site", "http://example.com");
STRUCTURE_FIELDS.forEach(function(key) {
  Pass.prototype.__defineGetter__(key, function() {
    return new Fields(this, key);
  });
});

// Field accessors.
function Fields(pass, key) {
  this.pass = pass;
  this.key = key;
}

// Adds a field to the end of the list.
//
// You can call this method with three/four arguments:
// key      - Field key
// label    - Field label (optional)
// value    - Field value
// options  - Other field options (e.g. dateStyle)
//
// You can call this method with a single object that contains all field
// properties (key, label, etc).
//
// You can also call with an array of either one.
//
// Returns self.
Fields.prototype.add = function(key, label, value, options) {
  var field, k;
  if (arguments.length > 1) {
    this.remove(key);
    field = { key: key, value: value };
    if (label)
      field.label = label;
    if (options) {
      for (k in options)
        field[k] = options[k];
    }
    this.all().push(field);
  } else if (Array.isArray(arguments[0])) {
    var array = arguments[0];
    for (var i in array)
      this.add.call(this, array[i]);
  } else {
    var properties = arguments[0];
    key = properties.key;
    this.remove(key);
    field = {};
      for (k in properties)
        field[k] = properties[k];
    this.all().push(field);
  }
  return this;
};

// Returns a field.
//
// If field exists, returns an object with:
// key      - Field key
// label    - Field label (optional)
// value    - Field value
// Other field options (e.g. dateStyle)
Fields.prototype.get = function(key) {
  var fields = this.pass.structure[this.key];
  if (fields) {
    for (var i in fields) {
      var field = fields[i];
      if (field.key == key)
        return field;
    }
  }
  return null;
};

// Returns an array of all fields.
Fields.prototype.all = function() {
  var fields = this.pass.structure[this.key];
  if (!fields)
    this.pass.structure[this.key] = fields = [];
  return fields;
};

// Removes a given field.
Fields.prototype.remove = function(key) {
  var fields = this.pass.structure[this.key];
  if (fields) {
    for (var i in fields) {
      if (fields[i].key == key) {
        fields.splice(i, 1);
        break;
      }
    }
  }
  return this;
};

// Removes all fields.
Fields.prototype.clear = function() {
  this.pass.structure[this.key] = [];
  return this;
};

// Validate pass, throws error if missing a mandatory top-level field or image.
Pass.prototype.validate = function() {
  for (var i in REQUIRED_TOP_LEVEL) {
    var k1 = REQUIRED_TOP_LEVEL[i];
    if (!this.fields[k1])
      throw new Error("Missing field " + k1);
  }
  for (var j in REQUIRED_IMAGES) {
    var k2 = REQUIRED_IMAGES[j];
    if (!this.images[k2])
      throw new Error("Missing image " + k2 + ".png");
  }
};

// Returns the pass.json object (not a string).
Pass.prototype.getPassJSON = function() {
  var fields = cloneObject(this.fields);
  fields.formatVersion = 1;
  return fields;
};

// Pipe pass to a write stream.
//
// output - Write stream
Pass.prototype.pipe = function(output) {
  var self = this;
  var zip = new Zip(output);
  var lastError;
  var doneImages = false;
  var doneLocals = false;

  zip.on("error", function(error) {
    lastError = error;
  });

  // Validate before attempting to create
  try {
    this.validate();
  } catch (error) {
    process.nextTick(function() {
      self.emit("error", error);
    });
    return;
  }

  // Construct manifest here
  var manifest = {};
  // Add file to zip and it's SHA to manifest
  function addFile(filename) {
    var file = zip.addFile(filename);
    var sha = new SHAWriteStream(manifest, filename, file);
    return sha;
  }

  // Create pass.json
  var passJson = new Buffer(JSON.stringify(this.getPassJSON()), "utf-8");
  addFile("pass.json").end(passJson, "utf8");

  var pass = this
  async.forEach(Object.keys(pass.images), function (key, cb) {
    var filename = key.replace(/2x$/, "@2x") + ".png";
    writeFile(addFile(filename), pass.images[key], cb);
  }, function(err) {
    if (err) {
      lastError = err;
      doneWithWriting();
    } else {
      if(!pass.localizations) return doneWithWriting();
      pass.localizations
      async.forEach(Object.keys(pass.localizations), function (key, cb) {
        writeFile(addFile(key), pass.localizations[key], cb);
      }, function(err) {
        if (err) lastError = err;
        doneWithWriting();
      })
    }
  });

  function doneWithWriting() {
    if (lastError) {
      zip.close();
      self.emit("error", lastError);
    } else {
      self.signZip(zip, manifest, function(error) {
        zip.close();
        zip.on("end", function() {
          self.emit("end");
        });
        zip.on("error", function(error) {
          self.emit("error", error);
        });
      });
    }
  }
};

// Use this to send pass as HTTP response.
//
// response - HTTP response
// callback - Called when done sending/error occurred
//
// Adds appropriate headers and pipes pass to response.
Pass.prototype.render = function(response, callback) {
  response.setHeader("Content-Type", "application/vnd.apple.pkpass");
  if (callback) {
    this.on("error", callback);
    this.on("end", callback);
  }
  this.pipe(response);
};

function writeFile(file, source, callback) {
  if (typeof(source) == "string" || source instanceof String) {
    if (/^https?:/i.test(source)) {
      // URL
      var protocol = /^https:/i.test(source) ? HTTPS : HTTP;
      protocol.get(source, function(response) {
        if (response.statusCode == 200) {
          response.on("end", callback);
          response.pipe(file);
          response.resume();
        } else
          callback(new Error("Server returned " + response.statusCode + " for " + source));
      }).on("error", callback);
    } else {
      // Assume filename
      var stream = File.createReadStream(source);
      stream.pipe(file);
      file.on("close", callback);
    }
  } else if (source instanceof Buffer) {
    file.on("close", callback);
    file.write(source);
    file.end();
  } else if (typeof(source) == "function") {
    try {
      source(file);
      callback();
    } catch (error) {
      callback(error);
    }
  } else {
    // image is not a supported type
    callback(new Error("Cannot load image " + file.filename + ", must be String (filename), Buffer or function"));
  }
}

function addLocalFile(file, source, callback) {
  if (typeof(source) == "string" || source instanceof String) {
    if (/^https?:/i.test(source)) {
      // URL
      var protocol = /^https:/i.test(source) ? HTTPS : HTTP;
      protocol.get(source, function(response) {
        if (response.statusCode == 200) {
          response.on("end", callback);
          response.pipe(file);
          response.resume();
        } else
          callback(new Error("Server returned " + response.statusCode + " for " + source));
      }).on("error", callback);
    } else {
      // Assume filename
      var stream = File.createReadStream(source);
      stream.pipe(file);
      file.on("close", callback);
    }
  } else if (source instanceof Buffer) {
    file.on("close", callback);
    file.write(source);
    file.end();
  } else if (typeof(source) == "function") {
    try {
      source(file);
      callback();
    } catch (error) {
      callback(error);
    }
  } else {
    // image is not a supported type
    callback(new Error("Cannot load image " + file.filename + ", must be String (filename), Buffer or function"));
  }
}

// Add manifest.json and signature files.
Pass.prototype.signZip = function(zip, manifest, callback) {
  var json = JSON.stringify(manifest);
  // Add manifest.json
  zip.addFile("manifest.json").end(json, "utf-8");
  // Create signature
  signManifest(this.template, json, function(error, signature) {
    if (!error) {
      // Write signature file
      zip.addFile("signature").end(signature);
    }
    callback(error);
  });
};

// Signs a manifest and returns the signature.
function signManifest(template, manifest, callback) {
  var identifier = template.passTypeIdentifier().replace(/^pass./, "");

  var args = [
    "smime",
    "-sign", "-binary",
    "-signer",    Path.resolve(template.keysPath, identifier + ".pem"),
    "-certfile",  Path.resolve(template.keysPath, "wwdr.pem"),
    "-passin",    "pass:" + template.password
  ];
  var sign = execFile("openssl", args, { stdio: "pipe" }, function(error, stdout, stderr) {
    if (error) {
      callback(new Error(stderr));
    } else {
      var signature = stdout.split(/\n\n/)[3];
      callback(null, new Buffer(signature, "base64"));
    }
  });
  sign.stdin.write(manifest);
  sign.stdin.end();
}

// Clone an object by copying all its properties and returning new object.
// If the argument is missing or null, returns a new object.
function cloneObject(object) {
  var clone = {};
  if (object) {
    for (var key in object)
      clone[key] = object[key];
  }
  return clone;
}

// -- Manifest output stream --

// A write stream that calculates SHA from the output and updates the manifest
// accordingly.
//
// manifest - Manifest object
// filename - Filename (manifest property to set)
// output   - Pipe to this output stream
function SHAWriteStream(manifest, filename, output) {
  this.output = output;
  this.manifest = manifest;
  this.filename = filename;
  this.sha = Crypto.createHash("sha1");
  output.on("close", this.emit.bind(this, "close"));
  output.on("error", this.emit.bind(this, "error"));
  var self = this;
  this.on("pipe", function(source) {
    source.on("data", self.write.bind(self));
    source.resume();
  });
}

inherits(SHAWriteStream, Stream);

SHAWriteStream.prototype.write = function(buffer, encoding) {
  this.output.write(buffer, encoding);
  this.sha.update(buffer, encoding);
  return true;
};

SHAWriteStream.prototype.end = function(buffer, encoding) {
  if (buffer)
    this.write(buffer, encoding);
  this.output.end();
  this.manifest[this.filename] = this.sha.digest("hex");
};

module.exports = Pass;
<|endoftext|>


<commit_before>var GlobalPinnedTabs = {

    windowId: undefined,
    tabId: undefined,
    disableTabUpdateHandling: false,

    init: function () {
        ArrayExtensions.init();
        Chrome.init();
        Storage.loadData(function () {
            GlobalPinnedTabs.createTabs();
        });

        GlobalPinnedTabs.registerForChromeEvents();
    },

    registerForChromeEvents: function () {
        chrome.windows.onFocusChanged.addListener(GlobalPinnedTabs.onActiveWindowChanged);
        chrome.windows.onRemoved.addListener(GlobalPinnedTabs.onWindowClosed);
        chrome.tabs.onUpdated.addListener(GlobalPinnedTabs.onTabUpdated);
        chrome.tabs.onRemoved.addListener(GlobalPinnedTabs.onTabClosed);
        chrome.tabs.onActivated.addListener(GlobalPinnedTabs.onTabActivated);
    },

    createTabs: function () {
        Chrome.getAllWindows(function (windows) {
            Storage.globallyPinnedTabs.createTabs(windows);
        });
    },

    onActiveWindowChanged: function (windowId) {
        console.log('active window changed');
        if (windowId === chrome.windows.WINDOW_ID_NONE)
            return;
        Chrome.executeWhenUserStoppedDragging(function () {
            Chrome.getAllWindows(function (windows) {
                var window = windows.filter(function (x) {
                    return x.type === 'normal' && x.focused;
                })[0];
                if (window) {
                    GlobalPinnedTabs.disableTabUpdateHandling = true;
                    Storage.globallyPinnedTabs.activateWindow(window, function () {
                        GlobalPinnedTabs.disableTabUpdateHandling = false;
                    });
                }
            });
        });
    },

    onWindowClosed: function (windowId) {
        console.log('window closed');
        Storage.globallyPinnedTabs.handleClosedWindow(windowId);
    },

    onTabActivated: function (activeInfo) {
        console.log('tab activated');
        chrome.tabs.get(activeInfo.tabId, Chrome.errorLogger(function (tab) {
            Storage.globallyPinnedTabs.updateTab(tab)
        }));
    },

    onTabUpdated: function (tabId, changeInfo, tab) {
        console.log('tab updated');
        if (GlobalPinnedTabs.disableTabUpdateHandling)
            return;
        if (changeInfo.pinned !== undefined) {
            if (changeInfo.pinned === true) {
                var isUnknownTab = !Storage.globallyPinnedTabs.getTabForAnyTabId(tabId);
                if (isUnknownTab && confirm('Make this a globally pinned tab that is visible in all windows?'))
                    Storage.globallyPinnedTabs.addTab(tab);
            } else {
                Storage.globallyPinnedTabs.handleClosedTab(tabId);
            }
        } else if (changeInfo.status === 'complete' || changeInfo.favIconUrl) {
            Storage.globallyPinnedTabs.updateTab(tab);
        }
    },

    onTabClosed: function (tabId, removeInfo) {
        console.log('tab closed');
        if (!removeInfo.isWindowClosing)
            Storage.globallyPinnedTabs.handleClosedTab(tabId);
    }
};

GlobalPinnedTabs.init();<commit_msg>Remove logging<commit_after>var GlobalPinnedTabs = {

    windowId: undefined,
    tabId: undefined,
    disableTabUpdateHandling: false,

    init: function () {
        ArrayExtensions.init();
        Chrome.init();
        Storage.loadData(function () {
            GlobalPinnedTabs.createTabs();
        });

        GlobalPinnedTabs.registerForChromeEvents();
    },

    registerForChromeEvents: function () {
        chrome.windows.onFocusChanged.addListener(GlobalPinnedTabs.onActiveWindowChanged);
        chrome.windows.onRemoved.addListener(GlobalPinnedTabs.onWindowClosed);
        chrome.tabs.onUpdated.addListener(GlobalPinnedTabs.onTabUpdated);
        chrome.tabs.onRemoved.addListener(GlobalPinnedTabs.onTabClosed);
        chrome.tabs.onActivated.addListener(GlobalPinnedTabs.onTabActivated);
    },

    createTabs: function () {
        Chrome.getAllWindows(function (windows) {
            Storage.globallyPinnedTabs.createTabs(windows);
        });
    },

    onActiveWindowChanged: function (windowId) {
        if (windowId === chrome.windows.WINDOW_ID_NONE)
            return;
        Chrome.executeWhenUserStoppedDragging(function () {
            Chrome.getAllWindows(function (windows) {
                var window = windows.filter(function (x) {
                    return x.type === 'normal' && x.focused;
                })[0];
                if (window) {
                    GlobalPinnedTabs.disableTabUpdateHandling = true;
                    Storage.globallyPinnedTabs.activateWindow(window, function () {
                        GlobalPinnedTabs.disableTabUpdateHandling = false;
                    });
                }
            });
        });
    },

    onWindowClosed: function (windowId) {
        Storage.globallyPinnedTabs.handleClosedWindow(windowId);
    },

    onTabActivated: function (activeInfo) {
        chrome.tabs.get(activeInfo.tabId, Chrome.errorLogger(function (tab) {
            Storage.globallyPinnedTabs.updateTab(tab)
        }));
    },

    onTabUpdated: function (tabId, changeInfo, tab) {
        if (GlobalPinnedTabs.disableTabUpdateHandling)
            return;
        if (changeInfo.pinned !== undefined) {
            if (changeInfo.pinned === true) {
                var isUnknownTab = !Storage.globallyPinnedTabs.getTabForAnyTabId(tabId);
                if (isUnknownTab && confirm('Make this a globally pinned tab that is visible in all windows?'))
                    Storage.globallyPinnedTabs.addTab(tab);
            } else {
                Storage.globallyPinnedTabs.handleClosedTab(tabId);
            }
        } else if (changeInfo.status === 'complete' || changeInfo.favIconUrl) {
            Storage.globallyPinnedTabs.updateTab(tab);
        }
    },

    onTabClosed: function (tabId, removeInfo) {
        if (!removeInfo.isWindowClosing)
            Storage.globallyPinnedTabs.handleClosedTab(tabId);
    }
};

GlobalPinnedTabs.init();<|endoftext|>


<commit_before>var _tabHistory = [];
var _opts = {
  // this option allow previous tab to be from any window
  'allWindows': true
};

// filters
function filterHistory(tab) {
  return (tab[this.key] !== this.value);
}

// Some type safety
function toObj(obj, idx, value) {
  if (typeof obj !== 'object') {
    obj = {};
  }
  obj[idx] = value;
  return obj;
}

function addToHistory(tabInfo) {
  var historyLen = _tabHistory.length - 1;

  // always push the first element
  if (historyLen < 0) {
    _tabHistory.push(tabInfo);
    return;
  }

  // the new tab should never be the same than the previous one, but in case...
  var lastTab = _tabHistory[historyLen];
  var tabId = tabInfo.tabId;

  if (lastTab.tabId === tabId) { return; }

  // In case of a simple swap between the 2 last tabs, avoid to push.
  var secondLastTab = _tabHistory[historyLen - 1];
  if (secondLastTab && secondLastTab.tabId === tabId) {
    _tabHistory[historyLen - 1] = _tabHistory[historyLen];
    _tabHistory[historyLen] = tabInfo;
  } else {
    // check if tab was already in the history
    var idx = getTabIdx(tabId);
    if (idx !== -1) {
      _tabHistory = _tabHistory.splice(idx, 1);
    }
    _tabHistory.push(tabInfo);
  }
  // Could filter history here if wierd stuff happen or if it gets to big
}

function getTabIdx(tabId) {
  for (var i = _tabHistory.length - 1; i >= 0; i--) {
    if (_tabHistory[i].tabId === tabId) {
      return i;
    }
  }
  return -1;
}

function removeFromHistory(tabId, removeInfo) {
  var context = {};
  if (removeInfo.isWindowClosing) {
    context.key = 'windowId';
    var idx = getTabIdx(tabId);
    // if the tab is not in the history we can stop here
    if (idx === -1) { return; }
    context.value = _tabHistory[idx].windowId;
  } else {
    context.key = 'tabId';
    context.value = tabId;
  }
  _tabHistory = _tabHistory.filter(filterHistory, context);
}

// Listen to tab changes to save previous tab
chrome.tabs.onActivated.addListener(addToHistory);

// Clean history of removed tabs
chrome.tabs.onRemoved.addListener(removeFromHistory);

// Listen to window changes to do the same
if (_opts.allWindows) {
  chrome.windows.onFocusChanged.addListener(function (windowId) {
    // get active tab
    var queryInfo = {
      'windowId': windowId,
      'active': true
    };
    chrome.tabs.query(queryInfo, function (tabs) {
      var tab = tabs[0];
      addToHistory({
        'tabId': tab.id,
        'windowId': tab.windowId
      });
    });
  });
}

function getPreviousTab() {
  if (_opts.allWindows) {
    // return second last tab, the last one being the current.
    var secondLastTab = _tabHistory[_tabHistory.length - 2];
    if (typeof secondLastTab !== 'undefined') {
      return secondLastTab.tabId;
    }
  } else {
    var i = _tabHistory.length - 1;
    var windowId = _tabHistory[i].windowId;
    var tabId = _tabHistory[i].tabId;
    for (i--; i >= 0; i--) {
      var tab = _tabHistory[i];
      if (tab.windowId === windowId && tab.tabId !== tabId) {
        return tab.tabId;
      }
    }
  }
  return null;
}

// Send previous tab
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  sendResponse(getPreviousTab());
});
<commit_msg>Ignore DevTools and icognito in history<commit_after>var _tabHistory = [];
var _opts = {
  // this option allow previous tab to be from any window
  'allWindows': true
};

// filters
function filterHistory(tab) {
  return (tab[this.key] !== this.value);
}

// Some type safety
function toObj(obj, idx, value) {
  if (typeof obj !== 'object') {
    obj = {};
  }
  obj[idx] = value;
  return obj;
}

function addToHistory(tabInfo) {
  var historyLen = _tabHistory.length - 1;

  // always push the first element
  if (historyLen < 0) {
    _tabHistory.push(tabInfo);
    return;
  }

  // the new tab should never be the same than the previous one, but in case...
  var lastTab = _tabHistory[historyLen];
  var tabId = tabInfo.tabId;

  if (lastTab.tabId === tabId) { return; }

  // In case of a simple swap between the 2 last tabs, avoid to push.
  var secondLastTab = _tabHistory[historyLen - 1];
  if (secondLastTab && secondLastTab.tabId === tabId) {
    _tabHistory[historyLen - 1] = _tabHistory[historyLen];
    _tabHistory[historyLen] = tabInfo;
  } else {
    // check if tab was already in the history
    var idx = getTabIdx(tabId);
    if (idx !== -1) {
      _tabHistory = _tabHistory.splice(idx, 1);
    }
    _tabHistory.push(tabInfo);
  }
  // Could filter history here if wierd stuff happen or if it gets to big
}

function getTabIdx(tabId) {
  for (var i = _tabHistory.length - 1; i >= 0; i--) {
    if (_tabHistory[i].tabId === tabId) {
      return i;
    }
  }
  return -1;
}

function removeFromHistory(tabId, removeInfo) {
  var context = {};
  if (removeInfo.isWindowClosing) {
    context.key = 'windowId';
    var idx = getTabIdx(tabId);
    // if the tab is not in the history we can stop here
    if (idx === -1) { return; }
    context.value = _tabHistory[idx].windowId;
  } else {
    context.key = 'tabId';
    context.value = tabId;
  }
  _tabHistory = _tabHistory.filter(filterHistory, context);
}

// Listen to tab changes to save previous tab
chrome.tabs.onActivated.addListener(addToHistory);

// Clean history of removed tabs
chrome.tabs.onRemoved.addListener(removeFromHistory);

// Listen to window changes to do the same
if (_opts.allWindows) {
  chrome.windows.onFocusChanged.addListener(function (windowId) {
    // get active tab
    var queryInfo = {
      'windowId': windowId,
      'active': true
    };
    chrome.tabs.query(queryInfo, function (tabs) {
      var tab = tabs[0];
      if (!(/^chrome\-devtools\:/.test(tab.url) || tab.incognito)) {
        addToHistory({
          'tabId': tab.id,
          'windowId': tab.windowId
        });
      }
    });
  });
}

function getPreviousTab() {
  if (_opts.allWindows) {
    // return second last tab, the last one being the current.
    var secondLastTab = _tabHistory[_tabHistory.length - 2];
    if (typeof secondLastTab !== 'undefined') {
      return secondLastTab.tabId;
    }
  } else {
    var i = _tabHistory.length - 1;
    var windowId = _tabHistory[i].windowId;
    var tabId = _tabHistory[i].tabId;
    for (i--; i >= 0; i--) {
      var tab = _tabHistory[i];
      if (tab.windowId === windowId && tab.tabId !== tabId) {
        return tab.tabId;
      }
    }
  }
  return null;
}

// Send previous tab
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  sendResponse(getPreviousTab());
});
<|endoftext|>


<commit_before>var cp  = require('child_process');
var p   = require('os').platform().toLowerCase();

function probe(addr, config, callback) {
    config = config || {};

    var ls  = null;
    var log = config.log || console.log;
    var outstring = '';

    config = {
        numeric:  config.numeric  === undefined ? true : config.numeric,
        timeout:  parseInt(config.timeout  === undefined ? 2    : config.timeout, 10),
        minReply: parseInt(config.minReply === undefined ? 1    : config.minReply, 10),
        extra:    config.extra || []
    };

    var args    = [];
    var xfamily = ['linux', 'sunos', 'unix'];
    var regex   = /=.*[<|=]([0-9]*).*TTL|ttl..*=([0-9\.]*)/;

    if (xfamily.indexOf(p) !== -1) {
        //linux
        args = [];
        if (config.numeric  !== false) args.push('-n');

        if (config.timeout  !== false) args.push('-w ' + config.timeout);

        if (config.minReply !== false) args.push('-c ' + config.minReply);

        if (config.extra    !== false) args = args.concat(config.extra);

        args.push(addr);
        log('System command: /bin/ping ' + args.join(' '));
        ls = cp.spawn('/bin/ping', args);
    } else if (p.match(/^win/)) {
        //windows
        args = [];
        if (config.minReply !== false) args.push('-n ' + config.minReply);

        if (config.timeout  !== false) args.push('-w ' + config.timeout * 1000);

        if (config.extra    !== false) args = args.concat(config.extra);

        args.push(addr);

        var allArgs = [
            '/s', // leave quotes as they are
            '/c', // run and exit
            // !!! order of c and s is important - c must come last!!!
            '"', // enforce starting quote
            process.env.SystemRoot + '\\system32\\ping.exe' // command itself. Notice that you'll have to pass it quoted if it contains spaces
        ].concat(args)
            .concat('"'); // enforce closing quote

        log('System command: ' + (process.env.comspec || 'cmd.exe') + ' ' + allArgs.join(' '));
        // switch the command to cmd shell instead of the original command
        ls = cp.spawn(process.env.comspec || 'cmd.exe', allArgs, {windowsVerbatimArguments: true});
    } else if (p === 'darwin' || p === 'freebsd') {
        //mac osx or freebsd
        args = [];
        if (config.numeric  !== false) args.push('-n');

        if (config.timeout  !== false) args.push('-t ' + config.timeout);

        if (config.minReply !== false) args.push('-c ' + config.minReply);

        if (config.extra    !== false) args = args.concat(config.extra);

        args.push(addr);
        log('System command: /sbin/ping ' + args.join(' '));
        ls = cp.spawn('/sbin/ping', args);
    } else {
        if (callback) callback('Your platform "' + p + '" is not supported');
    }

    ls.on('error', function (e) {
        if (callback) {
            callback(new Error(
                'ping.probe: there was an error while executing the ping program. check the path or permissions...'));
        }
        callback = null;
    });

    ls.stdout.on('data', function (data) {
        outstring += String(data);
    });

    ls.on('exit', function (code) {
        var lines  = outstring.split('\n');
        var ms     = null;
        var result = 1;

        for (var t = 0; t < lines.length; t++) {
            var m = regex.exec(lines[t]) || '';
            if (m !== '') {
                ms = m[1] || m[2];
                result = 0;
                break;
            }
        }

        if (p.match(/^win/)) {
            result = (ms !== null);
        } else {
            result = !code;
        }
        if (callback) {
            callback(null, {
                host:  addr,
                alive: result,
                ms:    ms
            });
        }
        callback = null;
    });
}

exports.probe = probe;
<commit_msg>Remove argument spaces<commit_after>var cp  = require('child_process');
var p   = require('os').platform().toLowerCase();

function probe(addr, config, callback) {
    config = config || {};

    var ls  = null;
    var log = config.log || console.log;
    var outstring = '';

    config = {
        numeric:  config.numeric  === undefined ? true : config.numeric,
        timeout:  parseInt(config.timeout  === undefined ? 2    : config.timeout, 10),
        minReply: parseInt(config.minReply === undefined ? 1    : config.minReply, 10),
        extra:    config.extra || []
    };

    var args    = [];
    var xfamily = ['linux', 'sunos', 'unix'];
    var regex   = /=.*[<|=]([0-9]*).*TTL|ttl..*=([0-9\.]*)/;

    if (xfamily.indexOf(p) !== -1) {
        //linux
        args = [];
        if (config.numeric  !== false) args.push('-n');

        if (config.timeout  !== false) args.push('-w' + config.timeout);

        if (config.minReply !== false) args.push('-c' + config.minReply);

        if (config.extra    !== false) args = args.concat(config.extra);

        args.push(addr);
        log('System command: /bin/ping ' + args.join(' '));
        ls = cp.spawn('/bin/ping', args);
    } else if (p.match(/^win/)) {
        //windows
        args = [];
        if (config.minReply !== false) args.push('-n ' + config.minReply);

        if (config.timeout  !== false) args.push('-w ' + config.timeout * 1000);

        if (config.extra    !== false) args = args.concat(config.extra);

        args.push(addr);

        var allArgs = [
            '/s', // leave quotes as they are
            '/c', // run and exit
            // !!! order of c and s is important - c must come last!!!
            '"', // enforce starting quote
            process.env.SystemRoot + '\\system32\\ping.exe' // command itself. Notice that you'll have to pass it quoted if it contains spaces
        ].concat(args)
            .concat('"'); // enforce closing quote

        log('System command: ' + (process.env.comspec || 'cmd.exe') + ' ' + allArgs.join(' '));
        // switch the command to cmd shell instead of the original command
        ls = cp.spawn(process.env.comspec || 'cmd.exe', allArgs, {windowsVerbatimArguments: true});
    } else if (p === 'darwin' || p === 'freebsd') {
        //mac osx or freebsd
        args = [];
        if (config.numeric  !== false) args.push('-n');

        if (config.timeout  !== false) args.push('-t ' + config.timeout);

        if (config.minReply !== false) args.push('-c ' + config.minReply);

        if (config.extra    !== false) args = args.concat(config.extra);

        args.push(addr);
        log('System command: /sbin/ping ' + args.join(' '));
        ls = cp.spawn('/sbin/ping', args);
    } else {
        if (callback) callback('Your platform "' + p + '" is not supported');
    }

    ls.on('error', function (e) {
        if (callback) {
            callback(new Error(
                'ping.probe: there was an error while executing the ping program. check the path or permissions...'));
        }
        callback = null;
    });

    ls.stdout.on('data', function (data) {
        outstring += String(data);
    });

    ls.on('exit', function (code) {
        var lines  = outstring.split('\n');
        var ms     = null;
        var result = 1;

        for (var t = 0; t < lines.length; t++) {
            var m = regex.exec(lines[t]) || '';
            if (m !== '') {
                ms = m[1] || m[2];
                result = 0;
                break;
            }
        }

        if (p.match(/^win/)) {
            result = (ms !== null);
        } else {
            result = !code;
        }
        if (callback) {
            callback(null, {
                host:  addr,
                alive: result,
                ms:    ms
            });
        }
        callback = null;
    });
}

exports.probe = probe;
<|endoftext|>


<commit_before>function getHolidays(text) {
  const parser = new DOMParser();
  // server sometimes returns escaped HTML instead of XML entities...
  const xmlDoc = parser.parseFromString(text, 'text/html');

  const nodes = xmlDoc.querySelectorAll('item title');

  return Array.from(nodes).map(node => node.text);
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  fetch('https://www.checkiday.com/rss.php')
    .then(response => response.text())
    .then(getHolidays)
    .then(holidays => {
      chrome.contextMenus.removeAll();

      for (const holiday of holidays) {
        chrome.contextMenus.create({
          id: holiday,
          title: holiday,
          contexts: ['editable'],
          documentUrlPatterns: [sender.url],
        });
      }

      chrome.contextMenus.onClicked.addListener(({ menuItemId }) => {
        chrome.tabs.sendMessage(sender.tab.id, menuItemId);
      });

      return holidays.length;
    })
    .then(length => sendResponse(length));

  return true;
});
<commit_msg>documentation<commit_after>function getHolidays(text) {
  const parser = new DOMParser();
  // server sometimes returns escaped HTML instead of XML entities...
  const xmlDoc = parser.parseFromString(text, 'text/html');

  const nodes = xmlDoc.querySelectorAll('item title');

  return Array.from(nodes).map(node => node.text);
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  fetch('https://www.checkiday.com/rss.php')
    .then(response => response.text())
    .then(getHolidays)
    .then(holidays => {
      chrome.contextMenus.removeAll();

      for (const holiday of holidays) {
        chrome.contextMenus.create({
          id: holiday,
          title: holiday,
          contexts: ['editable'],
          documentUrlPatterns: [sender.url],
        });
      }

      chrome.contextMenus.onClicked.addListener(({ menuItemId }) => {
        chrome.tabs.sendMessage(sender.tab.id, menuItemId);
      });

      return holidays.length;
    })
    .then(length => sendResponse(length));

  // return true to signify async
  return true;
});
<|endoftext|>


<commit_before>/*global chrome, hwRules */
chrome.runtime.onInstalled.addListener(function(details) {
    chrome.storage.local.get(null, function (items) {
         // Upgrade stored data to a new format when a new version is installed.
        if (details.reason == 'update') {
            _upgradeData(items);
        }

        hwRules.resetRules();
    });

    function _upgradeData(items) {
        Object.keys(items).filter(function (domain) {
            var settings = items[domain];

            // For data from previous versions that doesn't have the create/access dates.
            // We'll use 0 as a special value to indicate that the date is not known. This will
            // allow us to know that these sites already have hashwords created for them, as
            // well as show a special string in the options page for such cases.
            if (settings.createDate == null) {
                settings.createDate = 0;
                settings.accessDate = 0;
                return true;
            }

            return false;
        });

        chrome.storage.local.set(items);
    }
});
<commit_msg>Always install rules on startup<commit_after>/*global chrome, hwRules */
chrome.runtime.onInstalled.addListener(function(details) {
    chrome.storage.local.get(null, function (items) {
         // Upgrade stored data to a new format when a new version is installed.
        if (details.reason == 'update') {
            _upgradeData(items);
        }
    });

    function _upgradeData(items) {
        Object.keys(items).filter(function (domain) {
            var settings = items[domain];

            // For data from previous versions that doesn't have the create/access dates.
            // We'll use 0 as a special value to indicate that the date is not known. This will
            // allow us to know that these sites already have hashwords created for them, as
            // well as show a special string in the options page for such cases.
            if (settings.createDate == null) {
                settings.createDate = 0;
                settings.accessDate = 0;
                return true;
            }

            return false;
        });

        chrome.storage.local.set(items);
    }
});

// Install rules on initialization
hwRules.resetRules();
<|endoftext|>


<commit_before>(function () {
    'use strict';
    /*jslint browser: true */
    /*global chrome, console, alert */

    // Get the source of the page
    function fetchPage(url, parents) {
        var xhr = new XMLHttpRequest(),
            pageSource;

        xhr.open("GET", url, true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                pageSource = xhr.responseText;
                console.log('Source retrieved!');
                return getValue(pageSource, parents);
            }
        };
        xhr.send();
    }

    // Get the value of our element from the source and the list of parents
    function getValue(pageSource, parents) {
        var source,
            value,
            i = 0,
            position = 0;

        // We inject our HTML in a div to be able to parse it
        source = document.createElement("root");
        pageSource = pageSource.split(/(<body[^<]*>|<\/body>)/ig)[2];
        source.innerHTML = pageSource;

        // console.log(source);

        // Traverse the node tree to find the new value of our element
        for (i = parents.length - 1; i >= 0; i -= 1) {
            position = parents[i];
            source = source.children[position];
        }

        value = parseFloat(source.innerHTML.match(/\d+/g).join(''));

        console.log("Value", value);
        console.log("Source", source);
        return value;
    }

    // Process the data we received from the page
    function getSelectedTag(selectionText, pageUrl, parents) {
        var value;

        if (isNaN(parseFloat(selectionText))) {
            alert("You have to select a number!");
        } else {
            value = fetchPage(pageUrl, parents);
        }
    }

    // Ask the page to send us the info we need
    function sendRequest(selectionText, pageUrl) {
        chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
            chrome.tabs.sendMessage(
                tabs[0].id,
                {method: "sendSource"},
                function (response) {
                    getSelectedTag(selectionText, pageUrl, response.parents);
                }
            );
        });
    }

    // The onClicked callback function.
    function onClickHandler(info, tab) {
        // console.log("item " + info.menuItemId + " was clicked");
        // console.log("info: " + JSON.stringify(info));
        // console.log("tab: " + JSON.stringify(tab));

        if (info.editable === false) {
            console.info("User selected text: " + info.selectionText);
            console.info("Page URL: " + info.pageUrl);

            sendRequest(info.selectionText, info.pageUrl);
        }
    }

    // Initialize the extension
    function init() {
        chrome.contextMenus.onClicked.addListener(onClickHandler);

        // Set up context menu tree at install time.
        chrome.runtime.onInstalled.addListener(function () {
            console.info("Installation...");

            chrome.contextMenus.create({
                "title": "graph this !",
                "contexts": ["selection"],
                "id": "context_selection"
            });
            console.info("Context menu item created");
        });
    }

    init();
}());<commit_msg>Add timer<commit_after>(function () {
    'use strict';
    /*jslint browser: true */
    /*global chrome, console, alert */

    // Get the source of the page
    function fetchPage(url, parents) {
        var xhr = new XMLHttpRequest(),
            pageSource;

        xhr.open("GET", url, true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                pageSource = xhr.responseText;
                console.log('Source retrieved!');
                return getValue(pageSource, parents);
            }
        };
        xhr.send();
    }

    // Get the value of our element from the source and the list of parents
    function getValue(pageSource, parents) {
        var source,
            value,
            i = 0,
            position = 0;

        // We inject our HTML in a div to be able to parse it
        source = document.createElement("root");
        pageSource = pageSource.split(/(<body[^<]*>|<\/body>)/ig)[2];
        source.innerHTML = pageSource;

        // console.log(source);

        // Traverse the node tree to find the new value of our element
        for (i = parents.length - 1; i >= 0; i -= 1) {
            position = parents[i];
            source = source.children[position];
        }

        value = parseFloat(source.innerHTML.match(/\d+/g).join(''));

        console.log("Value", value);
        console.log("Source", source);
        return value;
    }

    // Process the data we received from the page
    function getSelectedTag(selectionText, pageUrl, parents) {
        var value;

        if (isNaN(parseFloat(selectionText))) {
            alert("You have to select a number!");
        } else {
            value = fetchPage(pageUrl, parents);
        }
    }

    var timer;
    // Ask the page to send us the info we need
    function sendRequest(selectionText, pageUrl) {
        var onResponse = function (response) {
            clearInterval(timer);
            timer = setInterval(function() {
                getSelectedTag(selectionText, pageUrl, response.parents);
            }, 10 * 1000);
        };

        chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
            chrome.tabs.sendMessage(
                tabs[0].id,
                {method: "sendSource"},
                onResponse
            );
        });
    }

    // The onClicked callback function.
    function onClickHandler(info, tab) {
        // console.log("item " + info.menuItemId + " was clicked");
        // console.log("info: " + JSON.stringify(info));
        // console.log("tab: " + JSON.stringify(tab));

        if (info.editable === false) {
            console.info("User selected text: " + info.selectionText);
            console.info("Page URL: " + info.pageUrl);

            sendRequest(info.selectionText, info.pageUrl);
        }
    }

    // Initialize the extension
    function init() {
        chrome.contextMenus.onClicked.addListener(onClickHandler);

        // Set up context menu tree at install time.
        chrome.runtime.onInstalled.addListener(function () {
            console.info("Installation...");

            chrome.contextMenus.create({
                "title": "graph this !",
                "contexts": ["selection"],
                "id": "context_selection"
            });
            console.info("Context menu item created");
        });
    }

    init();
}());<|endoftext|>


<commit_before>// Copyright 2017 Google Inc.
//
// 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.

import {ArithmeticGates} from "src/gates/ArithmeticGates.js"
import {AmplitudeDisplayFamily} from "src/gates/AmplitudeDisplay.js"
import {BitCountGates} from "src/gates/BitCountGates.js"
import {BlochSphereDisplay} from "src/gates/BlochSphereDisplay.js"
import {ComparisonGates} from "src/gates/ComparisonGates.js"
import {Controls} from "src/gates/Controls.js"
import {CountingGates} from "src/gates/CountingGates.js"
import {CycleBitsGates} from "src/gates/CycleBitsGates.js"
import {DensityMatrixDisplayFamily} from "src/gates/DensityMatrixDisplay.js"
import {ErrorInjectionGate} from "src/gates/Debug_ErrorInjectionGate.js"
import {ExponentiatingGates} from "src/gates/ExponentiatingGates.js"
import {FourierTransformGates} from "src/gates/FourierTransformGates.js"
import {HalfTurnGates} from "src/gates/HalfTurnGates.js"
import {InputGates} from "src/gates/InputGates.js"
import {InterleaveBitsGates} from "src/gates/InterleaveBitsGates.js"
import {MeasurementGate} from "src/gates/MeasurementGate.js"
import {ModularIncrementGates} from "src/gates/ModularIncrementGates.js"
import {ModularAdditionGates} from "src/gates/ModularAdditionGates.js"
import {ModularMultiplicationGates} from "src/gates/ModularMultiplicationGates.js"
import {ModularMultiplyAccumulateGates} from "src/gates/ModularMultiplyAccumulateGates.js"
import {MultiplicationGates} from "src/gates/MultiplicationGates.js"
import {MultiplyAccumulateGates} from "src/gates/MultiplyAccumulateGates.js"
import {NeGate} from "src/gates/Joke_NeGate.js"
import {ParametrizedRotationGates} from "src/gates/ParametrizedRotationGates.js"
import {PhaseGradientGates} from "src/gates/PhaseGradientGates.js"
import {PivotFlipGates} from "src/gates/PivotFlipGates.js"
import {PostSelectionGates} from "src/gates/PostSelectionGates.js"
import {PoweringGates} from "src/gates/PoweringGates.js"
import {ProbabilityDisplayFamily} from "src/gates/ProbabilityDisplay.js"
import {QuarterTurnGates} from "src/gates/QuarterTurnGates.js"
import {ReverseBitsGateFamily} from "src/gates/ReverseBitsGate.js"
import {SampleDisplayFamily} from "src/gates/SampleDisplay.js"
import {SpacerGate} from "src/gates/SpacerGate.js"
import {SwapGateHalf} from "src/gates/SwapGateHalf.js"
import {UniversalNotGate} from "src/gates/Impossible_UniversalNotGate.js"
import {VariousXGates} from "src/gates/VariousXGates.js"
import {VariousYGates} from "src/gates/VariousYGates.js"
import {VariousZGates} from "src/gates/VariousZGates.js"
import {XorGates} from "src/gates/XorGates.js"
import {ZeroGate} from "src/gates/Joke_ZeroGate.js"
import {MysteryGateMaker} from "src/gates/Joke_MysteryGate.js"

import {seq} from "src/base/Seq.js"

let Gates = {};

/** Gates that have special behavior requiring custom code / logic to handle. */
Gates.Special = {
    Measurement: MeasurementGate,
    SwapHalf: SwapGateHalf
};
/**
 * Gates that display information without affecting the state.
 * (In reality these would require multiple runs of the circuit to do tomography.)
 */
Gates.Displays = {
    AmplitudeDisplayFamily: AmplitudeDisplayFamily,
    ProbabilityDisplayFamily: ProbabilityDisplayFamily,
    SampleDisplayFamily: SampleDisplayFamily,
    DensityMatrixDisplayFamily: DensityMatrixDisplayFamily,
    BlochSphereDisplay: BlochSphereDisplay
};
Gates.Arithmetic = ArithmeticGates;
Gates.BitCountGates = BitCountGates;
Gates.ComparisonGates = ComparisonGates;
Gates.Controls = Controls;
Gates.CountingGates = CountingGates;
Gates.CycleBitsGates = CycleBitsGates;
Gates.Displays.DensityMatrixDisplay = DensityMatrixDisplayFamily.ofSize(1);
Gates.Displays.DensityMatrixDisplay2 = DensityMatrixDisplayFamily.ofSize(2);
Gates.Displays.ChanceDisplay = Gates.Displays.ProbabilityDisplayFamily.ofSize(1);
Gates.ErrorInjection = ErrorInjectionGate;
Gates.Exponentiating = ExponentiatingGates;
Gates.FourierTransformGates = FourierTransformGates;
Gates.HalfTurns = HalfTurnGates;
Gates.InputGates = InputGates;
Gates.InterleaveBitsGates = InterleaveBitsGates;
Gates.ModularIncrementGates = ModularIncrementGates;
Gates.ModularAdditionGates = ModularAdditionGates;
Gates.ModularMultiplicationGates = ModularMultiplicationGates;
Gates.ModularMultiplyAccumulateGates = ModularMultiplyAccumulateGates;
Gates.MultiplicationGates = MultiplicationGates;
Gates.MultiplyAccumulateGates = MultiplyAccumulateGates;
Gates.NeGate = NeGate;
Gates.OtherX = VariousXGates;
Gates.OtherY = VariousYGates;
Gates.OtherZ = VariousZGates;
Gates.ParametrizedRotationGates = ParametrizedRotationGates;
Gates.PhaseGradientGates = PhaseGradientGates;
Gates.PivotFlipGates = PivotFlipGates;
Gates.PostSelectionGates = PostSelectionGates;
Gates.Powering = PoweringGates;
Gates.QuarterTurns = QuarterTurnGates;
Gates.ReverseBitsGateFamily = ReverseBitsGateFamily;
Gates.SpacerGate = SpacerGate;
Gates.UniversalNot = UniversalNotGate;
Gates.XorGates = XorGates;
Gates.ZeroGate = ZeroGate;

/** @type {!Array.<!Gate>} */
Gates.KnownToSerializer = [
    ...Controls.all,
    ...InputGates.all,
    MeasurementGate,
    SwapGateHalf,
    SpacerGate,
    UniversalNotGate,
    ErrorInjectionGate,
    ZeroGate,
    NeGate,

    ...AmplitudeDisplayFamily.all,
    ...ProbabilityDisplayFamily.all,
    ...SampleDisplayFamily.all,
    ...DensityMatrixDisplayFamily.all,
    BlochSphereDisplay,

    ...ArithmeticGates.all,
    ...BitCountGates.all,
    ...ComparisonGates.all,
    ...CountingGates.all,
    ...CycleBitsGates.all,
    ...ExponentiatingGates.all,
    ...FourierTransformGates.all,
    ...HalfTurnGates.all,
    ...InterleaveBitsGates.all,
    ...ModularAdditionGates.all,
    ...ModularIncrementGates.all,
    ...ModularMultiplicationGates.all,
    ...ModularMultiplyAccumulateGates.all,
    ...MultiplicationGates.all,
    ...MultiplyAccumulateGates.all,
    ...QuarterTurnGates.all,
    ...ParametrizedRotationGates.all,
    ...PhaseGradientGates.all,
    ...PivotFlipGates.all,
    ...PostSelectionGates.all,
    ...PoweringGates.all,
    ...ReverseBitsGateFamily.all,
    ...VariousXGates.all,
    ...VariousYGates.all,
    ...VariousZGates.all,
    ...XorGates.all
];

let gatesById = seq(Gates.KnownToSerializer).keyedBy(g => g.serializedId);
/**
 * @param {!String} id
 * @param {!CustomGateSet} customGateSet
 * @returns {undefined|!Gate}
 */
Gates.findKnownGateById = (id, customGateSet) => {
    return gatesById.has(id) ? gatesById.get(id) : customGateSet.findGateWithSerializedId(id);
};

/** @type {!Array<!{hint: !string, gates: !Array<undefined|!Gate>}>} */
Gates.TopToolboxGroups = [
    {
        hint: "Probes",
        gates: [
            MeasurementGate,                  undefined,
            PostSelectionGates.PostSelectOff, PostSelectionGates.PostSelectOn,
            Controls.AntiControl,             Controls.Control
        ]
    },
    {
        hint: "Displays",
        gates: [
            SampleDisplayFamily.ofSize(3),        undefined,
            DensityMatrixDisplayFamily.ofSize(1), BlochSphereDisplay,
            ProbabilityDisplayFamily.ofSize(1),   AmplitudeDisplayFamily.ofSize(2)
        ]
    },
    {
        hint: "Half Turns",
        gates: [
            HalfTurnGates.Z, SwapGateHalf,
            HalfTurnGates.Y, undefined,
            HalfTurnGates.X, HalfTurnGates.H
        ]
    },
    {
        hint: "Quarter Turns",
        gates: [
            QuarterTurnGates.SqrtZForward, QuarterTurnGates.SqrtZBackward,
            QuarterTurnGates.SqrtYForward, QuarterTurnGates.SqrtYBackward,
            QuarterTurnGates.SqrtXForward, QuarterTurnGates.SqrtXBackward
        ]
    },
    {
        hint: "Eighth Turns",
        gates: [
            VariousZGates.Z4, VariousZGates.Z4i,
            VariousYGates.Y4, VariousYGates.Y4i,
            VariousXGates.X4, VariousXGates.X4i,
        ]
    },
    {
        hint: "Sixteenths",
        gates: [
            VariousZGates.Z8,  VariousZGates.Z8i,
            VariousYGates.Y8,  VariousYGates.Y8i,
            VariousXGates.X8,  VariousXGates.X8i,
        ]
    },
    {
        hint: "Spinning",
        gates: [
            PoweringGates.ZForward, PoweringGates.ZBackward,
            PoweringGates.YForward, PoweringGates.YBackward,
            PoweringGates.XForward, PoweringGates.XBackward,
        ]
    },
    {
        hint: "Parametrized",
        gates: [
            ParametrizedRotationGates.ZToA, ParametrizedRotationGates.ZToMinusA,
            ParametrizedRotationGates.YToA, ParametrizedRotationGates.YToMinusA,
            ParametrizedRotationGates.XToA, ParametrizedRotationGates.XToMinusA,
        ]
    },
    {
        hint: 'Silly',
        gates: [
            ZeroGate,   MysteryGateMaker(),
            NeGate,     undefined,
            SpacerGate, undefined
        ]
    }
];

/** @type {!Array<!{hint: !string, gates: !Array<undefined|!Gate>}>} */
Gates.BottomToolboxGroups = [
    {
        hint: "X/Y Probes",
        gates: [
            Controls.XAntiControl, Controls.XControl,
            Controls.YAntiControl, Controls.YControl,
            PostSelectionGates.PostSelectAntiX, PostSelectionGates.PostSelectX,
            PostSelectionGates.PostSelectAntiY, PostSelectionGates.PostSelectY,
        ]
    },
    {
        hint: "Order",
        gates: [
            CountingGates.CountingFamily.ofSize(3),          CountingGates.UncountingFamily.ofSize(3),
            ReverseBitsGateFamily.ofSize(2), undefined,
            CycleBitsGates.CycleBitsFamily.ofSize(3),        CycleBitsGates.ReverseCycleBitsFamily.ofSize(3),
            InterleaveBitsGates.InterleaveBitsGateFamily.ofSize(6),
            InterleaveBitsGates.DeinterleaveBitsGateFamily.ofSize(6),
        ]
    },
    {
        hint: 'Fourier',
        gates: [
            FourierTransformGates.FourierTransformFamily.ofSize(2),
                FourierTransformGates.InverseFourierTransformFamily.ofSize(2),
            undefined, undefined,
            PhaseGradientGates.PhaseGradientFamily.ofSize(2), PhaseGradientGates.PhaseDegradientFamily.ofSize(2),
            undefined, undefined,
        ]
    },
    {
        hint: "Inputs",
        gates: [
            InputGates.InputAFamily.ofSize(2), InputGates.InputRevAFamily.ofSize(2),
            InputGates.InputBFamily.ofSize(2), InputGates.InputRevBFamily.ofSize(2),
            InputGates.InputRFamily.ofSize(2), InputGates.SetR,
            InputGates.SetA, InputGates.SetB,
        ]
    },
    {
        hint: 'Arithmetic',
        gates: [
            ArithmeticGates.IncrementFamily.ofSize(2), ArithmeticGates.DecrementFamily.ofSize(2),
            ArithmeticGates.PlusAFamily.ofSize(2), ArithmeticGates.MinusAFamily.ofSize(2),
            MultiplyAccumulateGates.MultiplyAddInputsFamily.ofSize(2),
                MultiplyAccumulateGates.MultiplySubtractInputsFamily.ofSize(2),
            MultiplicationGates.TimesAFamily.ofSize(2), MultiplicationGates.TimesAInverseFamily.ofSize(2),
        ]
    },
    {
        hint: "Compare",
        gates: [
            ComparisonGates.ALessThanB, ComparisonGates.AGreaterThanB,
            ComparisonGates.ALessThanOrEqualToB, ComparisonGates.AGreaterThanOrEqualToB,
            ComparisonGates.AEqualToB, ComparisonGates.ANotEqualToB,
            undefined, undefined,
        ]
    },
    {
        hint: "Modular",
        gates: [
            ModularIncrementGates.IncrementModRFamily.ofSize(2), ModularIncrementGates.DecrementModRFamily.ofSize(2),
            ModularAdditionGates.PlusAModRFamily.ofSize(2), ModularAdditionGates.MinusAModRFamily.ofSize(2),
            ModularMultiplicationGates.TimesAModRFamily.ofSize(2),
                ModularMultiplicationGates.TimesAModRInverseFamily.ofSize(2),
            ModularMultiplicationGates.TimesBToTheAModRFamily.ofSize(2),
                ModularMultiplicationGates.TimesInverseBToTheAModRFamily.ofSize(2),
        ]
    },
];

export {Gates}
<commit_msg>Drop reversed input gates from toolbox<commit_after>// Copyright 2017 Google Inc.
//
// 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.

import {ArithmeticGates} from "src/gates/ArithmeticGates.js"
import {AmplitudeDisplayFamily} from "src/gates/AmplitudeDisplay.js"
import {BitCountGates} from "src/gates/BitCountGates.js"
import {BlochSphereDisplay} from "src/gates/BlochSphereDisplay.js"
import {ComparisonGates} from "src/gates/ComparisonGates.js"
import {Controls} from "src/gates/Controls.js"
import {CountingGates} from "src/gates/CountingGates.js"
import {CycleBitsGates} from "src/gates/CycleBitsGates.js"
import {DensityMatrixDisplayFamily} from "src/gates/DensityMatrixDisplay.js"
import {ErrorInjectionGate} from "src/gates/Debug_ErrorInjectionGate.js"
import {ExponentiatingGates} from "src/gates/ExponentiatingGates.js"
import {FourierTransformGates} from "src/gates/FourierTransformGates.js"
import {HalfTurnGates} from "src/gates/HalfTurnGates.js"
import {InputGates} from "src/gates/InputGates.js"
import {InterleaveBitsGates} from "src/gates/InterleaveBitsGates.js"
import {MeasurementGate} from "src/gates/MeasurementGate.js"
import {ModularIncrementGates} from "src/gates/ModularIncrementGates.js"
import {ModularAdditionGates} from "src/gates/ModularAdditionGates.js"
import {ModularMultiplicationGates} from "src/gates/ModularMultiplicationGates.js"
import {ModularMultiplyAccumulateGates} from "src/gates/ModularMultiplyAccumulateGates.js"
import {MultiplicationGates} from "src/gates/MultiplicationGates.js"
import {MultiplyAccumulateGates} from "src/gates/MultiplyAccumulateGates.js"
import {NeGate} from "src/gates/Joke_NeGate.js"
import {ParametrizedRotationGates} from "src/gates/ParametrizedRotationGates.js"
import {PhaseGradientGates} from "src/gates/PhaseGradientGates.js"
import {PivotFlipGates} from "src/gates/PivotFlipGates.js"
import {PostSelectionGates} from "src/gates/PostSelectionGates.js"
import {PoweringGates} from "src/gates/PoweringGates.js"
import {ProbabilityDisplayFamily} from "src/gates/ProbabilityDisplay.js"
import {QuarterTurnGates} from "src/gates/QuarterTurnGates.js"
import {ReverseBitsGateFamily} from "src/gates/ReverseBitsGate.js"
import {SampleDisplayFamily} from "src/gates/SampleDisplay.js"
import {SpacerGate} from "src/gates/SpacerGate.js"
import {SwapGateHalf} from "src/gates/SwapGateHalf.js"
import {UniversalNotGate} from "src/gates/Impossible_UniversalNotGate.js"
import {VariousXGates} from "src/gates/VariousXGates.js"
import {VariousYGates} from "src/gates/VariousYGates.js"
import {VariousZGates} from "src/gates/VariousZGates.js"
import {XorGates} from "src/gates/XorGates.js"
import {ZeroGate} from "src/gates/Joke_ZeroGate.js"
import {MysteryGateMaker} from "src/gates/Joke_MysteryGate.js"

import {seq} from "src/base/Seq.js"

let Gates = {};

/** Gates that have special behavior requiring custom code / logic to handle. */
Gates.Special = {
    Measurement: MeasurementGate,
    SwapHalf: SwapGateHalf
};
/**
 * Gates that display information without affecting the state.
 * (In reality these would require multiple runs of the circuit to do tomography.)
 */
Gates.Displays = {
    AmplitudeDisplayFamily: AmplitudeDisplayFamily,
    ProbabilityDisplayFamily: ProbabilityDisplayFamily,
    SampleDisplayFamily: SampleDisplayFamily,
    DensityMatrixDisplayFamily: DensityMatrixDisplayFamily,
    BlochSphereDisplay: BlochSphereDisplay
};
Gates.Arithmetic = ArithmeticGates;
Gates.BitCountGates = BitCountGates;
Gates.ComparisonGates = ComparisonGates;
Gates.Controls = Controls;
Gates.CountingGates = CountingGates;
Gates.CycleBitsGates = CycleBitsGates;
Gates.Displays.DensityMatrixDisplay = DensityMatrixDisplayFamily.ofSize(1);
Gates.Displays.DensityMatrixDisplay2 = DensityMatrixDisplayFamily.ofSize(2);
Gates.Displays.ChanceDisplay = Gates.Displays.ProbabilityDisplayFamily.ofSize(1);
Gates.ErrorInjection = ErrorInjectionGate;
Gates.Exponentiating = ExponentiatingGates;
Gates.FourierTransformGates = FourierTransformGates;
Gates.HalfTurns = HalfTurnGates;
Gates.InputGates = InputGates;
Gates.InterleaveBitsGates = InterleaveBitsGates;
Gates.ModularIncrementGates = ModularIncrementGates;
Gates.ModularAdditionGates = ModularAdditionGates;
Gates.ModularMultiplicationGates = ModularMultiplicationGates;
Gates.ModularMultiplyAccumulateGates = ModularMultiplyAccumulateGates;
Gates.MultiplicationGates = MultiplicationGates;
Gates.MultiplyAccumulateGates = MultiplyAccumulateGates;
Gates.NeGate = NeGate;
Gates.OtherX = VariousXGates;
Gates.OtherY = VariousYGates;
Gates.OtherZ = VariousZGates;
Gates.ParametrizedRotationGates = ParametrizedRotationGates;
Gates.PhaseGradientGates = PhaseGradientGates;
Gates.PivotFlipGates = PivotFlipGates;
Gates.PostSelectionGates = PostSelectionGates;
Gates.Powering = PoweringGates;
Gates.QuarterTurns = QuarterTurnGates;
Gates.ReverseBitsGateFamily = ReverseBitsGateFamily;
Gates.SpacerGate = SpacerGate;
Gates.UniversalNot = UniversalNotGate;
Gates.XorGates = XorGates;
Gates.ZeroGate = ZeroGate;

/** @type {!Array.<!Gate>} */
Gates.KnownToSerializer = [
    ...Controls.all,
    ...InputGates.all,
    MeasurementGate,
    SwapGateHalf,
    SpacerGate,
    UniversalNotGate,
    ErrorInjectionGate,
    ZeroGate,
    NeGate,

    ...AmplitudeDisplayFamily.all,
    ...ProbabilityDisplayFamily.all,
    ...SampleDisplayFamily.all,
    ...DensityMatrixDisplayFamily.all,
    BlochSphereDisplay,

    ...ArithmeticGates.all,
    ...BitCountGates.all,
    ...ComparisonGates.all,
    ...CountingGates.all,
    ...CycleBitsGates.all,
    ...ExponentiatingGates.all,
    ...FourierTransformGates.all,
    ...HalfTurnGates.all,
    ...InterleaveBitsGates.all,
    ...ModularAdditionGates.all,
    ...ModularIncrementGates.all,
    ...ModularMultiplicationGates.all,
    ...ModularMultiplyAccumulateGates.all,
    ...MultiplicationGates.all,
    ...MultiplyAccumulateGates.all,
    ...QuarterTurnGates.all,
    ...ParametrizedRotationGates.all,
    ...PhaseGradientGates.all,
    ...PivotFlipGates.all,
    ...PostSelectionGates.all,
    ...PoweringGates.all,
    ...ReverseBitsGateFamily.all,
    ...VariousXGates.all,
    ...VariousYGates.all,
    ...VariousZGates.all,
    ...XorGates.all
];

let gatesById = seq(Gates.KnownToSerializer).keyedBy(g => g.serializedId);
/**
 * @param {!String} id
 * @param {!CustomGateSet} customGateSet
 * @returns {undefined|!Gate}
 */
Gates.findKnownGateById = (id, customGateSet) => {
    return gatesById.has(id) ? gatesById.get(id) : customGateSet.findGateWithSerializedId(id);
};

/** @type {!Array<!{hint: !string, gates: !Array<undefined|!Gate>}>} */
Gates.TopToolboxGroups = [
    {
        hint: "Probes",
        gates: [
            MeasurementGate,                  undefined,
            PostSelectionGates.PostSelectOff, PostSelectionGates.PostSelectOn,
            Controls.AntiControl,             Controls.Control
        ]
    },
    {
        hint: "Displays",
        gates: [
            SampleDisplayFamily.ofSize(3),        undefined,
            DensityMatrixDisplayFamily.ofSize(1), BlochSphereDisplay,
            ProbabilityDisplayFamily.ofSize(1),   AmplitudeDisplayFamily.ofSize(2)
        ]
    },
    {
        hint: "Half Turns",
        gates: [
            HalfTurnGates.Z, SwapGateHalf,
            HalfTurnGates.Y, undefined,
            HalfTurnGates.X, HalfTurnGates.H
        ]
    },
    {
        hint: "Quarter Turns",
        gates: [
            QuarterTurnGates.SqrtZForward, QuarterTurnGates.SqrtZBackward,
            QuarterTurnGates.SqrtYForward, QuarterTurnGates.SqrtYBackward,
            QuarterTurnGates.SqrtXForward, QuarterTurnGates.SqrtXBackward
        ]
    },
    {
        hint: "Eighth Turns",
        gates: [
            VariousZGates.Z4, VariousZGates.Z4i,
            VariousYGates.Y4, VariousYGates.Y4i,
            VariousXGates.X4, VariousXGates.X4i,
        ]
    },
    {
        hint: "Sixteenths",
        gates: [
            VariousZGates.Z8,  VariousZGates.Z8i,
            VariousYGates.Y8,  VariousYGates.Y8i,
            VariousXGates.X8,  VariousXGates.X8i,
        ]
    },
    {
        hint: "Spinning",
        gates: [
            PoweringGates.ZForward, PoweringGates.ZBackward,
            PoweringGates.YForward, PoweringGates.YBackward,
            PoweringGates.XForward, PoweringGates.XBackward,
        ]
    },
    {
        hint: "Parametrized",
        gates: [
            ParametrizedRotationGates.ZToA, ParametrizedRotationGates.ZToMinusA,
            ParametrizedRotationGates.YToA, ParametrizedRotationGates.YToMinusA,
            ParametrizedRotationGates.XToA, ParametrizedRotationGates.XToMinusA,
        ]
    },
    {
        hint: 'Silly',
        gates: [
            ZeroGate,   MysteryGateMaker(),
            NeGate,     undefined,
            SpacerGate, undefined
        ]
    }
];

/** @type {!Array<!{hint: !string, gates: !Array<undefined|!Gate>}>} */
Gates.BottomToolboxGroups = [
    {
        hint: "X/Y Probes",
        gates: [
            Controls.XAntiControl, Controls.XControl,
            Controls.YAntiControl, Controls.YControl,
            PostSelectionGates.PostSelectAntiX, PostSelectionGates.PostSelectX,
            PostSelectionGates.PostSelectAntiY, PostSelectionGates.PostSelectY,
        ]
    },
    {
        hint: "Order",
        gates: [
            CountingGates.CountingFamily.ofSize(3),          CountingGates.UncountingFamily.ofSize(3),
            ReverseBitsGateFamily.ofSize(2), undefined,
            CycleBitsGates.CycleBitsFamily.ofSize(3),        CycleBitsGates.ReverseCycleBitsFamily.ofSize(3),
            InterleaveBitsGates.InterleaveBitsGateFamily.ofSize(6),
            InterleaveBitsGates.DeinterleaveBitsGateFamily.ofSize(6),
        ]
    },
    {
        hint: 'Fourier',
        gates: [
            FourierTransformGates.FourierTransformFamily.ofSize(2),
                FourierTransformGates.InverseFourierTransformFamily.ofSize(2),
            undefined, undefined,
            PhaseGradientGates.PhaseGradientFamily.ofSize(2), PhaseGradientGates.PhaseDegradientFamily.ofSize(2),
            undefined, undefined,
        ]
    },
    {
        hint: "Inputs",
        gates: [
            InputGates.InputAFamily.ofSize(2), InputGates.SetA,
            InputGates.InputBFamily.ofSize(2), InputGates.SetB,
            InputGates.InputRFamily.ofSize(2), InputGates.SetR,
            undefined, undefined,
        ]
    },
    {
        hint: 'Arithmetic',
        gates: [
            ArithmeticGates.IncrementFamily.ofSize(2), ArithmeticGates.DecrementFamily.ofSize(2),
            ArithmeticGates.PlusAFamily.ofSize(2), ArithmeticGates.MinusAFamily.ofSize(2),
            MultiplyAccumulateGates.MultiplyAddInputsFamily.ofSize(2),
                MultiplyAccumulateGates.MultiplySubtractInputsFamily.ofSize(2),
            MultiplicationGates.TimesAFamily.ofSize(2), MultiplicationGates.TimesAInverseFamily.ofSize(2),
        ]
    },
    {
        hint: "Compare",
        gates: [
            ComparisonGates.ALessThanB, ComparisonGates.AGreaterThanB,
            ComparisonGates.ALessThanOrEqualToB, ComparisonGates.AGreaterThanOrEqualToB,
            ComparisonGates.AEqualToB, ComparisonGates.ANotEqualToB,
            undefined, undefined,
        ]
    },
    {
        hint: "Modular",
        gates: [
            ModularIncrementGates.IncrementModRFamily.ofSize(2), ModularIncrementGates.DecrementModRFamily.ofSize(2),
            ModularAdditionGates.PlusAModRFamily.ofSize(2), ModularAdditionGates.MinusAModRFamily.ofSize(2),
            ModularMultiplicationGates.TimesAModRFamily.ofSize(2),
                ModularMultiplicationGates.TimesAModRInverseFamily.ofSize(2),
            ModularMultiplicationGates.TimesBToTheAModRFamily.ofSize(2),
                ModularMultiplicationGates.TimesInverseBToTheAModRFamily.ofSize(2),
        ]
    },
];

export {Gates}
<|endoftext|>