<commit_before>"use strict"
require(TEST_HELPER) // <--- This must be at the top of every test file.

const Text = require(__models + '/texts');
const pg      = require('../../db/db_setup');
const dbCleaner = require('knex-cleaner');

describe('Texts model', function() {
  describe('interface with database', function() {

  	beforeEach(function() {
      return dbCleaner.clean(pg, {mode: 'truncate'})
        .then(function() {
          return pg('texts').insert([
            {
              text_content: 'This is an example of Fwibble',
              room_id: 1,
              user_id: 1,
            },
          ])
        })
    })

    it_('should list all texts of a room', function * () {
      yield Text.allOfRoom(1)
        .then(function(texts) {
          expect(texts).to.have.length(1);
          expect(texts[0].text_content).to.equal('This is an example of Fwibble');
        })
        .catch(function(error) {
          console.error('error inserting text', error)
        })
    })

    it_('should create a new text', function * () {
      let newText = {
        text_content: 'New Fwibble in the database word',
        room_id: 1,
        user_id: 2,
      }

      yield Message.create(newText)
        .then(function(text) {
          expect(text.text_content).to.equal('New Fwibble in the database word');
          expect(text.room_id).to.equal(1);
          expect(text.user_id).to.equal(2);
          expect(text.createdAt).to.be.ok;
        })
        .catch(function(error) {
          console.error('error inserting text', error)
        })
    })
})
})

<commit_msg>Resolved issue with mocha tests, tests are functioning properly.<commit_after>"use strict"
require(TEST_HELPER) // <--- This must be at the top of every test file.

const Text = require(__models + '/texts');
const pg      = require('../../db/db_setup');
const dbCleaner = require('knex-cleaner');

describe('Texts model', function() {
  describe('interface with database', function() {

  	beforeEach(function() {
      return dbCleaner.clean(pg, {mode: 'truncate'})
        .then(function() {
          return pg('texts').insert([
            {
              text_id: 1,
              text_content: 'This is an example of Fwibble',
              room_id: 1,
              user_id: 1,
            },
          ])
        })
    })

    it_('should list all texts of a room', function * () {
      yield Text.allOfRoom(1)
        .then(function(texts) {
          expect(texts).to.have.length(1);
          expect(texts[0].text_content).to.equal('This is an example of Fwibble');
        })
        .catch(function(error) {
          console.error('error inserting text', error)
        })
    })

    it_('should create a new text', function * () {
      let newText = {
        text_content: 'New Fwibble in the database word',
        room_id: 1,
        user_id: 2,
      }

      yield Message.create(newText)
        .then(function(text) {
          expect(text.text_content).to.equal('New Fwibble in the database word');
          expect(text.room_id).to.equal(1);
          expect(text.user_id).to.equal(2);
          expect(text.createdAt).to.be.ok;
        })
        .catch(function(error) {
          console.error('error inserting text', error)
        })
    })
})
})

<|endoftext|>


<commit_before>/*!
 * Snakeskin
 * https://github.com/SnakeskinTpl/Snakeskin
 *
 * Released under the MIT license
 * https://github.com/SnakeskinTpl/Snakeskin/blob/master/LICENSE
 */

import { $C } from '../deps/collection';
import { Snakeskin } from '../core';
import { Parser } from '../parser/index';
import { ws, r } from '../helpers/string';
import { symbols } from '../consts/regs';
import { nmeRgxp, nmsRgxp, nmssRgxp } from '../parser/name';
import { applyDefEscape, escapeDoubleQuotes } from '../helpers/escape';
import { concatProp } from '../helpers/literals';
import {

	WRITE,
	SCOPE,

	TEMPLATES,
	CACHE,
	PROTOS,

	ARGS,
	ARGS_RES,
	OUTPUT,

	EXT_LIST,
	EXT_MAP

} from '../consts/cache';

import {

	G_MOD,
	L_MOD

} from '../consts/literals';

/**
 * The number of iteration,
 * where the active template was declared
 * @type {number}
 */
Parser.prototype.startTemplateI = 0;

/**
 * The number of a line,
 * where the active template was declared
 * @type {?number}
 */
Parser.prototype.startTemplateLine = null;

/**
 * If is true, then the active template is generator
 * @type {?boolean}
 */
Parser.prototype.generator = null;

/**
 * The name of the active template
 * @type {?string}
 */
Parser.prototype.tplName = null;

/**
 * The parent name of the active template
 * @type {?string}
 */
Parser.prototype.parentTplName = null;

/**
 * The array of declared constants
 * @type {Array}
 */
Parser.prototype.consts = null;

/**
 * The name of the parent BEM class
 * @type {string}
 */
Parser.prototype.bemRef = '';

$C(['template', 'interface', 'placeholder']).forEach((template) => {
	Snakeskin.addDirective(
		template,

		{
			deferInit: true,
			block: true,
			placement: Snakeskin.placement('global'),
			notEmpty: true,
			group: [
				'template',
				'rootTemplate',
				'define'
			]
		},

		function (command, commandLength, type, jsDoc) {
			const proto = this.proto;
			const rank = {
				'template': 2,
				'interface': 1,
				'placeholder': 0
			};

			this.startDir(
				!proto && this.renderAs && rank[this.renderAs] < rank[type] ?
					this.renderAs : null
			);

			let lastName = '';
			const
				iface = this.name === 'interface';

			this.startTemplateI = this.i + 1;
			this.startTemplateLine = this.info.line;

			const
				nameRgxp = new RegExp(`^[^${symbols}_$[]`, 'i'),
				esprimaNameHackRgxp = new RegExp(`[${r(G_MOD)}${r(L_MOD)}]`, 'g');

			let
				tmpTplName = this.getFnName(command),
				tplName = this.pasteDangerBlocks(tmpTplName);

			if (!proto) {
				tmpTplName = this.replaceFileNamePatterns(tmpTplName);

				let
					prfx = '',
					pos;

				if (/\*/.test(tmpTplName)) {
					prfx = '*';
					tmpTplName = tmpTplName.replace(prfx, '');
				}

				tplName = this.pasteDangerBlocks(tmpTplName);
				this.generator = Boolean(prfx);

				try {
					if (!tplName || nameRgxp.test(tplName)) {
						throw false;
					}

					esprima.parse(tplName.replace(esprimaNameHackRgxp, ''));

				} catch (ignore) {
					return this.error(`invalid "${this.name}" name`);
				}

				if (tplName === 'init') {
					return this.error(`can't declare the template "${tplName}", try another name`);
				}

				this.info.template =
					this.tplName = tplName;

				if (this.name !== 'template' && !WRITE[tplName]) {
					WRITE[tplName] = false;
				}

				const
					fnArgsKey = this.getFnArgs(command).join(',').replace(/=(.*?)(?:,|$)/g, '');

				this.save(
					(pos = `/* Snakeskin template: ${tplName}; ${fnArgsKey} */`),
					iface,
					jsDoc
				);

				if (jsDoc) {
					jsDoc += pos.length;
				}

				const tmpArr = tmpTplName
					.replace(nmssRgxp, '%')
					.replace(nmsRgxp, '.%')
					.replace(nmeRgxp, '')
					.split('.');

				const
					length = tmpArr.length,
					first = str[0];

				let
					str = tmpArr[0],
					shortcut = '';

				if (first === '%') {
					try {
						str = ws`['${
							applyDefEscape(
								this.returnEvalVal(
									this.out(str.slice(1), {sys: true})
								)
							)
						}']`;

					} catch (err) {
						return this.error(err.message);
					}

				} else {
					shortcut = str;
				}

				for (let i = 1; i < length; i++) {
					let el = tmpArr[i];

					const
						custom = el[0] === '%',
						def = `this${concatProp(str)}`;

					if (custom) {
						el = el.slice(1);
					}

					this.save(
						(pos = ws`
							if (${def} == null) {
								${def} = {};
							}

							${i === 1 && shortcut ? `var ${shortcut} = ${def};` : ''}
						`),

						iface,
						jsDoc
					);

					if (jsDoc) {
						jsDoc += pos.length;
					}

					if (custom) {
						try {
							str += ws`['${
								applyDefEscape(
									this.returnEvalVal(
										this.out(el, {sys: true})
									)
								)
							}']`;

						} catch (err) {
							return this.error(err.message);
						}

						continue;

					} else if (i === length - 1) {
						lastName = el;
					}

					str += `.${el}`;
				}

				tplName = str;
				this.save(
					(length === 1 && shortcut ? `var ${shortcut} = ` : '') +
						`this${concatProp(tplName)} = function ${prfx}${length > 1 ? lastName : shortcut}(`,

					iface
				);
			}

			this.info.template =
				this.tplName = tplName;

			this.blockStructure = {
				name: 'root',
				parent: null,
				children: []
			};

			this.blockTable = {};
			this.varCache[tplName] = {};

			if (proto) {
				this.sysSpace = proto.sysSpace;
				this.strongSpace = proto.strongSpace;
				this.chainSpace = proto.chainSpace;
				this.space = proto.space;
				return;
			}

			let parentTplName;
			if (/\)\s+extends\s+/.test(command)) {
				try {
					parentTplName = /\)\s+extends\s+(.*?(?:@|$))/
						.exec(command)[1]
						.replace(/\s*@$/, '');

					if (!parentTplName || nameRgxp.test(parentTplName)) {
						throw false;
					}

					esprima.parse(parentTplName.replace(esprimaNameHackRgxp, ''));

				} catch (ignore) {
					return this.error(`invalid template name "${this.name}" for inheritance`);
				}

				try {
					parentTplName =
						this.parentTplName = this.prepareNameDecl(parentTplName);

				} catch (err) {
					return this.error(err.message);
				}

				if (CACHE[parentTplName] == null) {
					if (!this.renderAs || this.renderAs === 'template') {
						return this.error(`the specified template "${parentTplName}" for inheritance is not defined`);
					}

					parentTplName =
						this.parentTplName = null;
				}
			}

			this.initTemplateCache(tplName);

			if (tplName in EXT_MAP) {
				Parser.clearScopeCache(tplName);
			}

			const
				scope = SCOPE['template'],
				parent = scope[parentTplName];

			scope[tplName] = {
				id: this.environment.id,
				parent: parent,
				children: {}
			};

			scope[tplName].root = parent ?
				parent.root : scope[tplName];

			if (parent) {
				parent.children[tplName] = scope[tplName];
			}

			ARGS[tplName] = {};
			ARGS_RES[tplName] = {};
			OUTPUT[tplName] = {};

			EXT_MAP[tplName] = parentTplName;
			delete EXT_LIST[tplName];

			const
				baseParams = {},
				flags = command.split('@=');

			if (!parentTplName) {
				$C(this.params[this.params.length - 1]).forEach((el, key) => {
					if (key !== 'renderAs' && key[0] !== '@' && el !== undefined) {
						baseParams[key] = el;
					}
				});
			}

			if (parentTplName && flags.length === 1) {
				flags.push('@skip true');
			}

			$C(flags).forEach((el) => {
				const name = el.split(' ')[0];
				delete baseParams[name];
				Snakeskin.Directives['__setSSFlag__'].call(this, el);
			});

			$C(baseParams).forEach((el, key) => {
				Snakeskin.Directives['__setSSFlag__'].call(this, [key, el]);
			});

			const
				args = this.prepareArgs(command, 'template', {tplName, parentTplName});

			this.save(`${args.str}) {`, iface);
			if (args.scope) {
				this.scope.push(args.scope);
			}

			const predefs = [
				'callee',
				'blocks',
				'getTplResult',
				'clearTplResult',
				'$0',
				'TPL_NAME',
				'PARENT_TPL_NAME'
			];

			$C(predefs).forEach((el) => {
				this.structure.vars[el] = {
					value: el,
					scope: 0
				};
			});

			this.save(ws`
				var
					__THIS__ = this,
					__CALLEE__ = __ROOT__${concatProp(tplName)},
					callee = __CALLEE__;

				var
					__BLOCKS__ = __CALLEE__.Blocks = {},
					blocks = __BLOCKS__;

				var
					__RESULT__ = ${this.getReturnDecl()},
					__COMMENT_RESULT__,
					__NODE__,
					$0;

				function getTplResult(opt_clear) {
					var res = ${this.getReturnResultDecl()};

					if (opt_clear) {
						__RESULT__ = ${this.getReturnDecl()};
					}

					return res;
				}

				function clearTplResult() {
					__RESULT__ = ${this.getReturnDecl()};
				}

				var
					__RETURN__ = false,
					__RETURN_VAL__;

				var
					TPL_NAME = "${escapeDoubleQuote(tplName)}",
					PARENT_TPL_NAME${parentTplName ? ` = "${escapeDoubleQuote(parentTplName)}"` : ''};

				${args.defParams}
			`);

			const preDefs = this.preDefs[tplName];
			if ((!EXT_MAP[tplName] || parentTplName) && preDefs) {
				this.source =
					this.source.slice(0, this.i + 1) +
					preDefs.text +
					this.source.slice(this.i + 1);

				delete this.preDefs[tplName];
			}
		},

		function (command, commandLength) {
			const
				tplName = this.tplName,
				proto = this.proto;

			if (proto) {
				if (this.backTableI) {
					const
						ctx = proto.ctx;

					ctx.backTableI += this.backTableI;
					$C(this.backTable).forEach((el, key) => {
						$C(el).forEach((el) => {
							el.pos += proto.pos;
							el.outer = true;
							el.vars = this.structure.vars;
						});

						ctx.backTable[key] = ctx.backTable[key] ?
							ctx.backTable[key].concat(el) : el;
					});
				}

				return;
			}

			const diff = this.getDiff(commandLength);
			CACHE[tplName] = this.source.slice(this.startTemplateI, this.i - diff);
			TEMPLATES[tplName] = this.blockTable;

			if (this.parentTplName) {
				this.info.line = this.startTemplateLine;
				this.lines.splice(this.startTemplateLine, this.lines.length);

				this.source =
					this.source.slice(0, this.startTemplateI) +
					this.getTplFullBody(tplName) +
					this.source.slice(this.i - diff);

				this.initTemplateCache(tplName);
				this.startDir(this.structure.name);
				this.i = this.startTemplateI - 1;
				this.parentTplName = null;
				this.blockTable = {};
				this.varCache[tplName] = {};
				return;
			}

			if (this.backTableI) {
				try {
					$C(this.backTable).forEach((arr, key) => {
						$C(arr).forEach((el) => {
							if (!el.outer) {
								return;
							}

							const
								tmp = PROTOS[tplName][key];

							if (!tmp) {
								throw `the proto "${key}" is not defined`;
							}

							this.res =
								this.res.slice(0, el.pos) +
								this.res.slice(el.pos).replace(el.label, (el.argsStr || '') + (el.recursive ? tmp.i + '++;' : tmp.body));
						});
					});

				} catch (err) { return this.error(err); }

				this.backTable = {};
				this.backTableI = 0;
			}

			const
				iface = this.structure.name === 'interface';

			if (iface) {
				this.save('};', true);

			} else {
				this.save(ws`
						${this.consts.join('')}
						return ${this.getReturnResultDecl()};
					};

					Snakeskin.cache["${escapeDoubleQuotes(tplName)}"] = this${concatProp(tplName)};
				`);
			}

			this.save('/* Snakeskin template. */', iface);
			if (this.params[this.params.length - 1]['@tplName'] === this.tplName) {
				this.popParams();
			}

			this.canWrite = true;
			this.tplName = null;
			delete this.info.template;

			if (this.scope.length) {
				this.scope.pop();
			}
		}

	);
});
<commit_msg>Refactoring<commit_after>/*!
 * Snakeskin
 * https://github.com/SnakeskinTpl/Snakeskin
 *
 * Released under the MIT license
 * https://github.com/SnakeskinTpl/Snakeskin/blob/master/LICENSE
 */

import { $C } from '../deps/collection';
import { Snakeskin } from '../core';
import { Parser } from '../parser/index';
import { ws, r } from '../helpers/string';
import { symbols } from '../consts/regs';
import { nmeRgxp, nmsRgxp, nmssRgxp } from '../parser/name';
import { applyDefEscape, escapeDoubleQuotes } from '../helpers/escape';
import { concatProp } from '../helpers/literals';
import {

	WRITE,
	SCOPE,

	TEMPLATES,
	CACHE,
	PROTOS,

	ARGS,
	ARGS_RES,
	OUTPUT,

	EXT_LIST,
	EXT_MAP

} from '../consts/cache';

import {

	G_MOD,
	L_MOD

} from '../consts/literals';

/**
 * The number of iteration,
 * where the active template was declared
 * @type {number}
 */
Parser.prototype.startTemplateI = 0;

/**
 * The number of a line,
 * where the active template was declared
 * @type {?number}
 */
Parser.prototype.startTemplateLine = null;

/**
 * If is true, then the active template is generator
 * @type {?boolean}
 */
Parser.prototype.generator = null;

/**
 * The name of the active template
 * @type {?string}
 */
Parser.prototype.tplName = null;

/**
 * The parent name of the active template
 * @type {?string}
 */
Parser.prototype.parentTplName = null;

/**
 * The array of declared constants
 * @type {Array}
 */
Parser.prototype.consts = null;

/**
 * The name of the parent BEM class
 * @type {string}
 */
Parser.prototype.bemRef = '';

$C(['template', 'interface', 'placeholder']).forEach((template) => {
	Snakeskin.addDirective(
		template,

		{
			deferInit: true,
			block: true,
			placement: Snakeskin.placement('global'),
			notEmpty: true,
			group: [
				'template',
				'rootTemplate',
				'define'
			]
		},

		function (command, commandLength, type, jsDoc) {
			const proto = this.proto;
			const rank = {
				'template': 2,
				'interface': 1,
				'placeholder': 0
			};

			this.startDir(
				!proto && this.renderAs && rank[this.renderAs] < rank[type] ?
					this.renderAs : null
			);

			let lastName = '';
			const
				iface = this.name === 'interface';

			this.startTemplateI = this.i + 1;
			this.startTemplateLine = this.info.line;

			const
				nameRgxp = new RegExp(`^[^${symbols}_$[]`, 'i'),
				esprimaNameHackRgxp = new RegExp(`[${r(G_MOD)}${r(L_MOD)}]`, 'g');

			let
				tmpTplName = this.getFnName(command),
				tplName = this.pasteDangerBlocks(tmpTplName);

			if (!proto) {
				tmpTplName = this.replaceFileNamePatterns(tmpTplName);

				let
					prfx = '',
					pos;

				if (/\*/.test(tmpTplName)) {
					prfx = '*';
					tmpTplName = tmpTplName.replace(prfx, '');
				}

				tplName = this.pasteDangerBlocks(tmpTplName);
				this.generator = Boolean(prfx);

				try {
					if (!tplName || nameRgxp.test(tplName)) {
						throw false;
					}

					esprima.parse(tplName.replace(esprimaNameHackRgxp, ''));

				} catch (ignore) {
					return this.error(`invalid "${this.name}" name`);
				}

				if (tplName === 'init') {
					return this.error(`can't declare the template "${tplName}", try another name`);
				}

				this.info.template =
					this.tplName = tplName;

				if (this.name !== 'template' && !WRITE[tplName]) {
					WRITE[tplName] = false;
				}

				const
					fnArgsKey = this.getFnArgs(command).join(',').replace(/=(.*?)(?:,|$)/g, '');

				this.save(
					(pos = `/* Snakeskin template: ${tplName}; ${fnArgsKey} */`),
					iface,
					jsDoc
				);

				if (jsDoc) {
					jsDoc += pos.length;
				}

				const tmpArr = tmpTplName
					.replace(nmssRgxp, '%')
					.replace(nmsRgxp, '.%')
					.replace(nmeRgxp, '')
					.split('.');

				const
					length = tmpArr.length,
					first = str[0];

				let
					str = tmpArr[0],
					shortcut = '';

				if (first === '%') {
					try {
						str = ws`['${
							applyDefEscape(
								this.returnEvalVal(
									this.out(str.slice(1), {sys: true})
								)
							)
						}']`;

					} catch (err) {
						return this.error(err.message);
					}

				} else {
					shortcut = str;
				}

				for (let i = 1; i < length; i++) {
					let el = tmpArr[i];

					const
						custom = el[0] === '%',
						def = `this${concatProp(str)}`;

					if (custom) {
						el = el.slice(1);
					}

					this.save(
						(pos = ws`
							if (${def} == null) {
								${def} = {};
							}

							${i === 1 && shortcut ? `var ${shortcut} = ${def};` : ''}
						`),

						iface,
						jsDoc
					);

					if (jsDoc) {
						jsDoc += pos.length;
					}

					if (custom) {
						try {
							str += ws`['${
								applyDefEscape(
									this.returnEvalVal(
										this.out(el, {sys: true})
									)
								)
							}']`;

						} catch (err) {
							return this.error(err.message);
						}

						continue;

					} else if (i === length - 1) {
						lastName = el;
					}

					str += `.${el}`;
				}

				tplName = str;
				this.save(
					(length === 1 && shortcut ? `var ${shortcut} = ` : '') +
						`this${concatProp(tplName)} = function ${prfx}${length > 1 ? lastName : shortcut}(`,

					iface
				);
			}

			this.info.template =
				this.tplName = tplName;

			this.blockStructure = {
				name: 'root',
				parent: null,
				children: []
			};

			this.blockTable = {};
			this.varCache[tplName] = {};

			if (proto) {
				this.sysSpace = proto.sysSpace;
				this.strongSpace = proto.strongSpace;
				this.chainSpace = proto.chainSpace;
				this.space = proto.space;
				return;
			}

			let parentTplName;
			if (/\)\s+extends\s+/.test(command)) {
				try {
					parentTplName = /\)\s+extends\s+(.*?(?:@|$))/
						.exec(command)[1]
						.replace(/\s*@$/, '');

					if (!parentTplName || nameRgxp.test(parentTplName)) {
						throw false;
					}

					esprima.parse(parentTplName.replace(esprimaNameHackRgxp, ''));

				} catch (ignore) {
					return this.error(`invalid template name "${this.name}" for inheritance`);
				}

				try {
					parentTplName =
						this.parentTplName = this.prepareNameDecl(parentTplName);

				} catch (err) {
					return this.error(err.message);
				}

				if (CACHE[parentTplName] == null) {
					if (!this.renderAs || this.renderAs === 'template') {
						return this.error(`the specified template "${parentTplName}" for inheritance is not defined`);
					}

					parentTplName =
						this.parentTplName = null;
				}
			}

			this.initTemplateCache(tplName);

			if (tplName in EXT_MAP) {
				Parser.clearScopeCache(tplName);
			}

			const
				scope = SCOPE['template'],
				parent = scope[parentTplName];

			scope[tplName] = {
				id: this.environment.id,
				parent: parent,
				children: {}
			};

			scope[tplName].root = parent ?
				parent.root : scope[tplName];

			if (parent) {
				parent.children[tplName] = scope[tplName];
			}

			ARGS[tplName] = {};
			ARGS_RES[tplName] = {};
			OUTPUT[tplName] = {};

			EXT_MAP[tplName] = parentTplName;
			delete EXT_LIST[tplName];

			const
				baseParams = {},
				flags = command.split('@=');

			if (!parentTplName) {
				$C(this.params[this.params.length - 1]).forEach((el, key) => {
					if (key !== 'renderAs' && key[0] !== '@' && el !== undefined) {
						baseParams[key] = el;
					}
				});
			}

			if (parentTplName && flags.length === 1) {
				flags.push('@skip true');
			}

			$C(flags).forEach((el) => {
				const name = el.split(' ')[0];
				delete baseParams[name];
				Snakeskin.Directives['__setSSFlag__'].call(this, el);
			});

			$C(baseParams).forEach((el, key) => {
				Snakeskin.Directives['__setSSFlag__'].call(this, [key, el]);
			});

			const
				args = this.prepareArgs(command, 'template', {tplName, parentTplName});

			this.save(`${args.str}) {`, iface);
			if (args.scope) {
				this.scope.push(args.scope);
			}

			const predefs = [
				'callee',
				'blocks',
				'getTplResult',
				'clearTplResult',
				'$0',
				'TPL_NAME',
				'PARENT_TPL_NAME'
			];

			$C(predefs).forEach((el) => {
				this.structure.vars[el] = {
					value: el,
					scope: 0
				};
			});

			this.save(ws`
				var
					__THIS__ = this,
					__CALLEE__ = __ROOT__${concatProp(tplName)},
					callee = __CALLEE__;

				var
					__BLOCKS__ = __CALLEE__.Blocks = {},
					blocks = __BLOCKS__;

				var
					__RESULT__ = ${this.getReturnDecl()},
					__COMMENT_RESULT__,
					__NODE__,
					$0;

				function getTplResult(opt_clear) {
					var res = ${this.getReturnResultDecl()};

					if (opt_clear) {
						__RESULT__ = ${this.getReturnDecl()};
					}

					return res;
				}

				function clearTplResult() {
					__RESULT__ = ${this.getReturnDecl()};
				}

				var
					__RETURN__ = false,
					__RETURN_VAL__;

				var
					TPL_NAME = "${escapeDoubleQuote(tplName)}",
					PARENT_TPL_NAME${parentTplName ? ` = "${escapeDoubleQuote(parentTplName)}"` : ''};

				${args.defParams}
			`);

			const preDefs = this.preDefs[tplName];
			if ((!EXT_MAP[tplName] || parentTplName) && preDefs) {
				this.source =
					this.source.slice(0, this.i + 1) +
					preDefs.text +
					this.source.slice(this.i + 1);

				delete this.preDefs[tplName];
			}
		},

		function (command, commandLength) {
			const
				tplName = this.tplName,
				proto = this.proto;

			if (proto) {
				if (this.backTableI) {
					const
						ctx = proto.ctx;

					ctx.backTableI += this.backTableI;
					$C(this.backTable).forEach((el, key) => {
						$C(el).forEach((el) => {
							el.pos += proto.pos;
							el.outer = true;
							el.vars = this.structure.vars;
						});

						ctx.backTable[key] = ctx.backTable[key] ?
							ctx.backTable[key].concat(el) : el;
					});
				}

				return;
			}

			const diff = this.getDiff(commandLength);
			CACHE[tplName] = this.source.slice(this.startTemplateI, this.i - diff);
			TEMPLATES[tplName] = this.blockTable;

			if (this.parentTplName) {
				this.info.line = this.startTemplateLine;
				this.lines.splice(this.startTemplateLine, this.lines.length);

				this.source =
					this.source.slice(0, this.startTemplateI) +
					this.getTplFullBody(tplName) +
					this.source.slice(this.i - diff);

				this.initTemplateCache(tplName);
				this.startDir(this.structure.name);
				this.i = this.startTemplateI - 1;
				this.parentTplName = null;
				this.blockTable = {};
				this.varCache[tplName] = {};
				return;
			}

			if (this.backTableI) {
				try {
					$C(this.backTable).forEach((arr, key) => {
						$C(arr).forEach((el) => {
							if (!el.outer) {
								return;
							}

							const
								tmp = PROTOS[tplName][key];

							if (!tmp) {
								throw `the proto "${key}" is not defined`;
							}

							this.res =
								this.res.slice(0, el.pos) +
								this.res.slice(el.pos).replace(el.label, (el.argsStr || '') +
								(el.recursive ? tmp.i + '++;' : tmp.body));
						});
					});

				} catch (err) { return this.error(err); }

				this.backTable = {};
				this.backTableI = 0;
			}

			const
				iface = this.structure.name === 'interface';

			if (iface) {
				this.save('};', true);

			} else {
				this.save(ws`
						${this.consts.join('')}
						return ${this.getReturnResultDecl()};
					};

					Snakeskin.cache["${escapeDoubleQuotes(tplName)}"] = this${concatProp(tplName)};
				`);
			}

			this.save('/* Snakeskin template. */', iface);
			if (this.params[this.params.length - 1]['@tplName'] === this.tplName) {
				this.popParams();
			}

			this.canWrite = true;
			this.tplName = null;
			delete this.info.template;

			if (this.scope.length) {
				this.scope.pop();
			}
		}

	);
});
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');
const minimatch = require('minimatch');
const walk = require('fs-extra').walk;
const _ = require('lodash');

const Info = require('../Info');

function getFiles(dirPath, recursive, pattern, files) {
    files = files || [];
    let items = fs.readdirSync(dirPath);

    for (let item of items) {
        let fullPath = path.resolve(dirPath, item);
        let stats = getStats(fullPath);
        if (stats) {
            if (recursive && stats.isDirectory()) {
                getFiles(fullPath, true, pattern, files);
            } else {
                let base = path.basename(item);
                if (minimatch(base, pattern)) {
                    files.push(fullPath);
                }
            }
        }
    }

    return files;
}

function getDirectories(dirPath, recursive, dirs) {
    dirs = dirs || [];
    let items = fs.readdirSync(dirPath);

    for (let item of items) {
        let fullPath = path.resolve(dirPath, item);
        let stats = getStats(fullPath);
        if (stats) {
            if (recursive && stats.isDirectory()) {
                dirs.push(fullPath);
                getDirectories(fullPath, true, dirs);
            }
        }
    }

    return dirs;
}

function getStats(fullPath) {
    try {
        return fs.statSync(fullPath);
    } catch (err) {
        return undefined;
    }
}

class Directory extends Info {

    /**
     * @param dirPath: directory path
     * @param options.recursive: (Boolean) get files recursive or stay. default: false
     * @param options.pattern: (String) get specific files pattern. default: *.*
     * @param cb: callback
     */
    static getFiles(dirPath, options, cb) {
        let defaultOptions = {recursive: false, pattern: '*.*'};
        if (typeof options === 'function') {
            cb = options;
            options = defaultOptions;
        } else {
            options = Object.assign(defaultOptions, options);
        }
        let files = [];
        let recursive = options.recursive;
        let pattern = options.pattern;

        if (!recursive) {
            files = getFiles(dirPath, recursive, pattern);
            return cb(null, files);
        }

        walk(dirPath)
            .on('data', (item) => {
                if (!item.stats.isDirectory()) {
                    let base = path.basename(item);
                    if (minimatch(base, pattern)) {
                        files.push(item.path);
                    }
                }
            })
            .on('end', () => {
                if (cb) {
                    cb(null, files);
                }
            })
            .on('error', (err) => {
                cb(err);
            });
    }

    static getFilesSync(dirPath, recursive, pattern) {
        recursive = recursive || false;
        pattern = pattern || '*.*';

        return getFiles(dirPath, recursive, pattern);
    }

    static getDirectories(dirPath, cb) {
        let dirs = [];
        walk(dirPath)
            .on('data', (item) => {
                if (item.stats.isDirectory()) {
                    dirs.push(item.path);
                }
            })
            .on('end', () => {
                if (cb) {
                    cb(null, dirs);
                }
            })
            .on('error', (err) => {
                cb(err);
            });
    }

    static getDirectoriesSync(dirPath, recursive) {
        return getDirectories(dirPath, recursive);
    }

    static deleteContentSync(dirPath) {
        let files = Directory.getFilesSync(dirPath, false);
        let dirs = Directory.getDirectoriesSync(dirPath, false);

        let all = _.union(files, dirs);
        Info.deleteSync(all);
    }
}

module.exports = Directory;<commit_msg># fixed get directories bug<commit_after>'use strict';

const fs = require('fs');
const path = require('path');
const minimatch = require('minimatch');
const walk = require('fs-extra').walk;
const _ = require('lodash');

const Info = require('../Info');

function getFiles(dirPath, recursive, pattern, files) {
    files = files || [];
    let items = fs.readdirSync(dirPath);

    for (let item of items) {
        let fullPath = path.resolve(dirPath, item);
        let stats = getStats(fullPath);
        if (stats) {
            if (recursive && stats.isDirectory()) {
                getFiles(fullPath, true, pattern, files);
            } else {
                let base = path.basename(item);
                if (minimatch(base, pattern)) {
                    files.push(fullPath);
                }
            }
        }
    }

    return files;
}

function getDirectories(dirPath, recursive, dirs) {
    dirs = dirs || [];
    let items = fs.readdirSync(dirPath);

    for (let item of items) {
        let fullPath = path.resolve(dirPath, item);
        let stats = getStats(fullPath);
        if (stats) {
            if (stats.isDirectory()) {
                dirs.push(fullPath);
                if (recursive) {
                    getDirectories(fullPath, true, dirs);
                }
            }
        }
    }

    return dirs;
}

function getStats(fullPath) {
    try {
        return fs.statSync(fullPath);
    } catch (err) {
        return undefined;
    }
}

class Directory extends Info {

    /**
     * @param dirPath: directory path
     * @param options.recursive: (Boolean) get files recursive or stay. default: false
     * @param options.pattern: (String) get specific files pattern. default: *.*
     * @param cb: callback
     */
    static getFiles(dirPath, options, cb) {
        let defaultOptions = {recursive: false, pattern: '*.*'};
        if (typeof options === 'function') {
            cb = options;
            options = defaultOptions;
        } else {
            options = Object.assign(defaultOptions, options);
        }
        let files = [];
        let recursive = options.recursive;
        let pattern = options.pattern;

        if (!recursive) {
            files = getFiles(dirPath, recursive, pattern);
            return cb(null, files);
        }

        walk(dirPath)
            .on('data', (item) => {
                if (!item.stats.isDirectory()) {
                    let base = path.basename(item);
                    if (minimatch(base, pattern)) {
                        files.push(item.path);
                    }
                }
            })
            .on('end', () => {
                if (cb) {
                    cb(null, files);
                }
            })
            .on('error', (err) => {
                cb(err);
            });
    }

    static getFilesSync(dirPath, recursive, pattern) {
        recursive = recursive || false;
        pattern = pattern || '*.*';

        return getFiles(dirPath, recursive, pattern);
    }

    static getDirectories(dirPath, cb) {
        let dirs = [];
        walk(dirPath)
            .on('data', (item) => {
                if (item.stats.isDirectory()) {
                    dirs.push(item.path);
                }
            })
            .on('end', () => {
                if (cb) {
                    cb(null, dirs);
                }
            })
            .on('error', (err) => {
                cb(err);
            });
    }

    static getDirectoriesSync(dirPath, recursive) {
        return getDirectories(dirPath, recursive);
    }

    static deleteContentSync(dirPath) {
        let files = Directory.getFilesSync(dirPath, false);
        let dirs = Directory.getDirectoriesSync(dirPath, false);

        let all = _.union(files, dirs);
        Info.deleteSync(all);
    }
}

module.exports = Directory;<|endoftext|>


<commit_before>/**
 * Copyright (c) Ajay Sreedhar. All rights reserved.
 *
 * Licensed under the MIT License.
 * Please see LICENSE file located in the project root for more information.
 */

'use strict';

import _ from '../lib/core-utils.js';

import KongDash from './kongdash.js';

import TokenInputDirective from './components/token-input-directive.js';
import MultiCheckDirective from './components/multi-check-directive.js';

import HeaderController from './controllers/header.js';
import FooterController from './controllers/footer.js';
import SidebarController from './controllers/sidebar.js';
import OverviewController from './controllers/overview.js';
import ServiceListController from './controllers/service-list.js';
import ServiceEditController from './controllers/service-edit.js';
import RouteEditController from './controllers/route-edit.js';
import CertificateListController from './controllers/certificate-list.js';
import CertificateEditController from './controllers/certificate-edit.js';
import TrustedCAEditController from './controllers/ca-edit.js';
import UpstreamListController from './controllers/upstream-list.js';
import UpstreamEditController from './controllers/upstream-edit.js';
import ConsumerListController from './controllers/consumer-list.js';
import ConsumerEditController from './controllers/consumer-edit.js';
import PluginListController from './controllers/plugin-list.js';
import PluginEditController from './controllers/plugin-edit.js';
import SettingsController from './controllers/settings.js';

import Templates from './templates.js';
import RouteListController from './controllers/route-list.js';

const {ipcRenderer} = require('electron');

/**
 *
 * @param {RESTClientProvider} provider
 */
function initRESTClient(provider) {
    const defaultHost = ipcRenderer.sendSync('workbench:SyncQuery', 'Read-Session-Connection');

    if (_.isText(defaultHost.adminHost) && false === _.isEmpty(defaultHost.adminHost)) {
        provider.initialize({
            /* TODO : Include basic auth not provided. */
            host: `${defaultHost.protocol}://${defaultHost.adminHost}:${defaultHost.adminPort}`
        });
    }
}

/**
 * Attaches application wide event listeners.
 *
 * @param {Window} window - Top level window object.
 * @param {Object} rootScope - Angular root scope object.
 * @param {ViewFrameFactory} viewFrame - Factory for sharing UI details.
 * @param {LoggerFactory} logger - Factory for logging activities.
 */
function attachEventListeners(window, rootScope, viewFrame, logger) {
    const {angular} = window;
    const main = window.document.querySelector('main.content');

    rootScope.ngViewAnimation = 'fade';

    rootScope.$on('$locationChangeStart', (event, next) => {
        viewFrame.clearActions();
        viewFrame.resetLoader();

        if (next.indexOf('#') > 1) {
            let refArray = next.split('#!/')[1].split('/');
            let href = '#!/' + refArray[0],
                nav = angular.element('nav.navigation');

            nav.find('a.navigation__link').removeClass('active');
            nav.find('.navigation__link[data-ng-href="' + href + '"]').addClass('active');
        }
    });

    main.addEventListener('click', (event) => {
        const {target: anchor} = event;

        if (anchor.nodeName !== 'A') {
            return true;
        }

        if (anchor.target === '_blank') {
            event.preventDefault();
            ipcRenderer.send('open-external', anchor.href);

            logger.info(`Opening ${anchor.href}`);
        }

        return true;
    });
}

ipcRenderer.on('workbench:AsyncEventPush', (event, action) => {
    switch (action) {
        case 'Open-Settings-View':
            window.location.href = '#!/settings';
            break;

        default:
            break;
    }
});

KongDash.config(['restClientProvider', initRESTClient]);

KongDash.directive('tokenInput', ['$window', TokenInputDirective]);
KongDash.directive('multiCheck', ['$window', MultiCheckDirective]);

KongDash.controller('SidebarController', ['$scope', 'restClient', 'toast', SidebarController]);

KongDash.controller('HeaderController', [
    '$window',
    '$scope',
    'restClient',
    'viewFrame',
    'toast',
    'logger',
    HeaderController
]);

KongDash.controller('FooterController', [
    '$window',
    '$scope',
    '$http',
    'viewFrame',
    'toast',
    'logger',
    FooterController
]);

KongDash.controller('OverviewController', [
    '$window',
    '$scope',
    'restClient',
    'toast',
    'viewFrame',
    OverviewController
]);

KongDash.controller('ServiceListController', ['$scope', 'restClient', 'viewFrame', 'toast', ServiceListController]);

KongDash.controller('ServiceEditController', [
    '$window',
    '$scope',
    '$location',
    '$routeParams',
    'restClient',
    'viewFrame',
    'toast',
    'logger',
    ServiceEditController
]);

KongDash.controller('RouteListController', ['$scope', 'restClient', 'viewFrame', 'toast', RouteListController]);

KongDash.controller('RouteEditController', [
    '$window',
    '$scope',
    '$location',
    '$routeParams',
    'restClient',
    'viewFrame',
    'toast',
    'logger',
    RouteEditController
]);

KongDash.controller('CertificateListController', [
    '$scope',
    'restClient',
    'viewFrame',
    'toast',
    CertificateListController
]);

KongDash.controller('CertificateEditController', [
    '$window',
    '$scope',
    '$location',
    '$routeParams',
    'restClient',
    'viewFrame',
    'toast',
    CertificateEditController
]);

KongDash.controller('TrustedCAEditController', [
    '$window',
    '$scope',
    '$location',
    '$routeParams',
    'restClient',
    'viewFrame',
    'toast',
    'logger',
    TrustedCAEditController
]);

KongDash.controller('UpstreamListController', ['$scope', 'restClient', 'viewFrame', 'toast', UpstreamListController]);

KongDash.controller('UpstreamEditController', [
    '$window',
    '$scope',
    '$location',
    '$routeParams',
    'restClient',
    'viewFrame',
    'toast',
    UpstreamEditController
]);

KongDash.controller('ConsumerListController', ['$scope', 'restClient', 'viewFrame', 'toast', ConsumerListController]);

KongDash.controller('ConsumerEditController', [
    '$window',
    '$scope',
    '$location',
    '$routeParams',
    'restClient',
    'viewFrame',
    'toast',
    'logger',
    ConsumerEditController
]);

KongDash.controller('PluginListController', ['$scope', 'restClient', 'viewFrame', 'toast', PluginListController]);

KongDash.controller('PluginEditController', [
    '$window',
    '$scope',
    '$location',
    '$routeParams',
    'restClient',
    'viewFrame',
    'toast',
    PluginEditController
]);

KongDash.controller('SettingsController', [
    '$window',
    '$rootScope',
    '$scope',
    'restClient',
    'viewFrame',
    'toast',
    SettingsController
]);

KongDash.config(['$routeProvider', Templates]);

KongDash.run(['$window', '$rootScope', 'viewFrame', 'logger', attachEventListeners]);
<commit_msg>remove: Nav event listener<commit_after>/**
 * Copyright (c) Ajay Sreedhar. All rights reserved.
 *
 * Licensed under the MIT License.
 * Please see LICENSE file located in the project root for more information.
 */

'use strict';

import _ from '../lib/core-utils.js';

import KongDash from './kongdash.js';

import TokenInputDirective from './components/token-input-directive.js';
import MultiCheckDirective from './components/multi-check-directive.js';

import HeaderController from './controllers/header.js';
import FooterController from './controllers/footer.js';
import SidebarController from './controllers/sidebar.js';
import OverviewController from './controllers/overview.js';
import ServiceListController from './controllers/service-list.js';
import ServiceEditController from './controllers/service-edit.js';
import RouteEditController from './controllers/route-edit.js';
import CertificateListController from './controllers/certificate-list.js';
import CertificateEditController from './controllers/certificate-edit.js';
import TrustedCAEditController from './controllers/ca-edit.js';
import UpstreamListController from './controllers/upstream-list.js';
import UpstreamEditController from './controllers/upstream-edit.js';
import ConsumerListController from './controllers/consumer-list.js';
import ConsumerEditController from './controllers/consumer-edit.js';
import PluginListController from './controllers/plugin-list.js';
import PluginEditController from './controllers/plugin-edit.js';
import SettingsController from './controllers/settings.js';

import Templates from './templates.js';
import RouteListController from './controllers/route-list.js';

const {ipcRenderer} = require('electron');

/**
 *
 * @param {RESTClientProvider} provider
 */
function initRESTClient(provider) {
    const defaultHost = ipcRenderer.sendSync('workbench:SyncQuery', 'Read-Session-Connection');

    if (_.isText(defaultHost.adminHost) && false === _.isEmpty(defaultHost.adminHost)) {
        provider.initialize({
            /* TODO : Include basic auth not provided. */
            host: `${defaultHost.protocol}://${defaultHost.adminHost}:${defaultHost.adminPort}`
        });
    }
}

/**
 * Attaches application wide event listeners.
 *
 * @param {Window} window - Top level window object.
 * @param {Object} rootScope - Angular root scope object.
 * @param {ViewFrameFactory} viewFrame - Factory for sharing UI details.
 * @param {LoggerFactory} logger - Factory for logging activities.
 */
function attachEventListeners(window, rootScope, viewFrame, logger) {
    const main = window.document.querySelector('main.content');

    rootScope.ngViewAnimation = 'fade';

    rootScope.$on('$locationChangeStart', () => {
        viewFrame.clearActions();
        viewFrame.resetLoader();
    });

    main.addEventListener('click', (event) => {
        const {target: anchor} = event;

        if (anchor.nodeName !== 'A') {
            return true;
        }

        if (anchor.target === '_blank') {
            event.preventDefault();
            ipcRenderer.send('open-external', anchor.href);

            logger.info(`Opening ${anchor.href}`);
        }

        return true;
    });
}

ipcRenderer.on('workbench:AsyncEventPush', (event, action) => {
    switch (action) {
        case 'Open-Settings-View':
            window.location.href = '#!/settings';
            break;

        default:
            break;
    }
});

KongDash.config(['restClientProvider', initRESTClient]);

KongDash.directive('tokenInput', ['$window', TokenInputDirective]);
KongDash.directive('multiCheck', ['$window', MultiCheckDirective]);

KongDash.controller('SidebarController', ['$scope', 'restClient', 'toast', SidebarController]);

KongDash.controller('HeaderController', [
    '$window',
    '$scope',
    'restClient',
    'viewFrame',
    'toast',
    'logger',
    HeaderController
]);

KongDash.controller('FooterController', [
    '$window',
    '$scope',
    '$http',
    'viewFrame',
    'toast',
    'logger',
    FooterController
]);

KongDash.controller('OverviewController', [
    '$window',
    '$scope',
    'restClient',
    'toast',
    'viewFrame',
    OverviewController
]);

KongDash.controller('ServiceListController', ['$scope', 'restClient', 'viewFrame', 'toast', ServiceListController]);

KongDash.controller('ServiceEditController', [
    '$window',
    '$scope',
    '$location',
    '$routeParams',
    'restClient',
    'viewFrame',
    'toast',
    'logger',
    ServiceEditController
]);

KongDash.controller('RouteListController', ['$scope', 'restClient', 'viewFrame', 'toast', RouteListController]);

KongDash.controller('RouteEditController', [
    '$window',
    '$scope',
    '$location',
    '$routeParams',
    'restClient',
    'viewFrame',
    'toast',
    'logger',
    RouteEditController
]);

KongDash.controller('CertificateListController', [
    '$scope',
    'restClient',
    'viewFrame',
    'toast',
    CertificateListController
]);

KongDash.controller('CertificateEditController', [
    '$window',
    '$scope',
    '$location',
    '$routeParams',
    'restClient',
    'viewFrame',
    'toast',
    CertificateEditController
]);

KongDash.controller('TrustedCAEditController', [
    '$window',
    '$scope',
    '$location',
    '$routeParams',
    'restClient',
    'viewFrame',
    'toast',
    'logger',
    TrustedCAEditController
]);

KongDash.controller('UpstreamListController', ['$scope', 'restClient', 'viewFrame', 'toast', UpstreamListController]);

KongDash.controller('UpstreamEditController', [
    '$window',
    '$scope',
    '$location',
    '$routeParams',
    'restClient',
    'viewFrame',
    'toast',
    UpstreamEditController
]);

KongDash.controller('ConsumerListController', ['$scope', 'restClient', 'viewFrame', 'toast', ConsumerListController]);

KongDash.controller('ConsumerEditController', [
    '$window',
    '$scope',
    '$location',
    '$routeParams',
    'restClient',
    'viewFrame',
    'toast',
    'logger',
    ConsumerEditController
]);

KongDash.controller('PluginListController', ['$scope', 'restClient', 'viewFrame', 'toast', PluginListController]);

KongDash.controller('PluginEditController', [
    '$window',
    '$scope',
    '$location',
    '$routeParams',
    'restClient',
    'viewFrame',
    'toast',
    PluginEditController
]);

KongDash.controller('SettingsController', [
    '$window',
    '$rootScope',
    '$scope',
    'restClient',
    'viewFrame',
    'toast',
    SettingsController
]);

KongDash.config(['$routeProvider', Templates]);

KongDash.run(['$window', '$rootScope', 'viewFrame', 'logger', attachEventListeners]);
<|endoftext|>


<commit_before>Www.Router = Ember.Router.extend({
  root: Ember.State.extend({
    index: Ember.State.extend({
      route: '/',
      redirectsTo: 'home'
    }),
    home: Ember.State.extend({
      route: '/home'
    }),
    quest: Ember.State.extend({
      route: '/quests'

      plan: Ember.State.extend({
        route: '/plan'
      })
    })
  })
});
<commit_msg>Fixed syntax typo<commit_after>Www.Router = Ember.Router.extend({
  root: Ember.Route.extend({
    index: Ember.Route.extend({
      route: '/',
      redirectsTo: 'home'
    }),
    home: Ember.Route.extend({
      route: '/home'
    }),
    quest: Ember.Route.extend({
      route: '/quests',

      plan: Ember.Route.extend({
        route: '/plan'
      })
    })
  })
});
<|endoftext|>


<commit_before>
var express = require('../')
  , request = require('./support/http');

describe('req', function(){
  describe('.signedCookies', function(){
    it('should return a signed JSON cookie', function(done){
      var app = express()
        , cookieHeader
        , val;

      app.use(express.cookieParser('secret'));

      app.use(function(req, res){
        res.send(req.signedCookies);
      });

      app.response.req = { secret: 'secret' };
      app.response.cookie('obj', { foo: 'bar' }, { signed: true });
      cookieHeader = app.response.get('set-cookie');

      val = JSON.stringify({ obj: { foo: 'bar' } });
      request(app)
      .get('/')
      .set('Cookie', cookieHeader)
      .expect(val, done);
    })

    it('should return a signed cookie', function(done){
      var app = express()
        , cookieHeader
        , val;

      app.use(express.cookieParser('secret'));

      app.use(function(req, res){
        res.send(req.signedCookies);
      });

      app.response.req = { secret: 'secret' };
      app.response.cookie('foo', 'bar', { signed: true });
      cookieHeader = app.response.get('set-cookie');

      val = JSON.stringify({ foo: 'bar' });
      request(app)
      .get('/')
      .set('Cookie', cookieHeader)
      .expect(val, done);
    })
  })
})

<commit_msg>See comments.<commit_after>
var express = require('../')
  , request = require('./support/http');

describe('req', function(){
  describe('.signedCookies', function(){
    it('should return a signed JSON cookie', function(done){
      var app = express()
        , cookieHeader
        , val;

      /* So we use the same serialization for expected results. */
      var replacer = app.get('json replacer')
        , spaces = app.get('json spaces');

      app.use(express.cookieParser('secret'));

      app.use(function(req, res){
        res.send(req.signedCookies);
      });

      app.response.req = { secret: 'secret' };
      app.response.cookie('obj', { foo: 'bar' }, { signed: true });
      cookieHeader = app.response.get('set-cookie');

      val = JSON.stringify({ obj: { foo: 'bar' } }, replacer, spaces);
      request(app)
      .get('/')
      .set('Cookie', cookieHeader)
      .expect(val, done);
    })

    it('should return a signed cookie', function(done){
      var app = express()
        , cookieHeader
        , val;

      /* So we use the same serialization for expected results. */
      var replacer = app.get('json replacer')
        , spaces = app.get('json spaces');

      app.use(express.cookieParser('secret'));

      app.use(function(req, res){
        res.send(req.signedCookies);
      });

      app.response.req = { secret: 'secret' };
      app.response.cookie('foo', 'bar', { signed: true });
      cookieHeader = app.response.get('set-cookie');

      val = JSON.stringify({ foo: 'bar' }, replacer, spaces);
      request(app)
      .get('/')
      .set('Cookie', cookieHeader)
      .expect(val, done);
    })
  })
})

<|endoftext|>


<commit_before>var test = require("tap").test,
    request = require("supertest");

var mockEmail = "test@example.org",
    mockSession = require("./mock.session"),
    mockProject = require("./mock.project")(),
    mockFilter = require("./mock.filter"),
    mockSanitizer = require("./mock.sanitizer"),
    mockStore = require("./mock.store"),
    utils = require("../lib/utils")({
      EMBED_HOSTNAME: "http://localhost:8888",
      EMBED_SUFFIX: "_"
    }, mockStore);

var express = require("express");
var app = express();

app.use(mockSession({
  email: mockEmail,
  _csrf: "FDaS435D2z"
}))
.use(express.bodyParser());

require("../routes")(app, mockProject, mockFilter, mockSanitizer, mockStore, utils);

app = app.listen(0);

test("whoami API valid", function(t) {
  request(app)
    .get("/api/whoami")
    .end(function(err, res) {
      t.equal(res.statusCode, 200, "status code is 200");
      t.equal(res.type, "application/json", "response type is json");
      t.deepEqual(res.body, {
        status: "okay",
        email: mockEmail,
        name: mockEmail,
        username: mockEmail,
        csrf: "FDaS435D2z"
      }, "response should have 5 attributes");

      t.end();
    });
});

test("project data get with error", function(t) {
  mockProject.error = true;
  mockProject.doc = false;

  request(app)
    .get("/api/project/1234")
    .end(function(err, res) {
      t.equal(res.statusCode, 500, "status code is 500");
      t.equal(res.type, "application/json", "response type is json");
      t.ok(res.body.error, "json contains an error");

      t.end();
    });
});

test("project data get not found", function(t) {
  mockProject.error = false;
  mockProject.doc = false;

  request(app)
    .get("/api/project/1234")
    .end(function(err, res) {
      t.equal(res.statusCode, 404, "status code is 404");
      t.equal(res.type, "application/json", "response type is json");
      t.ok(res.body.error, "json contains an error");

      t.end();
    });
});

test("project data get valid", function(t) {
  mockProject.error = false;
  mockProject.doc = true;

  request(app)
    .get("/api/project/1234")
    .end(function(err, res) {
      t.equal(res.statusCode, 200, "status code is 200");
      t.equal(res.type, "application/json", "response type is json");

      // This is very obtuse...
      var mockData = mockProject.generateMockData(1234);
      mockData.data = JSON.parse(mockData.data);
      mockData.data.name = mockData.name;
      mockData.data.projectID = mockData.id;
      mockData.data.author = mockData.author;
      mockData.data.template = mockData.template;
      mockData.data.publishUrl = mockData.publishUrl;
      mockData.data.iframeUrl = mockData.iframeUrl;
      mockData = mockData.data;
      t.deepEqual(res.body, mockData, "saved data is equal");

      t.end();
    });
});

test("delete project not found", function(t) {
  mockProject.error = true;

  request(app)
    .post("/api/delete/1234")
    .end(function(err, res) {
      t.equal(res.statusCode, 404, "status code is 404");
      t.equal(res.type, "application/json", "response type is json");
      t.ok(res.body.error, "json contains an error");

      t.end();
    });
});

test("delete project found", function(t) {
  mockProject.error = false;

  request(app)
    .post("/api/delete/1234")
    .end(function(err, res) {
      t.equal(res.statusCode, 200, "status code is 200");
      t.equal(res.type, "application/json", "response type is json");
      // wtf was I think when returning error is a good thing?
      t.equal(res.body.error, "okay", "json returns okay");

      t.end();
    });
});

/*******************
 * DANGER ZONE     *
 * HERE BE DRAGONS *
 *******************/

test("create project with error", function(t) {
  mockProject.error = true;

  var mockData = mockProject.generateMockData(1234);
  delete mockData.id;

  request(app)
    .post("/api/project/1234")
    .send(mockData)
    .end(function(err, res) {
      t.equal(res.statusCode, 500, "status code is 500");
      t.equal(res.type, "application/json", "response type is json");
      t.equal(res.body.error, "mock error", "error message is correct");

      t.end();
    });
});

test("create project with no data", function(t) {
  mockProject.error = false;

  var mockData = mockProject.generateMockData(1234);
  delete mockData.id;
  delete mockData.data;

  request(app)
    .post("/api/project/1234")
    .send(mockData)
    .end(function(err, res) {
      t.equal(res.statusCode, 500, "status code is 500");
      t.equal(res.type, "application/json", "response type is json");
      t.equal(res.body.error, "not enough parameters to update", "error message is correct");

      t.end();
    });
});

test("create project valid", function(t) {
  mockProject.error = false;

  var mockData = mockProject.generateMockData();
  mockData.data = JSON.parse(mockData.data);
  delete mockData.id;

  request(app)
    .post("/api/project/1234")
    .send(mockData)
    .end(function(err, res) {
      t.equal(res.statusCode, 200, "status code is 200");
      t.equal(res.type, "application/json", "response type is json");
      t.equal(res.body.error, "okay", "status is okay");
      t.ok(res.body.projectId, "id is present");

      t.end();
    });
});

test("update project with error", function(t) {
  mockProject.error = true;
  mockProject.doc = true;

  var mockData = mockProject.generateMockData(1234);
  mockData.data = JSON.parse(mockData.data);
  mockData.id = mockData.id;

  request(app)
    .post("/api/project/1234")
    .send(mockData)
    .end(function(err, res) {
      t.equal(res.statusCode, 500, "status code is 500");
      t.equal(res.type, "application/json", "response type is json");
      t.ok(res.body.error, "mock error");

      t.end();
    });
});

test("update project with no matching id", function(t) {
  mockProject.error = false;
  mockProject.doc = false;

  var mockData = mockProject.generateMockData(1234);
  mockData.data = JSON.parse(mockData.data);
  mockData.id = mockData.id;

  request(app)
    .post("/api/project/1234")
    .send(mockData)
    .end(function(err, res) {
      t.equal(res.statusCode, 500, "status code is 500");
      t.equal(res.type, "application/json", "response type is json");
      t.ok(res.body.error, "project id not found");

      t.end();
    });
});

test("update project valid", function(t) {
  mockProject.error = false;
  mockProject.doc = true;

  var mockData = mockProject.generateMockData(1234);
  mockData.data = JSON.parse(mockData.data);
  mockData.id = mockData.id;

  request(app)
    .post("/api/project/1234")
    .send(mockData)
    .end(function(err, res) {
      t.equal(res.statusCode, 200, "status code is 200");
      t.equal(res.type, "application/json", "response type is json");
      t.equal(res.body.error, "okay", "status is okay");
      mockData.data = JSON.stringify(mockData.data);
      t.deepEqual(res.body.project, mockData, "saved data is equal");

      t.end();
    });
});

test("remix project with error", function(t) {
  mockProject.error = true;
  mockProject.doc = false;

  request(app)
    .get("/api/remix/1234")
    .end(function(err, res) {
      t.equal(res.statusCode, 500, "status code is 500");
      t.equal(res.type, "application/json", "response type is json");
      t.ok(res.body.error, "json contains an error");

      t.end();
    });
});

test("remix project with no doc", function(t) {
  mockProject.error = false;
  mockProject.doc = false;

  request(app)
    .get("/api/remix/1234")
    .end(function(err, res) {
      t.equal(res.statusCode, 404, "status code is 404");
      t.equal(res.type, "application/json", "response type is json");
      t.ok(res.body.error, "json contains an error");

      t.end();
    });
});

test("remix project valid", function(t) {
  mockProject.error = false;
  mockProject.doc = true;

  request(app)
    .get("/api/remix/1234")
    .end(function(err, res) {
      t.equal(res.statusCode, 200, "status code is 200");
      t.equal(res.type, "application/json", "response type is json");

      // This is very obtuse...
      var mockData = mockProject.generateMockData(1234);
      mockData.data = JSON.parse(mockData.data);
      mockData.data.name = "Remix of " + mockData.name;
      mockData.data.template = "basic";
      mockData.data.remixedFrom = mockData.id;
      mockData = mockData.data;
      t.deepEqual(res.body, mockData, "saved data is equal");

      t.end();
    });
});

test("clean up server connections", function(t) {
  app.close();
  t.end();
});
<commit_msg>Bug873144 - Fix Failing Cornfield test<commit_after>var test = require("tap").test,
    request = require("supertest");

var mockEmail = "test@example.org",
    mockSession = require("./mock.session"),
    mockProject = require("./mock.project")(),
    mockFilter = require("./mock.filter"),
    mockSanitizer = require("./mock.sanitizer"),
    mockStore = require("./mock.store"),
    utils = require("../lib/utils")({
      EMBED_HOSTNAME: "http://localhost:8888",
      EMBED_SUFFIX: "_"
    }, mockStore);

var express = require("express");
var app = express();

app.use(mockSession({
  email: mockEmail,
  _csrf: "FDaS435D2z"
}))
.use(express.bodyParser());

require("../routes")(app, mockProject, mockFilter, mockSanitizer, mockStore, utils);

app = app.listen(0);

test("whoami API valid", function(t) {
  request(app)
    .get("/api/whoami")
    .end(function(err, res) {
      t.equal(res.statusCode, 200, "status code is 200");
      t.equal(res.type, "application/json", "response type is json");
      t.deepEqual(res.body, {
        status: "okay",
        email: mockEmail,
        name: mockEmail,
        username: mockEmail,
        csrf: "FDaS435D2z"
      }, "response should have 5 attributes");

      t.end();
    });
});

test("project data get with error", function(t) {
  mockProject.error = true;
  mockProject.doc = false;

  request(app)
    .get("/api/project/1234")
    .end(function(err, res) {
      t.equal(res.statusCode, 500, "status code is 500");
      t.equal(res.type, "application/json", "response type is json");
      t.ok(res.body.error, "json contains an error");

      t.end();
    });
});

test("project data get not found", function(t) {
  mockProject.error = false;
  mockProject.doc = false;

  request(app)
    .get("/api/project/1234")
    .end(function(err, res) {
      t.equal(res.statusCode, 404, "status code is 404");
      t.equal(res.type, "application/json", "response type is json");
      t.ok(res.body.error, "json contains an error");

      t.end();
    });
});

test("project data get valid", function(t) {
  mockProject.error = false;
  mockProject.doc = true;

  request(app)
    .get("/api/project/1234")
    .end(function(err, res) {
      t.equal(res.statusCode, 200, "status code is 200");
      t.equal(res.type, "application/json", "response type is json");

      // This is very obtuse...
      var mockData = mockProject.generateMockData(1234);
      mockData.data = JSON.parse(mockData.data);
      mockData.data.name = mockData.name;
      mockData.data.projectID = mockData.id;
      mockData.data.author = mockData.author;
      mockData.data.template = mockData.template;
      mockData.data.publishUrl = mockData.publishUrl;
      mockData.data.iframeUrl = mockData.iframeUrl;
      mockData = mockData.data;
      t.deepEqual(res.body, mockData, "saved data is equal");

      t.end();
    });
});

test("delete project not found", function(t) {
  mockProject.error = true;

  request(app)
    .post("/api/delete/1234")
    .end(function(err, res) {
      t.equal(res.statusCode, 404, "status code is 404");
      t.equal(res.type, "application/json", "response type is json");
      t.ok(res.body.error, "json contains an error");

      t.end();
    });
});

test("delete project found", function(t) {
  mockProject.error = false;

  request(app)
    .post("/api/delete/1234")
    .end(function(err, res) {
      t.equal(res.statusCode, 200, "status code is 200");
      t.equal(res.type, "application/json", "response type is json");
      // wtf was I think when returning error is a good thing?
      t.equal(res.body.error, "okay", "json returns okay");

      t.end();
    });
});

/*******************
 * DANGER ZONE     *
 * HERE BE DRAGONS *
 *******************/

test("create project with error", function(t) {
  mockProject.error = true;

  var mockData = mockProject.generateMockData(1234);
  delete mockData.id;

  request(app)
    .post("/api/project/1234")
    .send(mockData)
    .end(function(err, res) {
      t.equal(res.statusCode, 500, "status code is 500");
      t.equal(res.type, "application/json", "response type is json");
      t.equal(res.body.error, "mock error", "error message is correct");

      t.end();
    });
});

test("create project with no data", function(t) {
  mockProject.error = false;

  var mockData = mockProject.generateMockData(1234);
  delete mockData.id;
  delete mockData.data;

  request(app)
    .post("/api/project/1234")
    .send(mockData)
    .end(function(err, res) {
      t.equal(res.statusCode, 500, "status code is 500");
      t.equal(res.type, "application/json", "response type is json");
      t.equal(res.body.error, "not enough parameters to update", "error message is correct");

      t.end();
    });
});

test("create project valid", function(t) {
  mockProject.error = false;

  var mockData = mockProject.generateMockData();
  mockData.data = JSON.parse(mockData.data);
  delete mockData.id;

  request(app)
    .post("/api/project/1234")
    .send(mockData)
    .end(function(err, res) {
      t.equal(res.statusCode, 200, "status code is 200");
      t.equal(res.type, "application/json", "response type is json");
      t.equal(res.body.error, "okay", "status is okay");
      t.ok(res.body.projectId, "id is present");

      t.end();
    });
});

test("update project with error", function(t) {
  mockProject.error = true;
  mockProject.doc = true;

  var mockData = mockProject.generateMockData(1234);
  mockData.data = JSON.parse(mockData.data);
  mockData.id = mockData.id;

  request(app)
    .post("/api/project/1234")
    .send(mockData)
    .end(function(err, res) {
      t.equal(res.statusCode, 500, "status code is 500");
      t.equal(res.type, "application/json", "response type is json");
      t.ok(res.body.error, "mock error");

      t.end();
    });
});

test("update project with no matching id", function(t) {
  mockProject.error = false;
  mockProject.doc = false;

  var mockData = mockProject.generateMockData(1234);
  mockData.data = JSON.parse(mockData.data);
  mockData.id = mockData.id;

  request(app)
    .post("/api/project/1234")
    .send(mockData)
    .end(function(err, res) {
      t.equal(res.statusCode, 500, "status code is 500");
      t.equal(res.type, "application/json", "response type is json");
      t.ok(res.body.error, "project id not found");

      t.end();
    });
});

test("update project valid", function(t) {
  mockProject.error = false;
  mockProject.doc = true;

  var mockData = mockProject.generateMockData(1234);
  mockData.data = JSON.parse(mockData.data);
  mockData.id = mockData.id;

  request(app)
    .post("/api/project/1234")
    .send(mockData)
    .end(function(err, res) {
      t.equal(res.statusCode, 200, "status code is 200");
      t.equal(res.type, "application/json", "response type is json");
      t.equal(res.body.error, "okay", "status is okay");
      mockData.data = JSON.stringify(mockData.data);
      t.deepEqual(res.body.project, mockData, "saved data is equal");

      t.end();
    });
});

test("remix project with error", function(t) {
  mockProject.error = true;
  mockProject.doc = false;

  request(app)
    .get("/api/remix/1234")
    .end(function(err, res) {
      t.equal(res.statusCode, 500, "status code is 500");
      t.equal(res.type, "application/json", "response type is json");
      t.ok(res.body.error, "json contains an error");

      t.end();
    });
});

test("remix project with no doc", function(t) {
  mockProject.error = false;
  mockProject.doc = false;

  request(app)
    .get("/api/remix/1234")
    .end(function(err, res) {
      t.equal(res.statusCode, 404, "status code is 404");
      t.equal(res.type, "application/json", "response type is json");
      t.ok(res.body.error, "json contains an error");

      t.end();
    });
});

test("remix project valid", function(t) {
  mockProject.error = false;
  mockProject.doc = true;

  request(app)
    .get("/api/remix/1234")
    .end(function(err, res) {
      t.equal(res.statusCode, 200, "status code is 200");
      t.equal(res.type, "application/json", "response type is json");

      // This is very obtuse...
      var mockData = mockProject.generateMockData(1234);
      mockData.data = JSON.parse(mockData.data);
      mockData.data.name = "Remix of " + mockData.name;
      mockData.data.template = "basic";
      mockData.data.remixedFrom = mockData.id;
      mockData.data.remixedFromUrl = "http://localhost:8888/v/1234.html";
      mockData = mockData.data;
      t.deepEqual(res.body, mockData, "saved data is equal");

      t.end();
    });
});

test("clean up server connections", function(t) {
  app.close();
  t.end();
});
<|endoftext|>


<commit_before>require('../node_modules/enginemill/enginemill');

describe("save_html5_widget", function () {
    var save_html5_widget = require("../business/save_html5_widget")

    describe("parseWidget()", function () {

        it("should return a data struct", function () {
            save_html5_widget.parseWidget();
            (true).should.be.true;
            return;
        });

        return; // parseWidget()
    });

    return; // save_html5_widget
});
<commit_msg>define data struct for parseWidget()<commit_after>require('../node_modules/enginemill/enginemill');

describe("save_html5_widget", function () {
    var save_html5_widget = require("../business/save_html5_widget")

    describe("parseWidget()", function () {

        it("should return a data struct", function () {
            var struct = save_html5_widget.parseWidget();

            struct.id.should.be.a('string');
            struct.name.should.be.a('string');
            struct.owner.should.be.a('string');
            struct.filename.should.be.a('string');
            struct.height.should.be.a('number');
            struct.width.should.be.a('number');
            struct.mainHTML.should.be.a('string');

            struct.zip.extractAllTo.should.be.a('function');
            struct.zip.getEntries.should.be.a('function');
            struct.zip.getEntries().should.be.an.instanceOf(Array);
            return;
        });

        return; // parseWidget()
    });

    return; // save_html5_widget
});
<|endoftext|>


<commit_before>jQuery(document).ready(function($){

    $.getJSON('/index.php/rssnotifier/default/getJson', function(data){

        $.tmpl('

${title}

${content} ${link}

', data).appendTo('#rssNotifierItems');

        $("#rssNotifierItems a.rssNotifierLink").each(function(){
            $("#rssNotifierItems a").attr('href', $(this).text());
            $(this).html("Lire la suite...");
        });

    var sliderWidth = $("#rssNotifier").width();
    var elementWidth = sliderWidth;
    var nbElement = 5; //$("#rssNotifierItems li a").size();
    var imageReelWidth = elementWidth * nbElement;

    $('#rssNotifier').append('

1

2

3

4

5

');
    $('#rssNotifierItems').css('width', imageReelWidth);
    $('#rssNotifierItems li').css('width', elementWidth-20);

    // Rotation
    rotate = function (){
        var triggerID = $active.attr("rel") - 1; //Get number of times to slide
        var next_pos = triggerID * elementWidth; //Determines the distance the image reel needs to slide

        $("#rssNotifierSteps a").removeClass('active'); //Remove all active class
        $active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)

        //Slider Animation
        $("#rssNotifierItems").animate({
            left: -next_pos
        }, 500 );
    };

    //Rotation + Timing Event
    rotateSwitch = function(){
        play = setInterval(function(){ //Set timer - this will repeat itself every 3 seconds
            $active = $('#rssNotifierSteps a.active').parent('li').next().children();
            if ( $active.length === 0) { //If paging reaches the end...
                $active = $('#rssNotifierSteps a:first'); //go back to first
            }
            rotate(); //Trigger the paging and slider function
        }, 9000); //Timer speed in milliseconds
    };

    rotateSwitch(); //Run function on launch

    //On Hover
    $("#rssNotifier").hover(function() {
        clearInterval(play); //Stop the rotation
    }, function() {
        rotateSwitch(); //Resume rotation
    });

    //On Click
    $('#rssNotifierSteps a').click(function(){
        $active = $(this); //Activate the clicked paging
        //Reset Timer
        clearInterval(play); //Stop the rotation
        rotate(); //Trigger rotation immediately
        rotateSwitch(); // Resume rotation
        return false;
    });
});

});<commit_msg>RSS Notifier : gestion des cas à la noix, on revient à une méthode classique hein Arnaud...<commit_after>jQuery(document).ready(function($){

    $.getJSON('/index.php/rssnotifier/default/getJson', function(datas){

	var items = '';
	var buttons = '';
	var i = 1;

	$.each(datas, function(index,data) {
		items += '

'+data.title+'

'+data.content+' Lire la suite...

';
		buttons += '
'+i+'
';
		i++;
	});

	$('#rssNotifierItems').append(items);
	$('#rssNotifier').append('
'+buttons+'
');

    var sliderWidth = $("#rssNotifier").width();
    var elementWidth = sliderWidth;
    var nbElement = datas.length;
    var imageReelWidth = elementWidth * nbElement;

    $('#rssNotifierSteps li a:first').addClass('active');
    $('#rssNotifierItems').css('width', imageReelWidth);
    $('#rssNotifierItems li').css('width', elementWidth-20);

    // Rotation
    rotate = function (){
        var triggerID = $active.attr("rel") - 1; //Get number of times to slide
        var next_pos = triggerID * elementWidth; //Determines the distance the image reel needs to slide

        $("#rssNotifierSteps a").removeClass('active'); //Remove all active class
        $active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)

        //Slider Animation
        $("#rssNotifierItems").animate({
            left: -next_pos
        }, 500 );
    };

    //Rotation + Timing Event
    rotateSwitch = function(){
        play = setInterval(function(){ //Set timer - this will repeat itself every 3 seconds
            $active = $('#rssNotifierSteps a.active').parent('li').next().children();
            if ( $active.length === 0) { //If paging reaches the end...
                $active = $('#rssNotifierSteps a:first'); //go back to first
            }
            rotate(); //Trigger the paging and slider function
        }, 9000); //Timer speed in milliseconds
    };

    rotateSwitch(); //Run function on launch

    //On Hover
    $("#rssNotifier").hover(function() {
        clearInterval(play); //Stop the rotation
    }, function() {
        rotateSwitch(); //Resume rotation
    });

    //On Click
    $('#rssNotifierSteps a').click(function(){
        $active = $(this); //Activate the clicked paging
        //Reset Timer
        clearInterval(play); //Stop the rotation
        rotate(); //Trigger rotation immediately
        rotateSwitch(); // Resume rotation
        return false;
    });
});

});<|endoftext|>


<commit_before>import React, {Component} from "react";
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import Button from 'material-ui/Button';

const styles = theme => ({
  margin: theme.spacing.unit,
});

const buttonData = [
  {"key": 1, "hrefs":"https://www.linkedin.com/in/gregory-katchmar-3a48275a", "labels": "LinkedIn"},
  {"key": 2, "hrefs":"https://github.com/gnkatchmar", "labels": "Github"},
  {"key": 3, "hrefs":"https://drive.google.com/open?id=1CJxw4DKh_pf7Oi9t-StYHDTvVF6dT2_t", "labels": "Resume (PDF)"},
];

const buttons = buttonData.map((buttonData) =>

  <Button
    variant="raised"
    key={buttonData.key}
    href={buttonData.hrefs}
    target="_blank"
    color="primary"
    style={styles.button}
    children={buttonData.labels}
  />

);

class Home extends Component {
  render() {
    return (

Gregory N. Katchmar

JavaScript Developer

More information at:

        {buttons}

        <Button
        variant="raised"
        color="primary"
        href="https://gnkatchmar.github.io/brunch-finder/"
        target="_blank"
        rel="noopener noreferrer"
        children="Launch Portland Weekend Brunch Finder 2.0"
      />

Contact me at:

        gregkatchmar@gmail.com

A React/Material-UI site

Last updated: Jun3 16, 2018

    );
  }
}

Home.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(Home);<commit_msg>correction<commit_after>import React, {Component} from "react";
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import Button from 'material-ui/Button';

const styles = theme => ({
  margin: theme.spacing.unit,
});

const buttonData = [
  {"key": 1, "hrefs":"https://www.linkedin.com/in/gregory-katchmar-3a48275a", "labels": "LinkedIn"},
  {"key": 2, "hrefs":"https://github.com/gnkatchmar", "labels": "Github"},
  {"key": 3, "hrefs":"https://drive.google.com/open?id=1CJxw4DKh_pf7Oi9t-StYHDTvVF6dT2_t", "labels": "Resume (PDF)"},
];

const buttons = buttonData.map((buttonData) =>

  <Button
    variant="raised"
    key={buttonData.key}
    href={buttonData.hrefs}
    target="_blank"
    color="primary"
    style={styles.button}
    children={buttonData.labels}
  />

);

class Home extends Component {
  render() {
    return (

Gregory N. Katchmar

JavaScript Developer

More information at:

        {buttons}

        <Button
        variant="raised"
        color="primary"
        href="https://gnkatchmar.github.io/brunch-finder/"
        target="_blank"
        rel="noopener noreferrer"
        children="Launch Portland Weekend Brunch Finder 2.0"
      />

Contact me at:

        gregkatchmar@gmail.com

A React/Material-UI site

Last updated: June 16, 2018

    );
  }
}

Home.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(Home);<|endoftext|>


<commit_before>
angular.module('cesium.currency.services', ['ngApi', 'cesium.bma.services'])

.factory('csCurrency', function($rootScope, $q, $timeout, BMA, Api, csSettings) {
  'ngInject';

  function factory(id, BMA) {
    var
      constants = {
        // Avoid to many call on well known currencies
        WELL_KNOWN_CURRENCIES: {
          g1: {
            firstBlockTime: 1488987127,
            medianTimeOffset: 3600
          }
        }
      },

      data = {},
      started = false,
      startPromise,
      listeners,
      api = new Api(this, "csCurrency-" + id);

    function powBase(amount, base) {
      return base <= 0 ? amount : amount * Math.pow(10, base);
    }

    function resetData() {
      data.name = null;
      data.parameters = null;
      data.firstBlockTime = null;
      data.membersCount = null;
      data.cache = {};
      data.node = BMA;
      data.currentUD = null;
      data.medianTimeOffset = 0;
      started = false;
      startPromise = undefined;
      api.data.raise.reset(data);
    }

    function loadData() {

      // Load currency from default node
      return $q.all([

        // get parameters
        loadParameters()
          .then(function(parameters) {
            // load first block info
            return loadFirstBlock(parameters.currency);
          }),

        // get current UD
        loadCurrentUD(),

        // call extensions
        api.data.raisePromise.load(data)
      ])
      .catch(function(err) {
        resetData();
        throw err;
      });
    }

    function loadParameters() {
      return BMA.blockchain.parameters()
        .then(function(res){
          data.name = res.currency;
          data.parameters = res;
          data.medianTimeOffset = res.avgGenTime * res.medianTimeBlocks / 2;
          return res;
        });
    }

    function loadFirstBlock(currencyName) {
      // Well known currencies
      if (constants.WELL_KNOWN_CURRENCIES[currencyName]){
        angular.merge(data, constants.WELL_KNOWN_CURRENCIES[currencyName]);
        return $q.when();
      }

      return BMA.blockchain.block({block:0})
        .then(function(json) {
          // Need by graph plugin
          data.firstBlockTime = json.medianTime;
        })
        .catch(function(err) {
          // Special case, when currency not started yet
          if (err && err.ucode === BMA.errorCodes.BLOCK_NOT_FOUND) {
            data.firstBlockTime = 0;
            data.initPhase = true;
            console.warn('[currency] Blockchain not launched: Enable init phase mode');
            return;
          }
          throw err;
        });
    }

    function loadCurrentUD() {
      return BMA.blockchain.stats.ud()
        .then(function(res){
          // Special case for currency init
          if (!res.result.blocks.length) {
            data.currentUD = data.parameters ? data.parameters.ud0 : -1;
            return data.currentUD ;
          }
          else {
            var lastBlockWithUD = res.result.blocks[res.result.blocks.length - 1];
            return BMA.blockchain.block({ block: lastBlockWithUD })
              .then(function(block){
                data.currentUD = powBase(block.dividend, block.unitbase);
                return data.currentUD;
              })
              .catch(function(err) {
                console.error("[currency] Unable to load last block with UD, with number {0}".format(lastBlockWithUD));
                data.currentUD = null;
                throw err;
              });
          }
        })
        .catch(function(err) {
          data.currentUD = null;
          throw err;
        });
    }

    function getData() {

      if (started) { // load only once
        return $q.when(data);
      }

      // Previous load not finished: return the existing promise - fix #452
      return startPromise || start();
    }

    function getDataField(field) {
      return function() {
        if (started) { // load only once
          return $q.when(data[field]);
        }

        // Previous load not finished: return the existing promise - fix #452
        return startPromise || start() // load only once
            .then(function(){
              return data[field];
            });
      };
    }

    function onBlock(json) {
      var block = new Block(json);
      block.cleanData(); // Remove unused content (arrays...) and keep items count

      //console.debug('[currency] Received new block', block);
      console.debug('[currency] Received new block [' + block.number + '-' + block.hash + ']');

      data.currentBlock = block;
      data.currentBlock.receivedAt = moment().utc().unix();

      data.medianTime = block.medianTime;
      data.membersCount = block.membersCount;

      // Update UD
      if (block.dividend) {
        data.currentUD = block.dividend;
      }

      // Dispatch to extensions
      api.data.raise.newBlock(block);
    }

    function addListeners() {
      listeners = [
        // Listen if node changed
        BMA.api.node.on.restart($rootScope, restart, this),
        // open web socket on block
        BMA.websocket.block().onListener(onBlock)
      ];
    }

    function removeListeners() {
      _.forEach(listeners, function(remove){
        remove();
      });
      listeners = [];
    }

    function ready() {
      if (started) return $q.when(data);
      return startPromise || start();
    }

    function stop() {
      console.debug('[currency] Stopping...');
      removeListeners();
      resetData();
    }

    function restart() {
      stop();
      return $timeout(start, 200);
    }

    function start() {
      console.debug('[currency] Starting...');
      var now = Date.now();

      startPromise = BMA.ready()

        // Load data
        .then(loadData)

        // Emit ready event
        .then(function() {
          addListeners();

          console.debug('[currency] Started in ' + (Date.now() - now) + 'ms');

          started = true;
          startPromise = null;

          // Emit event (used by plugins)
          api.data.raise.ready(data);
        })
        .then(function(){
          return data;
        });

      return startPromise;
    }

    var currentBlockField = getDataField('currentBlock');

    function getCurrent(cache) {
      // Get field (and make sure service is started)
      return currentBlockField()

        .then(function(currentBlock) {

          var now = moment().utc().unix();

          if (cache) {
            if (currentBlock && (now - currentBlock.receivedAt) < 60/*1min*/) {
              //console.debug('[currency] Use current block #'+ currentBlock.number +' from cache (age='+ (now - currentBlock.receivedAt) + 's)');
              return currentBlock;
            }

            if (!currentBlock) {
              // Should never occur, if websocket /ws/block works !
              console.warn('[currency] No current block in cache: get it from network. Websocket [/ws/block] may not be started ?');
            }
          }

          return BMA.blockchain.current()
            .catch(function(err){
              // Special case for currency init (root block not exists): use fixed values
              if (err && err.ucode == BMA.errorCodes.NO_CURRENT_BLOCK) {
                return {number: 0, hash: BMA.constants.ROOT_BLOCK_HASH, medianTime: moment().utc().unix()};
              }
              throw err;
            })
            .then(function(current) {
              data.currentBlock = current;
              data.currentBlock.receivedAt = now;
              return current;
            });
        });
    }

    function getLastValidBlock() {
      if (csSettings.data.blockValidityWindow <= 0) {
        return getCurrent(true);
      }

      return getCurrent(true)
        .then(function(current) {
          var number = current.number - csSettings.data.blockValidityWindow;
          return (number > 0) ? BMA.blockchain.block({block: number}) : current;
        });
    }

    // Get time in second (UTC - medianTimeOffset)
    function getDateNow() {
      return moment().utc().unix() - (data.medianTimeOffset || constants.WELL_KNOWN_CURRENCIES.g1.medianTimeOffset);
    }

    // TODO register new block event, to get new UD value

    // Register extension points
    api.registerEvent('data', 'ready');
    api.registerEvent('data', 'load');
    api.registerEvent('data', 'reset');
    api.registerEvent('data', 'newBlock');

    // init data
    resetData();

    // Default action
    //start();

    return {
      ready: ready,
      start: start,
      stop: stop,
      data: data,
      get: getData,
      name: getDataField('name'),
      parameters: getDataField('parameters'),
      currentUD: getDataField('currentUD'),
      medianTimeOffset: getDataField('medianTimeOffset'),
      blockchain: {
        current: getCurrent,
        lastValid: getLastValidBlock
      },
      date: {
        now: getDateNow
      },
      // api extension
      api: api,
      // deprecated methods
      default: function() {
        console.warn('[currency] \'csCurrency.default()\' has been DEPRECATED - Please use \'csCurrency.get()\' instead.');
        return getData();
      }
    };
  }

  var service = factory('default', BMA);
  service.instance = factory;
  return service;
});
<commit_msg>[fix] Currency: Add a retry;, when loading last UD and when the block is not found.<commit_after>
angular.module('cesium.currency.services', ['ngApi', 'cesium.bma.services'])

.factory('csCurrency', function($rootScope, $q, $timeout, BMA, Api, csSettings) {
  'ngInject';

  function factory(id, BMA) {
    var
      constants = {
        // Avoid to many call on well known currencies
        WELL_KNOWN_CURRENCIES: {
          g1: {
            firstBlockTime: 1488987127,
            medianTimeOffset: 3600
          }
        }
      },

      data = {},
      started = false,
      startPromise,
      listeners,
      api = new Api(this, "csCurrency-" + id);

    function powBase(amount, base) {
      return base <= 0 ? amount : amount * Math.pow(10, base);
    }

    function resetData() {
      data.name = null;
      data.parameters = null;
      data.firstBlockTime = null;
      data.membersCount = null;
      data.cache = {};
      data.node = BMA;
      data.currentUD = null;
      data.medianTimeOffset = 0;
      started = false;
      startPromise = undefined;
      api.data.raise.reset(data);
    }

    function loadData() {

      // Load currency from default node
      return $q.all([

        // get parameters
        loadParameters()
          .then(function(parameters) {
            // load first block info
            return loadFirstBlock(parameters.currency);
          }),

        // get current UD
        loadCurrentUD(),

        // call extensions
        api.data.raisePromise.load(data)
      ])
      .catch(function(err) {
        resetData();
        throw err;
      });
    }

    function loadParameters() {
      return BMA.blockchain.parameters()
        .then(function(res){
          data.name = res.currency;
          data.parameters = res;
          data.medianTimeOffset = res.avgGenTime * res.medianTimeBlocks / 2;
          return res;
        });
    }

    function loadFirstBlock(currencyName) {
      // Well known currencies
      if (constants.WELL_KNOWN_CURRENCIES[currencyName]){
        angular.merge(data, constants.WELL_KNOWN_CURRENCIES[currencyName]);
        return $q.when();
      }

      return BMA.blockchain.block({block:0})
        .then(function(json) {
          // Need by graph plugin
          data.firstBlockTime = json.medianTime;
        })
        .catch(function(err) {
          // Special case, when currency not started yet
          if (err && err.ucode === BMA.errorCodes.BLOCK_NOT_FOUND) {
            data.firstBlockTime = 0;
            data.initPhase = true;
            console.warn('[currency] Blockchain not launched: Enable init phase mode');
            return;
          }
          throw err;
        });
    }

    function loadCurrentUD(res, retryCount) {
      return BMA.blockchain.stats.ud()
        .then(function(res) {
          // Special case for currency init
          if (!res.result.blocks.length) {
            data.currentUD = data.parameters ? data.parameters.ud0 : -1;
            return data.currentUD ;
          }
          return _safeLoadCurrentUD(res, res.result.blocks.length - 1);
        })
        .catch(function(err) {
          data.currentUD = null;
          throw err;
        })
    }

    /**
     * Load the last UD, with a workaround if last block with UD is not found in the node
     * @param res
     * @param blockIndex
     * @returns {*}
     * @private
     */
    function _safeLoadCurrentUD(res, blockIndex) {
      // Special case for currency init
      if (!res.result.blocks.length || blockIndex < 0) {
        data.currentUD = data.parameters ? data.parameters.ud0 : -1;
        return data.currentUD ;
      }
      else {
        var lastBlockWithUD = res.result.blocks[blockIndex];
        return BMA.blockchain.block({ block: lastBlockWithUD })
          .then(function(block){
            data.currentUD = powBase(block.dividend, block.unitbase);
            return data.currentUD;
          })
          .catch(function(err) {
            console.error("[currency] Unable to load last block with UD, with number {0}".format(lastBlockWithUD));
            if (blockIndex > 0) {
              console.error("[currency] Retrying to load UD from a previous block...");
              return _safeLoadCurrentUD(res, blockIndex-1);
            }
            data.currentUD = null;
            throw err;
          });
      }
    }

    function getData() {

      if (started) { // load only once
        return $q.when(data);
      }

      // Previous load not finished: return the existing promise - fix #452
      return startPromise || start();
    }

    function getDataField(field) {
      return function() {
        if (started) { // load only once
          return $q.when(data[field]);
        }

        // Previous load not finished: return the existing promise - fix #452
        return startPromise || start() // load only once
            .then(function(){
              return data[field];
            });
      };
    }

    function onBlock(json) {
      var block = new Block(json);
      block.cleanData(); // Remove unused content (arrays...) and keep items count

      //console.debug('[currency] Received new block', block);
      console.debug('[currency] Received new block [' + block.number + '-' + block.hash + ']');

      data.currentBlock = block;
      data.currentBlock.receivedAt = moment().utc().unix();

      data.medianTime = block.medianTime;
      data.membersCount = block.membersCount;

      // Update UD
      if (block.dividend) {
        data.currentUD = block.dividend;
      }

      // Dispatch to extensions
      api.data.raise.newBlock(block);
    }

    function addListeners() {
      listeners = [
        // Listen if node changed
        BMA.api.node.on.restart($rootScope, restart, this),
        // open web socket on block
        BMA.websocket.block().onListener(onBlock)
      ];
    }

    function removeListeners() {
      _.forEach(listeners, function(remove){
        remove();
      });
      listeners = [];
    }

    function ready() {
      if (started) return $q.when(data);
      return startPromise || start();
    }

    function stop() {
      console.debug('[currency] Stopping...');
      removeListeners();
      resetData();
    }

    function restart() {
      stop();
      return $timeout(start, 200);
    }

    function start() {
      console.debug('[currency] Starting...');
      var now = Date.now();

      startPromise = BMA.ready()

        // Load data
        .then(loadData)

        // Emit ready event
        .then(function() {
          addListeners();

          console.debug('[currency] Started in ' + (Date.now() - now) + 'ms');

          started = true;
          startPromise = null;

          // Emit event (used by plugins)
          api.data.raise.ready(data);
        })
        .then(function(){
          return data;
        });

      return startPromise;
    }

    var currentBlockField = getDataField('currentBlock');

    function getCurrent(cache) {
      // Get field (and make sure service is started)
      return currentBlockField()

        .then(function(currentBlock) {

          var now = moment().utc().unix();

          if (cache) {
            if (currentBlock && (now - currentBlock.receivedAt) < 60/*1min*/) {
              //console.debug('[currency] Use current block #'+ currentBlock.number +' from cache (age='+ (now - currentBlock.receivedAt) + 's)');
              return currentBlock;
            }

            if (!currentBlock) {
              // Should never occur, if websocket /ws/block works !
              console.warn('[currency] No current block in cache: get it from network. Websocket [/ws/block] may not be started ?');
            }
          }

          return BMA.blockchain.current()
            .catch(function(err){
              // Special case for currency init (root block not exists): use fixed values
              if (err && err.ucode == BMA.errorCodes.NO_CURRENT_BLOCK) {
                return {number: 0, hash: BMA.constants.ROOT_BLOCK_HASH, medianTime: moment().utc().unix()};
              }
              throw err;
            })
            .then(function(current) {
              data.currentBlock = current;
              data.currentBlock.receivedAt = now;
              return current;
            });
        });
    }

    function getLastValidBlock() {
      if (csSettings.data.blockValidityWindow <= 0) {
        return getCurrent(true);
      }

      return getCurrent(true)
        .then(function(current) {
          var number = current.number - csSettings.data.blockValidityWindow;
          return (number > 0) ? BMA.blockchain.block({block: number}) : current;
        });
    }

    // Get time in second (UTC - medianTimeOffset)
    function getDateNow() {
      return moment().utc().unix() - (data.medianTimeOffset || constants.WELL_KNOWN_CURRENCIES.g1.medianTimeOffset);
    }

    // TODO register new block event, to get new UD value

    // Register extension points
    api.registerEvent('data', 'ready');
    api.registerEvent('data', 'load');
    api.registerEvent('data', 'reset');
    api.registerEvent('data', 'newBlock');

    // init data
    resetData();

    // Default action
    //start();

    return {
      ready: ready,
      start: start,
      stop: stop,
      data: data,
      get: getData,
      name: getDataField('name'),
      parameters: getDataField('parameters'),
      currentUD: getDataField('currentUD'),
      medianTimeOffset: getDataField('medianTimeOffset'),
      blockchain: {
        current: getCurrent,
        lastValid: getLastValidBlock
      },
      date: {
        now: getDateNow
      },
      // api extension
      api: api,
      // deprecated methods
      default: function() {
        console.warn('[currency] \'csCurrency.default()\' has been DEPRECATED - Please use \'csCurrency.get()\' instead.');
        return getData();
      }
    };
  }

  var service = factory('default', BMA);
  service.instance = factory;
  return service;
});
<|endoftext|>


<commit_before>import React from 'react';

class Item extends React.Component {
  constructor() {
  super();

  this.state = {
    loading: true
      };
    }

  componentDidMount() {
    this.setState({
      key: this.props.id,
      id: this.props.id,
      name: this.props.name,
      description: this.props.description,
      createdAt: this.props.createdAt,
      updatedAt: this.props.updatedAt,
      loading: !!!this.props.id

    });
  }

    render() {
      console.log(this.state);
        return (

{this.state.id}

{this.state.name}

{this.state.description}

{this.state.availability}

        );
    }
}

export default Item;
<commit_msg>add update function for creating item in item.js<commit_after>import React from 'react';

class Item extends React.Component {
  constructor() {
  super();

  this.state = {
    loading: true
      };
    }

  componentDidMount() {
    this.setState({
      key: this.props.id,
      id: this.props.id,
      name: this.props.name,
      description: this.props.description,
      createdAt: this.props.createdAt,
      updatedAt: this.props.updatedAt,
      loading: !!!this.props.id
    });
  }
  // $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

  updateItem(newItem) {
    console.log(newItem);
    this.syncState({item: newItem});
  }

  // toggleChecked(event) {
  //   this.syncState({
  //     completed: this.refs.completed.checked
  //   });
  // }

  syncState(updatedState) {
    console.log("Syncing state!");

    this.setState({
      loading: true
    });

    let component = this;

    let newState = jQuery.extend({
      id: this.state.id,
      name: this.state.name,
      description: this.state.description
    }, updatedState);

    this.setState(newState);

    console.log(newState);

    jQuery.ajax({
      type: "PUT",
      url: `https://fierce-brook-27687.herokuapp.com/items/${this.props.id}.json`,
      data: JSON.stringify({
          item: newState
      }),
      contentType: "application/json",
      dataType: "json"
    })

    .done(function(data) {
      console.log(data);

      component.setState({
        id: data.item.id,
        name: data.item.name,
        description: data.item.description
      });
    })

    .fail(function(error) {
      console.log(error);
    })

    .always(function() {
      component.setState({
        loading: false
      });
      component.props.onChange();
    });
}

    render() {
      console.log(this.state);
        return (

{this.state.id}

{this.state.name}

{this.state.description}

{this.state.availability}

        );
    }
}

export default Item;
<|endoftext|>