<commit_before>/**
 * application.js v1.0
 * https://github.com/writethesky
 * https://github.com/writethesky/application.js
 */
(function(w){
	'use strict';

	//jQuery版本检测
	if(typeof($) == 'undefined' || typeof($.fn) == 'undefined' || typeof($.fn.jquery) == 'undefined' || $.fn.jquery < '3.1.1'){

		console.info("请引入3.1.1版本以上的jQuery");
		return;
	}

	if(!is_html5()){
		$("body").html("
您的内核版本太低

如果您正在使用的浏览器访问本站，建议升级您的浏览器

如果您正在使用手机等客户端打开本APP，建议您升级您的操作系统
").css({background: '#fff', fontSize: '.5rem', textAlign: 'center'});
		return;
	}

	var t = '?t=' + (new Date()).getTime();

	/**
	 * 设置参数
	 */
	var settings = {

		api: {
			location: "",
			version: "",
			versionSendType: 'url', //param、header
		},
		isChangeURL: false
	}

	var app = {
		//设置方法
		settings: function(param){

			settings = object_merge(settings, param);
		},

		api: {
			ajax: function(url, type, param, callback){
				ajax(url, param, type, callback);
			},
			get: function(url, param, callback){
				ajax(url, param, 'get', callback);
			},

			post: function(url, param, callback){
				ajax(url, param, 'post', callback);
			}
		},

		load_page: function(_this){
			load_page.call(_this);
		},

		back: function(){
			var prev_page_index = app.apphistory.length - 2;
			if(prev_page_index < 0){
				return;
			}

			var prev_page_data = app.apphistory[prev_page_index];

			load_page(null, prev_page_data);
			app.apphistory.pop();
			app.apphistory.pop();

		},
		namespace: {
			register: function(path){
			    var arr = path.split(".");
			    var ns = "";
			    for(var i=0;i<arr.length;i++){
			        if(i>0) ns += ".";
			        ns += arr[i];
			        eval("if(typeof(" + ns + ") == 'undefined') window." + ns + " = new Object();");
			    }
			}
		}
	}

	//对浏览器原生的a标签跳转机制进行调整
	$("html").on("click", "a[app]", load_page);

	app.apphistory = [];

	/**
	 * 发送ajax请求
	 * @param  {[type]}   url      [description]
	 * @param  {[type]}   param    [description]
	 * @param  {[type]}   method   [description]
	 * @param  {Function} callback [description]
	 * @return {[type]}            [description]
	 */
	function ajax(url, param, method, callback){
		for(var i in settings.api){
			if(settings.api[i] === ""){
				console.info("在此之前请调用 api.settings 方法");
				return;
			}
		}

		var ajaxObj = {
			type: method,
			data: param,
			url: settings.api.location + "/" + url,
			dataType: 'json',
			async:true,
			xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success: function(data){
            	callback && callback(data);
            }
		};

		switch(settings.api.versionSendType){
			case 'url':
				ajaxObj.url = settings.api.location + "/" + settings.api.version + "/" + url;
				break;
			case 'param':
				ajaxObj.data.version = settings.api.version;
				break;
			case 'header':
				ajaxObj.headers = {
					'Api-Version': settings.api.version,
				}
			break;
		}

		$.ajax(ajaxObj);

		// todo 当发生异常时，提示异常
	}

	/**
	 * 加载指定页面
	 * @param  {[type]} _this     [description]
	 * @param  {[type]} page_data [description]
	 * @return {[type]}           [description]
	 */
	function load_page(_this, page_data){

		if(page_data){
			var dataHref = page_data.html;
			var dataId = page_data.container_id;
			var dataCss = page_data.css;
			var dataJs = page_data.js;

			var dataObj = page_data.obj;
		}else{
			var dataHref = $(this).attr("href");
			var dataId = $(this).attr("container");
			var dataCss = $(this).attr("css");
			var dataJs = $(this).attr("js");

			var dataObj = $(this).attr("data-obj");
			if(dataObj){
				dataObj = dataObj.replace(/'/g, '"');

				(dataObj = $.parseJSON(dataObj));
				w.dataObj = dataObj;
			}
			dataCss = dataCss ? dataCss.split("|") : "";
			dataJs = dataJs ? dataJs.split("|") : "";
		}
		if(settings.isChangeURL){
			w.history.pushState(null, null, dataHref);
		}

		var page_data = {
			html: dataHref,
			css: dataCss,
			js: dataJs,
			container_id: dataId,
			obj: dataObj
		};

		app.apphistory.push(page_data);

		dataCss && load.css(dataCss, function(){
			$(window).resize();
			dataHref && load.html(dataHref, dataId, function(){
				$(window).resize();
				dataJs && load.js(dataJs);
			});
		});

		return false;
	}

	function load(){
		var __this = this;
		this.html = function(url, id, callback){

			$.get(url + t, function(data){
				$("#" + id).html(data);
				callback && callback();
			});
		}

		this.css = function(arr, callback){

			if(arr.length > 0){

				var href = arr[0] + t;
				var head = document.getElementsByTagName('HEAD').item(0);
				var is_run = true;
				$("link").each(function(){

					var tmp = window.location.href.split("/");
					var end_length = tmp[tmp.length - 1].length;

					var complete_href = (window.location.href.substr(0, window.location.href.length - end_length) + href);

					if(complete_href == this.href){
						is_run = false;
					}
				});

				if(is_run){
					var style = document.createElement('link');
					style.href = href;
					style.rel = 'stylesheet';
					style.type = 'text/css';
					head.appendChild(style);

					cssReady(style, function(){
						construct();

					});

				}else{
					construct();
				}

				function construct(){
					arr.shift();

					var tmp = __this.css;
					__this.css(arr, callback);
				}

			}else{
				callback && callback();
			}
		}

		this.js = function(arr, callback){
			var __js = this;

			if(arr.length > 0){
				var src = arr[0] + t;
				var body = document.getElementsByTagName('body').item(0);
				var is_run = true;
				var script;
				$("script").each(function(){

					var tmp = window.location.href.split("/");
					var end_length = tmp[tmp.length - 1].length;

					var complete_src = (window.location.href.substr(0, window.location.href.length - end_length) + src);

					if(complete_src == this.src){
						is_run = false;
						script = this;

					}
				});

				if(is_run){
					script = document.createElement('script');
					script.src = src;
					script.type = 'text/javascript';
					body.appendChild(script);
					jsReady(script, function(){

						construct();
					});
				}else{
					construct();
				}

				function construct(){
					var js_name = arr[0];
						js_name = js_name.replace(/\//g, '.');
						js_name = js_name.substr(0, js_name.length - 3);
					eval("try{" + js_name + "&&" + js_name + "()} catch(e) {}");

					arr.shift();
					var tmp = __this.js;
					tmp(arr, callback);
				}

			}else{
				callback && callback();
			}

		}
	}

	/**
	 * 等待CSS加载并渲染完毕
	 * @param  {Function} fn   [description]
	 * @param  {[type]}   link [description]
	 * @return {[type]}        [description]
	 */
	function cssReady(style, fn) {
		var d = document,
		t = d.createStyleSheet,
		r = t ? 'rules' : 'cssRules',
		s = t ? 'styleSheet' : 'sheet',
		l = d.getElementsByTagName('link');
		// passed link or last link node
		style || (style = l[l.length - 1]);

		function check() {
			try {
				return style && style[s] && style[s][r] && style[s][r];
			} catch(e) {

				return false;
			}
		}

		(function poll() {
			check() && setTimeout(fn, 0) || setTimeout(poll, 100);
		})();
	}

	function jsReady(script, fn){

		script.onload=script.onreadystatechange=function(){
		   if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete'){

			   script.onload=script.onreadystatechange=null;
			   setTimeout(fn, 0);
			}
			//
		}
	}

	/**
	 * 对象合并[递归级]
	 * @param  {[type]} obj1 [description]
	 * @param  {[type]} obj2 [description]
	 * @return {[type]}      [description]
	 */
	function object_merge(obj1, obj2){
		// for(var i in obj1){

			for(var j in obj2){
				if(obj1.hasOwnProperty(j) && (typeof(obj1[j]) == 'object')){
					if(typeof(obj2[j]) == 'object'){
						obj1[j] = object_merge(obj1[j], obj2[j]);
					}
				}else{
					obj1[j] = obj2[j];
				}
			}

			return obj1;
		// }
	}

	/**
	 * 检测浏览器是否支持html5
	 * @return {Boolean} [description]
	 */
	function is_html5(){
		var my_canvas = $("<canvas style='position: absolute; top: 0; z-index: -1;'/>");
		$("body").append(my_canvas);
		if(!my_canvas.get(0).getContext){

			return false;
		}
		return true;
	}

	var load = new load();

	//封装一个获取 时间格式为 yyyy/mm/dd  的方法
	w.getFormatDate = function(dateTmie){
		var myDate = new Date(dateTmie*1000);
		var yy = myDate.getFullYear();
		var mm = myDate.getMonth()+1;
		var dd = myDate.getDate();
		return yy + "/" + getTwo(mm) + "/" + getTwo(dd);
		//获取两位数
		function getTwo(num){
			if(num<10){
				return "0" + num;
			}else{
				return num;
			}
		}
	}

	/**
	 * 消息弹出
	 * @param  {[type]} msg         [description]
	 * @param  {[type]} m_width     [description]
	 * @param  {[type]} m_height    [description]
	 * @param  {[type]} m_loop_time [description]
	 * @param  {[type]} m_type      [description]
	 * @return {[type]}             [description]
	 */
	var alert_message = function(msg, m_width, m_height, m_loop_time, m_type){

		m_width = m_width ? m_width : '100%';
		m_height = m_height ? m_height : '2rem';
		m_loop_time = m_loop_time ? m_loop_time : 500;
		m_id = 'alert_' + (new Date()).getTime();

		b_height = $(window).height();
		var l_top = b_height / 2;

		var m_background_color = "rgb(255, 116, 116)";
		switch(m_type){
			case 'error':
				m_background_color = "rgb(255, 116, 116)";
				break;
			case 'success':
				m_background_color = "#65e26e";
				break;
			default:
				m_background_color = "rgb(255, 116, 116)";
				break;
		}
		var dom = $("
").css({
			width: m_width,
			height: m_height,
			background: m_background_color,
			position: 'fixed',
			zIndex: '9999',
			color: "#fff",
			textAlign: 'center',
			lineHeight: m_height,
			top: b_height
		}).attr('id', m_id).text(msg);

		$("body").append(dom);

		dom.animate({'top': l_top}, m_loop_time);

		setTimeout(function(){
			dom.remove();
		}, m_loop_time + 2000);

	}

	app.alert = {
		error: function(msg, m_width, m_height, m_loop_time){
			alert_message(msg, m_width, m_height, m_loop_time, 'error');
		},
		success: function(msg, m_width, m_height, m_loop_time){
			alert_message(msg, m_width, m_height, m_loop_time, 'success');
		}
	}

	w.app = app;
}(window));
<commit_msg>解决back失效的问题<commit_after>/**
 * application.js v1.0
 * https://github.com/writethesky
 * https://github.com/writethesky/application.js
 */
(function(w){
	'use strict';

	//jQuery版本检测
	if(typeof($) == 'undefined' || typeof($.fn) == 'undefined' || typeof($.fn.jquery) == 'undefined' || $.fn.jquery < '3.1.1'){

		console.info("请引入3.1.1版本以上的jQuery");
		return;
	}

	if(!is_html5()){
		$("body").html("
您的内核版本太低

如果您正在使用的浏览器访问本站，建议升级您的浏览器

如果您正在使用手机等客户端打开本APP，建议您升级您的操作系统
").css({background: '#fff', fontSize: '.5rem', textAlign: 'center'});
		return;
	}

	var t = '?t=' + (new Date()).getTime();

	/**
	 * 设置参数
	 */
	var settings = {

		api: {
			location: "",
			version: "",
			versionSendType: 'url', //param、header
		},
		isChangeURL: false
	}

	var app = {
		//设置方法
		settings: function(param){

			settings = object_merge(settings, param);
		},

		api: {
			ajax: function(url, type, param, callback){
				ajax(url, param, type, callback);
			},
			get: function(url, param, callback){
				ajax(url, param, 'get', callback);
			},

			post: function(url, param, callback){
				ajax(url, param, 'post', callback);
			}
		},

		load_page: function(_this){
			load_page.call(_this);
		},

		back: function(){
			var prev_page_index = app.apphistory.length - 2;
			if(prev_page_index < 0){
				return;
			}

			var prev_page_data = app.apphistory[prev_page_index];

			load_page(null, prev_page_data);
			app.apphistory.pop();
			app.apphistory.pop();

		},
		namespace: {
			register: function(path){
			    var arr = path.split(".");
			    var ns = "";
			    for(var i=0;i<arr.length;i++){
			        if(i>0) ns += ".";
			        ns += arr[i];
			        eval("if(typeof(" + ns + ") == 'undefined') window." + ns + " = new Object();");
			    }
			}
		}
	}

	//对浏览器原生的a标签跳转机制进行调整
	$("html").on("click", "a[app]", load_page);

	app.apphistory = [];

	/**
	 * 发送ajax请求
	 * @param  {[type]}   url      [description]
	 * @param  {[type]}   param    [description]
	 * @param  {[type]}   method   [description]
	 * @param  {Function} callback [description]
	 * @return {[type]}            [description]
	 */
	function ajax(url, param, method, callback){
		for(var i in settings.api){
			if(settings.api[i] === ""){
				console.info("在此之前请调用 api.settings 方法");
				return;
			}
		}

		var ajaxObj = {
			type: method,
			data: param,
			url: settings.api.location + "/" + url,
			dataType: 'json',
			async:true,
			xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success: function(data){
            	callback && callback(data);
            }
		};

		switch(settings.api.versionSendType){
			case 'url':
				ajaxObj.url = settings.api.location + "/" + settings.api.version + "/" + url;
				break;
			case 'param':
				ajaxObj.data.version = settings.api.version;
				break;
			case 'header':
				ajaxObj.headers = {
					'Api-Version': settings.api.version,
				}
			break;
		}

		$.ajax(ajaxObj);

		// todo 当发生异常时，提示异常
	}

	/**
	 * 加载指定页面
	 * @param  {[type]} _this     [description]
	 * @param  {[type]} page_data [description]
	 * @return {[type]}           [description]
	 */
	function load_page(_this, page_data){

		if(page_data){
			var dataHref = page_data.html;
			var dataId = page_data.container_id;
			var dataCss = page_data.css;
			var dataJs = page_data.js;

			var dataObj = page_data.obj;
		}else{
			var dataHref = $(this).attr("href");
			var dataId = $(this).attr("container");
			var dataCss = $(this).attr("css");
			var dataJs = $(this).attr("js");

			var dataObj = $(this).attr("data-obj");
			if(dataObj){
				dataObj = dataObj.replace(/'/g, '"');

				(dataObj = $.parseJSON(dataObj));
				w.dataObj = dataObj;
			}
			dataCss = dataCss ? dataCss.split("|") : "";
			dataJs = dataJs ? dataJs.split("|") : "";
		}
		if(settings.isChangeURL){
			w.history.pushState(null, null, dataHref);
		}

		var page_data = {
			html: dataHref,
			css: dataCss,
			js: dataJs,
			container_id: dataId,
			obj: dataObj
		};

		app.apphistory.push(page_data);

		dataCss && load.css(dataCss, function(){
			$(window).resize();
			dataHref && load.html(dataHref, dataId, function(){

				$(window).resize();
				dataJs && load.js(dataJs);
			});
		});

		return false;
	}

	function load(){
		var __this = this;
		this.html = function(url, id, callback){

			$.get(url + t, function(data){
				$("#" + id).html(data);
				callback && callback();
			});
		}

		this.css = function(arr, callback){

			if(arr.length > 0){

				var href = arr[0] + t;
				var head = document.getElementsByTagName('HEAD').item(0);
				var is_run = true;
				$("link").each(function(){

					var tmp = window.location.href.split("/");
					var end_length = tmp[tmp.length - 1].length;

					var complete_href = (window.location.href.substr(0, window.location.href.length - end_length) + href);

					if(complete_href == this.href){
						is_run = false;
					}
				});

				if(is_run){
					var style = document.createElement('link');
					style.href = href;
					style.rel = 'stylesheet';
					style.type = 'text/css';
					head.appendChild(style);

					cssReady(style, function(){
						construct();

					});

				}else{
					construct();
				}

				function construct(){
					var tmp_arr = arr.slice(0);
					tmp_arr.shift();

					var tmp = __this.css;
					__this.css(tmp_arr, callback);
				}

			}else{
				callback && callback();
			}
		}

		this.js = function(arr, callback){
			var __js = this;

			if(arr.length > 0){
				var src = arr[0] + t;
				var body = document.getElementsByTagName('body').item(0);
				var is_run = true;
				var script;
				$("script").each(function(){

					var tmp = window.location.href.split("/");
					var end_length = tmp[tmp.length - 1].length;

					var complete_src = (window.location.href.substr(0, window.location.href.length - end_length) + src);

					if(complete_src == this.src){
						is_run = false;
						script = this;

					}
				});

				if(is_run){
					script = document.createElement('script');
					script.src = src;
					script.type = 'text/javascript';
					body.appendChild(script);
					jsReady(script, function(){

						construct();
					});
				}else{
					construct();
				}

				function construct(){
					var js_name = arr[0];
						js_name = js_name.replace(/\//g, '.');
						js_name = js_name.substr(0, js_name.length - 3);
					eval("try{" + js_name + "&&" + js_name + "()} catch(e) {}");

					var tmp_arr = arr.slice(0);

					tmp_arr.shift();
					var tmp = __this.js;
					tmp(tmp_arr, callback);
				}

			}else{
				callback && callback();
			}

		}
	}

	/**
	 * 等待CSS加载并渲染完毕
	 * @param  {Function} fn   [description]
	 * @param  {[type]}   link [description]
	 * @return {[type]}        [description]
	 */
	function cssReady(style, fn) {
		var d = document,
		t = d.createStyleSheet,
		r = t ? 'rules' : 'cssRules',
		s = t ? 'styleSheet' : 'sheet',
		l = d.getElementsByTagName('link');
		// passed link or last link node
		style || (style = l[l.length - 1]);

		function check() {
			try {
				return style && style[s] && style[s][r] && style[s][r];
			} catch(e) {

				return false;
			}
		}

		(function poll() {
			check() && setTimeout(fn, 0) || setTimeout(poll, 100);
		})();
	}

	function jsReady(script, fn){

		script.onload=script.onreadystatechange=function(){
		   if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete'){

			   script.onload=script.onreadystatechange=null;
			   setTimeout(fn, 0);
			}
			//
		}
	}

	/**
	 * 对象合并[递归级]
	 * @param  {[type]} obj1 [description]
	 * @param  {[type]} obj2 [description]
	 * @return {[type]}      [description]
	 */
	function object_merge(obj1, obj2){
		// for(var i in obj1){

			for(var j in obj2){
				if(obj1.hasOwnProperty(j) && (typeof(obj1[j]) == 'object')){
					if(typeof(obj2[j]) == 'object'){
						obj1[j] = object_merge(obj1[j], obj2[j]);
					}
				}else{
					obj1[j] = obj2[j];
				}
			}

			return obj1;
		// }
	}

	/**
	 * 检测浏览器是否支持html5
	 * @return {Boolean} [description]
	 */
	function is_html5(){
		var my_canvas = $("<canvas style='position: absolute; top: 0; z-index: -1;'/>");
		$("body").append(my_canvas);
		if(!my_canvas.get(0).getContext){

			return false;
		}
		return true;
	}

	var load = new load();

	//封装一个获取 时间格式为 yyyy/mm/dd  的方法
	w.getFormatDate = function(dateTmie){
		var myDate = new Date(dateTmie*1000);
		var yy = myDate.getFullYear();
		var mm = myDate.getMonth()+1;
		var dd = myDate.getDate();
		return yy + "/" + getTwo(mm) + "/" + getTwo(dd);
		//获取两位数
		function getTwo(num){
			if(num<10){
				return "0" + num;
			}else{
				return num;
			}
		}
	}

	/**
	 * 消息弹出
	 * @param  {[type]} msg         [description]
	 * @param  {[type]} m_width     [description]
	 * @param  {[type]} m_height    [description]
	 * @param  {[type]} m_loop_time [description]
	 * @param  {[type]} m_type      [description]
	 * @return {[type]}             [description]
	 */
	var alert_message = function(msg, m_width, m_height, m_loop_time, m_type){

		m_width = m_width ? m_width : '100%';
		m_height = m_height ? m_height : '2rem';
		m_loop_time = m_loop_time ? m_loop_time : 500;
		m_id = 'alert_' + (new Date()).getTime();

		b_height = $(window).height();
		var l_top = b_height / 2;

		var m_background_color = "rgb(255, 116, 116)";
		switch(m_type){
			case 'error':
				m_background_color = "rgb(255, 116, 116)";
				break;
			case 'success':
				m_background_color = "#65e26e";
				break;
			default:
				m_background_color = "rgb(255, 116, 116)";
				break;
		}
		var dom = $("
").css({
			width: m_width,
			height: m_height,
			background: m_background_color,
			position: 'fixed',
			zIndex: '9999',
			color: "#fff",
			textAlign: 'center',
			lineHeight: m_height,
			top: b_height
		}).attr('id', m_id).text(msg);

		$("body").append(dom);

		dom.animate({'top': l_top}, m_loop_time);

		setTimeout(function(){
			dom.remove();
		}, m_loop_time + 2000);

	}

	app.alert = {
		error: function(msg, m_width, m_height, m_loop_time){
			alert_message(msg, m_width, m_height, m_loop_time, 'error');
		},
		success: function(msg, m_width, m_height, m_loop_time){
			alert_message(msg, m_width, m_height, m_loop_time, 'success');
		}
	}

	w.app = app;
}(window));
<|endoftext|>


<commit_before>var mbaasApi = require('fh-mbaas-api');
var express = require('express');
var mbaasExpress = mbaasApi.mbaasExpress();
var cors = require('cors');

// list the endpoints which you want to make securable here
var securableEndpoints;
// fhlint-begin: securable-endpoints
securableEndpoints = [];
// fhlint-end

var app = express();

// Enable CORS for all requests
app.use(cors());

// Note: the order which we add middleware to Express here is important!
app.use('/sys', mbaasExpress.sys(securableEndpoints));
app.use('/mbaas', mbaasExpress.mbaas);

// Note: important that this is added just before your own Routes
app.use(mbaasExpress.fhmiddleware());

// allow serving of static files from the public directory
app.use(express.static(__dirname + '/public'));

// fhlint-begin: custom-routes
app.use('/cloud', mbaasExpress.cloud(require('./main.js')));
// fhlint-end

// Important that this is last!
app.use(mbaasExpress.errorHandler());

var port = process.env.FH_PORT || process.env.VCAP_APP_PORT || 8001;
app.listen(port, function() {
  console.log("App started at: " + new Date() + " on port: " + port);
});
<commit_msg>move static file server before middleware routes - #8134<commit_after>var mbaasApi = require('fh-mbaas-api');
var express = require('express');
var mbaasExpress = mbaasApi.mbaasExpress();
var cors = require('cors');

// list the endpoints which you want to make securable here
var securableEndpoints;
// fhlint-begin: securable-endpoints
securableEndpoints = [];
// fhlint-end

var app = express();

// Enable CORS for all requests
app.use(cors());

// Note: the order which we add middleware to Express here is important!
app.use('/sys', mbaasExpress.sys(securableEndpoints));
app.use('/mbaas', mbaasExpress.mbaas);

// allow serving of static files from the public directory
app.use(express.static(__dirname + '/public'));

// Note: important that this is added just before your own Routes
app.use(mbaasExpress.fhmiddleware());

// fhlint-begin: custom-routes
app.use('/cloud', mbaasExpress.cloud(require('./main.js')));
// fhlint-end

// Important that this is last!
app.use(mbaasExpress.errorHandler());

var port = process.env.FH_PORT || process.env.VCAP_APP_PORT || 8001;
app.listen(port, function() {
  console.log("App started at: " + new Date() + " on port: " + port);
});
<|endoftext|>


<commit_before>var mbaasApi = require('fh-mbaas-api');
var express = require('express');
var mbaasExpress = mbaasApi.mbaasExpress();
var cors = require('cors');

// list the endpoints which you want to make securable here
var securableEndpoints;
// fhlint-begin: securable-endpoints
securableEndpoints = ['hello'];
// fhlint-end

var app = express();

// Enable CORS for all requests
app.use(cors());

// Note: the order which we add middleware to Express here is important!
app.use('/sys', mbaasExpress.sys(securableEndpoints));
app.use('/mbaas', mbaasExpress.mbaas);

// Note: important that this is added just before your own Routes
app.use(mbaasExpress.fhmiddleware());

// allow serving of static files from the public directory
app.use(express.static(__dirname + '/public'));

// fhlint-begin: custom-routes
app.use('/hello', require('./lib/hello.js')());
// fhlint-end

// Important that this is last!
app.use(mbaasExpress.errorHandler());

var port = process.env.FH_PORT || process.env.VCAP_APP_PORT || 8001;
var server = app.listen(port, function() {
  console.log("App started at: " + new Date() + " on port: " + port);
});<commit_msg>move static file server before middleware routes - #8134<commit_after>var mbaasApi = require('fh-mbaas-api');
var express = require('express');
var mbaasExpress = mbaasApi.mbaasExpress();
var cors = require('cors');

// list the endpoints which you want to make securable here
var securableEndpoints;
// fhlint-begin: securable-endpoints
securableEndpoints = ['hello'];
// fhlint-end

var app = express();

// Enable CORS for all requests
app.use(cors());

// Note: the order which we add middleware to Express here is important!
app.use('/sys', mbaasExpress.sys(securableEndpoints));
app.use('/mbaas', mbaasExpress.mbaas);

// allow serving of static files from the public directory
app.use(express.static(__dirname + '/public'));

// Note: important that this is added just before your own Routes
app.use(mbaasExpress.fhmiddleware());

// fhlint-begin: custom-routes
app.use('/hello', require('./lib/hello.js')());
// fhlint-end

// Important that this is last!
app.use(mbaasExpress.errorHandler());

var port = process.env.FH_PORT || process.env.VCAP_APP_PORT || 8001;
var server = app.listen(port, function() {
  console.log("App started at: " + new Date() + " on port: " + port);
});
<|endoftext|>


<commit_before>function guessStation(input){
    query = input.val();
    $.ajax({
        url: 'https://db-hafas.juliuste.de/locations?query='+query,
        dataType: 'json',
        success: function(res){
            console.log(res[0].id);
            if(res.length>0&&!input.next('input').attr('value')){
                input.attr('value', res[0].id);
                input.val(res[0].name);
            }
            else{
                input.val(null);
            }
        },
        error: function(data){
            input.val(null);
        }
    });
}
// AUTO COMPLETION

$('#from').autocomplete({
	serviceUrl: 'https://db-hafas.juliuste.de/locations',
	paramName: 'query',
	transformResult: function(response) {
		return {
			suggestions: $.map($.parseJSON(response).slice(0,5), function(dataItem) {
				return { value: dataItem.name, data: dataItem.id};
			})
		}
	},
	onSelect: function(suggestion) {
		$('#from').attr('value', suggestion.value);
        $('#from-id').attr('value', suggestion.data);
		$('#to').focus();
	}
})

$('#to').autocomplete({
	serviceUrl: 'https://db-hafas.juliuste.de/locations',
	paramName: 'query',
	transformResult: function(response) {
		return {
			suggestions: $.map($.parseJSON(response).slice(0,5), function(dataItem) {
				return { value: dataItem.name, data: dataItem.id};
			})
		}
	},
	onSelect: function(suggestion) {
		$('#to').attr('value', suggestion.value);
        $('#to-id').attr('value', suggestion.data);
		$('#submit').focus();
	}
})

$('.station').focusout(function(){
    if(!$(this).attr('value')){
        guessStation($(this));
    }
});<commit_msg>bugfix :bug:<commit_after>function guessStation(input){
    query = input.val();
    $.ajax({
        url: 'https://db-hafas.juliuste.de/locations?query='+query,
        dataType: 'json',
        success: function(res){
            console.log(res[0].id);
            if(res.length>0){
                if(!input.next('input').attr('value')){
                	input.attr('value', res[0].id);
                	input.val(res[0].name);
                }
            }
            else{
                input.val(null);
            }
        },
        error: function(data){
            input.val(null);
        }
    });
}
// AUTO COMPLETION

$('#from').autocomplete({
	serviceUrl: 'https://db-hafas.juliuste.de/locations',
	paramName: 'query',
	transformResult: function(response) {
		return {
			suggestions: $.map($.parseJSON(response).slice(0,5), function(dataItem) {
				return { value: dataItem.name, data: dataItem.id};
			})
		}
	},
	onSelect: function(suggestion) {
		$('#from').attr('value', suggestion.value);
        $('#from-id').attr('value', suggestion.data);
		$('#to').focus();
	}
})

$('#to').autocomplete({
	serviceUrl: 'https://db-hafas.juliuste.de/locations',
	paramName: 'query',
	transformResult: function(response) {
		return {
			suggestions: $.map($.parseJSON(response).slice(0,5), function(dataItem) {
				return { value: dataItem.name, data: dataItem.id};
			})
		}
	},
	onSelect: function(suggestion) {
		$('#to').attr('value', suggestion.value);
        $('#to-id').attr('value', suggestion.data);
		$('#submit').focus();
	}
})

$('.station').focusout(function(){
    if(!$(this).attr('value')){
        guessStation($(this));
    }
});<|endoftext|>


<commit_before>var scenes = [];

function updateStatus() {
  let xhr = new XMLHttpRequest();
  xhr.open('GET', 'http://localhost:6060/renders');
  xhr.onload = function() {
    let obj = JSON.parse(this.response);
    let statusTxt = `

          scene name
          px high
          px wide
          passes
          completed
          workers
          image

    `;
    for (let i = 0; i < obj.length; i++) {
      statusTxt += `

          ${obj[i].scene}
          ${obj[i].px_high}
          ${obj[i].px_wide}
          ${obj[i].passes}
          ${obj[i].completed}
          <button class="worker" uuid=${obj[i].uuid} workers=${obj[i].workers-1}>-</button>
          ${obj[i].workers}
          <button class="worker" uuid=${obj[i].uuid} workers=${obj[i].workers+1}>+</button>

            image

`
    }
    statusTxt += '
';
    document.getElementById('status').innerHTML = statusTxt;

    let buttons = document.getElementsByClassName('worker');
    for (let i = 0; i < buttons.length; i++) {
      let btn = buttons[i];
      btn.addEventListener("click", function() {
        let xhr = new XMLHttpRequest();
        let uuid = btn.getAttribute('uuid');
        xhr.open('PUT', `http://localhost:6060/renders/${uuid}/workers`);
        xhr.onload = updateStatus;
        let workers = btn.getAttribute('workers');
        xhr.send(workers);
      });
    }
  };
  xhr.send();
}

window.setInterval(updateStatus, 250);

function populateSceneSelector() {
  let xhr = new XMLHttpRequest();
  xhr.open('GET', 'http://localhost:6060/scenes');
  xhr.onload = function () {
    if (this.status != 200) {
      alert(this.status);
      return;
    }
    scenes = JSON.parse(this.response);
    let inner = '';
    for (let i = 0; i < scenes.length; i++) {
      inner += `<option value="${scenes[i].code}">${scenes[i].code}</option>`;
    }
    document.getElementById('scene-selection').innerHTML = inner;
    populateResolutionCheckboxes();
  };
  xhr.send();
}

document.getElementById('scene-selection').addEventListener("change", populateResolutionCheckboxes);

populateSceneSelector();

function populateResolutionCheckboxes() {
  let resolutionsDiv = document.getElementById('resolutions');
  let selected = document.getElementById('scene-selection').value;
  let xWides = [640, 800, 1024];
  for (let i = 0; i < scenes.length; i++) {
    let scene = scenes[i];
    if (selected == scene.code) {
      let inner = '';
      for (let j = 0; j < xWides.length; j++) {
        let pxWide = xWides[j];
        let pxHigh = scene.aspect_high * pxWide / scene.aspect_wide;
        inner += `<option value="${pxWide}">${pxWide}x${pxHigh}</option>`;
      }
      resolutionsDiv.innerHTML = inner;
      return;
    }
  }
  resolutionsDiv.innerHTML = ''; // Couldn't find the selected scene.
}

function handleAddResource() {
  let uuid = '';
  let xhr = new XMLHttpRequest();
  xhr.open('POST', 'http://localhost:6060/renders', false);
  xhr.onload = function() {
    if (this.status != 200) {
      alert(this.status);
      return;
    }
    let data = JSON.parse(this.response);
    uuid = data.uuid;
    updateStatus();
  }
  xhr.send(JSON.stringify({
    scene: document.getElementById('scene-selection').value,
    px_wide: Number(document.getElementById('resolutions').value),
  }));
}

document.getElementById("add-resource").addEventListener("click", handleAddResource)
<commit_msg>Increase resolutions. Filter out bad resolutions.<commit_after>var scenes = [];

function updateStatus() {
  let xhr = new XMLHttpRequest();
  xhr.open('GET', 'http://localhost:6060/renders');
  xhr.onload = function() {
    let obj = JSON.parse(this.response);
    let statusTxt = `

          scene name
          px high
          px wide
          passes
          completed
          workers
          image

    `;
    for (let i = 0; i < obj.length; i++) {
      statusTxt += `

          ${obj[i].scene}
          ${obj[i].px_high}
          ${obj[i].px_wide}
          ${obj[i].passes}
          ${obj[i].completed}
          <button class="worker" uuid=${obj[i].uuid} workers=${obj[i].workers-1}>-</button>
          ${obj[i].workers}
          <button class="worker" uuid=${obj[i].uuid} workers=${obj[i].workers+1}>+</button>

            image

`
    }
    statusTxt += '
';
    document.getElementById('status').innerHTML = statusTxt;

    let buttons = document.getElementsByClassName('worker');
    for (let i = 0; i < buttons.length; i++) {
      let btn = buttons[i];
      btn.addEventListener("click", function() {
        let xhr = new XMLHttpRequest();
        let uuid = btn.getAttribute('uuid');
        xhr.open('PUT', `http://localhost:6060/renders/${uuid}/workers`);
        xhr.onload = updateStatus;
        let workers = btn.getAttribute('workers');
        xhr.send(workers);
      });
    }
  };
  xhr.send();
}

window.setInterval(updateStatus, 250);

function populateSceneSelector() {
  let xhr = new XMLHttpRequest();
  xhr.open('GET', 'http://localhost:6060/scenes');
  xhr.onload = function () {
    if (this.status != 200) {
      alert(this.status);
      return;
    }
    scenes = JSON.parse(this.response);
    let inner = '';
    for (let i = 0; i < scenes.length; i++) {
      inner += `<option value="${scenes[i].code}">${scenes[i].code}</option>`;
    }
    document.getElementById('scene-selection').innerHTML = inner;
    populateResolutionCheckboxes();
  };
  xhr.send();
}

document.getElementById('scene-selection').addEventListener("change", populateResolutionCheckboxes);

populateSceneSelector();

function populateResolutionCheckboxes() {
  let resolutionsDiv = document.getElementById('resolutions');
  let selected = document.getElementById('scene-selection').value;
  let xWides = [640, 800, 1024, 1152, 1280, 1400, 1440, 1680, 1920, 2048, 2560, 2880, 3840, 4096, 5120];
  for (let i = 0; i < scenes.length; i++) {
    let scene = scenes[i];
    if (selected == scene.code) {
      let inner = '';
      for (let j = 0; j < xWides.length; j++) {
        let pxWide = xWides[j];
        if ((scene.aspect_high * pxWide) % scene.aspect_wide === 0) {
          let pxHigh = scene.aspect_high * pxWide / scene.aspect_wide;
          inner += `<option value="${pxWide}">${pxWide}x${pxHigh}</option>`;
        }
      }
      resolutionsDiv.innerHTML = inner;
      return;
    }
  }
  resolutionsDiv.innerHTML = ''; // Couldn't find the selected scene.
}

function handleAddResource() {
  let uuid = '';
  let xhr = new XMLHttpRequest();
  xhr.open('POST', 'http://localhost:6060/renders', false);
  xhr.onload = function() {
    if (this.status != 200) {
      alert(this.status);
      return;
    }
    let data = JSON.parse(this.response);
    uuid = data.uuid;
    updateStatus();
  }
  xhr.send(JSON.stringify({
    scene: document.getElementById('scene-selection').value,
    px_wide: Number(document.getElementById('resolutions').value),
  }));
}

document.getElementById("add-resource").addEventListener("click", handleAddResource)
<|endoftext|>


<commit_before>$(function() {

	var

		client = ZAFClient.init(),

		attachments = [],

		path = "ticket.comments",

		$download = $('#download'),
		$list = $('#list'),
		$message = $('#message'),
		$status = $('#status'),
		$progress = $('#progress'),

		findAttachments = function() {
			return client.get(path).then(function(response) {
				var allComments = response[path];
				attachments = $.map($.makeArray(allComments), function(comment) {
					return [].concat(comment.imageAttachments).concat(comment.nonImageAttachments);
				});
				return new Promise(function(resolve, reject) {
					if (!$.isArray(attachments) || attachments.length === 0) {
						reject("No attachments found in this ticket.");
					} else {
						resolve();
					}
				});
			});
		},

		displayAttachments = function() {
			var html = $.map(attachments, function(attachment) {
				return (
					"
" +
					""+attachment.filename+"" +
					"
"
				)
			});
			$list.
				append(html).
				toggle()
			;
			message("" + attachments.length + " attachment" + (attachments.length == 1 ? "" : "s") + " found in this ticket.");
		},

		makeZip = function() {
			var zip = new JSZip();
			$.each(attachments, function(index, attachment) {
				zip.file(
					attachment.filename,
					urlToPromise(attachment.contentUrl),
					{
						binary:true
					}
				);
			});
			return zip;
		},

		downloadAttachments = function() {
			var first = true;
			return makeZip()
			.generateAsync({type:"blob"}, function updateCallback(metadata) {

				if (first) {
					$progress.parent().show();
					first = false;
				}

				var percent = metadata.percent;

				$progress
				.attr('aria-valuenow', percent)
				.width(percent+"%");

				status("Making ZIP: " + percent.toFixed(2) + "%");
			})
			.then(function (blob) {
				client.context().then(function(context) {
					var filename = "Zendesk-";
					filename += context.ticketId;
					filename += "-attachments-";
					filename += new Date().getTime();
					filename += ".zip";
					saveAs(blob, filename);
				})
			});
		},

		message = function(message) {
			display($message, message);
		},

		status = function(message) {
			display($status, message);
		},

		display = function($element, message) {
			$element.html(message);
		},

		show = function($element) {
			$element.show(600);
		},

		hide = function($element) {
			$element.hide(600);
		}
	;

	// EVENT HANDLERS //

	client.on('app.registered', function appRegistered(event) {
		$progress.parent().hide();
		findAttachments()
		.then(function() {
			attachments.sort(function(a,b) {
				return a.filename > b.filename ? 1 : a.filename < b.filename ? -1 : 0;
			});
			displayAttachments();
			$download.show();
		})
		.catch(function(err) {
			message(err);
			$download.hide();
		})
		.then(function() {
			$('#container').show();
		});
	});

	client.on('ticket.comments.changed', function(event) {
		console.log(event);
	});

	$download.on("click", function() {
		hide($message);
		$download.hide();
		show($status);
		status("Fetching attachments...");
		downloadAttachments().
		then(function() {
			status("ZIP done!");
			setTimeout(function() {
				hide($status);
				hide($progress.parent());
				show($message);
				show($download);
			}, 2000);
		});
	});

	$message.on("click", function() {
		$list.slideToggle();
	});

});

/**
 * Fetch the content and return the associated promise.
 * @param {String} url the url of the content to fetch.
 * @return {Promise} the promise containing the data.
 */
function urlToPromise(url) {
	return new Promise(function(resolve, reject) {
		JSZipUtils.getBinaryContent(url, function (err, data) {
			if(err) {
				reject(err);
			} else {
				resolve(data);
			}
		});
	});
}

<commit_msg>Use strict<commit_after>$(function() {

	'use strict';

	var

		client = ZAFClient.init(),

		attachments = [],

		path = "ticket.comments",

		$download = $('#download'),
		$list = $('#list'),
		$message = $('#message'),
		$status = $('#status'),
		$progress = $('#progress'),

		findAttachments = function() {
			return client.get(path).then(function(response) {
				var allComments = response[path];
				attachments = $.map($.makeArray(allComments), function(comment) {
					return [].concat(comment.imageAttachments).concat(comment.nonImageAttachments);
				});
				return new Promise(function(resolve, reject) {
					if (!$.isArray(attachments) || attachments.length === 0) {
						reject("No attachments found in this ticket.");
					} else {
						resolve();
					}
				});
			});
		},

		displayAttachments = function() {
			var html = $.map(attachments, function(attachment) {
				return (
					"
" +
					""+attachment.filename+"" +
					"
"
				)
			});
			$list.
				append(html).
				toggle()
			;
			message("" + attachments.length + " attachment" + (attachments.length == 1 ? "" : "s") + " found in this ticket.");
		},

		makeZip = function() {
			var zip = new JSZip();
			$.each(attachments, function(index, attachment) {
				zip.file(
					attachment.filename,
					urlToPromise(attachment.contentUrl),
					{
						binary:true
					}
				);
			});
			return zip;
		},

		downloadAttachments = function() {
			var first = true;
			return makeZip()
			.generateAsync({type:"blob"}, function updateCallback(metadata) {

				if (first) {
					$progress.parent().show();
					first = false;
				}

				var percent = metadata.percent;

				$progress
				.attr('aria-valuenow', percent)
				.width(percent+"%");

				status("Making ZIP: " + percent.toFixed(2) + "%");
			})
			.then(function (blob) {
				client.context().then(function(context) {
					var filename = "Zendesk-";
					filename += context.ticketId;
					filename += "-attachments-";
					filename += new Date().getTime();
					filename += ".zip";
					saveAs(blob, filename);
				})
			});
		},

		message = function(message) {
			display($message, message);
		},

		status = function(message) {
			display($status, message);
		},

		display = function($element, message) {
			$element.html(message);
		},

		show = function($element) {
			$element.show(600);
		},

		hide = function($element) {
			$element.hide(600);
		}
	;

	// EVENT HANDLERS //

	client.on('app.registered', function appRegistered(event) {
		$progress.parent().hide();
		findAttachments()
		.then(function() {
			attachments.sort(function(a,b) {
				return a.filename > b.filename ? 1 : a.filename < b.filename ? -1 : 0;
			});
			displayAttachments();
			$download.show();
		})
		.catch(function(err) {
			message(err);
			$download.hide();
		})
		.then(function() {
			$('#container').show();
		});
	});

	client.on('ticket.comments.changed', function(event) {
		console.log(event);
	});

	$download.on("click", function() {
		hide($message);
		$download.hide();
		show($status);
		status("Fetching attachments...");
		downloadAttachments().
		then(function() {
			status("ZIP done!");
			setTimeout(function() {
				hide($status);
				hide($progress.parent());
				show($message);
				show($download);
			}, 2000);
		});
	});

	$message.on("click", function() {
		$list.slideToggle();
	});

});

/**
 * Fetch the content and return the associated promise.
 * @param {String} url the url of the content to fetch.
 * @return {Promise} the promise containing the data.
 */
function urlToPromise(url) {
	return new Promise(function(resolve, reject) {
		JSZipUtils.getBinaryContent(url, function (err, data) {
			if(err) {
				reject(err);
			} else {
				resolve(data);
			}
		});
	});
}

<|endoftext|>


<commit_before>"use strict";

let max = 2147483647;

module.exports = async function sleep(timeout) {
  if(isNaN(timeout) || typeof timeout != "number")
    return;

  /* istanbul ignore else */
  if(timeout <= max) {
    return new Promise(function(resolve) {
      setTimeout(resolve, timeout);
    });
  } else {
    let t = Math.floor(timeout / max), r = timeout % max;
    for(let i = 0; i < t; i++)
      await sleep(max);

    return sleep(r);
  }
};
<commit_msg>More broad test<commit_after>"use strict";

let max = 2147483647;

module.exports = async function sleep(timeout) {
  if(!timeout)
    return;

  /* istanbul ignore else */
  if(timeout <= max) {
    return new Promise(function(resolve) {
      setTimeout(resolve, timeout);
    });
  } else {
    let t = Math.floor(timeout / max), r = timeout % max;
    for(let i = 0; i < t; i++)
      await sleep(max);

    return sleep(r);
  }
};
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 Sam-Mauris Yong. All rights reserved.
 * This file is part of the asyncloader.js project, which is released under New BSD 3-Clause license.
 * See file LICENSE or go to http://opensource.org/licenses/BSD-3-Clause for full license details.
 */

var AsyncLoader = (function(loader, d){
    var s = 'script',
        fjs = d.getElementsByTagName(s)[0],
        waiting = [];

    var removeInArray = function(arr) {
        var what, a = arguments, L = a.length, ax;
        while (L > 1 && arr.length) {
            what = a[--L];
            while ((ax = arr.indexOf(what)) !== -1) {
                arr.splice(ax, 1);
            }
        }
        return arr;
    };

    var processWaiting = function(id){
        for (var idx in waiting) {
            var item = waiting[idx];
            item.depends = removeInArray(item.depends, id);
            if (item.depends.length == 0) {
                if( typeof item.url === 'function') {
                    item.url();
                } else {
                    loader.add(item.url, item.id, item.load);
                }
            }
        }
    };

    loader.add = function(u, id, load) {
        if (d.getElementById(id)) {return;}
        var js = d.createElement(s);
        js.src = u;
        id && (js.id = id);
        js.onload = function(){
            load && load.call(this);
            processWaiting(id);
        };
        fjs.parentNode.insertBefore(js, fjs);
    };

    loader.depends = function(depends, url, id, load){
        depends = typeof depends == 'string' ? [depends] : depends;
        waiting.push({
            depends: depends || [],
            url: url,
            id: id,
            load: load
        });
    };

    return loader;
})(AsyncLoader || {}, document);<commit_msg>experimenting with window.setTimeout(fn, 0);<commit_after>/*
 * Copyright (C) 2013 Sam-Mauris Yong. All rights reserved.
 * This file is part of the asyncloader.js project, which is released under New BSD 3-Clause license.
 * See file LICENSE or go to http://opensource.org/licenses/BSD-3-Clause for full license details.
 */

var AsyncLoader = (function(loader, d){
    var s = 'script',
        fjs = d.getElementsByTagName(s)[0],
        waiting = [];

    var removeInArray = function(arr) {
        var what, a = arguments, L = a.length, ax;
        while (L > 1 && arr.length) {
            what = a[--L];
            while ((ax = arr.indexOf(what)) !== -1) {
                arr.splice(ax, 1);
            }
        }
        return arr;
    };

    var processWaiting = function(id){
        for (var idx in waiting) {
            var item = waiting[idx];
            item.depends = removeInArray(item.depends, id);
            if (item.depends.length == 0) {
                if( typeof item.url === 'function') {
                    item.url();
                } else {
                    window.setTimeout(function(){
                        loader.add(item.url, item.id, item.load);
                    }, 0);
                }
            }
        }
    };

    loader.add = function(u, id, load) {
        if (d.getElementById(id)) {return;}
        var js = d.createElement(s);
        js.src = u;
        id && (js.id = id);
        js.onload = function(){
            load && load.call(this);
            processWaiting(id);
        };
        fjs.parentNode.insertBefore(js, fjs);
    };

    loader.depends = function(depends, url, id, load){
        depends = typeof depends == 'string' ? [depends] : depends;
        waiting.push({
            depends: depends || [],
            url: url,
            id: id,
            load: load
        });
    };

    return loader;
})(AsyncLoader || {}, document);<|endoftext|>


<commit_before>var assert = require("assert");
var pg = require("pg");
var fs = require("fs");

describe('Array', function(){
	describe('#indexOf()', function(){
		it('should return -1 when the value is not present', function(){
      		assert.equal(-1, [1,2,3].indexOf(5));
      		assert.equal(-1, [1,2,3].indexOf(0));
    	})
  	})
});

describe('PostgreSQL', function() {
	describe('DATABASE_URL test', function() {
		it('should fail when DATABASE_URL is not set', function() {
			assert.notEqual(process.env.DATABASE_URL, undefined, 'DATABASE_URL is undefined');
			console.log("DATABASE_URL: '"+process.env.DATABASE_URL+"'");
		});
	});

	describe('create user table', function() {
		it('should fail when unable to create the user table', function() {
			var entered = false;
			pg.connect(process.env.DATABASE_URL, function (err, client) {
				console.log("CONNECTED");
				entered = true;
				assert.ifError(err);
				assert.equal(true, fs.existsSync('databases/users.sql'));
				client.query(fs.readFileSync('databases/user.sql'), function (err, result) {
					assert.ifError(err);
				});
			});
			assert.equal(true, entered, 'PostgreSQL connection failed.');
		})
	})
});<commit_msg>tester<commit_after>var assert = require("assert");
var pg = require("pg");
var fs = require("fs");

describe('Array', function(){
	describe('#indexOf()', function(){
		it('should return -1 when the value is not present', function(){
      		assert.equal(-1, [1,2,3].indexOf(5));
      		assert.equal(-1, [1,2,3].indexOf(0));
    	})
  	})
});

describe('PostgreSQL', function() {
	describe('DATABASE_URL test', function() {
		it('should fail when DATABASE_URL is not set', function() {
			assert.notEqual(process.env.DATABASE_URL, undefined, 'DATABASE_URL is undefined');
			console.log("DATABASE_URL: '"+process.env.DATABASE_URL+"'");
		});
	});

	describe('create user table', function() {
		it('should fail when unable to create the user table', function() {
			var entered = false;
			pg.connect(process.env.DATABASE_URL, function (err, client) {
				console.log("CONNECTED");
				entered = true;
				assert.ifError(err);
				assert.equal(true, fs.existsSync('databases/users.sql'));
				client.query(fs.readFileSync('databases/user.sql'), function (err, result) {
					assert.ifError(err);
				});
			});
			//assert.equal(true, entered, 'PostgreSQL connection failed.');
		})
	})
});<|endoftext|>


<commit_before>'use strict';

const chai = require('chai'),
    expect = chai.expect,
    should = chai.should(),
    RxMongo = require('./../lib/RxMongo.js');

const collectionName = 'RadioStations';
const collectionInsert = 'InsertCollection';

describe('RxMongo', function() {
    before(function(done){
        RxMongo.connect('mongodb://localhost/rxmongo_test').subscribe(db => {
            // database connected
        }, err => console.log(`Err: ${err}`), () => done());
    });

    describe('.count(collection, query, options)', function(){
        describe('.count(collection)', function(done){
            it('should count of all documents in collection', function(done){
                RxMongo.collection(collectionName)
                        .flatMap(coll => RxMongo.count(coll))
                        .subscribe(count => {
                            expect(count > 1).to.be.true;
                        }, err => console.log(`Err: ${err}`), () => done());
            });
        });

        describe('.count(collection, query)', function(done){
            it('should count of all documents in collection matching the given query', function(done){
                const query = { categories: { $in: [new RegExp('music', 'i')] } };

                RxMongo.collection(collectionName)
                        .flatMap(coll => RxMongo.count(coll, query))
                        .subscribe(count => {
                            expect(count === 8).to.be.true;
                        }, err => console.log(`Err: ${err}`), () => done());
            });
        });
    });

    describe('.aggregate(collection, aggregationPipeline)', function(){
        it('should return documents based on aggregationPipeline', function(done){
            const aggregations = [
                {$unwind: '$categories'},
                {$group: {_id: '$categories', count: {$sum: 1}}},
                {$project: {name: '$_id', _id: 0, count: 1}}
            ];

            RxMongo.collection(collectionName)
                    .flatMap(coll => RxMongo.aggregate(coll, aggregations))
                    .subscribe(result => {
                        expect(result.length === 5).to.be.true;
                    }, err => console.log(`Error: ${err}`), () => done());
        });
    });

    describe('.insert(collection, docs)', function(){
        it('should insert single json document in provided collection', function(done){
            const doc = {
                name: 'single',
                items: ['one', 'two', 'three']
            };

            RxMongo.collection(collectionInsert)
                    .flatMap(coll => RxMongo.insert(coll, doc))
                    .subscribe(result => {
                        expect(result.insertedCount).to.equal(1);
                    }, err => console.log(`Error: ${err}`)
                    , () => done());
        });

        it('should insert an array of json documents in provided collection', function(done){
            const docs = [{
                name: 'array',
                items: ['arr1', 'arr2', 'arr3']
            }, {
                name: 'array',
                items: ['arr1', 'arr2', 'arr3']
            }];

            RxMongo.collection(collectionInsert)
                    .flatMap(coll => RxMongo.insert(coll, docs))
                    .subscribe(result => {
                        expect(result.insertedCount).to.equal(2);
                    }, err => console.log(`Error: ${err}`)
                    , () => done());
        });
    });

    describe('.updateOne(collection, filter, update)', function(){
        it('should update a single document based on filter condition', function(done){

            RxMongo.collection(collectionInsert)
                    .flatMap(coll => RxMongo.updateOne(coll, {name: 'array'}, {$set: {name: 'arrayUpdated'}}))
                    .subscribe(updates => {
                        expect(updates.result.ok).to.equal(1);
                    }, err => console.log(`Error: ${err}`)
                    , () => done());
        });
    });
});
<commit_msg>Added two RxCollection tests<commit_after>'use strict';

const chai = require('chai'),
    expect = chai.expect,
    should = chai.should(),
    RxMongo = require('./../lib/RxMongo'),
    RxCollection = require('./../lib/RxCollection');

const collectionName = 'RadioStations';
const collectionInsert = 'InsertCollection';

describe('RxMongo', function() {
    before(function(done){
        RxMongo.connect('mongodb://localhost/rxmongo_test').subscribe(db => {
            // database connected
        }, err => console.log(`Err: ${err}`), () => done());
    });

    describe('.count(collection, query, options)', function(){
        describe('.count(collection)', function(done){
            it('should count of all documents in collection', function(done){
                RxMongo.collection(collectionName)
                        .flatMap(coll => RxMongo.count(coll))
                        .subscribe(count => {
                            expect(count > 1).to.be.true;
                        }, err => console.log(`Err: ${err}`), () => done());
            });
        });

        describe('.count(collection, query)', function(done){
            it('should count of all documents in collection matching the given query', function(done){
                const query = { categories: { $in: [new RegExp('music', 'i')] } };

                RxMongo.collection(collectionName)
                        .flatMap(coll => RxMongo.count(coll, query))
                        .subscribe(count => {
                            expect(count === 8).to.be.true;
                        }, err => console.log(`Err: ${err}`), () => done());
            });
        });
    });

    describe('.aggregate(collection, aggregationPipeline)', function(){
        it('should return documents based on aggregationPipeline', function(done){
            const aggregations = [
                {$unwind: '$categories'},
                {$group: {_id: '$categories', count: {$sum: 1}}},
                {$project: {name: '$_id', _id: 0, count: 1}}
            ];

            RxMongo.collection(collectionName)
                    .flatMap(coll => RxMongo.aggregate(coll, aggregations))
                    .subscribe(result => {
                        expect(result.length === 5).to.be.true;
                    }, err => console.log(`Error: ${err}`), () => done());
        });
    });

    describe('.insert(collection, docs)', function(){
        it('should insert single json document in provided collection', function(done){
            const doc = {
                name: 'single',
                items: ['one', 'two', 'three']
            };

            RxMongo.collection(collectionInsert)
                    .flatMap(coll => RxMongo.insert(coll, doc))
                    .subscribe(result => {
                        expect(result.insertedCount).to.equal(1);
                    }, err => console.log(`Error: ${err}`)
                    , () => done());
        });

        it('should insert an array of json documents in provided collection', function(done){
            const docs = [{
                name: 'array',
                items: ['arr1', 'arr2', 'arr3']
            }, {
                name: 'array',
                items: ['arr1', 'arr2', 'arr3']
            }];

            RxMongo.collection(collectionInsert)
                    .flatMap(coll => RxMongo.insert(coll, docs))
                    .subscribe(result => {
                        expect(result.insertedCount).to.equal(2);
                    }, err => console.log(`Error: ${err}`)
                    , () => done());
        });
    });

    describe('.updateOne(collection, filter, update)', function(){
        it('should update a single document based on filter condition', function(done){

            RxMongo.collection(collectionInsert)
                    .flatMap(coll => RxMongo.updateOne(coll, {name: 'array'}, {$set: {name: 'arrayUpdated'}}))
                    .subscribe(updates => {
                        expect(updates.result.ok).to.equal(1);
                    }, err => console.log(`Error: ${err}`)
                    , () => done());
        });
    });

    describe('RxCollection', function(){
        describe('.find(query)', function(){
            it('should find documents based on query', function(done){
                new RxCollection(collectionName)
                            .find({})
                            .first()
                            .subscribe(docs => {
                                expect(docs).to.exist;
                                expect(docs).to.not.be.instanceOf(Array);
                            }, err => {
                                expect(err).to.not.exist;
                            },
                            () => done());
            });
        });

        describe('.count(query)', function(){
            it('should count number of documents in collection', function(done){
                new RxCollection(collectionName)
                            .count({})
                            .subscribe(count => {
                                expect(count).to.exist;
                                expect(count).to.equal(16);
                            }, err => {
                                expect(err).to.not.exist;
                            },
                            () => done());
            })
        });
    });
});
<|endoftext|>


<commit_before>var request = require('request');
var chai = require('chai');
var expect = chai.expect;
var App = require('../lib/routes');
var _ = require('lodash');

describe('All tests', function() {
  var baseUrl;
  var server;
  beforeEach(function(done) {
    server = require('http').createServer(new App());
    server.listen(0, function() {
      baseUrl = 'http://localhost:' + server.address().port;
      done();
    });
  });

  afterEach(function(done) {
    server.close(done);
  });

  function populateBuckets(cb) {
    request.put({ url: baseUrl + '/riak/bucket1/key1', json: { content1: 'val1' }, headers: { "x-riak-index-text_bin": "indexVal1", "x-riak-index-number_int": "1" } }, function() {
      request.put({ url: baseUrl + '/riak/bucket2/key2', json: { content2: 'val2' }, headers: { "x-riak-index-text_bin": "indexVal2", "x-riak-index-number_int": "2" }}, cb);
    });
  }

  describe('GET /buckets?buckets=true', function() {
    it('returns an empty list of buckets', function(done) {
      var route = baseUrl + '/buckets?buckets=true';
      request(route, function(err, res) {
        expect(res.headers['content-type']).to.contain('json');
        expect(res.statusCode).to.equal(200);
        var content = JSON.parse(res.body);
        expect(content).to.have.property('buckets').with.length(0);
        done();
      });
    });

    it('returns an list of buckets list of buckets', function(done) {
      var route = baseUrl + '/buckets?buckets=true';
      populateBuckets(function() {
        request(route, function(err, res) {
          expect(res.headers['content-type']).to.contain('json');
          expect(res.statusCode).to.equal(200);
          var content = JSON.parse(res.body);
          expect(content).to.have.property('buckets').with.length(2);
          done();
        });
      });
    });
  });

  describe('GET /riak/:bucket?keys=true', function() {
    it('returns an empty list of keys if no keys in bucket', function(done) {
      var route = baseUrl + '/riak/bucket1?keys=true';
      request(route, function(err, res) {
        expect(res.headers['content-type']).to.contain('json');
        expect(res.statusCode).to.equal(200);
        var content = JSON.parse(res.body);
        expect(content).to.have.property('keys').with.length(0);
        done();
      });
    });

    it('returns a list of all keys in this bucket', function(done) {
      var route = baseUrl + '/riak/bucket1?keys=true';
      populateBuckets(function() {
        request(route, function(err, res) {
          expect(res.headers['content-type']).to.contain('json');
          expect(res.statusCode).to.equal(200);
          var content = JSON.parse(res.body);
          expect(content).to.have.property('keys').with.length(1);
          done();
        });
      });
    });

    it('with stream=true returns a list of all keys in this bucket in a chunked encoding', function(done) {
      var route = baseUrl + '/riak/bucket1?keys=stream';
      populateBuckets(function() {
        request(route, function(err, res) {
          expect(res.headers['transfer-encoding']).to.equal('chunked');
          expect(res.headers['content-type']).to.contain('json');
          expect(res.statusCode).to.equal(200);
          var content = JSON.parse(res.body);
          expect(content).to.have.property('keys').with.length(1);
          done();
        });
      });
    });
  });

  var prefixes = ['riak', 'buckets'];
  _.each(prefixes, function(prefix) {
    describe('GET /'+prefix+'/:bucket/index/:indexName/:indexValue', function() {
      it('returns an empty list of keys if no keys match this indexValue', function(done) {
        var route = baseUrl + '/'+prefix+'/bucket1/index/text_bin/notFoundVal';
        populateBuckets(function() {
          request(route, function(err, res) {
            expect(res.headers['content-type']).to.contain('json');
            expect(res.statusCode).to.equal(200);
            var content = JSON.parse(res.body);
            expect(content).to.have.property('keys').with.length(0);
            done();
          });
        });
      });

      it('returns a of matching keys if the index matches', function(done) {
        var route = baseUrl + '/'+prefix+'/bucket1/index/text_bin/indexVal1';
        populateBuckets(function() {
          request(route, function(err, res) {
            expect(res.headers['content-type']).to.contain('json');
            expect(res.statusCode).to.equal(200);
            var content = JSON.parse(res.body);
            expect(content).to.have.property('keys').with.length(1);
            done();
          });
        });
      });

      it('can also handle numeric indexes', function(done) {
        var route = baseUrl + '/'+prefix+'/bucket1/index/number_int/1';
        populateBuckets(function() {
          request(route, function(err, res) {
            expect(res.headers['content-type']).to.contain('json');
            expect(res.statusCode).to.equal(200);
            var content = JSON.parse(res.body);
            expect(content).to.have.property('keys').with.length(1);
            done();
          });
        });
      });
    });

    describe('GET /'+prefix+'/:bucket/index/:indexName/:indexFrom/:indexTo', function() {
      it('returns an empty list of keys if no keys match this indexValue', function(done) {
        var route = baseUrl + '/'+prefix+'/bucket1/index/number_int/1000/1001';
        populateBuckets(function() {
          request(route, function(err, res) {
            expect(res.headers['content-type']).to.contain('json');
            expect(res.statusCode).to.equal(200);
            var content = JSON.parse(res.body);
            expect(content).to.have.property('keys').with.length(0);
            done();
          });
        });
      });

      it('returns a of matching keys if the index range matches', function(done) {
        var route = baseUrl + '/'+prefix+'/bucket1/index/number_int/0/2';
        populateBuckets(function() {
          request(route, function(err, res) {
            expect(res.headers['content-type']).to.contain('json');
            expect(res.statusCode).to.equal(200);
            var content = JSON.parse(res.body);
            expect(content).to.have.property('keys').with.length(1);
            done();
          });
        });
      });
    });
  });

  describe('GET /riak/:bucket/:key', function() {
    it('returns a 404 with "not found" if the key does not exist', function(done) {
      var route = baseUrl + '/riak/bucket1/key1';
      request(route, function(err, res) {
        expect(res.statusCode).to.equal(404);
        expect(res.body).to.equal('not found');
        done();
      });
    });

    it('returns data for a get request', function(done) {
      var route = baseUrl + '/riak/bucket1/key1';
      populateBuckets(function() {
        request(route, function(err, res) {
          expect(res.headers['content-type']).to.contain('json');
          expect(res.statusCode).to.equal(200);
          var content = JSON.parse(res.body);
          expect(content).to.have.property('content1', 'val1');
          done();
        });
      });
    });
  });

  describe('PUT /riak/:bucket/:key', function() {
    it('inserts a piece of data successfully', function(done) {
      request.put({ url: baseUrl + '/riak/bucket1/key1', json: { content1: 'val1' } }, function(err, res) {
        expect(res.statusCode).to.equal(204);
        // TODO check that data has really been written
        done();
      });
    });
  });

  describe('DELETE /riak/:bucket/:key', function() {
    it('returns a 404 with "not found" if the key does not exist', function(done) {
      request.del(baseUrl + '/riak/bucket1/key1', function(err, res) {
        expect(res.statusCode).to.equal(404);
        expect(res.body).to.equal('not found');
        done();
      });
    });

    it('deletes a piece of data successfully', function(done) {
      populateBuckets(function() {
        request.del(baseUrl + '/riak/bucket1/key1', function(err, res) {
          expect(res.statusCode).to.equal(204);
          // TODO check that data has really been written
          done();
        });
      });
    });
  });

  describe('POST /mapred', function() {
    it('executes a proper mapreduce query with a single value query', function(done) {
      populateBuckets(function() {
        request.post({ url: baseUrl + '/mapred', json: {"inputs":{"bucket":"bucket1","index":"number_int","key":1},"query":[{"map":{"language":"javascript","source":"function(v) { return [{key: v.key, data: v.values[0].data}]; }","keep":true}}]} }, function(err, res) {
          expect(res.headers['content-type']).to.contain('json');
          expect(res.statusCode).to.equal(200);
          expect(res.body).to.have.length(1);
          expect(res.body[0]).to.have.property('key').that.equals('key1');
          done();
        });
      });
    });
    it('executes a proper mapreduce query with a range query', function(done) {
      populateBuckets(function() {
        request.post({ url: baseUrl + '/mapred', json: {"inputs":{"bucket":"bucket1","index":"number_int","start":0, "end":1},"query":[{"map":{"language":"javascript","source":"function(v) { return [{key: v.key, data: v.values[0].data}]; }","keep":true}}]} }, function(err, res) {
          expect(res.headers['content-type']).to.contain('json');
          expect(res.statusCode).to.equal(200);
          expect(res.body).to.have.length(1);
          expect(res.body[0]).to.have.property('key').that.equals('key1');
          done();
        });
      });
    });
    it('passes arguments to handling function', function(done) {
      populateBuckets(function() {
        request.post({ url: baseUrl + '/mapred', json: {"inputs":"bucket1","query":[{"map":{"language":"javascript","source":"function(v, key, args) { return [args.val]; }", "keep":true, "arg":{"val":"test"}}}]}}, function(err, res) {
          expect(res.statusCode).to.equal(200);
          expect(res.headers['content-type']).to.contain('json');
          expect(res.body).to.have.length(1);
          expect(res.body[0]).to.equal('test');
          done();
        });
      });
    });
  });
});
<commit_msg>Added tests for filters ends_with and starts_with<commit_after>var request = require('request');
var chai = require('chai');
var expect = chai.expect;
var App = require('../lib/routes');
var _ = require('lodash');

describe('All tests', function() {
  var baseUrl;
  var server;
  beforeEach(function(done) {
    server = require('http').createServer(new App());
    server.listen(0, function() {
      baseUrl = 'http://localhost:' + server.address().port;
      done();
    });
  });

  afterEach(function(done) {
    server.close(done);
  });

  function populateBuckets(cb) {
    request.put({ url: baseUrl + '/riak/bucket1/key1', json: { content1: 'val1' }, headers: { "x-riak-index-text_bin": "indexVal1", "x-riak-index-number_int": "1" } }, function() {
      request.put({ url: baseUrl + '/riak/bucket2/key2', json: { content2: 'val2' }, headers: { "x-riak-index-text_bin": "indexVal2", "x-riak-index-number_int": "2" }}, cb);
    });
  }

  describe('GET /buckets?buckets=true', function() {
    it('returns an empty list of buckets', function(done) {
      var route = baseUrl + '/buckets?buckets=true';
      request(route, function(err, res) {
        expect(res.headers['content-type']).to.contain('json');
        expect(res.statusCode).to.equal(200);
        var content = JSON.parse(res.body);
        expect(content).to.have.property('buckets').with.length(0);
        done();
      });
    });

    it('returns an list of buckets list of buckets', function(done) {
      var route = baseUrl + '/buckets?buckets=true';
      populateBuckets(function() {
        request(route, function(err, res) {
          expect(res.headers['content-type']).to.contain('json');
          expect(res.statusCode).to.equal(200);
          var content = JSON.parse(res.body);
          expect(content).to.have.property('buckets').with.length(2);
          done();
        });
      });
    });
  });

  describe('GET /riak/:bucket?keys=true', function() {
    it('returns an empty list of keys if no keys in bucket', function(done) {
      var route = baseUrl + '/riak/bucket1?keys=true';
      request(route, function(err, res) {
        expect(res.headers['content-type']).to.contain('json');
        expect(res.statusCode).to.equal(200);
        var content = JSON.parse(res.body);
        expect(content).to.have.property('keys').with.length(0);
        done();
      });
    });

    it('returns a list of all keys in this bucket', function(done) {
      var route = baseUrl + '/riak/bucket1?keys=true';
      populateBuckets(function() {
        request(route, function(err, res) {
          expect(res.headers['content-type']).to.contain('json');
          expect(res.statusCode).to.equal(200);
          var content = JSON.parse(res.body);
          expect(content).to.have.property('keys').with.length(1);
          done();
        });
      });
    });

    it('with stream=true returns a list of all keys in this bucket in a chunked encoding', function(done) {
      var route = baseUrl + '/riak/bucket1?keys=stream';
      populateBuckets(function() {
        request(route, function(err, res) {
          expect(res.headers['transfer-encoding']).to.equal('chunked');
          expect(res.headers['content-type']).to.contain('json');
          expect(res.statusCode).to.equal(200);
          var content = JSON.parse(res.body);
          expect(content).to.have.property('keys').with.length(1);
          done();
        });
      });
    });
  });

  var prefixes = ['riak', 'buckets'];
  _.each(prefixes, function(prefix) {
    describe('GET /'+prefix+'/:bucket/index/:indexName/:indexValue', function() {
      it('returns an empty list of keys if no keys match this indexValue', function(done) {
        var route = baseUrl + '/'+prefix+'/bucket1/index/text_bin/notFoundVal';
        populateBuckets(function() {
          request(route, function(err, res) {
            expect(res.headers['content-type']).to.contain('json');
            expect(res.statusCode).to.equal(200);
            var content = JSON.parse(res.body);
            expect(content).to.have.property('keys').with.length(0);
            done();
          });
        });
      });

      it('returns a of matching keys if the index matches', function(done) {
        var route = baseUrl + '/'+prefix+'/bucket1/index/text_bin/indexVal1';
        populateBuckets(function() {
          request(route, function(err, res) {
            expect(res.headers['content-type']).to.contain('json');
            expect(res.statusCode).to.equal(200);
            var content = JSON.parse(res.body);
            expect(content).to.have.property('keys').with.length(1);
            done();
          });
        });
      });

      it('can also handle numeric indexes', function(done) {
        var route = baseUrl + '/'+prefix+'/bucket1/index/number_int/1';
        populateBuckets(function() {
          request(route, function(err, res) {
            expect(res.headers['content-type']).to.contain('json');
            expect(res.statusCode).to.equal(200);
            var content = JSON.parse(res.body);
            expect(content).to.have.property('keys').with.length(1);
            done();
          });
        });
      });
    });

    describe('GET /'+prefix+'/:bucket/index/:indexName/:indexFrom/:indexTo', function() {
      it('returns an empty list of keys if no keys match this indexValue', function(done) {
        var route = baseUrl + '/'+prefix+'/bucket1/index/number_int/1000/1001';
        populateBuckets(function() {
          request(route, function(err, res) {
            expect(res.headers['content-type']).to.contain('json');
            expect(res.statusCode).to.equal(200);
            var content = JSON.parse(res.body);
            expect(content).to.have.property('keys').with.length(0);
            done();
          });
        });
      });

      it('returns a of matching keys if the index range matches', function(done) {
        var route = baseUrl + '/'+prefix+'/bucket1/index/number_int/0/2';
        populateBuckets(function() {
          request(route, function(err, res) {
            expect(res.headers['content-type']).to.contain('json');
            expect(res.statusCode).to.equal(200);
            var content = JSON.parse(res.body);
            expect(content).to.have.property('keys').with.length(1);
            done();
          });
        });
      });
    });
  });

  describe('GET /riak/:bucket/:key', function() {
    it('returns a 404 with "not found" if the key does not exist', function(done) {
      var route = baseUrl + '/riak/bucket1/key1';
      request(route, function(err, res) {
        expect(res.statusCode).to.equal(404);
        expect(res.body).to.equal('not found');
        done();
      });
    });

    it('returns data for a get request', function(done) {
      var route = baseUrl + '/riak/bucket1/key1';
      populateBuckets(function() {
        request(route, function(err, res) {
          expect(res.headers['content-type']).to.contain('json');
          expect(res.statusCode).to.equal(200);
          var content = JSON.parse(res.body);
          expect(content).to.have.property('content1', 'val1');
          done();
        });
      });
    });
  });

  describe('PUT /riak/:bucket/:key', function() {
    it('inserts a piece of data successfully', function(done) {
      request.put({ url: baseUrl + '/riak/bucket1/key1', json: { content1: 'val1' } }, function(err, res) {
        expect(res.statusCode).to.equal(204);
        // TODO check that data has really been written
        done();
      });
    });
  });

  describe('DELETE /riak/:bucket/:key', function() {
    it('returns a 404 with "not found" if the key does not exist', function(done) {
      request.del(baseUrl + '/riak/bucket1/key1', function(err, res) {
        expect(res.statusCode).to.equal(404);
        expect(res.body).to.equal('not found');
        done();
      });
    });

    it('deletes a piece of data successfully', function(done) {
      populateBuckets(function() {
        request.del(baseUrl + '/riak/bucket1/key1', function(err, res) {
          expect(res.statusCode).to.equal(204);
          // TODO check that data has really been written
          done();
        });
      });
    });
  });

  describe('POST /mapred', function() {
    it('executes a proper mapreduce query with a single value query', function(done) {
      populateBuckets(function() {
        request.post({ url: baseUrl + '/mapred', json: {"inputs":{"bucket":"bucket1","index":"number_int","key":1},"query":[{"map":{"language":"javascript","source":"function(v) { return [{key: v.key, data: v.values[0].data}]; }","keep":true}}]} }, function(err, res) {
          expect(res.headers['content-type']).to.contain('json');
          expect(res.statusCode).to.equal(200);
          expect(res.body).to.have.length(1);
          expect(res.body[0]).to.have.property('key').that.equals('key1');
          done();
        });
      });
    });
    it('executes a proper mapreduce query with a range query', function(done) {
      populateBuckets(function() {
        request.post({ url: baseUrl + '/mapred', json: {"inputs":{"bucket":"bucket1","index":"number_int","start":0, "end":1},"query":[{"map":{"language":"javascript","source":"function(v) { return [{key: v.key, data: v.values[0].data}]; }","keep":true}}]} }, function(err, res) {
          expect(res.headers['content-type']).to.contain('json');
          expect(res.statusCode).to.equal(200);
          expect(res.body).to.have.length(1);
          expect(res.body[0]).to.have.property('key').that.equals('key1');
          done();
        });
      });
    });

    it('executes a proper mapreduce query with a ends_with key filter', function(done) {
      populateBuckets(function() {
        request.put({ url: baseUrl + '/riak/bucket1/key_endsWithA', json: { content1: 'val3' }, headers: { "x-riak-index-text_bin": "indexVal3", "x-riak-index-number_int": "3" } }, function() {
          request.put({ url: baseUrl + '/riak/bucket1/key_also_endsWithA', json: { content2: 'val4' }, headers: { "x-riak-index-text_bin": "indexVal4", "x-riak-index-number_int": "4" }}, function(){
            request.put({ url: baseUrl + '/riak/bucket1/key_endsWithA_Not', json: { content2: 'val5' }, headers: { "x-riak-index-text_bin": "indexVal5", "x-riak-index-number_int": "5" }}, function(){
              request.post({ url: baseUrl + '/mapred', json: {"inputs":{"bucket":"bucket1","index":"number_int","key_filters":[["ends_with", "endsWithA"]]},"query":[{"map":{"language":"javascript","source":"function(v) { return [{key: v.key, data: v.values[0].data}]; }","keep":true}}]} }, function(err, res) {
                expect(res.headers['content-type']).to.contain('json');
                expect(res.statusCode).to.equal(200);
                expect(res.body).to.have.length(2);
                done();
              });
            });
          });
        });

      });
    });

    it('executes a proper mapreduce query with a starts_with key filter', function(done) {
      populateBuckets(function() {
        request.put({ url: baseUrl + '/riak/bucket1/startsWithA_key', json: { content1: 'val3' }, headers: { "x-riak-index-text_bin": "indexVal3", "x-riak-index-number_int": "3" } }, function() {
          request.put({ url: baseUrl + '/riak/bucket1/startsWithA_key_also', json: { content2: 'val4' }, headers: { "x-riak-index-text_bin": "indexVal4", "x-riak-index-number_int": "4" }}, function(){
            request.put({ url: baseUrl + '/riak/bucket1/starts_not_WithA_key', json: { content2: 'val5' }, headers: { "x-riak-index-text_bin": "indexVal5", "x-riak-index-number_int": "5" }}, function(){
              request.post({ url: baseUrl + '/mapred', json: {"inputs":{"bucket":"bucket1","index":"number_int","key_filters":[["starts_with", "startsWithA"]]},"query":[{"map":{"language":"javascript","source":"function(v) { return [{key: v.key, data: v.values[0].data}]; }","keep":true}}]} }, function(err, res) {
                expect(res.headers['content-type']).to.contain('json');
                expect(res.statusCode).to.equal(200);
                expect(res.body).to.have.length(2);
                done();
              });
            });
          });
        });

      });
    });
    it('passes arguments to handling function', function(done) {
      populateBuckets(function() {
        request.post({ url: baseUrl + '/mapred', json: {"inputs":"bucket1","query":[{"map":{"language":"javascript","source":"function(v, key, args) { return [args.val]; }", "keep":true, "arg":{"val":"test"}}}]}}, function(err, res) {
          expect(res.statusCode).to.equal(200);
          expect(res.headers['content-type']).to.contain('json');
          expect(res.body).to.have.length(1);
          expect(res.body[0]).to.equal('test');
          done();
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>// Here to generate browserified code bundle
require('../src/bundled');

var chai   = require('chai');
var sinon  = require('sinon');
var expect = chai.expect;
var pkg    = require('../package.json');

chai.expect();
chai.should();

var LiteList = require('LiteList');
var mock     = require('./lib/mock');

describe(["LiteList"], function() {
    var dataSource = {
        bind: function(/*id, el*/) {},

        sync: function(id, el/*, itemIdx, item*/) {
            el.innerText = "innerText[" + id + "]";
        },

        unbind: function(/*id, el*/) {}
    };

    var itemTemplate    = document.createDocumentFragment();

    var fullOpts = {
        itemWidth:      100,
        itemHeight:     100,
        margin:         { x: 0, y: 0 },
        scrollView:     ".scrollView",
        itemsContainer: ".itemsContainer",
        dataSource:     dataSource,
        itemTemplate:   itemTemplate
    };

    var requiredOpts = {
        itemHeight:     100,
        scrollView:     ".scrollView"
    };

    var viewWidth = 1000, viewHeight = 1000;

    var scrollView, itemsContainer;
    var sandbox, qsStub, gcsStub;

    beforeEach(function() {
        scrollView      = mock.getFakeView(viewWidth, viewHeight);
        itemsContainer  = scrollView.children[0];

        if(itemTemplate.childNodes.length === 0) {
            itemTemplate.appendChild(document.createElement("div"));
        }

        // Create a new sandbox
        sandbox = sinon.sandbox.create();

        qsStub  = sandbox.stub(document, 'querySelector');
        gcsStub = sandbox.stub(window,   'getComputedStyle');

        qsStub.withArgs('.scrollView'    ).returns(scrollView);
        qsStub.withArgs('.itemsContainer').returns(itemsContainer);

        gcsStub.withArgs(scrollView).returns({ height: scrollView.clientHeight });
    });

    // Restore stuff to the way we were...
    afterEach(function () {
        sandbox.restore();
    });

    describe("bundled", function() {
        it("LiteList should exist", function() {
            expect(LiteList).to.exist;
        });

        it("should have RivetsLiteList", function() {
            expect(LiteList.RivetsLiteList).to.exist;
        });

        it("should have Scroll", function() {
            expect(LiteList.Scroll).to.exist;
        });

        it("should have rivets", function() {
            expect(require('rivets')).to.exist;
        });

        it("should have tween.js", function() {
            expect(require('tween.js')).to.exist;
            expect(require('TWEEN')).to.exist;
        });

        it("should have the same version as package.json", function() {
            expect(LiteList.VERSION).to.equal(pkg.version);
        });
    });

    describe("constructor", function() {
        it("Should create a LiteList object with all options specified", function() {
            var liteList = new LiteList(fullOpts);

            expect(liteList.itemsInView).to.be.instanceof(Array);
            expect(liteList.itemsInView.length).to.equal(0);
            expect(liteList.items).to.be.instanceof(Array);
            expect(liteList.items.length).to.equal(0);
            expect(liteList.itemWidth).to.equal(fullOpts.itemWidth);
            expect(liteList.itemHeight).to.equal(fullOpts.itemHeight);
            expect(liteList.margin).to.deep.equal(fullOpts.margin);
            expect(liteList.view).to.deep.equal(scrollView);
            expect(liteList.itemsContainer).to.deep.equal(itemsContainer);
            expect(liteList.dataSource).to.deep.equal(dataSource);
            expect(liteList.itemTemplate).to.deep.equal(itemTemplate);
            expect(liteList.scrollTop).to.equal(0);

            // View Metrics
            expect(liteList.clientHeight).to.equal(viewHeight);
            expect(liteList.clientWidth ).to.equal(viewWidth);
            expect(liteList.rowsPerPage ).to.equal(Math.ceil (viewHeight/fullOpts.itemHeight));
            expect(liteList.itemsPerRow ).to.equal(Math.floor(viewWidth /fullOpts.itemWidth ));
            expect(liteList.itemsPerPage).to.equal(liteList.rowsPerPage * liteList.itemsPerRow);
            expect(liteList.maxBuffer   ).to.equal(liteList.itemsPerPage * 3);
        });

        it("Should use expected defaults when only required opts are specified", function() {
            var liteList = new LiteList(requiredOpts);

            expect(liteList.itemsInView).to.be.instanceof(Array);
            expect(liteList.itemsInView.length).to.equal(0);
            expect(liteList.items).to.be.instanceof(Array);
            expect(liteList.items.length).to.equal(0);
            expect(liteList.itemWidth).to.equal(0);
            expect(liteList.itemHeight).to.equal(requiredOpts.itemHeight);
            expect(liteList.margin).to.deep.equal({x: 0, y: 0});
            expect(liteList.view).to.deep.equal(scrollView);
            expect(liteList.itemsContainer).to.deep.equal(itemsContainer);
            expect(liteList.dataSource).to.equal(false);
            expect(liteList.itemTemplate).to.equal(false);
            expect(liteList.scrollTop).to.equal(0);

            // View Metrics
            expect(liteList.clientHeight).to.equal(viewHeight);
            expect(liteList.clientWidth ).to.equal(viewWidth);
            expect(liteList.rowsPerPage ).to.equal(Math.ceil(viewHeight/fullOpts.itemHeight));
            expect(liteList.itemsPerRow ).to.equal(1);
            expect(liteList.itemsPerPage).to.equal(liteList.rowsPerPage * liteList.itemsPerRow);
            expect(liteList.maxBuffer   ).to.equal(liteList.itemsPerPage * 3);
        });
    });
});<commit_msg>Basic tests for _createInViewObj<commit_after>// Here to generate browserified code bundle
require('../src/bundled');

var chai   = require('chai');
var sinon  = require('sinon');
var expect = chai.expect;
var pkg    = require('../package.json');

chai.expect();
chai.should();

var LiteList = require('LiteList');
var mock     = require('./lib/mock');

describe(["LiteList"], function() {
    var dataSource = {
        bind: function(/*id, el*/) {},

        sync: function(id, el/*, itemIdx, item*/) {
            el.innerText = "innerText[" + id + "]";
        },

        unbind: function(/*id, el*/) {}
    };

    var itemTemplate    = document.createDocumentFragment();

    var fullOpts = {
        itemWidth:      100,
        itemHeight:     100,
        margin:         { x: 0, y: 0 },
        scrollView:     ".scrollView",
        itemsContainer: ".itemsContainer",
        dataSource:     dataSource,
        itemTemplate:   itemTemplate
    };

    var requiredOpts = {
        itemHeight:     100,
        scrollView:     ".scrollView"
    };

    var viewWidth = 1000, viewHeight = 1000;

    var scrollView, itemsContainer;
    var sandbox, qsStub, gcsStub;

    beforeEach(function() {
        scrollView      = mock.getFakeView(viewWidth, viewHeight);
        itemsContainer  = scrollView.children[0];

        if(itemTemplate.childNodes.length === 0) {
            itemTemplate.appendChild(document.createElement("div"));
        }

        // Create a new sandbox
        sandbox = sinon.sandbox.create();

        qsStub  = sandbox.stub(document, 'querySelector');
        gcsStub = sandbox.stub(window,   'getComputedStyle');

        qsStub.withArgs('.scrollView'    ).returns(scrollView);
        qsStub.withArgs('.itemsContainer').returns(itemsContainer);

        gcsStub.withArgs(scrollView).returns({ height: scrollView.clientHeight });
    });

    // Restore stuff to the way we were...
    afterEach(function () {
        sandbox.restore();
    });

    describe("bundled", function() {
        it("LiteList should exist", function() {
            expect(LiteList).to.exist;
        });

        it("should have RivetsLiteList", function() {
            expect(LiteList.RivetsLiteList).to.exist;
        });

        it("should have Scroll", function() {
            expect(LiteList.Scroll).to.exist;
        });

        it("should have rivets", function() {
            expect(require('rivets')).to.exist;
        });

        it("should have tween.js", function() {
            expect(require('tween.js')).to.exist;
            expect(require('TWEEN')).to.exist;
        });

        it("should have the same version as package.json", function() {
            expect(LiteList.VERSION).to.equal(pkg.version);
        });
    });

    describe("constructor", function() {
        it("Should create a LiteList object with all options specified", function() {
            var liteList = new LiteList(fullOpts);

            expect(liteList.itemsInView).to.be.instanceof(Array);
            expect(liteList.itemsInView.length).to.equal(0);
            expect(liteList.items).to.be.instanceof(Array);
            expect(liteList.items.length).to.equal(0);
            expect(liteList.itemWidth).to.equal(fullOpts.itemWidth);
            expect(liteList.itemHeight).to.equal(fullOpts.itemHeight);
            expect(liteList.margin).to.deep.equal(fullOpts.margin);
            expect(liteList.view).to.deep.equal(scrollView);
            expect(liteList.itemsContainer).to.deep.equal(itemsContainer);
            expect(liteList.dataSource).to.deep.equal(dataSource);
            expect(liteList.itemTemplate).to.deep.equal(itemTemplate);
            expect(liteList.scrollTop).to.equal(0);

            // View Metrics
            expect(liteList.clientHeight).to.equal(viewHeight);
            expect(liteList.clientWidth ).to.equal(viewWidth);
            expect(liteList.rowsPerPage ).to.equal(Math.ceil (viewHeight/fullOpts.itemHeight));
            expect(liteList.itemsPerRow ).to.equal(Math.floor(viewWidth /fullOpts.itemWidth ));
            expect(liteList.itemsPerPage).to.equal(liteList.rowsPerPage * liteList.itemsPerRow);
            expect(liteList.maxBuffer   ).to.equal(liteList.itemsPerPage * 3);
        });

        it("Should use expected defaults when only required opts are specified", function() {
            var liteList = new LiteList(requiredOpts);

            expect(liteList.itemsInView).to.be.instanceof(Array);
            expect(liteList.itemsInView.length).to.equal(0);
            expect(liteList.items).to.be.instanceof(Array);
            expect(liteList.items.length).to.equal(0);
            expect(liteList.itemWidth).to.equal(0);
            expect(liteList.itemHeight).to.equal(requiredOpts.itemHeight);
            expect(liteList.margin).to.deep.equal({x: 0, y: 0});
            expect(liteList.view).to.deep.equal(scrollView);
            expect(liteList.itemsContainer).to.deep.equal(itemsContainer);
            expect(liteList.dataSource).to.equal(false);
            expect(liteList.itemTemplate).to.equal(false);
            expect(liteList.scrollTop).to.equal(0);

            // View Metrics
            expect(liteList.clientHeight).to.equal(viewHeight);
            expect(liteList.clientWidth ).to.equal(viewWidth);
            expect(liteList.rowsPerPage ).to.equal(Math.ceil(viewHeight/fullOpts.itemHeight));
            expect(liteList.itemsPerRow ).to.equal(1);
            expect(liteList.itemsPerPage).to.equal(liteList.rowsPerPage * liteList.itemsPerRow);
            expect(liteList.maxBuffer   ).to.equal(liteList.itemsPerPage * 3);
        });
    });

    describe("_createInViewObj()", function() {
        it("should create an in view object and add it to the dom with all options specified", function() {
            var liteList  = new LiteList(fullOpts);
            var item      = {text: 'hello'};
            var inViewObj;

            liteList.items[0] = item;
            inViewObj = liteList._createInViewObj({text: 'hello'}, 0);
            expect(itemsContainer.children.length).to.equal(1);
        });

        it("should create an in view object and not add it to the dom with required options specified", function() {
            var liteList  = new LiteList(requiredOpts);
            var item      = {text: 'hello'};
            var inViewObj;

            liteList.items[0] = item;
            inViewObj = liteList._createInViewObj({text: 'hello'}, 0);
            expect(itemsContainer.children.length).to.equal(0);
        });
    });
});<|endoftext|>


<commit_before>/* global describe, it, before */

var expect = require('expect.js');
var glob = require('glob');
var path = require('path');

var bmvbhash_data = require('../blockhash.js').bmvbhash_data;

// attempt to load jpgjs using vm
var vm = require('vm');
var fs = require('fs');
vm.runInThisContext(fs.readFileSync(require.resolve('../jpgjs/jpg.js')));

// use standard require to load png.js
var PNG = require('../png.js/png-node.js');

var testFiles = glob.sync('test/data/*.jpg');

testFiles.forEach(function(fn) {
    describe(fn, function(){
        var basename = path.basename(fn, '.jpg');
        var bits = 16;

        [1, 2, 3, 4].forEach(function(m) {
            it('method' + m, function(done) {
                var jpg, data, imgData, hash, expectedHash;

                data = new Uint8Array(fs.readFileSync(fn));
                jpg = new JpegImage();
                jpg.parse(data);

                imgData = {
                    width: jpg.width,
                    height: jpg.height,
                    data: new Uint8Array(jpg.width * jpg.height * 4)
                };

                jpg.copyToImageData(imgData);
                hash = bmvbhash_data(imgData, bits, m);

                expectedHash = fs.readFileSync("test/data/" + basename + "_" + bits + "_" + m + ".txt", {
                    encoding: 'utf-8'
                }).split(/\s/)[1];

                expect(expectedHash).to.be(hash.join(""));

                done();
            });
        });
    });
})
<commit_msg>Test with hamming distance to iron out little differences in jpeg decoders.<commit_after>/* global describe, it, before */

function hammingDistance(a, b, bits) {
    var d = 0;
    for (i = 0; i < bits*bits; i++) {
        if (a[i] != b[i]) { d++; }
    }
    return d;
}

var expect = require('expect.js');
var glob = require('glob');
var path = require('path');

var bmvbhash_data = require('../blockhash.js').bmvbhash_data;

// attempt to load jpgjs using vm
var vm = require('vm');
var fs = require('fs');
vm.runInThisContext(fs.readFileSync(require.resolve('../jpgjs/jpg.js')));

// use standard require to load png.js
var PNG = require('../png.js/png-node.js');

var testFiles = glob.sync('test/data/*.jpg');

testFiles.forEach(function(fn) {
    describe(fn, function(){
        var basename = path.basename(fn, '.jpg');
        var bits = 16;

        [1, 2, 3, 4].forEach(function(m) {
            it('method' + m, function(done) {
                var jpg, data, imgData, hash, expectedHash;

                data = new Uint8Array(fs.readFileSync(fn));
                jpg = new JpegImage();
                jpg.parse(data);

                imgData = {
                    width: jpg.width,
                    height: jpg.height,
                    data: new Uint8Array(jpg.width * jpg.height * 4)
                };

                jpg.copyToImageData(imgData);
                hash = bmvbhash_data(imgData, bits, m);

                expectedHash = fs.readFileSync("test/data/" + basename + "_" + bits + "_" + m + ".txt", {
                    encoding: 'utf-8'
                }).split(/\s/)[1];

                // use hamming distance to iron out little differences in jpeg decoders
                var hd = hammingDistance(expectedHash, hash.join(""), bits);
                expect(hd).to.be.lessThan(3);

                done();
            });
        });
    });
})
<|endoftext|>