<commit_before>let assert = require('assert');
let exec = require('child_process').exec;
let fs = require('fs-extra');
let utils = require('./utils');

describe('diagrams sequence', function(){
    it('should create .svg from .sequence files', function(cb) {
        let generatedSVGPath = `${utils.getTmpDir()}/sequence.svg`;
        exec(`./bin/diagrams.js sequence tests/fixtures/sequence/simple.sequence ${generatedSVGPath}`, (err) => {
            if(err){
                return cb(err);
            }

            fs.readFile(generatedSVGPath, (err, fileContent) => {
                if(err){
                    return cb(err);
                }
                assert.equal(
                    fileContent.toString(),
                    `<svg height="260" version="1.1" width="485.2421875" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="overflow: hidden; position: relative;"><desc style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Created with RaphaÃ«l 2.1.4</desc><defs style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"><path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path><marker id="raphael-marker-endblock55-obj21" markerHeight="5" markerWidth="5" orient="auto" refX="2.5" refY="2.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"><use xlink:href="#raphael-marker-block" transform="rotate(180 2.5 2.5) scale(1,1)" stroke-width="1.0000" fill="#000000" stroke="none" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></use></marker><marker id="raphael-marker-endblock55-obj27" markerHeight="5" markerWidth="5" orient="auto" refX="2.5" refY="2.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"><use xlink:href="#raphael-marker-block" transform="rotate(180 2.5 2.5) scale(1,1)" stroke-width="1.0000" fill="#000000" stroke="none" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></use></marker></defs><rect x="10" y="20" width="68" height="38" rx="0" ry="0" fill="#ffffff" stroke="#000000" stroke-width="2" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></rect><text x="20" y="39" text-anchor="start" font-family="Andale Mono, monospace" font-size="16px" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: start; font-family: "Andale Mono", monospace; font-size: 16px;"><tspan dy="5.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Alice</tspan></text><rect x="10" y="202" width="68" height="38" rx="0" ry="0" fill="#ffffff" stroke="#000000" stroke-width="2" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></rect><text x="20" y="221" text-anchor="start" font-family="Andale Mono, monospace" font-size="16px" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: start; font-family: "Andale Mono", monospace; font-size: 16px;"><tspan dy="5.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Alice</tspan></text><path fill="none" stroke="#000000" d="M44,58L44,202" stroke-width="2" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path><rect x="260.4296875" y="20" width="48.796875" height="38" rx="0" ry="0" fill="#ffffff" stroke="#000000" stroke-width="2" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></rect><text x="270.421875" y="39" text-anchor="start" font-family="Andale Mono, monospace" font-size="16px" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: start; font-family: "Andale Mono", monospace; font-size: 16px;"><tspan dy="5.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Bob</tspan></text><rect x="260.4296875" y="202" width="48.796875" height="38" rx="0" ry="0" fill="#ffffff" stroke="#000000" stroke-width="2" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></rect><text x="270.421875" y="221" text-anchor="start" font-family="Andale Mono, monospace" font-size="16px" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: start; font-family: "Andale Mono", monospace; font-size: 16px;"><tspan dy="5.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Bob</tspan></text><path fill="none" stroke="#000000" d="M284.828125,58L284.828125,202" stroke-width="2" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path><text x="53.9921875" y="83" text-anchor="start" font-family="Andale Mono, monospace" font-size="16px" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: start; font-family: "Andale Mono", monospace; font-size: 16px;"><tspan dy="5.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Hello Bob, how are you?</tspan></text><path fill="none" stroke="#000000" d="M44,96C44,96,245.32186852861196,96,279.82576298834965,96" stroke-width="2" marker-end="url(#raphael-marker-endblock55-obj21)" stroke-dasharray="none" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path><rect x="304.828125" y="116" width="106.015625" height="28" rx="0" ry="0" fill="#ffffff" stroke="#000000" stroke-width="2" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></rect><text x="309.8203125" y="130" text-anchor="start" font-family="Andale Mono, monospace" font-size="16px" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: start; font-family: "Andale Mono", monospace; font-size: 16px;"><tspan dy="5.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Bob thinks</tspan></text><text x="82.8046875" y="169" text-anchor="start" font-family="Andale Mono, monospace" font-size="16px" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: start; font-family: "Andale Mono", monospace; font-size: 16px;"><tspan dy="5.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">I am good thanks!</tspan></text><path fill="none" stroke="#000000" d="M284.828125,182C284.828125,182,83.50625647138804,182,49.00236201165035,182" stroke-width="2" marker-end="url(#raphael-marker-endblock55-obj27)" stroke-dasharray="6,2" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path></svg>`
                )
                cb(null);
            });
        })
    });
});
<commit_msg>Have to disable tests for now<commit_after>let assert = require('assert');
let exec = require('child_process').exec;
let fs = require('fs-extra');
let utils = require('./utils');

describe('diagrams sequence', function(){
    it.skip('should create .svg from .sequence files', function(cb) {
        let generatedSVGPath = `${utils.getTmpDir()}/sequence.svg`;
        exec(`./bin/diagrams.js sequence tests/fixtures/sequence/simple.sequence ${generatedSVGPath}`, (err) => {
            if(err){
                return cb(err);
            }

            fs.readFile(generatedSVGPath, (err, fileContent) => {
                if(err){
                    return cb(err);
                }
                assert.equal(
                    fileContent.toString(),
                    `<svg height="260" version="1.1" width="485.2421875" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="overflow: hidden; position: relative;"><desc style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Created with RaphaÃ«l 2.1.4</desc><defs style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"><path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path><marker id="raphael-marker-endblock55-obj21" markerHeight="5" markerWidth="5" orient="auto" refX="2.5" refY="2.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"><use xlink:href="#raphael-marker-block" transform="rotate(180 2.5 2.5) scale(1,1)" stroke-width="1.0000" fill="#000000" stroke="none" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></use></marker><marker id="raphael-marker-endblock55-obj27" markerHeight="5" markerWidth="5" orient="auto" refX="2.5" refY="2.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"><use xlink:href="#raphael-marker-block" transform="rotate(180 2.5 2.5) scale(1,1)" stroke-width="1.0000" fill="#000000" stroke="none" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></use></marker></defs><rect x="10" y="20" width="68" height="38" rx="0" ry="0" fill="#ffffff" stroke="#000000" stroke-width="2" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></rect><text x="20" y="39" text-anchor="start" font-family="Andale Mono, monospace" font-size="16px" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: start; font-family: "Andale Mono", monospace; font-size: 16px;"><tspan dy="5.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Alice</tspan></text><rect x="10" y="202" width="68" height="38" rx="0" ry="0" fill="#ffffff" stroke="#000000" stroke-width="2" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></rect><text x="20" y="221" text-anchor="start" font-family="Andale Mono, monospace" font-size="16px" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: start; font-family: "Andale Mono", monospace; font-size: 16px;"><tspan dy="5.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Alice</tspan></text><path fill="none" stroke="#000000" d="M44,58L44,202" stroke-width="2" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path><rect x="260.4296875" y="20" width="48.796875" height="38" rx="0" ry="0" fill="#ffffff" stroke="#000000" stroke-width="2" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></rect><text x="270.421875" y="39" text-anchor="start" font-family="Andale Mono, monospace" font-size="16px" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: start; font-family: "Andale Mono", monospace; font-size: 16px;"><tspan dy="5.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Bob</tspan></text><rect x="260.4296875" y="202" width="48.796875" height="38" rx="0" ry="0" fill="#ffffff" stroke="#000000" stroke-width="2" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></rect><text x="270.421875" y="221" text-anchor="start" font-family="Andale Mono, monospace" font-size="16px" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: start; font-family: "Andale Mono", monospace; font-size: 16px;"><tspan dy="5.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Bob</tspan></text><path fill="none" stroke="#000000" d="M284.828125,58L284.828125,202" stroke-width="2" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path><text x="53.9921875" y="83" text-anchor="start" font-family="Andale Mono, monospace" font-size="16px" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: start; font-family: "Andale Mono", monospace; font-size: 16px;"><tspan dy="5.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Hello Bob, how are you?</tspan></text><path fill="none" stroke="#000000" d="M44,96C44,96,245.32186852861196,96,279.82576298834965,96" stroke-width="2" marker-end="url(#raphael-marker-endblock55-obj21)" stroke-dasharray="none" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path><rect x="304.828125" y="116" width="106.015625" height="28" rx="0" ry="0" fill="#ffffff" stroke="#000000" stroke-width="2" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></rect><text x="309.8203125" y="130" text-anchor="start" font-family="Andale Mono, monospace" font-size="16px" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: start; font-family: "Andale Mono", monospace; font-size: 16px;"><tspan dy="5.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Bob thinks</tspan></text><text x="82.8046875" y="169" text-anchor="start" font-family="Andale Mono, monospace" font-size="16px" stroke="none" fill="#000000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-anchor: start; font-family: "Andale Mono", monospace; font-size: 16px;"><tspan dy="5.5" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">I am good thanks!</tspan></text><path fill="none" stroke="#000000" d="M284.828125,182C284.828125,182,83.50625647138804,182,49.00236201165035,182" stroke-width="2" marker-end="url(#raphael-marker-endblock55-obj27)" stroke-dasharray="6,2" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path></svg>`
                )
                cb(null);
            });
        })
    });
});
<|endoftext|>


<commit_before>import Component from 'can/component/';
import Map from 'can/map/';
import 'can/map/define/';
import './nuevo_articulo.less!';
import template from './nuevo_articulo.stache!';

import UnidadesDeMedida from 'aleph-frontend/models/unidadesDeMedida';
import Articulos from 'aleph-frontend/models/articulos';
import Proveedores from 'aleph-frontend/models/proveedores';

export const ViewModel = Map.extend(
	{
		define:
		{
			unidadesDeMedida:
			{
				value: function()
				{
					return UnidadesDeMedida.getList();
				}
			}
		,	articulo:
			{
				value:	Articulos
			,	set: function(a)
				{
					this.attr('resetPaginadorProveedores',!this.attr('resetPaginadorProveedores'));
					$('a[href="#datos"]').click();
					return a;
				}
			}
		,	proveedores:
			{
				value: function()
				{
					return	Proveedores.getList()
				}
			}
		,	resetPaginadorProveedores:
			{
				value:	false
			}
		,	resetPaginador:
			{
				value:	false
			}
		,	errorMsg:
			{
				value:	null
			}
		,	query:
			{
				value: function()
				{
					var self
					=	this;

					var query
					=	new can.Map(
							{
								$skip: 0
							}
						);

					query
						.bind(
							'change'
						,	function()
							{
								self
									.attr(
										'proveedores'
									,	Proveedores.getList(
											query.serialize()
										)
									)
							}
						);

					return query;
				}
			}
		,	searchInput:
			{
				value:	undefined
			}
		,	listQuery:
			{
				value: function()
				{
					var self
					=	this;

					var query
					=	new can.Map(
							{
								current:
								{
									firstPage:	0
								,	lastPage:	4
								}
							}
						);

					query
						.bind(
							'change'
						,	function()
							{
								self.attr('articulo.proveedores')
									.map(
										function(prov, i)
										{
											prov.attr(
												'visible'
											,	(i >= query.current.firstPage && i <= query.current.lastPage)
											);
										}
									)
							}
						);

					return query;
				}
			}
		}
	,	searchProveedor: function(value)
		{
			var value
			=	this.attr('searchInput')
			,	fields
			=	[
					{
						name: 'denominacion'
					,	type: String
					}
				];

			this.attr(
				'query.$or'
			,	value.length
				?	createQuery(fields,value)
				:	undefined
			);
		}
	,	addProveedor: function(prov)
		{
			if (this.attr('articulo.proveedores').indexOf(prov) == -1) {
				this.attr('articulo.proveedores').push(prov.attr('visible',true));
			} else {
				$.notify(
					{
						message:	'El Proveedor '+prov.attr('denominacion')+' ya fue agregado al articulo.'
					}
				,	{
						type:		'danger'
					,	placement:
						{
							from:	'bottom',
							align:	'right'
						}
					}
				);
			}
		}
	,	removeProveedor: function(el)
		{
			this.attr('articulo.proveedores').splice(can.$(el).parents('tr').index(),1);
		}
	,	toggleAjuste: function(el)
		{
			if (!$(el).is(':checked')) {
				this.attr('articulo.ajuste','');
				$('[name="ajuste"]').val('')
			}

			$('[name="ajuste"]')
				.attr(
					'disabled'
				,	(!$(el).is(':checked'))
					?	'disabled'
					:	null
				);
		}
	,	cancelArticulo: function()
		{
			this.attr('articulo', new Articulos({}));
		}
	,	saveArticulo: function(el)
		{
			var $button
			=	$(el)
			,	self
			=	this;

			$button.button('loading');

			var	newMode
			=	self.attr('articulo').isNew();

			self.attr('articulo').save()
				.then(
					function(data)
					{
						$button.button('reset');

						if (newMode) {
							self.attr('articulo', new Articulos({}));
						} else {
							$(el).parents('.modal').modal('hide')
							self.attr('articulo.tempStock',data.stock);
							$('#ajuste-switch').click();
						}

						$.notify(
							{
								message:	'Artículo '+(newMode ? 'creado' : 'actualizado')+' correctamente.'
							}
						,	{
								type:		'success'
							,	placement:
								{
									from:	'bottom',
									align:	'right'
								}
							}
						);

						$('#nuevo-articulo-form').find('[name]').each(
							function()
							{
								$(this).parents('.form-group')
									.removeClass('has-error has-success')
							}
						);

						self.attr('errorMsg', '');

					}
				,	function(data)
					{
						$('#nuevo-articulo-form').find('[name]').each(
							function()
							{
								$(this).parents('.form-group')
									.removeClass('has-error has-success')
									.addClass(
										(data.errors[$(this).attr('name')])
										?	'has-error'
										:	'has-success'
									)
							}
						);

						self.attr('errorMsg','Datos incorrectos, verifique los datos ingresados.');

						$button.button('reset');
					}
				)
		}
	}
);

export default Component.extend({
	tag: 'aleph-stock-nuevo-articulo',
	viewModel: ViewModel,
	template
});<commit_msg>Fix #18<commit_after>import Component from 'can/component/';
import Map from 'can/map/';
import 'can/map/define/';
import './nuevo_articulo.less!';
import template from './nuevo_articulo.stache!';

import UnidadesDeMedida from 'aleph-frontend/models/unidadesDeMedida';
import Articulos from 'aleph-frontend/models/articulos';
import Proveedores from 'aleph-frontend/models/proveedores';

export const ViewModel = Map.extend(
	{
		define:
		{
			unidadesDeMedida:
			{
				value: function()
				{
					return UnidadesDeMedida.getList();
				}
			}
		,	articulo:
			{
				value:	Articulos
			,	set: function(a)
				{
					this.attr('resetPaginadorProveedores',!this.attr('resetPaginadorProveedores'));
					$('a[href="#datos"]').click();
					return a;
				}
			}
		,	proveedores:
			{
				value: function()
				{
					return	Proveedores.getList()
				}
			}
		,	resetPaginadorProveedores:
			{
				value:	false
			}
		,	resetPaginador:
			{
				value:	false
			}
		,	errorMsg:
			{
				value:	null
			}
		,	query:
			{
				value: function()
				{
					var self
					=	this;

					var query
					=	new can.Map(
							{
								$skip: 0
							}
						);

					query
						.bind(
							'change'
						,	function()
							{
								self
									.attr(
										'proveedores'
									,	Proveedores.getList(
											query.serialize()
										)
									)
							}
						);

					return query;
				}
			}
		,	searchInput:
			{
				value:	undefined
			}
		,	listQuery:
			{
				value: function()
				{
					var self
					=	this;

					var query
					=	new can.Map(
							{
								current:
								{
									firstPage:	0
								,	lastPage:	4
								}
							}
						);

					query
						.bind(
							'change'
						,	function()
							{
								self.attr('articulo.proveedores')
									.map(
										function(prov, i)
										{
											prov.attr(
												'visible'
											,	(i >= query.current.firstPage && i <= query.current.lastPage)
											);
										}
									)
							}
						);

					return query;
				}
			}
		}
	,	searchProveedor: function(value)
		{
			var value
			=	this.attr('searchInput')
			,	fields
			=	[
					{
						name: 'denominacion'
					,	type: String
					}
				,	{
						name: 'dni_cuit'
					,	type: String
					}
				];

			this.attr(
				'query.$or'
			,	value.length
				?	createQuery(fields,value)
				:	undefined
			);
		}
	,	addProveedor: function(prov)
		{
			if (this.attr('articulo.proveedores').indexOf(prov) == -1) {
				this.attr('articulo.proveedores').push(prov.attr('visible',true));
			} else {
				$.notify(
					{
						message:	'El Proveedor '+prov.attr('denominacion')+' ya fue agregado al articulo.'
					}
				,	{
						type:		'danger'
					,	placement:
						{
							from:	'bottom',
							align:	'right'
						}
					}
				);
			}
		}
	,	removeProveedor: function(el)
		{
			this.attr('articulo.proveedores').splice(can.$(el).parents('tr').index(),1);
		}
	,	toggleAjuste: function(el)
		{
			if (!$(el).is(':checked')) {
				this.attr('articulo.ajuste','');
				$('[name="ajuste"]').val('')
			}

			$('[name="ajuste"]')
				.attr(
					'disabled'
				,	(!$(el).is(':checked'))
					?	'disabled'
					:	null
				);
		}
	,	cancelArticulo: function()
		{
			this.attr('articulo', new Articulos({}));
		}
	,	saveArticulo: function(el)
		{
			var $button
			=	$(el)
			,	self
			=	this;

			$button.button('loading');

			var	newMode
			=	self.attr('articulo').isNew();

			self.attr('articulo').save()
				.then(
					function(data)
					{
						$button.button('reset');

						if (newMode) {
							self.attr('articulo', new Articulos({}));
						} else {
							$(el).parents('.modal').modal('hide')
							self.attr('articulo.tempStock',data.stock);
							$('#ajuste-switch').click();
						}

						$.notify(
							{
								message:	'Artículo '+(newMode ? 'creado' : 'actualizado')+' correctamente.'
							}
						,	{
								type:		'success'
							,	placement:
								{
									from:	'bottom',
									align:	'right'
								}
							}
						);

						$('#nuevo-articulo-form').find('[name]').each(
							function()
							{
								$(this).parents('.form-group')
									.removeClass('has-error has-success')
							}
						);

						self.attr('errorMsg', '');

					}
				,	function(data)
					{
						$('#nuevo-articulo-form').find('[name]').each(
							function()
							{
								$(this).parents('.form-group')
									.removeClass('has-error has-success')
									.addClass(
										(data.errors[$(this).attr('name')])
										?	'has-error'
										:	'has-success'
									)
							}
						);

						self.attr('errorMsg','Datos incorrectos, verifique los datos ingresados.');

						$button.button('reset');
					}
				)
		}
	}
);

export default Component.extend({
	tag: 'aleph-stock-nuevo-articulo',
	viewModel: ViewModel,
	template
});<|endoftext|>


<commit_before>'use strict';

var Base64;
(function(Base64) {
    Base64.URI_SAFE = 1;

    Base64.encode = function(source, flags) {
        var uri_safe, cod_map, nbytes, i, output, state, output_byte, b, b2;

        if (!(typeof source == 'object' && source && typeof source.length == 'number')) {
            throw Error('Source must be array-like object, was ' + typeof source);
        }
        flags = 0 | flags;

        uri_safe = !!(flags & Base64.URI_SAFE);
        nbytes = source.length;
        output = [];
        i = 0;
        state = 0;
        for (;;) {
            if (i === nbytes) {
                if (state === 0) {
                    break;
                }
                output_byte = b2;
                state = 0;
            } else if (state <= 1) {
                b = source[i];
                i += 1;
                if (state === 0) {
                    output_byte = b >> 2;
                    b2 = (b & 3) << 4;
                    state = 1;
                } else {
                    output_byte = b2 | (b >> 4);
                    b2 = (b & 15) << 2;
                    state = 2;
                }
            } else {
                if (state === 2) {
                    b = source[i];
                    output_byte = b2 | (b >> 6);
                    b2 = b & 63;
                    state = 3;
                } else {
                    output_byte = b2;
                    state = 0;
                    i += 1;
                }
            }
            if (output_byte < 26) {
                output_byte += 65;
            } else if (output_byte < 52) {
                output_byte += 71;
            } else if (output_byte < 62) {
                output_byte -= 4;
            } else if (output_byte === 62) {
                output_byte = uri_safe ? 45 : 43;
            } else {
                output_byte = uri_safe ? 95 : 47;
            }
            output[output.length] = output_byte;
        }

        if (!uri_safe) {
            // Pad with charcodes for '=' until 4 devides the length.
            while (output.length & 3) {
                output[output.length] = 61;
            }
        }

        return String.fromCharCode.apply(null, output);
    }
})(Base64 || (Base64 = {}));

function set_post_key(form) {
    var array, i, random, time_bits, key, elem;
    if (window.crypto && window.crypto.getRandomValues) {
        array = new Uint8Array(8);
        window.crypto.getRandomValues(array);
    } else {
        array = [];
        time_bits = Date.now();
        for (i = 0; i < 8; i += 1) {
            array[array.length] = Math.floor(Math.random() * 256) ^ (time_bits & 255);

            // Use float devision so we can get date bits outside
            // 2**32. Those changes each 50 days.
            time_bits = Math.floor(time_bits / 256);
        }
    }
    key = Base64.encode(array, Base64.URI_SAFE);
    elem = document.createElement('input');
    elem.type = 'hidden';
    elem.name = 'pkey';
    elem.value = key;
    form.appendChild(elem);

    document.cookie = 'pkey=' + key + '; secure; path=/';
    return true;
}

function check_edit_fields(form) {
    var h, str;
    if (!form.group.value && !form.group_force.value) {
        h = form.group;
        str = "Укажите, пожалуйста, категорию.";
    } else if (!form.year.value) {
        h = form.year;
        str = "Укажите, пожалуйста, год написания.";
    } else if (!form.author.value) {
        h = form.author;
        str = "Укажите, пожалуйста, автора.";
    } else if (form.content.value.length < 4) {
        h = form.content;
        str = "Неплохо бы и сам текст написать...";
    } else {
        return true;
    }
    alert (str);
    h.focus();
    return false;
}

function on_edit_page() {

    CKEDITOR.replace('text_content', {
        language: 'ru',
        enterMode: CKEDITOR.ENTER_BR
    });

    document.getElementById('edit_form').onsubmit = function() {
        return check_edit_fields(this) && set_post_key(this);
    }
}

function on_delete_page() {
    document.getElementById('confirm_delete_form').onsubmit = function() {
        return set_post_key(this);
    }
}
<commit_msg>incresing default ckeditor height<commit_after>'use strict';

var Base64;
(function(Base64) {
    Base64.URI_SAFE = 1;

    Base64.encode = function(source, flags) {
        var uri_safe, cod_map, nbytes, i, output, state, output_byte, b, b2;

        if (!(typeof source == 'object' && source && typeof source.length == 'number')) {
            throw Error('Source must be array-like object, was ' + typeof source);
        }
        flags = 0 | flags;

        uri_safe = !!(flags & Base64.URI_SAFE);
        nbytes = source.length;
        output = [];
        i = 0;
        state = 0;
        for (;;) {
            if (i === nbytes) {
                if (state === 0) {
                    break;
                }
                output_byte = b2;
                state = 0;
            } else if (state <= 1) {
                b = source[i];
                i += 1;
                if (state === 0) {
                    output_byte = b >> 2;
                    b2 = (b & 3) << 4;
                    state = 1;
                } else {
                    output_byte = b2 | (b >> 4);
                    b2 = (b & 15) << 2;
                    state = 2;
                }
            } else {
                if (state === 2) {
                    b = source[i];
                    output_byte = b2 | (b >> 6);
                    b2 = b & 63;
                    state = 3;
                } else {
                    output_byte = b2;
                    state = 0;
                    i += 1;
                }
            }
            if (output_byte < 26) {
                output_byte += 65;
            } else if (output_byte < 52) {
                output_byte += 71;
            } else if (output_byte < 62) {
                output_byte -= 4;
            } else if (output_byte === 62) {
                output_byte = uri_safe ? 45 : 43;
            } else {
                output_byte = uri_safe ? 95 : 47;
            }
            output[output.length] = output_byte;
        }

        if (!uri_safe) {
            // Pad with charcodes for '=' until 4 devides the length.
            while (output.length & 3) {
                output[output.length] = 61;
            }
        }

        return String.fromCharCode.apply(null, output);
    }
})(Base64 || (Base64 = {}));

function set_post_key(form) {
    var array, i, random, time_bits, key, elem;
    if (window.crypto && window.crypto.getRandomValues) {
        array = new Uint8Array(8);
        window.crypto.getRandomValues(array);
    } else {
        array = [];
        time_bits = Date.now();
        for (i = 0; i < 8; i += 1) {
            array[array.length] = Math.floor(Math.random() * 256) ^ (time_bits & 255);

            // Use float devision so we can get date bits outside
            // 2**32. Those changes each 50 days.
            time_bits = Math.floor(time_bits / 256);
        }
    }
    key = Base64.encode(array, Base64.URI_SAFE);
    elem = document.createElement('input');
    elem.type = 'hidden';
    elem.name = 'pkey';
    elem.value = key;
    form.appendChild(elem);

    document.cookie = 'pkey=' + key + '; secure; path=/';
    return true;
}

function check_edit_fields(form) {
    var h, str;
    if (!form.group.value && !form.group_force.value) {
        h = form.group;
        str = "Укажите, пожалуйста, категорию.";
    } else if (!form.year.value) {
        h = form.year;
        str = "Укажите, пожалуйста, год написания.";
    } else if (!form.author.value) {
        h = form.author;
        str = "Укажите, пожалуйста, автора.";
    } else if (form.content.value.length < 4) {
        h = form.content;
        str = "Неплохо бы и сам текст написать...";
    } else {
        return true;
    }
    alert (str);
    h.focus();
    return false;
}

function on_edit_page() {

    CKEDITOR.replace('text_content', {
        language: 'ru',
        enterMode: CKEDITOR.ENTER_BR,
        height: '400px',
    });

    document.getElementById('edit_form').onsubmit = function() {
        return check_edit_fields(this) && set_post_key(this);
    }
}

function on_delete_page() {
    document.getElementById('confirm_delete_form').onsubmit = function() {
        return set_post_key(this);
    }
}
<|endoftext|>


<commit_before>// select HTML elements and store them in variables
var body = document.querySelector('body') // body element to listen for clicks
var title = document.querySelector('.title') // title bar
var tiles = Array.from(document.querySelectorAll('.tile')) // monitor tiles for 'X' and 'O'
var reset = document.querySelector('.reset') // reset button to reset the game
// create variables for the tic tac toe game
var player, moves, winner
resetBoard()

// Event listener on reset button
reset.addEventListener('click', resetBoard)

// function to reset the game
function resetBoard () {
  player = true
  moves = 1
  winner = ''
  title.textContent = player ? 'X\'s turn' : 'O\'s turn'
  tiles.forEach(tile => tile.textContent = '')
  reset.classList.add('hidden')
  body.addEventListener('click', tictactoe)
}

function tictactoe (event) {
  var tile = event.target
  if (tile.className !== 'tile') return
  if (tile.textContent) return
  tile.textContent = player ? 'X' : 'O'
  // find winner by checking tiles for 'X' and 'O'
  winner = findWinner()
  if (winner) {
    title.textContent = winner + ' wins!'
    body.removeEventListener('click', tictactoe)
    reset.classList.remove('hidden')
  } else if (moves === 9) {
    // it's a tie
    title.textContent = 'It\'s a tie!'
  } else {
    moves = moves + 1
    player = !player
    title.textContent = player ? 'X\'s turn' : 'O\'s turn'
  }
}

function findWinner () {
  // tiles layout by index
  // [0] [1] [2]
  // [3] [4] [5]
  // [6] [7] [8]
  var winningCombination = [ [0, 1, 2], [3, 4, 5], [6, 7, 8],
                             [0, 3, 6], [1, 4, 7], [2, 5, 8],
                             [0, 4, 8], [2, 4, 6]]

  if (winningCombination.some(combo =>
    combo.map(index => tiles[index])
      .every(tile => tile.textContent === 'X'))) return 'X'
  else if (winningCombination.some(combo =>
    combo.every(tileIndex =>
      tiles[tileIndex].textContent === 'O'))) return 'O'
}
<commit_msg>Refactoring<commit_after>// select HTML elements and store them in variables
var body = document.querySelector('body') // body element to listen for clicks
var title = document.querySelector('.title') // title bar
var tiles = Array.from(document.querySelectorAll('.tile')) // monitor tiles for 'X' and 'O'
var reset = document.querySelector('.reset') // reset button to reset the game
// create variables for the tic tac toe game
var player, moves, winner
resetBoard()

// Event listener on reset button
reset.addEventListener('click', resetBoard)

// function to reset the game
function resetBoard () {
  player = true
  moves = 1
  winner = ''
  title.textContent = player ? 'X\'s turn' : 'O\'s turn'
  tiles.forEach(tile => tile.textContent = '')
  reset.classList.add('hidden')
  body.addEventListener('click', tictactoe)
}

function tictactoe (event) {
  var tile = event.target
  if (tile.className !== 'tile') return
  if (tile.textContent) return
  tile.textContent = player ? 'X' : 'O'
  // find winner by checking tiles for 'X' and 'O'
  winner = findWinner()
  if (winner) {
    title.textContent = winner + ' wins!'
    body.removeEventListener('click', tictactoe)
    reset.classList.remove('hidden')
  } else if (moves === 9) {
    // it's a tie
    title.textContent = 'It\'s a tie!'
  } else {
    moves = moves + 1
    player = !player
    title.textContent = player ? 'X\'s turn' : 'O\'s turn'
  }
}

function findWinner () {
  // tiles layout by index
  // [0] [1] [2]
  // [3] [4] [5]
  // [6] [7] [8]
  var winningCombination = [ [0, 1, 2], [3, 4, 5], [6, 7, 8],
                             [0, 3, 6], [1, 4, 7], [2, 5, 8],
                             [0, 4, 8], [2, 4, 6]]

  if (winningCombination.some(combo =>
    combo.map(index => tiles[index])
      .every(tile => tile.textContent === 'X'))) return 'X'
  else if (winningCombination.some(combo =>
    combo.map(index => tiles[index])
      .every(tile => tile.textContent === 'O'))) return 'O'
}
<|endoftext|>


<commit_before>class ZIF {

  constructor(file) {
    this.file = file;
    this.head = this.parseHead(); // A promise for the header
  }

  getTile(x, y, zoomLevel) {
    return this.getLevel(zoomLevel).then(level => level.getTile(x,y));
  }

  getLevel(zoomLevel) {
    return this.head.then(levels => levels[zoomLevel]);
  }

  parseHead() {
    return this.file.getBytes(0, ZIF.MAX_HEAD_SIZE).then(b => this.parseHeadBytes(b));
  }

  parseHeadBytes(bytes) {
    if (bytes.long(0) !== 0x08002b4949) throw new Error("invalid zif file");
    let levels = [];
    let ptr = 0x8;
    while ( ptr > 0 && ptr < ZIF.MAX_HEAD_SIZE) {
      ptr = bytes.long(ptr);
      let nTags = bytes.long(ptr);
      let level = new ZoomLevel(this.file);
      levels.push(level);
      let end = ptr + 8 + 20 * nTags;
      for(ptr += 8; ptr < end; ptr += 20) {
        level.set(bytes.short(ptr), bytes.long(ptr + 4), bytes.long(ptr + 12));
      }
    }
    return levels;
  }
  static MAX_HEAD_SIZE = 2000;
}

class ZoomLevel {
  constructor(file) {
    this.file = file;
    this.meta = new Map();
    this.tilesInfos = null;
  }

  getTilesInfos() {
    if (this.tilesInfos === null) {
      this.tilesInfos = Promise.all([this.getTileOffsets(), this.getTileSizes()])
                          .then(ZoomLevel.transpose);
    }
    return this.tilesInfos;
  }

  getTile(x, y) {
    return this.getTilesInfos().then(infos => this.subFile(infos[this.xy2num(x, y)]));
  }

  set(k, v1, v2) {
    return this.meta.set(k, [v1,v2]);
  }

  get(k){
    return this.meta.get(k[0])[k[1]];
  }

  static m_width    = [0x0100, 1];
  static m_height   = [0x0101, 1];
  static m_tilesize = [0x0142, 1];
  static m_count    = [0x0144, 0];
  static m_pos      = [0x0144, 1];
  static m_size     = [0x0145, 1];

  dimensions() {
    return [this.get(ZoomLevel.m_width), this.get(ZoomLevel.m_height)];
  }

  widthInTiles() {
    return Math.ceil(this.get(ZoomLevel.m_width) / this.get(ZoomLevel.m_tilesize));
  }
  heightInTiles() {
    return Math.ceil(this.get(ZoomLevel.m_height) / this.get(ZoomLevel.m_tilesize));
  }

  xy2num(x,y) {
    return x + y * this.widthInTiles();
  }

  subFile(posAndSize) {
    let [pos, size] = posAndSize;
    return this.file.getBytes(pos, pos+size)
            .then(bytes => new Blob([bytes.u8], {"type":"image/jpeg"}));
  }

  getTileOffsets() {
    const count = this.get(ZoomLevel.m_count);
    const tagval = this.get(ZoomLevel.m_pos);
    if (count === 1) return Promise.resolve([tagval]);
    return this.getUintArray(tagval, count, 8);
  }

  getTileSizes() {
    const count = this.get(ZoomLevel.m_count);
    const tagval = this.get(ZoomLevel.m_size);
    if (count < 3) {
      return Promise.resolve([tagval|0, tagval/0x100000000|0].slice(0, count));
    }
    return this.getUintArray(tagval, count, 4);
  }

  getUintArray(pos, count, bytesPerNum) {
    return this.file.getBytes(pos, pos + bytesPerNum * count)
            .then(bytes => {
                let res = new Array(bytes.length / bytesPerNum);
                for (var i = 0; i < res.length; i++)
                  res[i] = bytes.readLittleEndian(i*bytesPerNum, bytesPerNum);
                return res;
            });
  }

  static transpose(arrarr) {
    return arrarr[0].map((val, i) => arrarr.map(arr => arr[i]));
  }
}

class Bytes {
  // Little endian bytes
  constructor(buffer) {
    this.u8 = new Uint8Array(buffer);
    this.length = this.u8.length;
  }

  readLittleEndian(pos, bytes) {
    // Warning: javascript cannot store integers larger than 52 bits
    let multiplier = 1, res = 0;
    for(let i=pos; i<pos+bytes; i++) {
      res += multiplier * (this.u8[i] | 0);
      multiplier *= 0x100;
    }
    return res;
  }
  short(pos) {return this.u8[pos] | this.u8[pos + 1] << 8;}
  int(pos) {
    return this.u8[pos]           | this.u8[pos + 1] << 8 |
           this.u8[pos + 2] << 16 | this.u8[pos + 3] << 24 ;
  }
  long(pos) {return this.readLittleEndian(pos, 8);}
}

class LocalFile {
  constructor(file) {this.file = file;}
  getBytes(begin, end) {
    return new Promise((accept, reject) => {
      let r = new FileReader;
      r.onload = (evt) => accept(new Bytes(r.result));
      r.onerror = (evt) => reject(r.error);
      r.readAsArrayBuffer(this.file.slice(begin, end));
    });
  }
}
<commit_msg>Change MAX_HEAD_SIZE<commit_after>class ZIF {

  constructor(file) {
    this.file = file;
    this.head = this.parseHead(); // A promise for the header
  }

  getTile(x, y, zoomLevel) {
    return this.getLevel(zoomLevel).then(level => level.getTile(x,y));
  }

  getLevel(zoomLevel) {
    return this.head.then(levels => levels[zoomLevel]);
  }

  parseHead() {
    return this.file.getBytes(0, ZIF.MAX_HEAD_SIZE).then(b => this.parseHeadBytes(b));
  }

  parseHeadBytes(bytes) {
    if (bytes.long(0) !== 0x08002b4949) throw new Error("invalid zif file");
    let levels = [];
    let ptr = 0x8;
    while ( ptr > 0 && ptr < ZIF.MAX_HEAD_SIZE) {
      ptr = bytes.long(ptr);
      let nTags = bytes.long(ptr);
      let level = new ZoomLevel(this.file);
      levels.push(level);
      let end = ptr + 8 + 20 * nTags;
      for(ptr += 8; ptr < end; ptr += 20) {
        level.set(bytes.short(ptr), bytes.long(ptr + 4), bytes.long(ptr + 12));
      }
    }
    return levels;
  }
  static MAX_HEAD_SIZE = 8192;
}

class ZoomLevel {
  constructor(file) {
    this.file = file;
    this.meta = new Map();
    this.tilesInfos = null;
  }

  getTilesInfos() {
    if (this.tilesInfos === null) {
      this.tilesInfos = Promise.all([this.getTileOffsets(), this.getTileSizes()])
                          .then(ZoomLevel.transpose);
    }
    return this.tilesInfos;
  }

  getTile(x, y) {
    return this.getTilesInfos().then(infos => this.subFile(infos[this.xy2num(x, y)]));
  }

  set(k, v1, v2) {
    return this.meta.set(k, [v1,v2]);
  }

  get(k){
    return this.meta.get(k[0])[k[1]];
  }

  static m_width    = [0x0100, 1];
  static m_height   = [0x0101, 1];
  static m_tilesize = [0x0142, 1];
  static m_count    = [0x0144, 0];
  static m_pos      = [0x0144, 1];
  static m_size     = [0x0145, 1];

  dimensions() {
    return [this.get(ZoomLevel.m_width), this.get(ZoomLevel.m_height)];
  }

  widthInTiles() {
    return Math.ceil(this.get(ZoomLevel.m_width) / this.get(ZoomLevel.m_tilesize));
  }
  heightInTiles() {
    return Math.ceil(this.get(ZoomLevel.m_height) / this.get(ZoomLevel.m_tilesize));
  }

  xy2num(x,y) {
    return x + y * this.widthInTiles();
  }

  subFile(posAndSize) {
    let [pos, size] = posAndSize;
    return this.file.getBytes(pos, pos+size)
            .then(bytes => new Blob([bytes.u8], {"type":"image/jpeg"}));
  }

  getTileOffsets() {
    const count = this.get(ZoomLevel.m_count);
    const tagval = this.get(ZoomLevel.m_pos);
    if (count === 1) return Promise.resolve([tagval]);
    return this.getUintArray(tagval, count, 8);
  }

  getTileSizes() {
    const count = this.get(ZoomLevel.m_count);
    const tagval = this.get(ZoomLevel.m_size);
    if (count < 3) {
      return Promise.resolve([tagval|0, tagval/0x100000000|0].slice(0, count));
    }
    return this.getUintArray(tagval, count, 4);
  }

  getUintArray(pos, count, bytesPerNum) {
    return this.file.getBytes(pos, pos + bytesPerNum * count)
            .then(bytes => {
                let res = new Array(bytes.length / bytesPerNum);
                for (var i = 0; i < res.length; i++)
                  res[i] = bytes.readLittleEndian(i*bytesPerNum, bytesPerNum);
                return res;
            });
  }

  static transpose(arrarr) {
    return arrarr[0].map((val, i) => arrarr.map(arr => arr[i]));
  }
}

class Bytes {
  // Little endian bytes
  constructor(buffer) {
    this.u8 = new Uint8Array(buffer);
    this.length = this.u8.length;
  }

  readLittleEndian(pos, bytes) {
    // Warning: javascript cannot store integers larger than 52 bits
    let multiplier = 1, res = 0;
    for(let i=pos; i<pos+bytes; i++) {
      res += multiplier * (this.u8[i] | 0);
      multiplier *= 0x100;
    }
    return res;
  }
  short(pos) {return this.u8[pos] | this.u8[pos + 1] << 8;}
  int(pos) {
    return this.u8[pos]           | this.u8[pos + 1] << 8 |
           this.u8[pos + 2] << 16 | this.u8[pos + 3] << 24 ;
  }
  long(pos) {return this.readLittleEndian(pos, 8);}
}

class LocalFile {
  constructor(file) {this.file = file;}
  getBytes(begin, end) {
    return new Promise((accept, reject) => {
      let r = new FileReader;
      r.onload = (evt) => accept(new Bytes(r.result));
      r.onerror = (evt) => reject(r.error);
      r.readAsArrayBuffer(this.file.slice(begin, end));
    });
  }
}
<|endoftext|>


<commit_before>/* atom.js - Implementation of the Atom Syndication Format (RFC 4287)
 *
 * Copyright (C) 2010  Lincoln de Sousa <lincoln@comum.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/* Helper functions */
function isValidString(val) {
    return typeof(val) === typeof('') && val !== '';
}

/* Setting up a minimal inheritance infra */
Function.prototype.inherits = function (parent) {
    this.prototype = new parent();
    this.prototype.parent = parent;
}

Function.prototype.extend = function (obj) {
    for (var i in obj)
        this.prototype[i] = obj[i];
}

/* Base element for all Atom elements */

function BasicElement () {
    this.attrs = [];
    this.extraElements = [];
}

BasicElement.prototype = {
    _getElement: function () {
        throw new Error('BasicElement._getElement: This method should ' +
                        'be overrided;')
    },

    setAttr: function (key, val) {
        this.attrs.push({key: key, val: val});
    },

    getAttr: function (key) {
        for (var i = 0; i < this.attrs.length; i++) {
            if (this.attrs[i].key == key)
                return this.attrs[i].val;
        }
        return null;
    },

    addForeign: function (element) {
        this.extraElements.push(element);
    },

    toXML: function () {
        var element = this._getElement();
        var i, attr, subel;
        for (i = 0; i < this.attrs.length; i++) {
            attr = this.attrs[i];
            element.setAttribute(attr.key, attr.val);
        }

        for (i = 0; i < this.extraElements.length; i++) {
            subel = this.extraElements[i];
            element.appendChild(subel.toXML());
        }
        return element;
    },

    toString: function () {
        var node = this.toXML();

        /* Not using XMLSerializer because Firefox uppercases all node
         * names and it breaks our tests. I used to complain about IE,
         * not about FF :(
         */
        var container = document.createElement('container');
        container.appendChild(node.cloneNode(true));
        return container.innerHTML;
    }
};

/* Public objects in the `atom' namespace */

var atom = {
    SimpleElement: function (name, value) {
        this.parent();
        this.name = name;
        this.value = value;
    },

    Link: function (href) {
        this.parent();
        this.href = href;
        this.title = null;
        this.rel = null;
    },

    Content: function (type) {
        this.parent();
        this.type = type;
        this.src = null;
        this.content = null;
    },

    Person: function (name, email, uri) {
        this.parent();
        this.tagName = 'author';
        this.name = name;
        this.email = email;
        this.uri = uri;
    },

    Category: function (term, label, scheme) {
        this.parent();
        this.term = term;
        this.label = label;
        this.scheme = scheme;
    },

    Entry: function (title) {
        this.parent();
        this.title = title;
        this.id = null;
        this.updated = new Date();
        this.published = null;
        this.authors = [];
        this.categories = [];
        this.links = [];
        this.summary = null;
        this.rights = null;
        this.content = null;
    },

    parseEntry: doParseEntry

};

atom.SimpleElement.inherits(BasicElement);
atom.SimpleElement.extend({
    /* Element Creation */
    _getElement: function () {
        var element = document.createElement(this.name);
        if (this.value) {
            var elementValue = document.createTextNode(this.value);
            element.appendChild(elementValue);
        }
        return element;
    }
});

atom.Link.inherits(BasicElement);
atom.Link.extend({
    /* getters and setters */
    getHref: function () { return this.href; },
    setHref: function (href) { this.href = href; },
    getTitle: function () { return this.title; },
    setTitle: function (title) { this.title = title; },
    getRel: function () { return this.rel; },
    setRel: function (rel) { this.rel = rel; },

    /* Element Creation */
    _getElement: function () {
        var element = document.createElement('link');
        if (!isValidString(this.href))
            throw new Error("Link._getElement: `href' attribute is not set");
        element.setAttribute('href', this.href);
        if (isValidString(this.title))
            element.setAttribute('title', this.title);
        if (isValidString(this.rel))
            element.setAttribute('rel', this.rel);
        return element;
    }
});

atom.Content.inherits(BasicElement);
atom.Content.extend({
    /* getters and setters */
    getType: function () { return this.type; },
    setType: function (type) { this.type = type; },
    getSrc: function () { return this.src; },
    setSrc: function (src) { this.src = src; },
    getContent: function () { return this.content; },
    setContent: function (content) { this.content = content; },

    /* Element Creation */
    _getElement: function () {
        var element = document.createElement('content');

        if (!isValidString(this.type))
            throw new Error("Content._getElement: `type' attr is not set");
        element.setAttribute('type', this.type);

        if (isValidString(this.src) && isValidString(this.content))
            throw new Error("Content._getElement: `content' and `src' " +
                            "should not be set");
        else if (!isValidString(this.src) && !isValidString(this.content))
            throw new Error("Content._getElement: `content' OR `src' " +
                            "should be set");

        if (isValidString(this.src))
            element.setAttribute('src', this.src);
        else {
            var content = document.createTextNode(this.content);
            element.appendChild(content);
        }
        return element;
    }
});

atom.Person.inherits(BasicElement);
atom.Person.extend({
    /* getters and setters */
    getTagName: function () { return this.tagName; },
    setTagName: function (tagName) { this.tagName = tagName; },
    getName: function () { return this.name; },
    setName: function (name) { this.name = name; },
    getEmail: function () { return this.email; },
    setEmail: function (email) { this.email = email; },
    getUri: function () { return this.uri; },
    setUri: function (uri) { this.uri = uri; },

    /* Element Creation */
    _getElement: function () {
        var element = document.createElement(this.tagName);
        if (!isValidString(this.name)) {
            throw new Error("Person._getElement: `name' attr is not set");
        } else {
            var name = document.createElement('name')
            name.appendChild(document.createTextNode(this.name));
            element.appendChild(name);
        }

        if (isValidString(this.email)) {
            var email = document.createElement('email')
            email.appendChild(document.createTextNode(this.email));
            element.appendChild(email);
        }

        if (isValidString(this.uri)) {
            var uri = document.createElement('uri')
            uri.appendChild(document.createTextNode(this.uri));
            element.appendChild(uri);
        }

        return element;
    }
});

atom.Category.inherits(BasicElement);
atom.Category.extend({
    /* getters and setters */
    getTerm: function () { return this.term; },
    setTerm: function (term) { this.term = term; },
    getLabel: function () { return this.label; },
    setLabel: function (label) { this.label = label; },
    getScheme: function () { return this.scheme; },
    setScheme: function (scheme) { this.scheme = scheme; },

    /* Element Creation */
    _getElement: function () {
        var element = document.createElement('category');
        if (!isValidString(this.term))
            throw new Error("Category._getElement: `term' attr not set");
        element.setAttribute('term', this.term);
        if (isValidString(this.label))
            element.setAttribute('label', this.label);
        if (isValidString(this.scheme))
            element.setAttribute('scheme', this.scheme);
        return element;
    }
});

atom.Entry.inherits(BasicElement);
atom.Entry.extend({
    /* getters and setters */
    getTitle: function () { return this.title; },
    setTitle: function (title) { this.title = title; },
    getId: function () { return this.id; },
    setId: function (id) { this.id = id; },
    getUpdated: function () { return this.updated; },
    setUpdated: function (updated) { this.updated = updated; },
    getPublished: function () { return this.published; },
    setPublished: function (published) { this.published = published; },
    getSummary: function () { return this.summary; },
    setSummary: function (summary) { this.summary = summary; },
    getRights: function () { return this.rights; },
    setRights: function (rights) { this.rights = rights; },
    getContent: function () { return this.content; },
    setContent: function (content) { this.content = content; },

    /* List getters */
    getAuthors: function () { return this.authors; },
    getCategories: function () { return this.categories; },
    getLinks: function () { return this.links; },

    /* Methods to control lists of sub-elements */
    addAuthor: function (author) {
        if (author instanceof atom.Person)
            this.authors.push(author);
        else
            throw new Error('Waiting for an atom.Person object');
    },

    addCategory: function (category) {
        if (category instanceof atom.Category)
            this.categories.push(category);
        else
            throw new Error('Waiting for an atom.Category object');
    },

    addLink: function (link) {
        if (link instanceof atom.Link)
            this.links.push(link);
        else
            throw new Error('Waiting for an atom.Link object');
    },

    /* Element Creation */
    _getElement: function () {
        var element = document.createElement('entry');
        var i = 0;

        /* Setting the right namespace in the entry element */
        element.setAttribute('xmlns', 'http://www.w3.org/2005/Atom');

        if (isValidString(this.title)) {
            var title = document.createElement('title')
            title.appendChild(document.createTextNode(this.title));
            element.appendChild(title);
        }

        if (isValidString(this.id)) {
            var id = document.createElement('id')
            id.appendChild(document.createTextNode(this.id));
            element.appendChild(id);
        }

        if (this.updated instanceof Date) {
            var date = this.updated.toISOString();
            var updated = document.createElement('updated')
            updated.appendChild(document.createTextNode(date));
            element.appendChild(updated);
        }

        if (this.published instanceof Date) {
            var date = this.published.toISOString();
            var published = document.createElement('published')
            published.appendChild(document.createTextNode(date));
            element.appendChild(published);
        }

        if (isValidString(this.rights)) {
            var rights = document.createElement('rights');
            rights.appendChild(document.createTextNode(this.rights));
            element.appendChild(rights);
        }

        if (isValidString(this.summary)) {
            var summary = document.createElement('summary')
            summary.appendChild(document.createTextNode(this.summary));
            element.appendChild(summary);
        }

        /* Adding lists */
        for (i = 0; i < this.authors.length; i++)
            element.appendChild(this.authors[i]._getElement());
        for (i = 0; i < this.categories.length; i++)
            element.appendChild(this.categories[i]._getElement());
        for (i = 0; i < this.links.length; i++)
            element.appendChild(this.links[i]._getElement());

        /* Finally adding the content */
        if (this.content)
            element.appendChild(this.content._getElement());

        return element;
    }
});

function parseIsoDate (date) {
    var cleaned = date
        .replace(/-/g, '\/')
        .replace(/[TZ]/g, ' ')
        .replace(/\s+$/, '');
    return new Date(cleaned);
}

function doParseEntry (xml) {
    var parser = new DOMParser();
    var doc = parser.parseFromString(xml, "text/xml");
    var entry, i;

    /* Some sanity checks */
    if (!doc)
        throw new Error('Unable to parse document');
    if (doc.documentElement.tagName !== 'entry')
        throw new Error('Main element of xml is not an entry');

    /* The entry object itself! */
    entry = new atom.Entry();

    var childs = doc.documentElement.childNodes;
    for (i = 0; i < childs.length; i++) {
        var child = childs[i];
        switch (child.tagName) {
        case 'id':
            entry.setId(child.firstChild.nodeValue);
            break;

        case 'title':
            entry.setTitle(child.firstChild.nodeValue);
            break;

        case 'updated':
            entry.setUpdated(parseIsoDate(child.firstChild.nodeValue));
            break;

        case 'published':
            entry.setPublished(parseIsoDate(child.firstChild.nodeValue));
            break;

        case 'summary':
            entry.setSummary(child.firstChild.nodeValue);
            break;

        case 'rights':
            entry.setRights(child.firstChild.nodeValue);
            break;

        case 'author':
            var author = new atom.Person();
            var name = child.querySelector('name');
            if (name && name.firstChild)
                author.setName(name.firstChild.nodeValue);

            var email = child.querySelector('email');
            if (email && email.firstChild)
                author.setEmail(email.firstChild.nodeValue);

            var uri = child.querySelector('uri');
            if (uri && uri.firstChild)
                author.setUri(uri.firstChild.nodeValue);

            entry.addAuthor(author);
            break;

        case 'category':
            var category = new atom.Category();
            category.setTerm(child.getAttribute('term'));
            category.setLabel(child.getAttribute('label'));
            category.setScheme(child.getAttribute('scheme'));
            entry.addCategory(category);
            break;

        case 'link':
            var link = new atom.Link();
            link.setHref(child.getAttribute('href'));
            link.setTitle(child.getAttribute('title'));
            link.setRel(child.getAttribute('rel'))
            entry.addLink(link);
            break;

        case 'content':
            var content = new atom.Content(child.getAttribute('type'));
            content.setSrc(child.getAttribute('src'));
            if (!content.getSrc()) {
                var container = document.createElement('container');
                container.appendChild(child.cloneNode(true));
                content.setContent(container.innerHTML);
            }
            entry.setContent(content);
            break;
        }
    }

    return entry;
}
<commit_msg>Fixing some warnings<commit_after>/* atom.js - Implementation of the Atom Syndication Format (RFC 4287)
 *
 * Copyright (C) 2010  Lincoln de Sousa <lincoln@comum.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/* Helper functions */
function isValidString(val) {
    return typeof(val) === typeof('') && val !== '';
}

/* Setting up a minimal inheritance infra */
Function.prototype.inherits = function (parent) {
    this.prototype = new parent();
    this.prototype.parent = parent;
};

Function.prototype.extend = function (obj) {
    for (var i in obj)
        this.prototype[i] = obj[i];
};

/* Base element for all Atom elements */

function BasicElement () {
    this.attrs = [];
    this.extraElements = [];
}

BasicElement.prototype = {
    _getElement: function () {
        throw new Error('BasicElement._getElement: This method should ' +
                        'be overrided;');
    },

    setAttr: function (key, val) {
        this.attrs.push({key: key, val: val});
    },

    getAttr: function (key) {
        for (var i = 0; i < this.attrs.length; i++) {
            if (this.attrs[i].key == key)
                return this.attrs[i].val;
        }
        return null;
    },

    addForeign: function (element) {
        this.extraElements.push(element);
    },

    toXML: function () {
        var element = this._getElement();
        var i, attr, subel;
        for (i = 0; i < this.attrs.length; i++) {
            attr = this.attrs[i];
            element.setAttribute(attr.key, attr.val);
        }

        for (i = 0; i < this.extraElements.length; i++) {
            subel = this.extraElements[i];
            element.appendChild(subel.toXML());
        }
        return element;
    },

    toString: function () {
        var node = this.toXML();

        /* Not using XMLSerializer because Firefox uppercases all node
         * names and it breaks our tests. I used to complain about IE,
         * not about FF :(
         */
        var container = document.createElement('container');
        container.appendChild(node.cloneNode(true));
        return container.innerHTML;
    }
};

/* Public objects in the `atom' namespace */

var atom = {
    SimpleElement: function (name, value) {
        this.parent();
        this.name = name;
        this.value = value;
    },

    Link: function (href) {
        this.parent();
        this.href = href;
        this.title = null;
        this.rel = null;
    },

    Content: function (type) {
        this.parent();
        this.type = type;
        this.src = null;
        this.content = null;
    },

    Person: function (name, email, uri) {
        this.parent();
        this.tagName = 'author';
        this.name = name;
        this.email = email;
        this.uri = uri;
    },

    Category: function (term, label, scheme) {
        this.parent();
        this.term = term;
        this.label = label;
        this.scheme = scheme;
    },

    Entry: function (title) {
        this.parent();
        this.title = title;
        this.id = null;
        this.updated = new Date();
        this.published = null;
        this.authors = [];
        this.categories = [];
        this.links = [];
        this.summary = null;
        this.rights = null;
        this.content = null;
    },

    parseEntry: doParseEntry

};

atom.SimpleElement.inherits(BasicElement);
atom.SimpleElement.extend({
    /* Element Creation */
    _getElement: function () {
        var element = document.createElement(this.name);
        if (this.value) {
            var elementValue = document.createTextNode(this.value);
            element.appendChild(elementValue);
        }
        return element;
    }
});

atom.Link.inherits(BasicElement);
atom.Link.extend({
    /* getters and setters */
    getHref: function () { return this.href; },
    setHref: function (href) { this.href = href; },
    getTitle: function () { return this.title; },
    setTitle: function (title) { this.title = title; },
    getRel: function () { return this.rel; },
    setRel: function (rel) { this.rel = rel; },

    /* Element Creation */
    _getElement: function () {
        var element = document.createElement('link');
        if (!isValidString(this.href))
            throw new Error("Link._getElement: `href' attribute is not set");
        element.setAttribute('href', this.href);
        if (isValidString(this.title))
            element.setAttribute('title', this.title);
        if (isValidString(this.rel))
            element.setAttribute('rel', this.rel);
        return element;
    }
});

atom.Content.inherits(BasicElement);
atom.Content.extend({
    /* getters and setters */
    getType: function () { return this.type; },
    setType: function (type) { this.type = type; },
    getSrc: function () { return this.src; },
    setSrc: function (src) { this.src = src; },
    getContent: function () { return this.content; },
    setContent: function (content) { this.content = content; },

    /* Element Creation */
    _getElement: function () {
        var element = document.createElement('content');

        if (!isValidString(this.type))
            throw new Error("Content._getElement: `type' attr is not set");
        element.setAttribute('type', this.type);

        if (isValidString(this.src) && isValidString(this.content))
            throw new Error("Content._getElement: `content' and `src' " +
                            "should not be set");
        else if (!isValidString(this.src) && !isValidString(this.content))
            throw new Error("Content._getElement: `content' OR `src' " +
                            "should be set");

        if (isValidString(this.src))
            element.setAttribute('src', this.src);
        else {
            var content = document.createTextNode(this.content);
            element.appendChild(content);
        }
        return element;
    }
});

atom.Person.inherits(BasicElement);
atom.Person.extend({
    /* getters and setters */
    getTagName: function () { return this.tagName; },
    setTagName: function (tagName) { this.tagName = tagName; },
    getName: function () { return this.name; },
    setName: function (name) { this.name = name; },
    getEmail: function () { return this.email; },
    setEmail: function (email) { this.email = email; },
    getUri: function () { return this.uri; },
    setUri: function (uri) { this.uri = uri; },

    /* Element Creation */
    _getElement: function () {
        var element = document.createElement(this.tagName);
        if (!isValidString(this.name)) {
            throw new Error("Person._getElement: `name' attr is not set");
        } else {
            var name = document.createElement('name');
            name.appendChild(document.createTextNode(this.name));
            element.appendChild(name);
        }

        if (isValidString(this.email)) {
            var email = document.createElement('email');
            email.appendChild(document.createTextNode(this.email));
            element.appendChild(email);
        }

        if (isValidString(this.uri)) {
            var uri = document.createElement('uri');
            uri.appendChild(document.createTextNode(this.uri));
            element.appendChild(uri);
        }

        return element;
    }
});

atom.Category.inherits(BasicElement);
atom.Category.extend({
    /* getters and setters */
    getTerm: function () { return this.term; },
    setTerm: function (term) { this.term = term; },
    getLabel: function () { return this.label; },
    setLabel: function (label) { this.label = label; },
    getScheme: function () { return this.scheme; },
    setScheme: function (scheme) { this.scheme = scheme; },

    /* Element Creation */
    _getElement: function () {
        var element = document.createElement('category');
        if (!isValidString(this.term))
            throw new Error("Category._getElement: `term' attr not set");
        element.setAttribute('term', this.term);
        if (isValidString(this.label))
            element.setAttribute('label', this.label);
        if (isValidString(this.scheme))
            element.setAttribute('scheme', this.scheme);
        return element;
    }
});

atom.Entry.inherits(BasicElement);
atom.Entry.extend({
    /* getters and setters */
    getTitle: function () { return this.title; },
    setTitle: function (title) { this.title = title; },
    getId: function () { return this.id; },
    setId: function (id) { this.id = id; },
    getUpdated: function () { return this.updated; },
    setUpdated: function (updated) { this.updated = updated; },
    getPublished: function () { return this.published; },
    setPublished: function (published) { this.published = published; },
    getSummary: function () { return this.summary; },
    setSummary: function (summary) { this.summary = summary; },
    getRights: function () { return this.rights; },
    setRights: function (rights) { this.rights = rights; },
    getContent: function () { return this.content; },
    setContent: function (content) { this.content = content; },

    /* List getters */
    getAuthors: function () { return this.authors; },
    getCategories: function () { return this.categories; },
    getLinks: function () { return this.links; },

    /* Methods to control lists of sub-elements */
    addAuthor: function (author) {
        if (author instanceof atom.Person)
            this.authors.push(author);
        else
            throw new Error('Waiting for an atom.Person object');
    },

    addCategory: function (category) {
        if (category instanceof atom.Category)
            this.categories.push(category);
        else
            throw new Error('Waiting for an atom.Category object');
    },

    addLink: function (link) {
        if (link instanceof atom.Link)
            this.links.push(link);
        else
            throw new Error('Waiting for an atom.Link object');
    },

    /* Element Creation */
    _getElement: function () {
        var element = document.createElement('entry');
        var i = 0;
        var date;

        /* Setting the right namespace in the entry element */
        element.setAttribute('xmlns', 'http://www.w3.org/2005/Atom');

        if (isValidString(this.title)) {
            var title = document.createElement('title');
            title.appendChild(document.createTextNode(this.title));
            element.appendChild(title);
        }

        if (isValidString(this.id)) {
            var id = document.createElement('id');
            id.appendChild(document.createTextNode(this.id));
            element.appendChild(id);
        }

        if (this.updated instanceof Date) {
            var updated = document.createElement('updated');
            date = this.updated.toISOString();
            updated.appendChild(document.createTextNode(date));
            element.appendChild(updated);
        }

        if (this.published instanceof Date) {
            var published = document.createElement('published');
            date = this.published.toISOString();
            published.appendChild(document.createTextNode(date));
            element.appendChild(published);
        }

        if (isValidString(this.rights)) {
            var rights = document.createElement('rights');
            rights.appendChild(document.createTextNode(this.rights));
            element.appendChild(rights);
        }

        if (isValidString(this.summary)) {
            var summary = document.createElement('summary');
            summary.appendChild(document.createTextNode(this.summary));
            element.appendChild(summary);
        }

        /* Adding lists */
        for (i = 0; i < this.authors.length; i++)
            element.appendChild(this.authors[i]._getElement());
        for (i = 0; i < this.categories.length; i++)
            element.appendChild(this.categories[i]._getElement());
        for (i = 0; i < this.links.length; i++)
            element.appendChild(this.links[i]._getElement());

        /* Finally adding the content */
        if (this.content)
            element.appendChild(this.content._getElement());

        return element;
    }
});

function parseIsoDate (date) {
    var cleaned = date
        .replace(/-/g, '\/')
        .replace(/[TZ]/g, ' ')
        .replace(/\s+$/, '');
    return new Date(cleaned);
}

function doParseEntry (xml) {
    var parser = new DOMParser();
    var doc = parser.parseFromString(xml, "text/xml");
    var entry, i;

    /* Some sanity checks */
    if (!doc)
        throw new Error('Unable to parse document');
    if (doc.documentElement.tagName !== 'entry')
        throw new Error('Main element of xml is not an entry');

    /* The entry object itself! */
    entry = new atom.Entry();

    var childs = doc.documentElement.childNodes;
    for (i = 0; i < childs.length; i++) {
        var child = childs[i];
        switch (child.tagName) {
        case 'id':
            entry.setId(child.firstChild.nodeValue);
            break;

        case 'title':
            entry.setTitle(child.firstChild.nodeValue);
            break;

        case 'updated':
            entry.setUpdated(parseIsoDate(child.firstChild.nodeValue));
            break;

        case 'published':
            entry.setPublished(parseIsoDate(child.firstChild.nodeValue));
            break;

        case 'summary':
            entry.setSummary(child.firstChild.nodeValue);
            break;

        case 'rights':
            entry.setRights(child.firstChild.nodeValue);
            break;

        case 'author':
            var author = new atom.Person();
            var name = child.querySelector('name');
            if (name && name.firstChild)
                author.setName(name.firstChild.nodeValue);

            var email = child.querySelector('email');
            if (email && email.firstChild)
                author.setEmail(email.firstChild.nodeValue);

            var uri = child.querySelector('uri');
            if (uri && uri.firstChild)
                author.setUri(uri.firstChild.nodeValue);

            entry.addAuthor(author);
            break;

        case 'category':
            var category = new atom.Category();
            category.setTerm(child.getAttribute('term'));
            category.setLabel(child.getAttribute('label'));
            category.setScheme(child.getAttribute('scheme'));
            entry.addCategory(category);
            break;

        case 'link':
            var link = new atom.Link();
            link.setHref(child.getAttribute('href'));
            link.setTitle(child.getAttribute('title'));
            link.setRel(child.getAttribute('rel'));
            entry.addLink(link);
            break;

        case 'content':
            var content = new atom.Content(child.getAttribute('type'));
            content.setSrc(child.getAttribute('src'));
            if (!content.getSrc()) {
                var container = document.createElement('container');
                container.appendChild(child.cloneNode(true));
                content.setContent(container.innerHTML);
            }
            entry.setContent(content);
            break;
        }
    }

    return entry;
}
<|endoftext|>


<commit_before>// http://www.quirksmode.org/js/keys.html
/**
 * atta(b completion)
 * usage:
 *   $(selector).atta({
 *      completions: function () { return ['Foo', 'Bar', 'Baz' ] }
 *   })
 */
function ($) {
  'use strict';
  var defaults = {
      completions: function() {
          return $("#rsvp-list a.mem-name").
              map(function (i, a) { return a.text; }).sort();
      },
      at : {
          is: function(e){
              return  String.fromCharCode(e.which || e.keyCode) === "2" && e.shiftKey
          }
          , char : '@'
      }
  };
  /**
   * options is an object which may contain one of:
   * completions - a function which returns a list of completion options
   * at - an object representing the at trigger for tab completion.
   *      this object should contain a function, 'is', which should accept a key event
   *      and return true if the key event matches the trigger
   *      and a 'char' property which represents the display of the trigger.
   */
  $.fn.atta = function(options) {
     var self = this
      , options = options || {}
      , keys = {
          'up': 38
          , 'down': 40
          , 'escape': 27
          , 'enter': 13
          , 'tab': 9
      }
      , styles = [
          '#atta-list-container { position:relative; top: 0px; left: 5px; }'
          , '#atta-list { position:relative;margin-top:18px;background:#fff;border-radius:3px;border:1px solid #ddd;box-shadow:0 0 5px rgba(0,0,0,0.1);min-width:180px;}'
          , '#atta-list ul { list-style:none;margin:0;padding:0; }'
          , '#atta-list li { padding:5px 10px;font-weight:bold;border-bottom:1px solid #eee; color:#333; }'
          , '#atta-list li.sel { background:#1DCAFF; color:#fff; }' ]
      , completions = options.completions || defaults.completions
      , at = options.at || defaults.at
      , newList = function () {
          return $("

");
      }
      , newItem = function (name, i) {
          return '
' +
              name + '
';
      }
      , key = function(e, alias) {
          return (e.which || e.keyCode) === keys[alias];
      }
      , cancelKey = function (e) { return key(e, 'escape'); }
      , acceptKey = function (e) { return key(e, 'enter') || key(e, 'tab'); }
      , upKey = function (e) { return key(e, 'up'); }
      , downKey = function (e) { return key(e, 'down'); }
      , tabKey = function (e) { return key(e, 'tab'); }
      , buildMarkup = function (cs) {
          var current = $("#atta-list-container")
          , markup = current.length > 0 && current || newList()
          , ul = markup.find('ul')
          , buff = [];
          for(var i = 0, l = cs.length;i < l;i++) {
              buff.push(newItem(cs[i], i));
          }
          ul.empty().append(buff.join(''));
          return markup;
      }
      , cancel = function() {
          $('#atta-list-container').remove();
      }
      , showCompletions = function (ta, cs) {
          var markup = buildMarkup(cs);
          $(window).on('keyup', function (e) {
              var sel = $("#atta-list li.sel")
              , kids = $(sel.parent()).children()
              , cnt = kids.length
              , index = sel.length > 0 && sel.data().index || 0;
              if (cnt) {
                  if (upKey(e)) {
                      e.preventDefault();
                      sel.removeClass('sel');
                      if (index > 0) {
                          $(kids[index-1]).addClass('sel')
                      } else if (index == 0) {
                          $(kids[cnt-1]).addClass('sel')
                      }
                      return false;
                  } else if (downKey(e)) {
                      e.preventDefault();
                      sel.removeClass('sel');
                      if (index < cnt-1) {
                          $(kids[index+1]).addClass('sel')
                      } else if (index == cnt-1) {
                          $(kids[0]).addClass('sel')
                      }
                      return false;
                  }
              }
          });
          $(ta).parent().append(markup);
      };

      // append atta styles only once
      if ($('#atta-style').length < 1) {
          $('head').append('')
      }

      // bind accept and cancelation listener
      $(window).on('keyup', function(e) {
          if (cancelKey(e)) {
              cancel();
          } else if (acceptKey(e)) {
              var container = $('#atta-list-container');
              if (container.length > 0) {
                  e.preventDefault();
                  var name = container.find('.sel').text();
                  console.log('select ' + name);
                  cancel();
                  return false;
              }
          }
      });

      // bind query listener
      return self.each(function() {
          $(this).live('keyup', function (e) {
              var el = $(e.target);
              if (at.is(e)) {
                  showCompletions(e.target, completions() || []);
              } else {
                  var container = $("#atta-list-container");
                  if (container.length > 0) {
                      var txt = el.val(), query, matching, filteredCompletions;
                      if (txt.length > 0) {
                          var lastAt = txt.lastIndexOf(at.char);
                          if (lastAt != -1) {
                              query = txt.slice(lastAt + 1, txt.length);
                              matching = function(i, e) {
                                  return e.toLowerCase().indexOf(query.toLowerCase()) != -1;
                              }
                              filteredCompletions = (completions() || []).filter(matching);
                              showCompletions(el, filteredCompletions);
                          }
                      }
                  }
              }
          });
      });
  };
)(jQuery);<commit_msg>debugging whats focused<commit_after>// http://www.quirksmode.org/js/keys.html
/**
 * atta(b completion)
 * usage:
 *   $(selector).atta({
 *      completions: function () { return ['Foo', 'Bar', 'Baz' ] }
 *   })
 */
function ($) {
  'use strict';
  var defaults = {
      completions: function() {
          return $("#rsvp-list a.mem-name").
              map(function (i, a) { return a.text; }).sort();
      },
      at : {
          is: function(e){
              return  String.fromCharCode(e.which || e.keyCode) === "2" && e.shiftKey
          }
          , char : '@'
      }
  };
  /**
   * options is an object which may contain one of:
   * completions - a function which returns a list of completion options
   * at - an object representing the at trigger for tab completion.
   *      this object should contain a function, 'is', which should accept a key event
   *      and return true if the key event matches the trigger
   *      and a 'char' property which represents the display of the trigger.
   */
  $.fn.atta = function(options) {
     var self = this
      , options = options || {}
      , keys = {
          'up': 38
          , 'down': 40
          , 'escape': 27
          , 'enter': 13
          , 'tab': 9
      }
      , styles = [
          '#atta-list-container { position:relative; top: 0px; left: 5px; }'
          , '#atta-list { position:relative;margin-top:18px;background:#fff;border-radius:3px;border:1px solid #ddd;box-shadow:0 0 5px rgba(0,0,0,0.1);min-width:180px;}'
          , '#atta-list ul { list-style:none;margin:0;padding:0; }'
          , '#atta-list li { padding:5px 10px;font-weight:bold;border-bottom:1px solid #eee; color:#333; }'
          , '#atta-list li.sel { background:#1DCAFF; color:#fff; }' ]
      , completions = options.completions || defaults.completions
      , at = options.at || defaults.at
      , newList = function () {
          return $("

");
      }
      , newItem = function (name, i) {
          return '
' +
              name + '
';
      }
      , key = function(e, alias) {
          return (e.which || e.keyCode) === keys[alias];
      }
      , cancelKey = function (e) { return key(e, 'escape'); }
      , acceptKey = function (e) { return key(e, 'enter') || key(e, 'tab'); }
      , upKey = function (e) { return key(e, 'up'); }
      , downKey = function (e) { return key(e, 'down'); }
      , tabKey = function (e) { return key(e, 'tab'); }
      , buildMarkup = function (cs) {
          var current = $("#atta-list-container")
          , markup = current.length > 0 && current || newList()
          , ul = markup.find('ul')
          , buff = [];
          for(var i = 0, l = cs.length;i < l;i++) {
              buff.push(newItem(cs[i], i));
          }
          ul.empty().append(buff.join(''));
          return markup;
      }
      , cancel = function() {
          $('#atta-list-container').remove();
      }
      , showCompletions = function (ta, cs) {
          var markup = buildMarkup(cs);
          $(window).on('keyup', function (e) {
              var sel = $("#atta-list li.sel")
              , kids = $(sel.parent()).children()
              , cnt = kids.length
              , index = sel.length > 0 && sel.data().index || 0;
              if (cnt) {
                  if (upKey(e)) {
                      e.preventDefault();
                      sel.removeClass('sel');
                      if (index > 0) {
                          $(kids[index-1]).addClass('sel')
                      } else if (index == 0) {
                          $(kids[cnt-1]).addClass('sel')
                      }
                      return false;
                  } else if (downKey(e)) {
                      e.preventDefault();
                      sel.removeClass('sel');
                      if (index < cnt-1) {
                          $(kids[index+1]).addClass('sel')
                      } else if (index == cnt-1) {
                          $(kids[0]).addClass('sel')
                      }
                      return false;
                  }
              }
          });
          $(ta).parent().append(markup);
      };

      // append atta styles only once
      if ($('#atta-style').length < 1) {
          $('head').append('')
      }

      // bind accept and cancelation listener
      $(window).on('keyup', function(e) {
          if (cancelKey(e)) {
              cancel();
          } else if (acceptKey(e)) {
              var container = $('#atta-list-container');
              if (container.length > 0) {
                  var focused = $("*:focus");
                  console.log(focused);
                  e.preventDefault();
                  var name = container.find('.sel').text();
                  console.log('select ' + name);
                  cancel();
                  return false;
              }
          }
      });

      // bind query listener
      return self.each(function() {
          $(this).live('keyup', function (e) {
              var el = $(e.target);
              if (at.is(e)) {
                  showCompletions(e.target, completions() || []);
              } else {
                  var container = $("#atta-list-container");
                  if (container.length > 0) {
                      var txt = el.val(), query, matching, filteredCompletions;
                      if (txt.length > 0) {
                          var lastAt = txt.lastIndexOf(at.char);
                          if (lastAt != -1) {
                              query = txt.slice(lastAt + 1, txt.length);
                              matching = function(i, e) {
                                  return e.toLowerCase().indexOf(query.toLowerCase()) != -1;
                              }
                              filteredCompletions = (completions() || []).filter(matching);
                              showCompletions(el, filteredCompletions);
                          }
                      }
                  }
              }
          });
      });
  };
)(jQuery);<|endoftext|>


<commit_before>/*
 * Retro Game Night
 * Copyright (c) 2015 Andrew Reder, Cameron White, Chris Loeper
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

export default (FacebookStrategy, GoogleStrategy, rethinkdb, appconfig, passport) => {
  const GOOGLE_CLIENT_ID = appconfig.auth.google.clientID
  const GOOGLE_CLIENT_SECRET = appconfig.auth.google.clientSecret
  const FACEBOOK_CLIENT_ID = appconfig.auth.facebook.clientID
  const FACEBOOK_CLIENT_SECRET = appconfig.auth.facebook.clientSecret

  // Passport session setup.
  //   To support persistent login sessions, Passport needs to be able to
  //   serialize users into and deserialize users out of the session.  Typically,
  //   this will be as simple as storing the user ID when serializing, and finding
  //   the user by ID when deserializing.  However, since this example does not
  //   have a database of user records, the complete Google profile is
  //   serialized and deserialized.
  passport.serializeUser((user, done) => {
    done(null, user)
  })

  passport.deserializeUser((obj, done) => {
    done(null, obj)
  })

  const loginCallbackHandler = (objectMapper, type) =>
    (accessToken, refreshToken, profile, done) => {
      if (accessToken !== null) {
        rethinkdb
          .table('users')
          .getAll(profile.emails[0].value, { index: 'email' })
          //.filter({ type: type })
          .run(rethinkdb.conn)
          .then(cursor => {
            return cursor.toArray()
              .then(users => {
                if (users.length > 0) {
                  return done(null, users[0])
                }
                return rethinkdb.table('users')
                  .insert(objectMapper(profile))
                  .run(rethinkdb.conn)
                  .then(response => {
                    return rethinkdb.table('users')
                      .get(response.generated_keys[0])
                      .run(rethinkdb.conn)
                  })
                  .then(newUser => {
                    done(null, newUser)
                  })
              })
          })
          .catch(err => {
            console.log('Error Getting User', err)
          })
        }
      }
  // Use the GoogleStrategy within Passport.
  //   Strategies in Passport require a `verify` function, which accept
  //   credentials (in this case, an accessToken, refreshToken, and Google
  //   profile), and invoke a callback with a user object.
  passport.use(new GoogleStrategy({
      clientID: GOOGLE_CLIENT_ID,
      clientSecret: GOOGLE_CLIENT_SECRET,
      callbackURL: appconfig.auth.google.callbackURL,
    },
    loginCallbackHandler(profile => ({
            'name': profile.displayName || null,
            'email': profile.emails[0].value,
            'avatarUrl': profile.photos[0].value || '',
            'type': 'google',
            'createdAt': rethinkdb.now(),
        }), 'google')
  ))

  passport.use(new FacebookStrategy({
      clientID: FACEBOOK_CLIENT_ID,
      clientSecret: FACEBOOK_CLIENT_SECRET,
      callbackURL: appconfig.auth.facebook.callbackURL,
    },
    loginCallbackHandler(profile => ({
        'name': profile.displayName || null,
        'email': profile.emails[0].value,
        'avatarUrl': 'https://graph.facebook.com/' + profile.id + '/picture' || '',
        'type': 'facebook',
        'createdAt': rethinkdb.now(),
    }), 'facebook')
  ))
}<commit_msg>Fixed authentication/registration bug that was not allowing users<commit_after>/*
 * Retro Game Night
 * Copyright (c) 2015 Andrew Reder, Cameron White, Chris Loeper
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */
import appconfig from './config/appconfig'

export default (FacebookStrategy, GoogleStrategy, rethinkdb, appconfig, passport) => {
  const GOOGLE_CLIENT_ID = appconfig.auth.google.clientID
  const GOOGLE_CLIENT_SECRET = appconfig.auth.google.clientSecret
  const FACEBOOK_CLIENT_ID = appconfig.auth.facebook.clientID
  const FACEBOOK_CLIENT_SECRET = appconfig.auth.facebook.clientSecret

  // Passport session setup.
  //   To support persistent login sessions, Passport needs to be able to
  //   serialize users into and deserialize users out of the session.  Typically,
  //   this will be as simple as storing the user ID when serializing, and finding
  //   the user by ID when deserializing.  However, since this example does not
  //   have a database of user records, the complete Google profile is
  //   serialized and deserialized.
  passport.serializeUser((user, done) => {
    done(null, user)
  })

  passport.deserializeUser((obj, done) => {
    done(null, obj)
  })

  const loginCallbackHandler = (objectMapper, type) =>
    (accessToken, refreshToken, profile, done) => {
      if (accessToken !== null) {
        rethinkdb.connect(appconfig.rethinkdb, (err, conn) => {
          rethinkdb
            .table('users')
            .getAll(profile.emails[0].value, { index: 'email' })
            //.filter({ type: type })
            .run(conn)
            .then(cursor => {
              return cursor.toArray()
                .then(users => {
                  if (users.length > 0) {
                    return done(null, users[0])
                  }
                  return rethinkdb.table('users')
                    .insert(objectMapper(profile))
                    .run(conn)
                    .then(response => {
                      return rethinkdb.table('users')
                        .get(response.generated_keys[0])
                        .run(rethinkdb.conn)
                        .then(newUser => {
                          return done(null, newUser)
                        })
                    })
                })
              })
            })
            /*.catch(err => {
              console.log('Error Getting User', err)
            })*/
          }
        }

  // Use the GoogleStrategy within Passport.
  //   Strategies in Passport require a `verify` function, which accept
  //   credentials (in this case, an accessToken, refreshToken, and Google
  //   profile), and invoke a callback with a user object.
  passport.use(new GoogleStrategy({
      clientID: GOOGLE_CLIENT_ID,
      clientSecret: GOOGLE_CLIENT_SECRET,
      callbackURL: appconfig.auth.google.callbackURL,
    },
    loginCallbackHandler(profile => ({
            'name': profile.displayName || null,
            'email': profile.emails[0].value,
            'avatarUrl': profile.photos[0].value || '',
            'type': 'google',
            'createdAt': rethinkdb.now(),
        }), 'google')
  ))

  passport.use(new FacebookStrategy({
      clientID: FACEBOOK_CLIENT_ID,
      clientSecret: FACEBOOK_CLIENT_SECRET,
      callbackURL: appconfig.auth.facebook.callbackURL,
    },
    loginCallbackHandler(profile => ({
        'name': profile.displayName || null,
        'email': profile.emails[0].value,
        'avatarUrl': 'https://graph.facebook.com/' + profile.id + '/picture' || '',
        'type': 'facebook',
        'createdAt': rethinkdb.now(),
    }), 'facebook')
  ))
}<|endoftext|>


<commit_before>var config = require('./config.js');

function log(message){
	console.log("[LOG] ".green + message);
}

function warn(message){
	console.log("[WARN] ".red + message);
}

if (typeof String.prototype.startsWith !== 'function') {
	String.prototype.startsWith = function (str){
		return this.slice(0, str.length) == str;
	};
}

Array.prototype.contains = function(k, callback) {
    var self = this;
    return (function check(i) {
        if (i >= self.length) {
            return callback(false);
        }

        if (self[i] === k) {
            return callback(true);
        }

        return process.nextTick(check.bind(null, i+1));
    }(0));
}

Commands = [];

function processChatMessage(src, src2, msg, bot){
	if(msg !== ""){
		if(src2 !== undefined){
			console.log(("[CHAT " + src + "]").blue + " [" + bot.users[src2].playerName + "] " + msg);
		}else{
			console.log("[CHAT]".cyan + " [" + bot.users[src].playerName + "] " + msg);
		}
	}
	if(msg.startsWith("!help")){
		bot.sendMessage(src, "---- " + config.botName + " Commands ----");
		Commands.forEach(function(c){
			bot.sendMessage(src, c.params + " - " + c.help);
		});
	}else{
		Commands.forEach(function(c){
			if(c.regex.test(msg)){
				var steamId = src2 !== undefined ? src2 : src;
				c.action(src, msg, steamId);
				log(bot.users[steamId].playerName + " did command " + c.params);
			}
		});
	}
}

module.exports = {
	Command: function(regex, params, help, action){
		Commands.push({regex: regex, action: action, help: help, params: params});
	},
	processChatMessage: processChatMessage,
	isElevated: function(id){
		if(config.elevatedUsers.indexOf(id) !== -1)
			return true;
		return false;
	},
	elevatedUsers: function(bot){
		var users = [];
		config.elevatedUsers.forEach(function(id){
			users.push(id);
		});
		return users;
	},
	log: log,
	warn: warn,
	ChatErrors: {
		"1": "Success",
		"2": "Room doesn't exist",
		"3": "I'm not allowed to do that",
		"4": "Room is full",
		"5": "Unknown error",
		"6": "I'm banned from that room",
		"7": "I have limited account access (see https://support.steampowered.com/kb_article.php?ref=3330-IAGK-7663)",
		"8": "Clan disabled",
		"9": "I have been community banned",
		"10": "I've been blocked by you",
		"11": "I blocked you",
		"12": "Ranking data was not set",
		"13": "Ranking data was not set",
		"14": "My rank is invalid"
	}
};<commit_msg>keep going if command fails<commit_after>var config = require('./config.js');

function log(message){
	console.log("[LOG] ".green + message);
}

function warn(message){
	console.log("[WARN] ".red + message);
}

if (typeof String.prototype.startsWith !== 'function') {
	String.prototype.startsWith = function (str){
		return this.slice(0, str.length) == str;
	};
}

Array.prototype.contains = function(k, callback) {
    var self = this;
    return (function check(i) {
        if (i >= self.length) {
            return callback(false);
        }

        if (self[i] === k) {
            return callback(true);
        }

        return process.nextTick(check.bind(null, i+1));
    }(0));
}

Commands = [];

function processChatMessage(src, src2, msg, bot){
	if(msg !== ""){
		if(src2 !== undefined){
			console.log(("[CHAT " + src + "]").blue + " [" + bot.users[src2].playerName + "] " + msg);
		}else{
			console.log("[CHAT]".cyan + " [" + bot.users[src].playerName + "] " + msg);
		}
	}
	if(msg.startsWith("!help")){
		bot.sendMessage(src, "---- " + config.botName + " Commands ----");
		Commands.forEach(function(c){
			bot.sendMessage(src, c.params + " - " + c.help);
		});
	}else{
		Commands.forEach(function(c){
			if(c.regex.test(msg)){
				var steamId = src2 !== undefined ? src2 : src;
				try{
					c.action(src, msg, steamId);
				}catch(e){
					bot.sendMessage(src, "You broke something:\n" + e);
					warn("Error in command " + c.params + ": " + e);
				}
				log(bot.users[steamId].playerName + " did command " + c.params);
			}
		});
	}
}

module.exports = {
	Command: function(regex, params, help, action){
		Commands.push({regex: regex, action: action, help: help, params: params});
	},
	processChatMessage: processChatMessage,
	isElevated: function(id){
		if(config.elevatedUsers.indexOf(id) !== -1)
			return true;
		return false;
	},
	elevatedUsers: function(bot){
		var users = [];
		config.elevatedUsers.forEach(function(id){
			users.push(id);
		});
		return users;
	},
	log: log,
	warn: warn,
	ChatErrors: {
		"1": "Success",
		"2": "Room doesn't exist",
		"3": "I'm not allowed to do that",
		"4": "Room is full",
		"5": "Unknown error",
		"6": "I'm banned from that room",
		"7": "I have limited account access (see https://support.steampowered.com/kb_article.php?ref=3330-IAGK-7663)",
		"8": "Clan disabled",
		"9": "I have been community banned",
		"10": "I've been blocked by you",
		"11": "I blocked you",
		"12": "Ranking data was not set",
		"13": "Ranking data was not set",
		"14": "My rank is invalid"
	}
};<|endoftext|>