<commit_before>// deps: global Ember, global DS, global Firebase
//

DS.Firebase = {};

DS.Firebase.Serializer = DS.JSONSerializer.extend({

  // thanks @rpflorence's localStorage adapter
  extract: function(loader, json, type, record) {
    this._super(loader, this.rootJSON(json, type), type, record);
  },

  extractMany: function(loader, json, type, records) {
    this._super(loader, this.rootJSON(json, type, 'pluralize'), type, records);
  },

  rootJSON: function(json, type, pluralize) {
    var root = this.rootForType(type);
    if (pluralize == 'pluralize') { root = this.pluralize(root); }
    var rootedJSON = {};
    rootedJSON[root] = json;
    return rootedJSON;
  },

  extractHasMany: function(parent, data, key) {
    var items = data[key];
    var ids = [];
    for (var key in items) {
      ids.push(key);
    }
    return ids;
  },

  extractEmbeddedHasMany: function(loader, relationship, array, parent, prematerialized) {
    var objs = [];

    // find belongsTo key that matches the relationship
    var match;
    Ember.get(relationship.type, "relationshipsByName").forEach(function(name, relation) {
      if (relation.kind == "belongsTo" && relation.type == relationship.parentType)
        match = name;
    });

    // turn {id: resource} -> [resource] with id property
    for (var key in array) {
     var obj = Ember.copy(array[key]);
     obj.id = key;
     obj[match] = parent.id;
     objs.push(obj);
    };
    this._super(loader, relationship, objs, parent, prematerialized);
  },

  // slightly modified from json serializer
  addHasMany: function(hash, record, key, relationship) {
    var type = record.constructor;
    var name = relationship.key;
    var manyArray, embeddedType;

    // Get the DS.ManyArray for the relationship off the record
    manyArray = record.get(name);

    embeddedType = this.embeddedType(type, name);

    // if not embedded, just add array of ids
    if (embeddedType !== 'always') {
      record.getRef().child(key).once("value", function(snapshot) {
        var ids = [];
        snapshot.forEach(function (childSnap) {
          ids.push(childSnap.name());
        });

        manyArray.forEach(function (childRecord) {
          childRecord.getRef(record.get("id"));     // hacky - forces id creation
          if (!ids.contains(childRecord.get("id")))
            record.getRef().child(key).child(childRecord.get("id")).set(true);
        });
      });

      return;
    }

    // Build up the array of serialized records
    var serializedHasMany = {};
    manyArray.forEach(function (childRecord) {
      childRecord.getRef(record.get("id"));     // hacky - forces id creation
      serializedHasMany[childRecord.get("id")] = childRecord.serialize();
    }, this);

    // Set the appropriate property of the serialized JSON to the
    // array of serialized embedded records
    hash[key] = serializedHasMany;
  },
});

DS.Firebase.Adapter = DS.Adapter.extend({
  serializer: DS.Firebase.Serializer.create(),

  localLock: false,

  fb: undefined,

  init: function() {
    if (!this.dbName && !this.url) {
      throw new Error("You must specify a dbName representing the subdomain of your Firebase.");
    }

    if (!this.url) this.url = "https://" + this.dbName + ".firebaseio.com";
    this.fb = new Firebase(this.url);

    this._super();
  },

  createRecords: function(store, type, records) {
    records.forEach(function(record) {
      var ref = record.getRef();
      var data = record.serialize();

      // goofy. causes child_added callback to ignore local additions,
      // preventing duplicate items
      this.localLock = true;
      ref.update(data);
      this.localLock = false;
    }.bind(this));
    store.didSaveRecords(records);
  },

  updateRecords: function(store, type, records) {
    records.forEach(function(record) {
      var ref = record.getRef();
      var data = record.serialize();

      ref.update(data);
    }.bind(this));
    store.didSaveRecords(records);
  },

  deleteRecords: function(store, type, records) {
    records.forEach(function(record) {
      var ref = record.getRef();
      ref.remove();
    });
    store.didSaveRecords(records);
  },

  find: function(store, type, id) {
    var ref = this._getRefForType(type).child(id);
    ref.once("value", function(snapshot) {
      // TODO: ew, silent failure.
      var data = Ember.copy(snapshot.val()) || {};
      data.id = id;

      this.didFindRecord(store, type, data, id);
    }.bind(this));
  },

  findAll: function(store, type) {
    var ref = this._getRefForType(type);

    ref.once("value", function(snapshot) {
      var results = [];
      snapshot.forEach(function(child) {
        var data = child.val();
        data.id = child.name();
        results.push(Ember.copy(data));
      }.bind(this));

      this.didFindAll(store, type, results);

      ref.on("child_added", function(child) {
        if (!this.localLock) {
          var data = child.val()
          data.id = child.name();
          this.didFindMany(store, type, [data]);
        }
      }.bind(this));

    }.bind(this));
  },

  // some day this might do some sort of deeper find
  _getRefForType: function(type) {
    var name = this.serializer.pluralize(this.serializer.rootForType(type));

    return this.fb.child(name);
  }

});

DS.Firebase.LiveModel = DS.Model.extend({
  getRef: function(collection) {
    var adapter = this.store.adapter;
    var serializer = adapter.serializer;

    var name = serializer.pluralize(serializer.rootForType(this.constructor));

    // find belongsTo assocations
    var key;
    Ember.get(this.constructor, 'relationshipsByName')
      .forEach(function(rkey, relation) {
        if (relation.kind == "belongsTo" && relation.parentType == this.constructor) {
          if (serializer.embeddedType(relation.type, name))
            key = rkey;
        }
      }.bind(this));

    var parentRef;
    if (key) {
      if (this.get(key)) {
        parentRef = this.get(key).getRef();
      }
      else {
        // *probably* means will be deleted
        // watch out for anything bad that could trigger this.
        return this.get("_ref");
      }
    }
    else {
      parentRef = adapter.fb;
    }

    var ref;
    if (!this.get("id")) {
      ref = parentRef.child(name).push(); // generates new id
      this.set("id", ref.name());
    }
    else {
      ref = parentRef.child(name).child(this.get("id"));
    }

    this.set("_ref", ref);
    return ref;
  },

  init: function() {
    this._super();

    this.on("didLoad", this._initLiveBindings.bind(this));
    this.on("didCreate", this._initLiveBindings.bind(this));
  },

  _initLiveBindings: function() {
    if (!this.get("_liveBindingsWereEnabled")) {    // sanity check
      this.set("_liveBindingsWereEnabled", true);
      var ref = this.getRef();

      // get all possible attributes that aren't relationships for check
      var attrs = Ember.get(this.constructor, "attributes");

      // child object (or array of ids of child objects)
      ref.on("child_added", function(prop) {
        if (attrs.get(prop.name()) && (this.get(prop.name()) === null)) {
          console.log("child added " + prop.name());
          this.set(prop.name(), prop.val());
        }
      }.bind(this));

      ref.on("child_changed", function(prop) {
        if (attrs.get(prop.name()) && prop.val() !== this.get(prop.name())) {
          console.log("child changed " + prop.name());
          this.set(prop.name(), prop.val());
        }

      }.bind(this));

      this.get("constructor.relationshipsByName").forEach(function(name, relationship) {
        if (relationship.kind == "hasMany" && relationship.options.live === true) {
          console.log("adding live relation for " + relationship.key);
          var embedded = this.store.adapter.serializer.mappingOption(this.constructor, relationship.key, "embedded");

          // embedded relationship
          if (embedded == "always") {
            ref.child(relationship.key).on("child_added", function(snapshot) {
              var id = snapshot.name();

              // todo: likely very inefficient. may be a better way to get
              // list of ids - see how it's done when loading records
              var ids = this.get(relationship.key).map(function(item) {return item.get("id")});
              if (ids.contains(id)) { return; }

              var data = snapshot.val();
              var id = snapshot.name();
              data.id = id

              // find belongsTo key that matches the relationship
              var match;
              Ember.get(relationship.type, "relationshipsByName").forEach(function(name, relation) {
                if (relation.kind == "belongsTo" && relation.type == relationship.parentType)
                  match = name;
              });

              if(match) data[match] = this;

              // TODO: this kind of sucks. it's a workaround for didFindRecord
              // not playing nice with associations, for whatever reason.
              var rec = relationship.type.createRecord(data);

              // keeps the record from being attempted to be saved back to
              // the server
              rec.get('stateManager').send('willCommit');
              rec.get('stateManager').send('didCommit');

              rec._initLiveBindings();
            }.bind(this));

            ref.child(relationship.key).on("child_removed", function(snapshot) {
              var id = snapshot.name();

              var rec = this.get(relationship.key).find(function(item) {return item.get("id") == id});

              if (!rec) return;

              rec.deleteRecord();

              // fake sync
              rec.get('stateManager').send('willCommit');
              rec.get('stateManager').send('didCommit');
            }.bind(this));
          }

          else {
            ref.child(relationship.key).on("child_added", function(snapshot) {
              var id = snapshot.name();

              //var ids = this.get(relationship.key).map(function(item) {return item.get("id")});
              //if (ids.contains(id)) { return; }
              var ids = this._data.hasMany[relationship.key];
              if (ids.contains(id)) { return; }

              var mdl = relationship.type.find(id);

              this.get(relationship.key).pushObject(mdl);
            }.bind(this));

            ref.child(relationship.key).on("child_removed", function(snapshot) {
              var id = snapshot.name();

              var rec = this.get(relationship.key).find(function(item) {return item.get("id") == id;});
              if (!rec) return;

              rec.deleteRecord();
              rec.get('stateManager').send('willCommit');
              rec.get('stateManager').send('didCommit');
            }.bind(this));
          }
        }
      }.bind(this))
    }
  },

});
<commit_msg>Added resourceName, fixed relation child_added<commit_after>// deps: global Ember, global DS, global Firebase
//

DS.Firebase = {};

DS.Firebase.Serializer = DS.JSONSerializer.extend({

  // thanks @rpflorence's localStorage adapter
  extract: function(loader, json, type, record) {
    this._super(loader, this.rootJSON(json, type), type, record);
  },

  extractMany: function(loader, json, type, records) {
    this._super(loader, this.rootJSON(json, type, 'pluralize'), type, records);
  },

  rootJSON: function(json, type, pluralize) {
    var root = this.rootForType(type);
    if (pluralize == 'pluralize') { root = this.pluralize(root); }
    var rootedJSON = {};
    rootedJSON[root] = json;
    return rootedJSON;
  },

  rootForType: function(type) {
    var map = this.mappings.get(type)
    if (map && map.resourceName) return map.resourceName;

    var typeString = type.toString();

    Ember.assert("Your model must not be anonymous. It was " + type, typeString.charAt(0) !== '(');

    // use the last part of the name as the URL
    var parts = typeString.split(".");
    var name = parts[parts.length - 1];
    return name.replace(/([A-Z])/g, '_$1').toLowerCase().slice(1);
  },

  extractHasMany: function(parent, data, key) {
    var items = data[key];
    var ids = [];
    for (var key in items) {
      ids.push(key);
    }
    return ids;
  },

  extractEmbeddedHasMany: function(loader, relationship, array, parent, prematerialized) {
    var objs = [];

    // find belongsTo key that matches the relationship
    var match;
    Ember.get(relationship.type, "relationshipsByName").forEach(function(name, relation) {
      if (relation.kind == "belongsTo" && relation.type == relationship.parentType)
        match = name;
    });

    // turn {id: resource} -> [resource] with id property
    for (var key in array) {
     var obj = Ember.copy(array[key]);
     obj.id = key;
     obj[match] = parent.id;
     objs.push(obj);
    };
    this._super(loader, relationship, objs, parent, prematerialized);
  },

  // slightly modified from json serializer
  addHasMany: function(hash, record, key, relationship) {
    var type = record.constructor;
    var name = relationship.key;
    var manyArray, embeddedType;

    // Get the DS.ManyArray for the relationship off the record
    manyArray = record.get(name);

    embeddedType = this.embeddedType(type, name);

    // if not embedded, just add array of ids
    if (embeddedType !== 'always') {
      record.getRef().child(key).once("value", function(snapshot) {
        var ids = [];
        snapshot.forEach(function (childSnap) {
          ids.push(childSnap.name());
        });

        manyArray.forEach(function (childRecord) {
          childRecord.getRef(record.get("id"));     // hacky - forces id creation
          if (!ids.contains(childRecord.get("id")))
            record.getRef().child(key).child(childRecord.get("id")).set(true);
        });
      });

      return;
    }

    // Build up the array of serialized records
    var serializedHasMany = {};
    manyArray.forEach(function (childRecord) {
      childRecord.getRef(record.get("id"));     // hacky - forces id creation
      serializedHasMany[childRecord.get("id")] = childRecord.serialize();
    }, this);

    // Set the appropriate property of the serialized JSON to the
    // array of serialized embedded records
    hash[key] = serializedHasMany;
  },
});

DS.Firebase.Adapter = DS.Adapter.extend({
  serializer: DS.Firebase.Serializer.create(),

  localLock: false,

  fb: undefined,

  init: function() {
    if (!this.dbName && !this.url) {
      throw new Error("You must specify a dbName representing the subdomain of your Firebase.");
    }

    if (!this.url) this.url = "https://" + this.dbName + ".firebaseio.com";
    this.fb = new Firebase(this.url);

    this._super();
  },

  createRecords: function(store, type, records) {
    records.forEach(function(record) {
      var ref = record.getRef();
      var data = record.serialize();

      // goofy. causes child_added callback to ignore local additions,
      // preventing duplicate items
      this.localLock = true;
      ref.update(data);
      this.localLock = false;
    }.bind(this));
    store.didSaveRecords(records);
  },

  updateRecords: function(store, type, records) {
    records.forEach(function(record) {
      var ref = record.getRef();
      var data = record.serialize();

      ref.update(data);
    }.bind(this));
    store.didSaveRecords(records);
  },

  deleteRecords: function(store, type, records) {
    records.forEach(function(record) {
      var ref = record.getRef();
      ref.remove();
    });
    store.didSaveRecords(records);
  },

  find: function(store, type, id) {
    var ref = this._getRefForType(type).child(id);
    ref.once("value", function(snapshot) {
      // TODO: ew, silent failure.
      var data = Ember.copy(snapshot.val()) || {};
      data.id = id;

      this.didFindRecord(store, type, data, id);
    }.bind(this));
  },

  findAll: function(store, type) {
    var ref = this._getRefForType(type);

    ref.once("value", function(snapshot) {
      var results = [];
      snapshot.forEach(function(child) {
        var data = child.val();
        data.id = child.name();
        results.push(Ember.copy(data));
      }.bind(this));

      this.didFindAll(store, type, results);

      ref.on("child_added", function(child) {
        if (!this.localLock) {
          var data = child.val()
          data.id = child.name();
          this.didFindMany(store, type, [data]);
        }
      }.bind(this));

    }.bind(this));
  },

  // some day this might do some sort of deeper find
  _getRefForType: function(type) {
    var name = this.serializer.pluralize(this.serializer.rootForType(type));

    return this.fb.child(name);
  }

});

DS.Firebase.LiveModel = DS.Model.extend({
  getRef: function(collection) {
    var adapter = this.store.adapter;
    var serializer = adapter.serializer;

    var name = serializer.pluralize(serializer.rootForType(this.constructor));

    // find belongsTo assocations
    var key;
    Ember.get(this.constructor, 'relationshipsByName')
      .forEach(function(rkey, relation) {
        if (relation.kind == "belongsTo" && relation.parentType == this.constructor) {
          if (serializer.embeddedType(relation.type, name))
            key = rkey;
        }
      }.bind(this));

    var parentRef;
    if (key) {
      if (this.get(key)) {
        parentRef = this.get(key).getRef();
      }
      else {
        // *probably* means will be deleted
        // watch out for anything bad that could trigger this.
        return this.get("_ref");
      }
    }
    else {
      parentRef = adapter.fb;
    }

    var ref;
    if (!this.get("id")) {
      ref = parentRef.child(name).push(); // generates new id
      this.set("id", ref.name());
    }
    else {
      ref = parentRef.child(name).child(this.get("id"));
    }

    this.set("_ref", ref);
    return ref;
  },

  init: function() {
    this._super();

    this.on("didLoad", this._initLiveBindings.bind(this));
    this.on("didCreate", this._initLiveBindings.bind(this));
  },

  _initLiveBindings: function() {
    if (!this.get("_liveBindingsWereEnabled")) {    // sanity check
      this.set("_liveBindingsWereEnabled", true);
      var ref = this.getRef();

      // get all possible attributes that aren't relationships for check
      var attrs = Ember.get(this.constructor, "attributes");

      // child object (or array of ids of child objects)
      ref.on("child_added", function(prop) {
        if (attrs.get(prop.name()) && (this.get(prop.name()) === null)) {
          console.log("child added " + prop.name());
          this.set(prop.name(), prop.val());
        }
      }.bind(this));

      ref.on("child_changed", function(prop) {
        if (attrs.get(prop.name()) && prop.val() !== this.get(prop.name())) {
          console.log("child changed " + prop.name());
          this.set(prop.name(), prop.val());
        }

      }.bind(this));

      this.get("constructor.relationshipsByName").forEach(function(name, relationship) {
        if (relationship.kind == "hasMany" && relationship.options.live === true) {
          console.log("adding live relation for " + relationship.key);
          var embedded = this.store.adapter.serializer.mappingOption(this.constructor, relationship.key, "embedded");

          // embedded relationship
          if (embedded == "always") {
            ref.child(relationship.key).on("child_added", function(snapshot) {
              var id = snapshot.name();

              // todo: likely very inefficient. may be a better way to get
              // list of ids - see how it's done when loading records
              var ids = this.get(relationship.key).map(function(item) {return item.get("id")});
              if (ids.contains(id)) { return; }

              var data = snapshot.val();
              var id = snapshot.name();
              data.id = id

              // find belongsTo key that matches the relationship
              var match;
              Ember.get(relationship.type, "relationshipsByName").forEach(function(name, relation) {
                if (relation.kind == "belongsTo" && relation.type == relationship.parentType)
                  match = name;
              });

              if(match) data[match] = this;

              // TODO: this kind of sucks. it's a workaround for didFindRecord
              // not playing nice with associations, for whatever reason.
              var rec = relationship.type.createRecord(data);

              // keeps the record from being attempted to be saved back to
              // the server
              rec.get('stateManager').send('willCommit');
              rec.get('stateManager').send('didCommit');

              rec._initLiveBindings();
            }.bind(this));

            ref.child(relationship.key).on("child_removed", function(snapshot) {
              var id = snapshot.name();

              var rec = this.get(relationship.key).find(function(item) {return item.get("id") == id});

              if (!rec) return;

              rec.deleteRecord();

              // fake sync
              rec.get('stateManager').send('willCommit');
              rec.get('stateManager').send('didCommit');
            }.bind(this));
          }

          else {
            ref.child(relationship.key).on("child_added", function(snapshot) {
              var id = snapshot.name();

              var ids = this._data.hasMany[relationship.key];
              var state = this.get("stateManager.currentState.name");

              // below: the magic of ember data
              if (state === "inFlight") {return;}   // if inFlight, id will not be pushed to hasMany yet.
              if (ids == undefined)     {return;}   // this one is pretty baffling.
              if (ids.contains(id))     {return;}   // this one is obvious, and in a perfect world would be the only one needed.

              var mdl = relationship.type.find(id);

              this.get(relationship.key).pushObject(mdl);
            }.bind(this));

            ref.child(relationship.key).on("child_removed", function(snapshot) {
              var id = snapshot.name();

              var rec = this.get(relationship.key).find(function(item) {return item.get("id") == id;});
              if (!rec) return;

              rec.deleteRecord();
              rec.get('stateManager').send('willCommit');
              rec.get('stateManager').send('didCommit');
            }.bind(this));
          }
        }
      }.bind(this))
    }
  },

});
<|endoftext|>


<commit_before>'use strict';

const ezmesure    = require('../../..');
const ProgressBar = require('progress');
const fs          = require('fs');
const zlib        = require('zlib');
const co          = require('co');
const path        = require('path');

exports.command = 'insert <indice> <files..>';
exports.desc    = 'Insert <files> into an <indice>';
exports.builder = function (yargs) {
  return yargs.option('z', {
    alias: 'gunzip',
    describe: 'Uncompress Gzip files locally'
  });
};
exports.handler = function (argv) {
  const { files, indice } = argv;

  const globalOptions = {
    gunzip: argv.gunzip,
    headers: {}
  };

  if (argv.u) { globalOptions.baseUrl = argv.u; }
  if (argv.token) { globalOptions.token = argv.token; }
  if (argv.timeout) { globalOptions.timeout = argv.timeout; }
  if (argv.insecure) { globalOptions.strictSSL = false; }

  const aggs = {
    total: 0,
    inserted: 0,
    updated: 0,
    failed: 0
  };

  co(function* () {
    for (const file of files) {
      let res;
      try {
        res = yield insertFile(file, indice, globalOptions);
      } catch (e) {
        console.error(e);
        continue;
      }

      ['total','inserted','updated','failed'].forEach(cat => {
        res[cat] = parseInt(res[cat]);
        aggs[cat] += res[cat] || 0;
      });

      printMetric('Total sent', res.total);
      printMetric('  Inserted', res.inserted, res.total);
      printMetric('  Updated', res.updated, res.total);
      printMetric('  Failed', res.failed, res.total);

      if (res.errors && res.errors.length) {
        printErrors(res.errors);
      }
    }

    console.log();
    console.log('Global metrics');
    console.log('--------------');
    printMetric('Files', files.length);
    printMetric('Total sent', aggs.total);
    printMetric('  Inserted', aggs.inserted, aggs.total);
    printMetric('  Updated', aggs.updated, aggs.total);
    printMetric('  Failed', aggs.failed, aggs.total);

  }).catch(e => {
    console.error(e);
    process.exit(1);
  });

};

function printMetric(label, value, total) {
  let msg = `  ${label}: ${value}`;

  if (total) {
    const percent = Math.round(value / total * 100);
    msg += ` (${percent}%)`;
  }

  console.log(msg);
}

function printErrors(errors) {
  console.log('  Errors:');

  errors.forEach(error => {
    let msg = `    ${error.reason || error.type}`;
    if (error.caused_by) {
      msg += ` (caused by: ${error.caused_by.reason || error.caused_by.type})`;
    }
    console.log(msg);
  });
}

function insertFile(file, indice, globalOptions) {
  return co(function* () {
    const stats     = yield getStats(file);
    const options   = Object.assign({}, globalOptions);
    const barTokens = {
      indice,
      file: path.basename(file)
    };

    console.log();

    let bar = new ProgressBar('  :file => :indice [:bar] :percent :etas  ', {
      complete: '=',
      incomplete: ' ',
      width: 50,
      total: stats.size
    });

    const fileReader = fs.createReadStream(file);

    fileReader.on('data', chunk => {
      bar.tick(chunk.length, barTokens);
    });

    let stream = fileReader;

    if (path.extname(file).toLowerCase() === '.gz') {
      if (globalOptions.gunzip) {
        console.log('LOCAL')
        stream = zlib.createGunzip();
        fileReader.pipe(stream);
      } else {
        console.log('NOT LOCAL')
        options.headers['content-encoding'] = 'application/gzip';
        options.headers['content-length'] = stats.size;
      }
    }

    return ezmesure.indices.insert(stream, indice, options).then(res => {
      return res || Promise.reject(new Error('No result'));
    });
  });
}

function getStats(file) {
  return new Promise((resolve, reject) => {
    fs.stat(file, (err, stats) => {
      if (err) { return reject(err); }
      resolve(stats);
    });
  });
}
<commit_msg>remove console.log<commit_after>'use strict';

const ezmesure    = require('../../..');
const ProgressBar = require('progress');
const fs          = require('fs');
const zlib        = require('zlib');
const co          = require('co');
const path        = require('path');

exports.command = 'insert <indice> <files..>';
exports.desc    = 'Insert <files> into an <indice>';
exports.builder = function (yargs) {
  return yargs.option('z', {
    alias: 'gunzip',
    describe: 'Uncompress Gzip files locally'
  });
};
exports.handler = function (argv) {
  const { files, indice } = argv;

  const globalOptions = {
    gunzip: argv.gunzip,
    headers: {}
  };

  if (argv.u) { globalOptions.baseUrl = argv.u; }
  if (argv.token) { globalOptions.token = argv.token; }
  if (argv.timeout) { globalOptions.timeout = argv.timeout; }
  if (argv.insecure) { globalOptions.strictSSL = false; }

  const aggs = {
    total: 0,
    inserted: 0,
    updated: 0,
    failed: 0
  };

  co(function* () {
    for (const file of files) {
      let res;
      try {
        res = yield insertFile(file, indice, globalOptions);
      } catch (e) {
        console.error(e);
        continue;
      }

      ['total','inserted','updated','failed'].forEach(cat => {
        res[cat] = parseInt(res[cat]);
        aggs[cat] += res[cat] || 0;
      });

      printMetric('Total sent', res.total);
      printMetric('  Inserted', res.inserted, res.total);
      printMetric('  Updated', res.updated, res.total);
      printMetric('  Failed', res.failed, res.total);

      if (res.errors && res.errors.length) {
        printErrors(res.errors);
      }
    }

    console.log();
    console.log('Global metrics');
    console.log('--------------');
    printMetric('Files', files.length);
    printMetric('Total sent', aggs.total);
    printMetric('  Inserted', aggs.inserted, aggs.total);
    printMetric('  Updated', aggs.updated, aggs.total);
    printMetric('  Failed', aggs.failed, aggs.total);

  }).catch(e => {
    console.error(e);
    process.exit(1);
  });

};

function printMetric(label, value, total) {
  let msg = `  ${label}: ${value}`;

  if (total) {
    const percent = Math.round(value / total * 100);
    msg += ` (${percent}%)`;
  }

  console.log(msg);
}

function printErrors(errors) {
  console.log('  Errors:');

  errors.forEach(error => {
    let msg = `    ${error.reason || error.type}`;
    if (error.caused_by) {
      msg += ` (caused by: ${error.caused_by.reason || error.caused_by.type})`;
    }
    console.log(msg);
  });
}

function insertFile(file, indice, globalOptions) {
  return co(function* () {
    const stats     = yield getStats(file);
    const options   = Object.assign({}, globalOptions);
    const barTokens = {
      indice,
      file: path.basename(file)
    };

    console.log();

    let bar = new ProgressBar('  :file => :indice [:bar] :percent :etas  ', {
      complete: '=',
      incomplete: ' ',
      width: 50,
      total: stats.size
    });

    const fileReader = fs.createReadStream(file);

    fileReader.on('data', chunk => {
      bar.tick(chunk.length, barTokens);
    });

    let stream = fileReader;

    if (path.extname(file).toLowerCase() === '.gz') {
      if (globalOptions.gunzip) {
        stream = zlib.createGunzip();
        fileReader.pipe(stream);
      } else {
        options.headers['content-encoding'] = 'application/gzip';
        options.headers['content-length'] = stats.size;
      }
    }

    return ezmesure.indices.insert(stream, indice, options).then(res => {
      return res || Promise.reject(new Error('No result'));
    });
  });
}

function getStats(file) {
  return new Promise((resolve, reject) => {
    fs.stat(file, (err, stats) => {
      if (err) { return reject(err); }
      resolve(stats);
    });
  });
}
<|endoftext|>


<commit_before>// @flow weak

import React, { PureComponent, PropTypes } from 'react';
import { easePoly } from 'd3-ease';
import { BASE_DURATION } from '../module/constants';
import { dims } from '../module';

const colors = { APPEAR: '#3C564B', UPDATE: '#A5937C', REMOVE: '#4D2B1D' };

class Text extends PureComponent {
  static propTypes = {
    data: PropTypes.shape({
      xValue: PropTypes.number.isRequired,
      letter: PropTypes.string.isRequired,
    }).isRequired,
    type: PropTypes.string.isRequired,
    // removeNode: PropTypes.func.isRequired,
  };

  constructor(props) {
    super(props);

    this.state = {
      text: {
        x: props.data.xValue,
        y: 0,
        fill: colors[props.type],
        opacity: 1e-6,
      },
    };
  }

  text = null; // Root text ref set in render method

  onAppear() {
    const { type, data: { xValue } } = this.props;

    return {
      text: {
        x: xValue,
        y: [0, dims[1] / 2],
        fill: colors[type],
        opacity: [1],
      },
      timing: { duration: BASE_DURATION, ease: easePoly },
    };
  }

  // onUpdate() {
  //   const { type, data: { xValue } } = this.props;

  //   return {
  //     text: {
  //       x: [xValue],
  //       y: [dims[1] / 2],
  //       fill: colors[type],
  //       opacity: [1],
  //     },
  //     timing: { duration: BASE_DURATION, ease: easePoly },
  //   };
  // }

  // onRemove() {
  //   const { type, data: { xValue }, removeNode } = this.props;

  //   return {
  //     text: {
  //       x: [xValue],
  //       y: [dims[1]],
  //       fill: colors[type],
  //       opacity: [1e-6],
  //     },
  //     timing: { duration: BASE_DURATION, ease: easePoly },
  //     events: { end: removeNode },
  //   };
  // }

  render() {
    const { data: { letter } } = this.props;

    return (
      <text
        ref={(d) => { this.text = d; }}
        dy="-.35em"
        style={{ font: 'bold 30px monospace' }}
        {...this.state.text}
      >{letter}</text>
    );
  }
}

export default Text;

<commit_msg>state updates working<commit_after>// @flow weak

import React, { PureComponent, PropTypes } from 'react';
import { easePoly } from 'd3-ease';
import { BASE_DURATION } from '../module/constants';
import { dims } from '../module';

const colors = { APPEAR: '#3C564B', UPDATE: '#A5937C', REMOVE: '#4D2B1D' };

class Text extends PureComponent {
  static propTypes = {
    data: PropTypes.shape({
      xValue: PropTypes.number.isRequired,
      letter: PropTypes.string.isRequired,
    }).isRequired,
    type: PropTypes.string.isRequired,
    removeNode: PropTypes.func.isRequired,
  };

  constructor(props) {
    super(props);

    this.state = {
      text: {
        x: props.data.xValue,
        y: 0,
        fill: colors[props.type],
        opacity: 1e-6,
      },
    };
  }

  text = null; // Root text ref set in render method

  onAppear() {
    const { type, data: { xValue } } = this.props;

    return {
      text: {
        x: xValue,
        y: dims[1] / 2,
        fill: colors[type],
        opacity: 1,
      },
      timing: { duration: BASE_DURATION, ease: easePoly },
    };
  }

  onUpdate() {
    const { type, data: { xValue } } = this.props;

    return {
      text: {
        x: xValue,
        y: dims[1] / 2,
        fill: colors[type],
        opacity: 1,
      },
      timing: { duration: BASE_DURATION, ease: easePoly },
    };
  }

  onRemove() {
    const { type, data: { xValue }, removeNode } = this.props;

    return {
      text: {
        x: xValue,
        y: dims[1],
        fill: colors[type],
        // opacity: 1e-6,
      },
      timing: { duration: BASE_DURATION, ease: easePoly },
      events: { end: removeNode },
    };
  }

  render() {
    const { data: { letter } } = this.props;

    return (
      <text
        ref={(d) => { this.text = d; }}
        dy="-.35em"
        style={{ font: 'bold 30px monospace' }}
        {...this.state.text}
      >{letter}</text>
    );
  }
}

export default Text;

<|endoftext|>


<commit_before>var sax = require('sax');
var inherits = require('util').inherits;
var EventEmitter = require('events').EventEmitter;
var tags = {};

var isNumber = function(v) {
  return (typeof v === 'number' || v instanceof Number);
};

var isString = function(v) {
  return (typeof v === 'string' || v instanceof String);
};

var isArray = Array.isArray || function(v) {
  return (v instanceof Array);
};

function parse(string, root) {
  var parser;
  if (!isString(string)) {
    parser = string;
  } else {
    parser = sax.createStream(true);
  }

  var loc;
  root = root || new MicroNode();
  parser.on('opentag', function(node) {

    var Ctor = tags[node.name] || MicroNode;
    var unode = new Ctor(node.attributes);
    unode.name = node.name;

    if (!loc) {
      loc = root;
    }

    loc.append(unode);
    loc = unode;
  });

  parser.on('text', function(text) {
    var node = loc.append('text', {}, text);
  });

  parser.on('error', function(error) {
    if (!root.errors) {
      root.errors = [];
    }
    root.errors.push(error);
  });

  parser.on('closetag', function() {
    loc = loc.parent;
  });

  // Internal control of the parser
  if (isString(string)) {
    parser.end(string);
  }

  if (root.length() > 1) {
    return root.children();
  } else {
    return root.child(0);
  }
}

function MicroNode(attrs) {
  EventEmitter.call(this);
  this.attributes = {};
  attrs && this.attr(attrs);
  this._children = [];
}

inherits(MicroNode, EventEmitter);

MicroNode.prototype.isNode = true;

MicroNode.prototype.child = function(index) {
  return this._children[index] || null;
};

MicroNode.prototype.children = function() {
  return this._children;
};

MicroNode.prototype.length = function() {
  return this._children.length;
};

MicroNode.prototype.buildNode = function(name, obj, textContent) {

  if (!isString(name)) {
    obj = name;
    name = null;
  } else if (
    typeof obj === 'undefined' &&
    typeof textContent === 'undefined' &&
    name.indexOf('<') > -1
    )
  {
    // handle xml
    obj = parse(name);
    return obj;
  }

  if (!obj || !obj.isNode) {
    obj = (tags[name]) ? new tags[name](obj) : new MicroNode(obj);
  }

  if (name) {
    obj.name = name;
  }

  if (obj.parent) {
    obj.parent.remove(obj);
  }

  obj.parent = this;

  if (textContent) {
    obj.value = textContent;
  }

  obj.own(this.owner || this);

  return (isArray(obj)) ? obj : [obj];
};

MicroNode.prototype.prepend = function(name, obj, value) {
  obj = this.buildNode(name, obj, value);
  var children = this.children();

  for (var i=0; i<obj.length; i++) {
    children.unshift(obj[i]);
    obj[i].owner && obj[i].owner.emit('+node', obj[i]);
  }
  return (obj.length === 1) ? obj[0] : obj;
};

MicroNode.prototype.append = function(name, obj, value) {
  obj = this.buildNode(name, obj, value);
  var children = this.children();

  for (var i=0; i<obj.length; i++) {
    children.push(obj[i]);
    obj[i].owner && obj[i].owner.emit('+node', obj[i]);
  }
  return (obj.length === 1) ? obj[0] : obj;
};

MicroNode.prototype.indexOf = function(node) {
  var c = this.children(), l = this.length(), i = -1;
  if (l) {
    for (i = 0; i<l; i++) {
      if (node === c[i]) {
        break;
      }
    }
  }

  return i;
};

MicroNode.prototype.own = function(owner) {
  if (this.owner !== owner) {
    var c = this.children(), l = this.length();
    this.owner = owner;

    if (l) {
      for (var i = 0; i<l; i++) {
        c[i].own(owner);
        c[i].owner = owner;
      }
    }
  }

  return this;
};

MicroNode.prototype.remove = function(node) {
  var c = this.children(), l = this.length();

  if (l) {
    if (isNumber(node)) {
      if (node < 0 || node >= l) {
        return null;
      }

      node = c.splice(node, 1)[0];
    } else {
      for (var i = 0; i<l; i++) {
        if (node === c[i]) {
          c.splice(i, 1);
        }
      }
    }
  }

  node.parent = null;

  node.owner && node.owner.emit('-node', node);

  return node;
};

// Attribute getter/setter
MicroNode.prototype.attr = function(name, value) {
  var obj;

  if (!isString(name) || (isString(name) && typeof value !== 'undefined')) {
    if (isString(name)) {
      obj = {};
      obj[name] = value;
    } else {
      obj = name;
    }

    for (name in obj) {

      if (obj.hasOwnProperty(name)) {
        value = obj[name];

        var old = this.attributes[name] || null;
        this.attributes[name] = value;
        if (value === null) {
          this.owner && this.owner.emit('-attr.' + name, this, value, old);
        } else if (old !== null) {
          this.owner && this.owner.emit('~attr.' + name, this, value, old);
        } else {
          this.owner && this.owner.emit('+attr.' + name, this, value, old);
        }
      }
    }
  }

  return this.attributes[name] || null;
};

function MicroDom() {
  MicroNode.call(this);
}

inherits(MicroDom, MicroNode);

function microdom(xml, fn) {
  var dom = new MicroDom();

  if (xml) {
    parse(xml, dom);
    if (!isString(xml) && typeof fn == 'function') {
      xml.on('end', function() {
        fn.call(dom);
      });
    }
  }

  return dom;
};

microdom.tag = function(name, ctor) {
  tags[name] = ctor;
};

microdom.plugin = function(o) {
  var proto = MicroNode.prototype;
  if (typeof o === 'function') {
    o(proto);
  } else {
    Object.keys(o).forEach(function(key) {
      proto[key] = o[key];
    });
  }
};

microdom.parse = parse;
microdom.MicroNode = MicroNode;
microdom.MicroDom = MicroDom;
microdom.sax = sax;

if (typeof module !== 'undefined' && typeof module.exports == 'object') {
  module.exports = microdom;
}

if (typeof window !== 'undefined') {
  window.microdom = window.microdom || microdom;
}
<commit_msg>don't use object.keys for older IE<commit_after>var sax = require('sax');
var inherits = require('util').inherits;
var EventEmitter = require('events').EventEmitter;
var tags = {};

var isNumber = function(v) {
  return (typeof v === 'number' || v instanceof Number);
};

var isString = function(v) {
  return (typeof v === 'string' || v instanceof String);
};

var isArray = Array.isArray || function(v) {
  return (v instanceof Array);
};

function parse(string, root) {
  var parser;
  if (!isString(string)) {
    parser = string;
  } else {
    parser = sax.createStream(true);
  }

  var loc;
  root = root || new MicroNode();
  parser.on('opentag', function(node) {

    var Ctor = tags[node.name] || MicroNode;
    var unode = new Ctor(node.attributes);
    unode.name = node.name;

    if (!loc) {
      loc = root;
    }

    loc.append(unode);
    loc = unode;
  });

  parser.on('text', function(text) {
    var node = loc.append('text', {}, text);
  });

  parser.on('error', function(error) {
    if (!root.errors) {
      root.errors = [];
    }
    root.errors.push(error);
  });

  parser.on('closetag', function() {
    loc = loc.parent;
  });

  // Internal control of the parser
  if (isString(string)) {
    parser.end(string);
  }

  if (root.length() > 1) {
    return root.children();
  } else {
    return root.child(0);
  }
}

function MicroNode(attrs) {
  EventEmitter.call(this);
  this.attributes = {};
  attrs && this.attr(attrs);
  this._children = [];
}

inherits(MicroNode, EventEmitter);

MicroNode.prototype.isNode = true;

MicroNode.prototype.child = function(index) {
  return this._children[index] || null;
};

MicroNode.prototype.children = function() {
  return this._children;
};

MicroNode.prototype.length = function() {
  return this._children.length;
};

MicroNode.prototype.buildNode = function(name, obj, textContent) {

  if (!isString(name)) {
    obj = name;
    name = null;
  } else if (
    typeof obj === 'undefined' &&
    typeof textContent === 'undefined' &&
    name.indexOf('<') > -1
    )
  {
    // handle xml
    obj = parse(name);
    return obj;
  }

  if (!obj || !obj.isNode) {
    obj = (tags[name]) ? new tags[name](obj) : new MicroNode(obj);
  }

  if (name) {
    obj.name = name;
  }

  if (obj.parent) {
    obj.parent.remove(obj);
  }

  obj.parent = this;

  if (textContent) {
    obj.value = textContent;
  }

  obj.own(this.owner || this);

  return (isArray(obj)) ? obj : [obj];
};

MicroNode.prototype.prepend = function(name, obj, value) {
  obj = this.buildNode(name, obj, value);
  var children = this.children();

  for (var i=0; i<obj.length; i++) {
    children.unshift(obj[i]);
    obj[i].owner && obj[i].owner.emit('+node', obj[i]);
  }
  return (obj.length === 1) ? obj[0] : obj;
};

MicroNode.prototype.append = function(name, obj, value) {
  obj = this.buildNode(name, obj, value);
  var children = this.children();

  for (var i=0; i<obj.length; i++) {
    children.push(obj[i]);
    obj[i].owner && obj[i].owner.emit('+node', obj[i]);
  }
  return (obj.length === 1) ? obj[0] : obj;
};

MicroNode.prototype.indexOf = function(node) {
  var c = this.children(), l = this.length(), i = -1;
  if (l) {
    for (i = 0; i<l; i++) {
      if (node === c[i]) {
        break;
      }
    }
  }

  return i;
};

MicroNode.prototype.own = function(owner) {
  if (this.owner !== owner) {
    var c = this.children(), l = this.length();
    this.owner = owner;

    if (l) {
      for (var i = 0; i<l; i++) {
        c[i].own(owner);
        c[i].owner = owner;
      }
    }
  }

  return this;
};

MicroNode.prototype.remove = function(node) {
  var c = this.children(), l = this.length();

  if (l) {
    if (isNumber(node)) {
      if (node < 0 || node >= l) {
        return null;
      }

      node = c.splice(node, 1)[0];
    } else {
      for (var i = 0; i<l; i++) {
        if (node === c[i]) {
          c.splice(i, 1);
        }
      }
    }
  }

  node.parent = null;

  node.owner && node.owner.emit('-node', node);

  return node;
};

// Attribute getter/setter
MicroNode.prototype.attr = function(name, value) {
  var obj;

  if (!isString(name) || (isString(name) && typeof value !== 'undefined')) {
    if (isString(name)) {
      obj = {};
      obj[name] = value;
    } else {
      obj = name;
    }

    for (name in obj) {

      if (obj.hasOwnProperty(name)) {
        value = obj[name];

        var old = this.attributes[name] || null;
        this.attributes[name] = value;
        if (value === null) {
          this.owner && this.owner.emit('-attr.' + name, this, value, old);
        } else if (old !== null) {
          this.owner && this.owner.emit('~attr.' + name, this, value, old);
        } else {
          this.owner && this.owner.emit('+attr.' + name, this, value, old);
        }
      }
    }
  }

  return this.attributes[name] || null;
};

function MicroDom() {
  MicroNode.call(this);
}

inherits(MicroDom, MicroNode);

function microdom(xml, fn) {
  var dom = new MicroDom();

  if (xml) {
    parse(xml, dom);
    if (!isString(xml) && typeof fn == 'function') {
      xml.on('end', function() {
        fn.call(dom);
      });
    }
  }

  return dom;
};

microdom.tag = function(name, ctor) {
  tags[name] = ctor;
};

microdom.plugin = function(o) {
  var proto = MicroNode.prototype;
  if (typeof o === 'function') {
    o(proto);
  } else {
    for (var key in o) {
      if (o.hasOwnProperty(key)) {
        proto[key] = o[key];
      }
    }
  }
};

microdom.parse = parse;
microdom.MicroNode = MicroNode;
microdom.MicroDom = MicroDom;
microdom.sax = sax;

if (typeof module !== 'undefined' && typeof module.exports == 'object') {
  module.exports = microdom;
}

if (typeof window !== 'undefined') {
  window.microdom = window.microdom || microdom;
}
<|endoftext|>


<commit_before>if (Meteor.isClient) {

  var search = function(query) {

    var terms = query.split(" ");

    var must = "";
    var must_not = "";

    var term;
    for (var i = terms.length - 1; i >= 0; i--) {
      term = terms[i];

      if (term.charAt(0) === '-') {
        must_not += " " + term.substring(1, term.length);
      }
      else {
        must += " " + term;
      }
    }

    console.log(must);
    console.log(must_not);

    var q = {
      fields: ["file"],
      from: 0,
      size: 10,
      query: {
        bool: {
          must: [
            {
              multi_match: {
                query: must,
                fields: ["file^10", "_name"]
              }
            }
          ],
          must_not: [
            {
              multi_match: {
                query: must_not,
                fields: ["file^10", "_name"]
              }
            }
          ],
          // should: { match: { file: "Police" } },
        }
      },
      highlight: {
        fields: {
          file: {}
        }
      }
    };

    ElasticSearch.query(q, function(err, result) {
      if (err) {
        console.error(err);
      }
      else {
        var results = result.data;

        console.log(results);

        Session.set("results", results);
      }
    });
  };

  Template.searchIndex.helpers({
    results: function() {
      return Session.get("results") || [];
    },

    'toSeconds': function(ms) {
      var time = new Date(ms);
      return time.getSeconds() + "." + time.getMilliseconds();
    },

    urlToDocument: function(id) {
      var s = Meteor.settings.public.elasticSearch;

      var url = s.protocol + "://" + s.host + ":" + s.port + "/" + IndexSettings.getActiveIndex() + "/" + s.attachmentsPath + "/" + id;
      return url;
    },
  });

  Template.searchIndex.events({
    'click #search-btn': function(e, tmpl) {
      var query = tmpl.$('#search-query').val();
      search(query);
    },

    'keyup #search-query': function(e, tmpl) {
      if (e.keyCode == 13) {
        var query = tmpl.$('#search-query').val();
        search(query);
      }
    },

    'click .hit': function(e, tmpl) {

      ElasticSearch.get(this._id, function(err, result) {
        if (err) {
          console.error(err);
        }
        else {
          var attachment = result.data;

          var source = attachment._source;
          var contentType = source._content_type;
          var file = source.file;

          // console.log(contentType);

          var content = atob(file);

          var html;
          if (contentType == "image/jpeg") {
            html = ''
          }
          else {
            html = '

' + content + '

';
          }

          $.fancybox(html, {
            title: "Alderwood Daily News Articles"
          });
        }
      });
    },
  });
}
<commit_msg>Added the possibility for enter phrases into the search field by using either single or double quotes. Phrases can also be negated by adding a minus before the opening quotation mark.<commit_after>if (Meteor.isClient) {

  var search = function(query) {

    var SEARCH_FIELDS = ["file^10", "_name"];

    var terms = query.split(" ");

    var must = [];
    var must_not = [];

    var term;
    var quoteOpen;
    var not = false;

    //Some rather complex code for building queries, but here we go...
    //We walk over every (space-separated) term. Every term is converted into an
    //entry usable by elasticsearch. The entries are added to must/must_not, when:
    //    * A normal term is simply added to the must array
    //    * A term prefixed by '-' is added to the must_not arrya
    //    * If a term begins with a quote, it starts a phrase. The term is not added yet
    //    * The next term ending with a quote ends the phrase. The entire phrase is added
    //      to either must or must_not with the type "phrase"
    for (var i = 0; i < terms.length; i++) {
      if (quoteOpen === undefined) {
        term = terms[i];
        not = false;

        //Check for negation prefix
        if (term.charAt(0) === '-') {
          term = term.substring(1, term.length);
          not = true;
        }

        //Check for opening quotes
        if (term.charAt(0) === "'" || term.charAt(0) === '"') {
          quotesOpen = term.charAt(0);
          term = term.substring(1, term.length);
        } else {
          var entry = {
            multi_match: {
              query: term,
              fields: SEARCH_FIELDS
            }
          };

          if (not)  must_not.push(entry);
          else      must.push(entry);
        }
      } else {
        //A phrase is still open, add the term to the existing phrase
        term += " " + terms[i];

        //Check if the phrase ends here
        if (term.charAt(term.length-1) === quotesOpen) {
          term = term.substring(0, term.length-1);
          quotesOpen = undefined;

          var phraseEntry = {
            multi_match: {
              query: term,
              fields: SEARCH_FIELDS,
              type: "phrase"
            }
          };

          if (not)  must_not.push(phraseEntry);
          else      must.push(phraseEntry);
        }
      }
    }

    //elasticsearch can't handle empty must/must_not blocks
    var bool = {};
    if (must.length > 0) bool.must = must;
    if (must_not.length > 0) bool.must_not = must_not;

    var q = {
      fields: ["file"],
      from: 0,
      size: 10,
      query: { bool: bool },
      highlight: {
        fields: {
          file: {}
        }
      }
    };
    console.log(q);

    ElasticSearch.query(q, function(err, result) {
      if (err) {
        console.error(err);
      }
      else {
        var results = result.data;

        console.log(results);

        Session.set("results", results);
      }
    });
  };

  Template.searchIndex.helpers({
    results: function() {
      return Session.get("results") || [];
    },

    'toSeconds': function(ms) {
      var time = new Date(ms);
      return time.getSeconds() + "." + time.getMilliseconds();
    },

    urlToDocument: function(id) {
      var s = Meteor.settings.public.elasticSearch;

      var url = s.protocol + "://" + s.host + ":" + s.port + "/" + IndexSettings.getActiveIndex() + "/" + s.attachmentsPath + "/" + id;
      return url;
    },
  });

  Template.searchIndex.events({
    'click #search-btn': function(e, tmpl) {
      var query = tmpl.$('#search-query').val();
      search(query);
    },

    'keyup #search-query': function(e, tmpl) {
      if (e.keyCode == 13) {
        var query = tmpl.$('#search-query').val();
        search(query);
      }
    },

    'click .hit': function(e, tmpl) {

      ElasticSearch.get(this._id, function(err, result) {
        if (err) {
          console.error(err);
        }
        else {
          var attachment = result.data;

          var source = attachment._source;
          var contentType = source._content_type;
          var file = source.file;

          // console.log(contentType);

          var content = atob(file);

          var html;
          if (contentType == "image/jpeg") {
            html = ''
          }
          else {
            html = '

' + content + '

';
          }

          $.fancybox(html, {
            title: "Alderwood Daily News Articles"
          });
        }
      });
    },
  });
}
<|endoftext|>


<commit_before>// jQuery Context Menu Plugin
//
// Version 1.01
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
//
// More info: http://abeautifulsite.net/2008/09/jquery-context-menu-plugin/
//
// Terms of Use
//
// This plugin is dual-licensed under the GNU General Public License
//   and the MIT License and is copyright A Beautiful Site, LLC.
//
jQuery&&function(){$.extend($.fn,{contextMenu:function(a,e){if(a.menu==undefined)return false;if(a.inSpeed==undefined)a.inSpeed=150;if(a.outSpeed==undefined)a.outSpeed=75;if(a.inSpeed==0)a.inSpeed=-1;if(a.outSpeed==0)a.outSpeed=-1;$(this).each(function(){var d=$(this),i=$(d).offset();$("#"+a.menu).addClass("contextMenu");$(this).mousedown(function(j){j.stopPropagation();$(this).mouseup(function(f){f.stopPropagation();var k=$(this);$(this).unbind("mouseup");if(j.button==2){$(".contextMenu").hide();
var b=$("#"+a.menu);if($(d).hasClass("disabled"))return false;var c={},g,h;if(self.innerHeight){c.pageYOffset=self.pageYOffset;c.pageXOffset=self.pageXOffset;c.innerHeight=self.innerHeight;c.innerWidth=self.innerWidth}else if(document.documentElement&&document.documentElement.clientHeight){c.pageYOffset=document.documentElement.scrollTop;c.pageXOffset=document.documentElement.scrollLeft;c.innerHeight=document.documentElement.clientHeight;c.innerWidth=document.documentElement.clientWidth}else if(document.body){c.pageYOffset=
document.body.scrollTop;c.pageXOffset=document.body.scrollLeft;c.innerHeight=document.body.clientHeight;c.innerWidth=document.body.clientWidth}f.pageX?g=f.pageX:g=f.clientX+c.scrollLeft;f.pageY?h=f.pageY:h=f.clientY+c.scrollTop;$(document).unbind("click");$(b).css({top:h,left:g}).fadeIn(a.inSpeed);$(b).find("A").mouseover(function(){$(b).find("LI.hover").removeClass("hover");$(this).parent().addClass("hover")}).mouseout(function(){$(b).find("LI.hover").removeClass("hover")});$(document).keypress(function(l){switch(l.keyCode){case 38:if($(b).find("LI.hover").size()==
0)$(b).find("LI:last").addClass("hover");else{$(b).find("LI.hover").removeClass("hover").prevAll("LI:not(.disabled)").eq(0).addClass("hover");$(b).find("LI.hover").size()==0&&$(b).find("LI:last").addClass("hover")}break;case 40:if($(b).find("LI.hover").size()==0)$(b).find("LI:first").addClass("hover");else{$(b).find("LI.hover").removeClass("hover").nextAll("LI:not(.disabled)").eq(0).addClass("hover");$(b).find("LI.hover").size()==0&&$(b).find("LI:first").addClass("hover")}break;case 13:$(b).find("LI.hover A").trigger("click");
break;case 27:$(document).trigger("click");break}});$("#"+a.menu).find("A").unbind("click");$("#"+a.menu).find("LI:not(.disabled) A").click(function(){$(document).unbind("click").unbind("keypress");$(".contextMenu").hide();e&&e($(this).attr("href").substr(1),$(k),{x:g-i.left,y:h-i.top,docX:g,docY:h});return false});setTimeout(function(){$(document).click(function(){$(document).unbind("click").unbind("keypress");$(b).fadeOut(a.outSpeed);return false})},0)}})});if($.browser.mozilla)$("#"+a.menu).each(function(){$(this).css({MozUserSelect:"none"})});
else $.browser.msie?$("#"+a.menu).each(function(){$(this).bind("selectstart.disableTextSelect",function(){return false})}):$("#"+a.menu).each(function(){$(this).bind("mousedown.disableTextSelect",function(){return false})});$(d).add($("UL.contextMenu")).bind("contextmenu",function(){return false})});return $(this)},disableContextMenuItems:function(a){if(a==undefined){$(this).find("LI").addClass("disabled");return $(this)}$(this).each(function(){if(a!=undefined)for(var e=a.split(","),d=0;d<e.length;d++)$(this).find('A[href="'+
e[d]+'"]').parent().addClass("disabled")});return $(this)},enableContextMenuItems:function(a){if(a==undefined){$(this).find("LI.disabled").removeClass("disabled");return $(this)}$(this).each(function(){if(a!=undefined)for(var e=a.split(","),d=0;d<e.length;d++)$(this).find('A[href="'+e[d]+'"]').parent().removeClass("disabled")});return $(this)},disableContextMenu:function(){$(this).each(function(){$(this).addClass("disabled")});return $(this)},enableContextMenu:function(){$(this).each(function(){$(this).removeClass("disabled")});
return $(this)},destroyContextMenu:function(){$(this).each(function(){$(this).unbind("mousedown").unbind("mouseup")});return $(this)}})}(jQuery);<commit_msg>Fixed Issue 765: The context menu can go off the side of the screen by updating jquery.contextMenu.min.js with unminified version<commit_after>// jQuery Context Menu Plugin
//
// Version 1.01
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
//
// Modifications by Alexis Deveria
//
// More info: http://abeautifulsite.net/2008/09/jquery-context-menu-plugin/
//
// Terms of Use
//
// This plugin is dual-licensed under the GNU General Public License
//   and the MIT License and is copyright A Beautiful Site, LLC.
//
jQuery&&function(){var i=$(window),e=$(document);$.extend($.fn,{contextMenu:function(a,d){if(a.menu==undefined)return false;if(a.inSpeed==undefined)a.inSpeed=150;if(a.outSpeed==undefined)a.outSpeed=75;if(a.inSpeed==0)a.inSpeed=-1;if(a.outSpeed==0)a.outSpeed=-1;$(this).each(function(){var c=$(this),j=$(c).offset(),b=$("#"+a.menu);b.addClass("contextMenu");$(this).mousedown(function(m){$(this).mouseup(function(f){var k=$(this);k.unbind("mouseup");if(m.button===2||a.allowLeft){f.stopPropagation();$(".contextMenu").hide();
if(c.hasClass("disabled"))return false;var g=f.pageX,h=f.pageY;f=i.width()-b.width();var l=i.height()-b.height();if(g>f-15)g=f-15;if(h>l-30)h=l-30;e.unbind("click");b.css({top:h,left:g}).fadeIn(a.inSpeed);b.find("A").mouseover(function(){b.find("LI.hover").removeClass("hover");$(this).parent().addClass("hover")}).mouseout(function(){b.find("LI.hover").removeClass("hover")});e.keypress(function(n){switch(n.keyCode){case 38:if(b.find("LI.hover").length){b.find("LI.hover").removeClass("hover").prevAll("LI:not(.disabled)").eq(0).addClass("hover");
b.find("LI.hover").length||b.find("LI:last").addClass("hover")}else b.find("LI:last").addClass("hover");break;case 40:if(b.find("LI.hover").length==0)b.find("LI:first").addClass("hover");else{b.find("LI.hover").removeClass("hover").nextAll("LI:not(.disabled)").eq(0).addClass("hover");b.find("LI.hover").length||b.find("LI:first").addClass("hover")}break;case 13:b.find("LI.hover A").trigger("click");break;case 27:e.trigger("click")}});b.find("A").unbind("mouseup");b.find("LI:not(.disabled) A").mouseup(function(){e.unbind("click").unbind("keypress");
$(".contextMenu").hide();d&&d($(this).attr("href").substr(1),$(k),{x:g-j.left,y:h-j.top,docX:g,docY:h});return false});setTimeout(function(){e.click(function(){e.unbind("click").unbind("keypress");b.fadeOut(a.outSpeed);return false})},0)}})});if($.browser.mozilla)$("#"+a.menu).each(function(){$(this).css({MozUserSelect:"none"})});else $.browser.msie?$("#"+a.menu).each(function(){$(this).bind("selectstart.disableTextSelect",function(){return false})}):$("#"+a.menu).each(function(){$(this).bind("mousedown.disableTextSelect",
function(){return false})});$(c).add($("UL.contextMenu")).bind("contextmenu",function(){return false})});return $(this)},disableContextMenuItems:function(a){if(a==undefined){$(this).find("LI").addClass("disabled");return $(this)}$(this).each(function(){if(a!=undefined)for(var d=a.split(","),c=0;c<d.length;c++)$(this).find('A[href="'+d[c]+'"]').parent().addClass("disabled")});return $(this)},enableContextMenuItems:function(a){if(a==undefined){$(this).find("LI.disabled").removeClass("disabled");return $(this)}$(this).each(function(){if(a!=
undefined)for(var d=a.split(","),c=0;c<d.length;c++)$(this).find('A[href="'+d[c]+'"]').parent().removeClass("disabled")});return $(this)},disableContextMenu:function(){$(this).each(function(){$(this).addClass("disabled")});return $(this)},enableContextMenu:function(){$(this).each(function(){$(this).removeClass("disabled")});return $(this)},destroyContextMenu:function(){$(this).each(function(){$(this).unbind("mousedown").unbind("mouseup")});return $(this)}})}(jQuery);<|endoftext|>


<commit_before>#!/bin/sh
':' //; exec /usr/bin/env node --harmony "$0" "$@"

/**
* @Author: Popov Gennadiy <dio>
* @Date:   2016-12-01T07:41:25+03:00
* @Email:  me@westtrade.tk
* @Last modified by:   dio
* @Last modified time: 2016-12-07T02:13:27+03:00
*/

require('../index.js');
<commit_msg>Remove unnecessary ./bin folder<commit_after><|endoftext|>


<commit_before>angular.module('redash', [
  'redash.directives',
  'redash.admin_controllers',
  'redash.controllers',
  'redash.filters',
  'redash.services',
  'redash.visualization',
  'plotly',
  'angular-growl',
  'angularMoment',
  'ui.bootstrap',
  'ui.sortable',
  'smartTable.table',
  'ngResource',
  'ngRoute',
  'ui.select',
  'ui.ace',
  'naif.base64',
  'ui.bootstrap.showErrors',
  'angularResizable',
  'ngSanitize',
  'vs-repeat',
  'cfp.hotkeys'
]).config(['$routeProvider', '$locationProvider', '$compileProvider', 'growlProvider', 'uiSelectConfig', '$httpProvider',
  function ($routeProvider, $locationProvider, $compileProvider, growlProvider, uiSelectConfig, $httpProvider) {
    function getQuery(Query, $route) {
      var query = Query.get({'id': $route.current.params.queryId});
      return query.$promise;
    };

    if (currentUser.apiKey) {
      $httpProvider.defaults.headers.common.Authorization = 'Key ' + currentUser.apiKey;
    }

    uiSelectConfig.theme = "bootstrap";

    $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|http|data):/);
    $locationProvider.html5Mode(true);
    growlProvider.globalTimeToLive(2000);

    $routeProvider.when('/admin/queries/outdated', {
      templateUrl: '/views/admin/outdated_queries.html',
      controller: 'AdminOutdatedQueriesCtrl'
    });
    $routeProvider.when('/admin/queries/tasks', {
      templateUrl: '/views/admin/tasks.html',
      controller: 'AdminTasksCtrl'
    });
    $routeProvider.when('/dashboard/:dashboardSlug', {
      templateUrl: '/views/dashboard.html',
      controller: 'DashboardCtrl',
      reloadOnSearch: false
    });
    $routeProvider.when('/public/dashboards/:token', {
      templateUrl: '/views/dashboard.html',
      controller: 'PublicDashboardCtrl',
      reloadOnSearch: false
    });
    $routeProvider.when('/queries', {
      templateUrl: '/views/queries.html',
      controller: 'QueriesCtrl',
      reloadOnSearch: false
    });
    $routeProvider.when('/queries/new', {
      templateUrl: '/views/query.html',
      controller: 'QuerySourceCtrl',
      reloadOnSearch: false,
      resolve: {
        'query': ['Query', function newQuery(Query) {
          return Query.newQuery();
        }],
        'dataSources': ['DataSource', function (DataSource) {
          return DataSource.query().$promise
        }]
      }
    });
    $routeProvider.when('/queries/search', {
      templateUrl: '/views/queries_search_results.html',
      controller: 'QuerySearchCtrl',
      reloadOnSearch: true,
    });
    $routeProvider.when('/queries/:queryId', {
      templateUrl: '/views/query.html',
      controller: 'QueryViewCtrl',
      reloadOnSearch: false,
      resolve: {
        'query': ['Query', '$route', getQuery]
      }
    });
    $routeProvider.when('/queries/:queryId/source', {
      templateUrl: '/views/query.html',
      controller: 'QuerySourceCtrl',
      reloadOnSearch: false,
      resolve: {
        'query': ['Query', '$route', getQuery]
      }
    });
    $routeProvider.when('/admin/status', {
      templateUrl: '/views/admin_status.html',
      controller: 'AdminStatusCtrl'
    });

    $routeProvider.when('/alerts', {
      templateUrl: '/views/alerts/list.html',
      controller: 'AlertsCtrl'
    });
    $routeProvider.when('/alerts/:alertId', {
      templateUrl: '/views/alerts/edit.html',
      controller: 'AlertCtrl'
    });

    $routeProvider.when('/data_sources/:dataSourceId', {
      templateUrl: '/views/data_sources/edit.html',
      controller: 'DataSourceCtrl'
    });
    $routeProvider.when('/data_sources', {
      templateUrl: '/views/data_sources/list.html',
      controller: 'DataSourcesCtrl'
    });

    $routeProvider.when('/destinations/:destinationId', {
      templateUrl: '/views/destinations/edit.html',
      controller: 'DestinationCtrl'
    });
    $routeProvider.when('/destinations', {
      templateUrl: '/views/destinations/list.html',
      controller: 'DestinationsCtrl'
    });

    $routeProvider.when('/users/new', {
      templateUrl: '/views/users/new.html',
      controller: 'NewUserCtrl'
    });
    $routeProvider.when('/users/:userId', {
      templateUrl: '/views/users/show.html',
      reloadOnSearch: false,
      controller: 'UserCtrl'
    });
    $routeProvider.when('/users', {
      templateUrl: '/views/users/list.html',
      controller: 'UsersCtrl'
    });
    $routeProvider.when('/groups/:groupId/data_sources', {
      templateUrl: '/views/groups/show_data_sources.html',
      controller: 'GroupDataSourcesCtrl'
    });
    $routeProvider.when('/groups/:groupId', {
      templateUrl: '/views/groups/show.html',
      controller: 'GroupCtrl'
    });
    $routeProvider.when('/groups', {
      templateUrl: '/views/groups/list.html',
      controller: 'GroupsCtrl'
    });
    $routeProvider.when('/query_snippets/:snippetId', {
      templateUrl: '/views/query_snippets/show.html',
      controller: 'SnippetCtrl'
    });
    $routeProvider.when('/query_snippets', {
      templateUrl: '/views/query_snippets/list.html',
      controller: 'SnippetsCtrl'
    });
    $routeProvider.when('/', {
        templateUrl: '/views/query.html',
        controller: 'QuerySourceCtrl',
        reloadOnSearch: false,
        resolve: {
          'query': ['Query', function newQuery(Query) {
            return Query.newQuery();
          }],
          'dataSources': ['DataSource', function (DataSource) {
            return DataSource.query().$promise
          }]
        }
    });
    $routeProvider.when('/personal', {
      redirectTo: '/'
    });
    $routeProvider.otherwise({
      redirectTo: '/'
    });

  }
]);
<commit_msg>Revert "default to /queries/new"<commit_after>angular.module('redash', [
  'redash.directives',
  'redash.admin_controllers',
  'redash.controllers',
  'redash.filters',
  'redash.services',
  'redash.visualization',
  'plotly',
  'angular-growl',
  'angularMoment',
  'ui.bootstrap',
  'ui.sortable',
  'smartTable.table',
  'ngResource',
  'ngRoute',
  'ui.select',
  'ui.ace',
  'naif.base64',
  'ui.bootstrap.showErrors',
  'angularResizable',
  'ngSanitize',
  'vs-repeat',
  'cfp.hotkeys'
]).config(['$routeProvider', '$locationProvider', '$compileProvider', 'growlProvider', 'uiSelectConfig', '$httpProvider',
  function ($routeProvider, $locationProvider, $compileProvider, growlProvider, uiSelectConfig, $httpProvider) {
    function getQuery(Query, $route) {
      var query = Query.get({'id': $route.current.params.queryId});
      return query.$promise;
    };

    if (currentUser.apiKey) {
      $httpProvider.defaults.headers.common.Authorization = 'Key ' + currentUser.apiKey;
    }

    uiSelectConfig.theme = "bootstrap";

    $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|http|data):/);
    $locationProvider.html5Mode(true);
    growlProvider.globalTimeToLive(2000);

    $routeProvider.when('/admin/queries/outdated', {
      templateUrl: '/views/admin/outdated_queries.html',
      controller: 'AdminOutdatedQueriesCtrl'
    });
    $routeProvider.when('/admin/queries/tasks', {
      templateUrl: '/views/admin/tasks.html',
      controller: 'AdminTasksCtrl'
    });
    $routeProvider.when('/dashboard/:dashboardSlug', {
      templateUrl: '/views/dashboard.html',
      controller: 'DashboardCtrl',
      reloadOnSearch: false
    });
    $routeProvider.when('/public/dashboards/:token', {
      templateUrl: '/views/dashboard.html',
      controller: 'PublicDashboardCtrl',
      reloadOnSearch: false
    });
    $routeProvider.when('/queries', {
      templateUrl: '/views/queries.html',
      controller: 'QueriesCtrl',
      reloadOnSearch: false
    });
    $routeProvider.when('/queries/new', {
      templateUrl: '/views/query.html',
      controller: 'QuerySourceCtrl',
      reloadOnSearch: false,
      resolve: {
        'query': ['Query', function newQuery(Query) {
          return Query.newQuery();
        }],
        'dataSources': ['DataSource', function (DataSource) {
          return DataSource.query().$promise
        }]
      }
    });
    $routeProvider.when('/queries/search', {
      templateUrl: '/views/queries_search_results.html',
      controller: 'QuerySearchCtrl',
      reloadOnSearch: true,
    });
    $routeProvider.when('/queries/:queryId', {
      templateUrl: '/views/query.html',
      controller: 'QueryViewCtrl',
      reloadOnSearch: false,
      resolve: {
        'query': ['Query', '$route', getQuery]
      }
    });
    $routeProvider.when('/queries/:queryId/source', {
      templateUrl: '/views/query.html',
      controller: 'QuerySourceCtrl',
      reloadOnSearch: false,
      resolve: {
        'query': ['Query', '$route', getQuery]
      }
    });
    $routeProvider.when('/admin/status', {
      templateUrl: '/views/admin_status.html',
      controller: 'AdminStatusCtrl'
    });

    $routeProvider.when('/alerts', {
      templateUrl: '/views/alerts/list.html',
      controller: 'AlertsCtrl'
    });
    $routeProvider.when('/alerts/:alertId', {
      templateUrl: '/views/alerts/edit.html',
      controller: 'AlertCtrl'
    });

    $routeProvider.when('/data_sources/:dataSourceId', {
      templateUrl: '/views/data_sources/edit.html',
      controller: 'DataSourceCtrl'
    });
    $routeProvider.when('/data_sources', {
      templateUrl: '/views/data_sources/list.html',
      controller: 'DataSourcesCtrl'
    });

    $routeProvider.when('/destinations/:destinationId', {
      templateUrl: '/views/destinations/edit.html',
      controller: 'DestinationCtrl'
    });
    $routeProvider.when('/destinations', {
      templateUrl: '/views/destinations/list.html',
      controller: 'DestinationsCtrl'
    });

    $routeProvider.when('/users/new', {
      templateUrl: '/views/users/new.html',
      controller: 'NewUserCtrl'
    });
    $routeProvider.when('/users/:userId', {
      templateUrl: '/views/users/show.html',
      reloadOnSearch: false,
      controller: 'UserCtrl'
    });
    $routeProvider.when('/users', {
      templateUrl: '/views/users/list.html',
      controller: 'UsersCtrl'
    });
    $routeProvider.when('/groups/:groupId/data_sources', {
      templateUrl: '/views/groups/show_data_sources.html',
      controller: 'GroupDataSourcesCtrl'
    });
    $routeProvider.when('/groups/:groupId', {
      templateUrl: '/views/groups/show.html',
      controller: 'GroupCtrl'
    });
    $routeProvider.when('/groups', {
      templateUrl: '/views/groups/list.html',
      controller: 'GroupsCtrl'
    });
    $routeProvider.when('/query_snippets/:snippetId', {
      templateUrl: '/views/query_snippets/show.html',
      controller: 'SnippetCtrl'
    });
    $routeProvider.when('/query_snippets', {
      templateUrl: '/views/query_snippets/list.html',
      controller: 'SnippetsCtrl'
    });
    $routeProvider.when('/', {
      templateUrl: '/views/index.html',
      controller: 'IndexCtrl'
    });
    $routeProvider.when('/personal', {
      redirectTo: '/'
    });
    $routeProvider.otherwise({
      redirectTo: '/'
    });

  }
]);
<|endoftext|>


<commit_before>import React from 'react'
import moment from 'moment'
import {markdown} from 'markdown'
import Person from '../../components/person'
import deindent from 'deindent'

export default Episode

function Episode({episodeData}) {
  const {hangoutUrl, title, date, guests, description} = episodeData
  const time = episodeData.time || '12:00 PM (CT)'
  const dateDisplay = moment(date).format('dddd, MMMM Do, YYYY')
  return (

        {title}

        {dateDisplay} at {time}

        {guests.map((guest, index) => (
          <Person imgSrc={`episodes/${date}/${guest.twitter}.png`} key={index} {...guest} />
        ))}

  )
}

function getDescriptionHTML(description) {
  return {__html: markdown.toHTML(deindent(description))}
}

<commit_msg>Add special text if there's not yet a hangout URL<commit_after>import React from 'react'
import moment from 'moment'
import {markdown} from 'markdown'
import Person from '../../components/person'
import deindent from 'deindent'

export default Episode

function Episode({episodeData}) {
  const {hangoutUrl, title, date, guests, description} = episodeData
  const time = episodeData.time || '12:00 PM (CT)'
  const dateDisplay = moment(date).format('dddd, MMMM Do, YYYY')
  return (

        {getTitle(hangoutUrl, title)}

        {dateDisplay} at {time}

        {guests.map((guest, index) => (
          <Person imgSrc={`episodes/${date}/${guest.twitter}.png`} key={index} {...guest} />
        ))}

  )
}

function getDescriptionHTML(description) {
  return {__html: markdown.toHTML(deindent(description))}
}

function getTitle(hangoutUrl, title) {
  if (hangoutUrl) {
    return {title}
  } else {
    return {title} (hangout url coming soon)
  }
}

<|endoftext|>


<commit_before>/*$.Cow.ConnectWidget = {
init: function(){
var widget = $('#connect');
var cow = $('#cow').data('cow');
cow.events.bind('connected',{}, this._onConnect);
},
_onConnect: function() {
}
}
*/
(function($) {
$.widget("cow.PeersWidget", {
	options: {
        // The cow.core instance
        core: undefined,
		name: '#myname'
    },
 _create: function() {
        var core;
        var self = this;
        var element = this.element;

        core = $(this.options.core).data('cow');
		this.core=core;
        core.bind("ws-connected", {widget: self}, self._onPeerStoreChanged);
		core.bind("ws-disconnected", {widget: self}, self._onPeerStoreChanged);
		core.bind("ws-peerGone", {widget: self}, self._onPeerStoreChanged);
        core.bind("peerStoreChanged" ,{widget: self}, self._onPeerStoreChanged);
        /* SMO: obs? 8/8/13
		core.bind("peerInfo", {widget: self}, self._onPeerInfo);
		core.bind("newPeer", {widget: self}, self._onNewPeer);
		core.bind("peerupdated", {widget: self}, self._onPeerUpdated);
		core.bind("changeHerdRequest", {widget: self}, self._updateList);
        */

		element.delegate('.location','click', function(){
			var owner = $(this).attr('owner');
			var peer = core.getPeerByUid(owner);
			var location = peer.position().point;
            self.core.center({position:location});
			//TODO: extend the Peer object with peer.center()
            //self.core.trigger('zoomToPeerslocationRequest', location);
		});

		element.delegate('.extent','click', function(){
			var owner = $(this).attr('owner');
			var peer = core.getPeerByUid(owner);
			var bbox = peer.view().extent;
			self.core.center({view:bbox});
		});

		//Preliminary peerjs video connection
		element.delegate('.videoconnection','click', function(){
            var owner = $(this).attr('owner');
            $('#videopanel').add("button").on("click",function(e){
                console.log("Closing "  + owner);
                self.peer1.managers[owner].close();
                $('#videopanel').hide();
            });

            $('#videopanel').show();

            mc = self.peer1.call(owner, ls);
            tmp = self.peer1;
            mc.on('stream', function(s){
                window.remote = s;
                  z = $('<video></video>', {src: URL.createObjectURL(s), autoplay: true}).appendTo('#videoplace');
              });

         });

		element.delegate('.herd','click', function(){
			var herd = $(this).attr('herd');
			self.core.trigger('changeHerdRequest', herd);

		});

		$(this.options.name).change(function(){
            self.core.me().owner({"name":$(this).val()});

		});

    },
    _destroy: function() {
        this.element.removeClass('ui-dialog ui-widget ui-widget-content ' +
                                 'ui-corner-all')
            .empty();
    },

	_onPeerStoreChanged: function(evt) {
	console.log('_onNewPeer');
		var self = evt.data.widget;
		self._updateList(evt);
	},

	_updateList: function(evt) {
		var self = evt.data.widget;
		var peers = self.core.peers();
		var herds = self.core.herds();
        var element = self.element;

        var names = '';
		$.each(peers,function(){
			if(this.uid==self.core.UID) {
			names = names+ ''+this.owner().name+'
';
			}
			else {
			names = names+ ''+this.owner().name+'
';
			}
		});
		names = names + "
Herds
";
		$.each(herds,function(){
		    if(this.id==self.core.options.activeHerd) {
		        names = names + ''+this.name+'
';
		    }
		    else {
		        names = names + ''+this.name+'
';
		    }
		});
		element.html(names);

	}
	});
})(jQuery);

<commit_msg>tabs removed<commit_after>/*$.Cow.ConnectWidget = {
init: function(){
var widget = $('#connect');
var cow = $('#cow').data('cow');
cow.events.bind('connected',{}, this._onConnect);
},
_onConnect: function() {
}
}
*/
(function($) {
$.widget("cow.PeersWidget", {
    options: {
        // The cow.core instance
        core: undefined,
        name: '#myname'
    },
 _create: function() {
        var core;
        var self = this;
        var element = this.element;

        core = $(this.options.core).data('cow');
        this.core=core;
        core.bind("ws-connected", {widget: self}, self._onPeerStoreChanged);
        core.bind("ws-disconnected", {widget: self}, self._onPeerStoreChanged);
        core.bind("ws-peerGone", {widget: self}, self._onPeerStoreChanged);
        core.bind("peerStoreChanged" ,{widget: self}, self._onPeerStoreChanged);

        element.delegate('.location','click', function(){
            var owner = $(this).attr('owner');
            var peer = core.getPeerByUid(owner);
            var location = peer.position().point;
            self.core.center({position:location});
        });

        element.delegate('.extent','click', function(){
            var owner = $(this).attr('owner');
            var peer = core.getPeerByUid(owner);
            var bbox = peer.view().extent;
            self.core.center({view:bbox});
        });

        //Preliminary peerjs video connection
        element.delegate('.videoconnection','click', function(){
            var owner = $(this).attr('owner');
            $('#videopanel').add("button").on("click",function(e){
                console.log("Closing "  + owner);
                self.peer1.managers[owner].close();
                $('#videopanel').hide();
            });

            $('#videopanel').show();

            mc = self.peer1.call(owner, ls);
            tmp = self.peer1;
            mc.on('stream', function(s){
                window.remote = s;
                  z = $('<video></video>', {src: URL.createObjectURL(s), autoplay: true}).appendTo('#videoplace');
              });

         });

        element.delegate('.herd','click', function(){
            var herd = $(this).attr('herd');
            self.core.trigger('changeHerdRequest', herd);

        });

        $(this.options.name).change(function(){
            self.core.me().owner({"name":$(this).val()});

        });

    },
    _destroy: function() {
        this.element.removeClass('ui-dialog ui-widget ui-widget-content ' +
                                 'ui-corner-all')
            .empty();
    },

    _onPeerStoreChanged: function(evt) {
    console.log('_onNewPeer');
        var self = evt.data.widget;
        self._updateList(evt);
    },

    _updateList: function(evt) {
        var self = evt.data.widget;
        var peers = self.core.peers();
        var herds = self.core.herds();
        var element = self.element;

        var names = '';
        $.each(peers,function(){
            if(this.uid==self.core.UID) {
            names = names+ ''+this.owner().name+'
';
            }
            else {
            names = names+ ''+this.owner().name+'
';
            }
        });
        names = names + "
Herds
";
        $.each(herds,function(){
            if(this.id==self.core.options.activeHerd) {
                names = names + ''+this.name+'
';
            }
            else {
                names = names + ''+this.name+'
';
            }
        });
        element.html(names);

    }
    });
})(jQuery);

<|endoftext|>


<commit_before>import ndarray from 'ndarray';
import cwise from 'cwise';

// Euclidean distance
let euclidean = cwise({
  args: ['array', 'array'],
  pre: function(a, b) {
    this.sum = 0.0;
  },
  body: function(a, b) {
    var d = a - b;
    this.sum += d * d;
  },
  post: function(a, b) {
    return Math.sqrt(this.sum);
  }
});

// Manhattan distance
let manhattan = cwise({
  args: ['array', 'array'],
  pre: function(a, b) {
    this.sum = 0.0;
  },
  body: function(a, b) {
    this.sum += Math.abs(a - b);
  },
  post: function(a, b) {
    return this.sum;
  }
});

// Jaccard dissimilarity
let jaccard = cwise({
  args: ['array', 'array'],
  pre: function(a, b) {
    this.tf = 0.0;
    this.tt = 0.0;
  },
  body: function(a, b) {
    this.tf += +(a != b);
    this.tt += +(a == 1 && b == 1);
  },
  post: function(a, b) {
    if (this.tf + this.tt === 0) return 1.0;
    return this.tf / (this.tf + this.tt);
  }
});

// Dice dissimilarity
let dice = cwise({
  args: ['array', 'array'],
  pre: function(a, b) {
    this.tf = 0.0;
    this.tt = 0.0;
  },
  body: function(a, b) {
    this.tf += +(a != b);
    this.tt += +(a == 1 && b == 1);
  },
  post: function(a, b) {
    if (this.tf + this.tt === 0) return 1.0;
    return this.tf / (this.tf + 2 * this.tt);
  }
});

export default function(data, metric) {
  let nSamples = data.shape[0];
  let distance = ndarray(new Float64Array(nSamples * nSamples), [nSamples, nSamples]);

  switch (metric) {
    case 'euclidean':
      for (let i = 0; i < nSamples; i++) {
        for (let j = i + 1; j < nSamples; j++) {
          let d = euclidean(data.pick(i, null), data.pick(j, null));
          distance.set(i, j, d);
          distance.set(j, i, d);
        }
      }
      break;
    case 'manhattan':
      for (let i = 0; i < nSamples; i++) {
        for (let j = i + 1; j < nSamples; j++) {
          let d = manhattan(data.pick(i, null), data.pick(j, null));
          distance.set(i, j, d);
          distance.set(j, i, d);
        }
      }
      break;
    case 'jaccard':
      for (let i = 0; i < nSamples; i++) {
        for (let j = i + 1; j < nSamples; j++) {
          let d = jaccard(data.pick(i, null), data.pick(j, null));
          distance.set(i, j, d);
          distance.set(j, i, d);
        }
      }
      break;
    case 'dice':
      for (let i = 0; i < nSamples; i++) {
        for (let j = i + 1; j < nSamples; j++) {
          let d = dice(data.pick(i, null), data.pick(j, null));
          distance.set(i, j, d);
          distance.set(j, i, d);
        }
      }
      break;
    default:
  }

  return distance;
}
<commit_msg>fix jaccard and dice dissimilarity for non-boolean<commit_after>import ndarray from 'ndarray';
import cwise from 'cwise';

// Euclidean distance
let euclidean = cwise({
  args: ['array', 'array'],
  pre: function(a, b) {
    this.sum = 0.0;
  },
  body: function(a, b) {
    var d = a - b;
    this.sum += d * d;
  },
  post: function(a, b) {
    return Math.sqrt(this.sum);
  }
});

// Manhattan distance
let manhattan = cwise({
  args: ['array', 'array'],
  pre: function(a, b) {
    this.sum = 0.0;
  },
  body: function(a, b) {
    this.sum += Math.abs(a - b);
  },
  post: function(a, b) {
    return this.sum;
  }
});

// Jaccard dissimilarity
let jaccard = cwise({
  args: ['array', 'array'],
  pre: function(a, b) {
    this.tf = 0.0;
    this.tt = 0.0;
  },
  body: function(a, b) {
    var a_bool = Math.round(a);
    var b_bool = Math.round(b);
    this.tf += +(a_bool != b_bool);
    this.tt += +(a_bool == 1 && b_bool == 1);
  },
  post: function(a, b) {
    if (this.tf + this.tt === 0) return 1.0;
    return this.tf / (this.tf + this.tt);
  }
});

// Dice dissimilarity
let dice = cwise({
  args: ['array', 'array'],
  pre: function(a, b) {
    this.tf = 0.0;
    this.tt = 0.0;
  },
  body: function(a, b) {
    var a_bool = Math.round(a);
    var b_bool = Math.round(b);
    this.tf += +(a_bool != b_bool);
    this.tt += +(a_bool == 1 && b_bool == 1);
  },
  post: function(a, b) {
    if (this.tf + this.tt === 0) return 1.0;
    return this.tf / (this.tf + 2 * this.tt);
  }
});

export default function(data, metric) {
  let nSamples = data.shape[0];
  let distance = ndarray(new Float64Array(nSamples * nSamples), [nSamples, nSamples]);

  switch (metric) {
    case 'euclidean':
      for (let i = 0; i < nSamples; i++) {
        for (let j = i + 1; j < nSamples; j++) {
          let d = euclidean(data.pick(i, null), data.pick(j, null));
          distance.set(i, j, d);
          distance.set(j, i, d);
        }
      }
      break;
    case 'manhattan':
      for (let i = 0; i < nSamples; i++) {
        for (let j = i + 1; j < nSamples; j++) {
          let d = manhattan(data.pick(i, null), data.pick(j, null));
          distance.set(i, j, d);
          distance.set(j, i, d);
        }
      }
      break;
    case 'jaccard':
      for (let i = 0; i < nSamples; i++) {
        for (let j = i + 1; j < nSamples; j++) {
          let d = jaccard(data.pick(i, null), data.pick(j, null));
          distance.set(i, j, d);
          distance.set(j, i, d);
        }
      }
      break;
    case 'dice':
      for (let i = 0; i < nSamples; i++) {
        for (let j = i + 1; j < nSamples; j++) {
          let d = dice(data.pick(i, null), data.pick(j, null));
          distance.set(i, j, d);
          distance.set(j, i, d);
        }
      }
      break;
    default:
  }

  return distance;
}
<|endoftext|>


<commit_before>//check if browser supports file api and filereader features
// if (window.File && window.FileReader && window.FileList && window.Blob) {

	var fileSelect = document.getElementById("fileSelect"),
	  fileElem = document.getElementById("fileElem");

	fileSelect.addEventListener("click", function (e) {
	  if (fileElem) {
	    fileElem.click();
	  }
	  e.preventDefault();
	}, false);

// to show images as thumbnails in div

	function handleFiles(files) {
  for (var i = 0; i < files.length; i++) {
    var file = files[i];

    if (!file.type.startsWith('image/')){ continue }

			// img is draggable once loaded so needs this - draggable="true" ondragstart="drag(event)"
    var img = document.createElement("img");
		// img.ondragstart = drag(event);
    img.classList.add("obj");
		// img.setAttribute("id", "drag-img");
		// img.setAttribute("draggable", "true");
    img.file = file;
       // Assuming that "preview" is the div output where the content will be displayed.
		var preview = document.getElementById("preview");
		preview.appendChild(img);

    var reader = new FileReader();
    reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
    reader.readAsDataURL(file);
  }
}
// function drag(ev) {
//     ev.dataTransfer.setData("text/uri-list", ev.target.id);
// }
// else{
// 	alert('your browser does not support the html5 file api')
// }
// }
<commit_msg>add img src to arr<commit_after>//check if browser supports file api and filereader features
// if (window.File && window.FileReader && window.FileList && window.Blob) {

	var fileSelect = document.getElementById("fileSelect"),
	  fileElem = document.getElementById("fileElem");

	fileSelect.addEventListener("click", function (e) {
	  if (fileElem) {
	    fileElem.click();
	  }
	  e.preventDefault();
	}, false);

// to show images as thumbnails in div

	function handleFiles(files) {
  for (var i = 0; i < files.length; i++) {
    var file = files[i];

    if (!file.type.startsWith('image/')){ continue }

			// img is draggable once loaded so needs this - draggable="true" ondragstart="drag(event)"
    var img = document.createElement("img");
		// img.ondragstart = drag(event);
    img.classList.add("obj");
		// img.setAttribute("id", "drag-img");
		// img.setAttribute("draggable", "true");
    img.file = file;
       // Assuming that "preview" is the div output where the content will be displayed.
		var preview = document.getElementById("preview");
		preview.appendChild(img);

    var reader = new FileReader();
    reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
    reader.readAsDataURL(file);

    // create an array to hold image data src
		var imageArr = [];
		for(i =0; i < img.length; i++){
			imageArr.push[i];
			console.log(imageArr);
		}

  }
}
// function drag(ev) {
//     ev.dataTransfer.setData("text/uri-list", ev.target.id);
// }
// else{
// 	alert('your browser does not support the html5 file api')
// }
// }
<|endoftext|>