<commit_before>/**
 * cardData
 * Created by dcorns on 9/13/15
 * Copyright © 2015 Dale Corns
 * Define points and scoring card structures
 * Cards are two pinochle decks without nines. 1 - 80 represent all cards like so (jack-Ace) * 4 in spades followed by clubs, diamonds and hearts
 */
'use strict';

var cardData = {
  jacksAround: {
    points: 4,
    checkCard: function(meld, card){
      var jacks = [1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76];

    }
  },
  queensAround: {
    points: 6
  },
  kingsAround: {
    points: 8
  },
  acesAround: {
    points: 10
  },
  pinochle: {
    points: 4
  },
  pinochle2: {
    points: 30
  },
  pinochle3: {
    points: 90
  },
  pinochle4: {
    points: 500
  },
  marriage: {
    points: 2
  },
  roundRobin: {
    points: 24
  },
  runn: {
    points: 15
  },
  scoreAround: function(hand, basePosition, basePoints) {
    var c = 0,
      clubs = basePosition + 20,
      diamonds = basePosition + 40,
      hearts = basePosition + 60,
      len = hand.length,
      points = 0;
    var spadeCount = 0, clubsCount = 0, diamondsCount = 0, heartsCount = 0;
    for (c; c < len; c++) {
      if (hand[c] === basePosition || hand[c] === basePosition + 5 || hand[c] === basePosition + 10 || hand[c] === basePosition + 15) {
        spadeCount++;
      }
      else if (hand[c] === clubs || hand[c] === clubs + 5 || hand[c] === clubs + 10 || hand[c] === clubs + 15) {
        clubsCount++;
      }
      else if (hand[c] === diamonds || hand[c] === diamonds + 5 || hand[c] === diamonds + 10 || hand[c] === diamonds + 15) {
        diamondsCount++;
      }
      else if (hand[c] === hearts || hand[c] === hearts + 5 || hand[c] === hearts + 10 || hand[c] === hearts + 15) {
        heartsCount++;
      }
    }
    if (spadeCount > 0 && clubsCount > 0 && diamondsCount > 0 && heartsCount > 0) {
      points = basePoints;
      if (spadeCount > 1 && clubsCount > 1 && diamondsCount > 1 && heartsCount > 1) {
        points = basePoints * 10;
      }
    }
    return points;
  },
  scorePinochle: function(hand){

  },
  assignHand: function(hand){
    var meld = {total: 0},
      c = 0,
      len = hand.length;
    for(c; c < len; c++){

    }
  }
};
module.exports = cardData;
<commit_msg>save place<commit_after>/**
 * cardData
 * Created by dcorns on 9/13/15
 * Copyright © 2015 Dale Corns
 * Define points and scoring card structures
 * Cards are two pinochle decks without nines. 1 - 80 represent all cards like so (jack-Ace) * 4 in spades followed by clubs, diamonds and hearts
 */
'use strict';

function Meld(hand){
  this.hand = hand;
  this.len = hand.length;
  this.jacks = [];
}
Meld.prototype.recordJacks = function(){
  var ints = [1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76],
    c = 0;
  for(c; c < this.len; c++){
    if(this.hand[c] === 1 || this.hand[c] === 21 || this.hand[c] === 41 || this.hand[c] === 61) this.jacks[0] = this.hand[c];
  }
};<|endoftext|>


<commit_before>'use strict';

// modules dependencies
var mongoat = require('../../index');

var _this;
var id;

// test update method
describe('Versioning', function () {
  // connect to db before all tests
  beforeAll(function (done) {
    _this = this;

    mongoat.MongoClient.connect('mongodb://localhost:27017/mongoatTest')
    .then(function (db) {
      _this.testDb = db;
      return db.dropDatabase();
    })
    .then(function () {
      _this.testCol = _this.testDb.collection('Person.verioning');
      _this.testCol.datetime(true);
      _this.testCol.version(true);

      // add before update hooks
      _this.testCol.before('update', function (object) {
        expect(typeof object).toBe('object');
        return object;
      });

      _this.testCol.before('update', function (object) {
        expect(typeof object).toBe('object');
        return object;
      });

      // add after update hooks
      _this.testCol.after('update', function (object) {
        expect(typeof object).toBe('object');
        return object;
      });

      _this.testCol.after('update', function (object) {
        expect(typeof object).toBe('object');
        return object;
      });
    })
    .then(done);
  });

  // close db after all tests
  afterAll(function (done) {
    _this.testCol = _this.testDb.collection('Person.verioning.vermongo');
    _this.testCol.find().toArray()
    .then(function (mongoArray) {
      expect(mongoArray.length).toBe(7);
    })
    .then(function () {
      _this.testDb.dropDatabase();
    })
    .then(function () {
      _this.testDb.close();
    })
    .then(done);
  });

  // test restore
  it('should throw error, because of id undefined', function (done) {
    try {
      _this.testCol.restore();
    } catch(err) {
      expect(err.message).toBe('The provided id is null or undefined');
      done();
    }
  });

  // test insert
  it('should insert new document to collection', function (done) {
    _this.testCol.insert({
      firstName: 'Yacine',
      lastName: 'KHATAL',
      age: 25
    })
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(typeof mongObject.result).toBe('object');
      expect(mongObject.result.ok).toBe(1);
      expect(mongObject.result.n).toBe(1);
      id = mongObject.ops[0]._id;
    })
    .then(done);
  });

  // test upsert
  it('should upsert new document to collection', function (done) {
    _this.testCol.update(
      { firstName: 'Hichem' },
      { $setOnInsert: { lastName: 'KHATAL', age: 28 } },
      { upsert: true }
    )
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(typeof mongObject.result).toBe('object');
      expect(mongObject.result.ok).toBe(1);
      expect(mongObject.result.n).toBe(1);
      expect(mongObject.result.nModified).toBe(0);
    })
    .then(done);
  });

  // test update
  it('should update document from collection', function (done) {
    _this.testCol.update(
      { firstName: 'Yacine' },
      { $set: { age: 30, company: 'Dial Once' } }
    )
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(typeof mongObject.result).toBe('object');
      expect(mongObject.result.ok).toBe(1);
      expect(mongObject.result.n).toBe(1);
      expect(mongObject.result.nModified).toBe(1);
    })
    .then(done);
  });

  // test update
  it('should update document from collection', function (done) {
    _this.testCol.update(
      { firstName: 'Yacine' },
      { $set: { age: 35, job: 'software engineer' } }
    )
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(typeof mongObject.result).toBe('object');
      expect(mongObject.result.ok).toBe(1);
      expect(mongObject.result.n).toBe(1);
      expect(mongObject.result.nModified).toBe(1);
    })
    .then(done);
  });

  // test restore
  it('should throw error', function (done) {
    _this.testCol.restore(id, -7)
    .catch(function (err) {
      expect(err.message).toBe('The requested version doesn\'t exist');
    })
    .then(done);
  });

  // test restore
  it('should restore version 2 document by version', function (done) {
    _this.testCol.restore(id, 2)
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(mongObject.firstName).toBe('Yacine');
      expect(mongObject.lastName).toBe('KHATAL');
      expect(mongObject.age).toBe(30);
      expect(mongObject.company).toBe('Dial Once');
      expect(mongObject.job).toBeUndefined();
      expect(mongObject._version).toBe(4);
    })
    .then(done);
  });

  // test restore
  it('should restore version 3 document by version', function (done) {
    _this.testCol.restore(id, 3)
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(mongObject.firstName).toBe('Yacine');
      expect(mongObject.lastName).toBe('KHATAL');
      expect(mongObject.age).toBe(35);
      expect(mongObject.job).toBe('software engineer');
      expect(mongObject.company).toBe('Dial Once');
      expect(mongObject._version).toBe(5);
    })
    .then(done);
  });

  // test restore
  it('should restore last version of the document by version', function (done) {
    _this.testCol.restore(id, 0)
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(mongObject.firstName).toBe('Yacine');
      expect(mongObject.lastName).toBe('KHATAL');
      expect(mongObject.age).toBe(30);
      expect(mongObject.company).toBe('Dial Once');
      expect(mongObject.job).toBeUndefined();
      expect(mongObject._version).toBe(6);
    })
    .then(done);
  });

  // test restore
  it('should restore version -2 of the document by version', function (done) {
    _this.testCol.restore(id, -4)
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(mongObject.firstName).toBe('Yacine');
      expect(mongObject.lastName).toBe('KHATAL');
      expect(mongObject.age).toBe(25);
      expect(mongObject.job).toBeUndefined();
      expect(mongObject.company).toBeUndefined();
      expect(mongObject._version).toBe(7);
    })
    .then(done);
  });

  // test remove
  it('should remove document from collection', function (done) {
    _this.testCol.remove({ firstName: 'Yacine' })
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(typeof mongObject.result).toBe('object');
      expect(mongObject.result.ok).toBe(1);
      expect(mongObject.result.n).toBe(1);
    })
    .then(done);
  });

  // test restore
  it('should restore lest version', function (done) {
    _this.testCol.restore(id)
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(mongObject.firstName).toBe('Yacine');
      expect(mongObject.lastName).toBe('KHATAL');
      expect(mongObject.age).toBe(25);
      expect(mongObject.job).toBeUndefined();
      expect(mongObject.company).toBeUndefined();
      expect(mongObject._version).toBe(8);
    })
    .then(done);
  });
});
<commit_msg>Enhance test message<commit_after>'use strict';

// modules dependencies
var mongoat = require('../../index');

var _this;
var id;

// test update method
describe('Versioning', function () {
  // connect to db before all tests
  beforeAll(function (done) {
    _this = this;

    mongoat.MongoClient.connect('mongodb://localhost:27017/mongoatTest')
    .then(function (db) {
      _this.testDb = db;
      return db.dropDatabase();
    })
    .then(function () {
      _this.testCol = _this.testDb.collection('Person.verioning');
      _this.testCol.datetime(true);
      _this.testCol.version(true);

      // add before update hooks
      _this.testCol.before('update', function (object) {
        expect(typeof object).toBe('object');
        return object;
      });

      _this.testCol.before('update', function (object) {
        expect(typeof object).toBe('object');
        return object;
      });

      // add after update hooks
      _this.testCol.after('update', function (object) {
        expect(typeof object).toBe('object');
        return object;
      });

      _this.testCol.after('update', function (object) {
        expect(typeof object).toBe('object');
        return object;
      });
    })
    .then(done);
  });

  // close db after all tests
  afterAll(function (done) {
    _this.testCol = _this.testDb.collection('Person.verioning.vermongo');
    _this.testCol.find().toArray()
    .then(function (mongoArray) {
      expect(mongoArray.length).toBe(7);
    })
    .then(function () {
      _this.testDb.dropDatabase();
    })
    .then(function () {
      _this.testDb.close();
    })
    .then(done);
  });

  // test restore
  it('should throw error, because of id undefined', function (done) {
    try {
      _this.testCol.restore();
    } catch(err) {
      expect(err.message).toBe('The provided id is null or undefined');
      done();
    }
  });

  // test insert
  it('should insert new document to collection', function (done) {
    _this.testCol.insert({
      firstName: 'Yacine',
      lastName: 'KHATAL',
      age: 25
    })
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(typeof mongObject.result).toBe('object');
      expect(mongObject.result.ok).toBe(1);
      expect(mongObject.result.n).toBe(1);
      id = mongObject.ops[0]._id;
    })
    .then(done);
  });

  // test upsert
  it('should upsert new document to collection', function (done) {
    _this.testCol.update(
      { firstName: 'Hichem' },
      { $setOnInsert: { lastName: 'KHATAL', age: 28 } },
      { upsert: true }
    )
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(typeof mongObject.result).toBe('object');
      expect(mongObject.result.ok).toBe(1);
      expect(mongObject.result.n).toBe(1);
      expect(mongObject.result.nModified).toBe(0);
    })
    .then(done);
  });

  // test update
  it('should update document from collection', function (done) {
    _this.testCol.update(
      { firstName: 'Yacine' },
      { $set: { age: 30, company: 'Dial Once' } }
    )
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(typeof mongObject.result).toBe('object');
      expect(mongObject.result.ok).toBe(1);
      expect(mongObject.result.n).toBe(1);
      expect(mongObject.result.nModified).toBe(1);
    })
    .then(done);
  });

  // test update
  it('should update document from collection', function (done) {
    _this.testCol.update(
      { firstName: 'Yacine' },
      { $set: { age: 35, job: 'software engineer' } }
    )
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(typeof mongObject.result).toBe('object');
      expect(mongObject.result.ok).toBe(1);
      expect(mongObject.result.n).toBe(1);
      expect(mongObject.result.nModified).toBe(1);
    })
    .then(done);
  });

  // test restore
  it('should throw error', function (done) {
    _this.testCol.restore(id, -7)
    .catch(function (err) {
      expect(err.message).toBe('The requested version doesn\'t exist');
    })
    .then(done);
  });

  // test restore
  it('should restore version 2 of the document by version and id', function (done) {
    _this.testCol.restore(id, 2)
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(mongObject.firstName).toBe('Yacine');
      expect(mongObject.lastName).toBe('KHATAL');
      expect(mongObject.age).toBe(30);
      expect(mongObject.company).toBe('Dial Once');
      expect(mongObject.job).toBeUndefined();
      expect(mongObject._version).toBe(4);
    })
    .then(done);
  });

  // test restore
  it('should restore version 3 of the document by version and id', function (done) {
    _this.testCol.restore(id, 3)
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(mongObject.firstName).toBe('Yacine');
      expect(mongObject.lastName).toBe('KHATAL');
      expect(mongObject.age).toBe(35);
      expect(mongObject.job).toBe('software engineer');
      expect(mongObject.company).toBe('Dial Once');
      expect(mongObject._version).toBe(5);
    })
    .then(done);
  });

  // test restore
  it('should restore last version of the document by version and id', function (done) {
    _this.testCol.restore(id, 0)
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(mongObject.firstName).toBe('Yacine');
      expect(mongObject.lastName).toBe('KHATAL');
      expect(mongObject.age).toBe(30);
      expect(mongObject.company).toBe('Dial Once');
      expect(mongObject.job).toBeUndefined();
      expect(mongObject._version).toBe(6);
    })
    .then(done);
  });

  // test restore
  it('should restore version -2 of the document by version and id', function (done) {
    _this.testCol.restore(id, -4)
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(mongObject.firstName).toBe('Yacine');
      expect(mongObject.lastName).toBe('KHATAL');
      expect(mongObject.age).toBe(25);
      expect(mongObject.job).toBeUndefined();
      expect(mongObject.company).toBeUndefined();
      expect(mongObject._version).toBe(7);
    })
    .then(done);
  });

  // test remove
  it('should remove document from collection', function (done) {
    _this.testCol.remove({ firstName: 'Yacine' })
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(typeof mongObject.result).toBe('object');
      expect(mongObject.result.ok).toBe(1);
      expect(mongObject.result.n).toBe(1);
    })
    .then(done);
  });

  // test restore
  it('should restore last version of the document by id', function (done) {
    _this.testCol.restore(id)
    .then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(mongObject.firstName).toBe('Yacine');
      expect(mongObject.lastName).toBe('KHATAL');
      expect(mongObject.age).toBe(25);
      expect(mongObject.job).toBeUndefined();
      expect(mongObject.company).toBeUndefined();
      expect(mongObject._version).toBe(8);
    })
    .then(done);
  });
});
<|endoftext|>


<commit_before>function customSymbol(node, nodeSize) {
	size = nodeSize;

	// DEFINE A COUPLE OF CUSTOM SYMBOLS
	var reactionSize = nodeSize * .3;
	var emptySize = nodeSize * 0.4;

	var reaction =
		"m -" + reactionSize * 0.5 + " -" + reactionSize * 0.5 +
		" h " + reactionSize +
		" v " + reactionSize +
		" h -" + reactionSize +
		" z ";

	var dissociation =
		"m -" + size * 0.5 + " -" + size * 0.5 +
		" m -" + size * 0.5 + " " + size * 0.5 +
		" a " + size + " " + size + " 0 1 0 " + size * 2 + " 0" +
		" a " + size + " " + size + " 0 1 0 -" + size * 2 + " 0" +
		" m " + size * 0.3 + " 0" +
		" a " + size * 0.7 + " " + size * 0.7 + " 0 1 0 " + size * 0.7 * 2 + " 0" +
		" a " + size * 0.7 + " " + size * 0.7 + " 0 1 0 -" + size * 0.7 * 2 + " 0" +
		" m -" + size * 0.3 + " 0" +
		" h -" + size / 2 +
		" m " + size * 3 + " 0" +
		" h -" + size / 2;

	var association =
		"m -" + size * 0.5 + " -" + size * 0.5 +
		" m -" + size * 0.5 + " " + size * 0.5 +
		" a " + size + " " + size + " 0 1 0 " + size * 2 + " 0" +
		" a " + size + " " + size + " 0 1 0 -" + size * 2 + " 0" +
		" h -" + size / 2 +
		" m " + size * 3 + " 0" +
		" h -" + size / 2;

	var macromolecule =
		"m -" + size * 0.8 + " -" + size * 0.3 +
		" a " + size * 0.1 + " " + size * 0.1 + " 0 0 1 " + size * 0.1 + " " + -size * 0.1 +
		" l " + size * 1.4 + " 0" +
		" a " + size * 0.1 + " " + size * 0.1 + " 0 0 1 " + size * 0.1 + " " + size * 0.1 +
		" l 0 " + size * 0.6 +
		" a " + size * 0.1 + " " + size * 0.1 + " 0 0 1 " + -size * 0.1 + " " + size * 0.1 +
		" l " + -size * 1.4 + " 0" +
		" a " + size * 0.1 + " " + size * 0.1 + " 0 0 1 " + -size * 0.1 + " " + -size * 0.1 +
		" z ";

	var nucleicAcidFeature =
		"m -" + size * 0.8 + " -" + size * 0.3 +
		" l " + size * 1.5 + " 0" +
		" l 0 " + size * 0.6 +
		" a " + size * 0.1 + " " + size * 0.1 + " 0 0 1 " + -size * 0.1 + " " + size * 0.1 +
		" l " + -size * 1.5 + " 0" +
		" a " + size * 0.1 + " " + size * 0.1 + " 0 0 1 " + -size * 0.1 + " " + -size * 0.1 +
		" z ";

	var macromoleculeMultimer =
		"m -" + size * 0.5 + " -" + size * 0.5 +
		" m " + size * 0.1 + " 0" +
		" a " + size * 0.1 + " " + size * 0.1 + " " + size * 0.02 + " 0 0 -" + size * 0.1 + " " + size * 0.1 +
		" l 0 " + size * 0.8 +
		" a " + size * 0.1 + " " + size * 0.1 + " " + size * 0.02 + " 0 0 " + size * 0.1 + " " + size * 0.1 +
		" l " + size * 0.8 + " 0" +
		" a " + size * 0.1 + " " + size * 0.1 + " " + size * 0.02 + " 0 0 " + size * 0.1 + " -" + size * 0.1 +
		" l 0 -" + size * 0.8 +
		" a " + size * 0.1 + " " + size * 0.1 + " " + size * 0.02 + " 0 0 -" + size * 0.1 + " -" + size * 0.1 +
		" l " + size * -0.8 + " 0" +
		" m " + size * 0.9 + " " + size * 0.1;

	var unspecifiedEntity =
		"m -" + size + " -" + size * 0 +
		" a " + size * 0.5 + " " + size + " -90 0 1 " + size * 2 + " 0" +
		" a " + size * 0.5 + " " + size + " -90 0 1 -" + size * 2 + " 0";

	var sourceAndSink =
		"m -" + emptySize * 0.5 + " -" + emptySize * 0.5 +
		" m -" + emptySize * 0.5 + " " + emptySize * 0.5 +
		" a " + emptySize + " " + emptySize + " 0 1 0 " + emptySize * 2 + " 0" +
		" a " + emptySize + " " + emptySize + " 0 1 0 -" + emptySize * 2 + " 0" +
		" m 0 " + emptySize +
		" l " + 2 * emptySize + " -" + 2 * emptySize;

	var complex =
		"m -" + size * 0.5 + " -" + size * 0.5 +
		" m " + size * 0.25 + " 0" +
		" l " + size * 0.5 + " 0" +
		" l " + size * 0.25 + " " + size * 0.25 +
		" l 0 " + size * 0.5 +
		" l -" + size * 0.25 + " " + size * 0.25 +
		" l -" + size * 0.5 + " 0" +
		" l -" + size * 0.25 + " -" + size * 0.25 +
		" l 0 -" + size * 0.5 +
		" z ";

	var perturbingAgent =
		"m -" + size * 0.5 + " -" + size * 0.5 +
		" l " + size + " 0" +
		" l -" + size * 0.125 + " " + size * 0.5 +
		" l " + size * 0.125 + " " + size * 0.5 +
		" l -" + size + " " + " 0" +
		" l " + size * 0.125 + " -" + size * 0.5 +
		" z ";

	var simpleChemical =
		"m -" + size / 2 + " 0" +
		" a " + size / 2 + " " + size / 2 + " 0 1 0 " + size + " 0" +
		" a " + size / 2 + " " + size / 2 + " 0 1 0 -" + size + " 0";

	var simpleChemicalMulti =
		"m -" + size / 2 + " 0" +
		" a " + size / 2 + " " + size / 2 + " 0 1 0 " + size + " 0" +
		" a " + size / 2 + " " + size / 2 + " 0 1 0 -" + size + " 0" +
		" m " + size / 8.69565 + " " + size / 3.125 +
		" a " + size / 2 + " " + size / 2 + " 0 1 0 " + size * 0.9 + " " + -size / 2 +
		" a " + size / 2 + " " + size / 2 + " 0 0 0 " + -size / 6.6667 + " " + -size / 6.25; //+
	//" a " + size / 2 + " " + size / 2 + " 0 1 0 " + 7 * size / 8 + " -" + size / 2; // +
	//" a " + size / 2 + " " + size / 2 + " 0 1 0 -" + size + " 0";

	var missingNode =
		"m -" + size * 0.5 + " -" + size * 0.5 +
		"l " + size + " " + size +
		"m -" + size + " 0" +
		"l " + size + " -" + size;

	switch (node) {
		case 'simple chemical':
			return simpleChemical;
			break;
		case 'reaction':
		case 'process':
			return reaction;
			break;
		case 'dissociation':
			return dissociation;
			break;
		case 'association':
			return association;
			break;
		case 'macromolecule':
			return macromolecule;
			break;
		case 'nucleic acid feature':
			return nucleicAcidFeature;
			break;
		case 'unspecified entity':
			return unspecifiedEntity;
			break;
		case 'source and sink':
			return sourceAndSink;
			break;
		case 'complex':
			return complex;
			break;
		case 'perturbing agent':
			return perturbingAgent;
			break;
		case 'simple chemical multimer':
			return simpleChemicalMulti;
			break;
		default:
			console.log("missing node: " + node);
			return missingNode;

	}

}

/*  'process': reactionLayout,
  'production': reactionLayout,
  'consumption': reactionLayout,
  'modulation': reactionLayout,
  'stimulation': reactionLayout,
  'catalysis': reactionLayout,
  'necessary stimulation': reactionLayout,
*/<commit_msg>Update customSymbol.js<commit_after>function customSymbol(node, nodeSize) {
	size = nodeSize;

	// DEFINE A COUPLE OF CUSTOM SYMBOLS
	var reactionSize = nodeSize * .3;
	var emptySize = nodeSize * 0.4;

	var reaction =
		"m -" + reactionSize * 0.5 + " -" + reactionSize * 0.5 +
		" h " + reactionSize +
		" v " + reactionSize +
		" h -" + reactionSize +
		" z ";

	var dissociation =
		"m -" + size * 0.5 + " -" + size * 0.5 +
		" m -" + size * 0.5 + " " + size * 0.5 +
		" a " + size + " " + size + " 0 1 0 " + size * 2 + " 0" +
		" a " + size + " " + size + " 0 1 0 -" + size * 2 + " 0" +
		" m " + size * 0.3 + " 0" +
		" a " + size * 0.7 + " " + size * 0.7 + " 0 1 0 " + size * 0.7 * 2 + " 0" +
		" a " + size * 0.7 + " " + size * 0.7 + " 0 1 0 -" + size * 0.7 * 2 + " 0" +
		" m -" + size * 0.3 + " 0" +
		" h -" + size / 2 +
		" m " + size * 3 + " 0" +
		" h -" + size / 2;

	var association =
		"m -" + size * 0.5 + " -" + size * 0.5 +
		" m -" + size * 0.5 + " " + size * 0.5 +
		" a " + size + " " + size + " 0 1 0 " + size * 2 + " 0" +
		" a " + size + " " + size + " 0 1 0 -" + size * 2 + " 0" +
		" h -" + size / 2 +
		" m " + size * 3 + " 0" +
		" h -" + size / 2;

	var macromolecule =
		"m -" + size * 0.8 + " -" + size * 0.3 +
		" a " + size * 0.1 + " " + size * 0.1 + " 0 0 1 " + size * 0.1 + " " + -size * 0.1 +
		" l " + size * 1.4 + " 0" +
		" a " + size * 0.1 + " " + size * 0.1 + " 0 0 1 " + size * 0.1 + " " + size * 0.1 +
		" l 0 " + size * 0.6 +
		" a " + size * 0.1 + " " + size * 0.1 + " 0 0 1 " + -size * 0.1 + " " + size * 0.1 +
		" l " + -size * 1.4 + " 0" +
		" a " + size * 0.1 + " " + size * 0.1 + " 0 0 1 " + -size * 0.1 + " " + -size * 0.1 +
		" z ";

	var nucleicAcidFeature =
		"m -" + size + " -" + size * 0.4 +
		" l " + size * 1.5 + " 0" +
		" l 0 " + size * 0.6 +
		" a " + size * 0.1 + " " + size * 0.1 + " 0 0 1 " + -size * 0.1 + " " + size * 0.1 +
		" l " + -size * 1.5 + " 0" +
		" a " + size * 0.1 + " " + size * 0.1 + " 0 0 1 " + -size * 0.1 + " " + -size * 0.1 +
		" z ";

	var nucleicAcidFeatureMultimer =
		"m -" + size * 0.75 + " -" + size * 0.4 +
		" l " + size * 1.5 + " 0" +
		" l 0 " + size * 0.6 +
		" a " + size * 0.1 + " " + size * 0.1 + " 0 0 1 " + -size * 0.1 + " " + size * 0.1 +
		" l " + -size * 1.3 + " 0" +
		" a " + size * 0.1 + " " + size * 0.1 + " 0 0 1 " + -size * 0.1 + " " + -size * 0.1 +
		" z " +
		" m " + 1.5 * size + " " + 0.1 * size +
		" l " + size * 0.1 + " 0" +
		" l 0 " + size * 0.6 +
		" a " + size * 0.1 + " " + size * 0.1 + " 0 0 1 " + -size * 0.1 + " " + size * 0.1 +
		" l " + -size * 1.3 + " 0" +
		" a " + size * 0.1 + " " + size * 0.1 + " 0 0 1 " + -size * 0.1 + " " + -size * 0.1;

	var macromoleculeMultimer =
		"m -" + size * 0.5 + " -" + size * 0.5 +
		" m " + size * 0.1 + " 0" +
		" a " + size * 0.1 + " " + size * 0.1 + " " + size * 0.02 + " 0 0 -" + size * 0.1 + " " + size * 0.1 +
		" l 0 " + size * 0.8 +
		" a " + size * 0.1 + " " + size * 0.1 + " " + size * 0.02 + " 0 0 " + size * 0.1 + " " + size * 0.1 +
		" l " + size * 0.8 + " 0" +
		" a " + size * 0.1 + " " + size * 0.1 + " " + size * 0.02 + " 0 0 " + size * 0.1 + " -" + size * 0.1 +
		" l 0 -" + size * 0.8 +
		" a " + size * 0.1 + " " + size * 0.1 + " " + size * 0.02 + " 0 0 -" + size * 0.1 + " -" + size * 0.1 +
		" l " + size * -0.8 + " 0" +
		" m " + size * 0.9 + " " + size * 0.1;

	var unspecifiedEntity =
		"m -" + size + " -" + size * 0 +
		" a " + size * 0.5 + " " + size + " -90 0 1 " + size * 2 + " 0" +
		" a " + size * 0.5 + " " + size + " -90 0 1 -" + size * 2 + " 0";

	var sourceAndSink =
		"m -" + emptySize * 0.5 + " -" + emptySize * 0.5 +
		" m -" + emptySize * 0.5 + " " + emptySize * 0.5 +
		" a " + emptySize + " " + emptySize + " 0 1 0 " + emptySize * 2 + " 0" +
		" a " + emptySize + " " + emptySize + " 0 1 0 -" + emptySize * 2 + " 0" +
		" m 0 " + emptySize +
		" l " + 2 * emptySize + " -" + 2 * emptySize;

	var complex =
		"m -" + size * 0.5 + " -" + size * 0.5 +
		" m " + size * 0.25 + " 0" +
		" l " + size * 0.5 + " 0" +
		" l " + size * 0.25 + " " + size * 0.25 +
		" l 0 " + size * 0.5 +
		" l -" + size * 0.25 + " " + size * 0.25 +
		" l -" + size * 0.5 + " 0" +
		" l -" + size * 0.25 + " -" + size * 0.25 +
		" l 0 -" + size * 0.5 +
		" z ";

	var perturbingAgent =
		"m -" + size * 0.5 + " -" + size * 0.5 +
		" l " + size + " 0" +
		" l -" + size * 0.125 + " " + size * 0.5 +
		" l " + size * 0.125 + " " + size * 0.5 +
		" l -" + size + " " + " 0" +
		" l " + size * 0.125 + " -" + size * 0.5 +
		" z ";

	var simpleChemical =
		"m -" + size / 2 + " 0" +
		" a " + size / 2 + " " + size / 2 + " 0 1 0 " + size + " 0" +
		" a " + size / 2 + " " + size / 2 + " 0 1 0 -" + size + " 0";

	var simpleChemicalMulti =
		"m -" + size / 2 + " 0" +
		" a " + size / 2 + " " + size / 2 + " 0 1 0 " + size + " 0" +
		" a " + size / 2 + " " + size / 2 + " 0 1 0 -" + size + " 0" +
		" m " + size / 8.69565 + " " + size / 3.125 +
		" a " + size / 2 + " " + size / 2 + " 0 1 0 " + size * 0.9 + " " + -size / 2 +
		" a " + size / 2 + " " + size / 2 + " 0 0 0 " + -size / 6.6667 + " " + -size / 6.25; //+
	//" a " + size / 2 + " " + size / 2 + " 0 1 0 " + 7 * size / 8 + " -" + size / 2; // +
	//" a " + size / 2 + " " + size / 2 + " 0 1 0 -" + size + " 0";

	var missingNode =
		"m -" + size * 0.5 + " -" + size * 0.5 +
		"l " + size + " " + size +
		"m -" + size + " 0" +
		"l " + size + " -" + size;

	switch (node) {
		case 'simple chemical':
			return simpleChemical;
			break;
		case 'reaction':
		case 'process':
			return reaction;
			break;
		case 'dissociation':
			return dissociation;
			break;
		case 'association':
			return association;
			break;
		case 'macromolecule':
			return macromolecule;
			break;
		case 'nucleic acid feature':
			return nucleicAcidFeature;
			break;
		case 'unspecified entity':
			return unspecifiedEntity;
			break;
		case 'source and sink':
			return sourceAndSink;
			break;
		case 'complex':
			return complex;
			break;
		case 'perturbing agent':
			return perturbingAgent;
			break;
		case 'simple chemical multimer':
			return simpleChemicalMulti;
			break;
		case 'nucleic acid feature multimer':
			return nucleicAcidFeatureMultimer;
			break;
		default:
			console.log("missing node: " + node);
			return missingNode;

	}

}

/*  'process': reactionLayout,
  'production': reactionLayout,
  'consumption': reactionLayout,
  'modulation': reactionLayout,
  'stimulation': reactionLayout,
  'catalysis': reactionLayout,
  'necessary stimulation': reactionLayout,
*/<|endoftext|>


<commit_before>var express = require('express')
var router = express.Router()
var controllers = require('./controllers')
var passport = require('passport')
var huia_auth = require('./services/huia_auth')
var LocalStrategy = require('passport-local').Strategy
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

passport.use(new LocalStrategy(
    function(username, password, done) {
        var user = huia_auth.auth(username, password, function(err, user) {
            return done(null, user)
        })
    }
))

passport.serializeUser(function(user, done) {
    done(null, user);
});

passport.deserializeUser(function(user, done) {
    done(null, user);
});

router.get('/login', controllers.login.get_login)
router.post('/login',
    passport.authenticate('local', {
        failureRedirect: '/login',
        successRedirect: '/'
    }),
    function(req, res) {
        res.redirect('/photos')
    })

//Home
router.get('/', controllers.instagram.get_index)

//Photos
router.get('/photos', authorize, upload.array('image'), controllers.photos.get_index)
router.post('/photos', authorize, upload.array('image'), controllers.photos.post_index)

//Instagram
router.get('/instagram/', controllers.instagram.get_index)
router.get('/instagram/subscribe', controllers.instagram.get_subscribe)
router.post('/instagram/subscribe', controllers.instagram.post_subscribe)
router.get('/instagram/photos', controllers.instagram.get_photos)
router.get('/instagram/maps', authorize, controllers.instagram.get_maps)
router.post('/instagram/maps', authorize, controllers.instagram.post_maps)
router.get('/instagram/subscriptions', authorize, controllers.instagram.get_subscriptions)
router.post('/instagram/subscriptions', authorize, controllers.instagram.post_subscriptions)
//router.put('/instagram/subscriptions', authorize, controllers.instagram.put_subscriptions)
//router.delete('/instagram/subscriptions', authorize, controllers.instagram.delete_subscriptions)

module.exports = router

function authorize(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login');
}
<commit_msg>mudado redirect depois do login<commit_after>var express = require('express')
var router = express.Router()
var controllers = require('./controllers')
var passport = require('passport')
var huia_auth = require('./services/huia_auth')
var LocalStrategy = require('passport-local').Strategy
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

passport.use(new LocalStrategy(
    function(username, password, done) {
        var user = huia_auth.auth(username, password, function(err, user) {
            return done(null, user)
        })
    }
))

passport.serializeUser(function(user, done) {
    done(null, user);
});

passport.deserializeUser(function(user, done) {
    done(null, user);
});

router.get('/login', controllers.login.get_login)
router.post('/login',
    passport.authenticate('local', {
        failureRedirect: '/login',
        successRedirect: '/photos'
    }),
    function(req, res) {
        res.redirect('/photos')
    })

//Home
router.get('/', controllers.instagram.get_index)

//Photos
router.get('/photos', authorize, upload.array('image'), controllers.photos.get_index)
router.post('/photos', authorize, upload.array('image'), controllers.photos.post_index)

//Instagram
router.get('/instagram/', controllers.instagram.get_index)
router.get('/instagram/subscribe', controllers.instagram.get_subscribe)
router.post('/instagram/subscribe', controllers.instagram.post_subscribe)
router.get('/instagram/photos', controllers.instagram.get_photos)
router.get('/instagram/maps', authorize, controllers.instagram.get_maps)
router.post('/instagram/maps', authorize, controllers.instagram.post_maps)
router.get('/instagram/subscriptions', authorize, controllers.instagram.get_subscriptions)
router.post('/instagram/subscriptions', authorize, controllers.instagram.post_subscriptions)
//router.put('/instagram/subscriptions', authorize, controllers.instagram.put_subscriptions)
//router.delete('/instagram/subscriptions', authorize, controllers.instagram.delete_subscriptions)

module.exports = router

function authorize(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login');
}
<|endoftext|>


<commit_before>import React from 'react'
import { Icon } from 'semantic-ui-react'

const IconExampleIconGroup = () => (
  <Icon.Group size='huge'>
    <Icon size='big' name='thin circle' />
    <Icon name='user' />
  </Icon.Group>
)

export default IconExampleIconGroup
<commit_msg>docs(IconExampleIconGroup): fix circle outline<commit_after>import React from 'react'
import { Icon } from 'semantic-ui-react'

const IconExampleIconGroup = () => (
  <Icon.Group size='huge'>
    <Icon size='big' name='circle outline' />
    <Icon name='user' />
  </Icon.Group>
)

export default IconExampleIconGroup
<|endoftext|>


<commit_before>import { log, cozyClient } from 'cozy-konnector-libs'

import { DOCTYPE_FILES } from 'drive/lib/doctypes'
import {
  readSetting,
  createSetting,
  updateSetting,
  getDefaultParameters,
  updateSettingStatus,
  getDefaultParametersMode,
  updateParamsPeriod
} from 'photos/ducks/clustering/settings'
import {
  computeEpsTemporal,
  computeEpsSpatial,
  reachabilities
} from 'photos/ducks/clustering/service'
import {
  PERCENTILE,
  DEFAULT_MODE,
  EVALUATION_THRESHOLD
} from 'photos/ducks/clustering/consts'
import { spatioTemporalScaled } from 'photos/ducks/clustering/metrics'
import { gradientClustering } from 'photos/ducks/clustering/gradient'
import {
  saveClustering,
  findAutoAlbums,
  albumsToClusterize,
  findAlbumsByIds
} from 'photos/ducks/clustering/albums'
import { prepareDataset } from 'photos/ducks/clustering/utils'
import { getMatchingParameters } from 'photos/ducks/clustering/matching'

// Compute the actual clustering based on the new dataset and the existing albums
const createNewClusters = async (params, key, dataset, albums) => {
  const reachs = reachabilities(dataset, spatioTemporalScaled, params)
  const clusters = gradientClustering(dataset, reachs, params)
  if (clusters.length > 0) {
    const ids = key.split(':')
    const albumsToSave = findAlbumsByIds(albums, ids)
    return saveClustering(clusters, albumsToSave)
  }
  return 0
}

// Compute the inital clustering
const createInitialClusters = async (paramsMode, dataset) => {
  const reachs = reachabilities(dataset, spatioTemporalScaled, paramsMode)
  const clusters = gradientClustering(dataset, reachs, paramsMode)
  return saveClustering(clusters)
}

// Clusterize the given photos, i.e. organize them depending on metrics
const clusterizePhotos = async (setting, dataset) => {
  log('info', `Start clustering on ${dataset.length} photos`)

  let clusteredCount = 0
  try {
    const albums = await findAutoAlbums()

    if (albums && albums.length > 0) {
      // Get photos to clusterize based on the existing clusters
      const clusterize = await albumsToClusterize(dataset, albums)
      if (clusterize) {
        for (const [key, photos] of Object.entries(clusterize)) {
          // Retrieve the relevant parameters to compute this cluster
          const params = getMatchingParameters(setting.parameters, photos)
          const paramsMode = getDefaultParametersMode(params)
          if (!paramsMode) {
            log('warn', 'No parameters for clustering found')
            continue
          }
          // Actual clustering
          clusteredCount += await createNewClusters(
            paramsMode,
            key,
            photos,
            albums
          )
          setting = await updateParamsPeriod(setting, params, dataset)
        }
      }
    } else {
      // No album found: this is an initialization
      const params = setting.parameters[setting.parameters.length - 1]
      const paramsMode = getDefaultParametersMode(params)
      if (!paramsMode) {
        log('warn', 'No parameters for clustering found')
        return
      }
      clusteredCount = await createInitialClusters(paramsMode, dataset)
      setting = await updateParamsPeriod(setting, params, dataset)
    }
  } catch (e) {
    log('error', `An error occured during the clustering: ${JSON.stringify(e)}`)
  }
  return { setting, clusteredCount }
  // TODO adapt percentiles for large datasets
}

const getChanges = async lastSeq => {
  log('info', `Get changes on files since ${lastSeq}`)
  const result = await cozyClient.fetchJSON(
    'GET',
    `/data/${DOCTYPE_FILES}/_changes?include_docs=true&since=${lastSeq}`
  )
  const photos = result.results.map(res => res.doc).filter(doc => {
    return doc.class === 'image' && !doc._id.includes('_design') && !doc.trashed
  })
  const newLastSeq = result.last_seq
  return { photos, newLastSeq }
}

const getFilesFromDate = async date => {
  // Note a file without a metadata.datetime would not be indexed: this is not
  // a big deal as this is only to compute parameters
  const filesIndex = await cozyClient.data.defineIndex(DOCTYPE_FILES, [
    'metadata.datetime',
    'class',
    'trashed'
  ])
  const selector = {
    'metadata.datetime': { $gt: date },
    class: 'image',
    trashed: false
  }
  return cozyClient.data.query(filesIndex, {
    selector: selector
  })
}

const createParameter = (dataset, epsTemporal, epsSpatial) => {
  return {
    period: {
      start: dataset[0].datetime,
      end: dataset[dataset.length - 1].datetime
    },
    modes: [
      {
        name: DEFAULT_MODE,
        epsTemporal: epsTemporal,
        epsSpatial: epsSpatial
      }
    ]
  }
}
const initParameters = dataset => {
  log('info', `Compute clustering parameters on ${dataset.length} photos`)
  const epsTemporal = computeEpsTemporal(dataset, PERCENTILE)
  const epsSpatial = computeEpsSpatial(dataset, PERCENTILE)
  return createParameter(dataset, epsTemporal, epsSpatial)
}

const recomputeParameters = async setting => {
  const lastParams = setting.parameters[setting.parameters.length - 1]
  // The defaultEvaluation field is used at init if there are not enough files
  // for a proper parameters evaluation: we use default metrics and therefore,
  // this end period should not be taken into consideration.
  const lastPeriodEnd = lastParams.defaultEvaluation
    ? lastParams.period.start
    : lastParams.period.end

  const files = await getFilesFromDate(lastPeriodEnd)

  // Safety check
  if (files.length < EVALUATION_THRESHOLD) {
    return
  }
  log('info', `Compute clustering parameters on ${files.length} photos`)

  const dataset = prepareDataset(files)
  const epsTemporal = computeEpsTemporal(dataset, PERCENTILE)
  const epsSpatial = computeEpsSpatial(dataset, PERCENTILE)
  return createParameter(dataset, epsTemporal, epsSpatial)
}

const onPhotoUpload = async () => {
  let setting = await readSetting()
  const lastSeq = setting ? setting.lastSeq : 0

  const changes = await getChanges(lastSeq)
  if (!changes || changes.photos.length < 1) {
    log('warn', 'Service called but no photos found to clusterize')
    return
  }
  const dataset = prepareDataset(changes.photos)

  if (!setting) {
    // No settings found: init them or use default
    const params =
      dataset.length > EVALUATION_THRESHOLD
        ? initParameters(dataset)
        : getDefaultParameters(dataset)
    setting = await createSetting(params)
  } else {
    if (setting.evaluationCount > EVALUATION_THRESHOLD) {
      const newParams = await recomputeParameters(setting)
      if (newParams) {
        const params = [...setting.parameters, newParams]
        const newSetting = {
          ...setting,
          parameters: params,
          evaluationCount: 0
        }
        setting = await updateSetting(setting, newSetting)
      }
    }
  }

  const result = await clusterizePhotos(setting, dataset)
  if (!result.setting) {
    return
  }
  /*
    WARNING: we save the lastSeq retrieved at the beginning of the clustering.
    However, we might have produced new _changes on files by saving the
    referenced-by, so they will computed again at the next clustering.
    We cannot save the new lastSeq, as new files might have been uploaded by
    this time and would be ignored for the next clustering.
    This is unpleasant, but harmless, as no new writes will be produced on the
    already clustered files.
   */
  await updateSettingStatus(result.setting, result.clusteredCount, changes)
}

onPhotoUpload()
<commit_msg>chore: Add logs<commit_after>import { log, cozyClient } from 'cozy-konnector-libs'

import { DOCTYPE_FILES } from 'drive/lib/doctypes'
import {
  readSetting,
  createSetting,
  updateSetting,
  getDefaultParameters,
  updateSettingStatus,
  getDefaultParametersMode,
  updateParamsPeriod
} from 'photos/ducks/clustering/settings'
import {
  computeEpsTemporal,
  computeEpsSpatial,
  reachabilities
} from 'photos/ducks/clustering/service'
import {
  PERCENTILE,
  DEFAULT_MODE,
  EVALUATION_THRESHOLD
} from 'photos/ducks/clustering/consts'
import { spatioTemporalScaled } from 'photos/ducks/clustering/metrics'
import { gradientClustering } from 'photos/ducks/clustering/gradient'
import {
  saveClustering,
  findAutoAlbums,
  albumsToClusterize,
  findAlbumsByIds
} from 'photos/ducks/clustering/albums'
import { prepareDataset } from 'photos/ducks/clustering/utils'
import { getMatchingParameters } from 'photos/ducks/clustering/matching'

// Compute the actual clustering based on the new dataset and the existing albums
const createNewClusters = async (params, key, dataset, albums) => {
  const reachs = reachabilities(dataset, spatioTemporalScaled, params)
  const clusters = gradientClustering(dataset, reachs, params)
  if (clusters.length > 0) {
    const ids = key.split(':')
    const albumsToSave = findAlbumsByIds(albums, ids)
    return saveClustering(clusters, albumsToSave)
  }
  return 0
}

// Compute the inital clustering
const createInitialClusters = async (paramsMode, dataset) => {
  const reachs = reachabilities(dataset, spatioTemporalScaled, paramsMode)
  const clusters = gradientClustering(dataset, reachs, paramsMode)
  return saveClustering(clusters)
}

// Clusterize the given photos, i.e. organize them depending on metrics
const clusterizePhotos = async (setting, dataset) => {
  log('info', `Start clustering on ${dataset.length} photos`)

  let clusteredCount = 0
  try {
    const albums = await findAutoAlbums()

    if (albums && albums.length > 0) {
      // Get photos to clusterize based on the existing clusters
      const clusterize = await albumsToClusterize(dataset, albums)
      if (clusterize) {
        for (const [key, photos] of Object.entries(clusterize)) {
          // Retrieve the relevant parameters to compute this cluster
          const params = getMatchingParameters(setting.parameters, photos)
          const paramsMode = getDefaultParametersMode(params)
          if (!paramsMode) {
            log('warn', 'No parameters for clustering found')
            continue
          }
          // Actual clustering
          clusteredCount += await createNewClusters(
            paramsMode,
            key,
            photos,
            albums
          )
          setting = await updateParamsPeriod(setting, params, dataset)
        }
      }
    } else {
      // No album found: this is an initialization
      const params = setting.parameters[setting.parameters.length - 1]
      const paramsMode = getDefaultParametersMode(params)
      if (!paramsMode) {
        log('warn', 'No parameters for clustering found')
        return
      }
      clusteredCount = await createInitialClusters(paramsMode, dataset)
      setting = await updateParamsPeriod(setting, params, dataset)
    }
  } catch (e) {
    log('error', `An error occured during the clustering: ${JSON.stringify(e)}`)
  }
  return { setting, clusteredCount }
  // TODO adapt percentiles for large datasets
}

const getChanges = async lastSeq => {
  log('info', `Get changes on files since ${lastSeq}`)
  const result = await cozyClient.fetchJSON(
    'GET',
    `/data/${DOCTYPE_FILES}/_changes?include_docs=true&since=${lastSeq}`
  )
  const photos = result.results.map(res => res.doc).filter(doc => {
    return doc.class === 'image' && !doc._id.includes('_design') && !doc.trashed
  })
  const newLastSeq = result.last_seq
  return { photos, newLastSeq }
}

const getFilesFromDate = async date => {
  // Note a file without a metadata.datetime would not be indexed: this is not
  // a big deal as this is only to compute parameters
  const filesIndex = await cozyClient.data.defineIndex(DOCTYPE_FILES, [
    'metadata.datetime',
    'class',
    'trashed'
  ])
  const selector = {
    'metadata.datetime': { $gt: date },
    class: 'image',
    trashed: false
  }
  return cozyClient.data.query(filesIndex, {
    selector: selector
  })
}

const createParameter = (dataset, epsTemporal, epsSpatial) => {
  return {
    period: {
      start: dataset[0].datetime,
      end: dataset[dataset.length - 1].datetime
    },
    modes: [
      {
        name: DEFAULT_MODE,
        epsTemporal: epsTemporal,
        epsSpatial: epsSpatial
      }
    ]
  }
}
const initParameters = dataset => {
  log('info', `Compute clustering parameters on ${dataset.length} photos`)
  const epsTemporal = computeEpsTemporal(dataset, PERCENTILE)
  const epsSpatial = computeEpsSpatial(dataset, PERCENTILE)
  return createParameter(dataset, epsTemporal, epsSpatial)
}

const recomputeParameters = async setting => {
  const lastParams = setting.parameters[setting.parameters.length - 1]
  // The defaultEvaluation field is used at init if there are not enough files
  // for a proper parameters evaluation: we use default metrics and therefore,
  // this end period should not be taken into consideration.
  const lastPeriodEnd = lastParams.defaultEvaluation
    ? lastParams.period.start
    : lastParams.period.end

  const files = await getFilesFromDate(lastPeriodEnd)

  // Safety check
  if (files.length < EVALUATION_THRESHOLD) {
    return
  }
  log('info', `Compute clustering parameters on ${files.length} photos`)

  const dataset = prepareDataset(files)
  const epsTemporal = computeEpsTemporal(dataset, PERCENTILE)
  const epsSpatial = computeEpsSpatial(dataset, PERCENTILE)
  return createParameter(dataset, epsTemporal, epsSpatial)
}

const onPhotoUpload = async () => {
  let setting = await readSetting()
  const lastSeq = setting ? setting.lastSeq : 0

  const changes = await getChanges(lastSeq)
  if (!changes || changes.photos.length < 1) {
    log('warn', 'Service called but no photos found to clusterize')
    return
  }
  const dataset = prepareDataset(changes.photos)

  if (!setting) {
    // No settings found: init them or use default
    const params =
      dataset.length > EVALUATION_THRESHOLD
        ? initParameters(dataset)
        : getDefaultParameters(dataset)
    setting = await createSetting(params)
    log(
      'info',
      `Setting saved with ${JSON.stringify(
        params.modes
      )} on period ${JSON.stringify(params.period)}`
    )
  } else {
    if (setting.evaluationCount > EVALUATION_THRESHOLD) {
      const newParams = await recomputeParameters(setting)
      if (newParams) {
        const params = [...setting.parameters, newParams]
        const newSetting = {
          ...setting,
          parameters: params,
          evaluationCount: 0
        }
        setting = await updateSetting(setting, newSetting)
        log('info', `Setting updated with ${JSON.stringify(newParams)}`)
      }
    }
  }

  const result = await clusterizePhotos(setting, dataset)
  if (!result.setting) {
    return
  }
  /*
    WARNING: we save the lastSeq retrieved at the beginning of the clustering.
    However, we might have produced new _changes on files by saving the
    referenced-by, so they will computed again at the next clustering.
    We cannot save the new lastSeq, as new files might have been uploaded by
    this time and would be ignored for the next clustering.
    This is unpleasant, but harmless, as no new writes will be produced on the
    already clustered files.
   */
  await updateSettingStatus(result.setting, result.clusteredCount, changes)
}

onPhotoUpload()
<|endoftext|>


<commit_before>export default class CssSyntaxError extends SyntaxError {
    constructor(message, line, column, source, file, plugin) {
        this.reason = message;

        this.message  = plugin ? plugin + ': ' : '';
        this.message += file ? file : '<css input>';
        if ( typeof line !== 'undefined' && typeof column !== 'undefined' ) {
            this.line   = line;
            this.column = column;
            this.message += ':' + line + ':' + column + ': ' + message;
        } else {
            this.message += ': ' + message;
        }

        if ( file )   this.file   = file;
        if ( source ) this.source = source;
        if ( plugin ) this.plugin = plugin;

        if ( Error.captureStackTrace ) {
            Error.captureStackTrace(this, CssSyntaxError);
        }
    }

    showSourceCode(color) {
        if ( !this.source ) return '';

        let num   = this.line - 1;
        let lines = this.source.split('\n');

        let prev   = num > 0 ? lines[num - 1] + '\n' : '';
        let broken = lines[num];
        let next   = num < lines.length - 1 ? '\n' + lines[num + 1] : '';

        let mark = '\n';
        for ( let i = 0; i < this.column - 1; i++ ) {
            mark += ' ';
        }

        if ( typeof color === 'undefined' && typeof process !== 'undefined' ) {
            if ( process.stdout && process.env ) {
                color = process.stdout.isTTY &&
                       !process.env.NODE_DISABLE_COLORS;
            }
        }

        if ( color ) {
            mark += '\x1B[1;31m^\x1B[0m';
        } else {
            mark += '^';
        }

        return '\n' + prev + broken + mark + next;
    }

    setMozillaProps() {
        let sample = Error.call(this, this.message);
        if ( sample.columnNumber ) this.columnNumber = this.column;
        if ( sample.description )  this.description  = this.message;
        if ( sample.lineNumber )   this.lineNumber   = this.line;
        if ( sample.fileName )     this.fileName     = this.file;
    }

    toString() {
        return this.name + ': ' + this.message + this.showSourceCode();
    }
}

CssSyntaxError.prototype.name = 'CssSyntaxError';
<commit_msg>Add CssSyntaxError#highlight alias<commit_after>import warn from './warn';

export default class CssSyntaxError extends SyntaxError {
    constructor(message, line, column, source, file, plugin) {
        this.reason = message;

        this.message  = plugin ? plugin + ': ' : '';
        this.message += file ? file : '<css input>';
        if ( typeof line !== 'undefined' && typeof column !== 'undefined' ) {
            this.line   = line;
            this.column = column;
            this.message += ':' + line + ':' + column + ': ' + message;
        } else {
            this.message += ': ' + message;
        }

        if ( file )   this.file   = file;
        if ( source ) this.source = source;
        if ( plugin ) this.plugin = plugin;

        if ( Error.captureStackTrace ) {
            Error.captureStackTrace(this, CssSyntaxError);
        }
    }

    showSourceCode(color) {
        if ( !this.source ) return '';

        let num   = this.line - 1;
        let lines = this.source.split('\n');

        let prev   = num > 0 ? lines[num - 1] + '\n' : '';
        let broken = lines[num];
        let next   = num < lines.length - 1 ? '\n' + lines[num + 1] : '';

        let mark = '\n';
        for ( let i = 0; i < this.column - 1; i++ ) {
            mark += ' ';
        }

        if ( typeof color === 'undefined' && typeof process !== 'undefined' ) {
            if ( process.stdout && process.env ) {
                color = process.stdout.isTTY &&
                       !process.env.NODE_DISABLE_COLORS;
            }
        }

        if ( color ) {
            mark += '\x1B[1;31m^\x1B[0m';
        } else {
            mark += '^';
        }

        return '\n' + prev + broken + mark + next;
    }

    highlight(color) {
        warn('CssSyntaxError#highlight was deprecated and will be remove ' +
             'in 5.0. Use error.showSourceCode instead.');
        return showSourceCode(color).replace(/^\n/, '');
    }

    setMozillaProps() {
        let sample = Error.call(this, this.message);
        if ( sample.columnNumber ) this.columnNumber = this.column;
        if ( sample.description )  this.description  = this.message;
        if ( sample.lineNumber )   this.lineNumber   = this.line;
        if ( sample.fileName )     this.fileName     = this.file;
    }

    toString() {
        return this.name + ': ' + this.message + this.showSourceCode();
    }
}

CssSyntaxError.prototype.name = 'CssSyntaxError';
<|endoftext|>


<commit_before>#!/usr/bin/env node

const { spawn } = require('child_process');
const { promisify } = require('util');
const {
  readdir: readdirRaw,
  readFile: readFileRaw,
  writeFile: writeFileRaw,
  statSync,
  readFileSync,
} = require('fs');
const { join } = require('path');

const readdir = promisify(readdirRaw);
const writeFile = promisify(writeFileRaw);

const p = l => join(__dirname, '..', ...l);
const logger = console;

const exec = async (command, args = [], options = {}) =>
  new Promise((resolve, reject) => {
    const child = spawn(command, args, { ...options, stdio: 'inherit', shell: true });

    child
      .on('close', code => {
        if (code) {
          reject();
        } else {
          resolve();
        }
      })
      .on('error', e => {
        logger.error(e);
        reject();
      });
  });

const getDeployables = files => {
  return files.filter(f => {
    const packageJsonLocation = p(['examples', f, 'package.json']);
    let stats = null;
    try {
      stats = statSync(packageJsonLocation);
    } catch (e) {
      // the folder had no package.json, we'll ignore
    }
    return stats && stats.isFile() && hasBuildScript(packageJsonLocation);
  });
};

const hasBuildScript = l => {
  const text = readFileSync(l, 'utf8');
  const json = JSON.parse(text);

  return !!json.scripts['build-storybook'];
};

const createContent = deployables => {
  return `
    <style>
      body {
        background: black;
        color: white;
      }
      #frame {
        position: absolute;
        left: 0;
        right: 0;
        width: 100vw;
        height: calc(100vh - 30px);
        bottom: 0;
        top: 30px;
        border: 0 none;
        margin: 0;
        padding: 0;
      }
      #select {
        position: absolute;
        top: 0;
        right: 100px;
        left: 10px;
        height: 30px;
        width: calc(100vw - 120px);
        background: black;
        color: white;
        border: 0 none;
        border-radius: 0;
        padding: 10px;
        box-sizing: border-box;
      }
      #open {
        position: absolute;
        top: 0;
        right: 0;
        width: 100px;
        height: 30px;
        background: black;
        color: white;
        border: 0 none;
        border-radius: 0;
        padding: 10px;
        box-sizing: border-box;
      }
    </style>

    <script>
      function handleClick() {
        var value = document.getElementById("select").value;
        window.location = document.location.origin + value;
      }
      function handleSelect() {
        var value = document.getElementById("select").value;
        var frame = document.getElementById("frame");

        sessionStorage.clear();
        localStorage.clear();

        frame.setAttribute('src', value);
      }
    </script>

    <button id="open" onclick="handleClick()">open</button>

    <select id="select" onchange="handleSelect()">
      ${deployables.map(i => `<option value="/${i}/">${i}</option>`).join('\n')}
    </select>

    <iframe id="frame" src="/${deployables[0]}/" />
  `;
};

const handleExamples = async deployables => {
  await deployables.reduce(async (acc, d) => {
    await acc;

    logger.log('');
    logger.log(
      `-----------------${Array(d.length)
        .fill('-')
        .join('')}`
    );
    logger.log(`▶  building: ${d}`);
    logger.log(
      `-----------------${Array(d.length)
        .fill('-')
        .join('')}`
    );
    const out = p(['built-storybooks', d]);
    const cwd = p(['examples', d]);

    await exec(`yarn`, [`build-storybook`, `--output-dir=${out}`, '--quiet'], { cwd });

    logger.log('-------');
    logger.log(`✅ ${d} built`);
    logger.log('-------');
  }, Promise.resolve());
};

const run = async () => {
  const examples = await readdir(p(['examples']));

  const { length } = examples;
  const [a, b] = [process.env.CIRCLE_NODE_INDEX || 0, process.env.CIRCLE_NODE_TOTAL || 1];
  const step = Math.ceil(length / b);
  const offset = step * a;

  const list = examples.slice().splice(offset, step);
  const deployables = getDeployables(list);

  if (deployables.length) {
    logger.log(`will build: ${deployables.join(', ')}`);
    await handleExamples(deployables);
  }

  if (
    deployables.length &&
    (process.env.CIRCLE_NODE_INDEX === undefined ||
      process.env.CIRCLE_NODE_INDEX === '0' ||
      process.env.CIRCLE_NODE_INDEX === 0)
  ) {
    const indexLocation = p(['built-storybooks', 'index.html']);
    logger.log('');
    logger.log(`📑 creating index at: ${indexLocation}`);
    logger.log('');
    await writeFile(indexLocation, createContent(deployables));

    logger.log('-------');
    logger.log('✅ done');
    logger.log('-------');
  }
};

run().catch(e => {
  logger.error(e);
  process.exit(1);
});
<commit_msg>debug webpack when building examples<commit_after>#!/usr/bin/env node

const { spawn } = require('child_process');
const { promisify } = require('util');
const {
  readdir: readdirRaw,
  readFile: readFileRaw,
  writeFile: writeFileRaw,
  statSync,
  readFileSync,
} = require('fs');
const { join } = require('path');

const readdir = promisify(readdirRaw);
const writeFile = promisify(writeFileRaw);

const p = l => join(__dirname, '..', ...l);
const logger = console;

const exec = async (command, args = [], options = {}) =>
  new Promise((resolve, reject) => {
    const child = spawn(command, args, { ...options, stdio: 'inherit', shell: true });

    child
      .on('close', code => {
        if (code) {
          reject();
        } else {
          resolve();
        }
      })
      .on('error', e => {
        logger.error(e);
        reject();
      });
  });

const getDeployables = files => {
  return files.filter(f => {
    const packageJsonLocation = p(['examples', f, 'package.json']);
    let stats = null;
    try {
      stats = statSync(packageJsonLocation);
    } catch (e) {
      // the folder had no package.json, we'll ignore
    }
    return stats && stats.isFile() && hasBuildScript(packageJsonLocation);
  });
};

const hasBuildScript = l => {
  const text = readFileSync(l, 'utf8');
  const json = JSON.parse(text);

  return !!json.scripts['build-storybook'];
};

const createContent = deployables => {
  return `
    <style>
      body {
        background: black;
        color: white;
      }
      #frame {
        position: absolute;
        left: 0;
        right: 0;
        width: 100vw;
        height: calc(100vh - 30px);
        bottom: 0;
        top: 30px;
        border: 0 none;
        margin: 0;
        padding: 0;
      }
      #select {
        position: absolute;
        top: 0;
        right: 100px;
        left: 10px;
        height: 30px;
        width: calc(100vw - 120px);
        background: black;
        color: white;
        border: 0 none;
        border-radius: 0;
        padding: 10px;
        box-sizing: border-box;
      }
      #open {
        position: absolute;
        top: 0;
        right: 0;
        width: 100px;
        height: 30px;
        background: black;
        color: white;
        border: 0 none;
        border-radius: 0;
        padding: 10px;
        box-sizing: border-box;
      }
    </style>

    <script>
      function handleClick() {
        var value = document.getElementById("select").value;
        window.location = document.location.origin + value;
      }
      function handleSelect() {
        var value = document.getElementById("select").value;
        var frame = document.getElementById("frame");

        sessionStorage.clear();
        localStorage.clear();

        frame.setAttribute('src', value);
      }
    </script>

    <button id="open" onclick="handleClick()">open</button>

    <select id="select" onchange="handleSelect()">
      ${deployables.map(i => `<option value="/${i}/">${i}</option>`).join('\n')}
    </select>

    <iframe id="frame" src="/${deployables[0]}/" />
  `;
};

const handleExamples = async deployables => {
  await deployables.reduce(async (acc, d) => {
    await acc;

    logger.log('');
    logger.log(
      `-----------------${Array(d.length)
        .fill('-')
        .join('')}`
    );
    logger.log(`▶  building: ${d}`);
    logger.log(
      `-----------------${Array(d.length)
        .fill('-')
        .join('')}`
    );
    const out = p(['built-storybooks', d]);
    const cwd = p(['examples', d]);

    await exec(`yarn`, [`build-storybook`, `--output-dir=${out}`, '--quiet', '--debug-webpack'], {
      cwd,
    });

    logger.log('-------');
    logger.log(`✅ ${d} built`);
    logger.log('-------');
  }, Promise.resolve());
};

const run = async () => {
  const examples = await readdir(p(['examples']));

  const { length } = examples;
  const [a, b] = [process.env.CIRCLE_NODE_INDEX || 0, process.env.CIRCLE_NODE_TOTAL || 1];
  const step = Math.ceil(length / b);
  const offset = step * a;

  const list = examples.slice().splice(offset, step);
  const deployables = getDeployables(list);

  if (deployables.length) {
    logger.log(`will build: ${deployables.join(', ')}`);
    await handleExamples(deployables);
  }

  if (
    deployables.length &&
    (process.env.CIRCLE_NODE_INDEX === undefined ||
      process.env.CIRCLE_NODE_INDEX === '0' ||
      process.env.CIRCLE_NODE_INDEX === 0)
  ) {
    const indexLocation = p(['built-storybooks', 'index.html']);
    logger.log('');
    logger.log(`📑 creating index at: ${indexLocation}`);
    logger.log('');
    await writeFile(indexLocation, createContent(deployables));

    logger.log('-------');
    logger.log('✅ done');
    logger.log('-------');
  }
};

run().catch(e => {
  logger.error(e);
  process.exit(1);
});
<|endoftext|>


<commit_before>'use strict';

// CONSTANTS //

var EULER = require( 'compute-const-eulergamma' );

// GAMMA //

/**
* FUNCTION: gamma( x, z )
*	Computes a small-value approximation.
*
* @param {Number} x - input value
* @param {Number} z
* @returns {Number} approximation
*/
function gamma( x, z ) {
	return z / ((1 + EULER*x) * x );
} // end FUNCTION gamma()

// EXPORTS //

module.exports = gamma;
<commit_msg>Add space<commit_after>'use strict';

// CONSTANTS //

var EULER = require( 'compute-const-eulergamma' );

// GAMMA //

/**
* FUNCTION: gamma( x, z )
*	Computes a small-value approximation.
*
* @param {Number} x - input value
* @param {Number} z
* @returns {Number} approximation
*/
function gamma( x, z ) {
	return z / ( (1 + EULER*x) * x );
} // end FUNCTION gamma()

// EXPORTS //

module.exports = gamma;
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var Iss = mongoose.model('Issue');
var User = mongoose.model('User');
var utils = require('../../services/utils');
const activitiesService = require('../../services/activities.service');
const ToDo = mongoose.model('ToDo');

// POST /issues/new - Creates a new issue
module.exports.issuesCreate = function(req, res) {

  Iss.create({
    title: req.body.title,
    responsibleParty: req.body.responsibleParty,
    resolutionTimeframe: req.body.resolutionTimeframe,
    description: req.body.description,
    confidential: req.body.confidential,
    submitBy: req.payload._id,
    community: req.body.community._id
  }, function(err, issue) {
    if (err) {
      console.log(err);
      utils.sendJSONresponse(res, 400, err);
    } else {

      User.populate(issue, {
        path: 'responsibleParty submitBy'
      }, function(err, populatedIssue) {

        activitiesService.addActivity(" created issue " + req.body.title, req.body.responsibleParty,
                                        "issue-create", req.body.community._id);

        utils.sendJSONresponse(res, 200, populatedIssue);
      });

    }
  });
};

//PUT /issues/:issueid/finalplan - Adds a final plan item to an issue
module.exports.addFinalPlan = function(req, res) {

  let issueid = req.params.issueid;
  let todoId = req.body.todoid;

  if (utils.checkParams(req, res, ['issueid'])) {
    return;
  }

  if(!req.body.checklist) {

    let todo = ToDo.findById(todoId).exec();

    todo
    .then((todo) => {

      todo.tasks.push({
        "text" : req.body.text,
        "occurrence" : 1,
        "state" : "current",
        "activeDays" : [true, true, true, true, true, false, false],
        "activeWeeks": [false, false, false, false, false],
        "activeMonths": [false, false, false, false, false,false, false, false, false, false,false, false, false, false, false],
        "cycleDate" : new Date(),
        "issueName": req.body.issueName
      });

      return todo;
    })
    .then((todo) => {
      todo.save((err, todo) => {
          return todo.tasks[todo.tasks.length-1]._id;
      });
    })
    .then((taskId) => {
      finalPlan(req, res, taskId);
    });

  } else {
    finalPlan(req, res);
  }

};

//GET /issues/count/:userid/id/:communityid - Number of open issues asigned to an user
module.exports.issuesOpenCount = function(req, res) {

  var userid = req.params.userid;
  var community = req.params.communityid;

  if (utils.checkParams(req, res, ['userid', 'communityid'])) {
    return;
  }

  Iss.find({
    status: "Open",
    responsibleParty: userid,
    community: community
  }, function(err, issues) {
    if (issues) {
      utils.sendJSONresponse(res, 200, issues.length);
    } else {
      utils.sendJSONresponse(res, 404, 0);
    }

  });
};

// GET /issues/:issueid/updateinfo - Returns all updateInfo populated for an issue
module.exports.issueUpdateInfo = function(req, res) {
  var issueid = req.params.issueid;

  if (utils.checkParams(req, res, ['issueid'])) {
    return;
  }

  Iss.findById(issueid)
     .populate('updateInfo.updateBy', 'email name userImage')
     .exec(function(err, issue) {
       if(err) {
         utils.sendJSONresponse(res, 404, {'message' : err});
       } else {
           utils.sendJSONresponse(res, 200, issue.updateInfo);
       }
     });

};

// GET /issues/issuescount/:communityid - Number of open isues for a community
module.exports.issuesCount = function(req, res) {

  var communityid = req.params.communityid;

  if (utils.checkParams(req, res, ['communityid'])) {
    return;
  }

  Iss.find({
    status: "Open",
    community: communityid
  }, function(err, issues) {
    if (err) {
      utils.sendJSONresponse(res, 404, {
        'message': err
      });
    } else {
      utils.sendJSONresponse(res, 200, issues.length);
    }

  });
};

// GET /issues/list/:status/id/:communityid - Gets a list of issues grouped by responsibleParty
// and sorted by users issue number
module.exports.issuesList = function(req, res) {

  var id = req.params.communityid;
  var status = req.params.status;

  if (utils.checkParams(req, res, ['status', 'communityid'])) {
    return;
  }

  var issueTemplate = {
    "title": "$title",
    "responsibleParty": "$responsibleParty",
    "resolutionTimeframe": "$resolutionTimeframe",
    "description": "$description",
    "submitBy": "$submitBy",
    "submitDate": "$submitDate",
    "comments": "$comments",
    "updateInfo": "$updateInfo",
    "status": "$status",
    "idMembers": "$idMembers",
    "idLabels": "$idLabels",
    "idAttachmentCover": "$idAttachmentCover",
    "attachments": "$attachments",
    "finalPlan": "$finalPlan",
    "labels": "$labels",
    "checklists": "$checklists",
    "_id": "$_id",
    "community": "$community",
    "due": "$due",
    "confidential": "$confidential"
  };

  Iss.aggregate([{
      '$match': {
        community: new mongoose.Types.ObjectId(id),
        status: req.params.status
      }
    }, {
      '$group': {
        "_id": "$responsibleParty",
        count: {
          "$sum": 1
        },
        issues: {
          $push: issueTemplate
        }
      }
    }, {
      '$sort': {
        "count": -1
      }
    }],
    function(err, issues) {

      //Populate user model so we have responsibleParty name and not just the _id
      User.populate(issues, [{
        path: '_id',
        model: 'User'
      },{
        path: 'updateInfo.updateBy',
        model: 'User'
      },{
        path: 'submitBy',
        model: 'User'
      }], function(err) {
        if (err) {
          utils.sendJSONresponse(res, 404, {
            'message': err
          });
        } else {
          utils.sendJSONresponse(res, 200, issues);
        }

      });

    });
};

// GET /issues/:username/s/:status/id/:communityid - List issues in a community by status
module.exports.issuesListByStatus = function(req, res) {

  var status = req.params.status;
  var communityid = req.params.communityid;

  if (utils.checkParams(req, res, ['status', 'communityid'])) {
    return;
  }

  Iss.find({status: status, community: communityid})
      .populate("submitBy", "name _id")
      .exec(function(err, issues) {
    if (err) {
      utils.sendJSONresponse(res, 404, {
        'message': err
      });
    } else {
      utils.sendJSONresponse(res, 200, issues);
    }
  });
};

// GET /issues/due/:communityid - List of issues that are due in a community
module.exports.dueIssuesList = function(req, res) {

  var communityid = req.params.communityid;

  if (utils.checkParams(req, res, ['communityid'])) {
    return;
  }

  Iss.find({
      "due": {
        $exists: true
      },
      community: communityid
    },
    function(err, issues) {
      if (issues) {
        utils.sendJSONresponse(res, 200, issues);
      } else {
        utils.sendJSONresponse(res, 404, {
          "message": "Issues with due date not found"
        });
      }
    });
};

// GET /issues/:issueid - Reads issue info by id
module.exports.issuesReadOne = function(req, res) {

  if (utils.checkParams(req, res, ['issueid'])) {
    return;
  }

  if (req.params && req.params.issueid) {
    Iss
      .findById(req.params.issueid)
      .exec(function(err, issue) {
        if (!issue) {
          utils.sendJSONresponse(res, 404, {
            "message": "issueid not found"
          });
          return;
        } else if (err) {
          console.log(err);
          utils.sendJSONresponse(res, 404, err);
          return;
        }

        utils.sendJSONresponse(res, 200, issue);
      });
  } else {
    console.log('No issueid specified');
    utils.sendJSONresponse(res, 404, {
      "message": "No issueid in request"
    });
  }
};

// PUT issues/:issueid - Updates issue by its id
module.exports.issuesUpdateOne = function(req, res) {

  if (utils.checkParams(req, res, ['issueid'])) {
    return;
  }

  var updateInfo = {
    "updateBy": req.body.modifiedBy,
    "updateDate": req.body.modifiedDate,
    "updateField": req.body.updateField
  };

  Iss
    .findById(req.params.issueid)
    .exec(
      function(err, issue) {

        if (!issue) {
          utils.sendJSONresponse(res, 404, {
            "message": "issueid not found"
          });
          return;
        } else if (err) {
          utils.sendJSONresponse(res, 400, err);
          return;
        }

        issue.title = req.body.title;
        issue.responsibleParty = req.body.responsibleParty;
        issue.resolutionTimeframe = req.body.resolutionTimeframe;
        issue.submitBy = req.body.submitBy._id;
        issue.description = req.body.description;
        issue.status = req.body.status;
        issue.due = req.body.due;

        issue.checklists = req.body.checklists;
        issue.labels = req.body.labels;
        //issue.updateInfo = req.body.updateInfo;
        issue.shelvedDate = req.body.shelvedDate;

        if (req.body.deletedMember !== undefined) {
          issue.idMembers.splice(issue.idMembers.map(function(d) {
            return d.name;
          }).indexOf(req.body.deletedMember), 1);
        } else {
          issue.idMembers = req.body.idMembers;
        }

        if (updateInfo.updateField !== undefined) {
          if (updateInfo.updateField.length > 0) {
            issue.updateInfo.push(updateInfo);
          }

        }

        issue.save(function(err, issue) {
          if (err) {
            console.log(err);
            utils.sendJSONresponse(res, 404, err);
          } else {
            Iss.populate(issue.updateField, [{'path' : 'updateBy'}, {'path' : 'submitBy'}], function(err, iss) {
                    utils.sendJSONresponse(res, 200, iss);
            });
          }
        });
      }
    );
};

// DELETE /issues/:issueid - Delte an issue by id
module.exports.issuesDeleteOne = function(req, res) {
  var issueid = req.params.issueid;

  if (utils.checkParams(req, res, ['issueid'])) {
    return;
  }

  if (issueid) {
    Iss
      .findByIdAndRemove(issueid)
      .exec(
        function(err, issue) {
          if (err) {
            console.log(err);
            utils.sendJSONresponse(res, 404, err);
            return;
          }
          utils.sendJSONresponse(res, 204, null);
        }
      );
  } else {
    sendJSONresponse(res, 404, {
      "message": "No issueid"
    });
  }
};

//////////////////////// HELPER FUNCTIONS ////////////////////////////
function finalPlan(req, res, taskid) {
  Iss.findById(req.params.issueid)
     .exec(function(err, issue) {

       if(err) {
         utils.sendJSONresponse(res, 404, {'message' : 'Issue not found to add a final plan'});
       } else {

         let finalPlan = {
           "text" : req.body.text,
           "checklist" : req.body.checklist,
           "author" : req.body.author
         };

         if(taskid) {
           finalPlan.task = taskid;
         }

         issue.finalPlan.push(finalPlan);

         issue.save(function(err, issue) {
           if(err) {
             utils.sendJSONresponse(res, 404,
               {'message' : 'Unable to save issue while adding final plan'});
           } else {
             utils.sendJSONresponse(res, 200, finalPlan);
           }
         });
       }

     });
}
<commit_msg>working on issue responsible party changing<commit_after>var mongoose = require('mongoose');
var Iss = mongoose.model('Issue');
var User = mongoose.model('User');
var utils = require('../../services/utils');
const activitiesService = require('../../services/activities.service');
const ToDo = mongoose.model('ToDo');

// POST /issues/new - Creates a new issue
module.exports.issuesCreate = function(req, res) {

  Iss.create({
    title: req.body.title,
    responsibleParty: req.body.responsibleParty,
    resolutionTimeframe: req.body.resolutionTimeframe,
    description: req.body.description,
    confidential: req.body.confidential,
    submitBy: req.payload._id,
    community: req.body.community._id
  }, function(err, issue) {
    if (err) {
      console.log(err);
      utils.sendJSONresponse(res, 400, err);
    } else {

      User.populate(issue, {
        path: 'responsibleParty submitBy'
      }, function(err, populatedIssue) {

        activitiesService.addActivity(" created issue " + req.body.title, req.body.responsibleParty,
                                        "issue-create", req.body.community._id);

        utils.sendJSONresponse(res, 200, populatedIssue);
      });

    }
  });
};

//PUT /issues/:issueid/finalplan - Adds a final plan item to an issue
module.exports.addFinalPlan = function(req, res) {

  let issueid = req.params.issueid;
  let todoId = req.body.todoid;

  if (utils.checkParams(req, res, ['issueid'])) {
    return;
  }

  if(!req.body.checklist) {

    let todo = ToDo.findById(todoId).exec();

    todo
    .then((todo) => {

      todo.tasks.push({
        "text" : req.body.text,
        "occurrence" : 1,
        "state" : "current",
        "activeDays" : [true, true, true, true, true, false, false],
        "activeWeeks": [false, false, false, false, false],
        "activeMonths": [false, false, false, false, false,false, false, false, false, false,false, false, false, false, false],
        "cycleDate" : new Date(),
        "issueName": req.body.issueName
      });

      return todo;
    })
    .then((todo) => {
      todo.save((err, todo) => {
          return todo.tasks[todo.tasks.length-1]._id;
      });
    })
    .then((taskId) => {
      finalPlan(req, res, taskId);
    });

  } else {
    finalPlan(req, res);
  }

};

//GET /issues/count/:userid/id/:communityid - Number of open issues asigned to an user
module.exports.issuesOpenCount = function(req, res) {

  var userid = req.params.userid;
  var community = req.params.communityid;

  if (utils.checkParams(req, res, ['userid', 'communityid'])) {
    return;
  }

  Iss.find({
    status: "Open",
    responsibleParty: userid,
    community: community
  }, function(err, issues) {
    if (issues) {
      utils.sendJSONresponse(res, 200, issues.length);
    } else {
      utils.sendJSONresponse(res, 404, 0);
    }

  });
};

// GET /issues/:issueid/updateinfo - Returns all updateInfo populated for an issue
module.exports.issueUpdateInfo = function(req, res) {
  var issueid = req.params.issueid;

  if (utils.checkParams(req, res, ['issueid'])) {
    return;
  }

  Iss.findById(issueid)
     .populate('updateInfo.updateBy', 'email name userImage')
     .exec(function(err, issue) {
       if(err) {
         utils.sendJSONresponse(res, 404, {'message' : err});
       } else {
           utils.sendJSONresponse(res, 200, issue.updateInfo);
       }
     });

};

// GET /issues/issuescount/:communityid - Number of open isues for a community
module.exports.issuesCount = function(req, res) {

  var communityid = req.params.communityid;

  if (utils.checkParams(req, res, ['communityid'])) {
    return;
  }

  Iss.find({
    status: "Open",
    community: communityid
  }, function(err, issues) {
    if (err) {
      utils.sendJSONresponse(res, 404, {
        'message': err
      });
    } else {
      utils.sendJSONresponse(res, 200, issues.length);
    }

  });
};

// GET /issues/list/:status/id/:communityid - Gets a list of issues grouped by responsibleParty
// and sorted by users issue number
module.exports.issuesList = function(req, res) {

  var id = req.params.communityid;
  var status = req.params.status;

  if (utils.checkParams(req, res, ['status', 'communityid'])) {
    return;
  }

  var issueTemplate = {
    "title": "$title",
    "responsibleParty": "$responsibleParty",
    "resolutionTimeframe": "$resolutionTimeframe",
    "description": "$description",
    "submitBy": "$submitBy",
    "submitDate": "$submitDate",
    "comments": "$comments",
    "updateInfo": "$updateInfo",
    "status": "$status",
    "idMembers": "$idMembers",
    "idLabels": "$idLabels",
    "idAttachmentCover": "$idAttachmentCover",
    "attachments": "$attachments",
    "finalPlan": "$finalPlan",
    "labels": "$labels",
    "checklists": "$checklists",
    "_id": "$_id",
    "community": "$community",
    "due": "$due",
    "confidential": "$confidential"
  };

  Iss.aggregate([{
      '$match': {
        community: new mongoose.Types.ObjectId(id),
        status: req.params.status
      }
    }, {
      '$group': {
        "_id": "$responsibleParty",
        count: {
          "$sum": 1
        },
        issues: {
          $push: issueTemplate
        }
      }
    }, {
      '$sort': {
        "count": -1
      }
    }],
    function(err, issues) {

      //Populate user model so we have responsibleParty name and not just the _id
      User.populate(issues, [{
        path: '_id',
        model: 'User'
      },{
        path: 'updateInfo.updateBy',
        model: 'User'
      },{
        path: 'submitBy',
        model: 'User'
      },{
        path: 'responsibleParty',
        model: 'User'
      }], function(err) {
        if (err) {
          utils.sendJSONresponse(res, 404, {
            'message': err
          });
        } else {
          console.log(issues);
          utils.sendJSONresponse(res, 200, issues);
        }

      });

    });
};

// GET /issues/:username/s/:status/id/:communityid - List issues in a community by status
module.exports.issuesListByStatus = function(req, res) {

  var status = req.params.status;
  var communityid = req.params.communityid;

  if (utils.checkParams(req, res, ['status', 'communityid'])) {
    return;
  }

  Iss.find({status: status, community: communityid})
      .populate("submitBy", "name _id")
      .populate("responsibleParty", "name _id")
      .exec(function(err, issues) {
    if (err) {
      utils.sendJSONresponse(res, 404, {
        'message': err
      });
    } else {
      utils.sendJSONresponse(res, 200, issues);
    }
  });
};

// GET /issues/due/:communityid - List of issues that are due in a community
module.exports.dueIssuesList = function(req, res) {

  var communityid = req.params.communityid;

  if (utils.checkParams(req, res, ['communityid'])) {
    return;
  }

  Iss.find({
      "due": {
        $exists: true
      },
      community: communityid
    },
    function(err, issues) {
      if (issues) {
        utils.sendJSONresponse(res, 200, issues);
      } else {
        utils.sendJSONresponse(res, 404, {
          "message": "Issues with due date not found"
        });
      }
    });
};

// GET /issues/:issueid - Reads issue info by id
module.exports.issuesReadOne = function(req, res) {

  if (utils.checkParams(req, res, ['issueid'])) {
    return;
  }

  if (req.params && req.params.issueid) {
    Iss
      .findById(req.params.issueid)
      .exec(function(err, issue) {
        if (!issue) {
          utils.sendJSONresponse(res, 404, {
            "message": "issueid not found"
          });
          return;
        } else if (err) {
          console.log(err);
          utils.sendJSONresponse(res, 404, err);
          return;
        }

        utils.sendJSONresponse(res, 200, issue);
      });
  } else {
    console.log('No issueid specified');
    utils.sendJSONresponse(res, 404, {
      "message": "No issueid in request"
    });
  }
};

// PUT issues/:issueid - Updates issue by its id
module.exports.issuesUpdateOne = function(req, res) {

  if (utils.checkParams(req, res, ['issueid'])) {
    return;
  }

  var updateInfo = {
    "updateBy": req.body.modifiedBy,
    "updateDate": req.body.modifiedDate,
    "updateField": req.body.updateField
  };

  Iss
    .findById(req.params.issueid)
    .exec(
      function(err, issue) {

        if (!issue) {
          utils.sendJSONresponse(res, 404, {
            "message": "issueid not found"
          });
          return;
        } else if (err) {
          utils.sendJSONresponse(res, 400, err);
          return;
        }

        issue.title = req.body.title;
        issue.responsibleParty = req.body.responsibleParty;
        issue.resolutionTimeframe = req.body.resolutionTimeframe;
        issue.submitBy = req.body.submitBy._id;
        issue.description = req.body.description;
        issue.status = req.body.status;
        issue.due = req.body.due;

        issue.checklists = req.body.checklists;
        issue.labels = req.body.labels;
        //issue.updateInfo = req.body.updateInfo;
        issue.shelvedDate = req.body.shelvedDate;

        if (req.body.deletedMember !== undefined) {
          issue.idMembers.splice(issue.idMembers.map(function(d) {
            return d.name;
          }).indexOf(req.body.deletedMember), 1);
        } else {
          issue.idMembers = req.body.idMembers;
        }

        if (updateInfo.updateField !== undefined) {
          if (updateInfo.updateField.length > 0) {
            issue.updateInfo.push(updateInfo);
          }

        }

        issue.save(function(err, issue) {
          if (err) {
            console.log(err);
            utils.sendJSONresponse(res, 404, err);
          } else {
            Iss.populate(issue.updateField, [{'path' : 'updateBy'}, {'path' : 'submitBy'}], function(err, iss) {
                    utils.sendJSONresponse(res, 200, iss);
            });
          }
        });
      }
    );
};

// DELETE /issues/:issueid - Delte an issue by id
module.exports.issuesDeleteOne = function(req, res) {
  var issueid = req.params.issueid;

  if (utils.checkParams(req, res, ['issueid'])) {
    return;
  }

  if (issueid) {
    Iss
      .findByIdAndRemove(issueid)
      .exec(
        function(err, issue) {
          if (err) {
            console.log(err);
            utils.sendJSONresponse(res, 404, err);
            return;
          }
          utils.sendJSONresponse(res, 204, null);
        }
      );
  } else {
    sendJSONresponse(res, 404, {
      "message": "No issueid"
    });
  }
};

//////////////////////// HELPER FUNCTIONS ////////////////////////////
function finalPlan(req, res, taskid) {
  Iss.findById(req.params.issueid)
     .exec(function(err, issue) {

       if(err) {
         utils.sendJSONresponse(res, 404, {'message' : 'Issue not found to add a final plan'});
       } else {

         let finalPlan = {
           "text" : req.body.text,
           "checklist" : req.body.checklist,
           "author" : req.body.author
         };

         if(taskid) {
           finalPlan.task = taskid;
         }

         issue.finalPlan.push(finalPlan);

         issue.save(function(err, issue) {
           if(err) {
             utils.sendJSONresponse(res, 404,
               {'message' : 'Unable to save issue while adding final plan'});
           } else {
             utils.sendJSONresponse(res, 200, finalPlan);
           }
         });
       }

     });
}
<|endoftext|>