<commit_before>const path = require('path');

const gulp = require('gulp');

const clean = require('gulp-rimraf');

const dot = require('dot');
const template = require('gulp-dot-template');
var prettifyHtml = require('gulp-html-prettify');

const cssimport = require('gulp-cssimport');
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');

const rootFolder = 'www';
const distFolder = 'dist';
// const rootStaticFolder = path.join(rootFolder, 'static');
const staticFolders = ['static', 'img', 'i', 'font'];

const readFiles = require('./gulp/my-gulp-util').readFiles;

gulp.task('clean', function () {
    return gulp.src(path.join(distFolder, '**', '*'), {read: false})
        .pipe(clean({force: true}));
});

gulp.task('dot', function (cb) {

    readFiles(path.join(rootFolder, 'chunks'), {test: /\.dot$/})
        .then(chunks =>
            gulp.src(path.join(rootFolder, '*.html'))
                .pipe(template({chunks, dot}))
                .pipe(gulp.dest(distFolder))
                .on('end', cb)
        );

});

gulp.task('prettify-html', function () {
    return gulp.src(path.join(distFolder, '*.html'))
        .pipe(prettifyHtml({indent_char: ' ', indent_size: 4}))
        .pipe(gulp.dest(distFolder));
});

gulp.task('html', gulp.series('dot', 'prettify-html'));

gulp.task('watch:html', function () {
    gulp.watch([path.join(rootFolder, '**', '*.html'), path.join(rootFolder, '**', '*.dot')], gulp.series('html'));
});

gulp.task('import-css', function () {
    return gulp.src(path.join(rootFolder, 'css', 'main', 'main.scss'))
        .pipe(cssimport({}))
        .pipe(gulp.dest(path.join(distFolder, 'css')));
});

gulp.task('sass', function () {
    return gulp.src(path.join(distFolder, 'css', 'main.scss'))
        .pipe(clean({force: true}))
        .pipe(sass())
        .pipe(gulp.dest(path.join(distFolder, 'css')));
});

gulp.task('autoprefix', function () {
    return gulp.src(path.join(distFolder, 'css', 'main.css'))
        .pipe(autoprefixer({
            browsers: ['last 4 version', 'safari 5', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'],
            cascade: false
        }))
        .pipe(gulp.dest(path.join(distFolder, 'css')));
});

gulp.task('css', gulp.series('import-css', 'sass', 'autoprefix'));

gulp.task('watch:css', function () {
    gulp.watch(path.join(rootFolder, '**', '*.scss'), gulp.series('css'));
});

gulp.task('js', function () {
    return gulp.src(path.join(rootFolder, 'js', '**', '*')).pipe(gulp.dest(path.join(distFolder, 'js')));
});

gulp.task('watch:js', function () {
    gulp.watch(path.join(rootFolder, 'js', '**', '*'), gulp.series('js'));
});

gulp.task('copy-data', function () {
    return Promise
        .all(staticFolders.map(folder => {
                return new Promise((resolve, reject)=> {
                    gulp
                        .src(path.resolve(rootFolder, folder, '**', '*'))
                        .pipe(gulp.dest(path.resolve(distFolder, folder)))
                        .on('end', resolve)
                        .on('error', reject);
                })
            })
        );
});

gulp.task('watch:copy-data', function () {
    gulp.watch(
        staticFolders.map(folder => path.resolve(rootFolder, folder, '**', '*')),
        gulp.series('copy-data')
    );
});

gulp.task('default', gulp.parallel('html', 'css', 'js', 'copy-data'));
gulp.task('watch', gulp.series('default', gulp.parallel('watch:html', 'watch:css', 'watch:js', 'watch:copy-data')));
<commit_msg>gulpfile.js - refactor<commit_after>const path = require('path');

const gulp = require('gulp');

const clean = require('gulp-rimraf');

const dot = require('dot');
const template = require('gulp-dot-template');
const prettifyHtml = require('gulp-html-prettify');

const cssimport = require('gulp-cssimport');
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');

const rootFolder = 'www';
const distFolder = 'dist';
// const rootStaticFolder = path.join(rootFolder, 'static');
const staticFolders = ['static', 'img', 'i', 'font'];

const readFiles = require('./gulp/my-gulp-util').readFiles;

gulp.task('clean', function () {
    return gulp.src(path.join(distFolder, '**', '*'), {read: false})
        .pipe(clean({force: true}));
});

gulp.task('dot', function (cb) {

    readFiles(path.join(rootFolder, 'chunks'), {test: /\.dot$/})
        .then(chunks =>
            gulp.src(path.join(rootFolder, '*.html'))
                .pipe(template({chunks, dot}))
                .pipe(gulp.dest(distFolder))
                .on('end', cb)
        );

});

gulp.task('prettify-html', function () {
    return gulp.src(path.join(distFolder, '*.html'))
        .pipe(prettifyHtml({indent_char: ' ', indent_size: 4}))
        .pipe(gulp.dest(distFolder));
});

gulp.task('html', gulp.series('dot', 'prettify-html'));

gulp.task('watch:html', function () {
    gulp.watch([path.join(rootFolder, '**', '*.html'), path.join(rootFolder, '**', '*.dot')], gulp.series('html'));
});

gulp.task('import-css', function () {
    return gulp.src(path.join(rootFolder, 'css', 'main', 'main.scss'))
        .pipe(cssimport({}))
        .pipe(gulp.dest(path.join(distFolder, 'css')));
});

gulp.task('sass', function () {
    return gulp.src(path.join(distFolder, 'css', 'main.scss'))
        .pipe(clean({force: true}))
        .pipe(sass())
        .pipe(gulp.dest(path.join(distFolder, 'css')));
});

gulp.task('autoprefix', function () {
    return gulp.src(path.join(distFolder, 'css', 'main.css'))
        .pipe(autoprefixer({
            browsers: ['last 4 version', 'safari 5', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'],
            cascade: false
        }))
        .pipe(gulp.dest(path.join(distFolder, 'css')));
});

gulp.task('css', gulp.series('import-css', 'sass', 'autoprefix'));

gulp.task('watch:css', function () {
    gulp.watch(path.join(rootFolder, '**', '*.scss'), gulp.series('css'));
});

gulp.task('js', function () {
    return gulp.src(path.join(rootFolder, 'js', '**', '*')).pipe(gulp.dest(path.join(distFolder, 'js')));
});

gulp.task('watch:js', function () {
    gulp.watch(path.join(rootFolder, 'js', '**', '*'), gulp.series('js'));
});

gulp.task('copy-data', function () {
    return Promise
        .all(staticFolders.map(folder => {
                return new Promise((resolve, reject)=> {
                    gulp
                        .src(path.resolve(rootFolder, folder, '**', '*'))
                        .pipe(gulp.dest(path.resolve(distFolder, folder)))
                        .on('end', resolve)
                        .on('error', reject);
                })
            })
        );
});

gulp.task('watch:copy-data', function () {
    gulp.watch(
        staticFolders.map(folder => path.resolve(rootFolder, folder, '**', '*')),
        gulp.series('copy-data')
    );
});

gulp.task('default', gulp.parallel('html', 'css', 'js', 'copy-data'));
gulp.task('watch', gulp.series('default', gulp.parallel('watch:html', 'watch:css', 'watch:js', 'watch:copy-data')));
<|endoftext|>


<commit_before>//http://www.rhymezone.com/r/rhyme.cgi?Word=back&typeofrhyme=perfect&org1=syl&org2=l&org3=y
//if this seems like it will work, move to random tables. based on recursiveSlacker's idea.
var comedyInterestNouns = ["joke","clown","fun", "folk", "bloke"];
var comedyInterestVerbs = ["joke", "frown", "stun", "soak", "choke", "scrunch", "wisecrack"];

var athleticInterestNouns = ["sun","lunch","crown","yolk"];
var athleticInterestVerbs = ["run","punch", "down", "drown", "soak", "won"];

var musicInterestNouns = ["","","","","","","","","","","",""];
var musicInterestVerbs = ["","","","","","","","","","","",""];

var writingInterestNouns = ["","","","","","","","","","","",""];
var writingInterestVerbs = ["","","","","","","","","","","",""];

var popCultureInterestNouns = ["megalomaniac","Jack","sack","quack","asscrack","throwback","huge mistake","piece of cake","flake","mistake","",""];
var popCultureInterestVerbs = ["wisecrack","throwback","hoseseback","ransack","take","wake","headache","shake","","","",""];

var technologyInterestNouns = ["","","","","","","","","","","",""];
var technologyInterestVerbs = ["","","","","","","","","","","",""];

var socialInterestNouns = ["","","","","","","","","","","",""];
var socialInterestVerbs = ["","","","","","","","","","","",""];

var romanticInterestNouns = ["","","","","","","","","","","",""];
var romanticInterestVerbs = ["","","","","","","","","","","",""];

var academicInterestNouns = ["","","","","","","","","","","",""];
var academicInterestVerbs = ["","","","","","","","","","","",""];

var domesticInterestNouns = ["","","","","","","","","","","",""];
var domesticInterestVerbs = ["","","","","","","","","","","",""];

var terribleInterestNouns = ["","","","","","","","","","","",""];
var terribleInterestVerbs = ["","","","","","","","","","","",""];

var fantasyInterestNouns = ["fake","fakey-fake","lake","game","fame","brandname","","","","","",""];
var fantasyInterestVerbs = ["ache","make","quake","shake","game","shame","maim","tame","","","",""];

var justiceInterestNouns = ["crook","hook","same","game","suicide pill","fire drill","bunch","gun","son","","",""];
var justiceInterestVerbs = ["took","shook","look","kill","ill","aim","blame","hunch","punch","stun","",""];

//http://www.rhymezone.com/r/rhyme.cgi?Word=sun&typeofrhyme=perfect&org1=syl&org2=l&org3=y
//most common rhyming sounds are things like "ack", "ake", "ame", "ill", "uck", "ock", "unk", "ump", "ice", "unk"
var wordsRhymeTown = ["town", "down", "frown", "clown", "brown", "crown", "drown","noun"];
var wordsRhymeJoke = ["bloke","broke","croak","choke","folk","oak","smoke","soak","woke","yolk","yoke","coke", "spoke"];
var wordsRhymeSun = ["bun","fun","gun","son","hun","none","nun","stun","spun","shun","run","won"];
var wordsRhymePunch = ["brunch","punch","lunch","bunch","crunch","hunch","munch","scrunch"];
var wordsRhymeJack = ["jack", "Jack", "black","sack","clack","crack","knack","quack" "snack","smack","yack","attack","backtrack","hijack" "flashback","feedback","payback","soundtrack","wisecrack","throwback" ,"hunchback","horseback","ransack","asscrack","fallback","carjack","megalomaniac"];
var wordsRhymeFake = ["fake","fakey-fake","ache","bake","brake","break","cake","flake","lake","make","quake","shake","snake","wake","take","awake","cupcake","headache","heartache","heartbreak","mistake","piece of cake","emergency break","huge mistake"];
var wordsRhymeGame = ["game", "name","aim","blame","fame","lame","maim","tame","shellgame","shame","video game","pregame","postgame","brandname"];
var wordsRhymeKill = ["ill","kill","chill","drill","grill","shill","quill","will","thrill","swill","anthill","foothill","downhill","landfill","molehill","standstill","treadmill","daffodil","fire drill","pill","sleeping pill","suicide pill"];
var wordsRhymeSick = ["sick","slick","Billious Slick","brick","click","dick","lick","quick","thick","trick","homesick","dipstick","picnic","yardstick","seasick","lunatic","","","",""];
var wordsRhymeBlock = ["block","cock","hawk","gawk","crock","jock","squawk","talk","walk","bedrock","deadlock","gridlock","hemlock","peacock","small talk","sweet talk","laughingstock"];
var wordsRhymeJunk = ["hunk","junk","flunk","drunk","monk","skunk","sunk","debunk","spelunk","punk","funk","hella drunk"];
var wordsRhymeRump = ["rump","plush rump","hunk rump","chump","bump","hug bump","grump","hump","jump","slump","dump","lump"];
var wordsRhymeCrook = ["crook","nook", "cook", "rook","took","look","shook","hook","guidebook","book","songbook","sketchbook", "textbook", "comic book", "gobbledygook", "reference book"]

var noun = "noun";
var verb = "verb";
var rapTemplates = [new RapTemplate("Yo, you must be some kind of ",noun, " sitting there like you think you can ", verb) ];
rapTemplates.push(new RapTemplate("Your ass is grass, you ain't got that ",noun, " you have the worst skills that i ever did ", verb) );
rapTemplates.push(new RapTemplate("I got that  ",noun, " you have no ", noun) );
rapTemplates.push(new RapTemplate("You think you're a ",noun, " but you can't even ", verb) );

//would be so dope to rap about what's happened in the session.
//could read session summary?
//worry about this LATER, and definitely not in this stand alone page.
//instead of just your interests, can use THEIR interests to diss them.  "Yo, you ain't nothing but a piece of cake, a shake and bake."

function RapTemplate(part1, p1Type, part2, p2Type){
	this.part1 = part1;
	this.part1Type = p1Type;
	this.part2 = part2
	this.part2Type = p2Type;

	this.findWordBasedOnPart1AndInterest = function(interest){
		var wordTypeArray = this.matchInterestToWordTypeArray(interest, this.part1Type);
		if(wordTypeArray){
				return getRandomElementFromArray(wordTypeArray);
		}
		return null;
	}
	//grove is interests, and it don't stop. but also like the shitty gamzeetavros rap, each participant is just rapping about their OWN interests
	//and part of why it's so shitty is no common theme.
	this.matchInterestToWordTypeArray = function(interest,type){
		var ret = null;
		console.log(this.part1Type);
		if(comedy_interests.indexOf(interest) != -1 && type == noun){
				ret = comedyInterestNouns;
		}else if(comedy_interests.indexOf(interest) != -1 && type == verb){
			ret = comedyInterestVerbs;
		}else if(athletic_interests.indexOf(interest) != -1 && type == noun){
			ret = athleticInterestNouns;
		}else if(athletic_interests.indexOf(interest) != -1 && type == verb){
			ret = athleticInterestVerbs;
		}
		return ret;
	}

	this.matchWordWithRhymeArray = function(word){
		var ret = null;
		if(wordsRhymeTown.indexOf(word) != -1){
			return wordsRhymeTown;
		}else if(wordsRhymeJoke.indexOf(word) != -1){
			return wordsRhymeJoke;
		}else if(wordsRhymeSun.indexOf(word) != -1){
			return wordsRhymeSun;
		}else if(wordsRhymePunch.indexOf(word) != -1){
			return wordsRhymePunch;
		}
	}

	this.findWordBasedOnPart2AndInterestAndPart1Word = function(interest,word){
		//first, I need to know which set of rhyming words the word falls in.
		var rhyme_array = this.matchWordWithRhymeArray(word);
		//once I know that, see if I can find one of the rhyming words in the interest verb/noun list.
		var wordTypeArray =  this.matchInterestToWordTypeArray(interest, this.part2Type);
		if(rhyme_array){
			var results = intersection(rhyme_array, wordTypeArray);
		}
		if(results && results.length > 0){
			return getRandomElementFromArray(results);
		}
		return null;

	}

}

//http://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript
//really was a good idea on recursiveSlacker's part.
function intersection (a, b) {
  var seen = a.reduce(function (h, k) {
    h[k] = true;
    return h;
  }, {});

  return b.filter(function (k) {
    var exists = seen[k];
    delete seen[k];
    return exists;
  });
}
<commit_msg>more raps<commit_after>//http://www.rhymezone.com/r/rhyme.cgi?Word=back&typeofrhyme=perfect&org1=syl&org2=l&org3=y
//if this seems like it will work, move to random tables. based on recursiveSlacker's idea.
var comedyInterestNouns = ["joke","clown","fun", "folk", "bloke"];
var comedyInterestVerbs = ["joke", "frown", "stun", "soak", "choke", "scrunch", "wisecrack"];

var athleticInterestNouns = ["sun","lunch","crown","yolk"];
var athleticInterestVerbs = ["run","punch", "down", "drown", "soak", "won"];

var musicInterestNouns = ["songbook","hook","feedback","flashback","soundtrack","punk","drunk","","","","",""];
var musicInterestVerbs = ["hook","fame","attack","backtrack","hijack","clack","funk","","","","",""];

var writingInterestNouns = ["rook","reference book","textbook","guidebook","book","hook","swill","quill","daffodil","","",""];
var writingInterestVerbs = ["gobbledygook","shook","look","will","thrill","kill","chill","fire drill","ill","","",""];

var popCultureInterestNouns = ["flashback","megalomaniac","Jack","sack","quack","asscrack","throwback","huge mistake","piece of cake","flake","mistake","game","video game"];
var popCultureInterestVerbs = ["wisecrack","throwback","hoseseback","ransack","take","wake","headache","shake","croak","choke","maim","taim"];

var technologyInterestNouns = ["hack","","","","","","","","","","",""];
var technologyInterestVerbs = ["hijack","atack","hack","smack","","","","","","","",""];

var socialInterestNouns = ["punk","drunk","shame","heartbreak","mistake","fake","","","","","",""];
var socialInterestVerbs = ["blame","fame","brandname","quake","shake","fake","","","","","",""];

var romanticInterestNouns = ["heartbreak","heartache","fake","snake","flake","crock","punk","drunk","hunk","junk","fun","dick"];
var romanticInterestVerbs = ["heartbreak","sweet talk","talk","walk","stun","fun","sick","click","trick","lick","",""];

var academicInterestNouns = ["reference book","book","guidebook","reference book","lunatic","dipstick","brick","jock","laughingstock","quack","junk","monk"];
var academicInterestVerbs = ["trick","look","took","shook","small talk","squawk","block","backtrack","yack","attack","crack","smack", "debunk"];

var domesticInterestNouns = ["cake","piece of cake","cupcake","snake","mistake","huge mistake","flake","crock","cock","peacock","laughingstock","shell", "brandname"];
var domesticInterestVerbs = ["bake","shake","wake","heartbreak","small talk","gawk","squawk","block","shellgame","maim","tame","aim"];

var terribleInterestNouns = ["pill","suicide pill","shill","swill","landfill","molehill","standstill","plush rump","hunk rump","rump","chump","snake", "asscrack"];
var terribleInterestVerbs = ["kill","ill","drill","grill","dick","lick","trick","bump","hump","hug bump","take","wake","payback"];

var fantasyInterestNouns = ["fake","fakey-fake","lake","game","fame","brandname","","","","","",""];
var fantasyInterestVerbs = ["ache","make","quake","shake","game","shame","maim","tame","","","",""];

var justiceInterestNouns = ["crook","hook","same","game","suicide pill","fire drill","bunch","gun","son","hunch","",""];
var justiceInterestVerbs = ["took","shook","look","kill","ill","aim","blame","hunch","punch","stun","",""];

//http://www.rhymezone.com/r/rhyme.cgi?Word=sun&typeofrhyme=perfect&org1=syl&org2=l&org3=y
//most common rhyming sounds are things like "ack", "ake", "ame", "ill", "uck", "ock", "unk", "ump", "ice", "unk"
var wordsRhymeTown = ["town", "down", "frown", "clown", "brown", "crown", "drown","noun"];
var wordsRhymeJoke = ["bloke","broke","croak","choke","folk","oak","smoke","soak","woke","yolk","yoke","coke", "spoke"];
var wordsRhymeSun = ["bun","fun","gun","son","hun","none","nun","stun","spun","shun","run","won"];
var wordsRhymePunch = ["brunch","punch","lunch","bunch","crunch","hunch","munch","scrunch"];
var wordsRhymeJack = ["jack", "hack","Jack", "black","sack","clack","crack","knack","quack" "snack","smack","yack","attack","backtrack","hijack" "flashback","feedback","payback","soundtrack","wisecrack","throwback" ,"hunchback","horseback","ransack","asscrack","fallback","carjack","megalomaniac"];
var wordsRhymeFake = ["fake","fakey-fake","ache","bake","brake","break","cake","flake","lake","make","quake","shake","snake","wake","take","awake","cupcake","headache","heartache","heartbreak","mistake","piece of cake","emergency break","huge mistake"];
var wordsRhymeGame = ["game", "name","aim","blame","fame","lame","maim","tame","shellgame","shame","video game","pregame","postgame","brandname"];
var wordsRhymeKill = ["ill","kill","chill","drill","grill","shill","quill","will","thrill","swill","anthill","foothill","downhill","landfill","molehill","standstill","treadmill","daffodil","fire drill","pill","sleeping pill","suicide pill"];
var wordsRhymeSick = ["sick","slick","Billious Slick","brick","click","dick","lick","quick","thick","trick","homesick","dipstick","picnic","yardstick","seasick","lunatic","","","",""];
var wordsRhymeBlock = ["block","cock","hawk","gawk","crock","jock","squawk","talk","walk","bedrock","deadlock","gridlock","hemlock","peacock","small talk","sweet talk","laughingstock"];
var wordsRhymeJunk = ["hunk","junk","flunk","drunk","monk","skunk","sunk","debunk","spelunk","punk","funk","hella drunk"];
var wordsRhymeRump = ["rump","plush rump","hunk rump","chump","bump","hug bump","grump","hump","jump","slump","dump","lump"];
var wordsRhymeCrook = ["crook","nook", "cook", "rook","took","look","shook","hook","guidebook","book","songbook","sketchbook", "textbook", "comic book", "gobbledygook", "reference book"]

var noun = "noun";
var verb = "verb";
var rapTemplates = [new RapTemplate("Yo, you must be some kind of ",noun, " sitting there like you think you can ", verb) ];
rapTemplates.push(new RapTemplate("Your ass is grass, you ain't got that ",noun, " you have the worst skills that i ever did ", verb) );
rapTemplates.push(new RapTemplate("I got that  ",noun, " you have no ", noun) );
rapTemplates.push(new RapTemplate("You think you're a ",noun, " but you can't even ", verb) );

//would be so dope to rap about what's happened in the session.
//could read session summary?
//worry about this LATER, and definitely not in this stand alone page.
//instead of just your interests, can use THEIR interests to diss them.  "Yo, you ain't nothing but a piece of cake, a shake and bake."

function RapTemplate(part1, p1Type, part2, p2Type){
	this.part1 = part1;
	this.part1Type = p1Type;
	this.part2 = part2
	this.part2Type = p2Type;

	this.findWordBasedOnPart1AndInterest = function(interest){
		var wordTypeArray = this.matchInterestToWordTypeArray(interest, this.part1Type);
		if(wordTypeArray){
				return getRandomElementFromArray(wordTypeArray);
		}
		return null;
	}
	//grove is interests, and it don't stop. but also like the shitty gamzeetavros rap, each participant is just rapping about their OWN interests
	//and part of why it's so shitty is no common theme.
	this.matchInterestToWordTypeArray = function(interest,type){
		var ret = null;
		console.log(this.part1Type);
		if(comedy_interests.indexOf(interest) != -1 && type == noun){
				ret = comedyInterestNouns;
		}else if(comedy_interests.indexOf(interest) != -1 && type == verb){
			ret = comedyInterestVerbs;
		}else if(athletic_interests.indexOf(interest) != -1 && type == noun){
			ret = athleticInterestNouns;
		}else if(athletic_interests.indexOf(interest) != -1 && type == verb){
			ret = athleticInterestVerbs;
		}
		return ret;
	}

	this.matchWordWithRhymeArray = function(word){
		var ret = null;
		if(wordsRhymeTown.indexOf(word) != -1){
			return wordsRhymeTown;
		}else if(wordsRhymeJoke.indexOf(word) != -1){
			return wordsRhymeJoke;
		}else if(wordsRhymeSun.indexOf(word) != -1){
			return wordsRhymeSun;
		}else if(wordsRhymePunch.indexOf(word) != -1){
			return wordsRhymePunch;
		}
	}

	this.findWordBasedOnPart2AndInterestAndPart1Word = function(interest,word){
		//first, I need to know which set of rhyming words the word falls in.
		var rhyme_array = this.matchWordWithRhymeArray(word);
		//once I know that, see if I can find one of the rhyming words in the interest verb/noun list.
		var wordTypeArray =  this.matchInterestToWordTypeArray(interest, this.part2Type);
		if(rhyme_array){
			var results = intersection(rhyme_array, wordTypeArray);
		}
		if(results && results.length > 0){
			return getRandomElementFromArray(results);
		}
		return null;

	}

}

//http://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript
//really was a good idea on recursiveSlacker's part.
function intersection (a, b) {
  var seen = a.reduce(function (h, k) {
    h[k] = true;
    return h;
  }, {});

  return b.filter(function (k) {
    var exists = seen[k];
    delete seen[k];
    return exists;
  });
}
<|endoftext|>


<commit_before>"use strict"

var cluster = require('cluster');
var fs = require("fs")

if (cluster.isMaster) {

	//mssDb 1604 test for a lot of MMS items w/ no component matches

	var archivesSeralize = require("../lib/serialize_archives_resources_utils.js")
	var serializeUtils = require("../lib/serialize_utils.js")
	var clc = require('cli-color')
	var async = require("async")

	var botCount = 10, activeBotCount = 0
	var activeRegistryID = 100000000
	var addToDbWorkQueue = []
	var workingQueue = false
	var objectsCommitedCount = 0, collectionsCompletedCount = 0

	//the data back from the bots gets added to this queue, it enumerates them with a registry ID and then commits them to the object store
	setInterval(function(){

		process.stdout.cursorTo(0)
		process.stdout.write(clc.black.bgGreenBright("serialize Archives | bots: " + activeBotCount + " queue:" + addToDbWorkQueue.length + " objects: " + objectsCommitedCount + " id: " + activeRegistryID + " cols.: " +  collectionsCompletedCount))

		if (workingQueue){
			return false
		}else{
			workingQueue = true
		}

		if (addToDbWorkQueue.length===0){
			workingQueue = false
			return false
		}

		var objects = addToDbWorkQueue[0]
		addToDbWorkQueue.shift()

		var enumerated = serializeUtils.enumerateObjects(objects,activeRegistryID)

		activeRegistryID = enumerated.registryId

		for (var x = 0; x < (enumerated.objects.length/1000) + 1; x++){

			process.nextTick(function( ){
				var batch = enumerated.objects.splice(0,1000)
				if (batch.length>0){
					archivesSeralize.getBulk(function(bulk){
						batch.forEach(function(b){
							bulk.insert(b)
						})
						bulk.execute()
					})
				}
			})
		}

		workingQueue = false

	},10)

	archivesSeralize.returnAllCollectionIds(function(collectionIds){

		var getWork = function(){
			if (collectionIds.length == 0){
				return "die"
			}
			var record = JSON.parse(JSON.stringify(collectionIds[0]._id))
			//delete this one
			collectionIds.shift()
			return record
		}

		var buildWorker = function(){

			var worker = cluster.fork();
			console.log('Spawing worker:',worker.id)

			worker.on('message', function(msg) {
				//asking for work
				if (msg.request){
					worker.send({ work: getWork() })
				}
				//returning results
				if (msg.results){

					if (typeof msg.results == 'string'){
						var c = 0, allObjects = []
						file.streamJsonFile(msg.results, function(record,recordCb){
							if (record){
								//console.log("Reading large file",c++)
								allObjects.push(record)
								recordCb()
							}else{
								addToDbWorkQueue.push( allObjects )
							}
						})

					}else{
						addToDbWorkQueue.push( msg.results )
					}

					collectionsCompletedCount++

				}
			})

			//send the first one
			worker.send({ work: getWork() })
			activeBotCount++

		}

		for (var i = 1; i <= botCount; i++) {
			setTimeout(function(){
				buildWorker()
			}, Math.floor(Math.random() * (10000 - 0)))
		}

	})

	cluster.on('disconnect', function(worker, code, signal) {
		activeBotCount = Object.keys(cluster.workers).length
		if (Object.keys(cluster.workers).length < 3){
			setInterval(function(){
				if (addToDbWorkQueue.length===0 && Object.keys(cluster.workers).length == 1){
					process.exit()
				}
			},10000)
		}
	})

} else {

	var archivesSeralize = require("../lib/serialize_archives_resources_utils.js")

	// var mmsMappingStrategies = require("../lib/mms_mapping_strategies.js")

	var processRecord = function(msg){

		if (msg.work){

			if (msg.work==="die"){
				console.log("No more work, I'm leaving. 😵")
				cluster.worker.disconnect()
				process.exit()
			}

			// mmsMappingStrategies.returnMmsCollectionDetails(record,function(err,data){

			archivesSeralize.serializeArchives(msg.work,function(objects){

				if (objects.length>10000){

					var file = fs.createWriteStream("data/temp/archives"+msg.work+'.ndjson')
					file.on('error', function(err) { console.log(err) })
					file.on('finish', function () {
						process.send({ results: "data/temp/archives"+msg.work+'.ndjson' })
						process.send({ request: true })
					})
					var c = 0
					objects.forEach(function(o) { file.write( JSON.stringify(o) + '\n') })
					file.end()

				}else{

					process.send({ results: objects })
					process.send({ request: true })

				}

			})
		}

	}

	process.on('message', processRecord)

}
<commit_msg>mms ser. test<commit_after>"use strict"

var cluster = require('cluster');
var fs = require("fs")

if (cluster.isMaster) {

	//mssDb 1604 test for a lot of MMS items w/ no component matches

	var archivesSeralize = require("../lib/serialize_archives_resources_utils.js")
	var serializeUtils = require("../lib/serialize_utils.js")
	var clc = require('cli-color')
	var async = require("async")
	var file = require("../lib/file.js")

	var botCount = 10, activeBotCount = 0
	var activeRegistryID = 100000000
	var addToDbWorkQueue = []
	var workingQueue = false
	var objectsCommitedCount = 0, collectionsCompletedCount = 0

	//the data back from the bots gets added to this queue, it enumerates them with a registry ID and then commits them to the object store
	setInterval(function(){

		process.stdout.cursorTo(0)
		process.stdout.write(clc.black.bgGreenBright("serialize Archives | bots: " + activeBotCount + " queue:" + addToDbWorkQueue.length + " objects: " + objectsCommitedCount + " id: " + activeRegistryID + " cols.: " +  collectionsCompletedCount))

		if (workingQueue){
			return false
		}else{
			workingQueue = true
		}

		if (addToDbWorkQueue.length===0){
			workingQueue = false
			return false
		}

		var objects = addToDbWorkQueue[0]
		addToDbWorkQueue.shift()

		var enumerated = serializeUtils.enumerateObjects(objects,activeRegistryID)

		activeRegistryID = enumerated.registryId

		for (var x = 0; x < (enumerated.objects.length/1000) + 1; x++){

			process.nextTick(function( ){
				var batch = enumerated.objects.splice(0,1000)
				if (batch.length>0){
					archivesSeralize.getBulk(function(bulk){
						batch.forEach(function(b){
							bulk.insert(b)
						})
						bulk.execute()
					})
				}
			})
		}

		workingQueue = false

	},10)

	archivesSeralize.returnAllCollectionIds(function(collectionIds){

		var getWork = function(){
			if (collectionIds.length == 0){
				return "die"
			}
			var record = JSON.parse(JSON.stringify(collectionIds[0]._id))
			//delete this one
			collectionIds.shift()
			return record
		}

		var buildWorker = function(){

			var worker = cluster.fork();
			console.log('Spawing worker:',worker.id)

			worker.on('message', function(msg) {
				//asking for work
				if (msg.request){
					worker.send({ work: getWork() })
				}
				//returning results
				if (msg.results){

					if (typeof msg.results == 'string'){
						var c = 0, allObjects = []
						file.streamJsonFile(msg.results, function(record,recordCb){
							if (record){
								//console.log("Reading large file",c++)
								allObjects.push(record)
								recordCb()
							}else{
								addToDbWorkQueue.push( allObjects )
							}
						})

					}else{
						addToDbWorkQueue.push( msg.results )
					}

					collectionsCompletedCount++

				}
			})

			//send the first one
			worker.send({ work: getWork() })
			activeBotCount++

		}

		for (var i = 1; i <= botCount; i++) {
			setTimeout(function(){
				buildWorker()
			}, Math.floor(Math.random() * (10000 - 0)))
		}

	})

	cluster.on('disconnect', function(worker, code, signal) {
		activeBotCount = Object.keys(cluster.workers).length
		if (Object.keys(cluster.workers).length < 3){
			setInterval(function(){
				if (addToDbWorkQueue.length===0 && Object.keys(cluster.workers).length == 1){
					process.exit()
				}
			},10000)
		}
	})

} else {

	var archivesSeralize = require("../lib/serialize_archives_resources_utils.js")

	// var mmsMappingStrategies = require("../lib/mms_mapping_strategies.js")

	var processRecord = function(msg){

		if (msg.work){

			if (msg.work==="die"){
				console.log("No more work, I'm leaving. 😵")
				cluster.worker.disconnect()
				process.exit()
			}

			// mmsMappingStrategies.returnMmsCollectionDetails(record,function(err,data){

			archivesSeralize.serializeArchives(msg.work,function(objects){

				if (objects.length>10000){

					var file = fs.createWriteStream("data/temp/archives"+msg.work+'.ndjson')
					file.on('error', function(err) { console.log(err) })
					file.on('finish', function () {
						process.send({ results: "data/temp/archives"+msg.work+'.ndjson' })
						process.send({ request: true })
					})
					var c = 0
					objects.forEach(function(o) { file.write( JSON.stringify(o) + '\n') })
					file.end()

				}else{

					process.send({ results: objects })
					process.send({ request: true })

				}

			})
		}

	}

	process.on('message', processRecord)

}
<|endoftext|>


<commit_before>/**
 * argv.js
 * client arguments & defaults
 */

var
	fs = require('fs')
	, path = require('path')
	, banner = fs.readFileSync(
		path.resolve(
			__dirname
			, 'banner'
		)
	)
	, defaults
	, argv
;

if (process.env.NODE_ENV === "development") {

	defaults = {

		cloudHost : "127.0.0.1"
		, streamHost : "127.0.0.1"
		, apiHost : "127.0.0.1"
		, logFile : path.resolve(process.env.PWD, 'ninjablock.log')
		, updateLock : path.resolve(process.env.PWD, '.has_updated')
		, serialFile : path.resolve(process.env.PWD, 'serial-development.conf')
		, tokenFile : path.resolve(process.env.PWD, 'token-development.conf')
		, env : 'development'
		, streamPort : 3003
		, cloudPort : 3001
		, apiPort : 3000
		, secure : false
		, debug : true
		, client : process.env.NINJA_CLIENT_NAME
	}
}
else if (process.env.NODE_ENV === "hacking") {

	defaults = {
		cloudHost : "zendo.ninja.is"
		, apiHost : "api.ninja.is"
		, streamHost : "stream.ninja.is"
		, logFile : path.resolve(process.env.PWD, 'ninjablock.log')
		, updateLock : path.resolve(process.env.PWD, '.has_updated')
		, serialFile : path.resolve(process.env.PWD, 'serial-hacking.conf')
		, tokenFile : path.resolve(process.env.PWD, 'token-hacking.conf')
		, env : 'hacking'
		, streamPort : 443
		, cloudPort : 443
		, apiPort : 443
		, secure : true
		, debug : true
		, client : process.env.NINJA_CLIENT_NAME
	}
}
else if (process.env.NODE_ENV === "beta") {

	defaults = {
		cloudHost : "wakai-zendo.ninja.is"
		, apiHost : "wakai.ninja.is"
		, streamHost : "wakai-stream.ninja.is"
		, logFile : path.resolve(process.env.PWD, 'ninjablock.log')
		, updateLock : path.resolve(process.env.PWD, '.has_updated')
		, serialFile : path.resolve(process.env.PWD, 'serial-beta.conf')
		, tokenFile : path.resolve(process.env.PWD, 'token-beta.conf')
		, env : 'beta'
		, streamPort : 443
		, cloudPort : 443
		, apiPort : 443
		, secure : true
		, debug : true
		, client : process.env.NINJA_CLIENT_NAME
	}
}
else {

	defaults = {

		cloudHost : "zendo.ninja.is"
		, streamHost : "stream.ninja.is"
		, apiHost : "api.ninja.is"
		, logFile : '/var/log/ninjablock.log'
		, updateLock : '/etc/opt/ninja/.has_updated'
		, serialFile : '/etc/opt/ninja/serial.conf'
		, tokenFile : '/etc/opt/ninja/token.conf'
		, env : 'production'
		, streamPort : 443
		, cloudPort : 443
		, apiPort : 443
		, secure : true
		, debug : false
		, client : process.env.NINJA_CLIENT_NAME
	}
	if(!process.env.NODE_ENV) { process.env.NODE_ENV = "production"; }
}

argv = require('optimist')

	.usage(

		[	banner
			, "This process requires certain parameters to run."
			, "Please see usage information below."
			, ""
			, "Example: $0 --devicePath /dev/tty.usb*B"
		].join("\n")
	)
	.default(defaults)
	.boolean('secure')
	.boolean('debug')
	.argv
;

module.exports = argv;
<commit_msg>Replace process.env.PWD with __dirname+'../'<commit_after>/**
 * argv.js
 * client arguments & defaults
 */

var
	fs = require('fs')
	, path = require('path')
	, banner = fs.readFileSync(
		path.resolve(
			__dirname
			, 'banner'
		)
	)
	, defaults
	, argv
  , join = path.join
;

if (process.env.NODE_ENV === "development") {

	defaults = {

		cloudHost : "127.0.0.1"
		, streamHost : "127.0.0.1"
		, apiHost : "127.0.0.1"
		, logFile : join(__dirname, '..', 'ninjablock.log')
		, updateLock : join(__dirname, '..', '.has_updated')
		, serialFile : join(__dirname, '..', 'serial-development.conf')
		, tokenFile : join(__dirname, '..', 'token-development.conf')
		, env : 'development'
		, streamPort : 3003
		, cloudPort : 3001
		, apiPort : 3000
		, secure : false
		, debug : true
		, client : process.env.NINJA_CLIENT_NAME
	}
}
else if (process.env.NODE_ENV === "hacking") {

	defaults = {
		cloudHost : "zendo.ninja.is"
		, apiHost : "api.ninja.is"
		, streamHost : "stream.ninja.is"
		, logFile : join(__dirname, '..', 'ninjablock.log')
		, updateLock : join(__dirname, '..', '.has_updated')
		, serialFile : join(__dirname, '..', 'serial-hacking.conf')
		, tokenFile : join(__dirname, '..', 'token-hacking.conf')
		, env : 'hacking'
		, streamPort : 443
		, cloudPort : 443
		, apiPort : 443
		, secure : true
		, debug : true
		, client : process.env.NINJA_CLIENT_NAME
	}
}
else if (process.env.NODE_ENV === "beta") {

	defaults = {
		cloudHost : "wakai-zendo.ninja.is"
		, apiHost : "wakai.ninja.is"
		, streamHost : "wakai-stream.ninja.is"
		, logFile : join(__dirname, '..', 'ninjablock.log')
		, updateLock : join(__dirname, '..', '.has_updated')
		, serialFile : join(__dirname, '..', 'serial-beta.conf')
		, tokenFile : join(__dirname, '..', 'token-beta.conf')
		, env : 'beta'
		, streamPort : 443
		, cloudPort : 443
		, apiPort : 443
		, secure : true
		, debug : true
		, client : process.env.NINJA_CLIENT_NAME
	}
}
else {

	defaults = {

		cloudHost : "zendo.ninja.is"
		, streamHost : "stream.ninja.is"
		, apiHost : "api.ninja.is"
		, logFile : '/var/log/ninjablock.log'
		, updateLock : '/etc/opt/ninja/.has_updated'
		, serialFile : '/etc/opt/ninja/serial.conf'
		, tokenFile : '/etc/opt/ninja/token.conf'
		, env : 'production'
		, streamPort : 443
		, cloudPort : 443
		, apiPort : 443
		, secure : true
		, debug : false
		, client : process.env.NINJA_CLIENT_NAME
	}
	if(!process.env.NODE_ENV) { process.env.NODE_ENV = "production"; }
}

argv = require('optimist')

	.usage(

		[	banner
			, "This process requires certain parameters to run."
			, "Please see usage information below."
			, ""
			, "Example: $0 --devicePath /dev/tty.usb*B"
		].join("\n")
	)
	.default(defaults)
	.boolean('secure')
	.boolean('debug')
	.argv
;

module.exports = argv;
<|endoftext|>


<commit_before>function DatasetPopularController($scope, $location, rest, $rootScope, $sce, usSpinnerService) {
    usSpinnerService.spin('spinner');
    $rootScope.countQuery ++;
    $scope.showPopularCategories = false;
    $scope.totalStatistics = 0;
    $scope.letterLimit = 4;
    $scope.hideCategoriesSidebar = function () {
        $rootScope.showBackdrop = false;
        $rootScope.showCategoriesSidebar = false;
    };

    $scope.popularCategories = angular.copy($scope.popCats);

    var loadPorcentual = function (categories) {
        rest().statistics({
            type: "datasets",
            params: "groupBy=category&action=download"
        }, function (statistics) {

        // TODO: recieve total from API
            for (element in statistics.data) {
                $scope.totalStatistics += statistics.data[element].count.GET;
            }

            for (var i = 0; i < categories.length; i++) {
              if (!!statistics.data[categories[i].id]) {
                categories[i]['porcentaje'] = statistics.data[categories[i].id].count.GET * 100 / $scope.totalStatistics;
              }
            }

            categories.sort(function (a, b) {
                return b['porcentaje'] - a['porcentaje'];
            });

            $scope.showPopularCategories = true;
            $rootScope.countQuery --;
            if($rootScope.countQuery == 0) { usSpinnerService.stop('spinner'); }
        }, function (error) {
            $scope.showPopularCategories = true;
            $rootScope.countQuery --;
            if($rootScope.countQuery == 0) { usSpinnerService.stop('spinner'); }
        });
    };

    loadPorcentual($scope.popularCategories);
}
<commit_msg>refactor dataset statistics<commit_after>function DatasetPopularController($scope, $location, rest, $rootScope, $sce, usSpinnerService) {
    usSpinnerService.spin('spinner');
    $rootScope.countQuery ++;
    $scope.showPopularCategories = false;
    $scope.totalStatistics = 0;
    $scope.letterLimit = 4;
    $scope.hideCategoriesSidebar = function () {
        $rootScope.showBackdrop = false;
        $rootScope.showCategoriesSidebar = false;
    };

    $scope.popularCategories = angular.copy($scope.popCats);

    var loadPorcentual = function (categories) {
        rest().statistics({
            type: "datasets",
            params: "groupBy=category&action=download"
        }, function (statistics) {

        // TODO: recieve total from API odin
            for (element in statistics.data) {
                $scope.totalStatistics += statistics.data[element].count.GET;
            }

            for (var i = 0; i < categories.length; i++) {
              if (!!statistics.data[categories[i].id]) {
                categories[i]['porcentaje'] = statistics.data[categories[i].id].count.GET * 100 / $scope.totalStatistics;
              }
            }

            categories.sort(function (a, b) {
                return b['porcentaje'] - a['porcentaje'];
            });

            $scope.showPopularCategories = true;
            $rootScope.countQuery --;
            if($rootScope.countQuery == 0) { usSpinnerService.stop('spinner'); }
        }, function (error) {
            $scope.showPopularCategories = true;
            $rootScope.countQuery --;
            if($rootScope.countQuery == 0) { usSpinnerService.stop('spinner'); }
        });
    };

    loadPorcentual($scope.popularCategories);
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');

module.exports = {
    dump: dump
};

function getId (n) {
    return '@' + n;
}

var isPrimitive = _.curry(function isPrimitive (obj, prop) {
    return !_.isObject(obj[prop]);
});

var isNotPrimitive = _.curry(function isNotPrimitive (obj, prop) {
    return _.isObject(obj[prop]);
});

var clone = _.curry(function clone (target, src, prop) {
    // console.log('prop:', prop);
    target[prop] = src[prop];
});

function clonePrimitives (target, obj) {
    Object
        .keys(obj)
        .filter(isPrimitive(obj))
        .forEach(clone(target, obj))
    ;

    return target;
}

function dump (src) {
    var serialized = {};
    var unprocessed = new Map();
    var identities = new Map();
    var id = 0;
    var key = getId(id);

    if (src == null) return;

    _dump(serialized, unprocessed, src, key);

    var entries = unprocessed.entries();
    var entry;

    while ((entry = entries.next(), !entry.done)) {
        var obj = entry.value[0];
        var objId = entry.value[1];

        _dump(serialized, unprocessed, obj, objId);
    }

    function _dump (serialized, unprocessed, obj, key) {
        if (!identities.has(obj)) identities.set(obj, key);

        if (_.isArray(obj)) {
            serialized[key] = [];

            obj.map(function (item, index) {
                if (isPrimitive(obj, index)) {
                    serialized[key].push(item);
                } else {
                    var propId;

                    if (!identities.has(obj[index])) {
                        propId = getId(++id);
                        unprocessed.set(obj[index], propId);
                    } else {
                        propId = identities.get(obj[index]);
                    }

                    serialized[key].push(propId);
                }
            });
        } else {
            serialized[key] = clonePrimitives({}, obj);

            var objs = Object
                .keys(obj)
                .filter(isNotPrimitive(obj))
                .reduce(function (result, prop) {
                    var propId;

                    if (!identities.has(obj[prop])) {
                        propId = getId(++id);
                        unprocessed.set(obj[prop], propId);
                    } else {
                        propId = identities.get(obj[prop]);
                    }

                    result[prop] = propId;

                    return result;
                }, {})
            ;
            _.extend(serialized[key], objs);
        }
    }

    return JSON.stringify(serialized);
}
<commit_msg>Refactoring in progress<commit_after>'use strict';

var _ = require('lodash');

module.exports = {
    dump: dump
};

function getId (n) {
    return '@' + n;
}

var isPrimitive = _.curry(function isPrimitive (obj, prop) {
    return !_.isObject(obj[prop]);
});

var isNotPrimitive = _.curry(function isNotPrimitive (obj, prop) {
    return _.isObject(obj[prop]);
});

var clone = _.curry(function clone (target, src, prop) {
    // console.log('prop:', prop);
    target[prop] = src[prop];
});

function clonePrimitives (target, obj) {
    Object
        .keys(obj)
        .filter(isPrimitive(obj))
        .forEach(clone(target, obj))
    ;

    return target;
}

function dump (src) {
    var serialized = {};
    var unprocessed = new Map();
    var identities = new Map();
    var id = 0;
    var key = getId(id);

    if (src == null) return;

    _dump(serialized, unprocessed, src, key);

    var entries = unprocessed.entries();
    var entry;

    while ((entry = entries.next(), !entry.done)) {
        var obj = entry.value[0];
        var objId = entry.value[1];

        _dump(serialized, unprocessed, obj, objId);
    }

    function foobar (unprocessed, identities,   obj, prop) {
        var propId;

        if (!identities.has(obj[prop])) {
            propId = getId(++id);
            unprocessed.set(obj[prop], propId);
        } else {
            propId = identities.get(obj[prop]);
        }

        return propId;
    }

    function destruct (result, item, index) {
        var prop = _.isArray(result) ? index : item;
        if (isPrimitive(obj, prop)) {
            result[prop] = obj[prop];
        } else {
            result[prop] = foobar(unprocessed, identities, obj, prop);
        }

        return result[prop];
    }

    function _dump (serialized, unprocessed, obj, key) {
        if (!identities.has(obj)) identities.set(obj, key);

        if (_.isArray(obj)) {
            serialized[key] = obj.reduce(function (result, item, prop) {

                return destruct(result, item, prop);
            }, []);
        } else {
            serialized[key] = Object
                .keys(obj)
                .reduce(function (result, prop) {
                    if (isPrimitive(obj, prop)) {
                        result[prop] = obj[prop];
                    } else {
                        result[prop] = foobar(unprocessed, identities, obj, prop);
                    }

                    return result;
                }, {})
            ;
        }
    }

    return JSON.stringify(serialized);
}
<|endoftext|>


<commit_before>/*   Riassence Framework
 *   Copyright 2008 Riassence Inc.
 *   http://riassence.com/
 *
 *   You should have received a copy of the GNU General Public License along
 *   with this software package. If not, contact licensing@riassence.com
 */

HValidatorView = HControl.extend({

  constructor: function(_rect, _parent, _options) {
    if(_options !== undefined){
      if(_options.valueField && _options.valueField.componentBehaviour[1] === 'control'){
        _rect.offsetTo(
          _options.valueField.rect.right,
          _options.valueField.rect.top
        );
      }
    }
    this.base(_rect, _parent, _options);
  },

/** = Description
  * Ensures the value set is a Boolean.
  *
  * = Parameters
  * +_flag+::   True to set the status to selected, false to set to unselected.
  *
  **/
  setValue: function(_flag) {
    if (!_flag && _flag !== false) {
      _flag = false;
    }
    this.base(_flag);
  },

/** = Description
  * Updates the graphics to match the Boolean value.
  *
  **/
  refreshValue: function(){
    var _this = this,
        _value = _this.value,
        _trueValue = _value === true,
        _x = _trueValue?-21:0,
        _y = _this.enabled?0:-21,
        _title = _trueValue?'':_value,
        _elemId = _this.elemId;
    ELEM.setStyle(_elemId,'background-image',"url("+_this.getThemeGfxFile('validator.png')+")");
    ELEM.setStyle(_elemId,'background-repeat','no-repeat');
    ELEM.setStyle(_elemId,'background-position',_x+'px '+_y+'px');
  }

});
<commit_msg>Added default value: false<commit_after>/*   Riassence Framework
 *   Copyright 2008 Riassence Inc.
 *   http://riassence.com/
 *
 *   You should have received a copy of the GNU General Public License along
 *   with this software package. If not, contact licensing@riassence.com
 */

HValidatorView = HControl.extend({

  controlDefaults: (HControlDefaults.extend({
    value: false
  })),

  constructor: function(_rect, _parent, _options) {
    if(_options !== undefined){
      if(_options.valueField && _options.valueField.componentBehaviour[1] === 'control'){
        _rect.offsetTo(
          _options.valueField.rect.right,
          _options.valueField.rect.top
        );
      }
    }
    this.base(_rect, _parent, _options);
  },

/** = Description
  * Ensures the value set is a Boolean.
  *
  * = Parameters
  * +_flag+::   True to set the status to selected, false to set to unselected.
  *
  **/
  setValue: function(_flag) {
    if (!_flag && _flag !== false) {
      _flag = false;
    }
    this.base(_flag);
  },

/** = Description
  * Updates the graphics to match the Boolean value.
  *
  **/
  refreshValue: function(){
    var _this = this,
        _value = _this.value,
        _trueValue = _value === true,
        _x = _trueValue?-21:0,
        _y = _this.enabled?0:-21,
        _title = _trueValue?'':_value,
        _elemId = _this.elemId;
    ELEM.setStyle(_elemId,'background-image',"url("+_this.getThemeGfxFile('validator.png')+")");
    ELEM.setStyle(_elemId,'background-repeat','no-repeat');
    ELEM.setStyle(_elemId,'background-position',_x+'px '+_y+'px');
  }

});
<|endoftext|>


<commit_before>/**
 * Developer: Grigory Kuznetsov
 * Date: 07/16/2015
 * Copyright: 2009-2016 Comindware®
 *       All Rights Reserved
 * Published under the MIT license
 */

"use strict";

import { moment } from '../../libApi';
import template from './templates/dateTimeEditor.hbs';
import BaseLayoutEditorView from './base/BaseLayoutEditorView';
import DateView from './impl/dateTime/views/DateView';
import TimeView from './impl/dateTime/views/TimeView';

const defaultOptions = {
    enableDelete: false,
    timezoneOffset: -new Date().getTimezoneOffset()
};

/**
 * @name DateTimeEditorView
 * @memberof module:core.form.editors
 * @class Combined date and time editor. Supported data type: String in ISO8601 format
 * (for example, '2015-07-20T10:46:37Z').
 * @extends module:core.form.editors.base.BaseEditorView
 * @param {Object} options Options object.
 * All the properties of {@link module:core.form.editors.base.BaseEditorView BaseEditorView} class are also supported.
 * @param {Number} options.timezoneOffset - Number of minutes representing timezone offset.
 * E.g. for UTC+3 enter 180. Negative values allowed. Defaults to browser (system) local timezone offset.
 * */
Backbone.Form.editors.DateTime = BaseLayoutEditorView.extend(/** @lends module:core.form.editors.DateTimeEditorView.prototype */{
    initialize: function(options) {
        options = options || {};
        if (options.schema) {
            _.extend(this.options, defaultOptions, _.pick(options.schema, _.keys(defaultOptions)));
        } else {
            _.extend(this.options, defaultOptions, _.pick(options || {}, _.keys(defaultOptions)));
        }

        var readonly = this.getReadonly(),
            enabled = this.getEnabled();

        this.dateTimeModel = new Backbone.Model({
            value: this.value,
            readonly: readonly,
            enabled: enabled
        });

        this.listenTo(this.dateTimeModel, 'change:value', this.__change, this);
    },

    ui: {
        deleteButton: '.js-clear-button'
    },

    events: {
        'click @ui.deleteButton': '__onClear'
    },

    regions: {
        dateRegion: '.js-date-region',
        timeRegion: '.js-time-region'
    },

    className: 'l-field date-time',

    template: template,

    templateHelpers: function () {
        return this.options;
    },

    __change: function () {
        this.__value(this.dateTimeModel.get('value'), true, true);
        this.updateDelete();
    },

    setValue: function (value) {
        this.__value(value, true, false);
        this.dateTimeModel.set('value', value);
    },

    getValue: function () {
        return this.value === null ? this.value : moment(this.value).toISOString();
    },

    onRender: function () {
        this.dateView = new DateView({
            model: this.dateTimeModel,
            timezoneOffset: this.options.timezoneOffset,
            preserveTime: true
        });

        this.timeView = new TimeView({
            model: this.dateTimeModel,
            timezoneOffset: this.options.timezoneOffset
        });

        this.dateRegion.show(this.dateView);
        this.timeRegion.show(this.timeView);
        this.updateDelete();
    },

    updateDelete: function() {
        if (!this.options.enableDelete || !this.getValue()) {
            this.ui.deleteButton.hide();
        } else {
            this.ui.deleteButton.show();
        }
    },

    __value: function (value, updateUi, triggerChange) {
        if (this.value === value) {
            return;
        }
        this.value = value;

        if (triggerChange) {
            this.__triggerChange();
        }
    },

    __setEnabled: function (enabled) {
        BaseLayoutEditorView.prototype.__setEnabled.call(this, enabled);
        this.dateTimeModel.set({enabled: this.getEnabled()});
    },

    __setReadonly: function (readonly) {
        BaseLayoutEditorView.prototype.__setReadonly.call(this, readonly);
        this.dateTimeModel.set({readonly: this.getReadonly()});
    },

    __onClear: function() {
        this.__value(null, true, true);
        this.dateTimeModel.set('value', null);
    }
});

export default Backbone.Form.editors.DateTime;
<commit_msg>documented missed option<commit_after>/**
 * Developer: Grigory Kuznetsov
 * Date: 07/16/2015
 * Copyright: 2009-2016 Comindware®
 *       All Rights Reserved
 * Published under the MIT license
 */

"use strict";

import { moment } from '../../libApi';
import template from './templates/dateTimeEditor.hbs';
import BaseLayoutEditorView from './base/BaseLayoutEditorView';
import DateView from './impl/dateTime/views/DateView';
import TimeView from './impl/dateTime/views/TimeView';

const defaultOptions = {
    enableDelete: false,
    timezoneOffset: -new Date().getTimezoneOffset()
};

/**
 * @name DateTimeEditorView
 * @memberof module:core.form.editors
 * @class Combined date and time editor. Supported data type: String in ISO8601 format
 * (for example, '2015-07-20T10:46:37Z').
 * @extends module:core.form.editors.base.BaseEditorView
 * @param {Object} options Options object.
 * All the properties of {@link module:core.form.editors.base.BaseEditorView BaseEditorView} class are also supported.
 * @param {Boolean} options.enableDelete - Whether to display a delete button that sets the value to null.
 * @param {Number} options.timezoneOffset - Number of minutes representing timezone offset.
 * E.g. for UTC+3 enter 180. Negative values allowed. Defaults to browser (system) local timezone offset.
 * */
Backbone.Form.editors.DateTime = BaseLayoutEditorView.extend(/** @lends module:core.form.editors.DateTimeEditorView.prototype */{
    initialize: function(options) {
        options = options || {};
        if (options.schema) {
            _.extend(this.options, defaultOptions, _.pick(options.schema, _.keys(defaultOptions)));
        } else {
            _.extend(this.options, defaultOptions, _.pick(options || {}, _.keys(defaultOptions)));
        }

        var readonly = this.getReadonly(),
            enabled = this.getEnabled();

        this.dateTimeModel = new Backbone.Model({
            value: this.value,
            readonly: readonly,
            enabled: enabled
        });

        this.listenTo(this.dateTimeModel, 'change:value', this.__change, this);
    },

    ui: {
        deleteButton: '.js-clear-button'
    },

    events: {
        'click @ui.deleteButton': '__onClear'
    },

    regions: {
        dateRegion: '.js-date-region',
        timeRegion: '.js-time-region'
    },

    className: 'l-field date-time',

    template: template,

    templateHelpers: function () {
        return this.options;
    },

    __change: function () {
        this.__value(this.dateTimeModel.get('value'), true, true);
        this.updateDelete();
    },

    setValue: function (value) {
        this.__value(value, true, false);
        this.dateTimeModel.set('value', value);
    },

    getValue: function () {
        return this.value === null ? this.value : moment(this.value).toISOString();
    },

    onRender: function () {
        this.dateView = new DateView({
            model: this.dateTimeModel,
            timezoneOffset: this.options.timezoneOffset,
            preserveTime: true
        });

        this.timeView = new TimeView({
            model: this.dateTimeModel,
            timezoneOffset: this.options.timezoneOffset
        });

        this.dateRegion.show(this.dateView);
        this.timeRegion.show(this.timeView);
        this.updateDelete();
    },

    updateDelete: function() {
        if (!this.options.enableDelete || !this.getValue()) {
            this.ui.deleteButton.hide();
        } else {
            this.ui.deleteButton.show();
        }
    },

    __value: function (value, updateUi, triggerChange) {
        if (this.value === value) {
            return;
        }
        this.value = value;

        if (triggerChange) {
            this.__triggerChange();
        }
    },

    __setEnabled: function (enabled) {
        BaseLayoutEditorView.prototype.__setEnabled.call(this, enabled);
        this.dateTimeModel.set({enabled: this.getEnabled()});
    },

    __setReadonly: function (readonly) {
        BaseLayoutEditorView.prototype.__setReadonly.call(this, readonly);
        this.dateTimeModel.set({readonly: this.getReadonly()});
    },

    __onClear: function() {
        this.__value(null, true, true);
        this.dateTimeModel.set('value', null);
    }
});

export default Backbone.Form.editors.DateTime;
<|endoftext|>


<commit_before>import Crafty from 'crafty';
import 'app/components/camera_relative_motion';

Crafty.init(800,600, document.getElementById('game'));
Crafty.background('#000');

Crafty.e('2D, WebGL, Color, Fourway').attr({
  x: 200,
  y: 200,
  w: 20,
  h: 20,
  z: 5
}).color('#F00');

Crafty.e('2D, Fourway').fourway(100).bind('MotionChange', function(property) {
  let newValue = {};
  newValue[property.key] = this[property.key];
  Crafty.s('CameraSystem').camera.attr(newValue);
})

Crafty.e('2D, WebGL, Color, CameraRelativeMotion').attr({
  x: 700,
  y: 100,
  w: 30,
  h: 400,
  z: 10
}).color('#00F')

Crafty.e('2D, WebGL, Color, CameraRelativeMotion').attr({
  x: 500,
  y: 150,
  w: 20,
  h: 300
}).color('#0F0').cameraRelativeMotion({ xResponse: 0.5, yResponse: 0.5 });

<commit_msg>Experiment with zooming<commit_after>import Crafty from 'crafty';
import 'app/components/camera_relative_motion';

Crafty.init(800,600, document.getElementById('game'));
Crafty.background('#000');

Crafty.e('2D, WebGL, Color').attr({
  x: 200,
  y: 200,
  w: 20,
  h: 20,
  z: 5
}).color('#F00');

Crafty.e('Multiway').multiway(100, {UP_ARROW: -90, DOWN_ARROW: 90, RIGHT_ARROW: 0, LEFT_ARROW: 180})
  .bind('MotionChange', function(property) {
  let newValue = {};
  newValue[property.key] = this[property.key];
  Crafty.s('CameraSystem').camera.attr(newValue);
});

Crafty.e('Multiway').multiway(1, {W: -90, S: 90}).bind('MotionChange', function(property) {
  if (this.vy === 0) return;
  this.zoom = (this.zoom || 1.0);

  let oldScale = Crafty.viewport._scale;
  let newScale = this.zoom *= (1 + (this.vy * 0.10));

  let w = Crafty.viewport.width;
  let h = Crafty.viewport.height;

  Crafty.viewport.x -= ((w / oldScale) - (w / newScale)) / 2;
  Crafty.viewport.y -= ((h / oldScale) - (h / newScale)) / 2;
  Crafty.viewport.scale(newScale);
});

Crafty.e('2D, WebGL, Color, CameraRelativeMotion').attr({
  x: 700,
  y: 100,
  w: 30,
  h: 400,
  z: 10
}).color('#00F')

Crafty.e('2D, WebGL, Color, CameraRelativeMotion').attr({
  x: 500,
  y: 150,
  w: 20,
  h: 300
}).color('#0F0').cameraRelativeMotion({ xResponse: 0.5, yResponse: 0.5 });

<|endoftext|>


<commit_before>'use strict';
// Move vcSession initialization to here since the sessionEvent.js
// is the first one to be called in the dependency list.
window.vcSession = window.vcSession ? window.vcSession : {};

(function(vcSession, _) {
  if (!_.isObject(vcSession)) {
    vcSession = {};
  }
  vcSession.events = (function() {
    return {
      saveCohort: function(stats, name, description) {
        var def = new $.Deferred();
        $.when(vcSession.utils.buildVCObject(stats.filters, stats.studies,
          name, description)).done(function(_virtualCohort) {
          vcSession.model.saveSession(_virtualCohort)
            .done(function(response) {
              def.resolve(response);
            })
            .fail(function() {
              def.reject();
            });
        });
        return def.promise();
      },
      removeVirtualCohort: function(virtualCohort) {
        vcSession.model.removeSession(virtualCohort);
      },
      editVirtualCohort: function(virtualCohort) {
        vcSession.model.editSession(virtualCohort);
      },
      addSampleToVirtualCohort: function(virtualCohortID, cancerStudyID,
                                         sampleID) {
        var _returnString = 'error';
        var _virtualCohorts = vcSession.utils.getVirtualCohorts();
        var _studyMatch = _.findWhere(_virtualCohorts, {
          virtualCohortID: virtualCohortID
        });
        if (typeof _studyMatch === 'undefined') {
          /*
           TODO : if virtual cohort is not present in local storage
           */
          console.log('virtual cohort not found');
        } else {
          var _match = _.findWhere(_studyMatch.studies, {
            id: cancerStudyID
          });
          if (typeof _match === 'undefined') {
            var _selectedCases = vcSession.utils.buildCaseListObject(
              _studyMatch.studies, cancerStudyID, sampleID);
            _studyMatch.studies = _selectedCases;
            // TODO: this is the question I have for a while, should we have
            // individual length property? I understand it's convenient
            // but also easy to get out of sync with the samples array.
            _returnString = 'success';
          } else if (_.contains(_match.samples, sampleID)) {
            _returnString = 'warn';
          } else {
            _match.samples.push(sampleID);
            _returnString = 'success';
          }
          this.editVirtualCohort(_studyMatch);
        }
        return _returnString;
      }
    };
  })();
})(window.vcSession,
  window._);

'use strict';

(function(vcSession, _, $) {
  if (!_.isObject(vcSession)) {
    vcSession = {};
  }
  vcSession.model = (function() {
    var localStorageAdd_ = function(virtualCohort) {
      var _virtualCohorts = vcSession.utils.getVirtualCohorts();
      _virtualCohorts.push(virtualCohort);
      vcSession.utils.setVirtualCohorts(_virtualCohorts);
    };

    var localStorageDelete_ = function(virtualCohort) {
      var _virtualCohorts = vcSession.utils.getVirtualCohorts();
      _virtualCohorts = _.without(_virtualCohorts, _.findWhere(_virtualCohorts,
        {virtualCohortID: virtualCohort.virtualCohortID}));
      vcSession.utils.setVirtualCohorts(_virtualCohorts);
    };

    var localStorageEdit_ = function(updateVirtualCohort) {
      var _virtualCohorts = vcSession.utils.getVirtualCohorts();
      _.extend(_.findWhere(_virtualCohorts, {
        virtualCohortID: updateVirtualCohort.virtualCohortID
      }), updateVirtualCohort);
      vcSession.utils.setVirtualCohorts(_virtualCohorts);
    };

    return {
      saveSession: function(virtualCohort) {
        var def = new $.Deferred();
        $.ajax({
          type: 'POST',
          url: vcSession.URL,
          contentType: 'application/json;charset=UTF-8',
          data: JSON.stringify(virtualCohort)
        }).done(function(response) {
          if (virtualCohort.userID === 'DEFAULT') {
            virtualCohort.virtualCohortID = response.id;
            localStorageAdd_(virtualCohort);
          }
          def.resolve(response);
        }).fail(function() {
          virtualCohort.virtualCohortID = vcSession.utils.generateUUID();
          localStorageAdd_(virtualCohort);
          def.reject();
        });
        return def.promise();
      },
      saveSessionWithoutWritingLocalStorage: function(_virtualCohort, _callbackFunc) {
        $.ajax({
          type: 'POST',
          url: vcSession.URL,
          contentType: 'application/json;charset=UTF-8',
          data: JSON.stringify(_virtualCohort)
        }).done(function(response) {
          if (_virtualCohort.userID === 'DEFAULT') {
            _virtualCohort.virtualCohortID = response.id;
            _callbackFunc(response.id);
          }
        }).fail(function() {
          _virtualCohort.virtualCohortID = vcSession.utils.generateUUID();
          _callbackFunc(response.id);
        });
      },
      removeSession: function(_virtualCohort) {
        // Delete cohort just from browser localstorage
        localStorageDelete_(_virtualCohort);
      },
      editSession: function(_virtualCohort) {
        $.ajax({
          type: 'PUT',
          url: vcSession.URL + '/' + _virtualCohort.virtualCohortID,
          contentType: 'application/json;charset=UTF-8',
          data: JSON.stringify(_virtualCohort)
        }).done(function() {
          if (_virtualCohort.userID === 'DEFAULT') {
            localStorageEdit_(_virtualCohort);
          }
        }).fail(function(jqXHR) {
          // TODO: should we delete the virtual cohort if no record found
          // in the database? Should we add it into database?
          if (jqXHR.status === 404) {
            localStorageDelete_(_virtualCohort);
            vcSession.model.saveSession(_virtualCohort);
          } else {
            localStorageEdit_(_virtualCohort);
          }
        });
      },

      // TODO: should we send request without validating userID?
      loadUserVirtualCohorts: function() {
        var def = new $.Deferred();
        $.ajax({
          type: 'GET',
          url: vcSession.URL + '/get-user-cohorts',
          contentType: 'application/json;charset=UTF-8'
        }).done(function(response) {
          var _virtualCohorts = [];
          $.each(response, function(key, val) {
            var _virtualCohort = val.data;
            _virtualCohort.virtualCohortID = val.id;
            _virtualCohorts.push(_virtualCohort);
          });
          def.resolve(_virtualCohorts);
        }).fail(function() {
          def.resolve([]);
        });
        return def.promise();
      }
    };
  })();
})(window.vcSession,
  window._,
  window.$ || window.jQuery);

'use strict';

(function(vcSession, _, $) {
  if (!_.isObject(vcSession)) {
    vcSession = {};
  }
  vcSession.utils = (function() {
    var virtualCohort_ = {
      name: '',
      description: '',
      filters: '',
      studies: ''
    };

    var studies_ = {
      id: '',
      samples: []
    };

    var generateUUID_ = function() {
      var _d = new Date().getTime();
      if (window.performance && typeof window.performance.now === 'function') {
        _d += window.performance.now();
      }
      var _uuid = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
        function(c) {
          var r = (_d + Math.random() * 16) % 16 | 0;
          _d = Math.floor(_d / 16);
          return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
      return _uuid;
    };

    // Get Virtual cohorts from Local Storage
    var getVirtualCohorts_ = function() {
      return JSON.parse(localStorage.getItem('virtual-cohorts')) || [];
    };

    // Set Virtual cohorts in Local Storage
    var setVirtualCohorts_ = function(virtualCohorts) {
      localStorage.setItem('virtual-cohorts', JSON.stringify(virtualCohorts));
    };

    var buildVCObject_ = function(filters, cases, name,
                                  description) {
      var def = new $.Deferred();
      var _virtualCohort = $.extend(true, {}, virtualCohort_);
      _virtualCohort.filters = filters;
      _virtualCohort.studies = cases;
      if (name) {
        _virtualCohort.name = name;
      } else {
        _virtualCohort.name = cases.length > 1 ? "Combined Study" : "Selected Study";
      }
      _virtualCohort.description = description || '';
      def.resolve(_virtualCohort);
      return def.promise();
    };
    var buildCaseListObject_ = function(selectedCases, cancerStudyID,
                                        sampleID) {
      var _selectedCases = selectedCases;
      var _studies = $.extend(true, {}, studies_);
      _studies.id = cancerStudyID;
      _studies.samples.push(sampleID);
      _selectedCases.push(_studies);
      return _selectedCases;
    };

    var generateCohortDescription_ = function(_cases) {
      var def = new $.Deferred(), _desp = "";
      $.when(window.iviz.datamanager.getCancerStudyDisplayName(_.pluck(_cases, "id"))).done(function(_studyIdNameMap) {
        _.each(_cases, function (_i) {
          _desp += _studyIdNameMap[_i.id] + ": " + _i.samples.length + " samples\n";
        });
        def.resolve(_desp);
      });
      return def.promise();
    }

    return {
      buildVCObject: buildVCObject_,
      setVirtualCohorts: setVirtualCohorts_,
      getVirtualCohorts: getVirtualCohorts_,
      generateUUID: generateUUID_,
      generateCohortDescription: generateCohortDescription_,
      buildCaseListObject: buildCaseListObject_
    };
  })();
})(window.vcSession,
  window._,
  window.$ || window.jQuery);
<commit_msg>Study View: Fix bug due to VS meta data change<commit_after>'use strict';
// Move vcSession initialization to here since the sessionEvent.js
// is the first one to be called in the dependency list.
window.vcSession = window.vcSession ? window.vcSession : {};

(function(vcSession, _) {
  if (!_.isObject(vcSession)) {
    vcSession = {};
  }
  vcSession.events = (function() {
    return {
      saveCohort: function(stats, name, description) {
        var def = new $.Deferred();
        $.when(vcSession.utils.buildVCObject(stats.filters, stats.studies,
          name, description)).done(function(_virtualCohort) {
          vcSession.model.saveSession(_virtualCohort)
            .done(function(response) {
              def.resolve(response);
            })
            .fail(function() {
              def.reject();
            });
        });
        return def.promise();
      },
      removeVirtualCohort: function(virtualCohort) {
        vcSession.model.removeSession(virtualCohort);
      },
      editVirtualCohort: function(virtualCohort) {
        vcSession.model.editSession(virtualCohort);
      },
      addSampleToVirtualCohort: function(virtualCohortID, cancerStudyID,
                                         sampleID) {
        var _returnString = 'error';
        var _virtualCohorts = vcSession.utils.getVirtualCohorts();
        var _studyMatch = _.findWhere(_virtualCohorts, {
          virtualCohortID: virtualCohortID
        });
        if (typeof _studyMatch === 'undefined') {
          /*
           TODO : if virtual cohort is not present in local storage
           */
          console.log('virtual cohort not found');
        } else {
          var _match = _.findWhere(_studyMatch.studies, {
            id: cancerStudyID
          });
          if (typeof _match === 'undefined') {
            var _selectedCases = vcSession.utils.buildCaseListObject(
              _studyMatch.studies, cancerStudyID, sampleID);
            _studyMatch.studies = _selectedCases;
            // TODO: this is the question I have for a while, should we have
            // individual length property? I understand it's convenient
            // but also easy to get out of sync with the samples array.
            _returnString = 'success';
          } else if (_.contains(_match.samples, sampleID)) {
            _returnString = 'warn';
          } else {
            _match.samples.push(sampleID);
            _returnString = 'success';
          }
          this.editVirtualCohort(_studyMatch);
        }
        return _returnString;
      }
    };
  })();
})(window.vcSession,
  window._);

'use strict';

(function(vcSession, _, $) {
  if (!_.isObject(vcSession)) {
    vcSession = {};
  }
  vcSession.model = (function() {
    var localStorageAdd_ = function(virtualCohort) {
      var _virtualCohorts = vcSession.utils.getVirtualCohorts();
      _virtualCohorts.push(virtualCohort);
      vcSession.utils.setVirtualCohorts(_virtualCohorts);
    };

    var localStorageDelete_ = function(virtualCohort) {
      var _virtualCohorts = vcSession.utils.getVirtualCohorts();
      _virtualCohorts = _.without(_virtualCohorts, _.findWhere(_virtualCohorts,
        {virtualCohortID: virtualCohort.virtualCohortID}));
      vcSession.utils.setVirtualCohorts(_virtualCohorts);
    };

    var localStorageEdit_ = function(updateVirtualCohort) {
      var _virtualCohorts = vcSession.utils.getVirtualCohorts();
      _.extend(_.findWhere(_virtualCohorts, {
        virtualCohortID: updateVirtualCohort.virtualCohortID
      }), updateVirtualCohort);
      vcSession.utils.setVirtualCohorts(_virtualCohorts);
    };

    return {
      saveSession: function(virtualCohort) {
        var def = new $.Deferred();
        $.ajax({
          type: 'POST',
          url: vcSession.URL,
          contentType: 'application/json;charset=UTF-8',
          data: JSON.stringify(virtualCohort)
        }).done(function(response) {
          if (virtualCohort.userID === 'DEFAULT') {
            virtualCohort.virtualCohortID = response.id;
            localStorageAdd_(virtualCohort);
          }
          def.resolve(response);
        }).fail(function() {
          virtualCohort.virtualCohortID = vcSession.utils.generateUUID();
          localStorageAdd_(virtualCohort);
          def.reject();
        });
        return def.promise();
      },
      saveSessionWithoutWritingLocalStorage: function(_virtualCohort, _callbackFunc) {
        $.ajax({
          type: 'POST',
          url: vcSession.URL,
          contentType: 'application/json;charset=UTF-8',
          data: JSON.stringify(_virtualCohort)
        }).done(function(response) {
          if (_virtualCohort.userID === 'DEFAULT') {
            _virtualCohort.virtualCohortID = response.id;
            _callbackFunc(response.id);
          }
        }).fail(function() {
          _virtualCohort.virtualCohortID = vcSession.utils.generateUUID();
          _callbackFunc(response.id);
        });
      },
      removeSession: function(_virtualCohort) {
        // Delete cohort just from browser localstorage
        localStorageDelete_(_virtualCohort);
      },
      editSession: function(_virtualCohort) {
        $.ajax({
          type: 'PUT',
          url: vcSession.URL + '/' + _virtualCohort.virtualCohortID,
          contentType: 'application/json;charset=UTF-8',
          data: JSON.stringify(_virtualCohort)
        }).done(function() {
          if (_virtualCohort.userID === 'DEFAULT') {
            localStorageEdit_(_virtualCohort);
          }
        }).fail(function(jqXHR) {
          // TODO: should we delete the virtual cohort if no record found
          // in the database? Should we add it into database?
          if (jqXHR.status === 404) {
            localStorageDelete_(_virtualCohort);
            vcSession.model.saveSession(_virtualCohort);
          } else {
            localStorageEdit_(_virtualCohort);
          }
        });
      },

      // TODO: should we send request without validating userID?
      loadUserVirtualCohorts: function() {
        var def = new $.Deferred();
        $.ajax({
          type: 'GET',
          url: vcSession.URL + '/get-user-cohorts',
          contentType: 'application/json;charset=UTF-8'
        }).done(function(response) {
          var _virtualCohorts = [];
          $.each(response, function(key, val) {
            var _virtualCohort = val.data;
            _virtualCohort.virtualCohortID = val.id;
            _virtualCohorts.push(_virtualCohort);
          });
          def.resolve(_virtualCohorts);
        }).fail(function() {
          def.resolve([]);
        });
        return def.promise();
      }
    };
  })();
})(window.vcSession,
  window._,
  window.$ || window.jQuery);

'use strict';

(function(vcSession, _, $) {
  if (!_.isObject(vcSession)) {
    vcSession = {};
  }
  vcSession.utils = (function() {
    var virtualCohort_ = {
      name: '',
      description: '',
      filters: '',
      studies: ''
    };

    var generateUUID_ = function() {
      var _d = new Date().getTime();
      if (window.performance && typeof window.performance.now === 'function') {
        _d += window.performance.now();
      }
      var _uuid = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
        function(c) {
          var r = (_d + Math.random() * 16) % 16 | 0;
          _d = Math.floor(_d / 16);
          return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
      return _uuid;
    };

    // Get Virtual cohorts from Local Storage
    var getVirtualCohorts_ = function() {
      return JSON.parse(localStorage.getItem('virtual-cohorts')) || [];
    };

    // Set Virtual cohorts in Local Storage
    var setVirtualCohorts_ = function(virtualCohorts) {
      localStorage.setItem('virtual-cohorts', JSON.stringify(virtualCohorts));
    };

    var buildVCObject_ = function(filters, cases, name,
                                  description) {
      var def = new $.Deferred();
      var _virtualCohort = $.extend(true, {}, virtualCohort_);
      _virtualCohort.filters = filters;

      _virtualCohort.studies = cases.map(function(studyObj) {
        return {
          id: studyObj.id,
          samples: studyObj.samples
        };
      });
      if (name) {
        _virtualCohort.name = name;
      } else {
        _virtualCohort.name = cases.length > 1 ? "Combined Study" : "Selected Study";
      }
      _virtualCohort.description = description || '';
      def.resolve(_virtualCohort);
      return def.promise();
    };

    var generateCohortDescription_ = function(_cases) {
      var def = new $.Deferred(), _desp = "";
      $.when(window.iviz.datamanager.getCancerStudyDisplayName(_.pluck(_cases, "id"))).done(function(_studyIdNameMap) {
        _.each(_cases, function (_i) {
          _desp += _studyIdNameMap[_i.id] + ": " + _i.samples.length + " samples\n";
        });
        def.resolve(_desp);
      });
      return def.promise();
    }

    return {
      buildVCObject: buildVCObject_,
      setVirtualCohorts: setVirtualCohorts_,
      getVirtualCohorts: getVirtualCohorts_,
      generateUUID: generateUUID_,
      generateCohortDescription: generateCohortDescription_
    };
  })();
})(window.vcSession,
  window._,
  window.$ || window.jQuery);
<|endoftext|>


<commit_before>/**
 * i18n.js
 *
 * This will setup the i18n language files and locale data for your app.
 *
 */
import { addLocaleData } from 'react-intl'
import en from 'react-intl/locale-data/en'
import nl from 'react-intl/locale-data/nl'
import es from 'react-intl/locale-data/es'
import fr from 'react-intl/locale-data/fr'
import it from 'react-intl/locale-data/it'
import de from 'react-intl/locale-data/de'
import pt from 'react-intl/locale-data/pt'
import he from 'react-intl/locale-data/he'
import hr from 'react-intl/locale-data/hr'
import ca from 'react-intl/locale-data/ca'
import gl from 'react-intl/locale-data/gl'
import ru from 'react-intl/locale-data/ru'
import ar from 'react-intl/locale-data/ar'
import eu from 'react-intl/locale-data/eu'
import zh from 'react-intl/locale-data/zh'
import af from 'react-intl/locale-data/af'

import { DEFAULT_LOCALE, appLocales } from './containers/App/constants'
import enTranslationMessages from './translations/en.json'
import nlTranslationMessages from './translations/nl.json'
import esTranslationMessages from './translations/es.json'
import frTranslationMessages from './translations/fr.json'
import itTranslationMessages from './translations/it.json'
import deTranslationMessages from './translations/de.json'
import ptTranslationMessages from './translations/pt.json'
import heTranslationMessages from './translations/he.json'
import hrTranslationMessages from './translations/hr.json'
import caTranslationMessages from './translations/ca.json'
import glTranslationMessages from './translations/gl.json'
import ruTranslationMessages from './translations/ru.json'
import arTranslationMessages from './translations/ar.json'
import euTranslationMessages from './translations/eu.json'
import valTranslationMessages from './translations/val.json'
import zhTranslationMessages from './translations/zh.json'
import afTranslationMessages from './translations/af.json'

addLocaleData([
  ...en,
  ...es,
  ...fr,
  ...it,
  ...de,
  ...pt,
  ...he,
  ...hr,
  ...ca,
  ...gl,
  ...ru,
  ...ar,
  ...eu,
  ...zh,
  ...af
])

export const formatTranslationMessages = (locale, messages) => {
  const defaultFormattedMessages =
    locale !== DEFAULT_LOCALE
      ? formatTranslationMessages(DEFAULT_LOCALE, enTranslationMessages)
      : {}
  return Object.keys(messages).reduce((formattedMessages, key) => {
    let message = messages[key]
    if (!message && locale !== DEFAULT_LOCALE) {
      message = defaultFormattedMessages[key]
    }
    return Object.assign(formattedMessages, { [key]: message })
  }, {})
}

export const translationMessages = {
  en: formatTranslationMessages('en', enTranslationMessages),
  es: formatTranslationMessages('es', esTranslationMessages),
  fr: formatTranslationMessages('fr', frTranslationMessages),
  it: formatTranslationMessages('it', itTranslationMessages),
  de: formatTranslationMessages('de', deTranslationMessages),
  nl: formatTranslationMessages('nl', nlTranslationMessages),
  pt: formatTranslationMessages('pt', ptTranslationMessages),
  he: formatTranslationMessages('he', heTranslationMessages),
  hr: formatTranslationMessages('hr', hrTranslationMessages),
  ca: formatTranslationMessages('ca', caTranslationMessages),
  gl: formatTranslationMessages('gl', glTranslationMessages),
  ru: formatTranslationMessages('ru', ruTranslationMessages),
  ar: formatTranslationMessages('ar', arTranslationMessages),
  eu: formatTranslationMessages('eu', euTranslationMessages),
  val: formatTranslationMessages('val', valTranslationMessages),
  zh: formatTranslationMessages('zh', zhTranslationMessages),
  af: formatTranslationMessages('af', afTranslationMessages),
}
<commit_msg>add br with pt messages<commit_after>/**
 * i18n.js
 *
 * This will setup the i18n language files and locale data for your app.
 *
 */
import { addLocaleData } from 'react-intl'
import en from 'react-intl/locale-data/en'
import nl from 'react-intl/locale-data/nl'
import es from 'react-intl/locale-data/es'
import fr from 'react-intl/locale-data/fr'
import it from 'react-intl/locale-data/it'
import de from 'react-intl/locale-data/de'
import pt from 'react-intl/locale-data/pt'
import he from 'react-intl/locale-data/he'
import hr from 'react-intl/locale-data/hr'
import ca from 'react-intl/locale-data/ca'
import gl from 'react-intl/locale-data/gl'
import ru from 'react-intl/locale-data/ru'
import ar from 'react-intl/locale-data/ar'
import eu from 'react-intl/locale-data/eu'
import zh from 'react-intl/locale-data/zh'
import af from 'react-intl/locale-data/af'

import { DEFAULT_LOCALE, appLocales } from './containers/App/constants'
import enTranslationMessages from './translations/en.json'
import nlTranslationMessages from './translations/nl.json'
import esTranslationMessages from './translations/es.json'
import frTranslationMessages from './translations/fr.json'
import itTranslationMessages from './translations/it.json'
import deTranslationMessages from './translations/de.json'
import ptTranslationMessages from './translations/pt.json'
import heTranslationMessages from './translations/he.json'
import hrTranslationMessages from './translations/hr.json'
import caTranslationMessages from './translations/ca.json'
import glTranslationMessages from './translations/gl.json'
import ruTranslationMessages from './translations/ru.json'
import arTranslationMessages from './translations/ar.json'
import euTranslationMessages from './translations/eu.json'
import valTranslationMessages from './translations/val.json'
import zhTranslationMessages from './translations/zh.json'
import afTranslationMessages from './translations/af.json'

addLocaleData([
  ...en,
  ...es,
  ...fr,
  ...it,
  ...de,
  ...pt,
  ...he,
  ...hr,
  ...ca,
  ...gl,
  ...ru,
  ...ar,
  ...eu,
  ...zh,
  ...af
])

export const formatTranslationMessages = (locale, messages) => {
  const defaultFormattedMessages =
    locale !== DEFAULT_LOCALE
      ? formatTranslationMessages(DEFAULT_LOCALE, enTranslationMessages)
      : {}
  return Object.keys(messages).reduce((formattedMessages, key) => {
    let message = messages[key]
    if (!message && locale !== DEFAULT_LOCALE) {
      message = defaultFormattedMessages[key]
    }
    return Object.assign(formattedMessages, { [key]: message })
  }, {})
}

export const translationMessages = {
  en: formatTranslationMessages('en', enTranslationMessages),
  br: formatTranslationMessages('br', ptTranslationMessages),
  es: formatTranslationMessages('es', esTranslationMessages),
  fr: formatTranslationMessages('fr', frTranslationMessages),
  it: formatTranslationMessages('it', itTranslationMessages),
  de: formatTranslationMessages('de', deTranslationMessages),
  nl: formatTranslationMessages('nl', nlTranslationMessages),
  pt: formatTranslationMessages('pt', ptTranslationMessages),
  he: formatTranslationMessages('he', heTranslationMessages),
  hr: formatTranslationMessages('hr', hrTranslationMessages),
  ca: formatTranslationMessages('ca', caTranslationMessages),
  gl: formatTranslationMessages('gl', glTranslationMessages),
  ru: formatTranslationMessages('ru', ruTranslationMessages),
  ar: formatTranslationMessages('ar', arTranslationMessages),
  eu: formatTranslationMessages('eu', euTranslationMessages),
  val: formatTranslationMessages('val', valTranslationMessages),
  zh: formatTranslationMessages('zh', zhTranslationMessages),
  af: formatTranslationMessages('af', afTranslationMessages),
}
<|endoftext|>


<commit_before>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Fixes the iOS orientation change bug using a jQM version of this technique https://github.com/scottjehl/iOS-Orientationchange-Fix
//>>label: iOS orientation change bugfix

define( [ "jquery", "jquery.mobile.core", "jquery.mobile.zoom" ], function( $ ) {
//>>excludeEnd("jqmBuildExclude");
( function( $, window ) {
    var zoom = $.mobile.zoom,
		x, y, z, aig;

    function checkTilt( e ){
		evt = e.originalEvent;
		aig = evt.accelerationIncludingGravity;

		x = Math.abs( aig.x );
		y = Math.abs( aig.y );
		z = Math.abs( aig.z );

		// If portrait orientation and in one of the danger zones
        if( !w.orientation && ( x > 7 || ( ( z > 6 && y < 8 || z < 8 && y > 6 ) && x > 5 ) ) ){
			if( zoom.enabled ){
				zoom.disable();
			}
        }
		else if( !zoom.enabled ){
			zoom.enable();
        }
    }

    $( window )
		.bind( "orientationchange", zoom.enable )
		.bind( "devicemotion", checkTilt );

}( jQuery, this ));
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<commit_msg>window not w, evt wasn't defined. Thanks @staabm<commit_after>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Fixes the iOS orientation change bug using a jQM version of this technique https://github.com/scottjehl/iOS-Orientationchange-Fix
//>>label: iOS orientation change bugfix

define( [ "jquery", "jquery.mobile.core", "jquery.mobile.zoom" ], function( $ ) {
//>>excludeEnd("jqmBuildExclude");
( function( $, window ) {
    var zoom = $.mobile.zoom,
		evt, x, y, z, aig;

    function checkTilt( e ){
		evt = e.originalEvent;
		aig = evt.accelerationIncludingGravity;

		x = Math.abs( aig.x );
		y = Math.abs( aig.y );
		z = Math.abs( aig.z );

		// If portrait orientation and in one of the danger zones
        if( !window.orientation && ( x > 7 || ( ( z > 6 && y < 8 || z < 8 && y > 6 ) && x > 5 ) ) ){
			if( zoom.enabled ){
				zoom.disable();
			}
        }
		else if( !zoom.enabled ){
			zoom.enable();
        }
    }

    $( window )
		.bind( "orientationchange", zoom.enable )
		.bind( "devicemotion", checkTilt );

}( jQuery, this ));
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<|endoftext|>


<commit_before>import React from 'react'
import ReactDOM from 'react-dom'

class MyComponent extends React.Component {
  render() {
    return
Hi!
;
  }
}

ReactDOM.render(<MyComponent />, document.getElementById('app'));<commit_msg>Add semicolons<commit_after>import React from 'react';
import ReactDOM from 'react-dom';

class MyComponent extends React.Component {
  render() {
    return
Hi!
;
  }
}

ReactDOM.render(<MyComponent />, document.getElementById('app'));<|endoftext|>