<commit_before>//import React from 'react';

import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import ISSUE_IMPORTANCE from 'Parser/Core/ISSUE_IMPORTANCE';

import CoreAbilities from 'Parser/Core/Modules/Abilities';

//import SpellLink from 'common/SpellLink';

class Abilities extends CoreAbilities {
  spellbook() {
    const combatant = this.combatants.selected;
    return [
      {
        spell: SPELLS.CONSECRATION_CAST,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: haste => 9 / (1 + haste),
        isOnGCD: true,
        castEfficiency: {
          suggestion: true,
          recommendedEfficiency: 0.9,
        },
      },
      {
        spell: SPELLS.BLESSED_HAMMER_TALENT,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: haste => 4.5 / (1 + haste),
        charges: 3,
        enabled: combatant.hasTalent(SPELLS.BLESSED_HAMMER_TALENT.id),
        castEfficiency: {
          suggestion: true,
          recommendedEfficiency: 0.9,
        },
      },
      {
        spell: SPELLS.AVENGERS_SHIELD,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: haste => 15 / (1 + haste),
        isOnGCD: true,
        castEfficiency: {
          suggestion: true,
          recommendedEfficiency: 0.9,
        },
      },
      // Probably useless to try to count the number of casts
      //Note by yajinni: Since this is thier main source of damage mitigation, without it they get hit like by a truck.
      //And a main source of damage, it should be tracked somewhat. Keeping it at 80% for now.
      {
        spell: SPELLS.SHIELD_OF_THE_RIGHTEOUS,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: haste => 16 / (1 + haste),
        charges: 3,
        castEfficiency: {
          suggestion: true,
          recommendedEfficiency: 0.8,
        },
      },
      { // T15: Holy Shield
        spell: SPELLS.HAMMER_OF_THE_RIGHTEOUS,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: haste => 4.5 / (1 + haste),
        charges: 2,
        isOnGCD: true,
        enabled: combatant.hasTalent(SPELLS.HOLY_SHIELD_TALENT.id),
        castEfficiency: {
          suggestion: true,
        },
      },
      { // T15: Blessed Hammer (replaces Hammer of the Righteous)
        spell: SPELLS.BLESSED_HAMMER_TALENT,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: haste => 4.5 / (1 + haste),
        charges: 3,
        isOnGCD: true,
        enabled: combatant.hasTalent(SPELLS.BLESSED_HAMMER_TALENT.id),
        castEfficiency: {
          suggestion: true,
          recommendedEfficiency: 0.9,
        },
      },
      { // T15: Consecrated Hammer talent (Hammer of the Righteous has no cooldown)
        spell: SPELLS.HAMMER_OF_THE_RIGHTEOUS,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        isOnGCD: true,
        enabled: combatant.hasTalent(SPELLS.CONSECRATED_HAMMER_TALENT.id),
      },
      {
        spell: SPELLS.JUDGMENT_CAST,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: haste => 6 / (1 + haste),
        charges: combatant.hasTalent(SPELLS.CRUSADERS_JUDGMENT_TALENT.id) ? 2 : 1,
        isOnGCD: true,
        castEfficiency: {
          suggestion: true,
        },
      },
      {
        spell: SPELLS.LIGHT_OF_THE_PROTECTOR,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: 15 * (combatant.hasHead(ITEMS.SARUANS_RESOLVE.id) ? 0.9 : 1),
        charges: 1 + (combatant.hasHead(ITEMS.SARUANS_RESOLVE.id) ? 1 : 0),
        enabled: !combatant.hasTalent(SPELLS.HAND_OF_THE_PROTECTOR_TALENT.id),
        castEfficiency: {
          suggestion: true,
          recommendedEfficiency: 0.6,
          importance: ISSUE_IMPORTANCE.MINOR,
        },
      },
      {
        spell: SPELLS.HAND_OF_THE_PROTECTOR_TALENT,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: 10 * (combatant.hasHead(ITEMS.SARUANS_RESOLVE.id) ? 0.9 : 1),
        charges: 1 + (combatant.hasHead(ITEMS.SARUANS_RESOLVE.id) ? 1 : 0),
        enabled: combatant.hasTalent(SPELLS.HAND_OF_THE_PROTECTOR_TALENT.id),
        castEfficiency: {
          suggestion: true,
          recommendedEfficiency: 0.6,
          importance: ISSUE_IMPORTANCE.MINOR,
        },
      },
      //COOLDOWNS
      {
        spell: SPELLS.EYE_OF_TYR,
        category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
        cooldown: (haste, combatant) => 60 * (combatant.hasShoulder(ITEMS.PILLARS_OF_INMOST_LIGHT.id) ? 0.75 : 1),
        isOnGCD: true,
        castEfficiency: {
          suggestion: true,
          recommendedEfficiency: 0.85,
        },
      },
      {
        spell: SPELLS.ARDENT_DEFENDER,
        category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
        cooldown: 120 - (combatant.traitsBySpellId[SPELLS.UNFLINCHING_DEFENSE.id] || 0) * 10,
        castEfficiency: {
          suggestion: true,
        },
      },
      {
        spell: SPELLS.GUARDIAN_OF_ANCIENT_KINGS,
        category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
        cooldown: 300,
        castEfficiency: {
          suggestion: true,
        },
      },
      {
        spell: SPELLS.SERAPHIM_TALENT,
        category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
        cooldown: 45,
        enabled: combatant.hasTalent(SPELLS.SERAPHIM_TALENT.id),
        castEfficiency: {
          suggestion: true,
        },
      },
      {
        spell: SPELLS.AVENGING_WRATH_RET,
        category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
        cooldown: 120,
        // castEfficiency: {
        //   suggestion: true,
        //   recommendedEfficiency: 0.85,
        // },
      },
      {
        spell: SPELLS.LAY_ON_HANDS,
        category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
        cooldown: 600,
        castEfficiency: {
          suggestion: true,
          recommendedEfficiency: 0.1,
        },
      },
      {
        spell: SPELLS.FLASH_OF_LIGHT,
        category: Abilities.SPELL_CATEGORIES.OTHERS,
        isOnGCD: true,
      },
      {
        spell: SPELLS.DIVINE_STEED,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 45 * (combatant.hasTalent(SPELLS.KNIGHT_TEMPLAR_TALENT.id) ? 0.5 : 1),
        charges: combatant.hasTalent(SPELLS.CAVALIER_TALENT.id) ? 2 : 1,
        isOnGCD: true,
      },
      {
        spell: SPELLS.BLESSING_OF_FREEDOM,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 25,
        isOnGCD: true,
      },
      {
        spell: SPELLS.BLESSING_OF_PROTECTION,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 5 * 60,
        isOnGCD: true,
        enabled: !combatant.hasTalent(SPELLS.BLESSING_OF_SPELLWARDING_TALENT.id),
      },
      {
        spell: SPELLS.BLESSING_OF_SPELLWARDING_TALENT,
        category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
        cooldown: 180,
        isOnGCD: true,
        enabled: combatant.hasTalent(SPELLS.BLESSING_OF_SPELLWARDING_TALENT.id),
      },
      {
        spell: SPELLS.BLESSING_OF_SACRIFICE,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 2.5 * 60 - (combatant.traitsBySpellId[SPELLS.SACRIFICE_OF_THE_JUST.id] || 0) * 60,
        // castEfficiency: {
        //   suggestion: true,
        //   recommendedEfficiency: 0.85,
        // },
      },
      {
        spell: SPELLS.AEGIS_OF_LIGHT_TALENT,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 180,
        isOnGCD: true,
        enabled: combatant.hasTalent(SPELLS.AEGIS_OF_LIGHT_TALENT.id),
      },
      {
        spell: SPELLS.CLEANSE_TOXINS,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 8,
        isOnGCD: true,
      },
      {
        spell: SPELLS.HAMMER_OF_JUSTICE,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 60,
        isOnGCD: true,
      },
      {
        spell: SPELLS.HAND_OF_RECKONING,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 8,
      },
      {
        spell: SPELLS.REBUKE,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 15,
      },
      {
        spell: SPELLS.BLINDING_LIGHT_TALENT,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 90,
        isOnGCD: true,
        enabled: combatant.hasTalent(SPELLS.BLINDING_LIGHT_TALENT.id),
      },
      {
        spell: SPELLS.REPENTANCE_TALENT,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 15,
        isOnGCD: true,
        enabled: combatant.hasTalent(SPELLS.REPENTANCE_TALENT.id),
      },
      {
        spell: SPELLS.BASTION_OF_LIGHT_TALENT,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: 120,
        enabled: combatant.hasTalent(SPELLS.BASTION_OF_LIGHT_TALENT.id),
      },
    ];
  }
}

export default Abilities;
<commit_msg>Light of the Protector/Hand of the Protector are affected by Haste<commit_after>//import React from 'react';

import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import ISSUE_IMPORTANCE from 'Parser/Core/ISSUE_IMPORTANCE';

import CoreAbilities from 'Parser/Core/Modules/Abilities';

//import SpellLink from 'common/SpellLink';

class Abilities extends CoreAbilities {
  spellbook() {
    const combatant = this.combatants.selected;
    return [
      {
        spell: SPELLS.CONSECRATION_CAST,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: haste => 9 / (1 + haste),
        isOnGCD: true,
        castEfficiency: {
          suggestion: true,
          recommendedEfficiency: 0.9,
        },
      },
      {
        spell: SPELLS.BLESSED_HAMMER_TALENT,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: haste => 4.5 / (1 + haste),
        charges: 3,
        enabled: combatant.hasTalent(SPELLS.BLESSED_HAMMER_TALENT.id),
        castEfficiency: {
          suggestion: true,
          recommendedEfficiency: 0.9,
        },
      },
      {
        spell: SPELLS.AVENGERS_SHIELD,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: haste => 15 / (1 + haste),
        isOnGCD: true,
        castEfficiency: {
          suggestion: true,
          recommendedEfficiency: 0.9,
        },
      },
      // Probably useless to try to count the number of casts
      //Note by yajinni: Since this is thier main source of damage mitigation, without it they get hit like by a truck.
      //And a main source of damage, it should be tracked somewhat. Keeping it at 80% for now.
      {
        spell: SPELLS.SHIELD_OF_THE_RIGHTEOUS,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: haste => 16 / (1 + haste),
        charges: 3,
        castEfficiency: {
          suggestion: true,
          recommendedEfficiency: 0.8,
        },
      },
      { // T15: Holy Shield
        spell: SPELLS.HAMMER_OF_THE_RIGHTEOUS,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: haste => 4.5 / (1 + haste),
        charges: 2,
        isOnGCD: true,
        enabled: combatant.hasTalent(SPELLS.HOLY_SHIELD_TALENT.id),
        castEfficiency: {
          suggestion: true,
        },
      },
      { // T15: Blessed Hammer (replaces Hammer of the Righteous)
        spell: SPELLS.BLESSED_HAMMER_TALENT,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: haste => 4.5 / (1 + haste),
        charges: 3,
        isOnGCD: true,
        enabled: combatant.hasTalent(SPELLS.BLESSED_HAMMER_TALENT.id),
        castEfficiency: {
          suggestion: true,
          recommendedEfficiency: 0.9,
        },
      },
      { // T15: Consecrated Hammer talent (Hammer of the Righteous has no cooldown)
        spell: SPELLS.HAMMER_OF_THE_RIGHTEOUS,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        isOnGCD: true,
        enabled: combatant.hasTalent(SPELLS.CONSECRATED_HAMMER_TALENT.id),
      },
      {
        spell: SPELLS.JUDGMENT_CAST,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: haste => 6 / (1 + haste),
        charges: combatant.hasTalent(SPELLS.CRUSADERS_JUDGMENT_TALENT.id) ? 2 : 1,
        isOnGCD: true,
        castEfficiency: {
          suggestion: true,
        },
      },
      {
        spell: SPELLS.LIGHT_OF_THE_PROTECTOR,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: haste => 15 / (1 + haste) * (combatant.hasHead(ITEMS.SARUANS_RESOLVE.id) ? 0.9 : 1),
        charges: 1 + (combatant.hasHead(ITEMS.SARUANS_RESOLVE.id) ? 1 : 0),
        enabled: !combatant.hasTalent(SPELLS.HAND_OF_THE_PROTECTOR_TALENT.id),
        castEfficiency: {
          suggestion: true,
          recommendedEfficiency: 0.6,
          importance: ISSUE_IMPORTANCE.MINOR,
        },
      },
      {
        spell: SPELLS.HAND_OF_THE_PROTECTOR_TALENT,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: haste => 10 / (1 + haste) * (combatant.hasHead(ITEMS.SARUANS_RESOLVE.id) ? 0.9 : 1),
        charges: 1 + (combatant.hasHead(ITEMS.SARUANS_RESOLVE.id) ? 1 : 0),
        enabled: combatant.hasTalent(SPELLS.HAND_OF_THE_PROTECTOR_TALENT.id),
        castEfficiency: {
          suggestion: true,
          recommendedEfficiency: 0.6,
          importance: ISSUE_IMPORTANCE.MINOR,
        },
      },
      //COOLDOWNS
      {
        spell: SPELLS.EYE_OF_TYR,
        category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
        cooldown: (haste, combatant) => 60 * (combatant.hasShoulder(ITEMS.PILLARS_OF_INMOST_LIGHT.id) ? 0.75 : 1),
        isOnGCD: true,
        castEfficiency: {
          suggestion: true,
          recommendedEfficiency: 0.85,
        },
      },
      {
        spell: SPELLS.ARDENT_DEFENDER,
        category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
        cooldown: 120 - (combatant.traitsBySpellId[SPELLS.UNFLINCHING_DEFENSE.id] || 0) * 10,
        castEfficiency: {
          suggestion: true,
        },
      },
      {
        spell: SPELLS.GUARDIAN_OF_ANCIENT_KINGS,
        category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
        cooldown: 300,
        castEfficiency: {
          suggestion: true,
        },
      },
      {
        spell: SPELLS.SERAPHIM_TALENT,
        category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
        cooldown: 45,
        enabled: combatant.hasTalent(SPELLS.SERAPHIM_TALENT.id),
        castEfficiency: {
          suggestion: true,
        },
      },
      {
        spell: SPELLS.AVENGING_WRATH_RET,
        category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
        cooldown: 120,
        // castEfficiency: {
        //   suggestion: true,
        //   recommendedEfficiency: 0.85,
        // },
      },
      {
        spell: SPELLS.LAY_ON_HANDS,
        category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
        cooldown: 600,
        castEfficiency: {
          suggestion: true,
          recommendedEfficiency: 0.1,
        },
      },
      {
        spell: SPELLS.FLASH_OF_LIGHT,
        category: Abilities.SPELL_CATEGORIES.OTHERS,
        isOnGCD: true,
      },
      {
        spell: SPELLS.DIVINE_STEED,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 45 * (combatant.hasTalent(SPELLS.KNIGHT_TEMPLAR_TALENT.id) ? 0.5 : 1),
        charges: combatant.hasTalent(SPELLS.CAVALIER_TALENT.id) ? 2 : 1,
        isOnGCD: true,
      },
      {
        spell: SPELLS.BLESSING_OF_FREEDOM,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 25,
        isOnGCD: true,
      },
      {
        spell: SPELLS.BLESSING_OF_PROTECTION,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 5 * 60,
        isOnGCD: true,
        enabled: !combatant.hasTalent(SPELLS.BLESSING_OF_SPELLWARDING_TALENT.id),
      },
      {
        spell: SPELLS.BLESSING_OF_SPELLWARDING_TALENT,
        category: Abilities.SPELL_CATEGORIES.COOLDOWNS,
        cooldown: 180,
        isOnGCD: true,
        enabled: combatant.hasTalent(SPELLS.BLESSING_OF_SPELLWARDING_TALENT.id),
      },
      {
        spell: SPELLS.BLESSING_OF_SACRIFICE,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 2.5 * 60 - (combatant.traitsBySpellId[SPELLS.SACRIFICE_OF_THE_JUST.id] || 0) * 60,
        // castEfficiency: {
        //   suggestion: true,
        //   recommendedEfficiency: 0.85,
        // },
      },
      {
        spell: SPELLS.AEGIS_OF_LIGHT_TALENT,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 180,
        isOnGCD: true,
        enabled: combatant.hasTalent(SPELLS.AEGIS_OF_LIGHT_TALENT.id),
      },
      {
        spell: SPELLS.CLEANSE_TOXINS,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 8,
        isOnGCD: true,
      },
      {
        spell: SPELLS.HAMMER_OF_JUSTICE,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 60,
        isOnGCD: true,
      },
      {
        spell: SPELLS.HAND_OF_RECKONING,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 8,
      },
      {
        spell: SPELLS.REBUKE,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 15,
      },
      {
        spell: SPELLS.BLINDING_LIGHT_TALENT,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 90,
        isOnGCD: true,
        enabled: combatant.hasTalent(SPELLS.BLINDING_LIGHT_TALENT.id),
      },
      {
        spell: SPELLS.REPENTANCE_TALENT,
        category: Abilities.SPELL_CATEGORIES.UTILITY,
        cooldown: 15,
        isOnGCD: true,
        enabled: combatant.hasTalent(SPELLS.REPENTANCE_TALENT.id),
      },
      {
        spell: SPELLS.BASTION_OF_LIGHT_TALENT,
        category: Abilities.SPELL_CATEGORIES.ROTATIONAL,
        cooldown: 120,
        enabled: combatant.hasTalent(SPELLS.BASTION_OF_LIGHT_TALENT.id),
      },
    ];
  }
}

export default Abilities;
<|endoftext|>


<commit_before>const expect = require('expect.js');
const system = require('../system');
const supertest = require('supertest');

describe('Service Tests', () => {
  let request;
  let sys;

  before(done => {
    sys = system().start((err, { app }) => {
      if (err) return done(err);
      request = supertest(app);
      done();
    });
  });

  after(done => sys.stop(done));

  it('should return manifest', () =>
    request
      .get('/__/manifest')
      .expect(200)
      .then((response) => {
        expect(response.headers['content-type']).to.equal('application/json; charset=utf-8');
      }));
});
<commit_msg>Fix tests<commit_after>const expect = require('expect.js');
const system = require('../system');
const supertest = require('supertest');

describe('Service Tests', () => {
  let request;
  let sys = system();

  before(done => {
    sys.start((err, { app }) => {
      if (err) return done(err);
      request = supertest(app);
      done();
    });
  });

  after(done => { sys.stop(done) });s

  it('should return manifest', () =>
    request
      .get('/__/manifest')
      .expect(200)
      .then((response) => {
        expect(response.headers['content-type']).to.equal('application/json; charset=utf-8');
      }));
});
<|endoftext|>


<commit_before>'use strict';
Template.home.created = function () {
	this.subscribe('displayedBuilds');
};

Template.home.helpers({
	build: function () {
		return Collections.Builds.findOne({_id: this.buildId});
	},
	buildOrder: function () {
		return Collections.MyBuildDisplay.find({isDisplayed: true}, {sort: {sort: 1}});
	}
});

function _updateTime() {
	Session.set('timestamp', Date.now());
}

Template.clockBar.created = function() {
	setInterval(_updateTime, 1000);
};

Template.clockBar.helpers({
	currentDate: function () {
		return moment(Session.get('timestamp')).format('MMMM Do YYYY');
	},
	currentTime: function () {
		return moment(Session.get('timestamp')).tz("America/Chicago").format('HH:mm:ss z');
	},
	utcTime: function () {
		return moment(Session.get('timestamp')).tz("UTC").format('HH:mm:ss z');
	}
});

Template.buildItem.helpers({
	sizeClass: function () {
		var user = Meteor.user();
		if (!user.profile || !user.profile.sizeClass) {
			return 'col-xs-12 col-sm-6 col-md-4 col-lg-3';
		}
		return Meteor.user().profile.sizeClass;
	},
	myBigName: function () {
		var myItem = Collections.MyBuildDisplay.findOne({buildId: this._id});
		if (!myItem || s.isBlank(myItem.shortName)) {
			return this.name;
		}

		return myItem.shortName;
	},

	isBuildingClass: function () {
		return this.isBuilding ? 'blink_me' : '';
	},

	buildStateClass: function () {
		return this.isLastBuildSuccess ? 'success' : 'error';
	},

	lastBuild: function () {
		if (!this.builds || this.builds.length <= 0) {
			return null;
		}

		return this.builds[0];
	},

	buildTime: function (start, end) {
		var td = moment.duration(moment(end).diff(start));
		return s.lpad(td.minutes(), 2, '0') + ':' + s.lpad(td.seconds(), 2, '0');
	}
});

Template.buildHistory.helpers({
	icon: function () {
		if (this.isBuilding) {
			return 'fa-spinner faa-spin animated';
		}

		return this.isSuccess ? 'fa-check-circle' : 'fa-times-circle';
	},

	bhClass: function () {
		return this.isSuccess ? 'bh-succ' : 'bh-fail';
	}
});
<commit_msg>Updating icons<commit_after>'use strict';
Template.home.created = function () {
	this.subscribe('displayedBuilds');
};

Template.home.helpers({
	build: function () {
		return Collections.Builds.findOne({_id: this.buildId});
	},
	buildOrder: function () {
		return Collections.MyBuildDisplay.find({isDisplayed: true}, {sort: {sort: 1}});
	}
});

function _updateTime() {
	Session.set('timestamp', Date.now());
}

Template.clockBar.created = function() {
	setInterval(_updateTime, 1000);
};

Template.clockBar.helpers({
	currentDate: function () {
		return moment(Session.get('timestamp')).format('MMMM Do YYYY');
	},
	currentTime: function () {
		return moment(Session.get('timestamp')).tz("America/Chicago").format('HH:mm:ss z');
	},
	utcTime: function () {
		return moment(Session.get('timestamp')).tz("UTC").format('HH:mm:ss z');
	}
});

Template.buildItem.helpers({
	sizeClass: function () {
		var user = Meteor.user();
		if (!user.profile || !user.profile.sizeClass) {
			return 'col-xs-12 col-sm-6 col-md-4 col-lg-3';
		}
		return Meteor.user().profile.sizeClass;
	},
	myBigName: function () {
		var myItem = Collections.MyBuildDisplay.findOne({buildId: this._id});
		if (!myItem || s.isBlank(myItem.shortName)) {
			return this.name;
		}

		return myItem.shortName;
	},

	isBuildingClass: function () {
		return this.isBuilding ? 'blink_me' : '';
	},

	buildStateClass: function () {
		return this.isLastBuildSuccess ? 'success' : 'error';
	},

	lastBuild: function () {
		if (!this.builds || this.builds.length <= 0) {
			return null;
		}

		return this.builds[0];
	},

	buildTime: function (start, end) {
		var td = moment.duration(moment(end).diff(start));
		return s.lpad(td.minutes(), 2, '0') + ':' + s.lpad(td.seconds(), 2, '0');
	}
});

Template.buildHistory.helpers({
	icon: function () {
		if (this.isBuilding) {
			return 'fa-magic faa-wrench animated';
		}

		return this.isSuccess ? 'fa-sun-o' : 'fa-moon-o';
	},

	bhClass: function () {
		return this.isSuccess ? 'bh-succ' : 'bh-fail';
	}
});
<|endoftext|>


<commit_before>/**
 * Created by rinesnow on 16/3/29.
 */
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var crypto = require('crypto');
var session= require('express-session');
var moment = require('moment');
var authentication = require('./authentication.js');

var app = express();

//连接数据库
var mongoose = require('mongoose');
var models = require('./models/models');

var User = models.User;
var Intern = models.Intern;

mongoose.connect('mongodb://localhost:27017/interns');
mongoose.connection.on('error',console.error.bind(console,'连接数据库失败!'));

//定义EJS模版引擎和末班文件位置
app.set('views', path.join(__dirname,'views'));
app.set('view engine','ejs');

//定义静态文件目录
app.use(express.static(path.join(__dirname,'public')));

//定义数据解析器
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

//建立session模型
app.use(session({
    secret:'liuchong',//?
    name:'intern',
    //一周内免登录
    cookie:{maxAge:1000 * 60 * 60*24*7},//设置session的保存时间为 60min*24小时*7一周
    resave: false,
    saveUnintiallized:true
}));

//添加  页面提示功能
app.use(function(req, res, next) {
    res.locals.user = req.session.user;//???
    var err = req.session.error;//赋值给err变量,
    //var success = req.session.success;//赋值给err变量,

    delete req.session.error;//然后清空session内的数据
    res.locals.message = '';//初始化
    //res.locals.success = '';//初始化

    if (err) {
        //html通过js被操作,在html中用{%-message%}调用
        res.locals.message = '
' + err + '
';
    }
    //if (success) {
    //    //html通过js被操作,在html中用{%-message%}调用
    //    res.locals.success = '
' + success + '
';
    //}

    next();//?
});

   var OAuth = require('wechat-oauth');
   var client = new OAuth('wx75d11b4f981b1ded', '7a915c525f39451f3af19407012459ad');
 // var openid='hehehe';
app.use(function ifAuthorized(req,res,next){

    // var url = client.getAuthorizeURL('www.coderwitkey.com', 'STATE', 'snsapi_userinfo');
    var query = require('url').parse(req.url,true).query;
          console.log(query);

    var code = query.code;
          console.log(code);

    client.getUserByCode(code,function (err, result) {
      // var accessToken = result.data.access_token;
      var openid = result.openid;//必须要手动点击URL，原地刷新没用的。

      console.log(result);
      // console.log(accessToken);

      console.log("这是openid2"+openid);

       User.findOne({openid:openid},function(err,user){
           if(err){
               console.log(err);
           }
            // if(user){//有这个user 那么直接跳转
            //     return res.redirect('/');
            // }
            // //对密码进行md5加密
            // var md5 = crypto.createHash('md5'),
            //     md5newopenid = md5.update(openid).digest('hex');
            //新建user对象用于保存数据
            var newUser = new User({

                openid:openid,//openid 作为key存入，以后再用用户信息就用openid调。
                nickname:result.nickname,
                headimg:result.headimgurl
            });

            newUser.save(function(err,doc){
                if(err){
                    console.log("保存用户信息失败！"+err);
                }
                console.log('保存用户信息成功!');//怎么实现弹出框!!!!??????
                return res.redirect('/');
            });
        });
    });
    req.code=code;
    next();
});

//响应首页get请求
// app.get('/',authentication.ifAuthorized);//检测是否登录了
app.get('/',function(req,res){
    // console.log('res.code:'+res.code);

    // client.getUserByCode(res.code,function (err, result) {
    //   // var accessToken = result.data.access_token;
    //   var openid = result.openid;//必须要手动点击URL，原地刷新没用的。

    //   console.log(result);
    //   // console.log(accessToken);

    //   console.log("这是openid2"+openid);

    //    Intern.findOne({createTime:createTime},function(err,intern){
    //        if(err){
    //            console.log(err);
    //        }
    //         if(user){//有这个user 那么直接跳转
    //             return res.redirect('/');
    //         }
    //         // //对密码进行md5加密
    //         // var md5 = crypto.createHash('md5'),
    //         //     md5newopenid = md5.update(openid).digest('hex');
    //         //新建user对象用于保存数据
    //         var newUser = new User({

    //             openid:openid,//openid 作为key存入，以后再用用户信息就用openid调。
    //             nickname:result.nickname,
    //             headimg:result.headimgurl
    //         });

    //         newUser.save(function(err,doc){
    //             if(err){
    //                 console.log("保存用户信息失败！"+err);
    //             }
    //             console.log('保存用户信息成功!');//怎么实现弹出框!!!!??????
    //             return res.redirect('/');
    //         });
    //     });
    // });
    // console.log('发布!');
    // res.render('post',{
    //     user: req.session.user,//也要加?
    //     title:'发布'
    // });
    // Note.find({author:openid}).exec(function(err,allNotes){
    //     if(err){
    //         console.log(err);
    //         return res.redirect('/');
    //     }
    //     res.render('index',{
    //        title:'首页',
    //         openid: openid,
    //         notes:allNotes
    //     });
    // })
});

//登出
app.get('/quit',function(req,res){
    //退出功能只需将session中的user删除即可。
    // req.session.user = null;
    console.log('退出!');
    return res.redirect('/login');
});

//发布

//响应发布get请求
// app.get('/post',authentication.ifAuthorized);//检测是否登录了
app.get('/post',function(req,res){
   console.log('发布!');
    res.render('post',{
        user: req.session.user,//也要加?
        title:'发布'
    });
});
//响应发布post请求
app.post('/post',function(req,res){

     User.findOne({openid:openid},function(err,user){
           if(err){
               console.log(err);
           }
            if(user){//有这个user 那么直接跳转
                return res.redirect('/');
            }
        });
   var note = new Note({
       title:req.body.title,
       author:openid,
       tag: req.body.tag,
       content: req.body.content
   });
    note.save(function(err,doc){
       if(err){
           console.log(err);
           return res.redirect('/post');
       }
        console.log('文章发表成功!')
        return res.redirect('/');
    });
});
//

//博客细节

// app.get('/detail/',authentication.ifAuthorized);//检测是否登录了
app.get('/detail/:_id',function(req,res){//:id?
   console.log('查看笔记!');
    Note.findOne({_id:req.params._id}).exec(function(err,art){
        if(err){
            console.log(err);
            return res.redirect('/');
        }
        if(art) {
            res.render('detail', {
                title: '笔记详情',
                user: req.session.user,
                art: art,
                moment:moment
            });
            console.log(art);
        }
    });
});

// app.get('https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx75d11b4f981b1ded&secret=7a915c525f39451f3af19407012459ad&code=CODE&grant_type=authorization_code',function(req,res){

// });//获取appid

app.listen(3000, function(req,res){
    console.log('app is running at port 3000');
});<commit_msg>yonghu id<commit_after>/**
 * Created by rinesnow on 16/3/29.
 */
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var crypto = require('crypto');
var session= require('express-session');
var moment = require('moment');
var authentication = require('./authentication.js');

var app = express();

//连接数据库
var mongoose = require('mongoose');
var models = require('./models/models');

var User = models.User;
var Intern = models.Intern;

mongoose.connect('mongodb://localhost:27017/interns');
mongoose.connection.on('error',console.error.bind(console,'连接数据库失败!'));

//定义EJS模版引擎和末班文件位置
app.set('views', path.join(__dirname,'views'));
app.set('view engine','ejs');

//定义静态文件目录
app.use(express.static(path.join(__dirname,'public')));

//定义数据解析器
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

//建立session模型
app.use(session({
    secret:'liuchong',//?
    name:'intern',
    //一周内免登录
    cookie:{maxAge:1000 * 60 * 60*24*7},//设置session的保存时间为 60min*24小时*7一周
    resave: false,
    saveUnintiallized:true
}));

//添加  页面提示功能
app.use(function(req, res, next) {
    res.locals.user = req.session.user;//???
    var err = req.session.error;//赋值给err变量,
    //var success = req.session.success;//赋值给err变量,

    delete req.session.error;//然后清空session内的数据
    res.locals.message = '';//初始化
    //res.locals.success = '';//初始化

    if (err) {
        //html通过js被操作,在html中用{%-message%}调用
        res.locals.message = '
' + err + '
';
    }
    //if (success) {
    //    //html通过js被操作,在html中用{%-message%}调用
    //    res.locals.success = '
' + success + '
';
    //}

    next();//?
});

   var OAuth = require('wechat-oauth');
   var client = new OAuth('wx75d11b4f981b1ded', '7a915c525f39451f3af19407012459ad');
 // var openid='hehehe';
app.use(function ifAuthorized(req,res,next){

    // var url = client.getAuthorizeURL('www.coderwitkey.com', 'STATE', 'snsapi_userinfo');
    var query = require('url').parse(req.url,true).query;
          console.log(query);

    var code = query.code;
          console.log(code);

    client.getUserByCode(code,function (err, result) {
      // var accessToken = result.data.access_token;
      var openid = result.openid;//必须要手动点击URL，原地刷新没用的。

      console.log('这是result:'+result);
      // console.log(accessToken);

      console.log("这是openid2"+openid);

       User.findOne({openid:openid},function(err,user){
           if(err){
               console.log('这是err'+err);
           }
            // if(user){//有这个user 那么直接跳转
            //     return res.redirect('/');
            // }
            // //对密码进行md5加密
            // var md5 = crypto.createHash('md5'),
            //     md5newopenid = md5.update(openid).digest('hex');
            //新建user对象用于保存数据
            var newUser = new User({

                openid:openid,//openid 作为key存入，以后再用用户信息就用openid调。
                nickname:result.nickname,
                headimg:result.headimgurl
            });

            newUser.save(function(err,doc){
                if(err){
                    console.log("保存用户信息失败！"+err);
                }
                console.log('保存用户信息成功!');//怎么实现弹出框!!!!??????
                return res.redirect('/');
            });
        });
    });
    req.code=code;
    next();
});

//响应首页get请求
// app.get('/',authentication.ifAuthorized);//检测是否登录了
app.get('/',function(req,res){
    // console.log('res.code:'+res.code);

    // client.getUserByCode(res.code,function (err, result) {
    //   // var accessToken = result.data.access_token;
    //   var openid = result.openid;//必须要手动点击URL，原地刷新没用的。

    //   console.log(result);
    //   // console.log(accessToken);

    //   console.log("这是openid2"+openid);

    //    Intern.findOne({createTime:createTime},function(err,intern){
    //        if(err){
    //            console.log(err);
    //        }
    //         if(user){//有这个user 那么直接跳转
    //             return res.redirect('/');
    //         }
    //         // //对密码进行md5加密
    //         // var md5 = crypto.createHash('md5'),
    //         //     md5newopenid = md5.update(openid).digest('hex');
    //         //新建user对象用于保存数据
    //         var newUser = new User({

    //             openid:openid,//openid 作为key存入，以后再用用户信息就用openid调。
    //             nickname:result.nickname,
    //             headimg:result.headimgurl
    //         });

    //         newUser.save(function(err,doc){
    //             if(err){
    //                 console.log("保存用户信息失败！"+err);
    //             }
    //             console.log('保存用户信息成功!');//怎么实现弹出框!!!!??????
    //             return res.redirect('/');
    //         });
    //     });
    // });
    // console.log('发布!');
    // res.render('post',{
    //     user: req.session.user,//也要加?
    //     title:'发布'
    // });
    // Note.find({author:openid}).exec(function(err,allNotes){
    //     if(err){
    //         console.log(err);
    //         return res.redirect('/');
    //     }
    //     res.render('index',{
    //        title:'首页',
    //         openid: openid,
    //         notes:allNotes
    //     });
    // })
});

//登出
app.get('/quit',function(req,res){
    //退出功能只需将session中的user删除即可。
    // req.session.user = null;
    console.log('退出!');
    return res.redirect('/login');
});

//发布

//响应发布get请求
// app.get('/post',authentication.ifAuthorized);//检测是否登录了
app.get('/post',function(req,res){
   console.log('发布!');
    res.render('post',{
        user: req.session.user,//也要加?
        title:'发布'
    });
});
//响应发布post请求
app.post('/post',function(req,res){

     User.findOne({openid:openid},function(err,user){
           if(err){
               console.log(err);
           }
            if(user){//有这个user 那么直接跳转
                return res.redirect('/');
            }
        });
   var note = new Note({
       title:req.body.title,
       author:openid,
       tag: req.body.tag,
       content: req.body.content
   });
    note.save(function(err,doc){
       if(err){
           console.log(err);
           return res.redirect('/post');
       }
        console.log('文章发表成功!')
        return res.redirect('/');
    });
});
//

//博客细节

// app.get('/detail/',authentication.ifAuthorized);//检测是否登录了
app.get('/detail/:_id',function(req,res){//:id?
   console.log('查看笔记!');
    Note.findOne({_id:req.params._id}).exec(function(err,art){
        if(err){
            console.log(err);
            return res.redirect('/');
        }
        if(art) {
            res.render('detail', {
                title: '笔记详情',
                user: req.session.user,
                art: art,
                moment:moment
            });
            console.log(art);
        }
    });
});

// app.get('https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx75d11b4f981b1ded&secret=7a915c525f39451f3af19407012459ad&code=CODE&grant_type=authorization_code',function(req,res){

// });//获取appid

app.listen(3000, function(req,res){
    console.log('app is running at port 3000');
});<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependenices.
 */

var debug = require('debug')('secc:scheduler');
var os = require('os');
var path = require('path');

var bodyParser = require('body-parser');
var compression = require('compression');
var express = require('express');
var multer  = require('multer');

/**
 * Exports scheduler.
 */

module.exports = Scheduler;

/**
 * Scheduler Object.
 *
 * @param {Settings} SECC
 */

function Scheduler(SECC) {
  if (!(this instanceof Scheduler)) return new Scheduler(SECC);

  this.SECC = SECC || {scheduler : {}};
  this.SECC.scheduler.port = process.env.SECC_PORT || 10509;

  if (!this.SECC.archivePath || this.SECC.archivePath === '')
    this.SECC.archivePath = path.join(__dirname, '..', 'archive');
  if (!this.SECC.uploadPath || this.SECC.uploadPath === '')
    this.SECC.uploadPath = path.join(os.tmpdir(), 'secc', 'scheduler_upload');
  this.SECC.experimental = this.SECC.experimental || {allowLocalDaemon : false};

  this.server = null;
  this.sockets = {};
  this.nextSocketId = 0;

  require('mkdirp').sync(this.SECC.archivePath);
  require('mkdirp').sync(this.SECC.uploadPath);
}

function isEmptyObject(obj) {
  return (Object.keys(obj).length === 0);
}

/**
 * Init http server
 */

Scheduler.prototype.initServer = function(successCallback, failureCallback) {
  var self = this;

  if (!isEmptyObject(self.sockets))
    return failureCallback('Server is already initialized.');

  var SECC = this.SECC;
  var app = express();
  var server = require('http').Server(app);
  var io = require('socket.io')(server);
  var upload = multer({dest:SECC.uploadPath}).single('archiveFile');

  // set member variable
  this.server = server;

  app.set('views', path.join(__dirname, '..', 'views'));
  app.set('view engine', 'ejs');
  app.use(express.static(path.join(__dirname, '..', 'views')));
  app.use(express.static(path.join(__dirname, '..', 'public')));

  app.use(compression());
  app.use(bodyParser.json()); // for parsing application/json
  app.use(bodyParser.text()); // for parsing text/plain
  app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
  app.use(upload); // for parsing multipart/form-data
  app.use(require('morgan')('combined'));

  app.use(function(err, req, res, next) {
    console.error(err.stack);
    res.status(500).send('Something broke!');
  });

  //app.use(compression);
  var SCHEDULER = {};
  SCHEDULER.am = require('./archivemanager.js')(express, io, SECC, SCHEDULER);
  SCHEDULER.cm = require('./cachemanager.js')(express, io, SECC), SCHEDULER;
  SCHEDULER.dm = require('./daemonmanager.js')(express, io, SECC, SCHEDULER);
  SCHEDULER.jm = require('./jobmanager.js')(express, io, SECC, SCHEDULER);
  SCHEDULER.om = require('./optionmanager.js')();

  //WebSocket and routers
  var schedulerWebSocket = require('../routes/schedulerWebSocket')(express, io, SECC, SCHEDULER);
  var schedulerIndex = require('../routes/schedulerIndex')(express, io, SECC, SCHEDULER);
  var schedulerArchive = require('../routes/schedulerArchive')(express, io, SECC, SCHEDULER);
  var schedulerCache = require('../routes/schedulerCache')(express, io, SECC, SCHEDULER);
  var schedulerDaemon = require('../routes/schedulerDaemon')(express, io, SECC, SCHEDULER);
  var schedulerJob = require('../routes/schedulerJob')(express, io, SECC, SCHEDULER);
  var schedulerOption = require('../routes/schedulerOption')(express, io, SECC, SCHEDULER);
  var schedulerView = require('../routes/schedulerView')(express, io, SECC, SCHEDULER);

  app.use('/', schedulerIndex);
  app.use('/archive/', schedulerArchive);
  app.use('/cache/', schedulerCache);
  app.use('/daemon/', schedulerDaemon);
  app.use('/job/', schedulerJob);
  app.use('/option/', schedulerOption);
  app.use('/view/', schedulerView);

  successCallback('Server initialized');
}

/**
 * Start scheduer method
 */
Scheduler.prototype.startServer = function(successCallback, failureCallback) {
  var self = this;

  self.initServer(function(msg){
    debug(msg);

    var SECC = self.SECC;
    var server = self.server;

    if(!SECC || !server)
      return failureCallback('Server or SECC is null');

    // Server start listening
    server.on('error', failureCallback);  // in case of 'Error: listen EACCES'
    server.listen(SECC.scheduler.port, function() {
      var host = server.address().address;
      var port = server.address().port;

      console.log('secc-scheduler listening at http://%s:%s', host, port);

      // when server created successfully, call successCallback.
      server.removeListener('error', failureCallback);
      successCallback('Server has started');
    });

    // Server connection event
    server.on('connection', function (socket) {
      // Add a newly connected socket
      var socketId = self.nextSocketId++;
      self.sockets[socketId] = socket;

      // Remove the socket when it closes
      socket.on('close', function () {
        delete self.sockets[socketId];
      });
    });
  }, failureCallback);
}

/**
 * Stop scheduer method
 */
Scheduler.prototype.stopServer = function(successCallback, failureCallback) {
  var self = this;

  if(!isEmptyObject(self.sockets)) {
    // Before close is called, it check handle===0 && connections===0.
    // If connections exist, do not working close event.
    self.server.getConnections(function(err, count) {
      if (count) {
        // destroy all sockes
        for (var socketId in self.sockets) {
          self.sockets[socketId].destroy();
        }

        self.server.close(function(){
          debug('Server closed');

          self.nextSocketId = 0;
          self.server = null;
          self.sockets = {};

          successCallback('Server has stopped');
        });
      }
    }); // end getConnections
  } else {
    failureCallback('Server is already stopped');
  }
}

/* End of File */<commit_msg>[scheduler] bug fix. wrong braket position<commit_after>'use strict';

/**
 * Module dependenices.
 */

var debug = require('debug')('secc:scheduler');
var os = require('os');
var path = require('path');

var bodyParser = require('body-parser');
var compression = require('compression');
var express = require('express');
var multer  = require('multer');

/**
 * Exports scheduler.
 */

module.exports = Scheduler;

/**
 * Scheduler Object.
 *
 * @param {Settings} SECC
 */

function Scheduler(SECC) {
  if (!(this instanceof Scheduler)) return new Scheduler(SECC);

  this.SECC = SECC || {scheduler : {}};
  this.SECC.scheduler.port = process.env.SECC_PORT || 10509;

  if (!this.SECC.archivePath || this.SECC.archivePath === '')
    this.SECC.archivePath = path.join(__dirname, '..', 'archive');
  if (!this.SECC.uploadPath || this.SECC.uploadPath === '')
    this.SECC.uploadPath = path.join(os.tmpdir(), 'secc', 'scheduler_upload');
  this.SECC.experimental = this.SECC.experimental || {allowLocalDaemon : false};

  this.server = null;
  this.sockets = {};
  this.nextSocketId = 0;

  require('mkdirp').sync(this.SECC.archivePath);
  require('mkdirp').sync(this.SECC.uploadPath);
}

function isEmptyObject(obj) {
  return (Object.keys(obj).length === 0);
}

/**
 * Init http server
 */

Scheduler.prototype.initServer = function(successCallback, failureCallback) {
  var self = this;

  if (!isEmptyObject(self.sockets))
    return failureCallback('Server is already initialized.');

  var SECC = this.SECC;
  var app = express();
  var server = require('http').Server(app);
  var io = require('socket.io')(server);
  var upload = multer({dest:SECC.uploadPath}).single('archiveFile');

  // set member variable
  this.server = server;

  app.set('views', path.join(__dirname, '..', 'views'));
  app.set('view engine', 'ejs');
  app.use(express.static(path.join(__dirname, '..', 'views')));
  app.use(express.static(path.join(__dirname, '..', 'public')));

  app.use(compression());
  app.use(bodyParser.json()); // for parsing application/json
  app.use(bodyParser.text()); // for parsing text/plain
  app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
  app.use(upload); // for parsing multipart/form-data
  app.use(require('morgan')('combined'));

  app.use(function(err, req, res, next) {
    console.error(err.stack);
    res.status(500).send('Something broke!');
  });

  //app.use(compression);
  var SCHEDULER = {};
  SCHEDULER.am = require('./archivemanager.js')(express, io, SECC, SCHEDULER);
  SCHEDULER.cm = require('./cachemanager.js')(express, io, SECC, SCHEDULER);
  SCHEDULER.dm = require('./daemonmanager.js')(express, io, SECC, SCHEDULER);
  SCHEDULER.jm = require('./jobmanager.js')(express, io, SECC, SCHEDULER);
  SCHEDULER.om = require('./optionmanager.js')();

  //WebSocket and routers
  var schedulerWebSocket = require('../routes/schedulerWebSocket')(express, io, SECC, SCHEDULER);
  var schedulerIndex = require('../routes/schedulerIndex')(express, io, SECC, SCHEDULER);
  var schedulerArchive = require('../routes/schedulerArchive')(express, io, SECC, SCHEDULER);
  var schedulerCache = require('../routes/schedulerCache')(express, io, SECC, SCHEDULER);
  var schedulerDaemon = require('../routes/schedulerDaemon')(express, io, SECC, SCHEDULER);
  var schedulerJob = require('../routes/schedulerJob')(express, io, SECC, SCHEDULER);
  var schedulerOption = require('../routes/schedulerOption')(express, io, SECC, SCHEDULER);
  var schedulerView = require('../routes/schedulerView')(express, io, SECC, SCHEDULER);

  app.use('/', schedulerIndex);
  app.use('/archive/', schedulerArchive);
  app.use('/cache/', schedulerCache);
  app.use('/daemon/', schedulerDaemon);
  app.use('/job/', schedulerJob);
  app.use('/option/', schedulerOption);
  app.use('/view/', schedulerView);

  successCallback('Server initialized');
}

/**
 * Start scheduer method
 */
Scheduler.prototype.startServer = function(successCallback, failureCallback) {
  var self = this;

  self.initServer(function(msg){
    debug(msg);

    var SECC = self.SECC;
    var server = self.server;

    if(!SECC || !server)
      return failureCallback('Server or SECC is null');

    // Server start listening
    server.on('error', failureCallback);  // in case of 'Error: listen EACCES'
    server.listen(SECC.scheduler.port, function() {
      var host = server.address().address;
      var port = server.address().port;

      console.log('secc-scheduler listening at http://%s:%s', host, port);

      // when server created successfully, call successCallback.
      server.removeListener('error', failureCallback);
      successCallback('Server has started');
    });

    // Server connection event
    server.on('connection', function (socket) {
      // Add a newly connected socket
      var socketId = self.nextSocketId++;
      self.sockets[socketId] = socket;

      // Remove the socket when it closes
      socket.on('close', function () {
        delete self.sockets[socketId];
      });
    });
  }, failureCallback);
}

/**
 * Stop scheduer method
 */
Scheduler.prototype.stopServer = function(successCallback, failureCallback) {
  var self = this;

  if(!isEmptyObject(self.sockets)) {
    // Before close is called, it check handle===0 && connections===0.
    // If connections exist, do not working close event.
    self.server.getConnections(function(err, count) {
      if (count) {
        // destroy all sockes
        for (var socketId in self.sockets) {
          self.sockets[socketId].destroy();
        }

        self.server.close(function(){
          debug('Server closed');

          self.nextSocketId = 0;
          self.server = null;
          self.sockets = {};

          successCallback('Server has stopped');
        });
      }
    }); // end getConnections
  } else {
    failureCallback('Server is already stopped');
  }
}

/* End of File */<|endoftext|>


<commit_before>var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {
	console.log("Port Number : 3000");
    res.writeHead(200, {'Content-Type': 'video/mp4'});
    // change the to 'text/plain' to 'text/html' it will work as your index page
	var file = 'index.mp3';
	fs.exists('audio.mp3',function(exists){
		if(exists)
		{
			var rstream = fs.createReadStream('audio.mp3');
			rstream.pipe(res);
		}
		else
		{
			res.send("Its a 404");
			res.end();
		}

	});

}).listen(3000);

	<commit_msg>updated serve-mp3<commit_after>var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {
	console.log("Port Number : 3000");
	// change MIME type to 'audio/mp3'
    res.writeHead(200, {'Content-Type': 'audio/mp3'});
    fs.exists('audio.mp3',function(exists){
		if(exists)
		{
			var rstream = fs.createReadStream('audio.mp3');
			rstream.pipe(res);
		}
		else
		{
			res.end("Its a 404");
		}

	});

}).listen(3000);

	<|endoftext|>


<commit_before>var mongo = require('mongodb'),
	nconf = require('nconf'),
	assert = require('assert');

var Server = mongo.Server,
	Db = mongo.Db,
	Client = mongo.MongoClient,
	ObjectId = mongo.ObjectID;

nconf.env(['mongodb:connection'])
	.file('api/config.json');

var uri = nconf.get('mongodb:connection');
var os = require('os');
var networkInterfaces = os.networkInterfaces();
console.log(os.hostname());
console.log(networkInterfaces);

var Allowed = function (req, res) {
	//var ip = req.ip || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;
	//console.log(ip);
	//return (ip === '');

	res.send(req);
}

module.exports.GetAll = function (req, res) {
	if (!Allowed(req, res)) {
		res.end(403, 'Forbidden');
	};

	Client.connect(uri, function (err, db) {
		assert.equal(err, null);

		db.collection('WeWantTrubel-Petitioners')
			.find()
			.toArray(function (err, docs) {
				assert.equal(err, null);
				res.send(docs);
			});
	});
};

module.exports.Post = function (req, res) {

};<commit_msg>Secure by proper design! Ha! And IPs!<commit_after>var mongo = require('mongodb'),
	nconf = require('nconf'),
	assert = require('assert');

var Server = mongo.Server,
	Db = mongo.Db,
	Client = mongo.MongoClient,
	ObjectId = mongo.ObjectID;

nconf.env(['mongodb:connection'])
	.file('api/config.json');

var uri = nconf.get('mongodb:connection');
var os = require('os');
var networkInterfaces = os.networkInterfaces();
console.log(os.hostname());
console.log(networkInterfaces);

var Allowed = function (req, res) {
	//var ip = req.ip || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;
	//console.log(ip);
	//return (ip === '');

	console.log(req.hostname);
	console.dir(req.ips);

	return true;
}

module.exports.GetAll = function (req, res) {
	if (!Allowed(req, res)) {
		res.end(403, 'Forbidden');
	};

	Client.connect(uri, function (err, db) {
		assert.equal(err, null);

		db.collection('WeWantTrubel-Petitioners')
			.find({}, { "Name": 1, "Location": 1, "TimeStamp": 1 })
			.sort({ "TimeStamp": -1 })
			.toArray(function (err, docs) {
				assert.equal(err, null);
				res.send(docs);
			});
	});
};

module.exports.Post = function (req, res) {

};<|endoftext|>


<commit_before>import React from 'react'
import _ from 'underscore'
import ArrayComponent from './array'
import ObjectComponent from './object'
import DotObject from 'dot-object'
import {docToModifier} from './utility'
import Field from './field'

const propTypes = {
  /**
   * The object that has the values of the form.
   */
  state: React.PropTypes.object,
  /**
   * Alias of state
   */
  doc: React.PropTypes.object,

  /**
   * A callback that fires when the form value changes.
   * The argument will be the value.
   */
  onChange: React.PropTypes.func,

  /**
   * The Mongo Collection for the form.
   */
  collection: React.PropTypes.object,

  /**
   * The simple schema for the form.
   */
  schema: React.PropTypes.object,

  /**
   * The type of the form. insert or update.
   */
  type: React.PropTypes.oneOf(['insert', 'update', 'function']),

  /**
   * Set to true to enable automatic form submission for a type="update" form.
   * When the form change event is emitted, the change will be automatically
   * saved to the database.
   */
  autoSave: React.PropTypes.bool,

  /**
   * Set to false for an insert or update form to keep empty string values when
   * cleaning the form document.
   */
  removeEmptyStrings: React.PropTypes.bool,

  /**
   * Set to false for an insert or update form to skip filtering out unknown
   * properties when cleaning the form document.
   */
  filter: React.PropTypes.bool,

  /**
   * Set to false for an insert or update form to keep leading and trailing
   * spaces for string values when cleaning the form document.
   */
  trimStrings: React.PropTypes.bool,

  /**
   * Set to false for an insert or update form to skip autoconverting property
   * values when cleaning the form document.
   */
  autoConvert: React.PropTypes.bool,

  /**
   * Replace the current document if the one in the props changes.
   */
  replaceOnChange: React.PropTypes.bool,

  /**
   * Clear the form after a successful insert.
   * Only works on insert and function types.
   */
  clearOnSuccess: React.PropTypes.bool,

  /**
   * Keep arrays when updating.
   */
  keepArrays: React.PropTypes.bool,

  /**
   * A function that is called when the form action finished with success.
   */
  onSuccess: React.PropTypes.func,

  /**
   * A function that is called when the form action error.
   */
  onError: React.PropTypes.func,
  /**
   * A function that is called when the form is submitted.
   */
  onSubmit: React.PropTypes.func,

  /**
   * Id of the form.
   */
  formId: React.PropTypes.string,

  /**
   * The component for the array wrapper
   */
  arrayComponent: React.PropTypes.any,

  /**
   * The component for the object wrapper
   */
  objectComponent: React.PropTypes.any,

  /**
   * Show errors in the console
   */
  logErrors: React.PropTypes.bool,

  /**
   * Commit only changes
   */
  commitOnlyChanges: React.PropTypes.bool,

  /**
   * Minimum wait time between auto saves
   */
  autoSaveWaitTime: React.PropTypes.number,

  /**
   * Fields to be omited
   */
  omit: React.PropTypes.arrayOf(React.PropTypes.string),

  /**
   * Validate schema. Only for onSubmit
   */
  validate: React.PropTypes.bool,

  /**
   * The child components
   */
  children: React.PropTypes.any,

  /**
   * Render form tag
   */
  useFormTag: React.PropTypes.bool
}

const defaultProps = {
  type: 'function',
  keepArrays: true,
  autoSave: false,
  removeEmptyStrings: true,
  trimStrings: true,
  autoConvert: true,
  filter: true,
  replaceOnChange: true,
  clearOnSuccess: false,
  formId: 'defaultFormId',
  arrayComponent: ArrayComponent,
  objectComponent: ObjectComponent,
  logErrors: true,
  commitOnlyChanges: false,
  autoSaveWaitTime: 500,
  omit: [],
  validate: true,
  useFormTag: true
}

const childContextTypes = {
  schema: React.PropTypes.object,
  doc: React.PropTypes.object,
  onChange: React.PropTypes.func.isRequired,
  errorMessages: React.PropTypes.object,
  form: React.PropTypes.any.isRequired
}

export default class Form extends React.Component {

  constructor (props) {
    super(props)
    const state = this.props.state || this.props.doc || {}
    this.state = {
      doc: _.clone(state),
      changes: {},
      validationContext: this.getSchema() ? this.getSchema().newContext() : null,
      errorMessages: {}
    }
    this.fields = []
    this.autoSave = _.debounce(this.submit.bind(this), this.props.autoSaveWaitTime)
    this.errorMessages = {}
    this.onFormSubmit = this.onFormSubmit.bind(this)
    this.onValueChange = this.onValueChange.bind(this)
  }

  getChildContext () {
    return {
      schema: this.getSchema(),
      doc: this.state.doc,
      onChange: this.onValueChange,
      errorMessages: this.state.errorMessages,
      form: this
    }
  }

  componentWillReceiveProps (nextProps) {
    if (this.props.replaceOnChange || this.props.formId !== nextProps.formId) {
      const state = this.props.state || this.props.doc || {}
      const nextState = nextProps.state || nextProps.doc || {}
      if (!_.isEqual(state, nextState)) {
        this.setState({ doc: _.clone(nextState), changes: {} })
      }
    }
  }

  componentDidUpdate (prevProps, prevState) {
    //  Console.log('did update form', prevProps, prevState)
  }

  getSchema () {
    if (this.props.schema) {
      return this.props.schema
    } else if (this.props.collection) {
      return this.props.collection.simpleSchema()
    } else {
      //  Throw new Error('no schema was specified.')
    }
  }

  registerComponent ({ field, component }) {
    this.fields.push({ field, component })
  }

  callChildFields ({ method, input }) {
    this.fields.map((field) => {
      if (_.isFunction(field.component[method])) {
        field.component[method](input)
      }
    })
  }

  onCommit (error, docId) {
    this.setState({ errorMessages: {} })
    if (error) {
      if (error.reason === 'INVALID') {
        this.handleServerError(error)
      } else {
        this.handleError()
      }
      if (this.props.logErrors) {
        console.log(`[form-${this.props.formId}-error]`, error)
      }

      if (this.props.onError) {
        this.props.onError(error)
      }
    } else {
      this.callChildFields({ method: 'onSuccess' })
      if (_.isFunction(this.props.onSuccess)) {
        this.props.onSuccess(docId)
      }
      if (this.props.clearOnSuccess) {
        this.clearForm()
      } else {
        // if clearOnSuccess is false, we still need to clear the changes
        this.setState({ changes: {} })
      }
    }
  }

  getValidationOptions () {
    return {
      validationContext: this.props.formId,
      filter: this.props.filter,
      autoConvert: this.props.autoConvert,
      removeEmptyStrings: this.props.removeEmptyStrings,
      trimStrings: this.props.trimStrings
    }
  }

  onFormSubmit (event) {
    event.preventDefault()
    this.submit()
  }

  getPresentFields () {
    return _.filter(this.fields, field => {
      const props = field.component.props
      return !props.disabled
    }).map(field => field.field)
  }

  submit () {
    const data = this.props.commitOnlyChanges ? this.state.changes : this.state.doc
    if (this.props.type === 'insert') {
      const dot = DotObject.dot(this.state.doc)
      const doc = DotObject.object(dot)
      this.props.collection.insert(doc, this.getValidationOptions(), this.onCommit.bind(this))
    } else if (this.props.type === 'update') {
      var modifier = docToModifier(data, { keepArrays: this.props.keepArrays, fields: this.getPresentFields() })
      if (!_.isEqual(modifier, {})) {
        this.props.collection.update(this.state.doc._id, modifier, this.getValidationOptions(), this.onCommit.bind(this))
      } else {
        this.callChildFields({ method: 'onSuccess' })
        if (_.isFunction(this.props.onSuccess)) {
          this.props.onSuccess()
        }
      }
    } else if (this.props.type === 'function') {
      const doc = DotObject.object(DotObject.dot(data))
      var isValid = true
      if (this.props.validate && this.getSchema()) {
        isValid = this.getSchema().namedContext(this.getValidationOptions().validationContext).validate(doc)
      }
      if (isValid) {
        if (!_.isFunction(this.props.onSubmit)) {
          throw new Error('You must pass a onSubmit function or set the form type to insert or update')
        }
        var success = this.props.onSubmit(doc)
        if (success === false) {
          this.onCommit('onSubmit error')
        } else {
          this.onCommit()
        }
      } else {
        this.onCommit('Validation error')
      }
    }
  }

  cleanErrorMessages () {
    this.errorMessages = {}
    this.setState({ errorMessages: {} })
  }

  clearForm () {
    this.setState({doc: {}, changes: {}})
  }

  setErrorMessage (fieldName, message) {
    const errorMessages = _.clone(this.errorMessages)
    errorMessages[fieldName] = message
    this.errorMessages = errorMessages
    this.setState({ errorMessages })
  }

  setErrorsWithContext (context) {
    var invalidKeys = context.invalidKeys()
    var errorMessages = {}
    invalidKeys.map((field) => {
      errorMessages[field.name] = context.keyErrorMessage(field.name)
    })

    if (this.props.logErrors) {
      console.log(`[form-${this.props.formId}-error-messages]`, errorMessages)
    }

    if (this.props.onError) {
      this.props.onError(error)
    }

    this.errorMessages = errorMessages
    this.setState({ errorMessages })
  }

  handleError () {
    var context = this.getSchema().namedContext(this.getValidationOptions().validationContext)
    this.setErrorsWithContext(context)
  }

  handleServerError (error) {
    const errors = JSON.parse(error.details)
    let errorMessages = {}
    errors.forEach(fieldError => {
      errorMessages[fieldError.name] = this.getSchema().messageForError(fieldError.type, fieldError.name, null, fieldError.value)
    })
    if (this.props.logErrors) {
      console.log(`[form-${this.props.formId}-error-messages]`, errorMessages)
    }

    if (this.props.onError) {
      this.props.onError(error)
    }

    this.errorMessages = errorMessages
    this.setState({ errorMessages })
  }

  onValueChange (fieldName, newValue) {
    //  newValue = typeof newValue === 'undefined' ? null : newValue
    DotObject.del(fieldName, this.state.doc)
    var doc = DotObject.str(`val.${fieldName}`, newValue, { val: this.state.doc }).val
    DotObject.del(fieldName, this.state.changes)
    var changes = DotObject.str(`val.${fieldName}`, newValue, { val: this.state.changes }).val
    this.setState({ doc, changes })

    if (this.props.autoSave) {
      this.autoSave()
    }

    if (_.isFunction(this.props.onChange)) {
      this.props.onChange(this.state.doc, this.state.changes)
    }
  }

  generateInputsForKeys (keys, parent = '') {
    var schema = this.getSchema()
    keys = _.reject(keys, (key) => {
      var fullKey = parent ? `${parent}.${key}` : key
      var keySchema = schema.schema(fullKey)
      const options = keySchema.srf || keySchema.mrf
      if (options && options.omit) return true
      if (_.contains(this.props.omit, fullKey)) return true
    })
    return keys.map((key) => {
      var fullKey = parent ? `${parent}.${key}` : key
      return <Field fieldName={key} key={fullKey}/>
    })
  }

  generateChildren () {
    const schema = this.getSchema()
    if (!schema) {
      throw new Error('You must pass a schema or manually render the fields')
    }
    return this.generateInputsForKeys(schema._firstLevelSchemaKeys)
  }

  renderInsideForm () {
    if (!this.props.children) {
      return this.generateChildren()
    } else {
      return this.props.children
    }
  }

  render () {
    if (this.props.useFormTag) {
      return (
        <form onSubmit={this.onFormSubmit}>
          {this.renderInsideForm()}
        </form>
      )
    } else {
      return <div>{this.renderInsideForm()}</div>
    }
  }
}

Form.propTypes = propTypes
Form.defaultProps = defaultProps
Form.childContextTypes = childContextTypes
<commit_msg>added conditional check for react-native<commit_after>import React from 'react'
import _ from 'underscore'
import ArrayComponent from './array'
import ObjectComponent from './object'
import DotObject from 'dot-object'
import {docToModifier} from './utility'
import Field from './field'

const propTypes = {
  /**
   * The object that has the values of the form.
   */
  state: React.PropTypes.object,
  /**
   * Alias of state
   */
  doc: React.PropTypes.object,

  /**
   * A callback that fires when the form value changes.
   * The argument will be the value.
   */
  onChange: React.PropTypes.func,

  /**
   * The Mongo Collection for the form.
   */
  collection: React.PropTypes.object,

  /**
   * The simple schema for the form.
   */
  schema: React.PropTypes.object,

  /**
   * The type of the form. insert or update.
   */
  type: React.PropTypes.oneOf(['insert', 'update', 'function']),

  /**
   * Set to true to enable automatic form submission for a type="update" form.
   * When the form change event is emitted, the change will be automatically
   * saved to the database.
   */
  autoSave: React.PropTypes.bool,

  /**
   * Set to false for an insert or update form to keep empty string values when
   * cleaning the form document.
   */
  removeEmptyStrings: React.PropTypes.bool,

  /**
   * Set to false for an insert or update form to skip filtering out unknown
   * properties when cleaning the form document.
   */
  filter: React.PropTypes.bool,

  /**
   * Set to false for an insert or update form to keep leading and trailing
   * spaces for string values when cleaning the form document.
   */
  trimStrings: React.PropTypes.bool,

  /**
   * Set to false for an insert or update form to skip autoconverting property
   * values when cleaning the form document.
   */
  autoConvert: React.PropTypes.bool,

  /**
   * Replace the current document if the one in the props changes.
   */
  replaceOnChange: React.PropTypes.bool,

  /**
   * Clear the form after a successful insert.
   * Only works on insert and function types.
   */
  clearOnSuccess: React.PropTypes.bool,

  /**
   * Keep arrays when updating.
   */
  keepArrays: React.PropTypes.bool,

  /**
   * A function that is called when the form action finished with success.
   */
  onSuccess: React.PropTypes.func,

  /**
   * A function that is called when the form action error.
   */
  onError: React.PropTypes.func,
  /**
   * A function that is called when the form is submitted.
   */
  onSubmit: React.PropTypes.func,

  /**
   * Id of the form.
   */
  formId: React.PropTypes.string,

  /**
   * The component for the array wrapper
   */
  arrayComponent: React.PropTypes.any,

  /**
   * The component for the object wrapper
   */
  objectComponent: React.PropTypes.any,

  /**
   * Show errors in the console
   */
  logErrors: React.PropTypes.bool,

  /**
   * Commit only changes
   */
  commitOnlyChanges: React.PropTypes.bool,

  /**
   * Minimum wait time between auto saves
   */
  autoSaveWaitTime: React.PropTypes.number,

  /**
   * Fields to be omited
   */
  omit: React.PropTypes.arrayOf(React.PropTypes.string),

  /**
   * Validate schema. Only for onSubmit
   */
  validate: React.PropTypes.bool,

  /**
   * The child components
   */
  children: React.PropTypes.any,

  /**
   * Render form tag
   */
  useFormTag: React.PropTypes.bool
}

const defaultProps = {
  type: 'function',
  keepArrays: true,
  autoSave: false,
  removeEmptyStrings: true,
  trimStrings: true,
  autoConvert: true,
  filter: true,
  replaceOnChange: true,
  clearOnSuccess: false,
  formId: 'defaultFormId',
  arrayComponent: ArrayComponent,
  objectComponent: ObjectComponent,
  logErrors: true,
  commitOnlyChanges: false,
  autoSaveWaitTime: 500,
  omit: [],
  validate: true,
  useFormTag: true
}

const childContextTypes = {
  schema: React.PropTypes.object,
  doc: React.PropTypes.object,
  onChange: React.PropTypes.func.isRequired,
  errorMessages: React.PropTypes.object,
  form: React.PropTypes.any.isRequired
}

export default class Form extends React.Component {

  constructor (props) {
    super(props)
    const state = this.props.state || this.props.doc || {}
    this.state = {
      doc: _.clone(state),
      changes: {},
      validationContext: this.getSchema() ? this.getSchema().newContext() : null,
      errorMessages: {}
    }
    this.fields = []
    this.autoSave = _.debounce(this.submit.bind(this), this.props.autoSaveWaitTime)
    this.errorMessages = {}
    this.onFormSubmit = this.onFormSubmit.bind(this)
    this.onValueChange = this.onValueChange.bind(this)
  }

  getChildContext () {
    return {
      schema: this.getSchema(),
      doc: this.state.doc,
      onChange: this.onValueChange,
      errorMessages: this.state.errorMessages,
      form: this
    }
  }

  componentWillReceiveProps (nextProps) {
    if (this.props.replaceOnChange || this.props.formId !== nextProps.formId) {
      const state = this.props.state || this.props.doc || {}
      const nextState = nextProps.state || nextProps.doc || {}
      if (!_.isEqual(state, nextState)) {
        this.setState({ doc: _.clone(nextState), changes: {} })
      }
    }
  }

  componentDidUpdate (prevProps, prevState) {
    //  Console.log('did update form', prevProps, prevState)
  }

  getSchema () {
    if (this.props.schema) {
      return this.props.schema
    } else if (this.props.collection) {
      return this.props.collection.simpleSchema()
    } else {
      //  Throw new Error('no schema was specified.')
    }
  }

  registerComponent ({ field, component }) {
    this.fields.push({ field, component })
  }

  callChildFields ({ method, input }) {
    this.fields.map((field) => {
      if (_.isFunction(field.component[method])) {
        field.component[method](input)
      }
    })
  }

  onCommit (error, docId) {
    this.setState({ errorMessages: {} })
    if (error) {
      if (error.reason === 'INVALID') {
        this.handleServerError(error)
      } else {
        this.handleError()
      }
      if (this.props.logErrors) {
        console.log(`[form-${this.props.formId}-error]`, error)
      }

      if (this.props.onError) {
        this.props.onError(error)
      }
    } else {
      this.callChildFields({ method: 'onSuccess' })
      if (_.isFunction(this.props.onSuccess)) {
        this.props.onSuccess(docId)
      }
      if (this.props.clearOnSuccess) {
        this.clearForm()
      } else {
        // if clearOnSuccess is false, we still need to clear the changes
        this.setState({ changes: {} })
      }
    }
  }

  getValidationOptions () {
    return {
      validationContext: this.props.formId,
      filter: this.props.filter,
      autoConvert: this.props.autoConvert,
      removeEmptyStrings: this.props.removeEmptyStrings,
      trimStrings: this.props.trimStrings
    }
  }

  onFormSubmit (event) {
    event.preventDefault()
    this.submit()
  }

  getPresentFields () {
    return _.filter(this.fields, field => {
      const props = field.component.props
      return !props.disabled
    }).map(field => field.field)
  }

  submit () {
    const data = this.props.commitOnlyChanges ? this.state.changes : this.state.doc
    if (this.props.type === 'insert') {
      const dot = DotObject.dot(this.state.doc)
      const doc = DotObject.object(dot)
      this.props.collection.insert(doc, this.getValidationOptions(), this.onCommit.bind(this))
    } else if (this.props.type === 'update') {
      var modifier = docToModifier(data, { keepArrays: this.props.keepArrays, fields: this.getPresentFields() })
      if (!_.isEqual(modifier, {})) {
        this.props.collection.update(this.state.doc._id, modifier, this.getValidationOptions(), this.onCommit.bind(this))
      } else {
        this.callChildFields({ method: 'onSuccess' })
        if (_.isFunction(this.props.onSuccess)) {
          this.props.onSuccess()
        }
      }
    } else if (this.props.type === 'function') {
      const doc = DotObject.object(DotObject.dot(data))
      var isValid = true
      if (this.props.validate && this.getSchema()) {
        isValid = this.getSchema().namedContext(this.getValidationOptions().validationContext).validate(doc)
      }
      if (isValid) {
        if (!_.isFunction(this.props.onSubmit)) {
          throw new Error('You must pass a onSubmit function or set the form type to insert or update')
        }
        var success = this.props.onSubmit(doc)
        if (success === false) {
          this.onCommit('onSubmit error')
        } else {
          this.onCommit()
        }
      } else {
        this.onCommit('Validation error')
      }
    }
  }

  cleanErrorMessages () {
    this.errorMessages = {}
    this.setState({ errorMessages: {} })
  }

  clearForm () {
    this.setState({doc: {}, changes: {}})
  }

  setErrorMessage (fieldName, message) {
    const errorMessages = _.clone(this.errorMessages)
    errorMessages[fieldName] = message
    this.errorMessages = errorMessages
    this.setState({ errorMessages })
  }

  setErrorsWithContext (context) {
    var invalidKeys = context.invalidKeys()
    var errorMessages = {}
    invalidKeys.map((field) => {
      errorMessages[field.name] = context.keyErrorMessage(field.name)
    })

    if (this.props.logErrors) {
      console.log(`[form-${this.props.formId}-error-messages]`, errorMessages)
    }

    if (this.props.onError) {
      this.props.onError(error)
    }

    this.errorMessages = errorMessages
    this.setState({ errorMessages })
  }

  handleError () {
    var context = this.getSchema().namedContext(this.getValidationOptions().validationContext)
    this.setErrorsWithContext(context)
  }

  handleServerError (error) {
    const errors = JSON.parse(error.details)
    let errorMessages = {}
    errors.forEach(fieldError => {
      errorMessages[fieldError.name] = this.getSchema().messageForError(fieldError.type, fieldError.name, null, fieldError.value)
    })
    if (this.props.logErrors) {
      console.log(`[form-${this.props.formId}-error-messages]`, errorMessages)
    }

    if (this.props.onError) {
      this.props.onError(error)
    }

    this.errorMessages = errorMessages
    this.setState({ errorMessages })
  }

  isRN () {
    let isNative = false;
    try {
      let Platform = require('react-native').Platform;
      if (Platform) {
        isNative = true;
      };
    } catch(e) {}
    return isNative;
  }

  onValueChange (fieldName, newValue) {
    //  newValue = typeof newValue === 'undefined' ? null : newValue
    DotObject.del(fieldName, this.state.doc)
    var doc = DotObject.str(`val.${fieldName}`, newValue, { val: this.state.doc }).val
    DotObject.del(fieldName, this.state.changes)
    var changes = DotObject.str(`val.${fieldName}`, newValue, { val: this.state.changes }).val
    this.setState({ doc, changes })

    if (this.props.autoSave) {
      this.autoSave()
    }

    if (_.isFunction(this.props.onChange)) {
      this.props.onChange(this.state.doc, this.state.changes)
    }
  }

  generateInputsForKeys (keys, parent = '') {
    var schema = this.getSchema()
    keys = _.reject(keys, (key) => {
      var fullKey = parent ? `${parent}.${key}` : key
      var keySchema = schema.schema(fullKey)
      const options = keySchema.srf || keySchema.mrf
      if (options && options.omit) return true
      if (_.contains(this.props.omit, fullKey)) return true
    })
    return keys.map((key) => {
      var fullKey = parent ? `${parent}.${key}` : key
      return <Field fieldName={key} key={fullKey}/>
    })
  }

  generateChildren () {
    const schema = this.getSchema()
    if (!schema) {
      throw new Error('You must pass a schema or manually render the fields')
    }
    return this.generateInputsForKeys(schema._firstLevelSchemaKeys)
  }

  renderInsideForm () {
    if (!this.props.children) {
      return this.generateChildren()
    } else {
      return this.props.children
    }
  }

  render () {
    if (this.props.useFormTag) {
      return (
        <form onSubmit={this.onFormSubmit}>
          {this.renderInsideForm()}
        </form>
      )
    } else {
      if (this.isRN()) {
        return this.renderInsideForm()
      } else {
        return <div>{this.renderInsideForm()}</div>
      }
    }
  }
}

Form.propTypes = propTypes
Form.defaultProps = defaultProps
Form.childContextTypes = childContextTypes
<|endoftext|>


<commit_before>var MONTH_MAPPING = {
  "1": "January",
  "2": "February",
  "3": "March",
  "4": "April",
  "5": "May",
  "6": "June",
  "7": "July",
  "8": "August",
  "9": "September",
  "19": "October",
  "11": "November",
  "12": "December"
};

var util = {};

util.formatDate = function (pubDate) {
  var parts = pubDate.split("-");
  if (pubDate.split("-").length >= 3) {
    // new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
    // Note: months are 0-based
    var localDate = new Date(parts[0], parts[1]-1, parts[2]);
    return localDate.toUTCString().slice(0, 16);
  } else {
    var month = parts[1].replace("0", "");
    var year = parts[0];
    return MONTH_MAPPING[month]+" "+year;
  }
};

module.exports = util;
<commit_msg>Fixed silly error with date formatter.<commit_after>var MONTH_MAPPING = {
  "1": "January",
  "2": "February",
  "3": "March",
  "4": "April",
  "5": "May",
  "6": "June",
  "7": "July",
  "8": "August",
  "9": "September",
  "10": "October",
  "11": "November",
  "12": "December"
};

var util = {};

util.formatDate = function (pubDate) {
  var parts = pubDate.split("-");
  if (pubDate.split("-").length >= 3) {
    // new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
    // Note: months are 0-based
    var localDate = new Date(parts[0], parts[1]-1, parts[2]);
    return localDate.toUTCString().slice(0, 16);
  } else {
    var month = parts[1].replace(/^0/, "");
    var year = parts[0];
    return MONTH_MAPPING[month]+" "+year;
  }
};

module.exports = util;
<|endoftext|>


<commit_before>import validateDatasetAliasName from '../../../actions/dataset/alias/validateDatasetAliasName'
import * as aliasClient from './datasetAliasesClient'
import {ALIAS_PREFIX} from './datasetAliasesClient'

export default async (args, context) => {
  const {apiClient, prompt, output} = context
  const [, ds] = args.argsWithoutOptions
  const client = apiClient()
  if (!ds) {
    throw new Error('Dataset alias name must be provided')
  }

  let aliasName = `${ds}`
  const dsError = validateDatasetAliasName(aliasName)
  if (dsError) {
    throw dsError
  }
  aliasName = aliasName.startsWith(ALIAS_PREFIX) ? aliasName.substring(1) : aliasName

  const [fetchedAliases] = await Promise.all([aliasClient.listAliases(client)])
  const linkedAlias = fetchedAliases.find((elem) => elem.name === aliasName)
  const message =
    linkedAlias && linkedAlias.datasetName
      ? `This dataset alias is linked to ${linkedAlias.datasetName}. `
      : ''

  await prompt.single({
    type: 'input',
    message: `${message}Are you ABSOLUTELY sure you want to delete this dataset alias?\n  Type the name of the dataset alias to confirm delete: `,
    filter: (input) => `${input}`.trim(),
    validate: (input) => {
      return input === aliasName || 'Incorrect dataset alias name. Ctrl + C to cancel delete.'
    },
  })

  // Strip out alias prefix if it exist in the string
  aliasName = aliasName.startsWith(ALIAS_PREFIX) ? aliasName.substring(1) : aliasName

  return aliasClient.removeAlias(client, aliasName).then(() => {
    output.print('Dataset alias deleted successfully')
  })
}
<commit_msg>feat(core): add `--force` flag to dataset alias delete command<commit_after>import {hideBin} from 'yargs/helpers'
import yargs from 'yargs/yargs'
import validateDatasetAliasName from '../../../actions/dataset/alias/validateDatasetAliasName'
import * as aliasClient from './datasetAliasesClient'
import {ALIAS_PREFIX} from './datasetAliasesClient'

function parseCliFlags(args) {
  return yargs(hideBin(args.argv || process.argv).slice(2)).option('force', {type: 'boolean'}).argv
}

export default async (args, context) => {
  const {apiClient, prompt, output} = context
  const [, ds] = args.argsWithoutOptions
  const {force} = await parseCliFlags(args)
  const client = apiClient()
  if (!ds) {
    throw new Error('Dataset alias name must be provided')
  }

  let aliasName = `${ds}`
  const dsError = validateDatasetAliasName(aliasName)
  if (dsError) {
    throw dsError
  }
  aliasName = aliasName.startsWith(ALIAS_PREFIX) ? aliasName.substring(1) : aliasName

  const [fetchedAliases] = await Promise.all([aliasClient.listAliases(client)])
  const linkedAlias = fetchedAliases.find((elem) => elem.name === aliasName)
  const message =
    linkedAlias && linkedAlias.datasetName
      ? `This dataset alias is linked to ${linkedAlias.datasetName}. `
      : ''

  if (force) {
    output.warn(`'--force' used: skipping confirmation, deleting alias "${aliasName}"`)
  } else {
    await prompt.single({
      type: 'input',
      message: `${message}Are you ABSOLUTELY sure you want to delete this dataset alias?\n  Type the name of the dataset alias to confirm delete: `,
      filter: (input) => `${input}`.trim(),
      validate: (input) => {
        return input === aliasName || 'Incorrect dataset alias name. Ctrl + C to cancel delete.'
      },
    })
  }

  // Strip out alias prefix if it exist in the string
  aliasName = aliasName.startsWith(ALIAS_PREFIX) ? aliasName.substring(1) : aliasName

  return aliasClient.removeAlias(client, aliasName).then(() => {
    output.print('Dataset alias deleted successfully')
  })
}
<|endoftext|>