<commit_before>
var this$1 = this;
var TokenList = function (node) {
  var this$1 = this;

  var
    textify = function (node) { return (node.text = node.data, node); }

  , symbolize = function (symbol) { return symbol.match (/(\w+)/g) [0]; }

  , insert = function (token) { return function (symbol) { return this$1 [symbol] = token; }; }

  , tokenize = function (token) { return token.textContent
        .match (/{(\w+)}/g)
          .map (symbolize)
          .map (insert (token)); }

  this.text
    .call (node)
    .map(textify)
    .map(tokenize)
};

TokenList.prototype.bind = function (context, node) {
    var this$1 = this;

  for (var property in this$1)
    { node = this$1 [property]
    , node.data = node.text }

  for (var property$1 in this$1)
    { node = this$1 [property$1]
    , node.data = node.data
      .replace ('{'+property$1+'}', context [property$1]) }

  return this
};

TokenList.prototype.text = function () {

  console.log ('this', this)
  var
    visit = function (node, filter) {
          if ( filter === void 0 ) filter = /({\w+})/g;

          return filter.exec (node.data) // stored regex is faster https://jsperf.com/regexp-indexof-perf
        && NodeFilter.FILTER_ACCEPT;
    }

  , walker = document.createNodeIterator
      (this, NodeFilter.SHOW_TEXT, visit)
      // by default breaks on template YAY! 🎉

  var
    node
  , nodes = []

  while (node = walker.nextNode ())
    { nodes.push (node) }

  return nodes
};

// INTERESTING! Converting `Template` to a class increases size by ~16 octets

//class Template {

//  constructor ( name = 'snuggsi' ) {
//    return Object.assign (this.factory (...name), { bind: this.bind })
//  }

//  bind (context) {
//    context = Array.isArray (context) ? context : [context]
//  }

//  factory (name) {
//    return (
//      document.querySelector ('template[name='+name+']').cloneNode (true)
//        || document.createElement ('template'))
//  }
//}

var Template = function ( name ) {
  if ( name === void 0 ) name = 'snuggsi';

  this.dependents = []

  return Object.assign
    (document.querySelector ('template[name='+name+']'), { bind: bind } )

  function bind (context) {
    var this$1 = this;

    this.dependents = this.dependents || []

    context = Array.isArray (context) ? context : [context]

    var
      records   = []
    , dependant = undefined

    while
      (dependent = this.dependents.pop ())
        { dependent.remove () }

    for (var i = 0, list = context; i < list.length; i += 1) {
      var item = list[i];

      var
        clone  = this$1.cloneNode (true)
      , tokens = (new TokenList (clone ))

      tokens.bind (item)
      records.push (clone.content)
    }

    records.map
      (function (record) { (ref = this.dependents).push.apply (ref, record.childNodes)
      var ref; }, this)

    (ref = this).after.apply (ref, records)

    return this
    var ref;
  }
}
var EventTarget = function (Node) { return ((function (Node) {
    function anonymous () {
      Node.apply(this, arguments);
    }

    if ( Node ) anonymous.__proto__ = Node;
    anonymous.prototype = Object.create( Node && Node.prototype );
    anonymous.prototype.constructor = anonymous;

    anonymous.prototype.listen = function (event, listener)

    // MDN EventTarget.addEventListener
    // https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
    //
    // WHATWG Living Standard EventTarget.addEventListener
    // https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener
    //
    // DOM Level 2 EventTarget.addEventListener
    // https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget-addEventListener

    {
    if ( listener === void 0 ) listener = 'on' + this$1 [event];
 this.addEventListener (event, listener) };

    return anonymous;
  }(Node))); }
var ParentNode = function (prototype) { return ((function (prototype) {
    function anonymous () {
      prototype.apply(this, arguments);
    }

    if ( prototype ) anonymous.__proto__ = prototype;
    anonymous.prototype = Object.create( prototype && prototype.prototype );
    anonymous.prototype.constructor = anonymous;

    var prototypeAccessors = { tokens: {} };

    anonymous.prototype.selectAll = function (selector)
    { return this.querySelectorAll (selector) };

  anonymous.prototype.select = function (selector)
    // watch out for clobbering `HTMLInputElement.select ()`
    // https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select
    { return this.selectAll (selector) [0] };

  prototypeAccessors.tokens.get = function () {
    return this._tokens =
      this._tokens || new TokenList (this)
  };

    Object.defineProperties( anonymous.prototype, prototypeAccessors );

    return anonymous;
  }(prototype))); }

//function comb
//  // ElementTraversal interface
//  // https://www.w3.org/TR/ElementTraversal/#interface-elementTraversal
//
//(parent) {
//  if (parent.hasChildNodes())
//    for (let node = parent.firstChild; node; node = node.nextSibling)
//      comb (node)
//}
var GlobalEventHandlers = function (prototype) { return ((function (prototype) {
    function anonymous () {
      prototype.apply(this, arguments);
    }

    if ( prototype ) anonymous.__proto__ = prototype;
    anonymous.prototype = Object.create( prototype && prototype.prototype );
    anonymous.prototype.constructor = anonymous;

    anonymous.prototype.register = function (events) {
    var this$1 = this;
    if ( events === void 0 ) events = function (event) { return /^on/.exec (event); };

    var
      nodes = // CSS :not negation https://developer.mozilla.org/en-US/docs/Web/CSS/:not
        // How can we select elements with on* attribute? (i.e. <... onclick=foo onblur=bar>)
        // If we can do this we can only retrieve the elements that have a traditional inline event.
        // This is theoretically more performant as most elements won't need traditional event registration.
        ':not(script):not(template):not(style):not(link)' // remove metadata elements

    , children =
        Array
          .from (this.querySelectorAll (nodes))

    , registered = function (node) { return Array.from (node.attributes)
          .map (function (attr) { return attr.name; })
          .filter (events)
          .length > 0; }

    , handle =
        function (event, handler)  {
            if ( handler === void 0 ) handler = (/{\s*(\w+)\s*}/.exec (event) || []) [1];

            return handler
            && prototype [ handler ].bind (this$1)
            || event
            || null;
    }

    , reflect =
        function (self) { return function (node) { return Array
              .from (node.attributes)
              .map (function (attr) { return attr.name; })
              .filter (events)
              .filter (function (name) { return this$1 [name] !== undefined; })
              .map (reflection (node)); }; }

    , reflection =
        function (node) { return function (event) {
            node [event] = handle (node [event]) }; }

    , mirror = function (handler){ return !!! this$1 [handler]
        && (this$1 [handler] = prototype [handler].bind (this$1)); }

    void [this]
      .concat (children)
      .filter (registered)
      .map (reflect (this))

    Object
      .getOwnPropertyNames (prototype)
      .filter (events)
      .map (mirror)

    return this
  };

    return anonymous;
  }(prototype))); }
var ElementPrototype = window.Element.prototype // see bottom of this file

var Element = function
  //https://gist.github.com/allenwb/53927e46b31564168a1d
  // https://github.com/w3c/webcomponents/issues/587#issuecomment-271031208
  // https://github.com/w3c/webcomponents/issues/587#issuecomment-254017839

 ( tag, CustomElementRegistry )
{
if ( CustomElementRegistry === void 0 ) CustomElementRegistry = window.customElements;
 tag = tag [0]

  return function (HTMLElement) // https://en.wikipedia.org/wiki/Higher-order_function
  { // Should this be a class❓❓❓❓

    var context = this === window ? {} : this

//  try
//    { return new CustomElementRegistry.get (tag) }

//  catch (_)
//    { /* console.warn('Defining Element `'+tag+'` (class {})') */ }

    var HTMLCustomElement = (function (superclass) {
      function HTMLCustomElement () { superclass.call (this)
        this.context = context

        superclass.prototype.initialize && superclass.prototype.initialize.call (this)
      }

      if ( superclass ) HTMLCustomElement.__proto__ = superclass;
      HTMLCustomElement.prototype = Object.create( superclass && superclass.prototype );
      HTMLCustomElement.prototype.constructor = HTMLCustomElement;

      var prototypeAccessors = { context: {},templates: {} };

      prototypeAccessors.context.get = function ()
        { return self };

      prototypeAccessors.context.set = function (value)
        { self = value };

      prototypeAccessors.templates.get = function ()
        { return Array.from (this.selectAll ('template[name]')) };

      HTMLCustomElement.prototype.render = function () {
        // template = super.render ()
        // Where should this insert?
        // What about the meta elements (i.e. script, style, meta)

        this.tokens.bind (this)

        templatize.call (this, this.templates)

        function templatize (templates) {
          var this$1 = this;

          templates.forEach (function (template) {
            (new Template ([template.getAttribute ('name')]))
              .bind (this$1 [template.getAttribute ('name')] || [])
          })
        }

        this.register ()
      };

      // custom element reactions
      HTMLCustomElement.prototype.connectedCallback = function () {
        void ( superclass.prototype.constructor.onconnect
          || superclass.prototype.connectedCallback
          || function noop () {}
        ).call (this)

        this.render ()
      };

      Object.defineProperties( HTMLCustomElement.prototype, prototypeAccessors );

      return HTMLCustomElement;
    }(EventTarget ( ParentNode ( GlobalEventHandlers ( HTMLElement )))));

//  try
//    {
        CustomElementRegistry.define (tag, HTMLCustomElement)
//    }

//  finally
//    {
        return CustomElementRegistry.get (tag)
//    }
  }
}

// Assign `window.Element.prototype` in case of feature checking on `Element`
Element.prototype = ElementPrototype
  // http://2ality.com/2013/09/window.html
  // http://tobyho.com/2013/03/13/window-prop-vs-global-var
  // https://github.com/webcomponents/webcomponentsjs/blob/master/webcomponents-es5-loader.js#L19

<commit_msg>:muscle: distribute snuggsi.js<commit_after>
var this$1 = this;
var TokenList = function (node) {
  var this$1 = this;

  var
    textify = function (node) { return (node.text = node.data, node); }

  , symbolize = function (symbol) { return symbol.match (/{(\w+)}/g) [0]; }

  , insert = function (token) { return function (symbol) { return this$1 [symbol] = token; }; }

  , tokenize = function (token) { return token.textContent
        .match (/{(\w+)}/g)
          .map (symbolize)
          .map (insert (token)); }

  this
    .sift (node)
    .map(textify)
    .map(tokenize)
};

TokenList.prototype.bind = function (context, node) {
    var this$1 = this;

  for (var property in this$1)
    { node = this$1 [property]
    , node.data = node.text }

  for (var property$1 in this$1)
    { node = this$1 [property$1]
    , node.data = node.data
        .replace ('{'+property$1+'}', context [property$1]) }

  return this
};

TokenList.prototype.sift = function (node, nodes) {
    if ( nodes === void 0 ) nodes = [];

  var
    visit = function (node) { return /({\w+})/g.exec (node.data) // stored regex is faster https://jsperf.com/regexp-indexof-perf
        && NodeFilter.FILTER_ACCEPT; }

  , walker =
      document.createNodeIterator
        (node, NodeFilter.SHOW_TEXT, visit)
        // by default breaks on template YAY! 🎉

  while (node = walker.nextNode ())
    { nodes.push (node) }

  return nodes
};

TokenList.prototype.zip = function () {
  var elements = [], len = arguments.length;
  while ( len-- ) elements[ len ] = arguments[ len ];
 var zipper = []

  , lock = function (zipper, row) { return zipper.concat( row); }
  , pair = function (teeth){ return function (tooth, position) { return [tooth, teeth [position]]; }; }

  return elements [1]
    .map (pair (elements [0]))
    .reduce (lock)
};

TokenList.prototype.slice = function (text) { var tokens= []

 , match   = /({\w+})/g // stored regex is faster https://jsperf.com/regexp-indexof-perf
  , replace= function (token) { return (collect (token), '✂'); }
  , collect= function (token) { return tokens.push (token); }
  , sections = text
      .replace (match, replace)
        .split ('✂')

  return zip (tokens, sections)
     .filter (function (element) { return element; })
        .map (function (element) { return new Text (element); })
};

// INTERESTING! Converting `Template` to a class increases size by ~16 octets

//class Template {

//  constructor ( name = 'snuggsi' ) {
//    return Object.assign (this.factory (...name), { bind: this.bind })
//  }

//  bind (context) {
//    context = Array.isArray (context) ? context : [context]
//  }

//  factory (name) {
//    return (
//      document.querySelector ('template[name='+name+']').cloneNode (true)
//        || document.createElement ('template'))
//  }
//}

var Template = function ( name ) {
  if ( name === void 0 ) name = 'snuggsi';

  this.dependents = []

  return Object.assign
    (document.querySelector ('template[name='+name+']'), { bind: bind } )

  function bind (context) {
    var this$1 = this;

    this.dependents = this.dependents || []

    context = Array.isArray (context) ? context : [context]

    var
      records   = []
    , dependant = undefined

    while
      (dependent = this.dependents.pop ())
        { dependent.remove () }

    for (var i = 0, list = context; i < list.length; i += 1) {
      var item = list[i];

      var
        clone  = this$1.cloneNode (true)
      , tokens = (new TokenList (clone ))

      tokens.bind (item)
      records.push (clone.content)
    }

    records.map
      (function (record) { (ref = this.dependents).push.apply (ref, record.childNodes)
      var ref; }, this)

    (ref = this).after.apply (ref, records)

    return this
    var ref;
  }
}
var EventTarget = function (Element) { return ((function (Element) {
    function anonymous () {
      Element.apply(this, arguments);
    }

    if ( Element ) anonymous.__proto__ = Element;
    anonymous.prototype = Object.create( Element && Element.prototype );
    anonymous.prototype.constructor = anonymous;

    anonymous.prototype.listen = function (event, listener)

    // MDN EventTarget.addEventListener
    // https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
    //
    // WHATWG Living Standard EventTarget.addEventListener
    // https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener
    //
    // DOM Level 2 EventTarget.addEventListener
    // https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget-addEventListener

    {
    if ( listener === void 0 ) listener = this$1 [event];
 this.addEventListener (event, listener) };

    return anonymous;
  }(Element))); }
var ParentNode = function (Element) { return ((function (Element) {
    function anonymous () {
      Element.apply(this, arguments);
    }

    if ( Element ) anonymous.__proto__ = Element;
    anonymous.prototype = Object.create( Element && Element.prototype );
    anonymous.prototype.constructor = anonymous;

    var prototypeAccessors = { tokens: {} };

    anonymous.prototype.selectAll = function (selector)
    { return this.querySelectorAll (selector) };

  anonymous.prototype.select = function (selector)
    // watch out for clobbering `HTMLInputElement.select ()`
    // https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select
    { return this.selectAll (selector) [0] };

  prototypeAccessors.tokens.get = function () {
    return this._tokens = // This is Janky
      this._tokens || new TokenList (this)
  };

    Object.defineProperties( anonymous.prototype, prototypeAccessors );

    return anonymous;
  }(Element))); }

//function comb
//  // ElementTraversal interface
//  // https://www.w3.org/TR/ElementTraversal/#interface-elementTraversal
//
//(parent) {
//  if (parent.hasChildNodes())
//    for (let node = parent.firstChild; node; node = node.nextSibling)
//      comb (node)
//}
var GlobalEventHandlers = function (Element) { return ((function (Element) {
    function anonymous () {
      Element.apply(this, arguments);
    }

    if ( Element ) anonymous.__proto__ = Element;
    anonymous.prototype = Object.create( Element && Element.prototype );
    anonymous.prototype.constructor = anonymous;

    anonymous.prototype.register = function (events) {
    var this$1 = this;
    if ( events === void 0 ) events = function (event) { return /^on/.exec (event); };

    var
      nodes = // CSS :not negation https://developer.mozilla.org/en-US/docs/Web/CSS/:not
        // How can we select elements with on* attribute? (i.e. <... onclick=foo onblur=bar>)
        // If we can do this we can only retrieve the elements that have a traditional inline event.
        // This is theoretically more performant as most elements won't need traditional event registration.
        ':not(script):not(template):not(style):not(link)' // remove metadata elements

    , children =
        Array
          .from (this.querySelectorAll (nodes))

    , registered = function (node) { return Array.from (node.attributes)
          .map (function (attr) { return attr.name; })
          .filter (events)
          .length > 0; }

    , handle =
        function (event, handler)  {
            if ( handler === void 0 ) handler = (/{\s*(\w+)\s*}/.exec (event) || []) [1];

            return handler
            && Element [ handler ].bind (this$1)
            || event
            || null;
    }

    , reflect =
        function (self) { return function (node) { return Array
              .from (node.attributes)
              .map (function (attr) { return attr.name; })
              .filter (events)
              .filter (function (name) { return this$1 [name] !== undefined; })
              .map (reflection (node)); }; }

    , reflection =
        function (node) { return function (event) {
            node [event] = handle (node [event]) }; }

    , mirror = function (handler){ return !!! this$1 [handler]
        && (this$1 [handler] = Element [handler].bind (this$1)); }

    void [this]
      .concat (children)
      .filter (registered)
      .map (reflect (this))

    Object
      .getOwnPropertyNames (Element)
      .filter (events)
      .map (mirror)

    return this
  };

    return anonymous;
  }(Element))); }
var ElementPrototype = window.Element.prototype // see bottom of this file

var Element = function
  //https://gist.github.com/allenwb/53927e46b31564168a1d
  // https://github.com/w3c/webcomponents/issues/587#issuecomment-271031208
  // https://github.com/w3c/webcomponents/issues/587#issuecomment-254017839

 ( tag, CustomElementRegistry )
{
if ( CustomElementRegistry === void 0 ) CustomElementRegistry = window.customElements;
 tag = tag [0]

  return function (HTMLElement) // https://en.wikipedia.org/wiki/Higher-order_function
  { // Should this be a class❓❓❓❓

    var context = this === window ? {} : this

//  try
//    { return new CustomElementRegistry.get (tag) }

//  catch (_)
//    { /* console.warn('Defining Element `'+tag+'` (class {})') */ }

    var HTMLCustomElement = (function (superclass) {
      function HTMLCustomElement () { superclass.call (this)
        this.context = context

        superclass.prototype.initialize && superclass.prototype.initialize.call (this)
      }

      if ( superclass ) HTMLCustomElement.__proto__ = superclass;
      HTMLCustomElement.prototype = Object.create( superclass && superclass.prototype );
      HTMLCustomElement.prototype.constructor = HTMLCustomElement;

      var prototypeAccessors = { context: {},templates: {} };

      prototypeAccessors.context.get = function ()
        { return self };

      prototypeAccessors.context.set = function (value)
        { self = value };

      prototypeAccessors.templates.get = function ()
        { return Array.from (this.selectAll ('template[name]')) };

      HTMLCustomElement.prototype.render = function () {
        // template = super.render ()
        // Where should this insert?
        // What about the meta elements (i.e. script, style, meta)

        this.tokens.bind (this)

        templatize.call (this, this.templates)

        function templatize (templates) {
          var this$1 = this;

          templates.forEach (function (template) {
            (new Template ([template.getAttribute ('name')]))
              .bind (this$1 [template.getAttribute ('name')] || [])
          })
        }

        this.register ()
      };

      // custom element reactions
      HTMLCustomElement.prototype.connectedCallback = function () {
        void ( superclass.prototype.constructor.onconnect
          || superclass.prototype.connectedCallback
          || function noop () {}
        ).call (this)

        this.render ()
      };

      Object.defineProperties( HTMLCustomElement.prototype, prototypeAccessors );

      return HTMLCustomElement;
    }(EventTarget ( ParentNode ( GlobalEventHandlers ( HTMLElement )))));

//  try
//    {
        CustomElementRegistry.define (tag, HTMLCustomElement)
//    }

//  finally
//    {
        return CustomElementRegistry.get (tag)
//    }
  }
}

// Assign `window.Element.prototype` in case of feature checking on `Element`
Element.prototype = ElementPrototype
  // http://2ality.com/2013/09/window.html
  // http://tobyho.com/2013/03/13/window-prop-vs-global-var
  // https://github.com/webcomponents/webcomponentsjs/blob/master/webcomponents-es5-loader.js#L19

<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  <commit_msg>Incompatible dimensions found, Cthuhlu Error 666<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "<|endoftext|>


<commit_before>'use strict';
const db = require('../db');

class Base {

  constructor(properties) {
    Object.assign(this, properties);
  }

  static type() {
    return 'Base';
  }

  static fields() {
    return [];
  }

  static all() {

    const type = this.type();

    return new Promise(function all_promise(resolve, reject) {

      db.find({type: type}, function all_db(err, docs) {

        if(err)
          return reject('database error');

        resolve(docs.map(function all_map(doc) {
          doc[type].id = doc._id;
          resolve(doc[type]);
        }));

      });

    });

  }

  static get(...args) {

    const type = this.type(),
          id = args.pop();

    return new Promise(function get_promise(resolve, reject) {

      db.findOne(id_query(type, id), function get_db(err, doc) {

        if(err)
          return reject('database error');

        doc[type].id = doc._id;
        resolve(doc[type]);

      });

    });

  }

  static create(sent) {

    const type = this.type();

    return new Promise(function create_promise(resolve, reject) {

      const obj = {type: type};

      delete sent.id;
      sent.updated_at = (new Date()).toISOString();
      sent.created_at = sent.updated_at;
      obj[type] = sent;

      db.insert(obj, function create_db(err, doc) {

        if(err)
          return reject('creation failed');

        doc[type].id = doc._id;
        resolve(doc[type]);

      });

    });

  }

  static replace(...args) {

    const type = this.type(),
          sent = args.pop(),
          id = args.pop();

    return new Promise(function replace_promise(resolve, reject) {

      const obj = {type: type};

      delete sent.id;
      sent.updated_at = (new Date()).toISOString();
      obj[type] = sent;

      db.update(id_query(type, id), obj, function replace_db(err, doc) {

        if(err)
          return reject('update failed');

        doc[type].id = doc._id;
        resolve(doc[type]);

      });

    });

  }

  static update(...args) {

    const type = this.type(),
          sent = args.pop(),
          id = args.pop();

    return new Promise(function update_promise(resolve, reject) {

      const obj = {type: type};

      delete sent.id;
      sent.updated_at = (new Date()).toISOString();
      obj[type] = set_fields(type, sent);

      db.update(id_query(type, id), obj, function update_db(err, doc) {

        if(err)
          return reject('update failed');

        doc[type].id = doc._id;
        resolve(doc[type]);

      });

    });

  }

}

const id_query = function id_query(type, id_key_name) {

  const query = {type: type},
        id = {}, key = {}, name = {};

  id[`${type}.id`] = id_key_name;
  key[`${type}.key`] = id_key_name;
  name[`${type}.name`] = id_key_name;
  query['$or'] = [id, key, name];

  return query;

};

const set_fields = function set_fields(type, sent) {

  const obj = { '$set': {} };

  Object.keys(sent).forEach(function set_field_for(key) {
    obj['$set'][`${type}.${key}`] = sent[key];
  });

};

exports = module.exports = Base;
<commit_msg>adds validation, getters, & setters to base model class<commit_after>'use strict';

const db = require('../db');

class Base {

  constructor(properties) {

    properties = properties || {};

    this.constructor.validate(properties);
    this.properties = properties;

    this.constructor.fields().forEach(key => {
      Object.defineProperty(this, key, {
        get: () => this.properties[key],
        set: value => { this.properties[key] = value }
      });
    });

  }

  toJSON() {
    return this.toObject();
  }

  toObject() {
    return this.properties;
  }

  toString() {
    return JSON.stringify(this.toObject());
  }

  static type() {
    return 'Base';
  }

  static fields() {
    return [];
  }

  static validate(properties) {

    Object.keys(properties).forEach(key => {

      if(this.fields().indexOf(key) < 0)
        throw `invalid property ${key} for ${this.type()}`;

    });

  }

  static all() {

    const type = this.type();

    return new Promise((resolve, reject) => {

      db.find({type: type}, (err, docs) => {

        if(err)
          return reject(err.message);

        resolve(docs.map(doc => {
          doc[type].id = doc._id;
          return new this(doc[type]);
        }));

      });

    });

  }

  static get(...args) {

    const type = this.type(),
          id = args.pop();

    return new Promise((resolve, reject) => {

      db.findOne(id_query(type, id), (err, doc) => {

        if(err)
          return reject(err.message);

        if(! doc)
          return reject('not found');

        doc[type].id = doc._id;
        resolve(new this(doc[type]));

      });

    });

  }

  static create(sent) {

    const type = this.type();

    return new Promise((resolve, reject) => {

      const obj = {type: type};

      delete sent.id;
      sent.updated_at = (new Date()).toISOString();
      sent.created_at = sent.updated_at;
      obj[type] = sent;

      db.insert(obj, (err, doc) => {

        if(err)
          return reject(err.message);

        doc[type].id = doc._id;
        resolve(new this(doc[type]));

      });

    });

  }

  static replace(...args) {

    const type = this.type(),
          sent = args.pop(),
          id = args.pop();

    return new Promise((resolve, reject) => {

      const obj = {type: type};

      delete sent.id;
      sent.updated_at = (new Date()).toISOString();
      obj[type] = sent;

      db.update(id_query(type, id), obj, {}, (err, replaced, doc) => {

        if(err)
          return reject(err.message);

        if(replaced !== 1)
          return reject('update failed');

        console.log(doc);

        doc[type].id = doc._id;
        resolve(new this(doc[type]));

      });

    });

  }

  static update(...args) {

    const type = this.type(),
          sent = args.pop(),
          id = args.pop();

    return new Promise((resolve, reject) => {

      delete sent.id;
      sent.updated_at = (new Date()).toISOString();

      db.update(id_query(type, id), set_fields(type, sent), {}, (err, replaced, doc) => {

        if(err)
          return reject(err.message);

        if(replaced !== 1)
          return reject('update failed');

        resolve(this.get(sent.id || sent.key || sent.name || id));

      });

    });

  }

}

const id_query = function id_query(type, id_key_name) {

  const query = {type: type},
        id = {}, key = {}, name = {};

  id[`${type}.id`] = id_key_name;
  key[`${type}.key`] = id_key_name;
  name[`${type}.name`] = id_key_name;
  query['$or'] = [id, key, name];

  return query;

};

const set_fields = function set_fields(type, sent) {

  const obj = { '$set': {} };

  Object.keys(sent).forEach(function set_field_for(key) {
    obj['$set'][`${type}.${key}`] = sent[key];
  });

  return obj;

};

exports = module.exports = Base;
<|endoftext|>


<commit_before>module.exports = function (config) {
  if (!process.env.TB_KEY || !process.env.TB_SECRET) {
    console.log('Make sure the TB_KEY and TB_SECRET environment variables are set.')
    process.exit(1)
  }

  var customLaunchers = {
    'TB_Chrome': {
      base: 'TestingBot',
      platform: 'VISTA',
      browserName: 'chrome',
      customData: {
        awesome: true
      }
    },
    'TB_Firefox': {
      base: 'TestingBot',
      platform: 'VISTA',
      browserName: 'firefox'
    },
    'TB_IE': {
      base: 'TestingBot',
      platform: 'VISTA',
      browserName: 'internet explorer'
    }
  }

  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    files: [
      'src/*.js',
      'test/*.js'
    ],
    reporters: ['progress', 'testingbot'],
    port: 4040,
    colors: true,
    logLevel: config.LOG_DEBUG,
    testingbot: {
      testName: 'Karma and TestingBot demo',
      recordScreenshots: false,
      connectOptions: {
        verbose: true,
        'se-port': 4445,
        logfile: 'testingbot_tunnel.log'
      },
      public: 'public'
    },
    // Increase timeout in case connection in CI is slow
    captureTimeout: 120000,
    customLaunchers: customLaunchers,
    browsers: Object.keys(customLaunchers),
    singleRun: true
  })
}<commit_msg>Added concurrency config value in the example code<commit_after>module.exports = function (config) {
  if (!process.env.TB_KEY || !process.env.TB_SECRET) {
    console.log('Make sure the TB_KEY and TB_SECRET environment variables are set.')
    process.exit(1)
  }

  var customLaunchers = {
    'TB_Chrome': {
      base: 'TestingBot',
      platform: 'VISTA',
      browserName: 'chrome',
      customData: {
        awesome: true
      }
    },
    'TB_Firefox': {
      base: 'TestingBot',
      platform: 'VISTA',
      browserName: 'firefox'
    },
    'TB_IE': {
      base: 'TestingBot',
      platform: 'VISTA',
      browserName: 'internet explorer'
    }
  }

  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    files: [
      'src/*.js',
      'test/*.js'
    ],
    reporters: ['progress', 'testingbot'],
    port: 4040,
    colors: true,
    logLevel: config.LOG_DEBUG,
    testingbot: {
      testName: 'Karma and TestingBot demo',
      recordScreenshots: false,
      connectOptions: {
        verbose: true,
        'se-port': 4445,
        logfile: 'testingbot_tunnel.log'
      },
      public: 'public'
    },
    // Increase timeout in case connection in CI is slow
    captureTimeout: 120000,
    customLaunchers: customLaunchers,
    browsers: Object.keys(customLaunchers),
    singleRun: true,
    concurrency: 4 // number of concurrent tests
  })
}
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kan<commit_msg>Quick fix<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanb<|endoftext|>


<commit_before>"use strict";

module.exports = function(config) {
    var fluid = require('infusion');

    var namespace = "gpii.ctr.records";
    if (config.recordType) {
        if (config.recordType.toLowerCase() === "general") {
            namespace = "gpii.ctr.terms";
        }
        else if (config.recordType.toLowerCase() === "alias") {
            namespace = "gpii.ctr.aliases";
        }
        else if (config.recordType.toLowerCase() === "transform") {
            namespace = "gpii.ctr.transforms";
        }
        else if (config.recordType.toLowerCase() === "translation") {
            namespace = "gpii.ctr.translations";
        }
        else if (config.recordType.toLowerCase() === "operator") {
            namespace = "gpii.ctr.operators";
        }
        else {
            console.error("The record lookup API was configured to return an invalid record type '" + config.recordType + "'.  Ignoring this option, all records will be returned.");
        }
    }

    var records = fluid.registerNamespace(namespace);

    var request = require('request');

    records.validateInput = function() {
        if (!records.req.query) {
            throw records.constructError(400,"You must provide the required query parameters to use this interface.");
        }

        if (records.req.query.lastUpdated && new Date(records.req.query.lastUpdated).toString === "Invalid Date") {
            throw records.constructError(400, "Invalid 'lastUpdated' date specified: '" + records.req.query.lastUpdated + "'...");
        }

        var allowedStatuses = ["active","unreviewed","candidate","deleted"];
        if (records.req.query.status) {
            if (records.req.query.status instanceof Array) {
                records.req.query.status.forEach(function(status){
                    if (allowedStatuses.indexOf(status.toLowerCase()) === -1){
                        throw records.constructError(400,"Invalid status '" + status + "' specified...");
                    }

                });
            }
            else if (allowedStatuses.indexOf(records.req.query.status.toLowerCase()) === -1){
                 throw records.constructError(400,"Invalid status '" + records.req.query.status + "' specified...");
            }
        }

        if (records.req.query.offset && isNaN(parseInt(records.req.query.offset))) {
            throw records.constructError(400,"Offset must be a number.");
        }

        if (records.req.query.limit && isNaN(parseInt(records.req.query.limit))) {
            throw records.constructError(400,"Limit must be a number.");
        }

        if (config.recordType) {
            if (records.req.query.recordType) {
                throw records.constructError(400,"The 'recordType' parameter cannot be used with this interface.");
            }
        }
        else if (records.req.query.recordType) {
            var allowedRecordTypes = ["general","alias","transform","translation","operator"];
            if (allowedRecordTypes.indexOf(records.req.query.recordType.toLowerCase()) === -1) {
                throw records.constructError(400, "Invalid record type specified.");
            }
        }
    };

    records.getAndKnitTerms = function(error,response, body) {
        if (error) { return records.res.send(500, JSON.stringify(error)); }
        if (!body.rows) { return records.res.send(500,"No usable result object was returned from couch."); }

        // TODO:  Add support for limiting by status while still preserving paging
        // TODO:  Add support for limiting by lastUpdated date while still preserving paging

        var recordsByTermId = {};
        body.rows.forEach(function(row) {
            var record = row.value;
            var isParent = row.key[1] === 0;
            var termId = row.key[0];

            if (isParent) {
                recordsByTermId[termId] = record;
            }
            else {
                var parentRecord = recordsByTermId[termId];
                var arrayName = "aliases";

                if (record.type.toLowerCase() === "translation") {
                    arrayName = "translations";
                }

                if (!parentRecord) {
                    console.error("No parent record was found for record with uniqueId '" + record.uniqueId + "'...");
                }
                else {
                    if (!parentRecord[arrayName]) { parentRecord[arrayName] = []; }
                    parentRecord[arrayName].push(record);
                }
            }
        });

        var combinedRecords = Object.keys(recordsByTermId).map(function(key) { return recordsByTermId[key]; });
        records.results.total_rows = combinedRecords.length;
        records.results.records = combinedRecords.slice(records.results.offset, records.results.offset + records.results.limit);

        return records.res.send(200, JSON.stringify(records.results));
    };

    records.getRecords = function(error,response,body) {
        if (error) { return records.res.send(500, JSON.stringify(error)); }
        if (!body.rows) { return records.res.send(500,"No usable result object was returned from couch."); }

        records.results.total_rows = body.rows.length;

        // TODO:  Add support for limiting by status while still preserving paging
        // TODO:  Add support for limiting by lastUpdated date while still preserving paging
        // TODO:  Add support for limiting by record type while still preserving paging
        body.rows.forEach(function(record) {
            records.results.records.push(record.value);
        });

        return records.res.send(200, JSON.stringify(records.results));
    };

    records.constructError = function(status, message) {
        var error = new Error(message);
        error.status = status;
        error.ok = false;
        return error;
    };

    var express = require('express');
    return express.Router().get('/', function(req, res){
        // per-request variables need to be defined here, otherwise (for example) the results of the previous search will be returned if the next search has no records
        records.req = req;
        records.res = res;
        res.set('Content-Type', 'application/json');

        records.results = {
            "ok": true,
            "total_rows" : 0,
            "records": [],
            "q": records.req.query.q,
            "offset": records.req.query.offset ? parseInt(records.req.query.offset) : 0,
            "limit": records.req.query.limit ? parseInt(records.req.query.limit) : 100,
            "retrievedAt": new Date()
        };

        // Server config validation
        if (!config || !config['couch.url']) {
            var message = "Your instance is not configured correctly to enable record lookup.  You must have a couch.url variable configured.";
            console.log(message);
            return res.send(500,JSON.stringify({ ok:false, message: message }));
        }

        // User input validation
        try {
            records.validateInput();
        }
        catch(err) {
            return res.send(err.status ? err.status : 500, JSON.stringify(err));
        }

        // If we pass the right query parameters, we can let couch do the paging for us instead of doing it in memory
        // FIXME:  Only if we want to completely screw up limiting by status or recordType
        var queryParams = "";
        if (req.query.offset) {
            queryParams += "?skip=" + req.query.offset;
        }
        if (req.query.limit) {
            queryParams += (queryParams.length > 0 ? "&" : "?") + "limit=" + req.query.limit;
        }

        var urlsByRecordType = {
            "entries":     config['couch.url'] + "/_design/app/_view/entries" + queryParams,
            "alias":       config['couch.url'] + "/_design/app/_view/aliases" + queryParams,
            "transform":   config['couch.url'] + "/_design/app/_view/transforms" + queryParams,
            "translation": config['couch.url'] + "/_design/app/_view/translations" + queryParams,
            "operator":    config['couch.url'] + "/_design/app/_view/operators" + queryParams,
            "general":     config['couch.url'] + "/_design/app/_view/flat"
        };

        var recordType = config.recordType ? config.recordType : "entries";

        var requestConfig = {
            url: urlsByRecordType[recordType],
            json: true
        };

        if (recordType === "general") {
            // For terms, we need to do one mass lookup and put all the records together
            request.get(requestConfig,records.getAndKnitTerms);
        }
        else {
            // For everything else, we can just call the view for the recordType
            request.get(requestConfig,records.getRecords);
        }
    });
};
<commit_msg>Finished initial work on /api/records, including support for all variations, and paging and filtering.<commit_after>"use strict";

module.exports = function(config) {
    var fluid = require('infusion');

    var namespace = "gpii.ctr.records";
    if (config.recordType) {
        if (config.recordType.toLowerCase() === "general") {
            namespace = "gpii.ctr.terms";
        }
        else if (config.recordType.toLowerCase() === "alias") {
            namespace = "gpii.ctr.aliases";
        }
        else if (config.recordType.toLowerCase() === "transform") {
            namespace = "gpii.ctr.transforms";
        }
        else if (config.recordType.toLowerCase() === "translation") {
            namespace = "gpii.ctr.translations";
        }
        else if (config.recordType.toLowerCase() === "operator") {
            namespace = "gpii.ctr.operators";
        }
        else {
            console.error("The record lookup API was configured to return an invalid record type '" + config.recordType + "'.  Ignoring this option, all records will be returned.");
        }
    }

    var records = fluid.registerNamespace(namespace);
    var request = require('request');

    records.parseAndValidateInput = function() {
        if (!records.req.query) {
            throw records.constructError(400,"You must provide the required query parameters to use this interface.");
        }

        if (records.req.query.updated) {
            var parsedDate =  new Date(records.req.query.updated);
            if (parsedDate.toString() === "Invalid Date") {
                throw records.constructError(400, "Invalid 'updated' date specified: '" + records.req.query.updated + "'...");
            }
            else {
                records.filters.updated = parsedDate;
            }
        }

        var allowedStatuses = ["active","unreviewed","candidate","deleted"];
        if (records.req.query.status) {
            var statusesToDisplay = [];
            if (records.req.query.status instanceof Array) {
                records.req.query.status.forEach(function(status){
                    var lowerCaseStatus = status.toLowerCase();
                    if (allowedStatuses.indexOf(lowerCaseStatus) === -1){
                        throw records.constructError(400,"Invalid status '" + lowerCaseStatus + "' specified...");
                    }
                    else {
                        statusesToDisplay.push(lowerCaseStatus);
                    }
                });
            }
            else {
                var lowerCaseStatus = records.req.query.status.toLowerCase();
                if (allowedStatuses.indexOf(lowerCaseStatus) === -1){
                     throw records.constructError(400,"Invalid status '" + lowerCaseStatus + "' specified...");
                }
                else {
                    statusesToDisplay.push(lowerCaseStatus);
                }
            }

            if (statusesToDisplay.length > 0) {
                records.filters.statuses = statusesToDisplay;
            }
        }

        if (records.req.query.offset) {
            var parsedOffset = parseInt(records.req.query.offset);
            if (isNaN(parsedOffset)) {
                throw records.constructError(400,"Offset must be a number.");
            }
            else {
                records.filters.offset = parsedOffset;
            }
        }

        if (records.req.query.limit) {
            var parsedLimit = parseInt(records.req.query.limit);
            if (isNaN(parsedLimit)) {
                throw records.constructError(400,"Limit must be a number.");
            }
            else {
                records.filters.limit = parsedLimit;
            }
        }

        if (config.recordType) {
            if (records.req.query.recordType) {
                throw records.constructError(400,"The 'recordType' parameter cannot be used with this interface.");
            }
        }
        else if (records.req.query.recordType) {
            var allowedRecordTypes = ["general","alias","transform","translation","operator"];
            var recordTypesToDisplay = [];
            if (records.req.query.recordType instanceof Array) {
                records.req.query.recordType.forEach(function(recordType){
                    var lowerCaseRecordType = recordType.toLowerCase();
                    if (allowedRecordTypes.indexOf(lowerCaseRecordType) === -1) {
                        throw records.constructError(400, "Invalid record type specified.");
                    }
                    else {
                        recordTypesToDisplay.push(lowerCaseRecordType);
                    }
                });
            }
            else {
                var lowerCaseRecordType = records.req.query.recordType.toLowerCase();
                if (allowedRecordTypes.indexOf(lowerCaseRecordType) === -1) {
                    throw records.constructError(400, "Invalid record type specified.");
                }
                else {
                    recordTypesToDisplay.push(lowerCaseRecordType);
                }
            }

            if (recordTypesToDisplay.length > 0) {
                records.filters.recordTypes = recordTypesToDisplay;
            }
        }
    };

    records.getAndKnitTerms = function(error,response, body) {
        if (error) { return records.res.send(500, JSON.stringify(error)); }
        if (!body.rows) { return records.res.send(500,"No usable result object was returned from couch."); }

        var recordsByTermId = {};
        var excludedParentIds = [];

        body.rows.forEach(function(row) {
            var record = row.value;
            var isParent = row.key[1] === 0;
            var termId = row.key[0];

            if (isParent) {
                // Exclude records that are too old, the wrong status, or the wrong record type
                if ((records.filters.updated && new Date(record.updated) < records.filters.updated) ||
                    (records.filters.statuses && records.filters.statuses.indexOf(record.status.toLowerCase()) === -1) ||
                    (records.filters.recordTypes && records.filters.recordTypes.indexOf(record.type.toLowerCase()) === -1)) {
                    excludedParentIds.push(termId);
                }
                else {
                    recordsByTermId[termId] = record;
                }
            }
            else {
                if (excludedParentIds.indexOf(termId) !== -1) {
                    var parentRecord = recordsByTermId[termId];
                    var arrayName = "aliases";

                    if (record.type.toLowerCase() === "translation") {
                        arrayName = "translations";
                    }

                    if (!parentRecord) {
                        console.error("No parent record was found for record with uniqueId '" + record.uniqueId + "'...");
                    }
                    else {
                        if (!parentRecord[arrayName]) { parentRecord[arrayName] = []; }
                        parentRecord[arrayName].push(record);
                    }
                }
            }
        });

        var combinedRecords = Object.keys(recordsByTermId).map(function(key) { return recordsByTermId[key]; });
        records.results.total_rows = combinedRecords.length;
        records.results.records = combinedRecords.slice(records.results.offset, records.results.offset + records.results.limit);

        return records.res.send(200, JSON.stringify(records.results));
    };

    records.getRecords = function(error,response,body) {
        if (error) { return records.res.send(500, JSON.stringify(error)); }
        if (!body.rows) { return records.res.send(500,"No usable result object was returned from couch."); }

        var filteredRecords = [];
        body.rows.forEach(function(row) {
            var record = row.value;
            if ((!records.filters.updated || new Date(record.updated) >= records.filters.updated) &&
                (!records.filters.statuses    || records.filters.statuses.indexOf(record.status.toLowerCase()) !== -1) &&
                (!records.filters.recordTypes || records.filters.recordTypes.indexOf(record.type.toLowerCase()) !== -1)) {
                filteredRecords.push(record);
            }
        });

        records.results.records = filteredRecords.slice(records.results.offset, records.results.offset + records.results.limit);
        records.results.total_rows = filteredRecords.length;

        return records.res.send(200, JSON.stringify(records.results));
    };

    records.constructError = function(status, message) {
        var error = new Error(message);
        error.status = status;
        error.ok = false;
        return error;
    };

    var express = require('express');
    return express.Router().get('/', function(req, res){
        // per-request variables need to be defined here, otherwise (for example) the results of the previous search will be returned if the next search has no records
        records.filters = {};
        records.req = req;
        records.res = res;
        res.set('Content-Type', 'application/json');

        records.results = {
            "ok": true,
            "total_rows" : 0,
            "records": [],
            "offset": records.req.query.offset ? parseInt(records.req.query.offset) : 0,
            "limit": records.req.query.limit ? parseInt(records.req.query.limit) : 100,
            "filters": records.filters,
            "retrievedAt": new Date()
        };

        // Server config validation
        if (!config || !config['couch.url']) {
            var message = "Your instance is not configured correctly to enable record lookup.  You must have a couch.url variable configured.";
            console.log(message);
            return res.send(500,JSON.stringify({ ok:false, message: message }));
        }

        // User input validation
        try {
            records.parseAndValidateInput();
        }
        catch(err) {
            return res.send(err.status ? err.status : 500, JSON.stringify(err));
        }

        var urlsByRecordType = {
            "entries":     config['couch.url'] + "/_design/app/_view/entries",
            "alias":       config['couch.url'] + "/_design/app/_view/aliases",
            "transform":   config['couch.url'] + "/_design/app/_view/transforms",
            "translation": config['couch.url'] + "/_design/app/_view/translations",
            "operator":    config['couch.url'] + "/_design/app/_view/operators",
            "general":     config['couch.url'] + "/_design/app/_view/flat"
        };

        var recordType = config.recordType ? config.recordType : "entries";

        var requestConfig = {
            url: urlsByRecordType[recordType],
            json: true
        };

        if (recordType === "general") {
            // For terms, we need to do one mass lookup and put all the records together
            request.get(requestConfig,records.getAndKnitTerms);
        }
        else {
            // For everything else, we can just call the view for the recordType
            request.get(requestConfig,records.getRecords);
        }
    });
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { reduxForm, Field, FieldArray } from 'redux-form';
import round from 'lodash/round';
import {
  TextField,
} from 'redux-form-material-ui';

import styles from './styles.css';
import RaisedButton from 'material-ui/RaisedButton';
// import send from 'utils/send';

// const asyncValidate = (values) => new Promise((resolve, reject) => {
//   // si l'utilisateur est identifié, l'email ne doit pas être testé
//   if (values.id) resolve();
//
//   send({ url: '/api/checkMail', datas: { email: values.email } })
//     .then((res) => {
//       if (res.err) {
//         reject({ email: 'Cet email est déjà utilisé' });
//       }
//       resolve();
//     });
// });

const renderTarifications =
  ({ fields, meta: { error }, tarifications }) => // eslint-disable-line

        <RaisedButton primary label=" + Nouvelle tarification" onTouchTap={() => fields.push()} />

        {fields.map((tarification, index) =>

              <Field
                name={`${tarification}.qteMinRelais`}
                floatingLabelText="Qté min relais"
                component={TextField}
                fullWidth
                disabled={false}
                style={{ lineHeight: '30px', fontSize: 14 }}
              />

              <Field
                name={`${tarification}.qteMinProxiweb`}
                floatingLabelText="Qté min glob."
                component={TextField}
                fullWidth
                disabled={false}
                style={{ lineHeight: '30px', fontSize: 14 }}
              />

              <Field
                name={`${tarification}.prix`}
                floatingLabelText="prix fourn."
                fullWidth
                component={TextField}
                disabled={false}
                style={{ lineHeight: '30px', fontSize: 14 }}
              />

              {tarifications && tarifications[index] && tarifications[index].prix &&
                <TextField
                  disabled
                  floatingLabelText="prix distributeur (indicatif)"
                  fullWidth
                  value={round(tarifications[index].prix * 0.110, 2)}
                />}

              <RaisedButton
                label="supprimer"
                onTouchTap={() => fields.remove(index)}
                backgroundColor="red"
                labelStyle={{ color: 'white' }}
              />

        )}

;

class offreForm extends Component { // eslint-disable-line react/prefer-stateless-function
  static propTypes = {
    handleSubmit: PropTypes.func.isRequired,
    handleToggeState: PropTypes.func.isRequired,
    pending: PropTypes.bool.isRequired,
    pristine: PropTypes.bool.isRequired,
    valeurs: PropTypes.object.isRequired,
  }

  render() {
    const {
      handleSubmit,
      pending,
      pristine,
      handleToggeState,
      valeurs,
    } = this.props;

    // tarifications modifiées pour
    // calcul automatique part distributeur
    let tarifications;
    try {
      tarifications = valeurs.offre.values.tarifications;
    } catch (e) {
      tarifications = null;
    }

    return (
      <form onSubmit={handleSubmit}>

                <Field floatingLabelText="Description" fullWidth name="description" component={TextField} />

                <Field floatingLabelText="poids" name="poids" fullWidth component={TextField} />

            <Field
              floatingLabelText="Référence catalogue fournisseur"
              name="referenceFourn"
              fullWidth
              component={TextField}
            />
            <FieldArray name="tarifications" component={renderTarifications} props={{ tarifications }} />

          <div className={`col-md-6 ${styles.formFooter}`} style={{ minHeight: 52 }}>
            {!pristine && <RaisedButton type="submit" label="Valider" primary fullWidth disabled={pending} />}

          <div className={`col-md-6 ${styles.formFooter}`} style={{ minHeight: 52 }}>
            <RaisedButton
              label="Annuler"
              secondary
              fullWidth
              disabled={pending}
              onClick={handleToggeState}
            />

      </form>
    );
  }
}

const OffreForm = reduxForm({
  form: 'offre',
})(offreForm);

// @TODO passer par des selectors
const mapStateToProps = (state) => ({
  formvals: (state.form.wizard_contrat ? state.form.wizard_contrat.values : null),
});

export default connect(mapStateToProps)(OffreForm);
<commit_msg>préciser label poids<commit_after>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { reduxForm, Field, FieldArray } from 'redux-form';
import round from 'lodash/round';
import {
  TextField,
} from 'redux-form-material-ui';

import styles from './styles.css';
import RaisedButton from 'material-ui/RaisedButton';
// import send from 'utils/send';

// const asyncValidate = (values) => new Promise((resolve, reject) => {
//   // si l'utilisateur est identifié, l'email ne doit pas être testé
//   if (values.id) resolve();
//
//   send({ url: '/api/checkMail', datas: { email: values.email } })
//     .then((res) => {
//       if (res.err) {
//         reject({ email: 'Cet email est déjà utilisé' });
//       }
//       resolve();
//     });
// });

const renderTarifications =
  ({ fields, meta: { error }, tarifications }) => // eslint-disable-line

        <RaisedButton primary label=" + Nouvelle tarification" onTouchTap={() => fields.push()} />

        {fields.map((tarification, index) =>

              <Field
                name={`${tarification}.qteMinRelais`}
                floatingLabelText="Qté min relais"
                component={TextField}
                fullWidth
                disabled={false}
                style={{ lineHeight: '30px', fontSize: 14 }}
              />

              <Field
                name={`${tarification}.qteMinProxiweb`}
                floatingLabelText="Qté min glob."
                component={TextField}
                fullWidth
                disabled={false}
                style={{ lineHeight: '30px', fontSize: 14 }}
              />

              <Field
                name={`${tarification}.prix`}
                floatingLabelText="prix fourn."
                fullWidth
                component={TextField}
                disabled={false}
                style={{ lineHeight: '30px', fontSize: 14 }}
              />

              {tarifications && tarifications[index] && tarifications[index].prix &&
                <TextField
                  disabled
                  floatingLabelText="prix distributeur (indicatif)"
                  fullWidth
                  value={round(tarifications[index].prix * 0.110, 2)}
                />}

              <RaisedButton
                label="supprimer"
                onTouchTap={() => fields.remove(index)}
                backgroundColor="red"
                labelStyle={{ color: 'white' }}
              />

        )}

;

class offreForm extends Component { // eslint-disable-line react/prefer-stateless-function
  static propTypes = {
    handleSubmit: PropTypes.func.isRequired,
    handleToggeState: PropTypes.func.isRequired,
    pending: PropTypes.bool.isRequired,
    pristine: PropTypes.bool.isRequired,
    valeurs: PropTypes.object.isRequired,
  }

  render() {
    const {
      handleSubmit,
      pending,
      pristine,
      handleToggeState,
      valeurs,
    } = this.props;

    // tarifications modifiées pour
    // calcul automatique part distributeur
    let tarifications;
    try {
      tarifications = valeurs.offre.values.tarifications;
    } catch (e) {
      tarifications = null;
    }

    return (
      <form onSubmit={handleSubmit}>

                <Field floatingLabelText="Description" fullWidth name="description" component={TextField} />

                <Field floatingLabelText="poids (mg)" name="poids" fullWidth component={TextField} />

            <Field
              floatingLabelText="Référence catalogue fournisseur"
              name="referenceFourn"
              fullWidth
              component={TextField}
            />
            <FieldArray name="tarifications" component={renderTarifications} props={{ tarifications }} />

          <div className={`col-md-6 ${styles.formFooter}`} style={{ minHeight: 52 }}>
            {!pristine && <RaisedButton type="submit" label="Valider" primary fullWidth disabled={pending} />}

          <div className={`col-md-6 ${styles.formFooter}`} style={{ minHeight: 52 }}>
            <RaisedButton
              label="Annuler"
              secondary
              fullWidth
              disabled={pending}
              onClick={handleToggeState}
            />

      </form>
    );
  }
}

const OffreForm = reduxForm({
  form: 'offre',
})(offreForm);

// @TODO passer par des selectors
const mapStateToProps = (state) => ({
  formvals: (state.form.wizard_contrat ? state.form.wizard_contrat.values : null),
});

export default connect(mapStateToProps)(OffreForm);
<|endoftext|>


<commit_before>var giveMe = require('give-me');
var should = require('should');
var superagent = require('superagent');
var TestServers = require('./../lib/http-test-servers');

describe('when starting http servers', function(){

  it('should http-test-servers library provide an object with the correct object and a kill functionality', function(done){

    var endpoints = {
      route1: '/getData',
      route2: '/getData2'
    };

    var servers = {
      server1: {
        port: 3006
      },
      server2: {
        port: 3007
      }
    };

    var testServers = new TestServers(endpoints, servers);

    testServers.start(function(testServers){

      testServers.should.not.be.empty;
      testServers.endpoints.route1.should.be.eql('/getData');
      testServers.endpoints.route2.should.be.eql('/getData2');
      testServers.servers.server1.port.should.be.eql(3006);
      testServers.servers.server2.port.should.be.eql(3007);

      testServers.kill(done);
    });
  });

  it('should they properly respond when a http request is made to the created routes', function(done){

    var endpoints = {
      route1: '/getData',
      route2: '/getData2'
    };

    var servers = {
      server1: {
        port: 3006
      },
      server2: {
        port: 3007
      }
    };

    var testServers = new TestServers(endpoints, servers);

    testServers.start(function(testServers){

      giveMe.all(superagent.get, [["http://localhost:3006/getData"],["http://localhost:3007/getData2"]], function(responses){

        responses[0][0].statusCode.should.be.eql(200);
        responses[0][0].body.should.be.eql({ message: '/getData'});
        responses[1][0].statusCode.should.be.eql(200);
        responses[1][0].body.should.be.eql({ message: '/getData2'});

        testServers.kill(done);
      });
    });
  });

  it('should they properly respond in case of post routes', function(done){

    var endpoints = {
      route1: {
        route: '/postData',
        method: 'post'
      }
    };

    var servers = {
      server1: {
        port: 3006
      },
      server2: {
        port: 3007
      }
    };

    var testServers = new TestServers(endpoints, servers);

    testServers.start(function(testServers){

      giveMe.all(superagent.post, [["http://localhost:3006/postData"],["http://localhost:3007/postData"]], function(responses){

        responses[0][0].statusCode.should.be.eql(200);
        responses[0][0].body.should.be.eql({ message: '/postData'});
        responses[1][0].statusCode.should.be.eql(200);
        responses[1][0].body.should.be.eql({ message: '/postData'});

        testServers.kill(done);
      });
    });
  });

  it('should they properly respond with a specific response and status code if it is specified', function(done){

    var endpoints = {
      route1: {
        route: '/getData',
        method: 'get',
        response: { isThisATest: true },
        statusCode: 317
      }
    };

    var servers = {
      server1: {
        port: 3006
      }
    };

    var testServers = new TestServers(endpoints, servers);

    testServers.start(function(testServers){

      superagent.get("http://localhost:3006/getData", function(response){

        response.statusCode.should.be.eql(317);
        response.body.should.be.eql({ isThisATest: true });

        testServers.kill(done);
      });
    });
  });
});<commit_msg>added a delete test<commit_after>var giveMe = require('give-me');
var should = require('should');
var superagent = require('superagent');
var TestServers = require('./../lib/http-test-servers');

describe('when starting http servers', function(){

  it('should http-test-servers library provide an object with the correct object and a kill functionality', function(done){

    var endpoints = {
      route1: '/getData',
      route2: '/getData2'
    };

    var servers = {
      server1: {
        port: 3006
      },
      server2: {
        port: 3007
      }
    };

    var testServers = new TestServers(endpoints, servers);

    testServers.start(function(testServers){

      testServers.should.not.be.empty;
      testServers.endpoints.route1.should.be.eql('/getData');
      testServers.endpoints.route2.should.be.eql('/getData2');
      testServers.servers.server1.port.should.be.eql(3006);
      testServers.servers.server2.port.should.be.eql(3007);

      testServers.kill(done);
    });
  });

  it('should they properly respond when a http request is made to the created routes', function(done){

    var endpoints = {
      route1: '/getData',
      route2: '/getData2'
    };

    var servers = {
      server1: {
        port: 3006
      },
      server2: {
        port: 3007
      }
    };

    var testServers = new TestServers(endpoints, servers);

    testServers.start(function(testServers){

      giveMe.all(superagent.get, [["http://localhost:3006/getData"],["http://localhost:3007/getData2"]], function(responses){

        responses[0][0].statusCode.should.be.eql(200);
        responses[0][0].body.should.be.eql({ message: '/getData'});
        responses[1][0].statusCode.should.be.eql(200);
        responses[1][0].body.should.be.eql({ message: '/getData2'});

        testServers.kill(done);
      });
    });
  });

  it('should they properly respond in case of post routes', function(done){

    var endpoints = {
      route1: {
        route: '/postData',
        method: 'post'
      }
    };

    var servers = {
      server1: {
        port: 3006
      },
      server2: {
        port: 3007
      }
    };

    var testServers = new TestServers(endpoints, servers);

    testServers.start(function(testServers){

      giveMe.all(superagent.post, [["http://localhost:3006/postData"],["http://localhost:3007/postData"]], function(responses){

        responses[0][0].statusCode.should.be.eql(200);
        responses[0][0].body.should.be.eql({ message: '/postData'});
        responses[1][0].statusCode.should.be.eql(200);
        responses[1][0].body.should.be.eql({ message: '/postData'});

        testServers.kill(done);
      });
    });
  });

  it('should they properly respond in case of post routes', function(done){

    var endpoints = {
      route1: {
        route: '/deleteData',
        method: 'delete'
      }
    };

    var servers = {
      server1: {
        port: 3006
      }
    };

    var testServers = new TestServers(endpoints, servers);

    testServers.start(function(testServers){

      superagent.del("http://localhost:3006/deleteData", function(response){

        response.statusCode.should.be.eql(200);
        response.body.should.be.eql({ message: '/deleteData'});

        testServers.kill(done);
      });
    });
  });

  it('should they properly respond with a specific response and status code if it is specified', function(done){

    var endpoints = {
      route1: {
        route: '/getData',
        method: 'get',
        response: { isThisATest: true },
        statusCode: 317
      }
    };

    var servers = {
      server1: {
        port: 3006
      }
    };

    var testServers = new TestServers(endpoints, servers);

    testServers.start(function(testServers){

      superagent.get("http://localhost:3006/getData", function(response){

        response.statusCode.should.be.eql(317);
        response.body.should.be.eql({ isThisATest: true });

        testServers.kill(done);
      });
    });
  });
});<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [time in seconds]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (ne<commit_msg>Found an issue with the letter 'a', so I fixed it.<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [time in seconds]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new<|endoftext|>


<commit_before>/*
 *
 *  how to use ...
 *
 *  var forecast = require('./forecast');
 *
 *  forecast.getData("서울특별시", "동대문구", "청량리동", function(err, res){
 *     if(err) console.log(err);
 *     console.log(res);
 *     });
 *
 *  var coord = {my : 127, mx : 61 };
 *  var obj = [{date: '20150828', time: '0000', pop: 10, pty: 0, r06: 0, reh: 78, s06: 0, sky: 2, t3h: 20, tmn: 18, tmx: 29, uuu: 0, vvv: 1, wav: -1, vec: 160, wsd: 2},{...}];
 *
 *  forecast.setCurrentData(obj, coord, function(err, res){});
 *
 * */
var mongoose = require('mongoose');

var bSchema = new mongoose.Schema({
    town: {first: String, second: String, third: String},
    coord: {lon: Number, lat: Number},
    mData: {mCoord:{mx: Number, my: Number},
            data : { current : Array, short : Array}
	   }
});

bSchema.statics = {
    getData : function (first, second, third, cb){
	this.find({"town" : { "third" : third, "second" : second, "first" : first }})
	.exec(cb);
    },
    setCurrentData : function (currentObj, mCoord, cb){
	// 삭제 예정
//	this.find({ "mData.mCoord" : mCoord }, function(err, res){
//	    if(err) console.log(err);
//	    console.log(res.mData);
//	});
//	this.update({ "mData.mCoord" : mCoord },
	this.update({ "mData.mCoord.mx" : mCoord.mx, "mData.mCoord.my" : mCoord.my },
	{$push: { "mData.data.current": { $each : currentObj}}},
	{safe: true, multi : true, upsert: true},
	cb);
    },
    setShortData : function (currentObj, mCoord, cb){
	this.update({ "mData.mCoord.mx" : mCoord.mx, "mData.mCoord.my" : mCoord.my },
	{$push: { "mData.data.short": { $each : currentObj}}},
	{safe: true, multi : true, upsert: true},
	cb);
    }
}

module.exports = mongoose.model('base', bSchema);
<commit_msg>#10 Before and After 16 forecast data save<commit_after>/*
 *
 *  how to use ...
 *
 *  var forecast = require('./forecast');
 *
 *  forecast.getData("서울특별시", "동대문구", "청량리동", function(err, res){
 *     if(err) console.log(err);
 *     console.log(res);
 *     });
 *
 *  var coord = {my : 127, mx : 61 };
 *  var obj = [{date: '20150828', time: '0000', pop: 10, pty: 0, r06: 0, reh: 78, s06: 0, sky: 2, t3h: 20, tmn: 18, tmx: 29, uuu: 0, vvv: 1, wav: -1, vec: 160, wsd: 2},{...}];
 *
 *  forecast.setCurrentData(obj, coord, function(err, res){});
 *
 * */
var mongoose = require('mongoose');

var bSchema = new mongoose.Schema({
    town: {first: String, second: String, third: String},
    coord: {lon: Number, lat: Number},
    mData: {mCoord:{mx: Number, my: Number},
            data : { current : Array, short : Array}
	   }
});

bSchema.statics = {
    getData : function (first, second, third, cb){
	this.find({"town" : { "third" : third, "second" : second, "first" : first }})
	.exec(cb);
    },
    setCurrentData : function (currentObj, mCoord, cb){
	// 삭제 예정
//	this.find({ "mData.mCoord" : mCoord }, function(err, res){
//	    if(err) console.log(err);
//	    console.log(res.mData);
//	});
//	this.update({ "mData.mCoord" : mCoord },
	this.update({ "mData.mCoord.mx" : mCoord.mx, "mData.mCoord.my" : mCoord.my },
	{$push: { "mData.data.current": { $each : currentObj, $slice : 32}}},
	{safe: true, multi : true, upsert: true},
	cb);
    },
    setShortData : function (currentObj, mCoord, cb){
	this.update({ "mData.mCoord.mx" : mCoord.mx, "mData.mCoord.my" : mCoord.my },
	{$push: { "mData.data.short": { $each : currentObj}}},
	{safe: true, multi : true, upsert: true},
	cb);
    }
}

module.exports = mongoose.model('base', bSchema);
<|endoftext|>


<commit_before>var skts_prefService = Components.classes["@mozilla.org/preferences-service;1"]
                                 .getService(Components.interfaces.nsIPrefService)
                                 .getBranch("extensions.skts.");

var skts_prevTabKey = skts_prefService.getCharPref("prevTabKey");
var skts_nextTabKey = skts_prefService.getCharPref("nextTabKey");

/**
 * Returns true if focus is on an element which takes some sort of input. in
 * that case, we do not want to catch key presses.
 */
function skts_inputFocus() {
    var skts_inputFocus = false;
    var skts_element = document.commandDispatcher.focusedElement;

    // check if focused element takes input
    if (skts_element) {
        var skts_localName = skts_element.localName.toLowerCase();
        if (skts_localName === "input"
        ||  skts_localName === "textarea"
        ||  skts_localName === "select"
        ||  skts_localName === "button"
        ||  skts_localName === "isindex") {
            skts_inputFocus = true;
        }
    }

    // check if focused element has designMode="on"
    var skts_window = document.commandDispatcher.focusedWindow;
    if (skts_window) {
        if(skts_window.document.designMode === "on") {
            skts_inputFocus = true;
        }
    }

    return skts_inputFocus;
}

/**
 * Stop an Event from being propagated further. Called when an Event has been
 * handled.
 */
function skts_stopEvent(evt) {
    evt.preventDefault();
    evt.stopPropagation();
}

/**
 * Handles KeyboardEvents.
 */
function skts_switchTab(evt) {

    // if an input element has focus, we want to let the user input text into
    // the element, thus we return before the event is handled.
    if (skts_inputFocus()) {
        return;
    }

    // we only want to handle single key presses. to avoid interfering with
    // other key bindings, we return without handling the event if either of
    // Shift, Ctrl, Alt or Meta is pressed.
    if (evt.shiftKey
    ||  evt.ctrlKey
    ||  evt.altKey
    ||  evt.metaKey) {
        return;
    }

    skts_keyPressed = evt.which

    if (skts_keyPressed === skts_prevTabKey.charCodeAt(0)) {
        gBrowser.mTabContainer.advanceSelectedTab(-1, true);
        skts_stopEvent(evt);
    }
    else if (skts_keyPressed === skts_nextTabKey.charCodeAt(0)) {
        gBrowser.mTabContainer.advanceSelectedTab(1, true);
        skts_stopEvent(evt);
    }
}

window.addEventListener("keypress", skts_switchTab, false);
<commit_msg>Refactored focus checking slightly.<commit_after>var skts_prefService = Components.classes["@mozilla.org/preferences-service;1"]
                                 .getService(Components.interfaces.nsIPrefService)
                                 .getBranch("extensions.skts.");

var skts_prevTabKey = skts_prefService.getCharPref("prevTabKey");
var skts_nextTabKey = skts_prefService.getCharPref("nextTabKey");

/**
 * Returns true if focus is on an element which takes some sort of input. in
 * that case, we do not want to catch key presses.
 */
function skts_inputFocus() {
    var skts_element = document.commandDispatcher.focusedElement;

    // check if focused element takes input
    if (skts_element) {
        var skts_localName = skts_element.localName.toLowerCase();
        if (skts_localName === "input"
        ||  skts_localName === "textarea"
        ||  skts_localName === "select"
        ||  skts_localName === "button"
        ||  skts_localName === "isindex") {
            return true;
        }
    }

    // check if focused element has designMode="on"
    var skts_window = document.commandDispatcher.focusedWindow;
    if (skts_window) {
        if(skts_window.document.designMode === "on") {
            return true;
        }
    }

    // if we got this far, we should be able to catch key presses without
    // messing up something else; return false
    return false;
}

/**
 * Stop an Event from being propagated further. Called when an Event has been
 * handled.
 */
function skts_stopEvent(evt) {
    evt.preventDefault();
    evt.stopPropagation();
}

/**
 * Handles KeyboardEvents.
 */
function skts_switchTab(evt) {

    // if an input element has focus, we want to let the user input text into
    // the element, thus we return before the event is handled.
    if (skts_inputFocus()) {
        return;
    }

    // we only want to handle single key presses. to avoid interfering with
    // other key bindings, we return without handling the event if either of
    // Shift, Ctrl, Alt or Meta is pressed.
    if (evt.shiftKey
    ||  evt.ctrlKey
    ||  evt.altKey
    ||  evt.metaKey) {
        return;
    }

    skts_keyPressed = evt.which

    if (skts_keyPressed === skts_prevTabKey.charCodeAt(0)) {
        gBrowser.mTabContainer.advanceSelectedTab(-1, true);
        skts_stopEvent(evt);
    }
    else if (skts_keyPressed === skts_nextTabKey.charCodeAt(0)) {
        gBrowser.mTabContainer.advanceSelectedTab(1, true);
        skts_stopEvent(evt);
    }
}

window.addEventListener("keypress", skts_switchTab, false);
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick <commit_msg>Well that seemed pretty easy<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick f<|endoftext|>


<commit_before>var ObjectID = require('mongodb').ObjectID;
var DBRef = require('mongodb').DBRef;
var EventProxy = require('eventproxy');
var EventEmitter = require('events').EventEmitter;
var us = require('underscore');
var fs = require('fs');
var path = require('path');

var db = require('./db');
var ERR = require('../errorcode');
var U = require('../util');
var config = require('../config');

exports.create = function(params, callback){

    var doc = {
        path: params.path,
        md5: params.md5,
        size: Number(params.size),
        type: Number(params.type) || 0,
        mimes: params.mimes,
        ref: 0,
        createTime: Date.now(),
        updateTime: Date.now()
    }

    db.resource.insert(doc, function(err, result){
        callback(err, doc);
    });
}

exports.delete = function(resId, callback){

    db.resource.findAndRemove({ _id: new ObjectID(resId)}, [], callback);
}

exports.getResource = function(resId, callback){

    db.resource.findOne({ _id: ObjectID(resId)}, callback);
}

exports.updateRef = function(resId, value, callback){

    db.resource.findAndModify({ _id: ObjectID(resId) }, [],
            { $inc: { ref: value } }, { 'new': true }, function(err, doc){

        if(doc && doc.ref <= 0){ // 引用为0了, 删除文件
            console.log('>>>resource ref=0, delete it: ' + doc._id);
            db.resource.findAndRemove({ _id: doc._id }, [], callback);
            // 还要删除具体文件
            fs.unlink(path.join(config.FILE_SAVE_ROOT, config.FILE_SAVE_DIR, doc.path), function(err){
                if(err){
                    console.error('>>>delete file: ', err);
                }
            });
        }else{
            callback(err, doc);
        }

    });
}

<commit_msg>bugfix<commit_after>var ObjectID = require('mongodb').ObjectID;
var DBRef = require('mongodb').DBRef;
var EventProxy = require('eventproxy');
var EventEmitter = require('events').EventEmitter;
var us = require('underscore');
var fs = require('fs');
var path = require('path');

var db = require('./db');
var ERR = require('../errorcode');
var U = require('../util');
var config = require('../config');

exports.create = function(params, callback){

    var doc = {
        path: params.path,
        md5: params.md5,
        size: Number(params.size),
        type: Number(params.type) || 0,
        mimes: params.mimes,
        ref: 0,
        createTime: Date.now(),
        updateTime: Date.now()
    }

    db.resource.insert(doc, function(err, result){
        callback(err, doc);
    });
}

exports.delete = function(resId, callback){

    db.resource.findAndRemove({ _id: new ObjectID(resId)}, [], callback);
}

exports.getResource = function(resId, callback){

    db.resource.findOne({ _id: ObjectID(resId)}, callback);
}

exports.updateRef = function(resId, value, callback){

    db.resource.findAndModify({ _id: ObjectID(resId) }, [],
            { $inc: { ref: value } }, { 'new': true }, function(err, doc){

        if(doc && doc.ref <= 0){ // 引用为0了, 删除文件
            console.log('>>>resource ref=0, delete it: ' + doc._id);
            // 还要删除具体文件
            fs.unlink(path.join(config.FILE_SAVE_ROOT, config.FILE_SAVE_DIR, doc.path), function(err){
                if(err){
                    console.error('>>>delete file: ', err);
                    callback(err, null);
                }else{
                    db.resource.findAndRemove({ _id: doc._id }, [], callback);
                }
            });
        }else{
            callback(err, doc);
        }

    });
}

<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD <commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD =<|endoftext|>