<commit_before>'use strict';

const Boom = require('boom');
const User = require('../models/user');
const Tweet = require('../models/tweet');

const utils = require('./utils.js');
const _ = require('lodash');

exports.authenticate = {
  auth: false,
  handler: function (request, reply) {
    const user = request.payload;
    User.findOne({ email: user.email }).then(foundUser => {
      if (foundUser && foundUser.password === user.password) {
        const token = utils.createToken(foundUser);
        delete foundUser._doc.password;

        reply({ success: true, token: token, user: foundUser }).code(200);
      } else {
        reply({ success: false, message: 'Authentication failed.' }).code(400);
      }
    }).catch(err => {
      reply(Boom.notFound('internal db failure'));
    });
  },

};

exports.findAll = {
  auth: false,

  handler: function (request, reply) {
    User.find({}).then((users) => {
      users.map((user) => {
        delete user._doc.password;
        return user;
      });

      reply(users);
    }).catch((error) => {
      reply(Boom.badImplementation('error accessing db'));
    });
  },
};

exports.findOne = {
  auth: false,

  handler: function (request, reply) {
    User.findOne({ _id: request.params.id }).then((user) => {
      if (user == null) {
        reply(Boom.notFound('id not found'));
      } else {
        delete user._doc.password;
        reply(user);
      }
    }).catch((error) => {
      reply(Boom.notFound('id not found'));
    });
  },
};

exports.create = {
  auth: false,

  validate: {
    payload: User.validationSchema,

    failAction: function (request, reply, source, error) {
      const boomError = Boom.badRequest('Validation Failed.');
      boomError.output.payload.validation_errors = error.data.details;
      reply(boomError);
    },

    options: {
      abortEarly: false,
    },
  },

  handler: function (request, reply) {
    const user = new User(request.payload);

    user.save().then((newUser) => {
      delete newUser._doc.password;
      reply(newUser).code(201);
    }).catch((error) => {
      reply(Boom.badImplementation('error creating user'));
    });
  },
};

exports.update = {
  auth: {
    strategy: 'jwt',
  },

  validate: {
    payload: User.updateApiValidationSchema,

    failAction: function (request, reply, source, error) {
      const boomError = Boom.badRequest('Validation Failed.');
      boomError.output.payload.validation_errors = error.data.details;
      reply(boomError);
    },

    options: {
      abortEarly: false,
    },
  },

  handler: function (request, reply) {
    const userInfo = request.auth.credentials;

    if (userInfo.id == request.params.id) {
      User.findByIdAndUpdate({ _id: request.params.id },  { $set: request.payload }, { new: true })
        .then((user) => {
          delete user.password;
          reply(user).code(200);
        }).catch((error) => {
          reply(Boom.badImplementation('error updating user'));
        });
    } else {
      reply(Boom.forbidden('insufficient permissions'));
    }
  },
};

exports.deleteOne = {
  auth: {
    strategy: 'jwt',
  },

  handler: function (request, reply) {
    const userInfo = request.auth.credentials;

    if (userInfo.id == request.params.id || _.includes(userInfo.scope, 'admin')) {
      Tweet.remove({ creator: request.params.id }).then(tweets =>
          User.remove({ _id: request.params.id })
      ).then((user) => {
        reply().code(204);
      }).catch((error) => {
        reply(Boom.notFound('database error'));
      });
    } else {
      reply(Boom.forbidden('insufficient permissions'));
    }
  },
};
<commit_msg>Get user now returns followers and following<commit_after>'use strict';

const Boom = require('boom');
const User = require('../models/user');
const Tweet = require('../models/tweet');

const utils = require('./utils.js');
const _ = require('lodash');

exports.authenticate = {
  auth: false,
  handler: function (request, reply) {
    const user = request.payload;
    User.findOne({ email: user.email }).then(foundUser => {
      if (foundUser && foundUser.password === user.password) {
        const token = utils.createToken(foundUser);
        delete foundUser._doc.password;

        reply({ success: true, token: token, user: foundUser }).code(200);
      } else {
        reply({ success: false, message: 'Authentication failed.' }).code(400);
      }
    }).catch(err => {
      reply(Boom.notFound('internal db failure'));
    });
  },

};

exports.findAll = {
  auth: false,

  handler: function (request, reply) {
    User.find({}).then((users) => {
      users.map((user) => {
        delete user._doc.password;
        return user;
      });

      reply(users);
    }).catch((error) => {
      reply(Boom.badImplementation('error accessing db'));
    });
  },
};

exports.findOne = {
  auth: false,

  handler: function (request, reply) {
    let followers;

    User.find({ following: request.params.id }).then((users) => {
      followers = users.map(user => user._id);

      return User.findOne({ _id: request.params.id });
    }).then((user) => {
      if (user == null) {
        reply(Boom.notFound('id not found'));
      } else {
        delete user._doc.password;
        user._doc.followers = followers;
        reply(user);
      }
    }).catch((error) => {
      reply(Boom.notFound('id not found'));
    });
  },
};

exports.create = {
  auth: false,

  validate: {
    payload: User.validationSchema,

    failAction: function (request, reply, source, error) {
      const boomError = Boom.badRequest('Validation Failed.');
      boomError.output.payload.validation_errors = error.data.details;
      reply(boomError);
    },

    options: {
      abortEarly: false,
    },
  },

  handler: function (request, reply) {
    const user = new User(request.payload);

    user.save().then((newUser) => {
      delete newUser._doc.password;
      reply(newUser).code(201);
    }).catch((error) => {
      reply(Boom.badImplementation('error creating user'));
    });
  },
};

exports.update = {
  auth: {
    strategy: 'jwt',
  },

  validate: {
    payload: User.updateApiValidationSchema,

    failAction: function (request, reply, source, error) {
      const boomError = Boom.badRequest('Validation Failed.');
      boomError.output.payload.validation_errors = error.data.details;
      reply(boomError);
    },

    options: {
      abortEarly: false,
    },
  },

  handler: function (request, reply) {
    const userInfo = request.auth.credentials;

    if (userInfo.id == request.params.id) {
      User.findByIdAndUpdate({ _id: request.params.id },  { $set: request.payload }, { new: true })
        .then((user) => {
          delete user.password;
          reply(user).code(200);
        }).catch((error) => {
          reply(Boom.badImplementation('error updating user'));
        });
    } else {
      reply(Boom.forbidden('insufficient permissions'));
    }
  },
};

exports.deleteOne = {
  auth: {
    strategy: 'jwt',
  },

  handler: function (request, reply) {
    const userInfo = request.auth.credentials;

    if (userInfo.id == request.params.id || _.includes(userInfo.scope, 'admin')) {
      Tweet.remove({ creator: request.params.id }).then(tweets =>
          User.remove({ _id: request.params.id })
      ).then((user) => {
        reply().code(204);
      }).catch((error) => {
        reply(Boom.notFound('database error'));
      });
    } else {
      reply(Boom.forbidden('insufficient permissions'));
    }
  },
};
<|endoftext|>


<commit_before>define("dojox/mobile/Slider", ["dojo", "dijit", "dijit/_WidgetBase", "dijit/form/_FormWidgetMixin"], function(dojo, dijit) {
dojo.experimental("dojox.mobile.Slider");

dojo.declare(
	"dojox.mobile.Slider",
	[dijit._WidgetBase, dijit.form._FormValueMixin],
	{
		// summary:
		//		A non-templated Slider widget similar to the HTML5 INPUT type=range.
		//

		// value: [const] Number
		//		The current slider value.
		value: 0,

		// min: [const] Number
		//		The first value the slider can be set to.
		min: 0,

		// max: [const] Number
		//		The last value the slider can be set to.
		max: 100,

		// step: [const] Number
		//		The delta from 1 value to another.
		//		This causes the slider handle to snap/jump to the closest possible value.
		//		A value of 0 means continuous (as much as allowed by pixel resolution).
		step: 1,

		baseClass: "mblSlider",

		// flip: [const] Boolean
		//		Specifies if the slider should change its default: ascending <--> descending.
		flip: false,

		// orientation: [const] String
		//		The slider direction.
		//		"H": horizontal
		//		"V": vertical
		//		"auto": use width/height comparison at instantiation time (default is "H" if width/height are 0)
		orientation: "auto",

		// halo: Number
		//		Size of the boundary that extends beyond the edges of the slider
		//		to make it easier to touch.
		halo: "8pt",

		buildRendering: function(){
			this.focusNode = this.domNode = dojo.create("div", {});
			this.valueNode = dojo.create("input", (this.srcNodeRef && this.srcNodeRef.name) ? { type: "hidden", name: this.srcNodeRef.name } : {}, this.domNode, "last");
			var relativeParent = dojo.create("div", { style: { position:"relative", height:"100%", width:"100%" } }, this.domNode, "last");
			this.progressBar = dojo.create("div", { style:{ position:"absolute" }, "class":"mblSliderProgressBar" }, relativeParent, "last");
			this.touchBox = dojo.create("div", { style:{ position:"absolute" }, "class":"mblSliderTouchBox" }, relativeParent, "last");
			this.handle = dojo.create("div", { style:{ position:"absolute" }, "class":"mblSliderHandle" }, relativeParent, "last");
			this.inherited(arguments);
		},

		_setValueAttr: function(/*Number*/ value, /*Boolean?*/ priorityChange){
			// summary:
			//		Hook so set('value', value) works.
			var fromPercent = (this.value - this.min) * 100 / (this.max - this.min);
			this.valueNode.value = value;
			this.inherited(arguments);
			if(!this._started){ return; } // don't move images until all the properties are set
			this.focusNode.setAttribute("aria-valuenow", value);
			var toPercent = (value - this.min) * 100 / (this.max - this.min);
			// now perform visual slide
			var horizontal = this.orientation != "V";
			if(priorityChange === true){
				dojo.addClass(this.handle, "mblSliderTransition");
				dojo.addClass(this.progressBar, "mblSliderTransition");
			}else{
				dojo.removeClass(this.handle, "mblSliderTransition");
				dojo.removeClass(this.progressBar, "mblSliderTransition");
			}
			dojo.style(this.handle, this._attrs.handleLeft, (this._reversed ? (100-toPercent) : toPercent) + "%");
			dojo.style(this.progressBar, this._attrs.width, toPercent + "%");
		},

		postCreate: function(){
			this.inherited(arguments);

			function beginDrag(e){
				function getEventData(e){
					point = isMouse ? e[this._attrs.pageX] : (e.touches ? e.touches[0][this._attrs.pageX] : e[this._attrs.clientX]);
					pixelValue = point - startPixel;
					pixelValue = Math.min(Math.max(pixelValue, 0), maxPixels);
					var discreteValues = this.step ? ((this.max - this.min) / this.step) : maxPixels;
					if(discreteValues <= 1 || discreteValues == Infinity ){ discreteValues = maxPixels; }
					var wholeIncrements = Math.round(pixelValue * discreteValues / maxPixels);
					value = (this.max - this.min) * wholeIncrements / discreteValues;
					value = this._reversed ? (this.max - value) : (this.min + value);
				}
				function continueDrag(e){
					e.preventDefault();
					dojo.hitch(this, getEventData)(e);
					this.set('value', value, false);
				}

				function endDrag(e){
					e.preventDefault();
					dojo.forEach(actionHandles, dojo.hitch(this, "disconnect"));
					actionHandles = [];
					this.set('value', this.value, true);
				}

				e.preventDefault();
				var isMouse = e.type == "mousedown";
				var box = dojo.position(node, false); // can't use true since the added docScroll and the returned x are body-zoom incompatibile
				var bodyZoom = dojo.style(dojo.body(), "zoom") || 1;
				var nodeZoom = dojo.style(node, "zoom") || 1;
				var startPixel = box[this._attrs.x] * nodeZoom * bodyZoom + dojo._docScroll()[this._attrs.x];
				var maxPixels = box[this._attrs.w] * nodeZoom * bodyZoom;
				dojo.hitch(this, getEventData)(e);
				if(e.target == this.touchBox){
					this.set('value', value, true);
				}
				dojo.forEach(actionHandles, dojo.disconnect);
				var root = dojo.doc.documentElement;
				var actionHandles = [
					this.connect(root, isMouse ? "onmousemove" : "ontouchmove", continueDrag),
					this.connect(root, isMouse ? "onmouseup" : "ontouchend", endDrag)
				];
			}

			var point, pixelValue, value;
			var node = this.domNode;
			if(this.orientation == "auto"){
				 this.orientation = node.offsetHeight <= node.offsetWidth ? "H" : "V";
			}
			// add V or H suffix to baseClass for styling purposes
			dojo.addClass(this.domNode, dojo.map(this.baseClass.split(" "), dojo.hitch(this, function(c){ return c+this.orientation; })));
			var horizontal = this.orientation != "V";
			var ltr = horizontal ? this.isLeftToRight() : false;
			var flip = this.flip;
			// _reversed is complicated since you can have flipped right-to-left and vertical is upside down by default
			this._reversed = !(horizontal && ((ltr && !flip) || (!ltr && flip))) || (!horizontal && !flip);
			this._attrs = horizontal ? { x:'x', w:'w', l:'l', r:'r', pageX:'pageX', clientX:'clientX', handleLeft:"left", left:this._reversed ? "right" : "left", width:"width" } : { x:'y', w:'h', l:'t', r:'b', pageX:'pageY', clientX:'clientY', handleLeft:"top", left:this._reversed ? "bottom" : "top", width:"height" };
			this.progressBar.style[this._attrs.left] = "0px";
			this.connect(this.touchBox, "touchstart", beginDrag);
			this.connect(this.touchBox, "onmousedown", beginDrag); // in case this works
			this.connect(this.handle, "touchstart", beginDrag);
			this.connect(this.handle, "onmousedown", beginDrag); // in case this works
			this.startup();
			this.set('value', this.value);
		}
	}
);

return dojox.mobile.Slider;
});
<commit_msg>Fixes #12676.  IE's style.zoom was returning "normal" instead of a fraction which was causing NaN values.  I changed that to 1.0.<commit_after>define("dojox/mobile/Slider", ["dojo", "dijit", "dijit/_WidgetBase", "dijit/form/_FormWidgetMixin"], function(dojo, dijit) {
dojo.experimental("dojox.mobile.Slider");

dojo.declare(
	"dojox.mobile.Slider",
	[dijit._WidgetBase, dijit.form._FormValueMixin],
	{
		// summary:
		//		A non-templated Slider widget similar to the HTML5 INPUT type=range.
		//

		// value: [const] Number
		//		The current slider value.
		value: 0,

		// min: [const] Number
		//		The first value the slider can be set to.
		min: 0,

		// max: [const] Number
		//		The last value the slider can be set to.
		max: 100,

		// step: [const] Number
		//		The delta from 1 value to another.
		//		This causes the slider handle to snap/jump to the closest possible value.
		//		A value of 0 means continuous (as much as allowed by pixel resolution).
		step: 1,

		baseClass: "mblSlider",

		// flip: [const] Boolean
		//		Specifies if the slider should change its default: ascending <--> descending.
		flip: false,

		// orientation: [const] String
		//		The slider direction.
		//		"H": horizontal
		//		"V": vertical
		//		"auto": use width/height comparison at instantiation time (default is "H" if width/height are 0)
		orientation: "auto",

		// halo: Number
		//		Size of the boundary that extends beyond the edges of the slider
		//		to make it easier to touch.
		halo: "8pt",

		buildRendering: function(){
			this.focusNode = this.domNode = dojo.create("div", {});
			this.valueNode = dojo.create("input", (this.srcNodeRef && this.srcNodeRef.name) ? { type: "hidden", name: this.srcNodeRef.name } : {}, this.domNode, "last");
			var relativeParent = dojo.create("div", { style: { position:"relative", height:"100%", width:"100%" } }, this.domNode, "last");
			this.progressBar = dojo.create("div", { style:{ position:"absolute" }, "class":"mblSliderProgressBar" }, relativeParent, "last");
			this.touchBox = dojo.create("div", { style:{ position:"absolute" }, "class":"mblSliderTouchBox" }, relativeParent, "last");
			this.handle = dojo.create("div", { style:{ position:"absolute" }, "class":"mblSliderHandle" }, relativeParent, "last");
			this.inherited(arguments);
		},

		_setValueAttr: function(/*Number*/ value, /*Boolean?*/ priorityChange){
			// summary:
			//		Hook so set('value', value) works.
			var fromPercent = (this.value - this.min) * 100 / (this.max - this.min);
			this.valueNode.value = value;
			this.inherited(arguments);
			if(!this._started){ return; } // don't move images until all the properties are set
			this.focusNode.setAttribute("aria-valuenow", value);
			var toPercent = (value - this.min) * 100 / (this.max - this.min);
			// now perform visual slide
			var horizontal = this.orientation != "V";
			if(priorityChange === true){
				dojo.addClass(this.handle, "mblSliderTransition");
				dojo.addClass(this.progressBar, "mblSliderTransition");
			}else{
				dojo.removeClass(this.handle, "mblSliderTransition");
				dojo.removeClass(this.progressBar, "mblSliderTransition");
			}
			dojo.style(this.handle, this._attrs.handleLeft, (this._reversed ? (100-toPercent) : toPercent) + "%");
			dojo.style(this.progressBar, this._attrs.width, toPercent + "%");
		},

		postCreate: function(){
			this.inherited(arguments);

			function beginDrag(e){
				function getEventData(e){
					point = isMouse ? e[this._attrs.pageX] : (e.touches ? e.touches[0][this._attrs.pageX] : e[this._attrs.clientX]);
					pixelValue = point - startPixel;
					pixelValue = Math.min(Math.max(pixelValue, 0), maxPixels);
					var discreteValues = this.step ? ((this.max - this.min) / this.step) : maxPixels;
					if(discreteValues <= 1 || discreteValues == Infinity ){ discreteValues = maxPixels; }
					var wholeIncrements = Math.round(pixelValue * discreteValues / maxPixels);
					value = (this.max - this.min) * wholeIncrements / discreteValues;
					value = this._reversed ? (this.max - value) : (this.min + value);
				}
				function continueDrag(e){
					e.preventDefault();
					dojo.hitch(this, getEventData)(e);
					this.set('value', value, false);
				}

				function endDrag(e){
					e.preventDefault();
					dojo.forEach(actionHandles, dojo.hitch(this, "disconnect"));
					actionHandles = [];
					this.set('value', this.value, true);
				}

				e.preventDefault();
				var isMouse = e.type == "mousedown";
				var box = dojo.position(node, false); // can't use true since the added docScroll and the returned x are body-zoom incompatibile
				var bodyZoom = dojo.style(dojo.body(), "zoom") || 1;
				if(isNaN(bodyZoom)){ bodyZoom = 1; }
				var nodeZoom = dojo.style(node, "zoom") || 1;
				if(isNaN(nodeZoom)){ nodeZoom = 1; }
				var startPixel = box[this._attrs.x] * nodeZoom * bodyZoom + dojo._docScroll()[this._attrs.x];
				var maxPixels = box[this._attrs.w] * nodeZoom * bodyZoom;
				dojo.hitch(this, getEventData)(e);
				if(e.target == this.touchBox){
					this.set('value', value, true);
				}
				dojo.forEach(actionHandles, dojo.disconnect);
				var root = dojo.doc.documentElement;
				var actionHandles = [
					this.connect(root, isMouse ? "onmousemove" : "ontouchmove", continueDrag),
					this.connect(root, isMouse ? "onmouseup" : "ontouchend", endDrag)
				];
			}

			var point, pixelValue, value;
			var node = this.domNode;
			if(this.orientation == "auto"){
				 this.orientation = node.offsetHeight <= node.offsetWidth ? "H" : "V";
			}
			// add V or H suffix to baseClass for styling purposes
			dojo.addClass(this.domNode, dojo.map(this.baseClass.split(" "), dojo.hitch(this, function(c){ return c+this.orientation; })));
			var horizontal = this.orientation != "V";
			var ltr = horizontal ? this.isLeftToRight() : false;
			var flip = this.flip;
			// _reversed is complicated since you can have flipped right-to-left and vertical is upside down by default
			this._reversed = !(horizontal && ((ltr && !flip) || (!ltr && flip))) || (!horizontal && !flip);
			this._attrs = horizontal ? { x:'x', w:'w', l:'l', r:'r', pageX:'pageX', clientX:'clientX', handleLeft:"left", left:this._reversed ? "right" : "left", width:"width" } : { x:'y', w:'h', l:'t', r:'b', pageX:'pageY', clientX:'clientY', handleLeft:"top", left:this._reversed ? "bottom" : "top", width:"height" };
			this.progressBar.style[this._attrs.left] = "0px";
			this.connect(this.touchBox, "touchstart", beginDrag);
			this.connect(this.touchBox, "onmousedown", beginDrag); // in case this works
			this.connect(this.handle, "touchstart", beginDrag);
			this.connect(this.handle, "onmousedown", beginDrag); // in case this works
			this.startup();
			this.set('value', this.value);
		}
	}
);

return dojox.mobile.Slider;
});
<|endoftext|>


<commit_before>/* jshint esversion: 6 */

var mongoose = require('mongoose');

class T {
  constructor(i_title) {
    this._synonyms = [];
    this._title = i_title;
  }
  get name() {
    return T._toKey(this._title);
  }

  get title() {
    return this._title;
  }
  get synonyms() {
    return this._synonyms;
  }

  /*
  synonyms(i_synonyms) {
    this._synonyms = i_synonyms;
  }
  */

  static _toKey(i_string) {
    return i_string.replace(' ', '-').replace('\\', '_').replace('\'', '').replace('&', 'and');
  }

  static toplevel(i_title) {
    return new TTop(i_title);
  }

  static category(i_title, i_children) {
    return new TCategory(i_title, i_children);
  }

  static item(i_title) {
    return new TItem(i_title);
  }
}

class TItem extends T {
  constructor(i_title) {
    super(i_title);
  }

  serialize(i_parent) {
    return {
      name: this.name,
      synonyms: this.synonyms,
      parent: i_parent.topmost(),
      title: this.title,
      className: i_parent.className,
    };
  }
}

class TCategory extends T {
  constructor(i_title, i_children) {
    super(i_title);
    this._children = i_children;
  }

  get className() {
    return this.name();
  }

  serialize(i_parent) {
    for (var child in this._children) {
      out.concat(child.serialize(this));
    }
  }

  topmost() {
    var current = this;
    while(current != nullptr) {
      if(current instanceof T.toplevel) {
        break;
      }
    }

    return current;
  }
}

class TTop extends TCategory {
  get className() {
    return this.title.split(" ").pop();
  }

  serializeAll() {
    var out = [
      this.serializeThis()
    ];

    for (var child in this._children) {
      out.concat(child.serialize(this));
    }

    return out;
  }

  serializeThis() {
    return {
        name: this.name,
        synonyms: this.synonyms,
        parent: undefined,
        title: this.title,
        className: this.className,
    };
  }
}

const TAXONOMIES = {
  roles: T.toplevel('Roles', [
    T.category('Software Engineer', [
      T.item('Frontend'),
      T.item('Backend'),
      T.item('Full-stack'),
      T.item('QA'),
      T.item('DevOps'),
      T.item('Mobile'),
    ]),
    T.category('Design', [
      T.item('UI/UX Designer'),
      T.item('User Researcher'),
      T.item('Visual Designer'),
    ]),
    T.item('Data Science'),
    T.item('Operations'),
    T.item('Marketing'),
    T.item('Product Management'),
    T.item('Project Management'),
    T.category('General', [
      T.item('Government Employee'),
      T.item('Attorney / Legal Knowledge'),
      T.item('Partnerships'),
      T.item('Urban Planner'),
    ]),
  ]),
  skills: T.toplevel('Skills', [
    T.category('Frontend Development', [
      T.item('CSS'),
      T.item('D3'),
      T.item('Data Visualization'),
      T.item('HTML'),
      T.item('Jade'),
      T.item('JavaScript'),
      T.item('Other Tools And Technologies'),
      T.item('Rails'),
      T.item('React'),
    ]),
    T.category('Backend Development', [
      T.item('API Design'),
      T.item('Express'),
      T.item('Flask'),
      T.item('Go'),
      T.item('Java'),
      T.item('MongoDB'),
      T.item('Node'),
      T.item('Other Tools And Technologies '),
      T.item('PHP'),
      T.item('Parse'),
      T.item('Python'),
      T.item('Rails'),
      T.item('Ruby'),
      T.item('SQL'),
      T.item('XML'),
      T.item('Algorithm Design'),
      T.item('Databases'),
    ]),
    T.category('Full Stack', [
      T.item('Distributed Systems'),
    ]),
    T.category('QA', [
      T.item('Automated Testing'),
      T.item('Manual Testing'),
    ]),
    T.category('DevOps', [
      T.item('Amazon Web Services'),
      T.item('Azure'),
      T.item('Cloud Services'),
      T.item('Google Cloud Services'),
    ]),
    T.category('Mobile Development', [
      T.item('Android'),
      T.item('Objective-C'),
      T.item('Swift'),
      T.item('IOS'),
    ]),
    T.category('UI/UX Design', [
      T.item('Prototyping'),
      T.item('Visual Design'),
      T.item('Wireframes'),
    ]),
    T.category('User Research', [
      T.item('User Interviewing'),
      T.item('User Research'),
      T.item('User Testing'),
    ]),
    T.category('Marketing', [
      T.item('Content Development'),
      T.item('Copy Writing'),
      T.item('Communications'),
      T.item('Community Engagement'),
    ]),
    T.category('Data Science', [
      T.item('Machine Learning'),
      T.item('Other Tools And Technologies'),
      T.item('Python'),
      T.item('R'),
      T.item('Big Data'),
      T.item('Data Analysis'),
      T.item('Data Management'),
      T.item('Data Modeling'),
      T.item('Predictive Modeling'),
      T.item('Tableau'),
    ]),
    T.category('General', [
      T.item('Health'),
      T.item('Legal Knowledge'),
      T.item('Lobbying'),
      T.item('Government Budgeting And Operations'),
      T.item('Public Speaking'),
      T.item('Urban Planner'),
      T.item('Proficiency In A Language Other Than English'),
      T.item('Public Health'),
      T.item('Compliance'),
    ]),
    T.category('Product Management', [
      T.item('Requirements Gathering'),
      T.item('Scheduling And Planning'),
      T.item('Product Structure/Strategy'),
      T.item('Testing'),
    ]),
    T.category('Operations / Project Management', [
      T.item('Requirements Gathering'),
      T.item('Documentation'),
      T.item('Scheduling And Planning'),
    ]),
  ]),
  interests: T.toplevel('Civic Interests', [
    T.item('Arts And Culture'),
    T.category('Business, Finance & Economics', [
      T.item('Risk Assessments'),
      T.item('Economic Development'),
      T.item('Debt'),
      T.item('Stock Market'),
      T.item('Small Business Resources'),
    ]),
    T.item('Children And Youth'),
    T.category('Community Issues', [
      T.item('Homelessness'),
      T.item('Poverty'),
      T.item('Civic Rights'),
      T.item('Civic Engagement'),
    ]),
    T.category('Education', [
      T.item('K-12'),
      T.item('Extracurricular Programs'),
      T.item('College'),
      T.item('Continuing Education'),
    ]),
    T.category('Environment', [
      T.item('Natural Resources'),
      T.item('Climate Change'),
      T.item('Energy'),
      T.item('Sustainability'),
      T.item('Waste Management'),
      T.item('Parks And Preservation'),
    ]),
    T.category('Employment', [
      T.item('Unemployment'),
      T.item('Continuing Education'),
    ]),
    T.category('Human Rights', [
      T.item('Women\'s Rights'),
      T.item('Human Rights'),
      T.item('Veterans\' Rights'),
      T.item('LGBT Rights'),
      T.item('Racism & Discrimination'),
      T.item('Immigration & Refugees'),
      T.item('Civic Rights'),
      T.item('Workers\' Rights'),
      T.item('Legal Rights'),
      T.item('Income Inequality'),
      T.item('Labor Unions'),
    ]),
    T.category('Health & Healthcare', [
      T.item('Nutrition & Food'),
      T.item('Mental Health'),
      T.item('Health Care System'),
      T.item('Public Health'),
      T.item('Fitness'),
      T.item('Obesity'),
    ]),
    T.category('Housing & Urban Development', [
      T.item('Housing'),
      T.item('Gentrification'),
      T.item('Infrastructure'),
      T.item('Affordability'),
      T.item('Homelessness'),
    ]),
    T.item('International'),
    T.category('Justice & Law', [
      T.item('Criminal Justice'),
      T.item('Police'),
      T.item('Legal Rights'),
      T.item('Drug Regulation'),
    ]),
    T.category('Municipal Services', [
      T.item('Sanitation'),
      T.item('Social Services'),
      T.item('Waste Management'),
      T.item('Public Spaces'),
    ]),
    T.category('Politics', [
      T.item('Government Policy'),
      T.item('Government Operations'),
      T.item('Transparency And Corruption'),
      T.item('Crime Policy'),
      T.item('Drug Regulation'),
      T.item('Elections / Voting'),
      T.item('Budget Process'),
    ]),
    T.category('Transportation', [
      T.item('Public Transit'),
      T.item('Traffic'),
      T.item('Bicycling'),
      T.item('Parking'),
      T.item('Ride Shares'),
    ]),
  ]),
};

var ptSchema = new mongoose.Schema({
  name: {type: String, default: ''},
  title: {type: String, default: ''},
  parent: {type: String, default: ''},
  className: {type: String, default: ''},
  synonyms: {type: Array, default: []}
});

/*
  top-level taxonomies
*/

ptSchema.methods.getTaxonomies = function (cb) {
  return cb(null, TAXONOMIES.map(t => t.serializeThis()));
};

/*
  skills taxonomy
*/

ptSchema.methods.getSkills = function (cb) {
  return cb(null, TAXONOMIES.skills.serializeAll());
};

/*
  skills taxonomy
*/

ptSchema.methods.getInterests = function (cb) {
  return cb(null, TAXONOMIES.interests.serializeAll());
};

/*
  skills taxonomy
*/

ptSchema.methods.getRoles = function (cb) {
  return cb(null, TAXONOMIES.roles.serializeAll());
};

module.exports = mongoose.model('ProjectTaxonomies', ptSchema);
<commit_msg>Fix category serialization?<commit_after>/* jshint esversion: 6 */

var mongoose = require('mongoose');

class T {
  constructor(i_title) {
    this._synonyms = [];
    this._title = i_title;
  }
  get name() {
    return T._toKey(this._title);
  }

  get title() {
    return this._title;
  }
  get synonyms() {
    return this._synonyms;
  }

  /*
  synonyms(i_synonyms) {
    this._synonyms = i_synonyms;
  }
  */

  static _toKey(i_string) {
    return i_string.replace(' ', '-').replace('\\', '_').replace('\'', '').replace('&', 'and');
  }

  static toplevel(i_title) {
    return new TTop(i_title);
  }

  static category(i_title, i_children) {
    return new TCategory(i_title, i_children);
  }

  static item(i_title) {
    return new TItem(i_title);
  }
}

class TItem extends T {
  constructor(i_title) {
    super(i_title);
  }

  serialize(i_parent) {
    return {
      name: this.name,
      synonyms: this.synonyms,
      parent: i_parent.topmost(),
      title: this.title,
      className: i_parent.className,
    };
  }
}

class TCategory extends T {
  constructor(i_title, i_children) {
    super(i_title);
    this._children = i_children;
  }

  get className() {
    return this.name();
  }

  serialize(i_parent) {
    var out = [
      this.serialize(this)
    ];

    for (var child in this._children) {
      out.concat(child.serialize(this));
    }

    return out;
  }

  topmost() {
    var current = this;
    while(current != nullptr) {
      if(current instanceof T.toplevel) {
        break;
      }
    }

    return current;
  }
}

class TTop extends TCategory {
  get className() {
    return this.title.split(" ").pop();
  }

  serializeAll() {
    var out = [
      this.serializeThis()
    ];

    for (var child in this._children) {
      out.concat(child.serialize(this));
    }

    return out;
  }

  serializeThis() {
    return {
        name: this.name,
        synonyms: this.synonyms,
        parent: undefined,
        title: this.title,
        className: this.className,
    };
  }
}

const TAXONOMIES = {
  roles: T.toplevel('Roles', [
    T.category('Software Engineer', [
      T.item('Frontend'),
      T.item('Backend'),
      T.item('Full-stack'),
      T.item('QA'),
      T.item('DevOps'),
      T.item('Mobile'),
    ]),
    T.category('Design', [
      T.item('UI/UX Designer'),
      T.item('User Researcher'),
      T.item('Visual Designer'),
    ]),
    T.item('Data Science'),
    T.item('Operations'),
    T.item('Marketing'),
    T.item('Product Management'),
    T.item('Project Management'),
    T.category('General', [
      T.item('Government Employee'),
      T.item('Attorney / Legal Knowledge'),
      T.item('Partnerships'),
      T.item('Urban Planner'),
    ]),
  ]),
  skills: T.toplevel('Skills', [
    T.category('Frontend Development', [
      T.item('CSS'),
      T.item('D3'),
      T.item('Data Visualization'),
      T.item('HTML'),
      T.item('Jade'),
      T.item('JavaScript'),
      T.item('Other Tools And Technologies'),
      T.item('Rails'),
      T.item('React'),
    ]),
    T.category('Backend Development', [
      T.item('API Design'),
      T.item('Express'),
      T.item('Flask'),
      T.item('Go'),
      T.item('Java'),
      T.item('MongoDB'),
      T.item('Node'),
      T.item('Other Tools And Technologies '),
      T.item('PHP'),
      T.item('Parse'),
      T.item('Python'),
      T.item('Rails'),
      T.item('Ruby'),
      T.item('SQL'),
      T.item('XML'),
      T.item('Algorithm Design'),
      T.item('Databases'),
    ]),
    T.category('Full Stack', [
      T.item('Distributed Systems'),
    ]),
    T.category('QA', [
      T.item('Automated Testing'),
      T.item('Manual Testing'),
    ]),
    T.category('DevOps', [
      T.item('Amazon Web Services'),
      T.item('Azure'),
      T.item('Cloud Services'),
      T.item('Google Cloud Services'),
    ]),
    T.category('Mobile Development', [
      T.item('Android'),
      T.item('Objective-C'),
      T.item('Swift'),
      T.item('IOS'),
    ]),
    T.category('UI/UX Design', [
      T.item('Prototyping'),
      T.item('Visual Design'),
      T.item('Wireframes'),
    ]),
    T.category('User Research', [
      T.item('User Interviewing'),
      T.item('User Research'),
      T.item('User Testing'),
    ]),
    T.category('Marketing', [
      T.item('Content Development'),
      T.item('Copy Writing'),
      T.item('Communications'),
      T.item('Community Engagement'),
    ]),
    T.category('Data Science', [
      T.item('Machine Learning'),
      T.item('Other Tools And Technologies'),
      T.item('Python'),
      T.item('R'),
      T.item('Big Data'),
      T.item('Data Analysis'),
      T.item('Data Management'),
      T.item('Data Modeling'),
      T.item('Predictive Modeling'),
      T.item('Tableau'),
    ]),
    T.category('General', [
      T.item('Health'),
      T.item('Legal Knowledge'),
      T.item('Lobbying'),
      T.item('Government Budgeting And Operations'),
      T.item('Public Speaking'),
      T.item('Urban Planner'),
      T.item('Proficiency In A Language Other Than English'),
      T.item('Public Health'),
      T.item('Compliance'),
    ]),
    T.category('Product Management', [
      T.item('Requirements Gathering'),
      T.item('Scheduling And Planning'),
      T.item('Product Structure/Strategy'),
      T.item('Testing'),
    ]),
    T.category('Operations / Project Management', [
      T.item('Requirements Gathering'),
      T.item('Documentation'),
      T.item('Scheduling And Planning'),
    ]),
  ]),
  interests: T.toplevel('Civic Interests', [
    T.item('Arts And Culture'),
    T.category('Business, Finance & Economics', [
      T.item('Risk Assessments'),
      T.item('Economic Development'),
      T.item('Debt'),
      T.item('Stock Market'),
      T.item('Small Business Resources'),
    ]),
    T.item('Children And Youth'),
    T.category('Community Issues', [
      T.item('Homelessness'),
      T.item('Poverty'),
      T.item('Civic Rights'),
      T.item('Civic Engagement'),
    ]),
    T.category('Education', [
      T.item('K-12'),
      T.item('Extracurricular Programs'),
      T.item('College'),
      T.item('Continuing Education'),
    ]),
    T.category('Environment', [
      T.item('Natural Resources'),
      T.item('Climate Change'),
      T.item('Energy'),
      T.item('Sustainability'),
      T.item('Waste Management'),
      T.item('Parks And Preservation'),
    ]),
    T.category('Employment', [
      T.item('Unemployment'),
      T.item('Continuing Education'),
    ]),
    T.category('Human Rights', [
      T.item('Women\'s Rights'),
      T.item('Human Rights'),
      T.item('Veterans\' Rights'),
      T.item('LGBT Rights'),
      T.item('Racism & Discrimination'),
      T.item('Immigration & Refugees'),
      T.item('Civic Rights'),
      T.item('Workers\' Rights'),
      T.item('Legal Rights'),
      T.item('Income Inequality'),
      T.item('Labor Unions'),
    ]),
    T.category('Health & Healthcare', [
      T.item('Nutrition & Food'),
      T.item('Mental Health'),
      T.item('Health Care System'),
      T.item('Public Health'),
      T.item('Fitness'),
      T.item('Obesity'),
    ]),
    T.category('Housing & Urban Development', [
      T.item('Housing'),
      T.item('Gentrification'),
      T.item('Infrastructure'),
      T.item('Affordability'),
      T.item('Homelessness'),
    ]),
    T.item('International'),
    T.category('Justice & Law', [
      T.item('Criminal Justice'),
      T.item('Police'),
      T.item('Legal Rights'),
      T.item('Drug Regulation'),
    ]),
    T.category('Municipal Services', [
      T.item('Sanitation'),
      T.item('Social Services'),
      T.item('Waste Management'),
      T.item('Public Spaces'),
    ]),
    T.category('Politics', [
      T.item('Government Policy'),
      T.item('Government Operations'),
      T.item('Transparency And Corruption'),
      T.item('Crime Policy'),
      T.item('Drug Regulation'),
      T.item('Elections / Voting'),
      T.item('Budget Process'),
    ]),
    T.category('Transportation', [
      T.item('Public Transit'),
      T.item('Traffic'),
      T.item('Bicycling'),
      T.item('Parking'),
      T.item('Ride Shares'),
    ]),
  ]),
};

var ptSchema = new mongoose.Schema({
  name: {type: String, default: ''},
  title: {type: String, default: ''},
  parent: {type: String, default: ''},
  className: {type: String, default: ''},
  synonyms: {type: Array, default: []}
});

/*
  top-level taxonomies
*/

ptSchema.methods.getTaxonomies = function (cb) {
  return cb(null, TAXONOMIES.map(t => t.serializeThis()));
};

/*
  skills taxonomy
*/

ptSchema.methods.getSkills = function (cb) {
  return cb(null, TAXONOMIES.skills.serializeAll());
};

/*
  skills taxonomy
*/

ptSchema.methods.getInterests = function (cb) {
  return cb(null, TAXONOMIES.interests.serializeAll());
};

/*
  skills taxonomy
*/

ptSchema.methods.getRoles = function (cb) {
  return cb(null, TAXONOMIES.roles.serializeAll());
};

module.exports = mongoose.model('ProjectTaxonomies', ptSchema);
<|endoftext|>


<commit_before>/**
 * 変数
 */
var map;
var points = [];

/**
 * Leafletの表示
 */
function initLeaflet(lat, lng) {
  // LeafletのOSM表示
  map = L.map('map').setView([lat, lng], 17);
  L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(map);
}

function setMarker(datas) {
  var mk;
  var pop;
  for(var i=0 ; i<datas.length ; i++) {
    mk = L.marker(
      [datas[i].lat,datas[i].lng],
      {
        title: datas[i].title,
        alt: datas[i].tags[0]
      }
    );
    pop =
    "
"+datas[i].title+"
"
    +""
    +"
Tags:";
    for (var j=0 ; j<datas[i].tags.length ; j++) {
      if (j > 0) pop+=", ";
      pop += datas[i].tags[j];
    }
    mk.bindPopup(pop);
    points.push(mk);
    mk.addTo(map);
  }
}
<commit_msg>OSMのコピーライト表示<commit_after>/**
 * 変数
 */
var map;
var points = [];

/**
 * Leafletの表示
 */
function initLeaflet(lat, lng) {
  // LeafletのOSM表示
  map = L.map('map').setView([lat, lng], 17);
  L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
	attribution: '© OpenStreetMap contributors'
  }).addTo(map);
}

function setMarker(datas) {
  var mk;
  var pop;
  for(var i=0 ; i<datas.length ; i++) {
    mk = L.marker(
      [datas[i].lat,datas[i].lng],
      {
        title: datas[i].title,
        alt: datas[i].tags[0]
      }
    );
    pop =
    "
"+datas[i].title+"
"
    +""
    +"
Tags:";
    for (var j=0 ; j<datas[i].tags.length ; j++) {
      if (j > 0) pop+=", ";
      pop += datas[i].tags[j];
    }
    mk.bindPopup(pop);
    points.push(mk);
    mk.addTo(map);
  }
}
<|endoftext|>


<commit_before>import { t } from '../util/locale';
import { utilDisplayLabel } from '../util';
import { validationIssue, validationIssueFix } from '../core/validator';

export function validationIncompatibleSource() {
    var type = 'incompatible_source';

    var invalidSources = [{id:"google", regex:"google"}];

    var validation = function(entity, context) {
        var issues = [];

        if (entity.tags && entity.tags.source) {

            invalidSources.forEach(function(invalidSource) {
                var pattern = new RegExp(invalidSource.regex, "i");

                if (entity.tags.source.match(pattern)) {
                    issues.push(new validationIssue({
                        type: type,
                        severity: 'warning',
                        message: t('issues.incompatible_source.' + invalidSource.id + '.feature.message', {
                            feature: utilDisplayLabel(entity, context),
                        }),
                        tooltip: t('issues.incompatible_source.' + invalidSource.id + '.tip'),
                        entities: [entity],
                        fixes: [
                            new validationIssueFix({
                                title: t('issues.fix.remove_proprietary_data.title')
                            })
                        ]
                    }));
                }
            });
        }
        return issues;
    };

    validation.type = type;

    return validation;
}
<commit_msg>eslint fixes<commit_after>import { t } from '../util/locale';
import { utilDisplayLabel } from '../util';
import { validationIssue, validationIssueFix } from '../core/validator';

export function validationIncompatibleSource() {
    var type = 'incompatible_source';

    var invalidSources = [{id:'google', regex:'google'}];

    var validation = function(entity, context) {
        var issues = [];

        if (entity.tags && entity.tags.source) {

            invalidSources.forEach(function(invalidSource) {
                var pattern = new RegExp(invalidSource.regex, 'i');

                if (entity.tags.source.match(pattern)) {
                    issues.push(new validationIssue({
                        type: type,
                        severity: 'warning',
                        message: t('issues.incompatible_source.' + invalidSource.id + '.feature.message', {
                            feature: utilDisplayLabel(entity, context),
                        }),
                        tooltip: t('issues.incompatible_source.' + invalidSource.id + '.tip'),
                        entities: [entity],
                        fixes: [
                            new validationIssueFix({
                                title: t('issues.fix.remove_proprietary_data.title')
                            })
                        ]
                    }));
                }
            });
        }
        return issues;
    };

    validation.type = type;

    return validation;
}
<|endoftext|>


<commit_before>(function (angular) {

  angular
    .module('angularConsent.directives')
    .directive('consent', createDirectiveDDO);

  function createDirectiveDDO(){
    return {
      restrict: 'A',
      controller: 'angularConsent.ConsentController',
      controllerAs: '$consent'
    }
  }

})(angular);
<commit_msg>feat(directive): add semicolon<commit_after>(function (angular) {

  angular
    .module('angularConsent.directives')
    .directive('consent', createDirectiveDDO);

  function createDirectiveDDO(){
    return {
      restrict: 'A',
      controller: 'angularConsent.ConsentController',
      controllerAs: '$consent'
    };
  }

})(angular);
<|endoftext|>


<commit_before>import template from './blog.html';

class BlogCtrl {
  /* @ngInject */
  constructor(blogService, $scope) {
    this.blogService = blogService;
    this.$scope = $scope;
    this.$scope.$watch(()=>this.sortBy, ()=>this.handleSort());
  }

  $onInit() {
    this.filterValue = "";
    this.selectOptions = ['title', 'oldest', 'recent', 'liked' ,'viewed'];

    if (!this.blogService.blogItems){ //initialize data if not present yet
      this.blogService.getData()
      .then((resp) =>
      {
        this.blogService.blogItems = resp;
        this.blogItems = resp;
        this.sortBy = 'recent';
      });
    }
    else {
      this.blogItems = this.blogService.blogItems;
      this.sortBy = 'recent';
    }
  }

  isShort (desc) {
    if (desc.length < 100) {
      return true;
    }

    this.shortened = desc.substr(0, 99) + "...";
    return false;
  }

 isNew(blogDate) {
    let date = new Date();
    let isNew = date - new Date(blogDate);
    let hours = isNew/3600000; //converts ms to hr

    if(hours < 72 ) {
      return true;
    }

    return false;
  }

  handleSort (){
      if (this.sortBy === 'oldest') {
        this.blogItems.sort(function(a,b){
          return new Date(a.date) - new Date(b.date);
        });
      }
      else if (this.sortBy === 'recent') {
        this.blogItems.sort(function(a,b){
          return new Date(b.date) - new Date(a.date);
        });
      }

      else if (this.sortBy === "liked") {
        this.blogItems.sort(function(a,b) {
          return b.likes - a.likes;
        });
      }

      else if (this.sortBy === "viewed") {
        this.blogItems.sort(function(a,b) {
          return b.views - a.views;
        });
      }
    }

  deleteBlog (index) {
   this.$scope.$apply(()=>{
   this.blogService.deleteBlog(this.blogItems, index);
 })}
}

export const BlogComponent = {
  template,
  controller: BlogCtrl,
  bindings: {}
}
    <commit_msg>added a sort for comments<commit_after>import template from './blog.html';

class BlogCtrl {
  /* @ngInject */
  constructor(blogService, $scope) {
    this.blogService = blogService;
    this.$scope = $scope;
    this.$scope.$watch(()=>this.sortBy, ()=>this.handleSort());
  }

  $onInit() {
    this.filterValue = "";
    this.selectOptions = ['title', 'oldest', 'recent', 'liked' ,'viewed', 'discussed'];

    if (!this.blogService.blogItems){ //initialize data if not present yet
      this.blogService.getData()
      .then((resp) =>
      {
        this.blogService.blogItems = resp;
        this.blogItems = resp;
        this.sortBy = 'recent';
      });
    }
    else {
      this.blogItems = this.blogService.blogItems;
      this.sortBy = 'recent';
    }
  }

  isShort (desc) {
    if (desc.length < 100) {
      return true;
    }

    this.shortened = desc.substr(0, 99) + "...";
    return false;
  }

 isNew(blogDate) {
    let date = new Date();
    let isNew = date - new Date(blogDate);
    let hours = isNew/3600000; //converts ms to hr

    if(hours < 72 ) {
      return true;
    }

    return false;
  }

  handleSort (){
      if (this.sortBy === 'oldest') {
        this.blogItems.sort(function(a,b){
          return new Date(a.date) - new Date(b.date);
        });
      }
      else if (this.sortBy === 'recent') {
        this.blogItems.sort(function(a,b){
          return new Date(b.date) - new Date(a.date);
        });
      }

      else if (this.sortBy === "liked") {
        this.blogItems.sort(function(a,b) {
          return b.likes - a.likes;
        });
      }

      else if (this.sortBy === "viewed") {
        this.blogItems.sort(function(a,b) {
          return b.views - a.views;
        });
      }
      else if (this.sortBy === "discussed") {
        this.blogItems.sort(function(a,b) {
          return b.comments.length - a.comments.length;
        });
      }
    }

  deleteBlog (index) {
   this.$scope.$apply(()=>{
   this.blogService.deleteBlog(this.blogItems, index);
 })}
}

export const BlogComponent = {
  template,
  controller: BlogCtrl,
  bindings: {}
}
    <|endoftext|>


<commit_before>/*doc
 ---
 title: Alerts
 name: alerts_react
 categories:
 - react_components_alerts
 - react_all
 ---

 npm install pui-react-alerts --save

 Require the subcomponents:

 ```
 var SuccessAlert = require('pui-react-alerts').SuccessAlert;
 var InfoAlert = require('pui-react-alerts').InfoAlert;
 var WarningAlert = require('pui-react-alerts').WarningAlert;
 var ErrorAlert = require('pui-react-alerts').ErrorAlert;
 ```

 ```react_example_table
 <SuccessAlert>Everything is wonderful</SuccessAlert>

 <InfoAlert>Here's some information for you</InfoAlert>

 <WarningAlert>There is no parking on the dancefloor</WarningAlert>

 <ErrorAlert>Something has gone horribly awry</ErrorAlert>
 ```
 */

/*doc
 ---
 title: Dismissable
 name: alerts_dismissable_react
 parent: alerts_react
 ---

 Add the `dismissable` property to add a close button to the alert.

 ```react_example_table
 <SuccessAlert dismissable>Everything is wonderful</SuccessAlert>
 ```

 If you want a callback to be called when the close button is
 clicked, set the `dismissable` property to that callback.

 ```jsx_example
 var callback = function() {
   alert('Dismissed!');
 };
 ```

 ```react_example_table
 <InfoAlert dismissable={callback}>with callback</InfoAlert>
 ```

 */

/*doc
 ---
 title: Alerts with Icons
 name: alerts_icon_react
 parent: alerts_react
 ---

 If you want an icon to be displayed, set the `withIcon` property.

 ```react_example_table
 <SuccessAlert withIcon>success</SuccessAlert>

 <InfoAlert withIcon>info</InfoAlert>

 <WarningAlert withIcon>warning</WarningAlert>

 <ErrorAlert withIcon>error</ErrorAlert>
 ```

 Here's a dismissable alert with an icon

 ```react_example_table
 <WarningAlert dismissable withIcon>warning</WarningAlert>
 ```
 */
<commit_msg>chore(styleguide): Fix whitespace on alert documentation<commit_after>/*doc
 ---
 title: Alerts
 name: alerts_react
 categories:
 - react_components_alerts
 - react_all
 ---

 npm install pui-react-alerts --save

 Require the subcomponents:

```
var SuccessAlert = require('pui-react-alerts').SuccessAlert;
var InfoAlert = require('pui-react-alerts').InfoAlert;
var WarningAlert = require('pui-react-alerts').WarningAlert;
var ErrorAlert = require('pui-react-alerts').ErrorAlert;
```

 ```react_example_table
 <SuccessAlert>Everything is wonderful</SuccessAlert>

 <InfoAlert>Here's some information for you</InfoAlert>

 <WarningAlert>There is no parking on the dancefloor</WarningAlert>

 <ErrorAlert>Something has gone horribly awry</ErrorAlert>
 ```
 */

/*doc
 ---
 title: Dismissable
 name: alerts_dismissable_react
 parent: alerts_react
 ---

 Add the `dismissable` property to add a close button to the alert.

 ```react_example_table
 <SuccessAlert dismissable>Everything is wonderful</SuccessAlert>
 ```

 If you want a callback to be called when the close button is
 clicked, set the `dismissable` property to that callback.

 ```jsx_example
 var callback = function() {
   alert('Dismissed!');
 };
 ```

 ```react_example_table
 <InfoAlert dismissable={callback}>with callback</InfoAlert>
 ```

 */

/*doc
 ---
 title: Alerts with Icons
 name: alerts_icon_react
 parent: alerts_react
 ---

 If you want an icon to be displayed, set the `withIcon` property.

 ```react_example_table
 <SuccessAlert withIcon>success</SuccessAlert>

 <InfoAlert withIcon>info</InfoAlert>

 <WarningAlert withIcon>warning</WarningAlert>

 <ErrorAlert withIcon>error</ErrorAlert>
 ```

 Here's a dismissable alert with an icon

 ```react_example_table
 <WarningAlert dismissable withIcon>warning</WarningAlert>
 ```
 */
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const assert = require('assert');
const base64url = require('base64url');
const crypto = require('crypto');
const errors = require('../../helpers/errors');
const presence = require('../../helpers/validate_presence');
const instance = require('../../helpers/weak_cache');

module.exports.handler = function getAuthorizationCodeHandler(provider) {
  return function* authorizationCodeResponse(next) {
    presence.call(this, ['code', 'redirect_uri']);

    const code = yield provider.AuthorizationCode.find(this.oidc.params.code, {
      ignoreExpiration: true,
    });

    this.assert(code, new errors.InvalidGrantError('authorization code not found'));
    this.assert(!code.isExpired, new errors.InvalidGrantError('authorization code is expired'));

    // PKCE check
    if (code.codeChallenge) {
      try {
        assert(this.oidc.params.code_verifier);
        let expected = this.oidc.params.code_verifier;

        if (code.codeChallengeMethod === 'S256') {
          expected = base64url(crypto.createHash('sha256').update(expected).digest());
        }

        assert.equal(code.codeChallenge, expected);
      } catch (err) {
        this.throw(new errors.InvalidGrantError('PKCE verification failed'));
      }
    }

    try {
      this.assert(!code.consumed,
        new errors.InvalidGrantError('authorization code already consumed'));

      yield code.consume();
    } catch (err) {
      yield code.destroy();
      throw err;
    }

    this.assert(code.clientId === this.oidc.client.clientId,
      new errors.InvalidGrantError('authorization code client mismatch'));

    this.assert(code.redirectUri === this.oidc.params.redirect_uri,
      new errors.InvalidGrantError('authorization code redirect_uri mismatch'));

    const account = yield provider.Account.findById.call(this, code.accountId);

    this.assert(account,
      new errors.InvalidGrantError('authorization code invalid (referenced account not found)'));

    const AccessToken = provider.AccessToken;
    const at = new AccessToken({
      accountId: account.accountId,
      claims: code.claims,
      clientId: this.oidc.client.clientId,
      grantId: code.grantId,
      scope: code.scope,
      sid: code.sid,
    });

    const accessToken = yield at.save();
    const tokenType = 'Bearer';
    const expiresIn = AccessToken.expiresIn;

    let refreshToken;
    const grantPresent = this.oidc.client.grantTypes.indexOf('refresh_token') !== -1;
    const shouldIssue = instance(provider).configuration('features.alwaysIssueRefresh') ||
      code.scope.split(' ').indexOf('offline_access') !== -1;

    if (grantPresent && shouldIssue) {
      const RefreshToken = provider.RefreshToken;
      const rt = new RefreshToken({
        accountId: account.accountId,
        acr: code.acr,
        amr: code.amr,
        authTime: code.authTime,
        claims: code.claims,
        clientId: this.oidc.client.clientId,
        grantId: code.grantId,
        nonce: code.nonce,
        scope: code.scope,
        sid: code.sid,
      });

      refreshToken = yield rt.save();
    }

    const IdToken = provider.IdToken;
    const token = new IdToken(Object.assign({}, yield Promise.resolve(account.claims()), {
      acr: code.acr,
      amr: code.amr,
      auth_time: code.authTime,
    }), this.oidc.client.sectorIdentifier);

    token.scope = code.scope;
    token.mask = _.get(code.claims, 'id_token', {});

    token.set('nonce', code.nonce);
    token.set('at_hash', accessToken);
    token.set('rt_hash', refreshToken);
    token.set('sid', code.sid);

    const idToken = yield token.sign(this.oidc.client);

    this.body = {
      access_token: accessToken,
      expires_in: expiresIn,
      id_token: idToken,
      refresh_token: refreshToken,
      token_type: tokenType,
    };

    yield next;
  };
};

module.exports.parameters = ['code', 'redirect_uri', 'code_verifier'];
<commit_msg>always perform pkce check when part of the request<commit_after>'use strict';

const _ = require('lodash');
const assert = require('assert');
const base64url = require('base64url');
const crypto = require('crypto');
const errors = require('../../helpers/errors');
const presence = require('../../helpers/validate_presence');
const instance = require('../../helpers/weak_cache');

module.exports.handler = function getAuthorizationCodeHandler(provider) {
  return function* authorizationCodeResponse(next) {
    presence.call(this, ['code', 'redirect_uri']);

    const code = yield provider.AuthorizationCode.find(this.oidc.params.code, {
      ignoreExpiration: true,
    });

    this.assert(code, new errors.InvalidGrantError('authorization code not found'));
    this.assert(!code.isExpired, new errors.InvalidGrantError('authorization code is expired'));

    // PKCE check
    if (this.oidc.params.code_verifier || code.codeChallenge) {
      try {
        let expected = this.oidc.params.code_verifier;
        assert(expected);

        if (code.codeChallengeMethod === 'S256') {
          expected = base64url(crypto.createHash('sha256').update(expected).digest());
        }

        assert.equal(code.codeChallenge, expected);
      } catch (err) {
        this.throw(new errors.InvalidGrantError('PKCE verification failed'));
      }
    }

    try {
      this.assert(!code.consumed,
        new errors.InvalidGrantError('authorization code already consumed'));

      yield code.consume();
    } catch (err) {
      yield code.destroy();
      throw err;
    }

    this.assert(code.clientId === this.oidc.client.clientId,
      new errors.InvalidGrantError('authorization code client mismatch'));

    this.assert(code.redirectUri === this.oidc.params.redirect_uri,
      new errors.InvalidGrantError('authorization code redirect_uri mismatch'));

    const account = yield provider.Account.findById.call(this, code.accountId);

    this.assert(account,
      new errors.InvalidGrantError('authorization code invalid (referenced account not found)'));

    const AccessToken = provider.AccessToken;
    const at = new AccessToken({
      accountId: account.accountId,
      claims: code.claims,
      clientId: this.oidc.client.clientId,
      grantId: code.grantId,
      scope: code.scope,
      sid: code.sid,
    });

    const accessToken = yield at.save();
    const tokenType = 'Bearer';
    const expiresIn = AccessToken.expiresIn;

    let refreshToken;
    const grantPresent = this.oidc.client.grantTypes.indexOf('refresh_token') !== -1;
    const shouldIssue = instance(provider).configuration('features.alwaysIssueRefresh') ||
      code.scope.split(' ').indexOf('offline_access') !== -1;

    if (grantPresent && shouldIssue) {
      const RefreshToken = provider.RefreshToken;
      const rt = new RefreshToken({
        accountId: account.accountId,
        acr: code.acr,
        amr: code.amr,
        authTime: code.authTime,
        claims: code.claims,
        clientId: this.oidc.client.clientId,
        grantId: code.grantId,
        nonce: code.nonce,
        scope: code.scope,
        sid: code.sid,
      });

      refreshToken = yield rt.save();
    }

    const IdToken = provider.IdToken;
    const token = new IdToken(Object.assign({}, yield Promise.resolve(account.claims()), {
      acr: code.acr,
      amr: code.amr,
      auth_time: code.authTime,
    }), this.oidc.client.sectorIdentifier);

    token.scope = code.scope;
    token.mask = _.get(code.claims, 'id_token', {});

    token.set('nonce', code.nonce);
    token.set('at_hash', accessToken);
    token.set('rt_hash', refreshToken);
    token.set('sid', code.sid);

    const idToken = yield token.sign(this.oidc.client);

    this.body = {
      access_token: accessToken,
      expires_in: expiresIn,
      id_token: idToken,
      refresh_token: refreshToken,
      token_type: tokenType,
    };

    yield next;
  };
};

module.exports.parameters = ['code', 'redirect_uri', 'code_verifier'];
<|endoftext|>


<commit_before>
var SimResult=[];
var TotalSimsForMulticore;

var WorkerMessageHandler = function (e) {
	//console.log(e.data.result);

	// There are 3 main message types that are handled
	// Messages to the WorkerStatusText (to be put somewhere on screen to indicate what is currently occurring)
	// Messages to the ProgressBar
	// Message to return result/indicate completeness

	// Messages to the console
	if (typeof e.data.WorkerStatusText != 'undefined'){
		console.log(e.data.WorkerStatusText);
	}
	// Messages to the ProgressBar
	if (typeof e.data.ProgressBarValue != 'undefined'){
		MainProgress.value=e.data.ProgressBarValue;
	}
	if (typeof e.data.Result != 'undefined'){
		SimNumber=e.data.SimNumber;
		SimResult[SimNumber]=e.data.Result;

		//prompt a function that determines if all simulations are complete or not, then cleans up all remaining informations

		HCVTestResult=SimResult[SimNumber].HCVTestResult;
		console.log(HCVTestResult);
		RowLabel=[];
		for (i=0; i<HCVTestResult[0].length; i++){RowLabel[i]=i;}
		HCVResultsTable.innerHTML=MakeTableHTML(HCVTestResult, ["F0", "F1", "F2", "F3", "F4", "LF"], RowLabel);
	}
}

function HCVTest(){
	//Check that nothing else is running

	// Load information from form into population
	var SimData={};
	SimData.NoPeople=100000;
	// Set progress bar to zero
	MainProgress.value=0;

	// Create a simulation object

	// Start a webworker

	for (var SimNumber = 0; SimNumber < NoCores; SimNumber++) {
        var worker = new Worker("model/runsimulation.js");
        worker.onmessage = WorkerMessageHandler;

		console.log("Running a simulation");

        // Sending canvas data to the worker using a copy memory operation
        worker.postMessage({ SimNumber: SimNumber, SimData: SimData });
    }
	worker.terminate();//clean up memory
}

function HCVTestPlot(){
	// Get the relevant data
	HCVTestResult=SimResult[0].HCVTestResult;
	//create an x axis
	TimeAxis=[];
	for (i=0; i<HCVTestResult[0].length; i++){TimeAxis[i]=i;}
	// convert to a form that plot will accept
	PlotData=ConvertDataToLinePlot(TimeAxis, HCVTestResult);
	//Set up plot appearance // http://www.pikemere.co.uk/blog/flot-tutorial-how-to-create-area-charts/
	PlotSettings={xaxis: {
					axisLabel: 'Time (years)',
					axisLabelUseCanvas: true,
					axisLabelFontSizePixels: 12,
					axisLabelFontFamily: 'Verdana, Arial, Helvetica, Tahoma, sans-serif',
					axisLabelPadding: 5,
					tickLength: 0
				},
				yaxis: {
					min: 0,
					max: 100000,
					axisLabel: 'Number of people',
					axisLabelUseCanvas: true,
					axisLabelFontSizePixels: 12,
					axisLabelFontFamily: 'Verdana, Arial, Helvetica, Tahoma, sans-serif',
					axisLabelPadding: 5
				},
				series: {
					lines: {
						show: true,
						fill: true
					},
					stack: true
				}
			};

	//plot of HCVTestPlotHolder
	$.plot("#HCVTestPlotHolder", PlotData, PlotSettings);

}

function ConvertDataToLinePlot(x, InputMatrix){//Accepts [param][time] or [y][x]. Future systems will accept [param][time][sim]
	LinePlotData=[];
	NumberOfLines=InputMatrix.length;
	for (i=0; i<NumberOfLines; i++){
		ThisLine=[];
		for (var j = 0; j < InputMatrix[i].length; j++) {
			ThisLine.push([x[j], InputMatrix[i][j]]);
		}
		LinePlotData.push(ThisLine);
	}
	return LinePlotData;
}<commit_msg>Fixing early termination issue<commit_after>
var SimResult=[];
var TotalSimsForMulticore;

var WorkerMessageHandler = function (e) {
	//console.log(e.data.result);

	// There are 3 main message types that are handled
	// Messages to the WorkerStatusText (to be put somewhere on screen to indicate what is currently occurring)
	// Messages to the ProgressBar
	// Message to return result/indicate completeness

	// Messages to the console
	if (typeof e.data.WorkerStatusText != 'undefined'){
		console.log(e.data.WorkerStatusText);
	}
	// Messages to the ProgressBar
	if (typeof e.data.ProgressBarValue != 'undefined'){
		MainProgress.value=e.data.ProgressBarValue;
	}
	if (typeof e.data.Result != 'undefined'){
		SimNumber=e.data.SimNumber;
		SimResult[SimNumber]=e.data.Result;

		//prompt a function that determines if all simulations are complete or not, then cleans up all remaining informations

		HCVTestResult=SimResult[SimNumber].HCVTestResult;
		console.log(HCVTestResult);
		RowLabel=[];
		for (i=0; i<HCVTestResult[0].length; i++){RowLabel[i]=i;}
		HCVResultsTable.innerHTML=MakeTableHTML(HCVTestResult, ["F0", "F1", "F2", "F3", "F4", "LF"], RowLabel);
	}
}

function HCVTest(){
	//Check that nothing else is running

	// Load information from form into population
	var SimData={};
	SimData.NoPeople=100000;
	// Set progress bar to zero
	MainProgress.value=0;

	// Create a simulation object

	// Start a webworker

	for (var SimNumber = 0; SimNumber < NoCores; SimNumber++) {
        var worker = new Worker("model/runsimulation.js");
        worker.onmessage = WorkerMessageHandler;

		console.log("Running a simulation");

        // Sending canvas data to the worker using a copy memory operation
        worker.postMessage({ SimNumber: SimNumber, SimData: SimData });
    }
	//worker.terminate();//clean up memory: Don't call unless you are sure the simulation is not running any more!
}

function HCVTestPlot(){
	// Get the relevant data
	HCVTestResult=SimResult[0].HCVTestResult;
	//create an x axis
	TimeAxis=[];
	for (i=0; i<HCVTestResult[0].length; i++){TimeAxis[i]=i;}
	// convert to a form that plot will accept
	PlotData=ConvertDataToLinePlot(TimeAxis, HCVTestResult);
	//Set up plot appearance // http://www.pikemere.co.uk/blog/flot-tutorial-how-to-create-area-charts/
	PlotSettings={xaxis: {
					axisLabel: 'Time (years)',
					axisLabelUseCanvas: true,
					axisLabelFontSizePixels: 12,
					axisLabelFontFamily: 'Verdana, Arial, Helvetica, Tahoma, sans-serif',
					axisLabelPadding: 5,
					tickLength: 0
				},
				yaxis: {
					min: 0,
					max: 100000,
					axisLabel: 'Number of people',
					axisLabelUseCanvas: true,
					axisLabelFontSizePixels: 12,
					axisLabelFontFamily: 'Verdana, Arial, Helvetica, Tahoma, sans-serif',
					axisLabelPadding: 5
				},
				series: {
					lines: {
						show: true,
						fill: true
					},
					stack: true
				}
			};

	//plot of HCVTestPlotHolder
	$.plot("#HCVTestPlotHolder", PlotData, PlotSettings);

}

function ConvertDataToLinePlot(x, InputMatrix){//Accepts [param][time] or [y][x]. Future systems will accept [param][time][sim]
	LinePlotData=[];
	NumberOfLines=InputMatrix.length;
	for (i=0; i<NumberOfLines; i++){
		ThisLine=[];
		for (var j = 0; j < InputMatrix[i].length; j++) {
			ThisLine.push([x[j], InputMatrix[i][j]]);
		}
		LinePlotData.push(ThisLine);
	}
	return LinePlotData;
}<|endoftext|>


<commit_before>// - for all cases and organizations
// - compose an address string from the following article
//   location keys: address1, city, province, postal_code, country.
// - if no address string exists (meaning location keys are all falsey),
//   save lat/lng as null
// - if address string exists, pass that address string to geocode
//   service to get lat/lng and save new lat/lng.

// to run: node scripts/geocode-address-for-lat-lng.js

const GoogleMaps = require("@google/maps");
const { db } = require("../api/helpers/db.js");

const googleMapsClient = GoogleMaps.createClient({
  key: process.env.GOOGLE_MAPS_GEOCODE_API_KEY,
  Promise: Promise,
});

const MAP_TYPE_TO_DB_TABLE = {
  case: "cases",
  organization: "organizations",
};

function composeAddressString(article) {
  const { address1, city, province, postal_code, country } = article;
  const addressData = [address1, city, province, postal_code, country];
  let addressString = "";
  addressData.forEach((item, i) => {
    // if item is not empty string, add to address string
    if (item !== "") {
      addressString = addressString + item;
      if (i !== addressData.length - 1) {
        // if it's not the last item, append a comma and space
        addressString = addressString + ", ";
      }
    }
  });
  return addressString;
}

async function getAllArticlesForType(type) {
  // select articles that do not have latitude and longitude set yet
  const sql = `
    SELECT type, latitude, longitude, id, address1, city, province, postal_code, country
    FROM ${MAP_TYPE_TO_DB_TABLE[type]}
    WHERE latitude IS NULL
    AND longitude IS NULL;
  `;
  return db
    .any(sql)
    .then(result => result)
    .catch(err => console.log("getAllArticlesForType err", err));
}

function saveArticle(type, id, lat, lng) {
  const sql = `
    UPDATE ${MAP_TYPE_TO_DB_TABLE[type]}
    SET latitude = ${lat}, longitude = ${lng}
    WHERE id = ${id};
  `;
  return db
    .any(sql)
    .then(result => result)
    .catch(err => console.log("saveArticle err", err));
}

async function processArticles(type) {
  const articles = await getAllArticlesForType(type);
  articles.forEach(function(article) {
    const addressString = composeAddressString(article);
    if (addressString !== "") {
      // Geocode an address string to get lat/long
      googleMapsClient
        .geocode({ address: addressString })
        .asPromise()
        .then(response => {
          // set new lat lng on article object and save
          if (response.json.results && response.json.results[0]) {
            const { lat, lng } = response.json.results[0].geometry.location;
            if (lat && lng) {
              saveArticle(article.type, article.id, lat, lng).then(() => {
                console.log(
                  `UPDATED - ${article.type} #${
                    article.id
                  } saved with lat: ${lat}, lng: ${lng}`
                );
              });
            }
          }
        })
        .catch(err => {
          if (err) console.log("error:", err);
        });
    } else {
      // if there is no address data, set lat/lng to NULL
      saveArticle(article.type, article.id, null, null).then(() => {
        console.log(
          `NULL - ${article.type} #${
            article.id
          } - There is no address data, setting lat/lng as null`
        );
      });
    }
  });
}

function start() {
  if (!process.env.GOOGLE_MAPS_GEOCODE_API_KEY) {
    console.log(
      "*** Missing Google Maps Geocode API key. Add GOOGLE_MAPS_GEOCODE_API_KEY to your .env file ***"
    );
    console.log(
      "https://developers.google.com/maps/documentation/geocoding/get-api-key"
    );
    return;
  }

  const types = Object.keys(MAP_TYPE_TO_DB_TABLE);
  types.forEach(type => processArticles(type));
}

start();
<commit_msg>Refactored google key variable GOOGLE_API_KEY<commit_after>// - for all cases and organizations
// - compose an address string from the following article
//   location keys: address1, city, province, postal_code, country.
// - if no address string exists (meaning location keys are all falsey),
//   save lat/lng as null
// - if address string exists, pass that address string to geocode
//   service to get lat/lng and save new lat/lng.

// to run: node scripts/geocode-address-for-lat-lng.js

const GoogleMaps = require("@google/maps");
const { db } = require("../api/helpers/db.js");

const googleMapsClient = GoogleMaps.createClient({
  key: process.env.GOOGLE_API_KEY,
  Promise: Promise,
});

const MAP_TYPE_TO_DB_TABLE = {
  case: "cases",
  organization: "organizations",
};

function composeAddressString(article) {
  const { address1, city, province, postal_code, country } = article;
  const addressData = [address1, city, province, postal_code, country];
  let addressString = "";
  addressData.forEach((item, i) => {
    // if item is not empty string, add to address string
    if (item !== "") {
      addressString = addressString + item;
      if (i !== addressData.length - 1) {
        // if it's not the last item, append a comma and space
        addressString = addressString + ", ";
      }
    }
  });
  return addressString;
}

async function getAllArticlesForType(type) {
  // select articles that do not have latitude and longitude set yet
  const sql = `
    SELECT type, latitude, longitude, id, address1, city, province, postal_code, country
    FROM ${MAP_TYPE_TO_DB_TABLE[type]}
    WHERE latitude IS NULL
    AND longitude IS NULL;
  `;
  return db
    .any(sql)
    .then(result => result)
    .catch(err => console.log("getAllArticlesForType err", err));
}

function saveArticle(type, id, lat, lng) {
  const sql = `
    UPDATE ${MAP_TYPE_TO_DB_TABLE[type]}
    SET latitude = ${lat}, longitude = ${lng}
    WHERE id = ${id};
  `;
  return db
    .any(sql)
    .then(result => result)
    .catch(err => console.log("saveArticle err", err));
}

async function processArticles(type) {
  const articles = await getAllArticlesForType(type);
  articles.forEach(function(article) {
    const addressString = composeAddressString(article);
    if (addressString !== "") {
      // Geocode an address string to get lat/long
      googleMapsClient
        .geocode({ address: addressString })
        .asPromise()
        .then(response => {
          // set new lat lng on article object and save
          if (response.json.results && response.json.results[0]) {
            const { lat, lng } = response.json.results[0].geometry.location;
            if (lat && lng) {
              saveArticle(article.type, article.id, lat, lng).then(() => {
                console.log(
                  `UPDATED - ${article.type} #${
                    article.id
                  } saved with lat: ${lat}, lng: ${lng}`
                );
              });
            }
          }
        })
        .catch(err => {
          if (err) console.log("error:", err);
        });
    } else {
      // if there is no address data, set lat/lng to NULL
      saveArticle(article.type, article.id, null, null).then(() => {
        console.log(
          `NULL - ${article.type} #${
            article.id
          } - There is no address data, setting lat/lng as null`
        );
      });
    }
  });
}

function start() {
  if (!process.env.GOOGLE_API_KEY) {
    console.log(
      "*** Missing Google Maps Geocode API key. Add GOOGLE_API_KEY to your .env file ***"
    );
    console.log(
      "https://developers.google.com/maps/documentation/geocoding/get-api-key"
    );
    return;
  }

  const types = Object.keys(MAP_TYPE_TO_DB_TABLE);
  types.forEach(type => processArticles(type));
}

start();
<|endoftext|>


<commit_before>// import learnsets
// FROM: text in learnsets-g6
// TO: PS data/learnsets.js

toId = function(text) {
        if (text && text.id) text = text.id;
        else if (text && text.userid) text = text.userid;

        return string(text).toLowerCase().replace(/[^a-z0-9]+/g, '');
};
string = function(str) {
        if (typeof str === 'string' || typeof str === 'number') return ''+str;
        return '';
}
require("sugar");
fs = require("fs");
fs.exists = require("path").exists;
fs.existsSync = require("path").existsSync;

var Tools = require('./tools.js');
var Learnsets = Tools.data.Learnsets;

// remove existing gen 6 data

for (var speciesid in Learnsets) {
	if (!Learnsets[speciesid] || !Learnsets[speciesid].learnset) continue;
	var learnset = Learnsets[speciesid].learnset;
	for (var moveid in learnset) {
		var sources = learnset[moveid];
		for (var i=sources.length-1; i>=0; i--) {
			if (sources[i].charAt(0) === '6') {
				sources.splice(i, 1);
			}
		}
		if (!sources.length) delete learnset[moveid];
	}
}

// build learnsetsG6

var LearnsetsG6 = {};
for (var speciesid in Learnsets) {
	LearnsetsG6[speciesid] = {learnset:{}};
	for (var moveid in Learnsets[speciesid].learnset) {
		LearnsetsG6[speciesid].learnset[moveid] = [];
	}
}

// If modern computers didn't come standard with 4GB of RAM,
// I'd probably stream this
var input = ''+fs.readFileSync('learnsets-g6/learnsets-g6-A-to-C.txt');
input += ''+fs.readFileSync('learnsets-g6/learnsets-g6-D-to-I.txt');
input += ''+fs.readFileSync('learnsets-g6/learnsets-g6-J-to-O.txt');
input += ''+fs.readFileSync('learnsets-g6/learnsets-g6-P-to-R.txt');
input += ''+fs.readFileSync('learnsets-g6/learnsets-g6-S-to-Z.txt');

input = input.split('\n');

var speciesid = '';
var species = '';

for (var i=0; i<input.length; i++) {
	var line = input[i];
	line = line.trim();
	if (!line) continue;
	if (line.charAt(0) === '(') continue; // this is a comment
	if (line.charAt(0) === '=') {
		speciesid = Tools.getTemplate(line).id;
		species = line;
		continue;
	}
	var parts = line.split(' - ');
	if (!parts[0] || !parts[1] || parts.length != 2) {
		console.log("Line '"+line+"' must be in the format 'Source - Move' for "+species);
		continue;
	}
	var move = Tools.getMove(parts[1]);
	if (!move.exists) {
		console.log("Move '"+parts[1]+"' in '"+line+"' doesn't exist for "+species);
		continue;
	}
	var typeString = parts[0].toLowerCase().replace(/ /g,'').replace('.','');

	var type = '';
	var level = '';
	if (typeString.substr(0,2) in {tm:1,hm:1}) type = '6M';
	else if (typeString === 'tutor') type = '6T';
	else if (typeString === 'egg') type = '6E';
	else if (typeString === 'moverelearner' || typeString === 'relearn' || typeString === 'mr' || typeString === 'l?' || typeString === '?') type = '6L0';
	else if (typeString === 'start') type = '6L1';
	else if (typeString.substr(0,5) === 'level') {
		level = typeString.substr(5);
	}
	else if (typeString.substr(0,3) === 'lvl') {
		level = typeString.substr(3);
	}
	else if (typeString.substr(0,2) === 'lv') {
		level = typeString.substr(2);
	}
	else if (typeString.substr(0,1) === 'l') {
		level = typeString.substr(1);
	}
	if (!type && !level) level = typeString;
	if (level) {
		if (level.charAt(0) in {'<':1,'>':1,'?':1}) type = '6L0';
		else if (/^[0-9]{1,3}$/.test(level)) type = '6L'+(parseInt(level, 10)||1);
	}
	if (!type) console.log("Source '"+parts[0]+"' in '"+line+"' not formatted correctly for "+species);
	if (type) {
		if (!Learnsets[speciesid]) {
			if (Learnsets[speciesid] !== '') console.log("Pokemon '"+species+"' doesn't exist or shouldn't have a learnset.");
			Learnsets[speciesid] = '';
			continue;
		}
		if (!Learnsets[speciesid].learnset[move.id]) Learnsets[speciesid].learnset[move.id] = [type];
		else Learnsets[speciesid].learnset[move.id].push(type);

		if (!LearnsetsG6[speciesid].learnset[move.id]) LearnsetsG6[speciesid].learnset[move.id] = [type];
		else LearnsetsG6[speciesid].learnset[move.id].push(type);
	}
}

// Fill out gen 5 level-up and TM data for fallback
for (var speciesid in Learnsets) {
	if (!Learnsets[speciesid] || !Learnsets[speciesid].learnset) continue;
	var learnset = Learnsets[speciesid].learnset;
	for (var moveid in learnset) {
		if (LearnsetsG6[speciesid].learnset[moveid].length) continue;
		var sources = learnset[moveid];
		for (var i=sources.length-1; i>=0; i--) {
			if (sources[i].substr(0,2) === '5L') {
				LearnsetsG6[speciesid].learnset[moveid] = ['6L0'];
				Learnsets[speciesid].learnset[moveid].push('6L0');
			} else if ((sources[i] === '5M' && !(moveid in {allyswitch:1,telekinesis:1,workup:1,pluck:1})) || (sources[i] === '5T' && moveid === 'roost')) {
				LearnsetsG6[speciesid].learnset[moveid] = ['6M'];
				Learnsets[speciesid].learnset[moveid].push('6M');
			}
			break;
		}
	}
}

var output = 'exports.BattleLearnsets = {\n';

for (var speciesid in Learnsets) {
	var learnset = Learnsets[speciesid].learnset;
	output += '	'+speciesid+':{learnset:{';
	output += Object.keys(learnset).map(function(key) {
		return (key==='return'?'"return"':key)+':'+JSON.stringify(learnset[key]);
	}).join(',');
	output += '}},\n';
}

output = output.substr(0, output.length-2)+'\n';

output += '};';

fs.writeFileSync('data/learnsets.js', output);

output = 'exports.BattleLearnsets = {\n';

for (var speciesid in LearnsetsG6) {
	var learnset = LearnsetsG6[speciesid].learnset;
	output += '	'+speciesid+':{learnset:{';
	output += Object.keys(learnset).map(function(key) {
		return (key==='return'?'"return"':key)+':'+JSON.stringify(learnset[key]);
	}).join(',');
	output += '}},\n';
}

output = output.substr(0, output.length-2)+'\n';

output += '};';

fs.writeFileSync('data/learnsets-g6.js', output);
<commit_msg>Learnsets importer wasn't importing entire learnset<commit_after>// import learnsets
// FROM: text in learnsets-g6
// TO: PS data/learnsets.js

toId = function(text) {
        if (text && text.id) text = text.id;
        else if (text && text.userid) text = text.userid;

        return string(text).toLowerCase().replace(/[^a-z0-9]+/g, '');
};
string = function(str) {
        if (typeof str === 'string' || typeof str === 'number') return ''+str;
        return '';
}
require("sugar");
fs = require("fs");
fs.exists = require("path").exists;
fs.existsSync = require("path").existsSync;

var Tools = require('./tools.js');
var Learnsets = Tools.data.Learnsets;

// remove existing gen 6 data

for (var speciesid in Learnsets) {
	if (!Learnsets[speciesid] || !Learnsets[speciesid].learnset) continue;
	var learnset = Learnsets[speciesid].learnset;
	for (var moveid in learnset) {
		var sources = learnset[moveid];
		for (var i=sources.length-1; i>=0; i--) {
			if (sources[i].charAt(0) === '6') {
				sources.splice(i, 1);
			}
		}
		if (!sources.length) delete learnset[moveid];
	}
}

// build learnsetsG6

var LearnsetsG6 = {};
for (var speciesid in Learnsets) {
	LearnsetsG6[speciesid] = {learnset:{}};
	for (var moveid in Learnsets[speciesid].learnset) {
		LearnsetsG6[speciesid].learnset[moveid] = [];
	}
}

// If modern computers didn't come standard with 4GB of RAM,
// I'd probably stream this
var input = ''+fs.readFileSync('learnsets-g6/learnsets-g6-A-to-C.txt');
input += ''+fs.readFileSync('learnsets-g6/learnsets-g6-D-to-I.txt');
input += ''+fs.readFileSync('learnsets-g6/learnsets-g6-J-to-O.txt');
input += ''+fs.readFileSync('learnsets-g6/learnsets-g6-P-to-R.txt');
input += ''+fs.readFileSync('learnsets-g6/learnsets-g6-S-to-Z.txt');

input = input.split('\n');

var speciesid = '';
var species = '';

for (var i=0; i<input.length; i++) {
	var line = input[i];
	line = line.trim();
	if (!line) continue;
	if (line.charAt(0) === '(') continue; // this is a comment
	if (line.charAt(0) === '=') {
		speciesid = Tools.getTemplate(line).id;
		species = line;
		continue;
	}
	var parts = line.split(' - ');
	if (!parts[0] || !parts[1] || parts.length != 2) {
		console.log("Line '"+line+"' must be in the format 'Source - Move' for "+species);
		continue;
	}
	var move = Tools.getMove(parts[1]);
	if (!move.exists) {
		console.log("Move '"+parts[1]+"' in '"+line+"' doesn't exist for "+species);
		continue;
	}
	var typeString = parts[0].toLowerCase().replace(/ /g,'').replace('.','');

	var type = '';
	var level = '';
	if (typeString.substr(0,2) in {tm:1,hm:1}) type = '6M';
	else if (typeString === 'tutor') type = '6T';
	else if (typeString === 'egg') type = '6E';
	else if (typeString === 'moverelearner' || typeString === 'relearn' || typeString === 'mr' || typeString === 'l?' || typeString === '?') type = '6L0';
	else if (typeString === 'start') type = '6L1';
	else if (typeString.substr(0,5) === 'level') {
		level = typeString.substr(5);
	}
	else if (typeString.substr(0,3) === 'lvl') {
		level = typeString.substr(3);
	}
	else if (typeString.substr(0,2) === 'lv') {
		level = typeString.substr(2);
	}
	else if (typeString.substr(0,1) === 'l') {
		level = typeString.substr(1);
	}
	if (!type && !level) level = typeString;
	if (level) {
		if (level.charAt(0) in {'<':1,'>':1,'?':1}) type = '6L0';
		else if (/^[0-9]{1,3}$/.test(level)) type = '6L'+(parseInt(level, 10)||1);
	}
	if (!type) console.log("Source '"+parts[0]+"' in '"+line+"' not formatted correctly for "+species);
	if (type) {
		if (!Learnsets[speciesid]) {
			if (Learnsets[speciesid] !== '') console.log("Pokemon '"+species+"' doesn't exist or shouldn't have a learnset.");
			Learnsets[speciesid] = '';
			continue;
		}
		if (!Learnsets[speciesid].learnset[move.id]) Learnsets[speciesid].learnset[move.id] = [type];
		else Learnsets[speciesid].learnset[move.id].push(type);

		if (!LearnsetsG6[speciesid].learnset[move.id]) LearnsetsG6[speciesid].learnset[move.id] = [type];
		else LearnsetsG6[speciesid].learnset[move.id].push(type);
	}
}

// Fill out gen 5 level-up and TM data for fallback
for (var speciesid in Learnsets) {
	if (!Learnsets[speciesid] || !Learnsets[speciesid].learnset) continue;
	var learnset = Learnsets[speciesid].learnset;
	for (var moveid in learnset) {
		if (LearnsetsG6[speciesid].learnset[moveid].length) continue;
		var sources = learnset[moveid];
		for (var i=sources.length-1; i>=0; i--) {
			if (sources[i].substr(0,2) === '5L') {
				LearnsetsG6[speciesid].learnset[moveid] = ['6L0'];
				Learnsets[speciesid].learnset[moveid].push('6L0');
			} else if ((sources[i] === '5M' && !(moveid in {allyswitch:1,telekinesis:1,workup:1,pluck:1})) || (sources[i] === '5T' && moveid === 'roost')) {
				LearnsetsG6[speciesid].learnset[moveid] = ['6M'];
				Learnsets[speciesid].learnset[moveid].push('6M');
			}
		}
	}
}

var output = 'exports.BattleLearnsets = {\n';

for (var speciesid in Learnsets) {
	var learnset = Learnsets[speciesid].learnset;
	output += '	'+speciesid+':{learnset:{';
	output += Object.keys(learnset).map(function(key) {
		return (key==='return'?'"return"':key)+':'+JSON.stringify(learnset[key]);
	}).join(',');
	output += '}},\n';
}

output = output.substr(0, output.length-2)+'\n';

output += '};';

fs.writeFileSync('data/learnsets.js', output);

output = 'exports.BattleLearnsets = {\n';

for (var speciesid in LearnsetsG6) {
	var learnset = LearnsetsG6[speciesid].learnset;
	output += '	'+speciesid+':{learnset:{';
	output += Object.keys(learnset).map(function(key) {
		return (key==='return'?'"return"':key)+':'+JSON.stringify(learnset[key]);
	}).join(',');
	output += '}},\n';
}

output = output.substr(0, output.length-2)+'\n';

output += '};';

fs.writeFileSync('data/learnsets-g6.js', output);
<|endoftext|>


<commit_before>'use strict'

let fs = require('fs')
let gulp = require('gulp'),
	webpack = require('webpack'),
	gutil = require('gulp-util')

let mithrilier = require('jade-mithrilier')

gulp.task('mithril', function ( cb ) {
	let folder = './m/'

	let jadeContent = fs.readFileSync( folder + 'Content.jade', { encoding: 'utf8' })
	mithrilier.generateMithrilJS( jadeContent, null, null, function (err, mithrilView) {
		if ( err ) return cb(err)

		fs.writeFileSync( folder + 'Content.js', mithrilView.trim() + '\n', { encoding: 'utf8' } )
		cb()
	} )
})

let config = {
	cache: true,
	entry: './main.js',
	node: {
		fs: 'empty'
	},
	output: {
		path: './',
		filename: './www/main.js',
		publicPath: './'
	},
	module: {
		noParse: [
			/Gulpfile\.js$/, /.\.json$/, /.\.txt$/, /\.gitignore$/, /\.jshintrc$/
		]
	},
	plugins: [ ]
}
gulp.task('webpack', function ( callback ) {
	webpack( config, function (err, stats) {
		if (err) {
			throw new global.gutil.PluginError('webpack', err)
		}
		gutil.log('[webpack]', stats.toString({
			// output options
		}))
		callback()
	})
})

gulp.task( 'default', [ 'mithril', 'webpack' ] )
<commit_msg>fixed demo gulp file<commit_after>'use strict'

let fs = require('fs')
let gulp = require('gulp'),
	webpack = require('webpack'),
	gutil = require('gulp-util')

let mithrilier = require('pug-mithrilier')

gulp.task('mithril', function ( cb ) {
	let folder = './m/'

	let jadeContent = fs.readFileSync( folder + 'Content.jade', { encoding: 'utf8' })
	mithrilier.generateMithrilJS( folder + 'Content.jade', jadeContent, null, null, function (err, mithrilView) {
		if ( err ) return cb(err)

		fs.writeFileSync( folder + 'Content.js', mithrilView.trim() + '\n', { encoding: 'utf8' } )
		cb()
	} )
})

let config = {
	cache: true,
	entry: './main.js',
	node: {
		fs: 'empty'
	},
	output: {
		path: './',
		filename: './www/main.js',
		publicPath: './'
	},
	module: {
		noParse: [
			/Gulpfile\.js$/, /.\.json$/, /.\.txt$/, /\.gitignore$/, /\.jshintrc$/
		]
	},
	plugins: [ ]
}
gulp.task('webpack', function ( callback ) {
	webpack( config, function (err, stats) {
		if (err) {
			throw new global.gutil.PluginError('webpack', err)
		}
		gutil.log('[webpack]', stats.toString({
			// output options
		}))
		callback()
	})
})

gulp.task( 'default', [ 'mithril', 'webpack' ] )
<|endoftext|>


<commit_before>/**
 * Created by rebel on 22/03/2017.
 */

const fs = require('fs');
const SettingsFile = require('./SettingsFile');
const Notifications = require('./Notifications');

function ChannelPlay() {
}

function launchPlayer(channelObj, LQ = null) {
    let channelLink = channelObj.link;

    launchPlayerLink(channelLink, LQ);
}

function launchPlayerLink(channelLink, LQ = null) {
    if (channelLink.indexOf('rtmp') != 0 && channelLink.indexOf('http') != 0)
        return;

    let settingsJson = new SettingsFile().returnSettings();

    let quality = 'best';

    if (LQ == null)
        LQ = settingsJson.settings.LQ;

    if (channelLink.startsWith("rtmp")) {
        channelLink += " live=1";

        if (LQ && channelLink.indexOf('klpq.men/live/') >= 0) {
            console.log('live to restream');
            channelLink = channelLink.replace('/live/', '/restream/');
        }
    } else {
        if (LQ)
            quality = 'high';
    }

    let path = settingsJson.settings.livestreamerPath;

    if (fs.existsSync(path)) {
        var child = require('child_process').execFile;

        console.log('launching player for ' + channelLink);

        child(path, [channelLink, quality], function (err, data) {
            //console.log(err);
            console.log(data);
            console.log('player was closed.');

            //new Notifications().printNotification('Player was Closed', channelLink);
        });
    } else {
        console.log(path + " not found.");
    }
}

ChannelPlay.prototype.launchPlayer = launchPlayer;
ChannelPlay.prototype.launchPlayerLink = launchPlayerLink;

module.exports = ChannelPlay;
<commit_msg>no message<commit_after>/**
 * Created by rebel on 22/03/2017.
 */

const fs = require('fs');
const SettingsFile = require('./SettingsFile');
const Notifications = require('./Notifications');

function ChannelPlay() {
}

function launchPlayer(channelObj, LQ = null) {
    let channelLink = channelObj.link;

    launchPlayerLink(channelLink, LQ);
}

function launchPlayerLink(channelLink, LQ = null) {
    if (channelLink.indexOf('rtmp') != 0 && channelLink.indexOf('http') != 0)
        return;

    const SettingsFile = require('./SettingsFile');
    let settingsJson = new SettingsFile().returnSettings();

    let quality = 'best';

    if (LQ == null)
        LQ = settingsJson.settings.LQ;

    if (channelLink.startsWith("rtmp")) {
        channelLink += " live=1";

        if (LQ && channelLink.indexOf('klpq.men/live/') >= 0) {
            console.log('live to restream');
            channelLink = channelLink.replace('/live/', '/restream/');
        }
    } else {
        if (LQ)
            quality = 'high';
    }

    let path = settingsJson.settings.livestreamerPath;

    if (fs.existsSync(path)) {
        var child = require('child_process').execFile;

        console.log('launching player for ' + channelLink);

        child(path, [channelLink, quality], function (err, data) {
            //console.log(err);
            console.log(data);
            console.log('player was closed.');

            //new Notifications().printNotification('Player was Closed', channelLink);
        });
    } else {
        console.log(path + " not found.");
    }
}

ChannelPlay.prototype.launchPlayer = launchPlayer;
ChannelPlay.prototype.launchPlayerLink = launchPlayerLink;

module.exports = ChannelPlay;
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var eventSchema = new Schema({
    title: String,
    description: String,
    startDate: Date,
    endDate: Date,
    deadline: Date,
    duration: String,
    participants: [String]
});

module.exports = mongoose.model('events', eventSchema);
<commit_msg>Change the schema of model.<commit_after>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var slotSchema = new Schema({
  startDate: { type: String, required: true },
  startTime: { type: String, required: true },
  duration:  { type: String, required: true }
});

var participantSchema = new Schema({
  name:       { type: String, required: true },
  facebookId: { type: String, required: true },
  slot:       [slotSchema]
});

var eventSchema = new Schema({
  title:        { type: String, trim: true, required: true },
  description:  { type: String, trim: true },
  startDate:    { type: String, required: true },
  endDate:      { type: String, required: true },
  deadline:     { type: String, required: true },
  duration:     { type: String, required: true },
  participants: { type: [participantSchema], required: true }
});

module.exports = mongoose.model('events', eventSchema);
<|endoftext|>