<commit_before>/**
 * some utils for work
 */
//unicode转换为字符
var imagemagick = require('imagemagick'),
fs = require('fs'),
config = require('./config'),
EventProxy = require('eventproxy').EventProxy,
Path = require('path'),
Calendar = require('calendar').Calendar,
cal = new Calendar(),
rootdir = require('../lib/config').rootdir,
pichost = 'http://' + config.imagehost + '/images/',
picsize = [80, 150, 300, 500];

exports.drawUrl = function(str) {
	var regUrl = /(htt(p|ps):\/\/[A-Za-z\.\d\/\?\&\;\=\-\#_(\u4e00-\u9fa5)]+)/gi;
	return str.replace(regUrl, function(s1, s2, s3, s4) {
		var uri = s2;
		return '' + uri + '';
	});
};

exports.monthHTML = function(year, month, day, classname, head) {
	var Html = '
',
	mdc = cal.monthDays(year, month);
	if (head) Html += '
' + head + '
';
	for (var i = 0; i < mdc.length; i++) {
		var week = mdc[i];
		Html += '
';
		for (var k = 0; k < week.length; k++) {
			if (week[k] === day) Html += '' + week[k] + '	';
			else if (week[k] !== 0) Html += '' + week[k] + '	';
			else if (week[k] === 0) Html += ' 	';
		}
		Html += '
';
	}
	Html += '
';
	return Html;
};

exports.unicode2Chr = function(str) {
	if ('' !== str) {
		var st, t, i;
		st = '';
		for (i = 1; i <= str.length / 4; i++) {
			t = str.slice(4 * i - 4, 4 * i - 2);
			t = str.slice(4 * i - 2, 4 * i).concat(t);
			st = st.concat('%u').concat(t);
		}
		st = unescape(st);
		return (st);
	}
	else return ('');
};
//字符转换为unicode
exports.chr2Unicode = function(str) {
	if ('' !== str) {
		var st, t, i;
		st = '';
		for (i = 1; i <= str.length; i++) {
			t = str.charCodeAt(i - 1).toString(16);
			if (t.length < 4) {
				while (t.length < 4) {
					t = '0'.concat(t);
				}
			}
			t = t.slice(2, 4).concat(t.slice(0, 2));
			st = st.concat(t);
		}
		return (st.toUpperCase());
	}
	else {
		return ('');
	}
};

exports.replaceReg = function(str) {
	var self = this;
	var qstr = this.chr2Unicode(str);
	var reglist = ['.', '$', '^', '{', '[', '(', '|', ')', '*', '+', '?', '\\', '}', ']'];
	reglist.forEach(function(r, index) {
		reglist[index] = self.chr2Unicode(r);
	});
	var reg = new RegExp(reglist.join('|'), 'g');
	qstr = qstr.replace(reg, function(text) {
		return '5C00' + text;
	});
	return this.unicode2Chr(qstr);
};

exports.mix = function(target, source, covered) {
	var key;
	for (key in source) {
		if (!covered || ! (key in target)) {
			target[key] = source[key];
		}
	}
	return target;
};

exports.paramUrl = function(url) {
	var ret = {},
	data = url.split('&');
	for (var i = 0; i < data.length; i++) {
		var oc = data[i].split('=');
		ret[oc[0]] = oc[1];
	}
	return ret;
};

exports.random36 = function(len) {
	var lists = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'],
	ret = [],
	total = lists.length;
	for (var i = 0; i < len; i++) {
		ret.push(lists[Math.floor(Math.random() * total)]);
	}
	return ret.join('');
};

exports.ov = function(ar) {
	var m, n = [],
	o = {};
	for (var i = 0;
	(m = ar[i]) !== undefined; i++) {
		if (!o[m]) {
			n.push(m);
			o[m] = true;
		}
	}
	return n.sort(function(a, b) {
		return a - b;
	});
};

exports.isEmptyObject = function(obj) {
	for (var i in obj) return false;
	return true;
};

exports.notHasfiles = function(obj) {
	if (this.isEmptyObject(obj)) return true;
	for (var i in obj) {
		if (obj[i]['size'] === 0) return true;
	}
	return false;
};

exports.getpics = function(size, counts, data) {
	if (this.isEmptyObject(data) || ! data) return false;
	var n = 0,
	ret = [];
	for (var i in data) {
		ret.push(pichost + size + '/' + data[i]);
		n++;
		if (n === counts) break;
	}
	if (ret.length === 1) return ret[0];
	return ret;
};

exports.removePic = function(filelist, callback) {
	for (var i in filelist) {
		var pic = filelist[i];
		picsize.forEach(function(size) {
			try {
				fs.unlinkSync(rootdir + '/public/images/' + size + '/' + pic);
			} catch(e) {
				if (callback) callback(e);
			}
		});
	}
	if (callback) callback();
};

exports.setNoCache = function(res) {
	res.header('expires', 'Sun, 1 Jan 2006 01:00:00 GMT');
	res.header('cache-control', 'no-cache,must-revalidate,private,no-store');
	res.header('pragma', 'no-cache');
};

exports.setTime = function(data) {
	var D = new Date(data['created_at']);
	var hour = D.getHours();
	var since;
	if (hour >= 12 && hour < 18) since = '下午';
	if (hour >= 18 && hour < 20) since = '傍晚';
	if (hour >= 20 && hour < 24) since = '夜晚';
	if (hour >= 0 && hour < 6) since = '凌晨';
	if (hour >= 6 && hour < 9) since = '早晨';
	if (hour >= 9 && hour < 12) since = '上午';
	data['created_at'] = D.getFullYear() + '-' + (D.getMonth() + 1) + '-' + D.getDate() + ' ' + since;
};

exports.setDay = function(data) {
	var D = new Date(data['created_at']);
	data['created_at'] = D.getFullYear() + '-' + (D.getMonth() + 1) + '-' + D.getDate();
};

exports.remove_temp = function(proxy, trigger, temp_path) {
	fs.unlink(temp_path, function(err) {
		if (err) {
			throw err;
		} else {
			proxy.trigger(trigger);
		}
	});
};

exports.bacthImages = function(path, callback) {
	var proxy = new EventProxy(),
	finish = function() {
		callback(null);
	};

	var queue = [80, 150, 300, 500, 'unlink'],
	picname = Path.basename(path),
	index = 0;

	proxy.assign(80, 150, 300, 500, 'unlink', finish);

	var resizesize = function(i) {
		var ret = {
			srcPath: path,
			dstPath: rootdir + '/public/images/' + queue[i] + '/' + picname,
			width: queue[i],
			height: queue[i],
			timeout: 1000 * 30
		};
		return ret;
	};

	function resizehandle(err) {
		if (err) {
			try {
				fs.unlinkSync(path);
				fs.unlinkSync(rootdir + '/public/images/50/' + picname);
				fs.unlinkSync(rootdir + '/public/images/150/' + picname);
				fs.unlinkSync(rootdir + '/public/images/300/' + picname);
				fs.unlinkSync(rootdir + '/public/images/500/' + picname);
			} catch(e) {
				console.log(e);
			}
			callback(err);
		} else {
			proxy.trigger(queue[index]);
			index++;
			if (queue[index] == 'unlink') {
				fs.unlink(path, function(err) {
					if (err) callback(err);
					else proxy.trigger('unlink');
				});
			} else {
				imagemagick.resize(resizesize(index), resizehandle);
			}
		}
	}
	imagemagick.resize(resizesize(index), resizehandle);
};

<commit_msg>修改时间格式<commit_after>/**
 * some utils for work
 */
//unicode转换为字符
var imagemagick = require('imagemagick'),
fs = require('fs'),
config = require('./config'),
EventProxy = require('eventproxy').EventProxy,
Path = require('path'),
Calendar = require('calendar').Calendar,
cal = new Calendar(),
rootdir = require('../lib/config').rootdir,
pichost = 'http://' + config.imagehost + '/images/',
picsize = [80, 150, 300, 500];

exports.drawUrl = function(str) {
	var regUrl = /(htt(p|ps):\/\/[A-Za-z\.\d\/\?\&\;\=\-\#_(\u4e00-\u9fa5)]+)/gi;
	return str.replace(regUrl, function(s1, s2, s3, s4) {
		var uri = s2;
		return '' + uri + '';
	});
};

exports.monthHTML = function(year, month, day, classname, head) {
	var Html = '
',
	mdc = cal.monthDays(year, month);
	if (head) Html += '
' + head + '
';
	for (var i = 0; i < mdc.length; i++) {
		var week = mdc[i];
		Html += '
';
		for (var k = 0; k < week.length; k++) {
			if (week[k] === day) Html += '' + week[k] + '	';
			else if (week[k] !== 0) Html += '' + week[k] + '	';
			else if (week[k] === 0) Html += ' 	';
		}
		Html += '
';
	}
	Html += '
';
	return Html;
};

exports.unicode2Chr = function(str) {
	if ('' !== str) {
		var st, t, i;
		st = '';
		for (i = 1; i <= str.length / 4; i++) {
			t = str.slice(4 * i - 4, 4 * i - 2);
			t = str.slice(4 * i - 2, 4 * i).concat(t);
			st = st.concat('%u').concat(t);
		}
		st = unescape(st);
		return (st);
	}
	else return ('');
};
//字符转换为unicode
exports.chr2Unicode = function(str) {
	if ('' !== str) {
		var st, t, i;
		st = '';
		for (i = 1; i <= str.length; i++) {
			t = str.charCodeAt(i - 1).toString(16);
			if (t.length < 4) {
				while (t.length < 4) {
					t = '0'.concat(t);
				}
			}
			t = t.slice(2, 4).concat(t.slice(0, 2));
			st = st.concat(t);
		}
		return (st.toUpperCase());
	}
	else {
		return ('');
	}
};

exports.replaceReg = function(str) {
	var self = this;
	var qstr = this.chr2Unicode(str);
	var reglist = ['.', '$', '^', '{', '[', '(', '|', ')', '*', '+', '?', '\\', '}', ']'];
	reglist.forEach(function(r, index) {
		reglist[index] = self.chr2Unicode(r);
	});
	var reg = new RegExp(reglist.join('|'), 'g');
	qstr = qstr.replace(reg, function(text) {
		return '5C00' + text;
	});
	return this.unicode2Chr(qstr);
};

exports.mix = function(target, source, covered) {
	var key;
	for (key in source) {
		if (!covered || ! (key in target)) {
			target[key] = source[key];
		}
	}
	return target;
};

exports.paramUrl = function(url) {
	var ret = {},
	data = url.split('&');
	for (var i = 0; i < data.length; i++) {
		var oc = data[i].split('=');
		ret[oc[0]] = oc[1];
	}
	return ret;
};

exports.random36 = function(len) {
	var lists = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'],
	ret = [],
	total = lists.length;
	for (var i = 0; i < len; i++) {
		ret.push(lists[Math.floor(Math.random() * total)]);
	}
	return ret.join('');
};

exports.ov = function(ar) {
	var m, n = [],
	o = {};
	for (var i = 0;
	(m = ar[i]) !== undefined; i++) {
		if (!o[m]) {
			n.push(m);
			o[m] = true;
		}
	}
	return n.sort(function(a, b) {
		return a - b;
	});
};

exports.isEmptyObject = function(obj) {
	for (var i in obj) return false;
	return true;
};

exports.notHasfiles = function(obj) {
	if (this.isEmptyObject(obj)) return true;
	for (var i in obj) {
		if (obj[i]['size'] === 0) return true;
	}
	return false;
};

exports.getpics = function(size, counts, data) {
	if (this.isEmptyObject(data) || ! data) return false;
	var n = 0,
	ret = [];
	for (var i in data) {
		ret.push(pichost + size + '/' + data[i]);
		n++;
		if (n === counts) break;
	}
	if (ret.length === 1) return ret[0];
	return ret;
};

exports.removePic = function(filelist, callback) {
	for (var i in filelist) {
		var pic = filelist[i];
		picsize.forEach(function(size) {
			try {
				fs.unlinkSync(rootdir + '/public/images/' + size + '/' + pic);
			} catch(e) {
				if (callback) callback(e);
			}
		});
	}
	if (callback) callback();
};

exports.setNoCache = function(res) {
	res.header('expires', 'Sun, 1 Jan 2006 01:00:00 GMT');
	res.header('cache-control', 'no-cache,must-revalidate,private,no-store');
	res.header('pragma', 'no-cache');
};

exports.setTime = function(data) {
	var D = new Date(data['created_at']);
	var hour = D.getHours(),
        Minutes = D.getMinutes();
	var since;
	if (hour >= 12 && hour < 18) since = '下午';
	if (hour >= 18 && hour < 20) since = '傍晚';
	if (hour >= 20 && hour < 24) since = '夜晚';
	if (hour >= 0 && hour < 6) since = '凌晨';
	if (hour >= 6 && hour < 9) since = '早晨';
	if (hour >= 9 && hour < 12) since = '上午';
    since = since +' '+ hour + '时' + Minutes +'分';
	data['created_at'] = D.getFullYear() + '-' + (D.getMonth() + 1) + '-' + D.getDate() + ' ' + since;
};

exports.setDay = function(data) {
	var D = new Date(data['created_at']);
	data['created_at'] = D.getFullYear() + '-' + (D.getMonth() + 1) + '-' + D.getDate();
};

exports.remove_temp = function(proxy, trigger, temp_path) {
	fs.unlink(temp_path, function(err) {
		if (err) {
			throw err;
		} else {
			proxy.trigger(trigger);
		}
	});
};

exports.bacthImages = function(path, callback) {
	var proxy = new EventProxy(),
	finish = function() {
		callback(null);
	};

	var queue = [80, 150, 300, 500, 'unlink'],
	picname = Path.basename(path),
	index = 0;

	proxy.assign(80, 150, 300, 500, 'unlink', finish);

	var resizesize = function(i) {
		var ret = {
			srcPath: path,
			dstPath: rootdir + '/public/images/' + queue[i] + '/' + picname,
			width: queue[i],
			height: queue[i],
			timeout: 1000 * 30
		};
		return ret;
	};

	function resizehandle(err) {
		if (err) {
			try {
				fs.unlinkSync(path);
				fs.unlinkSync(rootdir + '/public/images/50/' + picname);
				fs.unlinkSync(rootdir + '/public/images/150/' + picname);
				fs.unlinkSync(rootdir + '/public/images/300/' + picname);
				fs.unlinkSync(rootdir + '/public/images/500/' + picname);
			} catch(e) {
				console.log(e);
			}
			callback(err);
		} else {
			proxy.trigger(queue[index]);
			index++;
			if (queue[index] == 'unlink') {
				fs.unlink(path, function(err) {
					if (err) callback(err);
					else proxy.trigger('unlink');
				});
			} else {
				imagemagick.resize(resizesize(index), resizehandle);
			}
		}
	}
	imagemagick.resize(resizesize(index), resizehandle);
};

<|endoftext|>


<commit_before>'use babel'

import { BufferedProcess, Point, Range } from 'atom'

export default {
  initialDelay: 1000,
  startMoieServer(afterStart) {
    const self=this
    const execPath = atom.config.get('Moie.moieExec')
    const interface = atom.config.get('Moie.interface')
    const port = atom.config.get('Moie.port')
    const command = atom.config.get('Moie.javaExec')
    const args = ['-jar', execPath]
    const stdout = data => {
      if(data.indexOf(`Server running at ${interface}:${port}`) > -1) {
        //wait a vew seconds until server is loaded
        window.setTimeout(afterStart, self.initialDelay)
      }
      console.log("stdout", data)
    }
    const stderr = data => atom.notifications.addError("Mo|E-Server process error", {detail:data})
    const exit = code => console.log("server exited with ", code)
    const process = new BufferedProcess({command,args, stdout, stderr, exit})
  },

  createErrorLine(errorObj) {
      //link to file
    const fileName = errorObj.file.substring(errorObj.file.lastIndexOf("/")+1)
    const fileElem = (errorObj.file !== "") ?
      `
        ${fileName}
      ` : "";

      //HTML linebreaks
    const msg = errorObj.message.replace(/\n/g, "
")
      //badge indicator
    const cssClass = errorObj.type == 'Warning' ? 'warning-badge' : 'error-badge'
      //final error indicator line
    return `
    ${errorObj.type}
    ${fileElem} from
    ${errorObj.start.line}:${errorObj.start.column} to
    ${errorObj.end.line}:${errorObj.end.column}
    : ${msg}`
  },

  saveAllFiles() {
    const editors = atom.workspace.getTextEditors()
    editors.filter(v => this.isModelicaFile(v.getPath())).forEach(editor => {
      editor.save()
    })
  },

  currentFile() {
    return atom.workspace.getActiveTextEditor().getPath()
  },

  wordBelowCursor() {
    const editor = atom.workspace.getActiveTextEditor()
    const buffer = editor.getBuffer()
    const cursorPos = editor.getCursorBufferPosition()
    return this.wordBefore(cursorPos, buffer)
  },

  wordBelowPosition(position, buffer) {
    return this.wordBefore(position, buffer) + this.wordAfter(position, buffer)
  },

  wordBefore(pos, textBuffer) {
    let startPos = new Point(pos.row,pos.column-1)
    let word = textBuffer.getTextInRange(new Range(startPos, pos))
    while(!word.startsWith(" ") && startPos.column !=0) {
      startPos = new Point(startPos.row, startPos.column-1)
      word = textBuffer.getTextInRange(new Range(startPos, pos))
    }
    return word.trim()
  },

  wordAfter(pos, textBuffer) {
    let endPos = new Point(pos.row,pos.column+1)
    let word = textBuffer.getTextInRange(new Range(pos, endPos))
    const lineLength = textBuffer.lineLengthForRow(pos.row)
    while(!word.endsWith(" ") && !word.endsWith("\n") && endPos.column < lineLength) {
      endPos = new Point(endPos.row, endPos.column+1)
      word = textBuffer.getTextInRange(new Range(pos, endPos))
    }
    return word.trim()
  },

  rangeBelowPosition(pos, buffer) {
    let startPos = new Point(pos.row, pos.column-1)
    let word = buffer.getTextInRange(new Range(startPos, pos))
    while(!word.startsWith(" ") && startPos.column !=0) {
      startPos = new Point(startPos.row, startPos.column-1)
      word = buffer.getTextInRange(new Range(startPos, pos))
    }

    let endPos = new Point(pos.row, pos.column+1)
    word = buffer.getTextInRange(new Range(pos, endPos))
    while(!word.endsWith(" ") && !word.endsWith("\n")) {
      endPos = new Point(endPos.row, endPos.column+1)
      word = buffer.getTextInRange(new Range(pos, endPos))
    }

    return new Range(startPos, endPos)
  },
  isModelicaFile(path) { return path.endsWith(".mo") },
  isModelicaScript(path) { return path.endsWith(".mos") },
  openFile(path) {
    atom.workspace.open(path)
  },

  FilePath(path) {
    this.path = path;
  },

  FilePosition(line, column) {
    this.line = line
    this.column = column
  }
}
<commit_msg>Fix starting moie-server as subprocess<commit_after>'use babel'

import { BufferedProcess, Point, Range } from 'atom'

export default {
  initialDelay: 1000,
  startMoieServer(afterStart) {
    const self=this
    const execPath = atom.config.get('Moie.moieExec')
    const interface = atom.config.get('Moie.interface')
    const port = atom.config.get('Moie.port')
    const command = atom.config.get('Moie.javaExec')
    const args = ['-jar', execPath]
    const stdout = data => {
      if(data.indexOf("Server running at") > -1) {
        //wait a vew seconds until server is loaded
        window.setTimeout(afterStart, self.initialDelay)
      }
      console.log("stdout", data)
    }
    const stderr = data => atom.notifications.addError("Mo|E-Server process error", {detail:data})
    const exit = code => console.log("server exited with ", code)
    const process = new BufferedProcess({command,args, stdout, stderr, exit})
  },

  createErrorLine(errorObj) {
      //link to file
    const fileName = errorObj.file.substring(errorObj.file.lastIndexOf("/")+1)
    const fileElem = (errorObj.file !== "") ?
      `
        ${fileName}
      ` : "";

      //HTML linebreaks
    const msg = errorObj.message.replace(/\n/g, "
")
      //badge indicator
    const cssClass = errorObj.type == 'Warning' ? 'warning-badge' : 'error-badge'
      //final error indicator line
    return `
    ${errorObj.type}
    ${fileElem} from
    ${errorObj.start.line}:${errorObj.start.column} to
    ${errorObj.end.line}:${errorObj.end.column}
    : ${msg}`
  },

  saveAllFiles() {
    const editors = atom.workspace.getTextEditors()
    editors.filter(v => this.isModelicaFile(v.getPath())).forEach(editor => {
      editor.save()
    })
  },

  currentFile() {
    return atom.workspace.getActiveTextEditor().getPath()
  },

  wordBelowCursor() {
    const editor = atom.workspace.getActiveTextEditor()
    const buffer = editor.getBuffer()
    const cursorPos = editor.getCursorBufferPosition()
    return this.wordBefore(cursorPos, buffer)
  },

  wordBelowPosition(position, buffer) {
    return this.wordBefore(position, buffer) + this.wordAfter(position, buffer)
  },

  wordBefore(pos, textBuffer) {
    let startPos = new Point(pos.row,pos.column-1)
    let word = textBuffer.getTextInRange(new Range(startPos, pos))
    while(!word.startsWith(" ") && startPos.column !=0) {
      startPos = new Point(startPos.row, startPos.column-1)
      word = textBuffer.getTextInRange(new Range(startPos, pos))
    }
    return word.trim()
  },

  wordAfter(pos, textBuffer) {
    let endPos = new Point(pos.row,pos.column+1)
    let word = textBuffer.getTextInRange(new Range(pos, endPos))
    const lineLength = textBuffer.lineLengthForRow(pos.row)
    while(!word.endsWith(" ") && !word.endsWith("\n") && endPos.column < lineLength) {
      endPos = new Point(endPos.row, endPos.column+1)
      word = textBuffer.getTextInRange(new Range(pos, endPos))
    }
    return word.trim()
  },

  rangeBelowPosition(pos, buffer) {
    let startPos = new Point(pos.row, pos.column-1)
    let word = buffer.getTextInRange(new Range(startPos, pos))
    while(!word.startsWith(" ") && startPos.column !=0) {
      startPos = new Point(startPos.row, startPos.column-1)
      word = buffer.getTextInRange(new Range(startPos, pos))
    }

    let endPos = new Point(pos.row, pos.column+1)
    word = buffer.getTextInRange(new Range(pos, endPos))
    while(!word.endsWith(" ") && !word.endsWith("\n")) {
      endPos = new Point(endPos.row, endPos.column+1)
      word = buffer.getTextInRange(new Range(pos, endPos))
    }

    return new Range(startPos, endPos)
  },
  isModelicaFile(path) { return path.endsWith(".mo") },
  isModelicaScript(path) { return path.endsWith(".mos") },
  openFile(path) {
    atom.workspace.open(path)
  },

  FilePath(path) {
    this.path = path;
  },

  FilePosition(line, column) {
    this.line = line
    this.column = column
  }
}
<|endoftext|>


<commit_before>"use strict";

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

exports.isEmptyString = function (str) {
    return exports.isString(str) && str.length === 0;
};

exports.isUndefined = function (value) {
    return typeof value === "undefined";
};

exports.isString = function (value) {
    return typeof value === "string" || value instanceof String;
};
<commit_msg>fix isEmptyObject not checking whether arg is Object at all<commit_after>"use strict";

exports.isObject = function (obj) {
    return !exports.isUndefined(obj) && obj.constructor === Object;
};

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

exports.isEmptyString = function (str) {
    return exports.isString(str) && str.length === 0;
};

exports.isUndefined = function (value) {
    return typeof value === "undefined";
};

exports.isString = function (value) {
    return typeof value === "string" || value instanceof String;
};
<|endoftext|>


<commit_before>/*global fail: true */
/*jslint es5: true */

/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2016 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

define([
    "global/Promise",
    "joynr",
    "joynr/datatypes/DatatypesProxy",
    "joynr/datatypes/exampleTypes/Country",
    "integration/TestEnd2EndDatatypesTestData",
    "integration/IntegrationUtils",
    "joynr/provisioning/provisioning_cc",
    "uuid",
    "global/WaitsFor"
], function(
        Promise,
        joynr,
        DatatypesProxy,
        Country,
        TestEnd2EndDatatypesTestData,
        IntegrationUtils,
        provisioning,
        uuid,
        waitsFor) {
    describe("libjoynr-js.integration.end2end.datatypes", function() {

        var datatypesProxy, workerId;
        var testIdentifier = 0;

        beforeEach(function(done) {
            datatypesProxy = undefined;
            var provisioningSuffix = "End2EndDatatypesTest" + "-" + testIdentifier++;
            var domain = provisioningSuffix;
            var testProvisioning = IntegrationUtils.getProvisioning(provisioning, domain);
            joynr.load(testProvisioning).then(function(newJoynr){
                joynr = newJoynr;
                IntegrationUtils.initialize(joynr);

                IntegrationUtils.initializeWebWorker(
                        "TestEnd2EndDatatypesProviderWorker",
                        provisioningSuffix,
                        domain).then(function(newWorkerId) {
                    workerId = newWorkerId;
                    return IntegrationUtils.startWebWorker(workerId);
                }).then(
                        function() {
                            return IntegrationUtils.buildProxy(DatatypesProxy, domain).then(
                                    function(newDatatypesProxy) {
                                        datatypesProxy = newDatatypesProxy;
                                        done();
                                        return null;
                                    });
                        });
            }).catch(function(error){
                throw error;
            });
        });

        it("supports all datatypes in attributes get/set", function(done) {
            var i, j;

            function testAttrType(attributeName, attributeValue) {
                return new Promise(function(resolve, reject) {
                    var attribute;
                    attribute = datatypesProxy[attributeName];
                    attribute.set({
                        value : attributeValue
                    }).then(function() {
                        // get the value
                        attribute.get().then(resolve, reject);
                        return null;
                    }).catch(function(error) {
                        reject(error);
                        IntegrationUtils.outputPromiseError(error);
                    });
                });
            }

            function setAndGetAttribute(attributeName, attributeValue, promiseChain) {
                return promiseChain.then(function() {
                    var onFulfilledSpy = jasmine.createSpy("onFulfilledSpy");
                    return testAttrType(attributeName, attributeValue).then(function(value) {
                        expect(value).toEqual(attributeValue);
                        IntegrationUtils.checkValueAndType(value, attributeValue);
                    }).catch(IntegrationUtils.outputPromiseError);
                });
            }

            var promiseChain = Promise.resolve();
            for (i = 0; i < TestEnd2EndDatatypesTestData.length; ++i) {
                var test = TestEnd2EndDatatypesTestData[i];
                for (j = 0; j < test.values.length; ++j) {
                    promiseChain = setAndGetAttribute(test.attribute, test.values[j], promiseChain);
                }
            }
            promiseChain.then(function() {
                done();
                return null;
            }).catch(fail);
        }, 60000);

        it("supports all datatypes as operation arguments", function(done) {
            var i;

            function testGetJavascriptType(arg, expectedReturnValue, promiseChain) {

                return promiseChain.then(function() {
                    var onFulfilledSpy;
                    onFulfilledSpy = jasmine.createSpy("onFulfilledSpy");
                    datatypesProxy.getJavascriptType({
                        arg : arg
                    }).then(onFulfilledSpy).catch(IntegrationUtils.outputPromiseError);

                    return waitsFor(function() {
                        return onFulfilledSpy.calls.count() > 0;
                    }, "operation is called", provisioning.ttl).then(function() {
                        expect(onFulfilledSpy).toHaveBeenCalled();
                        expect(onFulfilledSpy).toHaveBeenCalledWith({
                            javascriptType : expectedReturnValue
                        });
                    });
                });
            }

            var promiseChain = Promise.resolve();
            for (i = 0; i < TestEnd2EndDatatypesTestData.length; ++i) {
                var test = TestEnd2EndDatatypesTestData[i];
                promiseChain = testGetJavascriptType(test.values[0], test.jsRuntimeType, promiseChain);
            }
            promiseChain.then(function() {
                done();
                return null;
            }).catch(fail);
        }, 60000);

        it("supports all datatypes as operation argument and return value", function(done) {
            var i;

            function testGetArgumentBack(arg, promiseChain) {
                return promiseChain.then(function() {
                    return datatypesProxy.getArgumentBack({
                        arg : arg
                    }).then(function(value) {
                        expect(value).toEqual({ returnValue : arg });
                        IntegrationUtils.checkValueAndType(value.returnValue, arg);
                    }).catch(IntegrationUtils.outputPromiseError);
                });
            }

            var promiseChain = Promise.resolve();
            for (i = 0; i < TestEnd2EndDatatypesTestData.length; ++i) {
                var test = TestEnd2EndDatatypesTestData[i];
                promiseChain = testGetArgumentBack(test.values[0], promiseChain);
            }
            promiseChain.then(function() {
                done();
                return null;
            }).catch(fail);
        }, 60000);

        it("supports multiple operation arguments", function(done) {
            var i;

            function testMultipleArguments(opArgs) {
                var onFulfilledSpy;

                onFulfilledSpy = jasmine.createSpy("onFulfilledSpy");
                datatypesProxy.multipleArguments(opArgs).then(
                        onFulfilledSpy).catch(IntegrationUtils.outputPromiseError);

                return waitsFor(function() {
                    return onFulfilledSpy.calls.count() > 0;
                }, "operation is called", provisioning.ttl).then(function() {
                    expect(onFulfilledSpy).toHaveBeenCalled();
                    expect(onFulfilledSpy).toHaveBeenCalledWith({
                        serialized : JSON.stringify(opArgs)
                    });
                });
            }

            var opArgs = {};
            for (i = 0; i < TestEnd2EndDatatypesTestData.length; ++i) {
                var test = TestEnd2EndDatatypesTestData[i];
                /* replace all dots with _ */
                var paramName = test.joynrType.replace(/\./g, "_") + "Arg";
                paramName = paramName.slice(0, 1).toLowerCase() + paramName.slice(1);
                opArgs[paramName] = test.values[0];
            }
            testMultipleArguments(opArgs).then(function() {
                done();
                return null;
            }).catch(fail);
        }, 60000);

        afterEach(function(done) {
            IntegrationUtils.shutdownWebWorker(workerId).then(IntegrationUtils.shutdownLibjoynr).then(function() {
                done();
                return null;
            }).catch(fail);
        });
    });
});
<commit_msg>[JS] Increase test timeout in Datatypes test<commit_after>/*global fail: true */
/*jslint es5: true */

/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2016 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

define([
    "global/Promise",
    "joynr",
    "joynr/datatypes/DatatypesProxy",
    "joynr/datatypes/exampleTypes/Country",
    "integration/TestEnd2EndDatatypesTestData",
    "integration/IntegrationUtils",
    "joynr/provisioning/provisioning_cc",
    "uuid",
    "global/WaitsFor"
], function(
        Promise,
        joynr,
        DatatypesProxy,
        Country,
        TestEnd2EndDatatypesTestData,
        IntegrationUtils,
        provisioning,
        uuid,
        waitsFor) {
    describe("libjoynr-js.integration.end2end.datatypes", function() {

        var datatypesProxy, workerId;
        var testIdentifier = 0;

        beforeEach(function(done) {
            datatypesProxy = undefined;
            var provisioningSuffix = "End2EndDatatypesTest" + "-" + testIdentifier++;
            var domain = provisioningSuffix;
            var testProvisioning = IntegrationUtils.getProvisioning(provisioning, domain);
            joynr.load(testProvisioning).then(function(newJoynr){
                joynr = newJoynr;
                IntegrationUtils.initialize(joynr);

                IntegrationUtils.initializeWebWorker(
                        "TestEnd2EndDatatypesProviderWorker",
                        provisioningSuffix,
                        domain).then(function(newWorkerId) {
                    workerId = newWorkerId;
                    return IntegrationUtils.startWebWorker(workerId);
                }).then(
                        function() {
                            return IntegrationUtils.buildProxy(DatatypesProxy, domain).then(
                                    function(newDatatypesProxy) {
                                        datatypesProxy = newDatatypesProxy;
                                        done();
                                        return null;
                                    });
                        });
            }).catch(function(error){
                throw error;
            });
        });

        it("supports all datatypes in attributes get/set", function(done) {
            var i, j;

            function testAttrType(attributeName, attributeValue) {
                return new Promise(function(resolve, reject) {
                    var attribute;
                    attribute = datatypesProxy[attributeName];
                    attribute.set({
                        value : attributeValue
                    }).then(function() {
                        // get the value
                        attribute.get().then(resolve, reject);
                        return null;
                    }).catch(function(error) {
                        reject(error);
                        IntegrationUtils.outputPromiseError(error);
                    });
                });
            }

            function setAndGetAttribute(attributeName, attributeValue, promiseChain) {
                return promiseChain.then(function() {
                    var onFulfilledSpy = jasmine.createSpy("onFulfilledSpy");
                    return testAttrType(attributeName, attributeValue).then(function(value) {
                        expect(value).toEqual(attributeValue);
                        IntegrationUtils.checkValueAndType(value, attributeValue);
                    }).catch(IntegrationUtils.outputPromiseError);
                });
            }

            var promiseChain = Promise.resolve();
            for (i = 0; i < TestEnd2EndDatatypesTestData.length; ++i) {
                var test = TestEnd2EndDatatypesTestData[i];
                for (j = 0; j < test.values.length; ++j) {
                    promiseChain = setAndGetAttribute(test.attribute, test.values[j], promiseChain);
                }
            }
            promiseChain.then(function() {
                done();
                return null;
            }).catch(fail);
        }, 120000);

        it("supports all datatypes as operation arguments", function(done) {
            var i;

            function testGetJavascriptType(arg, expectedReturnValue, promiseChain) {

                return promiseChain.then(function() {
                    var onFulfilledSpy;
                    onFulfilledSpy = jasmine.createSpy("onFulfilledSpy");
                    datatypesProxy.getJavascriptType({
                        arg : arg
                    }).then(onFulfilledSpy).catch(IntegrationUtils.outputPromiseError);

                    return waitsFor(function() {
                        return onFulfilledSpy.calls.count() > 0;
                    }, "operation is called", provisioning.ttl).then(function() {
                        expect(onFulfilledSpy).toHaveBeenCalled();
                        expect(onFulfilledSpy).toHaveBeenCalledWith({
                            javascriptType : expectedReturnValue
                        });
                    });
                });
            }

            var promiseChain = Promise.resolve();
            for (i = 0; i < TestEnd2EndDatatypesTestData.length; ++i) {
                var test = TestEnd2EndDatatypesTestData[i];
                promiseChain = testGetJavascriptType(test.values[0], test.jsRuntimeType, promiseChain);
            }
            promiseChain.then(function() {
                done();
                return null;
            }).catch(fail);
        }, 60000);

        it("supports all datatypes as operation argument and return value", function(done) {
            var i;

            function testGetArgumentBack(arg, promiseChain) {
                return promiseChain.then(function() {
                    return datatypesProxy.getArgumentBack({
                        arg : arg
                    }).then(function(value) {
                        expect(value).toEqual({ returnValue : arg });
                        IntegrationUtils.checkValueAndType(value.returnValue, arg);
                    }).catch(IntegrationUtils.outputPromiseError);
                });
            }

            var promiseChain = Promise.resolve();
            for (i = 0; i < TestEnd2EndDatatypesTestData.length; ++i) {
                var test = TestEnd2EndDatatypesTestData[i];
                promiseChain = testGetArgumentBack(test.values[0], promiseChain);
            }
            promiseChain.then(function() {
                done();
                return null;
            }).catch(fail);
        }, 60000);

        it("supports multiple operation arguments", function(done) {
            var i;

            function testMultipleArguments(opArgs) {
                var onFulfilledSpy;

                onFulfilledSpy = jasmine.createSpy("onFulfilledSpy");
                datatypesProxy.multipleArguments(opArgs).then(
                        onFulfilledSpy).catch(IntegrationUtils.outputPromiseError);

                return waitsFor(function() {
                    return onFulfilledSpy.calls.count() > 0;
                }, "operation is called", provisioning.ttl).then(function() {
                    expect(onFulfilledSpy).toHaveBeenCalled();
                    expect(onFulfilledSpy).toHaveBeenCalledWith({
                        serialized : JSON.stringify(opArgs)
                    });
                });
            }

            var opArgs = {};
            for (i = 0; i < TestEnd2EndDatatypesTestData.length; ++i) {
                var test = TestEnd2EndDatatypesTestData[i];
                /* replace all dots with _ */
                var paramName = test.joynrType.replace(/\./g, "_") + "Arg";
                paramName = paramName.slice(0, 1).toLowerCase() + paramName.slice(1);
                opArgs[paramName] = test.values[0];
            }
            testMultipleArguments(opArgs).then(function() {
                done();
                return null;
            }).catch(fail);
        }, 60000);

        afterEach(function(done) {
            IntegrationUtils.shutdownWebWorker(workerId).then(IntegrationUtils.shutdownLibjoynr).then(function() {
                done();
                return null;
            }).catch(fail);
        });
    });
});
<|endoftext|>


<commit_before>module.exports = {
    /**
     * Enforcing options
     * When set to true, these options will make JSHint produce more warnings about your code.
     */

    // This option prohibits the use of bitwise operators such as ^ (XOR), | (OR) and others.
    // Bitwise operators are very rare in JavaScript programs and quite often & is simply a mistyped &&.
    bitwise: true,
    // This option allows you to force all variable names to use either camelCase style or UPPER_CASE with underscores.
    camelcase: true,
    // This option requires you to always put curly braces around blocks in loops and conditionals.
    curly: true,
    // This options prohibits the use of == and != in favor of === and !==.
    eqeqeq: true,
    // This option tells JSHint that your code needs to adhere to ECMAScript 3 specification.
    es3: true,
    // This option requires all for in loops to filter object's items.
    forin: true,
    // This option prohibits the use of immediate function invocations without wrapping them in parentheses.
    immed: true,
    // This option enforces specific tab width for your code. For example, the following code will trigger a warning on line 4:
    indent: 4,
    // This option prohibits the use of a variable before it was defined.
    latedef: true,
    // This option requires you to capitalize names of constructor functions.
    newcap: true,
    // This option prohibits the use of arguments.caller and arguments.callee.
    noarg: true,
    // This option warns when you have an empty block in your code.
    noempty: true,
    // This option prohibits the use of constructor functions for side-effects.
    nonew: true,
    // This option prohibits the use of unary increment and decrement operators.
    plusplus: true,
    // This option enforces the consistency of quotation marks used throughout your code.
    quotmark: true,
    // This option prohibits the use of explicitly undeclared variables.
    undef: true,
    // This option warns when you define and never use your variables.
    unused: true,
    // This option requires all functions to run in ECMAScript 5's strict mode.
    strict: true,
    // This option makes it an error to leave a trailing whitespace in your code.
    trailing: true,

    /**
     * Relaxing options
     * When set to true, these options will make JSHint produce less warnings about your code.
     */

    // This option suppresses warnings about missing semicolons.
    asi: false,
    // This option suppresses warnings about the use of assignments in cases where comparisons are expected.
    boss: false,
    // This option suppresses warnings about the debugger statements in your code.
    debug: false,
    // This option suppresses warnings about == null comparisons.
    eqnull: false,
    // This option tells JSHint that your code uses ECMAScript 6 specific syntax.
    esnext: false,
    // This option suppresses warnings about the use of eval.
    evil: false,
    // This option suppresses warnings about the use of expressions where normally you would expect to see assignments or function calls.
    expr: false,
    // This option suppresses warnings about declaring variables inside of control structures while accessing them later from the outside.
    funcscope: false,
    // This option suppresses warnings about the use of global strict mode.
    globalstrict: true,
    // This option suppresses warnings about the __iterator__ property.
    iterator: false,
    // This option suppresses warnings about missing semicolons, but only when the semicolon is omitted for the last statement in a one-line block.
    lastsemic: false,
    // This option suppresses most of the warnings about possibly unsafe line breakings in your code.
    laxbreak: false,
    // This option suppresses warnings about comma-first coding style.
    laxcomma: false,
    // This option suppresses warnings about functions inside of loops.
    loopfunc: false,
    // This options tells JSHint that your code uses Mozilla JavaScript extensions.
    moz: false,
    // This option suppresses warnings about multi-line strings.
    multistr: false,
    // This option suppresses warnings about the __proto__ property.
    proto: false,
    // This option suppresses warnings about the use of script-targeted URLs—such as javascript:....
    scripturl: false,
    // This option suppresses warnings about mixed tabs and spaces when the latter are used for alignmnent only.
    smarttabs: false,
    // This option suppresses warnings about variable shadowing i.e. declaring a variable that had been already declared somewhere in the outer scope.
    shadow: false,
    // This option suppresses warnings about using [] notation when it can be expressed in dot notation
    sub: true,
    // This option suppresses warnings about "weird" constructions like new function () { ... } and new Object;.
    supernew: false,
    // This option suppresses warnings about possible strict violations when the code is running in strict mode and you use this in a non-constructor function.
    validthis: false,

    /**
     * Environments
     * These options let JSHint know about some pre-defined global variables.
     */
    browser: true,

    globals: {
        __dirname: true,
        process: true,
        exports: true,
        module: true,
        console: true,
        define: true,
        require: true
    }
};
<commit_msg>Adding JSON to globals ignore in config/jshint.js<commit_after>module.exports = {
    /**
     * Enforcing options
     * When set to true, these options will make JSHint produce more warnings about your code.
     */

    // This option prohibits the use of bitwise operators such as ^ (XOR), | (OR) and others.
    // Bitwise operators are very rare in JavaScript programs and quite often & is simply a mistyped &&.
    bitwise: true,
    // This option allows you to force all variable names to use either camelCase style or UPPER_CASE with underscores.
    camelcase: true,
    // This option requires you to always put curly braces around blocks in loops and conditionals.
    curly: true,
    // This options prohibits the use of == and != in favor of === and !==.
    eqeqeq: true,
    // This option tells JSHint that your code needs to adhere to ECMAScript 3 specification.
    es3: true,
    // This option requires all for in loops to filter object's items.
    forin: true,
    // This option prohibits the use of immediate function invocations without wrapping them in parentheses.
    immed: true,
    // This option enforces specific tab width for your code. For example, the following code will trigger a warning on line 4:
    indent: 4,
    // This option prohibits the use of a variable before it was defined.
    latedef: true,
    // This option requires you to capitalize names of constructor functions.
    newcap: true,
    // This option prohibits the use of arguments.caller and arguments.callee.
    noarg: true,
    // This option warns when you have an empty block in your code.
    noempty: true,
    // This option prohibits the use of constructor functions for side-effects.
    nonew: true,
    // This option prohibits the use of unary increment and decrement operators.
    plusplus: true,
    // This option enforces the consistency of quotation marks used throughout your code.
    quotmark: true,
    // This option prohibits the use of explicitly undeclared variables.
    undef: true,
    // This option warns when you define and never use your variables.
    unused: true,
    // This option requires all functions to run in ECMAScript 5's strict mode.
    strict: true,
    // This option makes it an error to leave a trailing whitespace in your code.
    trailing: true,

    /**
     * Relaxing options
     * When set to true, these options will make JSHint produce less warnings about your code.
     */

    // This option suppresses warnings about missing semicolons.
    asi: false,
    // This option suppresses warnings about the use of assignments in cases where comparisons are expected.
    boss: false,
    // This option suppresses warnings about the debugger statements in your code.
    debug: false,
    // This option suppresses warnings about == null comparisons.
    eqnull: false,
    // This option tells JSHint that your code uses ECMAScript 6 specific syntax.
    esnext: false,
    // This option suppresses warnings about the use of eval.
    evil: false,
    // This option suppresses warnings about the use of expressions where normally you would expect to see assignments or function calls.
    expr: false,
    // This option suppresses warnings about declaring variables inside of control structures while accessing them later from the outside.
    funcscope: false,
    // This option suppresses warnings about the use of global strict mode.
    globalstrict: true,
    // This option suppresses warnings about the __iterator__ property.
    iterator: false,
    // This option suppresses warnings about missing semicolons, but only when the semicolon is omitted for the last statement in a one-line block.
    lastsemic: false,
    // This option suppresses most of the warnings about possibly unsafe line breakings in your code.
    laxbreak: false,
    // This option suppresses warnings about comma-first coding style.
    laxcomma: false,
    // This option suppresses warnings about functions inside of loops.
    loopfunc: false,
    // This options tells JSHint that your code uses Mozilla JavaScript extensions.
    moz: false,
    // This option suppresses warnings about multi-line strings.
    multistr: false,
    // This option suppresses warnings about the __proto__ property.
    proto: false,
    // This option suppresses warnings about the use of script-targeted URLs—such as javascript:....
    scripturl: false,
    // This option suppresses warnings about mixed tabs and spaces when the latter are used for alignmnent only.
    smarttabs: false,
    // This option suppresses warnings about variable shadowing i.e. declaring a variable that had been already declared somewhere in the outer scope.
    shadow: false,
    // This option suppresses warnings about using [] notation when it can be expressed in dot notation
    sub: true,
    // This option suppresses warnings about "weird" constructions like new function () { ... } and new Object;.
    supernew: false,
    // This option suppresses warnings about possible strict violations when the code is running in strict mode and you use this in a non-constructor function.
    validthis: false,

    /**
     * Environments
     * These options let JSHint know about some pre-defined global variables.
     */
    browser: true,

    globals: {
        __dirname: true,
        process: true,
        exports: true,
        module: true,
        console: true,
        define: true,
        require: true,
        JSON: true
    }
};
<|endoftext|>


<commit_before>'use strict';

var $ = require('jquery');
var NodeGit = require('nodegit');
var utils = require('./utils');
var templates = require('./templates');
var CompositeDisposable = require('atom').CompositeDisposable;

var GitTravelView = function (serializedState) { // eslint-disable-line no-unused-vars
  this.subscriptions = new CompositeDisposable; // eslint-disable-line new-parens

  this.element = document.createElement('div');
  this.$element = $(this.element);

  this.$element
    .addClass('git-travel padded')
    .append(templates.panels.branches())
    .append(templates.panels.tags())
    .append(templates.panels.commits());

  this.$element.on('click', '.commit', function (e) {
    var target = $(e.target);
    var oid = target.data('id');

    utils.getRepo()
      .then((repo) => {
        repo.setHeadDetached(oid);

        $('.commit, .branch, .tag').removeClass('selected');
        target.addClass('selected');

        return NodeGit.Checkout.head(repo, {
          checkoutStrategy: NodeGit.Checkout.STRATEGY.FORCE
        });
      })
      .catch((err) => console.log(err));
  });

  this.$element.on('click', '.branch', function (e) {
    var target = $(e.target);

    var name = target.data('name');
    var ref = 'refs/heads/' + name;
    var repo;

    utils.getRepo()
      .then((r) => {
        repo = r;
        repo.checkoutBranch(ref);
      })
      .then((err) => {
        if (!err) {
          $('.commit, .branch, .tag').removeClass('selected');
          target.addClass('selected');

          return NodeGit.Checkout.head(repo, {
            checkoutStrategy: NodeGit.Checkout.STRATEGY.FORCE
          });
        } else {
          var choice = confirm('Your index isn\'t clean, if you proceed the changes your\'ve made will be discarded. Proceed?');

          if (choice) {
            $('.commit, .branch, .tag').removeClass('selected');
            target.addClass('selected');

            return repo.setHead(ref).then(() => {
              return NodeGit.Checkout.head(repo, {
                checkoutStrategy: NodeGit.Checkout.STRATEGY.FORCE
              });
            });
          }
        }
      })
      .catch((err) => console.log(err));
  });
};

GitTravelView.prototype.serialize = function () {};

GitTravelView.prototype.destroy = function () {
  this.subscriptions.dispose();
  this.element.remove();
};

GitTravelView.prototype.getElement = function () {
  return this.element;
};

GitTravelView.prototype.updateElement = function (type, items) {
  var panel = this.$element.find(`.${type}s-panel`);
  var target = panel.find('.panel-body');

  target.empty();

  items.length ? panel.show() : panel.hide();

  items
    .map((item) => {
      target.append(templates.item(type, item));

      var currentElement = target.children().last()[0];

      this.subscriptions.add(
        atom.tooltips.add(currentElement, {
          title: item.name || item.ref.message()
        })
      );
    });
};

module.exports = GitTravelView;
<commit_msg>do nothing if an error is triggered<commit_after>'use strict';

var $ = require('jquery');
var NodeGit = require('nodegit');
var utils = require('./utils');
var templates = require('./templates');
var CompositeDisposable = require('atom').CompositeDisposable;

var GitTravelView = function (serializedState) { // eslint-disable-line no-unused-vars
  this.subscriptions = new CompositeDisposable; // eslint-disable-line new-parens

  this.element = document.createElement('div');
  this.$element = $(this.element);

  this.$element
    .addClass('git-travel padded')
    .append(templates.panels.branches())
    .append(templates.panels.tags())
    .append(templates.panels.commits());

  this.$element.on('click', '.commit', function (e) {
    var target = $(e.target);
    var oid = target.data('id');

    utils.getRepo()
      .then((repo) => {
        repo.setHeadDetached(oid);

        $('.commit, .branch, .tag').removeClass('selected');
        target.addClass('selected');

        return NodeGit.Checkout.head(repo, {
          checkoutStrategy: NodeGit.Checkout.STRATEGY.FORCE
        });
      })
      .catch((err) => console.log(err));
  });

  this.$element.on('click', '.branch', function (e) {
    var target = $(e.target);

    var name = target.data('name');
    var ref = 'refs/heads/' + name;
    var repo;

    utils.getRepo()
      .then((r) => {
        repo = r;
        repo.checkoutBranch(ref);
      })
      .then((err) => {
        if (!err) {
          $('.commit, .branch, .tag').removeClass('selected');
          target.addClass('selected');

          return NodeGit.Checkout.head(repo, {
            checkoutStrategy: NodeGit.Checkout.STRATEGY.FORCE
          });
        }
      })
      .catch((err) => console.log(err));
  });
};

GitTravelView.prototype.serialize = function () {};

GitTravelView.prototype.destroy = function () {
  this.subscriptions.dispose();
  this.element.remove();
};

GitTravelView.prototype.getElement = function () {
  return this.element;
};

GitTravelView.prototype.updateElement = function (type, items) {
  var panel = this.$element.find(`.${type}s-panel`);
  var target = panel.find('.panel-body');

  target.empty();

  items.length ? panel.show() : panel.hide();

  items
    .map((item) => {
      target.append(templates.item(type, item));

      var currentElement = target.children().last()[0];

      this.subscriptions.add(
        atom.tooltips.add(currentElement, {
          title: item.name || item.ref.message()
        })
      );
    });
};

module.exports = GitTravelView;
<|endoftext|>


<commit_before>var http = require('http');
var cheerio = require('cheerio');
var request = require('request');
var iconv = require('iconv-lite');

function stripScripts(s) {
  return s.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
}

function getUserId(s) {
  return s.replace(/.+&id=(.+)'\)/g, '$1');
}

function listData(data) {
  var $ = cheerio.load(data);
  var $posts = $('tr[height="30"]');

  var arr = [];
  var lastid;

  $posts.each(function(i, elem) {
    var item = this.children[1].children[1].children[1];
    var obj = {};

    var comment;

    if (this.type === 'tag' && this.children) {
      item = item.children;

      obj.num = item[1].children[0].children[0].data;
      obj.articleId = item[3].children[1].attribs.title;
      obj.subject = item[3].children[1].children[0].data.trim();

      comment = item[3].children[2].children[0].children[0].children[0].children[0].children[0];
      obj.commentCount = comment ? comment.children[0].data : '';

      obj.author = item[5].children[0].children[1].children[0].data;
      obj.userId = getUserId(item[5].children[0].children[0].children[0].children[0].attribs.onclick);
      obj.date = item[9].children[0].children[0].data;
      obj.views = item[11].children[0].children[0].data;

      arr.push(obj);
      lastid = obj.articleId;
    }
  });

  return {
    array: arr,
    lastid: lastid
  };
}

var mlbparkPath = 'http://mlbpark.donga.com';

module.exports = function(app) {
  app.get('/', function(req, res) {
    res.redirect('/list');
  });

  app.get('/list', function(req, res) {
    var reqURL = mlbparkPath + '/mbs/articleL.php?mbsC=bullpen2&cpage=1';

    http.get(reqURL, function(response) {
      response.pipe(iconv.decodeStream('EUC-KR')).collect(function(err, body) {
        body = stripScripts(body);

        res.render('index', {
          items: listData(body)
        });
      });
    });
  });

  app.post('/api/list', function(req, res) {
    var reqURL = mlbparkPath + '/mbs/articleL.php?mbsC=bullpen2&cpage=' + req.params.pageNum;
    http.get(reqURL, function(response) {
      response.pipe(iconv.decodeStream('EUC-KR')).collect(function(err, body) {
        body = stripScripts(body);

        res.json(listData(body));
      });
    });
  });

  app.get('/article/:articleId', function(req, res) {
    var reqParams = req.params;
    var articleId = reqParams.articleId;
    var reqURL = mlbparkPath + '/mbs/articleV.php?mbsC=bullpen2&mbsIdx=' + articleId;

    http.get(reqURL, function(response) {
      response.pipe(iconv.decodeStream('EUC-KR')).collect(function(err, body) {
        body = stripScripts(body);
        var $ = cheerio.load(body);

        if (!$('body').length) {
          res.send('존재하지 않는 게시물 입니다.');
        }

        var data = {};
        data.subject = $('td[width="82%"] strong').text();
        data.author = $('td[width="18%"] font');
        data.authorNickname = data.author[0].children[3].children[0].children[0].data;
        data.authorId = getUserId(data.author[0].children[1].children[1].children[0].attribs.onclick);
        data.article = $('.G13 div[align="justify"]').html();
        data.articleNumber = articleId;
        data.date = $('.D11[width="225"] font:last-child').text();
        data.ip = $('.D11[width="201"] font:last-child').text();
        data.viewAndVotes = $('.D11[width="76"] strong');
        data.views = data.viewAndVotes.eq(0).text();
        data.votes = data.viewAndVotes.eq(1).text();

        res.render('view', data);
      });
    });
  });
};
<commit_msg>리스트 데이터를 dom object 에서 찾지 않고, selector 를 이용하여 찾도록 변경<commit_after>var http = require('http');
var cheerio = require('cheerio');
var request = require('request');
var iconv = require('iconv-lite');

function stripScripts(s) {
  return s.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
}

function getUserId(s) {
  return s.replace(/.+&id=(.+)'\)/g, '$1');
}

function listData(data) {
  var $ = cheerio.load(data);
  var $posts = $('tr[height="30"]');

  var arr = [];
  var lastid;

  $posts.each(function(i, elem) {
    var item = this.children[1].children[1].children[1];
    var obj = {};
    var $link;

    if (this.type === 'tag' && this.children) {
      item = item.children;

      obj.num = $(this).find('td[width="45"]').text();

      $link = $(this).find('td[width="383"] > a');
      obj.articleId = $link.attr('title');
      obj.subject = $link.text();

      obj.commentCount = $(this).find('td[width="383"] .A12oreng').text();

      console.log();

      obj.author = $(this).find('td[width="82"] a').text();
      obj.userId = getUserId($(this).find('td[width="82"] li:first-child').attr('onclick'));
      obj.date = $(this).find('td[width="66"]').text();
      obj.views = $(this).find('td[width="40"]').text();

      arr.push(obj);
      lastid = obj.articleId;
    }
  });

  return {
    array: arr,
    lastid: lastid
  };
}

var mlbparkPath = 'http://mlbpark.donga.com';

module.exports = function(app) {
  app.get('/', function(req, res) {
    res.redirect('/list');
  });

  app.get('/list', function(req, res) {
    var reqURL = mlbparkPath + '/mbs/articleL.php?mbsC=bullpen2&cpage=1';

    http.get(reqURL, function(response) {
      response.pipe(iconv.decodeStream('EUC-KR')).collect(function(err, body) {
        body = stripScripts(body);

        res.render('index', {
          items: listData(body)
        });
      });
    });
  });

  app.post('/api/list', function(req, res) {
    var reqURL = mlbparkPath + '/mbs/articleL.php?mbsC=bullpen2&cpage=' + req.params.pageNum;
    http.get(reqURL, function(response) {
      response.pipe(iconv.decodeStream('EUC-KR')).collect(function(err, body) {
        body = stripScripts(body);

        res.json(listData(body));
      });
    });
  });

  app.get('/article/:articleId', function(req, res) {
    var reqParams = req.params;
    var articleId = reqParams.articleId;
    var reqURL = mlbparkPath + '/mbs/articleV.php?mbsC=bullpen2&mbsIdx=' + articleId;

    http.get(reqURL, function(response) {
      response.pipe(iconv.decodeStream('EUC-KR')).collect(function(err, body) {
        body = stripScripts(body);
        var $ = cheerio.load(body);

        if (!$('body').length) {
          res.send('존재하지 않는 게시물 입니다.');
        }

        var data = {};
        data.subject = $('td[width="82%"] strong').text();
        data.author = $('td[width="18%"] font');
        data.authorNickname = data.author[0].children[3].children[0].children[0].data;
        data.authorId = getUserId(data.author[0].children[1].children[1].children[0].attribs.onclick);
        data.article = $('.G13 div[align="justify"]').html();
        data.articleNumber = articleId;
        data.date = $('.D11[width="225"] font:last-child').text();
        data.ip = $('.D11[width="201"] font:last-child').text();
        data.viewAndVotes = $('.D11[width="76"] strong');
        data.views = data.viewAndVotes.eq(0).text();
        data.votes = data.viewAndVotes.eq(1).text();

        res.render('view', data);
      });
    });
  });
};
<|endoftext|>


<commit_before>// Draw routes.  Locomotive's router provides expressive syntax for drawing
// routes, including support for resourceful routes, namespaces, and nesting.
// MVC routes can be mapped mapped to controllers using convenient
// `controller#action` shorthand.  Standard middleware in the form of
// `function(req, res, next)` is also fully supported.  Consult the Locomotive
// Guide on [routing](http://locomotivejs.org/guide/routing.html) for additional
// information.
module.exports = function routes() {
  //this.root('restaurants#index');
  //this.resources('restaurants');

	/*
	 * Clients routes
	 */
	this.match('survey', { controller: 'clients', action: 'startsurvey', via: 'GET'});
	//this.match('reservation', { controller: 'clients', action: 'makereservation', via: 'GET'});

	/*
	 * Restaurants routes
	 */
	this.match('restaurants/search', 'restaurants#search');
	this.match('restaurants/:id/showcodes', 'restaurants#showcodes');
	this.match('restaurants/:id/gencodes', 'restaurants#generatecodes');
	this.resources('restaurants');
	/*
	 * Surveys routes
	 */
	this.match('surveycodes/generate', { controller: 'surveycodes', action: 'generate', via: 'POST'});
	this.match('surveycodes/check', { controller: 'surveycodes', action: 'check', via: 'GET'});
	this.match('surveycodes/validate', { controller: 'surveycodes', action: 'validate', via: 'POST'});
	this.resources('surveycodes', { only: ['show', 'update', 'destroy'] });
}
<commit_msg>Add new routes to config<commit_after>// Draw routes.  Locomotive's router provides expressive syntax for drawing
// routes, including support for resourceful routes, namespaces, and nesting.
// MVC routes can be mapped mapped to controllers using convenient
// `controller#action` shorthand.  Standard middleware in the form of
// `function(req, res, next)` is also fully supported.  Consult the Locomotive
// Guide on [routing](http://locomotivejs.org/guide/routing.html) for additional
// information.
module.exports = function routes() {
  //this.root('restaurants#index');
  //this.resources('restaurants');

	/*
	 * Clients routes
	 */
	this.match('survey', { controller: 'clients', action: 'startsurvey', via: 'GET'});
	//this.match('reservation', { controller: 'clients', action: 'makereservation', via: 'GET'});

	/*
	 * Restaurants routes
	 */

	/*
	 * Routes for Restaurant
	 *
	 * Name				Method		Path
	 * ---------------------------------------------
	 * Index			GET 		/restaurants
	 * Show				GET			/restaurants/:id
	 * New				GET			/restaurants/new
	 * Create			POST		/restaurants
	 * Edit 			GET 		/restaurants/edit
	 * Update 			PUT 		/restaurants/:id
	 * Delete 			GET 		/restaurants/delete
	 * Destroy 			DELETE 		/restaurants/:id
	 * Search			GET			/restaurants/search?<query>
	 * Showcodes		GET			/restaurants/:id/codes
	 * Generatecodes	GET			/restaurants/:id/generate?n=<number>
	 */
	this.match('restaurants', 				'restaurants#index');
	this.match('restaurants/new', 			'restaurants#new');
	this.match('restaurants/edit', 			'restaurants#edit');
	this.match('restaurants/delete', 		'restaurants#delete');
	this.match('restaurants/search', 		'restaurants#search');
	this.match('restaurants/:id', 			'restaurants#show');
	this.match('restaurants/:id/showcodes', 'restaurants#showcodes');
	this.match('restaurants/:id/gencodes', 	'restaurants#generatecodes');
	this.match('restaurants', 				{ controller: 'restaurants', action: 'create', via: 'POST'});
	this.match('restaurants/:id', 			{ controller: 'restaurants', action: 'update', via: 'PUT'});
	this.match('restaurants/:id', 			{ controller: 'restaurants', action: 'destroy', via: 'DELETE'});

	/*
	 * Surveys routes
	 */
	this.match('surveycodes/generate', { controller: 'surveycodes', action: 'generate', via: 'POST'});
	this.match('surveycodes/check', { controller: 'surveycodes', action: 'check', via: 'GET'});
	this.match('surveycodes/validate', { controller: 'surveycodes', action: 'validate', via: 'POST'});
	this.resources('surveycodes', { only: ['show', 'update', 'destroy'] });
}
<|endoftext|>


<commit_before>//
// Vows.js - asynchronous event-based BDD for node.js
//
//   usage:
//
//       var vows = require('vows');
//
//       vows.describe('Deep Thought').addVows(function () {
//           question('what is the answer to the universe?').addVow(function (answer) {
//               assert.equals(answer, 42);
//           }, 'it should know the answer to the ultimate question of life');
//       });
//
var path = require('path');

require.paths.unshift(path.join(path.dirname(__filename), 'vendor'),
                      path.dirname(__filename));

var sys = require('sys'),
    assert = require('assert'),
    events = require('events'),
    eyes = require('eyes').inspector({ writer: null }),
    vows = exports;

// Keeps track of the outcome of vows.
var total  = 0, honored = 0,
    broken = 0, errored = 0,

    start,  // Start time
    end,    // End time
    suites; // Number of test suites added by `addVows()`

// Context stack, used in addVow() to keep track
var lastContext;

// Output buffer
var buffer;

//
// Assertion Macros
//
vows.macros = require('vows/macros');

assert.AssertionError.prototype.toString = function () {
    var that = this,
        source = this.stack.match(/([a-zA-Z0-9_-]+\.js)(:\d+):\d+/);

    function parse(str) {
        return str.replace(/{actual}/g,   inspect(that.actual)).
                   replace(/{expected}/g, inspect(that.expected)).
                   replace(/{operator}/g, stylize(that.operator, 'bold'));
    }

    if (this.message) {
        return stylize(parse(this.message), 'yellow') +
               stylize(' // ' + source[1] + source[2], 'grey');
    } else {
        return stylize([
            this.expected,
            this.operator,
            this.actual
        ].join(' '), 'yellow');
    }
}

//
// This function gets added to events.EventEmitter.prototype, by default.
// It's essentially a wrapper around `addCallback`, which adds all the specification
// goodness.
//
function addVow(/* description & callback */) {
    var desc, callback, context = '', vow = {}, args = arguments;

    total++;

    if (args.length > 1) {
        // Sometimes it might be nicer to pass the proof first,
        // and the description second, so we let the user choose
        // the order.
        if (typeof(args[0]) === "function") {
            vow.callback = args[0], vow.description = args[1];
        } else {
            vow.callback = args[1], vow.description = args[0];
        }
    } else if (args[0].callback && args[0].context) {
        vow = args[0];
    } else {
        throw new(Error)("wrong argument type for addVow()");
    }

    return this.addListener("success", function () {
        var title = ' - ', exception, topic, msg;

        // Run the test, and try to catch `AssertionError`s and other exceptions;
        // increment counters accordingly.
        try {
            vow.callback.apply(args[0].binding || null, arguments);
            title += stylize(vow.description, 'green');
            honored++;
        } catch (e) {
            if (e.name && e.name.match(/AssertionError/)) {
                title += stylize(vow.description, 'yellow');
                exception = '   ~ ' + e.toString();
                broken++;
            } else {
                title += stylize(vow.description, 'red');
                msg = e.stack || e.message || e.toString() || e;
                exception = '   ! ' + stylize(msg, 'red');
                errored++;
            }
        }
        output(title, exception);
    }).addListener("error", function (err) {
        var exception = "  * " + stylize('The promise returned an error: ' +
                                 stylize(err, 'bold'), 'red');
        errored++;
        output('- ' + stylize(vow.description, 'red'), exception + "\n");
    });

    function output(title, exception) {
        if (exception || !vows.options.brief) {
            if (vow.context && lastContext !== vow.context) {
                lastContext = vow.context;
                puts(vow.context);
            }
            puts(title);
            if (exception) puts(exception);
        }
        tryFinish(vows.remaining, vow.promise);
    }
};

function Context(vow, ctx, env) {
    this.tests = vow.callback;
    this.topics = (ctx.topics || []).slice(0);
    this.env = env || {};
    this.env.context = this;
    this.name = (ctx.name ? ctx.name + ' ' : '') +
                (vow.description || '');
}

function addVows(tests) {
    var promise = new(events.EventEmitter);
    var remaining = 0;

    suites++;

    vows.promises.push(promise);

    if (typeof(tests) === 'object') {
        // Count the number of vows/promises expected to fire,
        // so we know when the tests are over.
        // We match the keys against `matcher`, to decide
        // whether or not they should be included in the test.
        (function count(tests) {
            var match = false;
            remaining++;
            Object.keys(tests).forEach(function (key) {
                if (typeof(tests[key]) === "object" && !Array.isArray(tests[key])) {
                    if (! (match = count(tests[key]) ||
                           match || vows.options.matcher.test(key))) {
                        delete tests[key];
                        remaining--;
                    }
                }
            });
            return match;
        })(tests);
    }

    this.addListener("end", function (honored, broken, errored) {
        var topic, vow, env;

        vows.remaining += remaining;

        if (typeof(tests) === 'function') {
            return tests.call(null);
        } else {
            // The test runner, it calls itself recursively, passing the
            // previous context to the inner contexts. This is so the `topic`
            // functions have access to all the previous context topics in their
            // arguments list.
            // It is defined and invoked at the same time.
            // If it encounters a `topic` function, it waits for the returned
            // promise to emit (the topic), at which point it runs the functions under it,
            // passing the topic as an argument.
            (function run(ctx, lastTopic) {
                var ctxAdded = false;

                topic = lastTopic = ('topic' in ctx.tests) ? ctx.tests.topic
                                                           : lastTopic;
                // Topic isn't a function, wrap it into one.
                if (typeof(topic) !== 'function') {
                    topic = (function (topic) {
                        return function () { return topic };
                    })(topic);
                }

                // Run the topic, passing the previous context topics
                topic = topic.apply(ctx.env, ctx.topics);

                // If the topic doesn't return an event emitter (such as a promise),
                // we create it ourselves, and emit the value on the next tick.
                if (! (topic instanceof vows.options.Emitter)) {
                    var emitter = new(vows.options.Emitter);

                    process.nextTick(function (val) {
                        return function () { emitter.emit("success", val) };
                    }(topic)); topic = emitter;
                }

                topic.addListener('success', function (val) {
                    // Once the topic fires, add the return value
                    // to the beginning of the topics list, so it
                    // becomes the first argument for the next topic.
                    ctx.topics.unshift(val);
                });

                // Now run the tests, or sub-contexts
                Object.keys(ctx.tests).filter(function (k) {
                    return ctx.tests[k] && k !== 'topic';
                }).forEach(function (item) {
                    // Holds the current test or context
                    vow = Object.create({
                        callback: ctx.tests[item],
                        context: ctx.name,
                        description: item,
                        binding: ctx.env,
                        promise: promise
                    });
                    env = Object.create(ctx.env);

                    // If we encounter a function, add it to the callbacks
                    // of the `topic` function, so it'll get called once the
                    // topic fires.
                    // If we encounter an object literal, we recurse, sending it
                    // our current context.
                    if (typeof(vow.callback) === 'function') {
                        topic.addVow(vow);
                    } else if (typeof(vow.callback) === 'object' && ! Array.isArray(vow.callback)) {
                        // If there's a setup stage, we have to wait for it to fire,
                        // before calling the inner context. Else, just run the inner context
                        // synchronously.
                        if (topic) {
                            topic.addListener("success", function (vow, ctx) {
                                return function (val) {
                                    return run(new(Context)(vow, ctx, env), lastTopic);
                                };
                            }(vow, ctx));
                        } else {
                            run(new(Context)(vow, ctx, env), lastTopic);
                        }
                    }
                });
                // Check if we're done running the tests
                tryFinish(--vows.remaining, promise);
            // This is our initial, empty context
            })(new(Context)({ callback: tests, context: null, description: null }, {}));
        }
    });
    return promise;
}

function puts() {
    var args = Array.prototype.slice.call(arguments);
    if (vows.promises[suites - 1].listeners('finish').length > 0) {
        buffer.push(args.join('\n'));
    } else {
      sys.puts.apply(null, args);
    }
}

//
// Checks if all the required tests have been run,
// and either triggers the next test suite, if any,
// or exits the process.
//
function tryFinish(remaining, promise) {
    var result, style;

    // Output results once all the vows have been checked
    if (honored + broken + errored === total && remaining === 0) {
        result = honored + " honored, " +
                 broken  + " broken, "  +
                 errored + " errored",
        style  = honored === total ? ('green')
                                   : (errored === 0 ? 'yellow' : 'red');

        // If this isn't the last test suite in the chain,
        // emit 'end', to trigger the next test suite.
        if (promise && promise.listeners('end').length > 0) {
            sys.print('\n');
            promise.emit('end', honored, broken, errored);
        } else {
            if (!vows.options.brief) {
                puts("\nVerified " + total + " vows in " +
                     (((new(Date)) - start) / 1000) + " seconds.");
                puts("\n" + stylize(result, style));
            }

            // The 'finish' event is triggered once all the tests have been run.
            // It's used by bin/vows
            vows.promises[suites - 1].emit("finish", honored, broken, errored);

            if ((broken || errored) && buffer.length) { sys.puts(buffer.join('\n') + '\n') }

            // Don't exit until stdout is empty
            process.stdout.addListener('drain', function () {
                process.exit(broken || errored ? 1 : 0);
            });
        }
    }
}

//
// On exit, check that all promises have been fired.
// If not, print an error message.
//
process.addListener('exit', function () {
    if (honored + broken + errored < total) {
        sys.puts('\n* ' + stylize("An EventEmitter has failed to fire.", 'red'));
    }
});

//
// Wrap a Node.js style async function into an EventEmmitter
//
vows.prepare = function (obj, targets) {
    targets.forEach(function (target) {
        if (target in obj) {
            obj[target] = (function (fun) {
                return function () {
                    var args = Array.prototype.slice.call(arguments);
                    var ee = new(events.EventEmitter);

                    args.push(function (err /* [, data] */) {
                        var args = Array.prototype.slice.call(arguments, 1);

                        if (err) { ee.emit('error', err) }
                        else     { ee.emit.apply(ee, ['success'].concat(args)) }
                    });
                    fun.apply(obj, args);

                    return ee;
                };
            })(obj[target]);
        }
    });
    return obj;
};

// Options
vows.options = {
    Emitter: events.EventEmitter,
    brief: false,
    matcher: /.*/
};

// Run all vows/tests.
// It can take either a function as `tests`,
// or an object literal.
vows.describe = function (subject) {
    this.options.Emitter.prototype.addVow = addVow;
    this.options.Emitter.prototype.addVows = addVows;
    this.remaining = 0;
    this.promises = [];

    // Reset values
    total  = 0, honored = 0,
    broken = 0, errored = 0;
    buffer = [], suites = 0;

    var promise = new(events.EventEmitter);

    process.nextTick(function () {
        if (!vows.options.brief) {
            puts('\n' + stylize(subject, 'underline') + '\n');
        }
        promise.emit("end");
    });
    start = new(Date);

    return promise;
};

vows.tell = vows.describe;

// Return the `vows` object after setting some options
vows.config = function (opts) {
    for (var k in opts) { this.options[k] = opts[k] }
    return this;
};

//
// Utility functions
//

function inspect(val) {
    return '\033[1m' + eyes(val) + '\033[22m';
}

// Stylize a string
function stylize(str, style) {
    var styles = {
        'bold'      : [1,  22],
        'underline' : [4,  24],
        'yellow'    : [33, 39],
        'green'     : [32, 39],
        'red'       : [31, 39],
        'grey'      : [90, 39]
    };
    return '\033[' + styles[style][0] + 'm' + str +
           '\033[' + styles[style][1] + 'm';
}

<commit_msg>improved emitter code in describe()<commit_after>//
// Vows.js - asynchronous event-based BDD for node.js
//
//   usage:
//
//       var vows = require('vows');
//
//       vows.describe('Deep Thought').addVows(function () {
//           question('what is the answer to the universe?').addVow(function (answer) {
//               assert.equals(answer, 42);
//           }, 'it should know the answer to the ultimate question of life');
//       });
//
var path = require('path');

require.paths.unshift(path.join(path.dirname(__filename), 'vendor'),
                      path.dirname(__filename));

var sys = require('sys'),
    assert = require('assert'),
    events = require('events'),
    eyes = require('eyes').inspector({ writer: null }),
    vows = exports;

// Keeps track of the outcome of vows.
var total  = 0, honored = 0,
    broken = 0, errored = 0,

    start,  // Start time
    end,    // End time
    suites; // Number of test suites added by `addVows()`

// Context stack, used in addVow() to keep track
var lastContext;

// Output buffer
var buffer;

//
// Assertion Macros
//
vows.macros = require('vows/macros');

assert.AssertionError.prototype.toString = function () {
    var that = this,
        source = this.stack.match(/([a-zA-Z0-9_-]+\.js)(:\d+):\d+/);

    function parse(str) {
        return str.replace(/{actual}/g,   inspect(that.actual)).
                   replace(/{expected}/g, inspect(that.expected)).
                   replace(/{operator}/g, stylize(that.operator, 'bold'));
    }

    if (this.message) {
        return stylize(parse(this.message), 'yellow') +
               stylize(' // ' + source[1] + source[2], 'grey');
    } else {
        return stylize([
            this.expected,
            this.operator,
            this.actual
        ].join(' '), 'yellow');
    }
}

//
// This function gets added to events.EventEmitter.prototype, by default.
// It's essentially a wrapper around `addCallback`, which adds all the specification
// goodness.
//
function addVow(/* description & callback */) {
    var desc, callback, context = '', vow = {}, args = arguments;

    total++;

    if (args.length > 1) {
        // Sometimes it might be nicer to pass the proof first,
        // and the description second, so we let the user choose
        // the order.
        if (typeof(args[0]) === "function") {
            vow.callback = args[0], vow.description = args[1];
        } else {
            vow.callback = args[1], vow.description = args[0];
        }
    } else if (args[0].callback && args[0].context) {
        vow = args[0];
    } else {
        throw new(Error)("wrong argument type for addVow()");
    }

    return this.addListener("success", function () {
        var title = ' - ', exception, topic, msg;

        // Run the test, and try to catch `AssertionError`s and other exceptions;
        // increment counters accordingly.
        try {
            vow.callback.apply(args[0].binding || null, arguments);
            title += stylize(vow.description, 'green');
            honored++;
        } catch (e) {
            if (e.name && e.name.match(/AssertionError/)) {
                title += stylize(vow.description, 'yellow');
                exception = '   ~ ' + e.toString();
                broken++;
            } else {
                title += stylize(vow.description, 'red');
                msg = e.stack || e.message || e.toString() || e;
                exception = '   ! ' + stylize(msg, 'red');
                errored++;
            }
        }
        output(title, exception);
    }).addListener("error", function (err) {
        var exception = "  * " + stylize('The promise returned an error: ' +
                                 stylize(err, 'bold'), 'red');
        errored++;
        output('- ' + stylize(vow.description, 'red'), exception + "\n");
    });

    function output(title, exception) {
        if (exception || !vows.options.brief) {
            if (vow.context && lastContext !== vow.context) {
                lastContext = vow.context;
                puts(vow.context);
            }
            puts(title);
            if (exception) puts(exception);
        }
        tryFinish(vows.remaining, vow.promise);
    }
};

function Context(vow, ctx, env) {
    this.tests = vow.callback;
    this.topics = (ctx.topics || []).slice(0);
    this.env = env || {};
    this.env.context = this;
    this.name = (ctx.name ? ctx.name + ' ' : '') +
                (vow.description || '');
}

function addVows(tests) {
    var promise = new(events.EventEmitter);
    var remaining = 0;

    suites++;

    vows.promises.push(promise);

    if (typeof(tests) === 'object') {
        // Count the number of vows/promises expected to fire,
        // so we know when the tests are over.
        // We match the keys against `matcher`, to decide
        // whether or not they should be included in the test.
        (function count(tests) {
            var match = false;
            remaining++;
            Object.keys(tests).forEach(function (key) {
                if (typeof(tests[key]) === "object" && !Array.isArray(tests[key])) {
                    if (! (match = count(tests[key]) ||
                           match || vows.options.matcher.test(key))) {
                        delete tests[key];
                        remaining--;
                    }
                }
            });
            return match;
        })(tests);
    }

    this.addListener("end", function (honored, broken, errored) {
        var topic, vow, env;

        vows.remaining += remaining;

        if (typeof(tests) === 'function') {
            return tests.call(null);
        } else {
            // The test runner, it calls itself recursively, passing the
            // previous context to the inner contexts. This is so the `topic`
            // functions have access to all the previous context topics in their
            // arguments list.
            // It is defined and invoked at the same time.
            // If it encounters a `topic` function, it waits for the returned
            // promise to emit (the topic), at which point it runs the functions under it,
            // passing the topic as an argument.
            (function run(ctx, lastTopic) {
                var ctxAdded = false;

                topic = lastTopic = ('topic' in ctx.tests) ? ctx.tests.topic
                                                           : lastTopic;
                // Topic isn't a function, wrap it into one.
                if (typeof(topic) !== 'function') {
                    topic = (function (topic) {
                        return function () { return topic };
                    })(topic);
                }

                // Run the topic, passing the previous context topics
                topic = topic.apply(ctx.env, ctx.topics);

                // If the topic doesn't return an event emitter (such as a promise),
                // we create it ourselves, and emit the value on the next tick.
                if (! (topic instanceof vows.options.Emitter)) {
                    var emitter = new(vows.options.Emitter);

                    process.nextTick(function (val) {
                        return function () { emitter.emit("success", val) };
                    }(topic)); topic = emitter;
                }

                topic.addListener('success', function (val) {
                    // Once the topic fires, add the return value
                    // to the beginning of the topics list, so it
                    // becomes the first argument for the next topic.
                    ctx.topics.unshift(val);
                });

                // Now run the tests, or sub-contexts
                Object.keys(ctx.tests).filter(function (k) {
                    return ctx.tests[k] && k !== 'topic';
                }).forEach(function (item) {
                    // Holds the current test or context
                    vow = Object.create({
                        callback: ctx.tests[item],
                        context: ctx.name,
                        description: item,
                        binding: ctx.env,
                        promise: promise
                    });
                    env = Object.create(ctx.env);

                    // If we encounter a function, add it to the callbacks
                    // of the `topic` function, so it'll get called once the
                    // topic fires.
                    // If we encounter an object literal, we recurse, sending it
                    // our current context.
                    if (typeof(vow.callback) === 'function') {
                        topic.addVow(vow);
                    } else if (typeof(vow.callback) === 'object' && ! Array.isArray(vow.callback)) {
                        // If there's a setup stage, we have to wait for it to fire,
                        // before calling the inner context. Else, just run the inner context
                        // synchronously.
                        if (topic) {
                            topic.addListener("success", function (vow, ctx) {
                                return function (val) {
                                    return run(new(Context)(vow, ctx, env), lastTopic);
                                };
                            }(vow, ctx));
                        } else {
                            run(new(Context)(vow, ctx, env), lastTopic);
                        }
                    }
                });
                // Check if we're done running the tests
                tryFinish(--vows.remaining, promise);
            // This is our initial, empty context
            })(new(Context)({ callback: tests, context: null, description: null }, {}));
        }
    });
    return promise;
}

function puts() {
    var args = Array.prototype.slice.call(arguments);
    if (vows.promises[suites - 1].listeners('finish').length > 0) {
        buffer.push(args.join('\n'));
    } else {
      sys.puts.apply(null, args);
    }
}

//
// Checks if all the required tests have been run,
// and either triggers the next test suite, if any,
// or exits the process.
//
function tryFinish(remaining, promise) {
    var result, style;

    // Output results once all the vows have been checked
    if (honored + broken + errored === total && remaining === 0) {
        result = honored + " honored, " +
                 broken  + " broken, "  +
                 errored + " errored",
        style  = honored === total ? ('green')
                                   : (errored === 0 ? 'yellow' : 'red');

        // If this isn't the last test suite in the chain,
        // emit 'end', to trigger the next test suite.
        if (promise && promise.listeners('end').length > 0) {
            sys.print('\n');
            promise.emit('end', honored, broken, errored);
        } else {
            if (!vows.options.brief) {
                puts("\nVerified " + total + " vows in " +
                     (((new(Date)) - start) / 1000) + " seconds.");
                puts("\n" + stylize(result, style));
            }

            // The 'finish' event is triggered once all the tests have been run.
            // It's used by bin/vows
            vows.promises[suites - 1].emit("finish", honored, broken, errored);

            if ((broken || errored) && buffer.length) { sys.puts(buffer.join('\n') + '\n') }

            // Don't exit until stdout is empty
            process.stdout.addListener('drain', function () {
                process.exit(broken || errored ? 1 : 0);
            });
        }
    }
}

//
// On exit, check that all promises have been fired.
// If not, print an error message.
//
process.addListener('exit', function () {
    if (honored + broken + errored < total) {
        sys.puts('\n* ' + stylize("An EventEmitter has failed to fire.", 'red'));
    }
});

//
// Wrap a Node.js style async function into an EventEmmitter
//
vows.prepare = function (obj, targets) {
    targets.forEach(function (target) {
        if (target in obj) {
            obj[target] = (function (fun) {
                return function () {
                    var args = Array.prototype.slice.call(arguments);
                    var ee = new(events.EventEmitter);

                    args.push(function (err /* [, data] */) {
                        var args = Array.prototype.slice.call(arguments, 1);

                        if (err) { ee.emit('error', err) }
                        else     { ee.emit.apply(ee, ['success'].concat(args)) }
                    });
                    fun.apply(obj, args);

                    return ee;
                };
            })(obj[target]);
        }
    });
    return obj;
};

// Options
vows.options = {
    Emitter: events.EventEmitter,
    brief: false,
    matcher: /.*/
};

// Run all vows/tests.
// It can take either a function as `tests`,
// or an object literal.
vows.describe = function (subject) {
    this.options.Emitter.prototype.addVow = addVow;
    this.options.Emitter.prototype.addVows = addVows;
    this.remaining = 0;
    this.promises = [];

    // Reset values
    total  = 0, honored = 0,
    broken = 0, errored = 0;
    buffer = [], suites = 0;

    process.nextTick(function () {
        if (!vows.options.brief) {
            puts('\n' + stylize(subject, 'underline') + '\n');
        }
    });
    return new(events.EventEmitter)().addListener('newListener', function (e, listener) {
        if (e === 'end') {
            this.removeListener(e, listener);
            start = new(Date);
            listener.call(this);
        }
    });
};

vows.tell = vows.describe;

// Return the `vows` object after setting some options
vows.config = function (opts) {
    for (var k in opts) { this.options[k] = opts[k] }
    return this;
};

//
// Utility functions
//

function inspect(val) {
    return '\033[1m' + eyes(val) + '\033[22m';
}

// Stylize a string
function stylize(str, style) {
    var styles = {
        'bold'      : [1,  22],
        'underline' : [4,  24],
        'yellow'    : [33, 39],
        'green'     : [32, 39],
        'red'       : [31, 39],
        'grey'      : [90, 39]
    };
    return '\033[' + styles[style][0] + 'm' + str +
           '\033[' + styles[style][1] + 'm';
}

<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */
var basePath = 'http://report.karbonat.com/bolmalzemos';

var mongoose = require('mongoose');
var passportOptions = {
  failureFlash: 'Invalid email or password.',
  failureRedirect: '/login'
};

// controllers
var home = require('home'),
    admin = require('admin'),
    users = require('users');

// middlewares
var requiresLogin = function(req, res, next) {
  if (req.isAuthenticated()) return next();
  if (req.method == "GET") req.session.returnTo = req.originalUrl;
  res.redirect(basePath + '/admin/login');
};

/**
 * Expose
 */
module.exports = function (app, passport) {

  app.namespace(basePath, function() {
    // public pages
    app.get('/', home.index);
    app.get('/videos', home.videos);

    // auth pages
    app.get('/admin/login', admin.login);
    app.post('/admin/login', passport.authenticate(
          'local',
          {
            successRedirect: basePath + '/admin',
            failureRedired: basePath + '/admin/login'
          }));
    app.get('/admin/logout', requiresLogin, admin.logout);
    app.get('/admin/create', requiresLogin, admin.createAdmin);
    app.post('/admin/create', requiresLogin, admin.createAdminPost);

    // admin pages
    app.get('/admin', requiresLogin, admin.index);
    app.post('/admin/video/approve', requiresLogin, admin.approve);
    app.post('/admin/video/delete', requiresLogin, admin.disapprove);
    app.get('/admin/video/ids', requiresLogin, admin.approved);

    // user pages
    app.get('/users', requiresLogin, users.index);
    app.post('/users/delete', requiresLogin, users.deleteUser);
  });

};
<commit_msg>Routes changed to static<commit_after>
/**
 * Module dependencies.
 */
var basePath = 'http://report.karbonat.com/bolmalzemos';

var mongoose = require('mongoose');
var passportOptions = {
  failureFlash: 'Invalid email or password.',
  failureRedirect: '/login'
};

// controllers
var home = require('home'),
    admin = require('admin'),
    users = require('users');

// middlewares
var requiresLogin = function(req, res, next) {
  if (req.isAuthenticated()) return next();
  if (req.method == "GET") req.session.returnTo = req.originalUrl;
  res.redirect(basePath + '/admin/login');
};

/**
 * Expose
 */
module.exports = function (app, passport) {

  app.namespace(basePath, function() {
    // public pages
    app.get(basePath, home.index);
    app.get(basePath + '/videos', home.videos);

    // auth pages
    app.get(basePath + '/admin/login', admin.login);
    app.post(basePath + '/admin/login', passport.authenticate(
          'local',
          {
            successRedirect: basePath + '/admin',
            failureRedired: basePath + '/admin/login'
          }));
    app.get(basePath + '/admin/logout', requiresLogin, admin.logout);
    app.get(basePath + '/admin/create', requiresLogin, admin.createAdmin);
    app.post(basePath + '/admin/create', requiresLogin, admin.createAdminPost);

    // admin pages
    app.get(basePath + '/admin', requiresLogin, admin.index);
    app.post(basePath + '/admin/video/approve', requiresLogin, admin.approve);
    app.post(basePath + '/admin/video/delete', requiresLogin, admin.disapprove);
    app.get(basePath + '/admin/video/ids', requiresLogin, admin.approved);

    // user pages
    app.get(basePath + '/users', requiresLogin, users.index);
    app.post(basePath + '/users/delete', requiresLogin, users.deleteUser);
  });

};
<|endoftext|>