<commit_before>export default function nextHandler (nextApp) {
  return function ({ req, res, route, params }) {
    const pagePath = `/${route.action.replace('#', '/')}`
    const query = {
      params,
      action: route.action
    }

    if (route.isPage()) {
      return nextApp.render(req, res, pagePath, query)
    } else {
      return route.handler({ req, res, route, params })
    }
  }
}
<commit_msg>Whitespace<commit_after>export default function nextHandler (nextApp) {
  return function ({ req, res, route, params }) {
    const pagePath = `/${route.action.replace('#', '/')}`
    const query = { params, action: route.action }

    if (route.isPage()) {
      return nextApp.render(req, res, pagePath, query)
    } else {
      return route.handler({ req, res, route, params })
    }
  }
}
<|endoftext|>


<commit_before>import d3 from "d3"

var height=200,width=1200;

var viz=(stackdataArr,color2,bun,hatsugen,svg,checkedBun) => {
	console.log("func viz start");
	var m;
	var bunsuu=2;//前後の余白
	for(m=1;m<hatsugen.length;m=m+2){//患者の発言で間隔を作る
		if(m==hatsugen.length-1){
			bunsuu = bunsuu + hatsugen[m].length/2;
			break;
		}
		bunsuu = bunsuu + hatsugen[m].length;
	}
	console.log("bunsuu=%d",bunsuu);
	var nagasa=[];//縦棒の位置
	nagasa[0]=1*width/(bunsuu+1);
	for(m=1;m<=hatsugen.length;m=m+2){
		nagasa[(m+1)/2]=nagasa[-1 + (m+1)/2]+hatsugen[m].length*width/bunsuu;
	}
	console.log("nagasa");
	console.log(nagasa);

	var stack = d3.layout.stack()
	.x(function(d){return 1;})
	.y(function(d){return d.y;})
	.values(function(d){return d;});
	var stackdata = stack(stackdataArr);
	//var max = d3.max(stackdata[stackdata.length-1], function(d){return d.y + d.y0;});
	var scaleX = d3.scale.linear().domain([0,color2.length]).range([width/(color2.length),width]);
	var scaleY = d3.scale.linear().domain([0,6]).range([0,height]);
	var colors = ["#7777ff","#77ff77","#ff7777"];
	var colorBun=["dimgray","#ff7777","#77ff77","#7777ff"];

	var area = d3.svg.area()
	.x(function(d,i){return (nagasa[i]+nagasa[i+1])/2})
	.y0(function(d){return height})
	.y1(function(d){return height - scaleY(d.y+d.y0)});
	svg.selectAll("path")
	.data(stackdata.reverse())
	.enter()
	.append("path")
	.attr("d", area)
	.attr("fill",function(d,i){return colors[i]});

	var range = d3.range((width)-(width/(color2.length*2)), color2.length-1, -width/(color2.length));
	svg.selectAll("line.v")
	.data(range).enter().append("line")
	.attr("x1", function(d,i){
		console.log("i=%d",i);
		return nagasa[i];
	}).attr("y1", 0)//i=1から始まってる？←そんなことはなかった
	.attr("x2", function(d,i){return nagasa[i];}).attr("y2", height);
	svg.selectAll("line")
	.attr("stroke", function(d,i){return color2[i]})
	.attr("stroke-width", 3)
	.on('mouseover', function(d,i){
		var e = document.getElementById('msg');
		var k,l;
		e.innerHTML = "";
		for(k=-3;k<=3;k++){
			if(2*(i)+k<0||2*(i)+k>=hatsugen.length){
				console.log("%d,continue",2*i+k);
				continue;
			}
			if(k==0){
				e.innerHTML += ""+(1+2*i)+" "+hatsugen[2*i]+"
";
			}else if(k%2==0){
				e.innerHTML += ""+(1+k+2*i)+" "+hatsugen[k+2*i]+"
";
			}else{
				e.innerHTML += (1+k+2*i)+" ";
				for(l=0;l<bun[k+2*i].length;l++){
					e.innerHTML += ""+bun[k+2*i][l]+"";
				}
				e.innerHTML += "
";
			}
		}
	})
};

var funcChecked = (chboxlist,checked,taiou,chboxlength) => {
	console.log("funcChecked");
	var c;
	for(c=1;c<=chboxlength;c++){
		//console.log(document.getElementById(c));
		const radio = document.getElementById(c).children;
		console.log("radio");
		console.log(radio);
		console.log("radio.length=%d",radio.length);
		for(let i = 2, l = radio.length; i < l; i++){
			if(radio[i].control.checked==true){
				console.log("radio[%d].control.checked==true",i);
				if(radio[i].control.value=="1"){
					console.log("radio[%d].control.value==1",i);
					checked[taiou[c-1]] =1;
					break;
				}else if(radio[i].control.value=="2"){
					console.log("radio[%d].control.value==2",i);
					checked[taiou[c-1]] =2;
					break;
				}else if(radio[i].control.value=="3"){
					console.log("radio[%d].control.value==3",i);
					checked[taiou[c-1]] =3;
					break;
				}
			}else{
				checked[taiou[c-1]] =0;
			}
		}
	}
};

var funcChecked2 = (chboxlist,chboxlist2,checked2,taiou,chboxlength,chboxlength2) => {
	//console.log("funcChecked2");
	var c;
	//console.log(chboxlength2);
	for(c=chboxlength+1;c<=chboxlength+chboxlength2;c++){
		//console.log("c=%d",c);
		//console.log(document.getElementById(c-1+chboxlength));
		const radio = document.getElementById(c-1+chboxlength).children;
		//console.log(radio);
		//console.log("radio.length=%d",radio.length);
		for(let i = radio.length-3, l = radio.length; i < l; i++){
			if(radio[i].control.checked==true){
				if(radio[i].control.value=="6"){
					//console.log("radio[%d].control.value==6",i);
					checked2[taiou[c-1]] =6;
					break;
				}else if(radio[i].control.value=="7"){
					//console.log("radio[%d].control.value==7",i);
					checked2[taiou[c-1]] =7;
					break;
				}
			}else{
				checked2[taiou[c-1]] =4;
			}
		}
	}
};

var setForViz = (keitaisokaiseki,chboxlist,chboxlist2,RGBlist,hatsugen,bun,checked,checked2,taiou,chboxlength,chboxlength2) => {

	d3.select("#svgdiv").select("svg").remove();

	var svg = d3.select("#svgdiv").append("svg")
	.attr("height",height)
	.attr("width",width);

	console.log("setForViz");
	var color2=[];
	var stackdataArr = [];
	console.log("chboxlength=%d",chboxlength);
	if(chboxlength>=1){
		funcChecked(chboxlist,checked,taiou,chboxlength);
	}
	console.log("checked");
	console.log(checked);
	console.log("chboxlist");
	console.log(chboxlist);
	if(chboxlength2>=1){
		funcChecked2(chboxlist,chboxlist2,checked2,taiou,chboxlength,chboxlength2);
	}
	console.log("checked2");
	console.log(checked2);

	var h,i,j,c,m,n;

	//console.log(RGBlist);

	for(n=0;n<RGBlist.length;n++){
		RGBlist[n][0]=0;
		RGBlist[n][1]=0;
		RGBlist[n][2]=0;
	}

	var checkedBun=[];

	for(c=1;c<chboxlist.length;c++){

		n=0;
		for(m=1;m<keitaisokaiseki.length;m=m+2){
			checkedBun[m]=[];//svgでの描画ではm→i
			for(i=0;i<keitaisokaiseki[m].length;i++){
				//for(j=0;j<keitaisokaiseki[m][i].length;j++){
				checkedBun[m][i]=0;
				if(bun[m][i]==chboxlist[c][0]){
					if(checked[c-1]==1){
						RGBlist[n][0]=RGBlist[n][0]+1;
						checkedBun[m][i]=1;
					}else if(checked[c-1]==2){
						RGBlist[n][1]=RGBlist[n][1]+1;
						checkedBun[m][i]=2;
					}else if(checked[c-1]==3){
						RGBlist[n][2]=RGBlist[n][2]+1;
						checkedBun[m][i]=3;
					}
				}
				//}//j=0;j<keitaisokaiseki[m][i].length;j++
			}
			n++
		}
	}
	console.log("checkedBun");
	console.log(checkedBun);
	console.log("RGBlist");
	console.log(RGBlist);//←グラフにすなお

	for(c=0;c<checked2.length;c++){
		if(checked2[c]==3){
			color2[c]="#d4d";
		}else if(checked2[c]==5){
			color2[c]="yellow";
		}else if(checked2[c]==4){
			color2[c]="blue";
		}else if(checked2[c]==6){
			color2[c]="red";
		}else{
			color2[c]="silver";
		}
	}

	var RGBmax=[];
	var RGBmaxmax=1;

	console.log("color2");
	console.log(color2.length);

	for(m=0;m<((keitaisokaiseki.length-1)/2);m++){//2個飛ばしにしたら後が面倒くさい。患者 1→0　3→1 長さ9なら番号は8まで
		RGBmax[m]=1;
		for(h=0;h<3;h++){
			RGBmax[m]=RGBmax[m]+RGBlist[m][h];
		}
		if(RGBmaxmax<RGBmax[m]){
			RGBmaxmax=RGBmax[m];
		}
	}

	for(h=0;h<3;h++){
		stackdataArr[h] = [];
		for(m=0;m<((keitaisokaiseki.length-1)/2);m++){//2個飛ばしにしたら後が面倒くさい。患者 1→0　3→1 長さ9なら番号は8まで
			stackdataArr[h][m]=new Object();
			stackdataArr[h][m]= {x:m+1,y:(5*(RGBlist[m][h])/RGBmaxmax)};
			//console.log(stackdataArr[h][m]);
		}
	}

	console.log("stackdataArr");
	console.log(stackdataArr);
	console.log("color2");
	console.log(color2);
	console.log("checkedBun");
	console.log(checkedBun);
	viz(stackdataArr,color2,bun,hatsugen,svg,checkedBun);
	console.log("chboxlist2");
	console.log(chboxlist2);

	return{
		chboxlist:chboxlist,
		chboxlist2:chboxlist2,
		RGBlist:RGBlist,
		checked:checked,
		checked2:checked2,
		chboxlength:chboxlength,
		chboxlength2:chboxlength2
	}
}

export {setForViz};
<commit_msg>colored client's sentences<commit_after>import d3 from "d3"

var height=200,width=1200;

var viz=(stackdataArr,color2,bun,hatsugen,svg,checkedBun) => {
	console.log("func viz start");
	var m;
	var bunsuu=2;//前後の余白
	for(m=1;m<hatsugen.length;m=m+2){//患者の発言で間隔を作る
		if(m==hatsugen.length-1){
			bunsuu = bunsuu + hatsugen[m].length/2;
			break;
		}
		bunsuu = bunsuu + hatsugen[m].length;
	}
	console.log("bunsuu=%d",bunsuu);
	var nagasa=[];//縦棒の位置
	nagasa[0]=1*width/(bunsuu+1);
	for(m=1;m<=hatsugen.length;m=m+2){
		nagasa[(m+1)/2]=nagasa[-1 + (m+1)/2]+hatsugen[m].length*width/bunsuu;
	}
	console.log("nagasa");
	console.log(nagasa);

	var stack = d3.layout.stack()
	.x(function(d){return 1;})
	.y(function(d){return d.y;})
	.values(function(d){return d;});
	var stackdata = stack(stackdataArr);
	//var max = d3.max(stackdata[stackdata.length-1], function(d){return d.y + d.y0;});
	var scaleX = d3.scale.linear().domain([0,color2.length]).range([width/(color2.length),width]);
	var scaleY = d3.scale.linear().domain([0,6]).range([0,height]);
	var colors = ["#7777ff","#77ff77","#ff7777"];
	var colorBun=["dimgray","#ff7777","#77ff77","#7777ff"];

	var area = d3.svg.area()
	.x(function(d,i){return (nagasa[i]+nagasa[i+1])/2})
	.y0(function(d){return height})
	.y1(function(d){return height - scaleY(d.y+d.y0)});
	svg.selectAll("path")
	.data(stackdata.reverse())
	.enter()
	.append("path")
	.attr("d", area)
	.attr("fill",function(d,i){return colors[i]});

	var range = d3.range((width)-(width/(color2.length*2)), color2.length-1, -width/(color2.length));
	svg.selectAll("line.v")
	.data(range).enter().append("line")
	.attr("x1", function(d,i){
		console.log("i=%d",i);
		return nagasa[i];
	}).attr("y1", 0)//i=1から始まってる？←そんなことはなかった
	.attr("x2", function(d,i){return nagasa[i];}).attr("y2", height);
	svg.selectAll("line")
	.attr("stroke", function(d,i){return color2[i]})
	.attr("stroke-width", 3)
	.on('mouseover', function(d,i){
		var e = document.getElementById('msg');
		var k,l;
		e.innerHTML = "";
		for(k=-3;k<=3;k++){
			if(2*(i)+k<0||2*(i)+k>=hatsugen.length){
				console.log("%d,continue",2*i+k);
				continue;
			}
			if(k==0){
				e.innerHTML += ""+(1+2*i)+" "+hatsugen[2*i]+"
";
			}else if(k%2==0){
				e.innerHTML += ""+(1+k+2*i)+" "+hatsugen[k+2*i]+"
";
			}else{
				e.innerHTML += (1+k+2*i)+" ";
				for(l=0;l<bun[k+2*i].length;l++){
					e.innerHTML += ""+bun[k+2*i][l]+"";
				}
				e.innerHTML += "
";
			}
		}
	})
};

var funcChecked = (chboxlist,checked,taiou,chboxlength) => {
	console.log("funcChecked");
	var c;
	for(c=1;c<=chboxlength;c++){
		//console.log(document.getElementById(c));
		const radio = document.getElementById(c).children;
		console.log("radio");
		console.log(radio);
		console.log("radio.length=%d",radio.length);
		for(let i = 2, l = radio.length; i < l; i++){
			if(radio[i].control.checked==true){
				console.log("radio[%d].control.checked==true",i);
				if(radio[i].control.value=="1"){
					console.log("radio[%d].control.value==1",i);
					checked[taiou[c-1]] =1;
					break;
				}else if(radio[i].control.value=="2"){
					console.log("radio[%d].control.value==2",i);
					checked[taiou[c-1]] =2;
					break;
				}else if(radio[i].control.value=="3"){
					console.log("radio[%d].control.value==3",i);
					checked[taiou[c-1]] =3;
					break;
				}
			}else{
				checked[taiou[c-1]] =0;
			}
		}
	}
};

var funcChecked2 = (chboxlist,chboxlist2,checked2,taiou,chboxlength,chboxlength2) => {
	//console.log("funcChecked2");
	var c;
	//console.log(chboxlength2);
	for(c=chboxlength+1;c<=chboxlength+chboxlength2;c++){
		const radio = document.getElementById(c-1+chboxlength).children;
		for(let i = radio.length-3, l = radio.length; i < l; i++){
			if(radio[i].control.checked==true){
				if(radio[i].control.value=="6"){
					//console.log("radio[%d].control.value==6",i);
					checked2[taiou[c-1]] =6;
					break;
				}else if(radio[i].control.value=="7"){
					//console.log("radio[%d].control.value==7",i);
					checked2[taiou[c-1]] =7;
					break;
				}
			}else{
				checked2[taiou[c-1]] =4;
			}
		}
	}
};

var setForViz = (keitaisokaiseki,chboxlist,chboxlist2,RGBlist,hatsugen,bun,checked,checked2,taiou,chboxlength,chboxlength2) => {

	d3.select("#svgdiv").select("svg").remove();

	var svg = d3.select("#svgdiv").append("svg")
	.attr("height",height)
	.attr("width",width);

	console.log("setForViz");
	var color2=[];
	var stackdataArr = [];
	console.log("chboxlength=%d",chboxlength);
	if(chboxlength>=1){
		funcChecked(chboxlist,checked,taiou,chboxlength);
	}
	console.log("checked");
	console.log(checked);
	console.log("chboxlist");
	console.log(chboxlist);
	if(chboxlength2>=1){
		funcChecked2(chboxlist,chboxlist2,checked2,taiou,chboxlength,chboxlength2);
	}
	//console.log("checked2");
	//console.log(checked2);

	var h,i,j,c,m,n;

	for(n=0;n<RGBlist.length;n++){
		RGBlist[n][0]=0;
		RGBlist[n][1]=0;
		RGBlist[n][2]=0;
	}

	var checkedBun=[];

	n=0;//m=1;m<keitaisokaiseki.length;m=m+2の外
	for(m=1;m<keitaisokaiseki.length;m=m+2){
		checkedBun[m]=[];//svgでの描画ではm→i
		for(i=0;i<keitaisokaiseki[m].length;i++){
			checkedBun[m][i]=0;
			for(c=1;c<chboxlist.length;c++){
				if(bun[m][i]==chboxlist[c][0]){
					if(checked[c-1]==1){
						RGBlist[n][0]=RGBlist[n][0]+1;
						checkedBun[m][i]=1;
						console.log("%d,%d,「%s」は「愛」",m,i,bun[m][i]);
					}else if(checked[c-1]==2){
						RGBlist[n][1]=RGBlist[n][1]+1;
						checkedBun[m][i]=2;
						console.log("%d,%d,「%s」は「交友」",m,i,bun[m][i]);
					}else if(checked[c-1]==3){
						RGBlist[n][2]=RGBlist[n][2]+1;
						checkedBun[m][i]=3;
						console.log("%d,%d,「%s」は「仕事」",m,i,bun[m][i]);
					}
				}
			}//c=1;c<chboxlist.length;c++
		}//i=0;i<keitaisokaiseki[m].length;i++
		n++
	}//m=1;m<keitaisokaiseki.length;m=m+2

	console.log("checkedBun");
	console.log(checkedBun);
	//console.log("RGBlist");
	//console.log(RGBlist);//←グラフにすなお

	for(c=0;c<checked2.length;c++){
		if(checked2[c]==3){
			color2[c]="#d4d";
		}else if(checked2[c]==5){
			color2[c]="yellow";
		}else if(checked2[c]==4){
			color2[c]="blue";
		}else if(checked2[c]==6){
			color2[c]="red";
		}else{
			color2[c]="silver";
		}
	}

	var RGBmax=[];
	var RGBmaxmax=1;

	//console.log("color2");
	//console.log(color2.length);

	for(m=0;m<((keitaisokaiseki.length-1)/2);m++){//2個飛ばしにしたら後が面倒くさい。患者 1→0　3→1 長さ9なら番号は8まで
		RGBmax[m]=1;
		for(h=0;h<3;h++){
			RGBmax[m]=RGBmax[m]+RGBlist[m][h];
		}
		if(RGBmaxmax<RGBmax[m]){
			RGBmaxmax=RGBmax[m];
		}
	}

	for(h=0;h<3;h++){
		stackdataArr[h] = [];
		for(m=0;m<((keitaisokaiseki.length-1)/2);m++){//2個飛ばしにしたら後が面倒くさい。患者 1→0　3→1 長さ9なら番号は8まで
			stackdataArr[h][m]=new Object();
			stackdataArr[h][m]= {x:m+1,y:(5*(RGBlist[m][h])/RGBmaxmax)};
		}
	}

	//	console.log("stackdataArr");
	//console.log(stackdataArr);
	//console.log("color2");
	//console.log(color2);
	console.log("checkedBun");
	console.log(checkedBun);
	viz(stackdataArr,color2,bun,hatsugen,svg,checkedBun);
	//console.log("chboxlist2");
	//console.log(chboxlist2);

	return{
		chboxlist:chboxlist,
		chboxlist2:chboxlist2,
		RGBlist:RGBlist,
		checked:checked,
		checked2:checked2,
		chboxlength:chboxlength,
		chboxlength2:chboxlength2
	}
}

export {setForViz};
<|endoftext|>


<commit_before>var express = require('express');
var User = require('../schemas/userSchema.js');

var app = express();

app.get('/users', function (req, res, next) {
  if (req.isAuthenticated()) {
    res.json({
      "users": [req.user]
    });
  } else {
    res.json({
      "users": [{
        _id: "anonymous user"
      }]
    })
  }
});

app.put('/users/:id', function (req, res, next) {
  if (!req.isAuthenticated()) {
    res.send(401, 'You must be logged in to join a project');
  }

  User.findById(req.params.id).exec().then(function (user) {
    user.projects = req.body.user.projects;
    user.save();

    res.json({
      "user": user
    });
  }, next);
});

module.exports = app;<commit_msg>Add isAnonymous property to anonymous user<commit_after>var express = require('express');
var User = require('../schemas/userSchema.js');

var app = express();

app.get('/users', function (req, res, next) {
  if (req.isAuthenticated()) {
    res.json({
      "users": [req.user]
    });
  } else {
    res.json({
      "users": [{
        _id: "anonymous user",
        isAnonymous: true
      }]
    })
  }
});

app.put('/users/:id', function (req, res, next) {
  if (!req.isAuthenticated()) {
    res.send(401, 'You must be logged in to join a project');
  }

  User.findById(req.params.id).exec().then(function (user) {
    user.projects = req.body.user.projects;
    user.save();

    res.json({
      "user": user
    });
  }, next);
});

module.exports = app;<|endoftext|>


<commit_before>var winston = require('winston');

module.exports = function(ceres) {
  var master = require('./master');
  var child = require('./child');

  // Ensure secret is present
  if (!ceres.config.secret) {
    console.error('Unable to find secret.');
    process.exit();
  }

  if (ceres.config.env === 'production') {
    // Save uncaught exceptions to their own file in production
    winston.handleExceptions(new winston.transports.DailyRotateFile({
      filename: ceres.config.folders.logs + '/exceptions.log',
      tailable: true
    }));
  }

  // Setup logging app
  ceres.log = require('./setup/logs')(ceres.config);
  // Setup internal framework logger so we can tell if its an app or framework erro
  ceres.log._ceres = require('./setup/logs')(ceres.config, 'ceres');

  if (ceres.config.instances && ceres.config.instances > 1) {
    ceres.log._ceres.silly('Starting cluster with %d workers', ceres.config.instances);
    // Clustering
    var cluster = require('cluster');

    if (cluster.isMaster) {
      master.call(ceres, ceres);
    } else {
      child.call(ceres, ceres);
    }
  } else {
    ceres.log._ceres.silly('Starting a single instance');

    // Single Instance
    child.call(ceres, ceres);
  }
};
<commit_msg>Moved imports to top level of run<commit_after>var winston = require('winston');
var master = require('./master');
var child = require('./child');
var cluster = require('cluster');

module.exports = function(ceres) {
  // Ensure secret is present
  if (!ceres.config.secret) {
    console.error('Unable to find secret.');
    process.exit();
  }

  if (ceres.config.env === 'production') {
    // Save uncaught exceptions to their own file in production
    winston.handleExceptions(new winston.transports.DailyRotateFile({
      filename: ceres.config.folders.logs + '/exceptions.log',
      tailable: true
    }));
  }

  // Setup logging app
  ceres.log = require('./setup/logs')(ceres.config);
  // Setup internal framework logger so we can tell if its an app or framework erro
  ceres.log._ceres = require('./setup/logs')(ceres.config, 'ceres');

  if (ceres.config.instances && ceres.config.instances > 1) {
    ceres.log._ceres.silly('Starting cluster with %d workers', ceres.config.instances);

    if (cluster.isMaster) {
      master.call(ceres, ceres);
    } else {
      child.call(ceres, ceres);
    }
  } else {
    ceres.log._ceres.silly('Starting a single instance');

    // Single Instance
    child.call(ceres, ceres);
  }
};
<|endoftext|>


<commit_before>'use strict';

import mongoose from 'mongoose';
const genders = 'Neutrois Male Female Bigender None'.split(' ');

/**
 * Mongoose schema of user profile.
 *
 */
const profileSchema = new mongoose.Schema({
  username: { type: String, unique: true, required: '{PATH} is required' },
  avatar: { type: String, default: 'style/core/images/users/default.png' },
  banner: { type: String, default: null },
  tagline: { type: String, default: null },
  gender: { type: String, enum: genders, default: 'None' },
  dob: { type: Date },
  tokenLive: { type: String, default: '24h' },
  lastLogin: { type: Date, default: Date.now },
  lastOnline: { type: Date, default: Date.now },
});

mongoose.model('Profile', profileSchema);
<commit_msg>added method for generating default avatar<commit_after>'use strict';

import mongoose from 'mongoose';
const genders = 'Neutrois Male Female Bigender None'.split(' ');

/**
 * Mongoose schema of user profile.
 *
 */
const profileSchema = new mongoose.Schema({
  username: { type: String, unique: true, required: '{PATH} is required' },
  avatar: { type: String, default: null },
  banner: { type: String, default: null },
  tagline: { type: String, default: null },
  gender: { type: String, enum: genders, default: 'None' },
  dob: { type: Date },
  tokenLive: { type: String, default: '24h' },
  lastLogin: { type: Date, default: Date.now },
  lastOnline: { type: Date, default: Date.now },
});

profileSchema.methods.generateAvatar = function (username) {
  const colors = ['5600FF', '0CDBE8', '5EFF00', 'E8A408', 'FF190D'];
  let size = 512;
  let meta = 'data:image/svg+xml;base64,';
  let svg = `<svg xmlns="http://www.w3.org/2000/svg" height="${size}" width="${size}">
              <circle cx="${size/2}" cy="${size/2}" r="${size/2}" fill="#${colors[Math.floor(Math.random() * 5)]}"/>
              <text x="50%" y="50%" dy="180px" style="
                font-family: Arial Black;
                font-size: ${size}px;
                fill: white;"
              text-anchor="middle">${username[0].toUpperCase()}</text>
            </svg>`;
  this.avatar = meta + new Buffer(svg).toString('base64');
  return this.save();
};

mongoose.model('Profile', profileSchema);
<|endoftext|>


<commit_before>$(function () {
    $p.apply = function () {
        $('.menu').menu();
        $('#EditorTabsContainer:not(.applied),#MailEditorTabsContainer:not(.applied),#ViewTabsContainer:not(.applied)').tabs({
            beforeActivate: function (event, ui) {
                if (ui.newPanel.attr('data-action')) {
                    $p.send(ui.newPanel);
                }
            }
        }).addClass('applied');
        $('.button-icon:not(.applied)').each(function () {
            var $control = $(this);
            var icon = $control.attr('data-icon');
            $control.button({ icon: icon });
        }).addClass('applied');
        $('select[multiple]:not(.applied)').multiselect({
            selectedList: 100,
            checkAllText: $p.display('CheckAll'),
            uncheckAllText: $p.display('UncheckAll'),
            noneSelectedText: '',
            beforeopen: function (){
                if ($(this).hasClass('search')) {
                    $p.openDropDownSearchDialog($(this));
                    return false;
                }
            },
            click: function () {
                $p.changeMultiSelect($(this))
            },
            checkAll: function () {
                $p.changeMultiSelect($(this))
            },
            uncheckAll: function () {
                $p.changeMultiSelect($(this))
            }
        }).addClass('applied');
        $('.datepicker:not(.applied)').datepicker({
            showButtonPanel: true,
            onSelect: function (date) {
                $p.getData($(this))[this.id] = date;
            }
        }).addClass('applied');
        $('.radio:not(.applied)').buttonset().addClass('applied');
        $('.control-selectable:not(.applied)').selectable({
            stop: function () {
                $p.onSelectableSelected($(this));
            }
        }).addClass('applied');
        $('.control-slider-ui').each(function () {
            var $control = $('#' + $(this).attr('id').split(',')[0]);
            $(this).slider({
                min: parseFloat($(this).attr('data-min')),
                max: parseFloat($(this).attr('data-max')),
                step: parseFloat($(this).attr('data-step')),
                value: parseFloat($control.text()),
                slide: function (event, ui) {
                    $control.text(ui.value);
                    $p.setData($control);
                }
            });
        });
        $('.control-spinner:not(.applied)').each(function () {
            var $control = $(this);
            $control.spinner({
                min: $control.attr('data-min'),
                max: $control.attr('data-max'),
                step: $control.attr('data-step')
            }).css('width', function () {
                return $control.attr('data-width');
            });
            $control.addClass('applied');
        });
        $('[class*="enclosed"] .legend:not(.applied)').each(function (e) {
            var $control = $(this);
            if ($control.find('[class^="ui-icon ui-icon-triangle-1-"]').length === 0) {
                $control.prepend($('<span/>').addClass('ui-icon ui-icon-triangle-1-s'));
            }
            $control.addClass('applied');
        });
        $('.status:not(.applied)').each(function () {
            var $control = $(this);
            $control
                .addClass($control.find('option:selected').attr('data-class'))
                .addClass('applied');
        });
        $('.control-markdown:not(.applied)').each(function () {
            var $control = $(this);
            var $viewer = $('[id="' + this.id + '.viewer"]');
            $viewer.html($p.markup($control.val()));
            $control.addClass('applied');
        });
        $('.markup:not(.applied)').each(function () {
            var $control = $(this);
            $control.html($p.markup($control.html(), true));
            $control.addClass('applied');
        });
    }
    $p.apply();
});<commit_msg>Refactored: データセット用のメソッドを共通メソッドに変更。<commit_after>$(function () {
    $p.apply = function () {
        $('.menu').menu();
        $('#EditorTabsContainer:not(.applied),#MailEditorTabsContainer:not(.applied),#ViewTabsContainer:not(.applied)').tabs({
            beforeActivate: function (event, ui) {
                if (ui.newPanel.attr('data-action')) {
                    $p.send(ui.newPanel);
                }
            }
        }).addClass('applied');
        $('.button-icon:not(.applied)').each(function () {
            var $control = $(this);
            var icon = $control.attr('data-icon');
            $control.button({ icon: icon });
        }).addClass('applied');
        $('select[multiple]:not(.applied)').multiselect({
            selectedList: 100,
            checkAllText: $p.display('CheckAll'),
            uncheckAllText: $p.display('UncheckAll'),
            noneSelectedText: '',
            beforeopen: function (){
                if ($(this).hasClass('search')) {
                    $p.openDropDownSearchDialog($(this));
                    return false;
                }
            },
            click: function () {
                $p.changeMultiSelect($(this))
            },
            checkAll: function () {
                $p.changeMultiSelect($(this))
            },
            uncheckAll: function () {
                $p.changeMultiSelect($(this))
            }
        }).addClass('applied');
        $('.datepicker:not(.applied)').datepicker({
            showButtonPanel: true,
            onSelect: function (date) {
                $p.getData($(this))[this.id] = date;
            }
        }).addClass('applied');
        $('.radio:not(.applied)').buttonset().addClass('applied');
        $('.control-selectable:not(.applied)').selectable({
            stop: function () {
                $p.setData($(this));
            }
        }).addClass('applied');
        $('.control-slider-ui').each(function () {
            var $control = $('#' + $(this).attr('id').split(',')[0]);
            $(this).slider({
                min: parseFloat($(this).attr('data-min')),
                max: parseFloat($(this).attr('data-max')),
                step: parseFloat($(this).attr('data-step')),
                value: parseFloat($control.text()),
                slide: function (event, ui) {
                    $control.text(ui.value);
                    $p.setData($control);
                }
            });
        });
        $('.control-spinner:not(.applied)').each(function () {
            var $control = $(this);
            $control.spinner({
                min: $control.attr('data-min'),
                max: $control.attr('data-max'),
                step: $control.attr('data-step')
            }).css('width', function () {
                return $control.attr('data-width');
            });
            $control.addClass('applied');
        });
        $('[class*="enclosed"] .legend:not(.applied)').each(function (e) {
            var $control = $(this);
            if ($control.find('[class^="ui-icon ui-icon-triangle-1-"]').length === 0) {
                $control.prepend($('<span/>').addClass('ui-icon ui-icon-triangle-1-s'));
            }
            $control.addClass('applied');
        });
        $('.status:not(.applied)').each(function () {
            var $control = $(this);
            $control
                .addClass($control.find('option:selected').attr('data-class'))
                .addClass('applied');
        });
        $('.control-markdown:not(.applied)').each(function () {
            var $control = $(this);
            var $viewer = $('[id="' + this.id + '.viewer"]');
            $viewer.html($p.markup($control.val()));
            $control.addClass('applied');
        });
        $('.markup:not(.applied)').each(function () {
            var $control = $(this);
            $control.html($p.markup($control.html(), true));
            $control.addClass('applied');
        });
    }
    $p.apply();
});<|endoftext|>


<commit_before>import models from '../models';

const Message = models.Message;

module.exports = {
  create(req, res) {
    Message.sync({ force: false }).then(() => {
      Message
        .create({
          content: req.body.content,
          userId: 1,
          groupId: req.params.groupid,
        })
        .then(text => res.status(201).send(text))
        .catch(error => res.status(400).send(error));
    });
  }
};
<commit_msg>Edit the catch block<commit_after>import models from '../models';

const Message = models.Message;

module.exports = {
  create(req, res) {
    Message.sync({ force: false }).then(() => {
      Message
        .create({
          content: req.body.content,
          userId: 1,
          groupId: req.params.groupid,
        })
        .then(text => res.status(201).send(text))
        .catch(error => {
          console.log(error.message);
          res.status(400).send(error);
        })
    });
  }
};
<|endoftext|>


<commit_before>export var i18n = {
    PanelTitle: {
        en: "Sign Up",
        pt: "Registe-se"
    },
    AgreementText: {
        en: "By signing up you are agreeing to our terms of service and privacy policy.",
        pt: "Ao fazer este registo está a concordar com os nossos termos de serviço e política de privacidade."
    },
    SignUpButton: {
        en: "Sign Up",
        pt: "Registar"
    },
    SignInButton: {
        en: "Sign In",
        pt: "Entrar"
    },
    TextBetweenButtons: {
        en:"or",
        pt: "ou"
    },
    ConfirmationMessage: {
        en: "
Thank you for signing up

In a few moments you will receive an email with a confirmation link.

Please confirm your account by clicking that link.
",
        pt: "
Obrigado pelo seu registo

Dentro de alguns instantes receberá um mail com um link de confirmação.

Por favor confirme a sua conta clicando nesse link.
"
    }
};
<commit_msg>update<commit_after>export var i18n = {
    PanelTitle: {
        en: "Sign Up",
        pt: "Registe-se"
    },
    AgreementText: {
        en: "By signing up you are agreeing to our terms of service and privacy policy.",
        pt: "Ao fazer este registo está a concordar com os nossos termos de serviço e política de privacidade."
    },
    SignUpButton: {
        en: "Sign Up",
        pt: "Registar"
    },
    SignInButton: {
        en: "Sign In",
        pt: "Entrar"
    },
    TextBetweenButtons: {
        en:"or",
        pt: "ou"
    },
    ConfirmationMessage: {
        en: "
Thank you

In a few moments you will receive an email with a confirmation link.

Please confirm your account by clicking that link.
",
        pt: "
Obrigado

Dentro de alguns instantes receberá um mail com um link de confirmação.

Por favor confirme a sua conta clicando nesse link.
"
    }
};
<|endoftext|>


<commit_before>// jazz.js

var chord = require('./chord');
var note = require('./note');
var interval = require('./interval');
var _ = require('underscore');

// Map for roman numerals
var romanNumeral = [null, 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII'];

// Map for Mehegan qualities
var meheganQuality = [null, 'M', 'm', 'm', 'M', 'x', 'm', 'ø'];

var tonicChords = [
  'IM', 'Im', 'Ix', 'Iø',
  'IIIM', 'IIIm', 'IIIx', 'IIIø',
  'bIIIM', 'bIIIm', 'bIIIx', 'bIIIø',
  'VIM', 'VIm', 'VIx', 'VIø',
  'bVIM', 'bVIm', 'bVIx', 'bVIø',
];
var subdominantChords = [
  'IIM', 'IIm', 'IIx', 'IIø',
  'IVM', 'IVm', 'IVx', 'IVø',
  'VIM', 'VIm', 'VIx', 'VIø',
  'bVIM', 'bVIm', 'bVIx', 'bVIø'
];
var dominantChords = ['IIIx', 'bIIIx', 'Vx', 'VIIx', 'bVIIx'];

// Given a chord, return the Mehegan quality
var getQuality = function (ch) {
  if (ch.hasInterval('M3')) {
    return ch.hasInterval('m7') ? 'x' : 'M';
  }

  if (ch.hasInterval('m3')) {
    if (ch.hasInterval('dim5')) {
      return ch.hasInterval('m7') ? 'ø' : 'o';
    }

    return 'm';
  }

  return null;
};

// Given a key and a note, return a roman numeral representing the note
var getNumeral = function (key, n) {
  var int;
  var numeral;

  try {
    int = key.getInterval(n);
  } catch (err) {
    int = key.getInterval(n.clean());
  }

  // Although dim7, for example, is a valid interval, we don't want a bbVII in our symbol
  if (!interval.isPerfect(int.number) && int.quality === 'dim') {
    int = interval.parse((int.number - 1).toString());
  }

  numeral = romanNumeral[int.number];

  if (int.quality === 'm' || int.quality === 'dim') numeral = 'b' + numeral;
  if (int.quality === 'aug') numeral = '#' + numeral;

  return numeral;
};

// Given a roman numeral, return the number of half steps
var getHalfSteps = function (numeral) {
  var matches = numeral.match(/([b#]?)([iIvV]+)/);
  var halfSteps = interval.parse(_.indexOf(romanNumeral, matches[2]).toString()).halfSteps();

  if (matches[1] === 'b') halfSteps -= 1;
  if (matches[1] === '#') halfSteps += 1;

  return halfSteps;
};

// Given a roman numeral, infer the Mehegan chord qualitiy
var inferQuality = function (numeral) {
  return meheganQuality[_.indexOf(romanNumeral, numeral)];
};

// A symbol that is used in the jazz automaton.  Each symbol can be thought of as a roman numeral
// representing a chord using the Mehegan system.
var Symbol = function (numeral, quality) {
  // Roman numeral representing chord
  this.numeral = numeral;

  // Chord quality: M, m, x, o, ø
  this.quality = quality;
  if (!_.contains(['M', 'm', 'x', 'o', 'ø'], quality)) {
    throw new Error('Invalid chord quality');
  }

  // The number of half-steps between the key and the chord
  // e.g. I => 0, bIV => 6
  this.interval = getHalfSteps(numeral);

  this.toString = function () {
    return this.numeral + this.quality;
  };
};

// Create a symbol given a key and a chord
var symbolFromChord = function (key, ch) {
  key = note.create(key);
  ch = chord.create(ch);

  return new Symbol(getNumeral(key, ch.root), getQuality(ch));
};

// Create a symbol given a Mehegan chord
var symbolFromMehegan = function (mehegan) {
  var matches = mehegan.match(/([b#]?)([iIvV]+)([mMxoø]?)/);
  var alteration;
  var numeral;
  var quality;

  if (!matches) {
    throw new Error('Invalid Mehegan symbol');
  }

  alteration = matches[1];
  numeral = matches[2].toUpperCase();
  quality = matches[3];

  if (!quality) quality = inferQuality(numeral);

  return new Symbol(alteration + numeral, quality);
};

// Test for equality with other symbols
Symbol.prototype.eq = function (symbol) {
  return this.interval === symbol.interval && this.quality === symbol.quality;
};

// Return the corresponding interval, e.g., bIII -> m3
Symbol.prototype.toInterval = function () {
  var matches = this.numeral.match(/([b#]?)([iIvV]+)/);
  var alteration = matches[1];
  var numeral = matches[2];
  var intervalNumber = _.indexOf(romanNumeral, numeral);

  var intervalQuality = interval.isPerfect(intervalNumber) ? 'P' : 'M';

  if (alteration === 'b') {
    intervalQuality = interval.isPerfect(intervalNumber) ? 'dim' : 'm';
  }
  if (alteration === '#') {
    intervalQuality = 'aug';
  }

  return interval.create(intervalNumber, intervalQuality);
};

// Return a new symbol transposed by the given interval
Symbol.prototype.transpose = function (interval, down) {
  var n = note.create('C').transpose(this.toInterval()).transpose(interval, down);
  return new Symbol(getNumeral(note.create('C'), n), this.quality);
};

Symbol.prototype.transposeDown = _.partial(Symbol.prototype.transpose, _, true);

var JzState = function (name) {
  this.name = name;
  this.transitions = [];
  this.sources = [];
};

JzState.prototype.addTransition = function (symbol, state) {
  // Don't add transition if equivalent one already exists
  if (!_.some(this.transitions, function (t) {
    return t.symbol.eq(symbol) && t.state === state;
  })) {
    this.transitions.push({symbol: symbol, state: state});
    state.sources.push({symbol: symbol, state: this});
  }
};

JzState.prototype.addSource = function (symbol, state) {
  // Don't add source if equivalent one already exists
  if (!_.some(this.sources, function (s) {
    return s.symbol.eq(symbol) && s.state === state;
  })) {
    this.sources.push({symbol: symbol, state: state});
    state.transitions.push({symbol: symbol, state: this});
  }
};

JzState.prototype.hasTransition = function (symbol, state) {
  return _.some(this.transitions, function (transition) {
    return transition.symbol.eq(symbol) && transition.state === state;
  });
};

JzState.prototype.hasSource = function (symbol, state) {
  return _.some(this.sources, function (source) {
    return source.symbol.eq(symbol) && source.state === state;
  });
};

JzState.prototype.getTransitionStatesBySymbol = function (symbol) {
  return _.chain(this.transitions)
    .filter(function (transition) {
      return transition.symbol.eq(symbol);
    })
    .pluck('state')
    .value();
};

JzState.prototype.getSourceStatesBySymbol = function (symbol) {
  return _.chain(this.sources)
    .filter(function (source) {
      return source.symbol.eq(symbol);
    })
    .pluck('state')
    .value();
};

var JzA = function () {
  this.states = [];
};

JzA.prototype.addState = function (name) {
  var state = new JzState(name);
  this.states.push(state);
  return state;
};

JzA.prototype.addTransition = function (symbol, from, to) {
  from.addTransition(symbol, to);
};

JzA.prototype.getTransitions = function () {
  return _.chain(this.states)
  .map(function (state) {
    return _.map(state.transitions, function (transition) {
      return {symbol: transition.symbol, from: state, to: transition.state};
    });
  })
  .flatten()
  .value();
};

JzA.prototype.getTransitionsBySymbol = function (symbol) {
  return _.filter(this.getTransitions(), function (t) {
    return t.symbol.eq(symbol);
  });
};

JzA.prototype.getStatesByName = function (name) {
  return _.filter(this.states, function (state) {
    return state.name.toLowerCase() === name.toLowerCase();
  });
};

JzA.prototype.getStateByName = function (name) {
  return _.first(this.getStatesByName(name));
};

JzA.prototype.analyze = function (symbols) {
  // We are going to keep track of all possible pathways through the automaton
  // Since any state can be an "initial" state, start by finding all transitions for the first symbol
  var pathways = _.chain(this.getTransitionsBySymbol(_.first(symbols)))
    .map(function (transition) {
      return transition.to;
    })
    .uniq() // Eliminate duplicate first states
    .map(function (state) { // Do this after the elimination because [x] !== [x]
      return [state];
    })
    .value();
  var oldPathways;
  var nextStates;

  // With each symbol, we will construct a new list of valid pathways and then iterate
  // With each iteration, some pathways will be eliminated and others may split into multiple possibilities
  _.each(_.rest(symbols), function (symbol) {
    oldPathways = pathways;
    pathways = [];

    _.each(oldPathways, function (pathway) {
      nextStates = _.last(pathway).getTransitionStatesBySymbol(symbol);

      // If we're at a dead end, don't add this pathway
      // Otherwise, add all possible pathways we can take
      if (nextStates.length) {
        _.each(nextStates, function (nextState) {
          pathways.push(pathway.concat([nextState]));
        });
      }
    });
  });

  return pathways;
};

JzA.prototype.validate = function (symbols) {
  return this.analyze(symbols).length > 0;
};

var addPrimitiveChords = function (tonic, subdominant, dominant) {
  _.each(tonicChords, function (sym) {
    dominant.addTransition(symbolFromMehegan(sym), tonic);
    tonic.addTransition(symbolFromMehegan(sym), tonic);
  });

  _.each(subdominantChords, function (sym) {
    tonic.addTransition(symbolFromMehegan(sym), subdominant);
    subdominant.addTransition(symbolFromMehegan(sym), subdominant);
  });

  _.each(dominantChords, function (sym) {
    subdominant.addTransition(symbolFromMehegan(sym), dominant);
    dominant.addTransition(symbolFromMehegan(sym), dominant);
  });
};

var addTritoneSubstitutions = function (jza) {
  var dominantSevenths = _.filter(jza.getTransitions(), function (t) {
    return t.symbol.quality === 'x';
  });

  // For each dominant seventh transition, add another transition with its tritone sub
  _.each(dominantSevenths, function (t) {
    jza.addTransition(t.symbol.transpose('dim5'), t.from, t.to);
  });
};

var constructDefaultJzA = function (jza) {
  var tonic = jza.addState('Tonic');
  var subdominant = jza.addState('Subdominant');
  var dominant = jza.addState('Dominant');

  addPrimitiveChords(tonic, subdominant, dominant);
  addTritoneSubstitutions(jza);

  return jza;
};

module.exports.symbolFromChord = symbolFromChord;
module.exports.symbolFromMehegan = symbolFromMehegan;
module.exports.symbolsFromChord = _.partial(_.map, _, symbolFromChord);
module.exports.symbolsFromMehegan = _.partial(_.map, _, symbolFromMehegan);

module.exports.jza = function (type) {
  var jza = new JzA();

  if (type !== 'empty') {
    constructDefaultJzA(jza);
  }

  return jza;
};
<commit_msg>Consolidated transition/source methods with helper functions<commit_after>// jazz.js

var chord = require('./chord');
var note = require('./note');
var interval = require('./interval');
var _ = require('underscore');

// Map for roman numerals
var romanNumeral = [null, 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII'];

// Map for Mehegan qualities
var meheganQuality = [null, 'M', 'm', 'm', 'M', 'x', 'm', 'ø'];

var tonicChords = [
  'IM', 'Im', 'Ix', 'Iø',
  'IIIM', 'IIIm', 'IIIx', 'IIIø',
  'bIIIM', 'bIIIm', 'bIIIx', 'bIIIø',
  'VIM', 'VIm', 'VIx', 'VIø',
  'bVIM', 'bVIm', 'bVIx', 'bVIø',
];
var subdominantChords = [
  'IIM', 'IIm', 'IIx', 'IIø',
  'IVM', 'IVm', 'IVx', 'IVø',
  'VIM', 'VIm', 'VIx', 'VIø',
  'bVIM', 'bVIm', 'bVIx', 'bVIø'
];
var dominantChords = ['IIIx', 'bIIIx', 'Vx', 'VIIx', 'bVIIx'];

// Given a chord, return the Mehegan quality
var getQuality = function (ch) {
  if (ch.hasInterval('M3')) {
    return ch.hasInterval('m7') ? 'x' : 'M';
  }

  if (ch.hasInterval('m3')) {
    if (ch.hasInterval('dim5')) {
      return ch.hasInterval('m7') ? 'ø' : 'o';
    }

    return 'm';
  }

  return null;
};

// Given a key and a note, return a roman numeral representing the note
var getNumeral = function (key, n) {
  var int;
  var numeral;

  try {
    int = key.getInterval(n);
  } catch (err) {
    int = key.getInterval(n.clean());
  }

  // Although dim7, for example, is a valid interval, we don't want a bbVII in our symbol
  if (!interval.isPerfect(int.number) && int.quality === 'dim') {
    int = interval.parse((int.number - 1).toString());
  }

  numeral = romanNumeral[int.number];

  if (int.quality === 'm' || int.quality === 'dim') numeral = 'b' + numeral;
  if (int.quality === 'aug') numeral = '#' + numeral;

  return numeral;
};

// Given a roman numeral, return the number of half steps
var getHalfSteps = function (numeral) {
  var matches = numeral.match(/([b#]?)([iIvV]+)/);
  var halfSteps = interval.parse(_.indexOf(romanNumeral, matches[2]).toString()).halfSteps();

  if (matches[1] === 'b') halfSteps -= 1;
  if (matches[1] === '#') halfSteps += 1;

  return halfSteps;
};

// Given a roman numeral, infer the Mehegan chord qualitiy
var inferQuality = function (numeral) {
  return meheganQuality[_.indexOf(romanNumeral, numeral)];
};

// A symbol that is used in the jazz automaton.  Each symbol can be thought of as a roman numeral
// representing a chord using the Mehegan system.
var Symbol = function (numeral, quality) {
  // Roman numeral representing chord
  this.numeral = numeral;

  // Chord quality: M, m, x, o, ø
  this.quality = quality;
  if (!_.contains(['M', 'm', 'x', 'o', 'ø'], quality)) {
    throw new Error('Invalid chord quality');
  }

  // The number of half-steps between the key and the chord
  // e.g. I => 0, bIV => 6
  this.interval = getHalfSteps(numeral);

  this.toString = function () {
    return this.numeral + this.quality;
  };
};

// Create a symbol given a key and a chord
var symbolFromChord = function (key, ch) {
  key = note.create(key);
  ch = chord.create(ch);

  return new Symbol(getNumeral(key, ch.root), getQuality(ch));
};

// Create a symbol given a Mehegan chord
var symbolFromMehegan = function (mehegan) {
  var matches = mehegan.match(/([b#]?)([iIvV]+)([mMxoø]?)/);
  var alteration;
  var numeral;
  var quality;

  if (!matches) {
    throw new Error('Invalid Mehegan symbol');
  }

  alteration = matches[1];
  numeral = matches[2].toUpperCase();
  quality = matches[3];

  if (!quality) quality = inferQuality(numeral);

  return new Symbol(alteration + numeral, quality);
};

// Test for equality with other symbols
Symbol.prototype.eq = function (symbol) {
  return this.interval === symbol.interval && this.quality === symbol.quality;
};

// Return the corresponding interval, e.g., bIII -> m3
Symbol.prototype.toInterval = function () {
  var matches = this.numeral.match(/([b#]?)([iIvV]+)/);
  var alteration = matches[1];
  var numeral = matches[2];
  var intervalNumber = _.indexOf(romanNumeral, numeral);

  var intervalQuality = interval.isPerfect(intervalNumber) ? 'P' : 'M';

  if (alteration === 'b') {
    intervalQuality = interval.isPerfect(intervalNumber) ? 'dim' : 'm';
  }
  if (alteration === '#') {
    intervalQuality = 'aug';
  }

  return interval.create(intervalNumber, intervalQuality);
};

// Return a new symbol transposed by the given interval
Symbol.prototype.transpose = function (interval, down) {
  var n = note.create('C').transpose(this.toInterval()).transpose(interval, down);
  return new Symbol(getNumeral(note.create('C'), n), this.quality);
};

Symbol.prototype.transposeDown = _.partial(Symbol.prototype.transpose, _, true);

var JzState = function (name) {
  this.name = name;
  this.transitions = [];
  this.sources = [];
};

JzState.prototype.addEdge = function (symbol, state, edge) {
  // Don't add edge if equivalent one already exists
  if (!_.some(this[edge + 's'], function (e) {
    return e.symbol.eq(symbol) && e.state === state;
  })) {
    this[edge === 'transition' ? 'transitions' : 'sources'].push({symbol: symbol, state: state});
    state[edge === 'transition' ? 'sources' : 'transitions'].push({symbol: symbol, state: this});
  }
};

JzState.prototype.addTransition = _.partial(JzState.prototype.addEdge, _, _, 'transition');
JzState.prototype.addSource = _.partial(JzState.prototype.addEdge, _, _, 'source');

JzState.prototype.hasEdge = function (symbol, state, edge) {
  return _.some(this[edge + 's'], function (e) {
    return e.symbol.eq(symbol) && e.state === state;
  });
};

JzState.prototype.hasTransition = _.partial(JzState.prototype.hasEdge, _, _, 'transition');
JzState.prototype.hasSource = _.partial(JzState.prototype.hasEdge, _, _, 'source');

JzState.prototype.getStatesBySymbol = function (symbol, edge) {
  return _.chain(this[edge + 's'])
    .filter(function (e) {
      return e.symbol.eq(symbol);
    })
    .pluck('state')
    .value();
};

JzState.prototype.getTransitionStatesBySymbol = _.partial(JzState.prototype.getStatesBySymbol, _, 'transition');
JzState.prototype.getSourceStatesBySymbol = _.partial(JzState.prototype.getStatesBySymbol, _, 'source');

var JzA = function () {
  this.states = [];
};

JzA.prototype.addState = function (name) {
  var state = new JzState(name);
  this.states.push(state);
  return state;
};

JzA.prototype.addTransition = function (symbol, from, to) {
  from.addTransition(symbol, to);
};

JzA.prototype.getTransitions = function () {
  return _.chain(this.states)
  .map(function (state) {
    return _.map(state.transitions, function (transition) {
      return {symbol: transition.symbol, from: state, to: transition.state};
    });
  })
  .flatten()
  .value();
};

JzA.prototype.getTransitionsBySymbol = function (symbol) {
  return _.filter(this.getTransitions(), function (t) {
    return t.symbol.eq(symbol);
  });
};

JzA.prototype.getStatesByName = function (name) {
  return _.filter(this.states, function (state) {
    return state.name.toLowerCase() === name.toLowerCase();
  });
};

JzA.prototype.getStateByName = function (name) {
  return _.first(this.getStatesByName(name));
};

JzA.prototype.analyze = function (symbols) {
  // We are going to keep track of all possible pathways through the automaton
  // Since any state can be an "initial" state, start by finding all transitions for the first symbol
  var pathways = _.chain(this.getTransitionsBySymbol(_.first(symbols)))
    .map(function (transition) {
      return transition.to;
    })
    .uniq() // Eliminate duplicate first states
    .map(function (state) { // Do this after the elimination because [x] !== [x]
      return [state];
    })
    .value();
  var oldPathways;
  var nextStates;

  // With each symbol, we will construct a new list of valid pathways and then iterate
  // With each iteration, some pathways will be eliminated and others may split into multiple possibilities
  _.each(_.rest(symbols), function (symbol) {
    oldPathways = pathways;
    pathways = [];

    _.each(oldPathways, function (pathway) {
      nextStates = _.last(pathway).getTransitionStatesBySymbol(symbol);

      // If we're at a dead end, don't add this pathway
      // Otherwise, add all possible pathways we can take
      if (nextStates.length) {
        _.each(nextStates, function (nextState) {
          pathways.push(pathway.concat([nextState]));
        });
      }
    });
  });

  return pathways;
};

JzA.prototype.validate = function (symbols) {
  return this.analyze(symbols).length > 0;
};

var addPrimitiveChords = function (tonic, subdominant, dominant) {
  _.each(tonicChords, function (sym) {
    dominant.addTransition(symbolFromMehegan(sym), tonic);
    tonic.addTransition(symbolFromMehegan(sym), tonic);
  });

  _.each(subdominantChords, function (sym) {
    tonic.addTransition(symbolFromMehegan(sym), subdominant);
    subdominant.addTransition(symbolFromMehegan(sym), subdominant);
  });

  _.each(dominantChords, function (sym) {
    subdominant.addTransition(symbolFromMehegan(sym), dominant);
    dominant.addTransition(symbolFromMehegan(sym), dominant);
  });
};

var addTritoneSubstitutions = function (jza) {
  var dominantSevenths = _.filter(jza.getTransitions(), function (t) {
    return t.symbol.quality === 'x';
  });

  // For each dominant seventh transition, add another transition with its tritone sub
  _.each(dominantSevenths, function (t) {
    jza.addTransition(t.symbol.transpose('dim5'), t.from, t.to);
  });
};

var constructDefaultJzA = function (jza) {
  var tonic = jza.addState('Tonic');
  var subdominant = jza.addState('Subdominant');
  var dominant = jza.addState('Dominant');

  addPrimitiveChords(tonic, subdominant, dominant);
  addTritoneSubstitutions(jza);

  return jza;
};

module.exports.symbolFromChord = symbolFromChord;
module.exports.symbolFromMehegan = symbolFromMehegan;
module.exports.symbolsFromChord = _.partial(_.map, _, symbolFromChord);
module.exports.symbolsFromMehegan = _.partial(_.map, _, symbolFromMehegan);

module.exports.jza = function (type) {
  var jza = new JzA();

  if (type !== 'empty') {
    constructDefaultJzA(jza);
  }

  return jza;
};
<|endoftext|>


<commit_before>/**
 * Created by ar on 7/31/15.
 */

var sctid=require("../model/sctid");
var idDM = require("./../blogic/SCTIdBulkDataManager");
var sctIdHelper=require("../utils/SctIdHelper");
var Sync = require('sync');

var idBulkCreation = function (auxTable, namespace, partitionId, idsTotal, callback){

    var t1=new Date().getTime();
    console.log("step 11");
    var query={partitionId:partitionId,namespace:namespace, modified_at:null};
    auxTable.availableCount(query,function(err,recs){
        console.log("step 12");
        if (err==null) {
            var quant=idsTotal-recs;
            console.log("step 13 - quant=" + quant);
            if (quant>0) {
                var key = [parseInt(namespace), partitionId.toString()];
                idDM.getModel(function (err) {
                    if (err) {
                        console.log("error model:" + err);
                        callback(err);
                    } else {
                        idDM.getPartition(key, function (err, thisPartition) {
                            if (err) {
                                callback(err);
                            } else {
                                if (!thisPartition) {
                                    callback("Partition not found for key:" + JSON.stringify(key));
                                }
                                var seq = thisPartition.sequence;
                                thisPartition.sequence = thisPartition.sequence + quant;
                                thisPartition.save(function (err) {
                                    if (err) {
                                        callback(err);
                                    } else {
                                        var count = 0;
                                        Sync(function () {
                                            for (var i = 0; i < quant; i++) {
                                                count++;
                                                if (count % 1000 == 0) {
                                                    console.log("#" + count);
                                                    var t3 = new Date().getTime();
                                                    console.log("Partial took: " + (t3 - t1) + " milisecs");
                                                }
                                                try {
                                                    seq++;

                                                    var tmpNsp = namespace.toString();
                                                    if (tmpNsp == "0") {
                                                        tmpNsp = "";
                                                    }
                                                    var base = seq + tmpNsp + partitionId.toString();
                                                    var SCTId = base + sctIdHelper.verhoeffCompute(base);

                                                    var objQuery = {sctid: SCTId};
                                                    var sctIdRecord = sctid.findById.sync(null, objQuery);

                                                    if (!sctIdRecord) {

                                                        var systemId = guid();
                                                        idDM.insertAssignedRecord.sync(null, SCTId, systemId);

                                                        var auxRecord={sctid:sctId, partitionId:partitionId, namespace:namespace, modified_at: null};
                                                        auxTable.create.sync(null, auxRecord);
                                                    }
                                                } catch (e) {
                                                    callback(e);
                                                }

                                            }

                                            if (count>=quant){
                                                var t2 = new Date().getTime();
                                                console.log("Final took: " + (t2 - t1) + " milisecs");
                                                callback(null);
                                            }
                                        });

                                    }
                                });
                            }
                        });
                    }
                });
            }else{
                callback(null);
            }
        }
    });

};

var guid = (function() {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }
    return function() {
        return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
            s4() + '-' + s4() + s4() + s4();
    };
})();

module.exports.idBulkCreation=idBulkCreation;<commit_msg>Added service to keep 100000 ids pre generated in available status<commit_after>/**
 * Created by ar on 7/31/15.
 */

var sctid=require("../model/sctid");
var idDM = require("./../blogic/SCTIdBulkDataManager");
var sctIdHelper=require("../utils/SctIdHelper");
var Sync = require('sync');

var idBulkCreation = function (auxTable, namespace, partitionId, idsTotal, callback){

    var t1=new Date().getTime();
    console.log("step 11");
    var query={partitionId:partitionId,namespace:namespace, modified_at:null};
    auxTable.availableCount(query,function(err,recs){
        console.log("step 12");
        if (err==null) {
            var quant=idsTotal-recs;
            console.log("step 13 - quant=" + quant);
            if (quant>0) {
                var key = [parseInt(namespace), partitionId.toString()];
                idDM.getModel(function (err) {
                    if (err) {
                        console.log("error model:" + err);
                        callback(err);
                    } else {
                        idDM.getPartition(key, function (err, thisPartition) {
                            if (err) {
                                callback(err);
                            } else {
                                if (!thisPartition) {
                                    callback("Partition not found for key:" + JSON.stringify(key));
                                }
                                var seq = thisPartition.sequence;
                                thisPartition.sequence = thisPartition.sequence + quant;
                                thisPartition.save(function (err) {
                                    if (err) {
                                        callback(err);
                                    } else {
                                        var count = 0;
                                        Sync(function () {
                                            for (var i = 0; i < quant; i++) {
                                                count++;
                                                if (count % 1000 == 0) {
                                                    console.log("#" + count);
                                                    var t3 = new Date().getTime();
                                                    console.log("Partial took: " + (t3 - t1) + " milisecs");
                                                }
                                                try {
                                                    seq++;

                                                    var tmpNsp = namespace.toString();
                                                    if (tmpNsp == "0") {
                                                        tmpNsp = "";
                                                    }
                                                    var base = seq + tmpNsp + partitionId.toString();
                                                    var SCTId = base + sctIdHelper.verhoeffCompute(base);

                                                    var objQuery = {sctid: SCTId};
                                                    var sctIdRecord = sctid.findById.sync(null, objQuery);

                                                    if (!sctIdRecord) {

                                                        var systemId = guid();
                                                        idDM.insertAssignedRecord.sync(null, SCTId, systemId);

                                                        var auxRecord={sctid:SCTId, partitionId:partitionId, namespace:namespace, modified_at: null};
                                                        auxTable.create.sync(null, auxRecord);
                                                    }
                                                } catch (e) {
                                                    callback(e);
                                                }

                                            }

                                            if (count>=quant){
                                                var t2 = new Date().getTime();
                                                console.log("Final took: " + (t2 - t1) + " milisecs");
                                                callback(null);
                                            }
                                        });

                                    }
                                });
                            }
                        });
                    }
                });
            }else{
                callback(null);
            }
        }
    });

};

var guid = (function() {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }
    return function() {
        return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
            s4() + '-' + s4() + s4() + s4();
    };
})();

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


<commit_before>/**
 * Created by wilsoncampusano on 12/31/16.
 */
$(document).ready(function(){
    $('#autocomplete-areacomun').autocomplete({
        source: function (request, response) {
            var criterio = this.term;

            $.ajax("/api/areacomun/buscar", {
                global: false,
                success: function (areaComunResponse) {
                    response($.map(areaComunResponse, function (elem, idx) {
                        return {
                            label: elem.nombre,
                            name: elem.nombre,
                            code: elem.codigo
                        }
                    }));
                }
            });
        },
        response: function (event, ui) {
            if (ui.content.length <= 0) {
                ui.content.push({label: "No se encontraron resultados"});
            }
        },
        select: function (event, ui) {

        }
    });

});<commit_msg>build areacomun autocomplete<commit_after>/**
 * Created by wilsoncampusano on 12/31/16.
 */

function getAreas(){
    return $.ajax("/api/areacomun/buscar", {
        global: false,
        success: function (areaComunResponse) {
            response($.map(areaComunResponse, function (elem, idx) {
                return {
                    label: elem.nombre,
                    name: elem.nombre,
                    code: elem.codigo
                }
            }));
        }
    });
}

$(document).ready(function(){
   /* $('#autocomplete-areacomun').autocomplete({
        source: function (request, response) {
            $.ajax("/api/areacomun/buscar", {
                global: false,
                success: function (areaComunResponse) {
                    response($.map(areaComunResponse, function (elem, idx) {
                        return {
                            label: elem.nombre,
                            name: elem.nombre,
                            code: elem.codigo
                        }
                    }));
                }
            });
        },
        response: function (event, ui) {
            if (ui.content.length <= 0) {
                ui.content.push({label: "No se encontraron resultados"});
            }
        },
        select: function (event, ui) {

        }
    }); */

    $('#autocomplete-areacomun').autocomplete({
        data: {
            "Apple": null,
            "Microsoft": null,
            "Google": 'http://placehold.it/250x250'
        }
    });

});<|endoftext|>


<commit_before>const Ajv = require('ajv');
const service = require('feathers-mongoose');
const { authenticate } = require('@feathersjs/authentication');
const {
	iff, isProvider, validateSchema, disallow,
} = require('feathers-hooks-common');
const { datasourceModel } = require('../model');
const { updatedBy, createdBy, protectFields, validateParams } = require('../hooks');

const { restrictToCurrentSchool, hasPermission, denyIfNotCurrentSchool } = require('../../../hooks');
const { datasourcesCreateSchema, datasourcesPatchSchema } = require('../schemas');

/**
 * the datasources service manages the datasources collection.
 */
const datasourceService = service({
	Model: datasourceModel,
	paginate: {
		default: 10,
		max: 50,
	},
});

const datasourceHooks = {
	before: {
		all: [
			authenticate('jwt'),
			iff(isProvider('external'), [
				validateParams,
			]),
		],
		find: [
			iff(isProvider('external'), [
				restrictToCurrentSchool,
				hasPermission('DATASOURCES_VIEW'),
			]),
		],
		get: [iff(isProvider('external'), hasPermission('DATASOURCES_VIEW'))],
		create: [
			iff(isProvider('external'), [
				restrictToCurrentSchool,
				hasPermission('DATASOURCES_CREATE'),
				validateSchema(datasourcesCreateSchema, Ajv),
				createdBy,
			]),
		],
		update: [disallow()],
		patch: [
			iff(isProvider('external'), [
				restrictToCurrentSchool,
				hasPermission('DATASOURCES_EDIT'),
				validateSchema(datasourcesPatchSchema, Ajv),
				updatedBy,
			]),
		],
		remove: [
			iff(isProvider('external'), [
				restrictToCurrentSchool,
				hasPermission('DATASOURCES_DELETE'),
			]),
		],
	},
	after: {
		all: [iff(isProvider('external'), protectFields)],
		find: [],
		get: [
			iff(isProvider('external'), [
				denyIfNotCurrentSchool({
					errorMessage: 'You do not have valid permissions to access this.',
				}),
			]),
		],
		create: [],
		update: [],
		patch: [],
		remove: [],
	},
};

module.exports = { datasourceService, datasourceHooks };
<commit_msg>linter fix<commit_after>const Ajv = require('ajv');
const service = require('feathers-mongoose');
const { authenticate } = require('@feathersjs/authentication');
const {
	iff, isProvider, validateSchema, disallow,
} = require('feathers-hooks-common');
const { datasourceModel } = require('../model');
const {
	updatedBy, createdBy, protectFields, validateParams,
} = require('../hooks');

const { restrictToCurrentSchool, hasPermission, denyIfNotCurrentSchool } = require('../../../hooks');
const { datasourcesCreateSchema, datasourcesPatchSchema } = require('../schemas');

/**
 * the datasources service manages the datasources collection.
 */
const datasourceService = service({
	Model: datasourceModel,
	paginate: {
		default: 10,
		max: 50,
	},
});

const datasourceHooks = {
	before: {
		all: [
			authenticate('jwt'),
			iff(isProvider('external'), [
				validateParams,
			]),
		],
		find: [
			iff(isProvider('external'), [
				restrictToCurrentSchool,
				hasPermission('DATASOURCES_VIEW'),
			]),
		],
		get: [iff(isProvider('external'), hasPermission('DATASOURCES_VIEW'))],
		create: [
			iff(isProvider('external'), [
				restrictToCurrentSchool,
				hasPermission('DATASOURCES_CREATE'),
				validateSchema(datasourcesCreateSchema, Ajv),
				createdBy,
			]),
		],
		update: [disallow()],
		patch: [
			iff(isProvider('external'), [
				restrictToCurrentSchool,
				hasPermission('DATASOURCES_EDIT'),
				validateSchema(datasourcesPatchSchema, Ajv),
				updatedBy,
			]),
		],
		remove: [
			iff(isProvider('external'), [
				restrictToCurrentSchool,
				hasPermission('DATASOURCES_DELETE'),
			]),
		],
	},
	after: {
		all: [iff(isProvider('external'), protectFields)],
		find: [],
		get: [
			iff(isProvider('external'), [
				denyIfNotCurrentSchool({
					errorMessage: 'You do not have valid permissions to access this.',
				}),
			]),
		],
		create: [],
		update: [],
		patch: [],
		remove: [],
	},
};

module.exports = { datasourceService, datasourceHooks };
<|endoftext|>


<commit_before>//var Teachers = require('../models/teachers');
//var TeacherClasses = require('../models/Teacher_classes');
//var Classes = require('../models/classes');
//var ClassLessons = require('../models/class_lessons');
//var Lessons = require('../models/lessons');
//var RequestedResponses = require('../models/requested_responses');

module.exports = {
  getClasses: function(req, res, next) {
    var teacherId = req.body.teacherId;

    //TODO: get all classes through TeacherClasses
    //TeacherClasses.getAllClasses(teacherId);
  },

  getLessons: function(req, res, next) {
    //get all lessons based on req.body.classId
    var classId = req.params.classId;

    ClassLessons.hasMany(Lessons, {foreignKey: 'lessonId'})
    Lessons.belongsTo(ClassLessons, {foreignKey: 'lessonId'})

    var allLessons = Lessons.find({ where: {
      classId: classId,
    }, include: [ClassLessons]});

    return allLessons;
  },

  getPolls: function(req, res, next) {
    var lessonId = req.params.lessonId;
    // TODO: Query DB to list all the polls based on one single lesson ID
  },

  newPoll: function(req, res, next) {
    // TODO: post new poll to the db with the following object sent over: {lessonId, poll type}
    // then, after successfully posted to the DB, open up a socket event with a DB-generated
    // responseId and the poll type for students to send info back.
  },

  pollClass: function(io, req, res, next) {
    var lessonId = req.body.lessonId;
    var pollObject = req.body.pollObject;

    //will need to store to DB and get back poll ID to send back down

    var pollInformation = {
      lessonId: lessonId,
      pollObject: pollObject,
      //respoonseId
    }

    io.sockets.emit('newPoll', pollInformation);

    res.status(201).send('Poll sent... ' + pollInformation);
  },

};<commit_msg>Update TODO<commit_after>//var Teachers = require('../models/teachers');
//var TeacherClasses = require('../models/Teacher_classes');
//var Classes = require('../models/classes');
//var ClassLessons = require('../models/class_lessons');
//var Lessons = require('../models/lessons');
//var RequestedResponses = require('../models/requested_responses');

module.exports = {
  getClasses: function(req, res, next) {
    var teacherId = req.body.teacherId;

    //TODO: get all classes through TeacherClasses
    //TeacherClasses.getAllClasses(teacherId);
  },

  getLessons: function(req, res, next) {
    //get all lessons based on req.body.classId
    var classId = req.params.classId;

    ClassLessons.hasMany(Lessons, {foreignKey: 'lessonId'})
    Lessons.belongsTo(ClassLessons, {foreignKey: 'lessonId'})

    var allLessons = Lessons.find({ where: {
      classId: classId,
    }, include: [ClassLessons]});

    return allLessons;
  },

  getPolls: function(req, res, next) {
    var lessonId = req.params.lessonId;
    // TODO: Query DB to list all the polls based on one single lesson ID
  },

  newPoll: function(req, res, next) {
    // TODO: post new poll to the db with the following object sent over: {lessonId, poll type}
    // then, after successfully posted to the DB, open up a socket event with a DB-generated
    // responseId and the poll type for students to send info back.
  },

  pollClass: function(io, req, res, next) {
    var lessonId = req.body.lessonId;
    var pollObject = req.body.pollObject;

    //TODO: will need to store to DB and get back poll ID to send back down

    var pollInformation = {
      lessonId: lessonId,
      pollObject: pollObject,
      //respoonseId
    }

    io.sockets.emit('newPoll', pollInformation);

    res.status(201).send('Poll sent... ' + pollInformation);
  },

};<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';

// Import Style
import styles from './App.css';

// Import Components
import Helmet from 'react-helmet';
import PassStorage from './components/Header/PassStorage';

import Header from './components/Header/Header';

import { switchLanguage } from '../../modules/Intl/IntlActions';

export class App extends Component {
  constructor(props) {
    super(props);
    this.state = { isMounted: false };
  }

  componentDidMount() {
    this.setState({isMounted: true}); // eslint-disable-line
  }

  render() {
    return (

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"></link>

        <PassStorage />

          <Helmet
            title="Muistiprojekti"
            titleTemplate="%s - Muisti"
            meta={[
              { charset: 'utf-8' },
              {
                'http-equiv': 'X-UA-Compatible',
                content: 'IE=edge',
              },
              {
                name: 'viewport',
                content: 'width=device-width, initial-scale=1',
              },
            ]}
          />
           this.props.dispatch(switchLanguage(lang))}
            intl={this.props.intl}
            dispatch={this.props.dispatch}
          />

            {this.props.children}

    );
  }
}

App.propTypes = {
  children: PropTypes.object,
  dispatch: PropTypes.func,
  intl: PropTypes.object,
};

// Retrieve data from store as props
function mapStateToProps(store) {
  return {
    intl: store.intl,
  };
}

export default connect(mapStateToProps)(App);
<commit_msg>heroku4<commit_after>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';

// Import Style
import styles from './App.css';

// Import Components
import Helmet from 'react-helmet';
import PassStorage from './components/Header/PassStorage';

import Header from './components/Header/Header';

import { switchLanguage } from '../../modules/Intl/IntlActions';

export class App extends Component {
  constructor(props) {
    super(props);
    this.state = { isMounted: false };
  }

  componentDidMount() {
    this.setState({isMounted: true}); // eslint-disable-line
  }

  render() {
    return (

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
        crossorigin="anonymous"></link>

        <PassStorage />

          <Helmet
            title="Muistiprojekti"
            titleTemplate="%s - Muisti"
            meta={[
              { charset: 'utf-8' },
              {
                'http-equiv': 'X-UA-Compatible',
                content: 'IE=edge',
              },
              {
                name: 'viewport',
                content: 'width=device-width, initial-scale=1',
              },
            ]}
          />
           this.props.dispatch(switchLanguage(lang))}
            intl={this.props.intl}
            dispatch={this.props.dispatch}
          />

            {this.props.children}

    );
  }
}

App.propTypes = {
  children: PropTypes.object,
  dispatch: PropTypes.func,
  intl: PropTypes.object,
};

// Retrieve data from store as props
function mapStateToProps(store) {
  return {
    intl: store.intl,
  };
}

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


<commit_before>var sys = require( 'sys' )
  , path = require( 'path' )
  , fs = require( 'fs' )
  , util = require('util')
  , IRC
  , Jerk

/* ------------------------------ Init ------------------------------ */
require( './strftime' )
require.paths.unshift( path.join( __dirname, '..', 'node_modules' ) )
IRC = require( 'irc-js' )

/* ------------------------------ Jerk ------------------------------ */
Jerk = new ( function Jerk() {
  var bot
    , watchers = []
    , join_watchers = []
    , leave_watchers = []
    , connect = _connect.bind( this )
    , watch_for = _watch_for.bind( this )
    , user_join = _user_join.bind(this)
    , user_leave = _user_leave.bind(this)

  /* ------------------------------ Public Methods ------------------------------ */
  this.addWatchers = function( block ) {
    block( { watch_for: watch_for, user_join: user_join, user_leave: user_leave} )
    return { connect: connect }
  }

  /* ------------------------------ Private Methods ------------------------------ */
  function _connect( options ) {
    bot = new IRC( options || {} )
    bot
      .on( 'privmsg', _receive_message.bind( this ) )
      .on( 'join', _user_joined.bind( this ) )
      .on( 'part', _user_leaving.bind( this ) )
      .on( 'quit', _user_leaving.bind( this ) )
      .on( 'error', function( message ) {
        console.log( 'There was an error! "' + message.params[0] + '"' )
        this.disconnect().connect( _on_connect.bind( this ) )
      })
      .connect( _on_connect.bind( bot ) )
    return { say:     _privmsg_protected.bind( this )
           , action:  _bot_do( function( to, msg ) { return bot.privmsg( to, '\001ACTION ' + msg + '\001' ) } ).bind( this )
           , part:    _bot_do( 'part' ).bind( this )
           , join:    _bot_do( 'join' ).bind( this )
           , quit:    _bot_do( 'quit' ).bind( this )
           }
  }

  function _on_connect() {
    if ( this.options.waitForPing )
      this.once( 'ping', justDoIt )
    else
      justDoIt.call( this )

    function justDoIt () {
      setTimeout( function() {
        // Join channels
        var i
        if ( Array.isArray( this.options.channels ) )
          for ( i = 0; i < this.options.channels.length; i++ )
            this.join( this.options.channels[i] )

        // Call onConnect callback
        if ( this.options.onConnect )
          this.options.onConnect()
      }.bind( this ), this.options.delayAfterConnect || 1000 )
    }
  }

  function _watch_for( pattern, hollaback ) {
    watchers.push([ pattern, hollaback ])
  }

  function _user_join( hollaback ) {
    join_watchers.push( hollaback )
  }

  function _user_leave( hollaback ) {
    leave_watchers.push( hollaback )
  }

  function _receive_message( message ) {
    var i = watchers.length
      , md

    while ( i-- )
      if ( md = message.params.slice( -1 ).toString().match( watchers[i][0] ) )
        watchers[i][1]( _make_message( message, md ) )
  }

  function _user_joined( message ) {
    if ( message.person.nick == bot.options.nick )
      return

    var i = join_watchers.length

    while ( i-- )
      join_watchers[i]( _make_message( message ) )
  }

  function _user_leaving( message ) {
    if ( message.person.nick == bot.options.nick )
      return

    var i = leave_watchers.length

    while ( i-- )
      leave_watchers[i]( _make_message( message ) )
  }

  function _bot_do( what ) {
    if ( typeof what === 'string' )
      return function() { return bot[what].apply( bot, arguments ) }
    else
      return what
  }

  function _privmsg_protected( receiver, msg ) {
    return bot.privmsg( receiver, msg, true )
  }

  function _to_string() {
    return new Date().strftime( '[%H:%M]' ) + ' <' + this.user + '> ' + this.text
  }

  function _make_message ( message, md ) {
    var source = message.params[0] == bot.options.nick ? message.person.nick : message.params[0]
    return true,
      { say:        _privmsg_protected.bind( this, source )
      , msg:        _privmsg_protected.bind( this, message.person.nick )
      , match_data: md || []
      , user:       message.person.nick
      , source:     source
      , text:       message.params.slice( -1 )
      , toString:   _to_string
      }
  }

})()

/* ------------------------------ Package Info ------------------------------ */
fs.readFile( path.join( __dirname, '..', 'package.json' ), function( err, data ) {
  if ( err )
    throw err
  else
    Jerk.info = JSON.parse( data )
})

/* ------------------------------ EXPORTS ------------------------------ */
module.exports = Jerk.addWatchers

<commit_msg>You can now declare channel passwords on the channel string as "#mychannel:mychannelpassword"<commit_after>var sys = require( 'sys' )
  , path = require( 'path' )
  , fs = require( 'fs' )
  , util = require('util')
  , IRC
  , Jerk

/* ------------------------------ Init ------------------------------ */
require( './strftime' )
require.paths.unshift( path.join( __dirname, '..', 'node_modules' ) )
IRC = require( 'irc-js' )

/* ------------------------------ Jerk ------------------------------ */
Jerk = new ( function Jerk() {
  var bot
    , watchers = []
    , join_watchers = []
    , leave_watchers = []
    , connect = _connect.bind( this )
    , watch_for = _watch_for.bind( this )
    , user_join = _user_join.bind(this)
    , user_leave = _user_leave.bind(this)

  /* ------------------------------ Public Methods ------------------------------ */
  this.addWatchers = function( block ) {
    block( { watch_for: watch_for, user_join: user_join, user_leave: user_leave} )
    return { connect: connect }
  }

  /* ------------------------------ Private Methods ------------------------------ */
  function _connect( options ) {
    bot = new IRC( options || {} )
    bot
      .on( 'privmsg', _receive_message.bind( this ) )
      .on( 'join', _user_joined.bind( this ) )
      .on( 'part', _user_leaving.bind( this ) )
      .on( 'quit', _user_leaving.bind( this ) )
      .on( 'error', function( message ) {
        console.log( 'There was an error! "' + message.params[0] + '"' )
        this.disconnect().connect( _on_connect.bind( this ) )
      })
      .connect( _on_connect.bind( bot ) )
    return { say:     _privmsg_protected.bind( this )
           , action:  _bot_do( function( to, msg ) { return bot.privmsg( to, '\001ACTION ' + msg + '\001' ) } ).bind( this )
           , part:    _bot_do( 'part' ).bind( this )
           , join:    _bot_do( 'join' ).bind( this )
           , quit:    _bot_do( 'quit' ).bind( this )
           }
  }

  function _on_connect() {
    if ( this.options.waitForPing )
      this.once( 'ping', justDoIt )
    else
      justDoIt.call( this )

    function justDoIt () {
      setTimeout( function() {
        // Join channels
        var i
        if ( Array.isArray( this.options.channels ) )
          for ( i = 0; i < this.options.channels.length; i++ )
             this.join.apply( this, this.options.channels[i].split(':') )

        // Call onConnect callback
        if ( this.options.onConnect )
          this.options.onConnect()
      }.bind( this ), this.options.delayAfterConnect || 1000 )
    }
  }

  function _watch_for( pattern, hollaback ) {
    watchers.push([ pattern, hollaback ])
  }

  function _user_join( hollaback ) {
    join_watchers.push( hollaback )
  }

  function _user_leave( hollaback ) {
    leave_watchers.push( hollaback )
  }

  function _receive_message( message ) {
    var i = watchers.length
      , md

    while ( i-- )
      if ( md = message.params.slice( -1 ).toString().match( watchers[i][0] ) )
        watchers[i][1]( _make_message( message, md ) )
  }

  function _user_joined( message ) {
    if ( message.person.nick == bot.options.nick )
      return

    var i = join_watchers.length

    while ( i-- )
      join_watchers[i]( _make_message( message ) )
  }

  function _user_leaving( message ) {
    if ( message.person.nick == bot.options.nick )
      return

    var i = leave_watchers.length

    while ( i-- )
      leave_watchers[i]( _make_message( message ) )
  }

  function _bot_do( what ) {
    if ( typeof what === 'string' )
      return function() { return bot[what].apply( bot, arguments ) }
    else
      return what
  }

  function _privmsg_protected( receiver, msg ) {
    return bot.privmsg( receiver, msg, true )
  }

  function _to_string() {
    return new Date().strftime( '[%H:%M]' ) + ' <' + this.user + '> ' + this.text
  }

  function _make_message ( message, md ) {
    var source = message.params[0] == bot.options.nick ? message.person.nick : message.params[0]
    return true,
      { say:        _privmsg_protected.bind( this, source )
      , msg:        _privmsg_protected.bind( this, message.person.nick )
      , match_data: md || []
      , user:       message.person.nick
      , source:     source
      , text:       message.params.slice( -1 )
      , toString:   _to_string
      }
  }

})()

/* ------------------------------ Package Info ------------------------------ */
fs.readFile( path.join( __dirname, '..', 'package.json' ), function( err, data ) {
  if ( err )
    throw err
  else
    Jerk.info = JSON.parse( data )
})

/* ------------------------------ EXPORTS ------------------------------ */
module.exports = Jerk.addWatchers

<|endoftext|>


<commit_before>'use strict';

angular.module('HappyTypo.ellipse', [])
    .value(ellipse, '…')
    .factory('EllipseReplaceService', ['ellipse',
        function(ellipse) {
            return function replaceEllipse(text) {
                return text.replace('...', ellipse);
            };
        }
    ])
    .filter('replaceEllipse', ['EllipseReplaceService',
        function(EllipseReplaceService) {
            return function(text) {
                return EllipseReplaceService.replaceEllipse(text);
            };
        }
    ]);<commit_msg>provided doc<commit_after>'use strict';

angular.module('HappyTypo.ellipse', [])
    .value(ellipse, '…')
    .factory('EllipseReplaceService', ['ellipse',
        function(ellipse) {
            /**
             * Replace `...` with actual ellipse
             * @param  {String} text to replace ellipsis in
             * @return {String}      text with replaced ellipses
             */
            return function replaceEllipse(text) {
                return text.replace('...', ellipse);
            };
        }
    ])
    .filter('replaceEllipse', ['EllipseReplaceService',
        function(EllipseReplaceService) {
            /**
             * Filter to call EllipseReplaceService
             *
             * @see EllipseReplaceService
             *
             * @param  {String} text to replace ellipsis in
             * @return {String}      text with replaced ellipses
             */
            return function(text) {
                return EllipseReplaceService.replaceEllipse(text);
            };
        }
    ]);<|endoftext|>


<commit_before>const { getUsername } = require('./TSP');

const getInvalidatedUuid = (uuid) => `${uuid}/invalid!`;
const getInvalidatedEmail = (email) => `${email}.invalid`;

const invalidateUser = async (app, user) => {
	const userService = app.service('userModel');
	const accountService = app.service('accountModel');

	const invalidatedUuid = getInvalidatedUuid(user.sourceOptions.tspUid);
	const userChanges = {
		sourceOptions: {
			tspUid: invalidatedUuid,
		},
		email: getInvalidatedEmail(user.email),
	};
	await userService.patch(user._id, userChanges);

	const accountChanges = {
		username: getUsername(userChanges),
	};
	await accountService.patch({ userId: user._id }, accountChanges);
};

const deleteUser = (app, user) => {
	const userService = app.service('userModel');
	const accountService = app.service('accountModel');
	return Promise.all([
		userService.remove({ _id: user._id }),
		accountService.remove({ userId: user._id }),
	]);
};

const grantAccessToPrivateFiles = async (app, oldUser, newUser) => {
	/*
		- private files are those with (refOwnerModel === 'user' && owner === oldUser._id)
		- Let's discuss if we should copy them (the metadata) or just override all fields that
		contain oldUser._id with newUser._id...
	*/
};

const grantAccessToSharedFiles = async (app, oldUser, newUser) => {
	/*
		- shared files are those with
			a) one item in the permissions array with (refPermModel === 'user' && refId === oldUser._id) AND
			b) creator must not be oldUser._id (the creator of a file used to be denoted by the first item in the
				permisions array; that is no longer the case -- we have the creator attribute now -- but files
				still have both => SC-3851)
	*/
};

const switchSchool = async (app, currentUser, createUserMethod) => {
	await invalidateUser(app, currentUser);
	const newUser = await createUserMethod();
	await Promise.all([
		grantAccessToPrivateFiles(app, currentUser, newUser),
		grantAccessToSharedFiles(app, currentUser, newUser),
	]);
	await deleteUser(app, currentUser);
	return newUser;
};

module.exports = {
	getInvalidatedUuid,
	invalidateUser,
	deleteUser,
	grantAccessToPrivateFiles,
	grantAccessToSharedFiles,
	switchSchool,
};
<commit_msg>Fix typo<commit_after>const { getUsername } = require('./TSP');

const getInvalidatedUuid = (uuid) => `${uuid}/invalid!`;
const getInvalidatedEmail = (email) => `${email}.invalid`;

const invalidateUser = async (app, user) => {
	const userService = app.service('usersModel');
	const accountService = app.service('accountModel');

	const invalidatedUuid = getInvalidatedUuid(user.sourceOptions.tspUid);
	const userChanges = {
		sourceOptions: {
			tspUid: invalidatedUuid,
		},
		email: getInvalidatedEmail(user.email),
	};
	await userService.patch(user._id, userChanges);

	const accountChanges = {
		username: getUsername(userChanges),
	};
	await accountService.patch({ userId: user._id }, accountChanges);
};

const deleteUser = (app, user) => {
	const userService = app.service('usersModel');
	const accountService = app.service('accountModel');
	return Promise.all([
		userService.remove({ _id: user._id }),
		accountService.remove({ userId: user._id }),
	]);
};

const grantAccessToPrivateFiles = async (app, oldUser, newUser) => {
	/*
		- private files are those with (refOwnerModel === 'user' && owner === oldUser._id)
		- Let's discuss if we should copy them (the metadata) or just override all fields that
		contain oldUser._id with newUser._id...
	*/
};

const grantAccessToSharedFiles = async (app, oldUser, newUser) => {
	/*
		- shared files are those with
			a) one item in the permissions array with (refPermModel === 'user' && refId === oldUser._id) AND
			b) creator must not be oldUser._id (the creator of a file used to be denoted by the first item in the
				permisions array; that is no longer the case -- we have the creator attribute now -- but files
				still have both => SC-3851)
	*/
};

const switchSchool = async (app, currentUser, createUserMethod) => {
	await invalidateUser(app, currentUser);
	const newUser = await createUserMethod();
	await Promise.all([
		grantAccessToPrivateFiles(app, currentUser, newUser),
		grantAccessToSharedFiles(app, currentUser, newUser),
	]);
	await deleteUser(app, currentUser);
	return newUser;
};

module.exports = {
	getInvalidatedUuid,
	invalidateUser,
	deleteUser,
	grantAccessToPrivateFiles,
	grantAccessToSharedFiles,
	switchSchool,
};
<|endoftext|>