<commit_before>import React  from 'react';
import { render }  from 'react-dom';
import { Router, Route, IndexRoute, Link, hashHistory } from 'react-router';

import App from './components/App';
import Home from './components/Home';
import LoginForm from './components/LoginForm';
import Hello from './components/Hello';
import Routing from './components/Routing';
import Administration from './components/Administration';
import NotFound from './components/NotFound';

/*
  Routes
*/

function requireAuth(nextState, replace) {
  console.log('Testing auth-status')
  console.log(App.loggedIn())
  if (!App.loggedIn()) {
    console.log('No csrfToken found, asking for login')
    replace({
      pathname: '/login',
      state: {nextPathname: nextState.location.pathname }
    })
  }
}

function createHello(Hello, props) {
  return <Hello log={App.state.log} fetchLog={App.fetchLog} />
}

render((
  <Router history={hashHistory}>
    <Router createElement={createHello}/>
    <Route path="/" component={App}>
      <IndexRoute component={Home}/>
      <Route path="/login" component={LoginForm}/>
      <Route path="/hello" component={Hello}/>
      <Route path="/routing" component={Routing}/>
      <Route path="/administration" component={Administration}/>
      <Route path="*" component={NotFound}/>
    </Route>
  </Router>

), document.querySelector('#main'))
<commit_msg>stashy stash<commit_after>import React  from 'react';
import { render }  from 'react-dom';
import { Router, Route, IndexRoute, Link, hashHistory } from 'react-router';

import App from './components/App';
import Home from './components/Home';
import LoginForm from './components/LoginForm';
import Hello from './components/Hello';
import Routing from './components/Routing';
import Administration from './components/Administration';
import NotFound from './components/NotFound';

/*
  Main
*/

  function requireAuth(nextState, replace) {
    console.log('Testing auth-status')
    console.log(App.loggedIn())
    if (!App.loggedIn()) {
      console.log('No csrfToken found, asking for login')
      replace({
        pathname: '/login',
        state: {nextPathname: nextState.location.pathname }
      })
    }
  }

  function fetchLog() {
    console.log('Fetching Log from server')
    fetch('http://localhost:6543/hello', {
      credentials: 'include',
      headers: {
        'X-CSRF-TOKEN': this.state.csrfToken
      }
    }).then(r => r.json())
      .then(data => this.setState({
          log : data
      }, console.log(data)))
      .catch(e => console.log("Error"))
    }

  function createHello(Hello, props) {
    return <Hello log={App.state.log} fetchLog={fetchLog()} />
  }

  render((
    <Router history={hashHistory}>
      <Router createElement={createHello}/>
      <Route path="/" component={App}>
        <IndexRoute component={Home}/>
        <Route path="/login" component={LoginForm}/>
        <Route path="/hello" component={Hello}/>
        <Route path="/routing" component={Routing}/>
        <Route path="/administration" component={Administration}/>
        <Route path="*" component={NotFound}/>
      </Route>
    </Router>

  ), document.querySelector('#main'))
<|endoftext|>


<commit_before>function urlIsSupported( url, callback )
{
	getSupportedSite( url, function( site )
	{
		var isValid = false;

		if( site !== null )
		{
			for( var i in site.pages )
			{
				var page = site.pages[i];
				var parts = getUrlParts( url, page );

				if( parts !== null && parts.length == page.captureGroups + 1 )
				{
					isValid = true;
					break;
				}
			}
		}

		callback( isValid );
	});
}

function getSupportedSite( url, callback )
{
	getSupportedSiteList( function( siteList )
	{
		var site = null;
		if( siteList != null )
		{
			for( var i in siteList )
			{
				var tempSite = siteList[i];

				if( checkDomain( tempSite, url ) )
				{
					site = tempSite;
					break;
				}
			}
		}

		callback( site );
	});
}

function checkDomain( site, url )
{
	return site.domainRegex.test( url );
}

function getUrlParts( url, page )
{
	return page.capturePattern.exec( url );
}

function addPageToSite( page, site )
{
    var pageFound = false;
    for( var ii in site.pages )
    {
        var tempPage = site.pages[ii];
        if( tempPage.capturePattern.source === page.capturePattern.source )
        {
            pageFound = true;

            site.pages.splice( ii, 1 );
            site.pages.push( page );

            break;
        }
    }

    if( pageFound === false )
    {
        site.pages.push( page );
    }
}

function putSupportedSiteList( newSiteList )
{
	var tempSiteList = clone( newSiteList );

	for( var ii in tempSiteList )
	{
		delete tempSiteList.domainRegex;
		var pages = tempSiteList[ii].pages;
		for( var xx in pages )
		{
			pages[xx].capturePattern = pages[xx].capturePattern.source;
		}
	}

	chrome.storage.sync.set( {"supportedSites" : tempSiteList}, function()
	{
		if( saveDataErrorCheck() )
		{
			chrome.storage.sync.getBytesInUse("supportedSites", function( bytes ){ console.log( "Bytes in use: " + bytes ); });

			getSupportedSiteList.list = null;
			// Let the background page know the site list has been updated
			chrome.extension.sendMessage( {siteListUpdated: true} );
		}
	} );
}

function saveDataErrorCheck()
{
	var success = true;
	if( chrome.runtime.lastError !== undefined  )
	{
		success = false;
		console.log( chrome.runtime.lastError );
		alert( chrome.runtime.lastError.message );
	}
	return success;
}

function getSupportedSiteList( callback )
{
	if( getSupportedSiteList.list === null )
	{
		chrome.storage.sync.get( "supportedSites", function( data )
		{
			if( chrome.runtime.lastError === undefined )
			{
				getSupportedSiteList.list = data.supportedSites;

				for( var ii in getSupportedSiteList.list )
				{
					var site = getSupportedSiteList.list[ii];
					site.domainRegex = new RegExp( "^(?:http|https):\/\/(?:www.)?" + site.domain + ".*$", "i" );

					var pages = site.pages;
					for( var xx in pages )
					{
						pages[xx].capturePattern = new RegExp( pages[xx].capturePattern );
					}
				}

				if( callback !== undefined )
				{
					callback( getSupportedSiteList.list );
				}
			}
		} );
	}
	else
	{
		callback( getSupportedSiteList.list );
	}
}
getSupportedSiteList.list = null;

function invalidateSiteList()
{
	getSupportedSiteList.list = null;
	getSupportedSiteList();
}

function clone( obj )
{
	return $.extend(true, [], obj);
}

///////////////////////////////////////////////////////////
// Helper methods
///////////////////////////////////////////////////////////

function pruneDefaults( siteList )
{
    for( var ii=0; ii<siteList.length; ++ii )
    {
        var site = siteList[ii];
        if( site.isDefault === true )
        {
            for( var xx=0; xx<site.pages.length; ++xx )
            {
                var page = siteList[ii].pages[xx];
                if( page.isDefault === true )
                {
                    siteList[ii].pages.splice( xx, 1 );
					--xx;
                }
            }

            // If all the pages were defaults, then remove the whole site
            if( siteList[ii].pages.length === 0 )
            {
                siteList.splice( ii, 1 );
				--ii;
            }
        }
    }
}

function findSiteInDefaults( site, defaults )
{
    var defaultSite = null;
    for( var ii in defaults )
    {
        var tempSite = defaults[ii];
        if( tempSite.domain === site.domain )
        {
            defaultSite = tempSite;
            break;
        }
    }
    return defaultSite;
}<commit_msg>Added in some extra saftey<commit_after>function urlIsSupported( url, callback )
{
	getSupportedSite( url, function( site )
	{
		var isValid = false;

		if( site !== null )
		{
			for( var i in site.pages )
			{
				var page = site.pages[i];
				var parts = getUrlParts( url, page );

				if( parts !== null && parts.length == page.captureGroups + 1 )
				{
					isValid = true;
					break;
				}
			}
		}

		callback( isValid );
	});
}

function getSupportedSite( url, callback )
{
	getSupportedSiteList( function( siteList )
	{
		var site = null;
		if( siteList != null )
		{
			for( var i in siteList )
			{
				var tempSite = siteList[i];

				if( checkDomain( tempSite, url ) )
				{
					site = tempSite;
					break;
				}
			}
		}

		callback( site );
	});
}

function checkDomain( site, url )
{
	return site.domainRegex.test( url );
}

function getUrlParts( url, page )
{
	return page.capturePattern.exec( url );
}

function addPageToSite( page, site )
{
    var pageFound = false;
    for( var ii in site.pages )
    {
        var tempPage = site.pages[ii];
        if( tempPage.capturePattern.source === page.capturePattern.source )
        {
            pageFound = true;

            site.pages.splice( ii, 1 );
            site.pages.push( page );

            break;
        }
    }

    if( pageFound === false )
    {
        site.pages.push( page );
    }
}

function putSupportedSiteList( newSiteList )
{
	var tempSiteList = clone( newSiteList );

	for( var ii in tempSiteList )
	{
		delete tempSiteList.domainRegex;
		var pages = tempSiteList[ii].pages;
		for( var xx in pages )
		{
			pages[xx].capturePattern = pages[xx].capturePattern.source;
		}
	}

	chrome.storage.sync.set( {"supportedSites" : tempSiteList}, function()
	{
		if( saveDataErrorCheck() )
		{
			chrome.storage.sync.getBytesInUse("supportedSites", function( bytes ){ console.log( "Bytes in use: " + bytes ); });

			getSupportedSiteList.list = null;
			// Let the background page know the site list has been updated
			chrome.extension.sendMessage( {siteListUpdated: true} );
		}
	} );
}

function saveDataErrorCheck()
{
	var success = true;
	if( chrome.runtime.lastError !== undefined  )
	{
		success = false;
		console.log( chrome.runtime.lastError );
		alert( chrome.runtime.lastError.message );
	}
	return success;
}

function getSupportedSiteList( callback )
{
	if( getSupportedSiteList.list === null )
	{
		chrome.storage.sync.get( "supportedSites", function( data )
		{
			if( chrome.runtime.lastError === undefined )
			{
				getSupportedSiteList.list = data.supportedSites;

				for( var ii in getSupportedSiteList.list )
				{
					var site = getSupportedSiteList.list[ii];
					site.domainRegex = new RegExp( "^(?:http|https):\/\/(?:www.)?" + site.domain + ".*$", "i" );

					var pages = site.pages;
					for( var xx in pages )
					{
						pages[xx].capturePattern = new RegExp( pages[xx].capturePattern );
					}
				}

				if( callback !== undefined )
				{
					callback( getSupportedSiteList.list );
				}
			}
		} );
	}
	else
	{
		if( callback !== undefined )
		{
			callback( getSupportedSiteList.list );
		}
	}
}
getSupportedSiteList.list = null;

function invalidateSiteList()
{
	getSupportedSiteList.list = null;
	getSupportedSiteList();
}

function clone( obj )
{
	return $.extend(true, [], obj);
}

///////////////////////////////////////////////////////////
// Helper methods
///////////////////////////////////////////////////////////

function pruneDefaults( siteList )
{
    for( var ii=0; ii<siteList.length; ++ii )
    {
        var site = siteList[ii];
        if( site.isDefault === true )
        {
            for( var xx=0; xx<site.pages.length; ++xx )
            {
                var page = siteList[ii].pages[xx];
                if( page.isDefault === true )
                {
                    siteList[ii].pages.splice( xx, 1 );
					--xx;
                }
            }

            // If all the pages were defaults, then remove the whole site
            if( siteList[ii].pages.length === 0 )
            {
                siteList.splice( ii, 1 );
				--ii;
            }
        }
    }
}

function findSiteInDefaults( site, defaults )
{
    var defaultSite = null;
    for( var ii in defaults )
    {
        var tempSite = defaults[ii];
        if( tempSite.domain === site.domain )
        {
            defaultSite = tempSite;
            break;
        }
    }
    return defaultSite;
}<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');
    gvm.lastIdFromDb = -1;
    gvm.lastId = -1;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectCompletenessTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectCompletenessTitle");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.documents = ko.observableArray([]);

    gvm.addDocument = function(id, description, amount_required, weight) {
        var document = {id: id, description: description, amount_required: amount_required, weight: weight};
        gvm.documents.push(document);

        $('#removebtn-' + id).bind('click', function(event, data) {
            gvm.removeDocument(id, document);
            event.stopPropagation();
        });
    };

    gvm.addDocumentToSubmit = function() {
        ++gvm.lastId;
        gvm.addDocument(gvm.lastId, "", "", "");
    };

    gvm.getDocumentsToSubmit = function() {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents', function(data) {
            $.each(data, function(i, item) {
                gvm.addDocument(item.id, item.description, item.amount_required, item.weight);
                gvm.lastIdFromDb = item.id;
                gvm.lastId = item.id;
            });
        });
    };

    gvm.removeDocument = function(id, document) {
        if(id <= gvm.lastIdFromDb) {
            $.ajax({
                url: "/api/delete/document/" + id,
                type: "DELETE",
                success: function() {
                    gvm.documents.remove(document);
                }
            });
        } else {
            gvm.documents.remove(document);
        }
    };

    gvm.saveDocumentsToSubmit = function() {
        console.log("/api/project/" + gvm.projectId + "/documents/" + gvm.lastId);
        var data = [];
        ko.utils.arrayForEach(gvm.documents(), function(document) {
            var obj = {
                "id": document.id,
                "description": document.description,
                "amount_required": document.amount_required,
                "weight": document.weight
            };
            data.push(obj);
        });
        console.log(data);
        $.ajax({
            url: "/api/project/" + gvm.projectId + "/documents/" + gvm.lastId,
            type: "PUT",

            success: function() {
                console.log("success");
            },
            error: function() {
                console.log("error");
            }
        });
    };
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getDocumentsToSubmit();
}<commit_msg>completeness page<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');
    gvm.lastIdFromDb = -1;
    gvm.lastId = -1;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectCompletenessTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectCompletenessTitle");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.documents = ko.observableArray([]);

    gvm.addDocument = function(id, description, amount_required, weight) {
        var document = {id: id, description: description, amount_required: amount_required, weight: weight};
        gvm.documents.push(document);

        $('#removebtn-' + id).bind('click', function(event, data) {
            gvm.removeDocument(id, document);
            event.stopPropagation();
        });
    };

    gvm.addDocumentToSubmit = function() {
        ++gvm.lastId;
        gvm.addDocument(gvm.lastId, "", "", "");
    };

    gvm.getDocumentsToSubmit = function() {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents', function(data) {
            $.each(data, function(i, item) {
                gvm.addDocument(item.id, item.description, item.amount_required, item.weight);
                gvm.lastIdFromDb = item.id;
                gvm.lastId = item.id;
            });
        });
    };

    gvm.removeDocument = function(id, document) {
        if(id <= gvm.lastIdFromDb) {
            $.ajax({
                url: "/api/delete/document/" + id,
                type: "DELETE",
                success: function() {
                    gvm.documents.remove(document);
                }
            });
        } else {
            gvm.documents.remove(document);
        }
    };

    gvm.saveDocumentsToSubmit = function() {
        console.log("/api/project/" + gvm.projectId + "/documents/" + gvm.lastId);
        var data = [];
        console.log(gvm.documents);
        ko.utils.arrayForEach(gvm.documents(), function(document) {
            var obj = {
                "id": document.id,
                "description": document.description,
                "amount_required": document.amount_required,
                "weight": document.weight
            };
            data.push(obj);
        });
        console.log(data);
        $.ajax({
            url: "/api/project/" + gvm.projectId + "/documents/" + gvm.lastId,
            type: "PUT",

            success: function() {
                console.log("success");
            },
            error: function() {
                console.log("error");
            }
        });
    };
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getDocumentsToSubmit();
}<|endoftext|>


<commit_before>"use strict"; // run code in ES5 strict mode

var spawn = require("child_process").spawn,
    _ = require("underscore");

function runCreateBundle(config, callback) {

    var createBundleProcess;

    createBundleProcess = spawn("node", ["createBundle.js"], {
        cwd: __dirname,
        env: _(config).extend(process.env)
    });
    createBundleProcess.stdout.pipe(process.stdout);
    createBundleProcess.stderr.pipe(process.stderr);
    createBundleProcess.on("exit", function onProcessExit(code) {
        if (code !== 0) {
            callback(new Error("(alamid) Bundle creation failed"));
            return;
        }

        callback(null);
    });
}

module.exports = runCreateBundle;<commit_msg>- runCreateBundle: using fork now, to pass config to child process<commit_after>"use strict"; // run code in ES5 strict mode

var fork = require("child_process").fork,
    _ = require("underscore");

/**
 * call the bundler as a separate forked process
 * pass config via message to forked process
 *
 * @param {!Object} config server-config
 * @param {!Function} callback
 */
function runCreateBundle(config, callback) {

    var createBundleProcess;

    createBundleProcess = fork(__dirname + "/createBundle.js", {
        cwd: __dirname
    });

    //send config to start bundle process
    createBundleProcess.send(config);
    createBundleProcess.on("exit", function onProcessExit(code) {
        if (code !== 0) {
            callback(new Error("(alamid) Bundle creation failed"));
            return;
        }

        callback(null);
    });
}

module.exports = runCreateBundle;<|endoftext|>


<commit_before>// script generated by /scripts/make_ast_classes.py
(function($B){

// --- start AST classes
$B.ast_classes = {
Add:'',
And:'',
AnnAssign:'target,annotation,value?,simple',
Assert:'test,msg?',
Assign:'targets*,value,type_comment?',
AsyncFor:'target,iter,body*,orelse*,type_comment?',
AsyncFunctionDef:'name,args,body*,decorator_list*,returns?,type_comment?',
AsyncWith:'items*,body*,type_comment?',
Attribute:'value,attr,ctx',
AugAssign:'target,op,value',
Await:'value',
BinOp:'left,op,right',
BitAnd:'',
BitOr:'',
BitXor:'',
BoolOp:'op,values*',
Break:'',
Call:'func,args*,keywords*',
ClassDef:'name,bases*,keywords*,body*,decorator_list*',
Compare:'left,ops*,comparators*',
Constant:'value,kind?',
Continue:'',
Del:'',
Delete:'targets*',
Dict:'keys*,values*',
DictComp:'key,value,generators*',
Div:'',
Eq:'',
ExceptHandler:'type?,name?,body*',
Expr:'value',
Expression:'body',
FloorDiv:'',
For:'target,iter,body*,orelse*,type_comment?',
FormattedValue:'value,conversion,format_spec?',
FunctionDef:'name,args,body*,decorator_list*,returns?,type_comment?',
FunctionType:'argtypes*,returns',
GeneratorExp:'elt,generators*',
Global:'names*',
Gt:'',
GtE:'',
If:'test,body*,orelse*',
IfExp:'test,body,orelse',
Import:'names*',
ImportFrom:'module?,names*,level?',
In:'',
Interactive:'body*',
Invert:'',
Is:'',
IsNot:'',
JoinedStr:'values*',
LShift:'',
Lambda:'args,body',
List:'elts*,ctx',
ListComp:'elt,generators*',
Load:'',
Lt:'',
LtE:'',
MatMult:'',
Match:'subject,cases*',
MatchAs:'pattern?,name?',
MatchClass:'cls,patterns*,kwd_attrs*,kwd_patterns*',
MatchMapping:'keys*,patterns*,rest?',
MatchOr:'patterns*',
MatchSequence:'patterns*',
MatchSingleton:'value',
MatchStar:'name?',
MatchValue:'value',
Mod:'',
Module:'body*,type_ignores*',
Mult:'',
Name:'id,ctx',
NamedExpr:'target,value',
Nonlocal:'names*',
Not:'',
NotEq:'',
NotIn:'',
Or:'',
Pass:'',
Pow:'',
RShift:'',
Raise:'exc?,cause?',
Return:'value?',
Set:'elts*',
SetComp:'elt,generators*',
Slice:'lower?,upper?,step?',
Starred:'value,ctx',
Store:'',
Sub:'',
Subscript:'value,slice,ctx',
Try:'body*,handlers*,orelse*,finalbody*',
Tuple:'elts*,ctx',
TypeIgnore:'lineno,tag',
UAdd:'',
USub:'',
UnaryOp:'op,operand',
While:'test,body*,orelse*',
With:'items*,body*,type_comment?',
Yield:'value?',
YieldFrom:'value',
alias:'name,asname?',
arg:'arg,annotation?,type_comment?',
arguments:'posonlyargs*,args*,vararg?,kwonlyargs*,kw_defaults*,kwarg?,defaults*',
boolop:['And','Or'],
cmpop:['Eq','NotEq','Lt','LtE','Gt','GtE','Is','IsNot','In','NotIn'],
comprehension:'target,iter,ifs*,is_async',
excepthandler:['ExceptHandler'],
expr:['BoolOp','NamedExpr','BinOp','UnaryOp','Lambda','IfExp','Dict','Set','ListComp','SetComp','DictComp','GeneratorExp','Await','Yield','YieldFrom','Compare','Call','FormattedValue','JoinedStr','Constant','Attribute','Subscript','Starred','Name','List','Tuple','Slice'],
expr_context:['Load','Store','Del'],
keyword:'arg?,value',
match_case:'pattern,guard?,body*',
mod:['Module','Interactive','Expression','FunctionType'],
operator:['Add','Sub','Mult','MatMult','Div','Mod','Pow','LShift','RShift','BitOr','BitXor','BitAnd','FloorDiv'],
pattern:['MatchValue','MatchSingleton','MatchSequence','MatchMapping','MatchClass','MatchStar','MatchAs','MatchOr'],
stmt:['FunctionDef','AsyncFunctionDef','ClassDef','Return','Delete','Assign','AugAssign','AnnAssign','For','AsyncFor','While','If','With','AsyncWith','Match','Raise','Try','Assert','Import','ImportFrom','Global','Nonlocal','Expr','Pass','Break','Continue'],
type_ignore:['TypeIgnore'],
unaryop:['Invert','Not','UAdd','USub'],
withitem:'context_expr,optional_vars?'
}
// --- end AST classes

// binary operator tokens
var binary_ops = {
    '+': 'Add', '-': 'Sub', '*': 'Mult', '/': 'Div', '//': 'FloorDiv',
    '%': 'Mod', '**': 'Pow', '<<': 'LShift', '>>': 'RShift', '|': 'BitOr',
    '^': 'BitXor', '&': 'BitAnd', '@': 'MatMult'
    }

// boolean operator tokens
var boolean_ops = {'and': 'And', 'or': 'Or'}

// comparison operator tokens
var comparison_ops = {
    '==': 'Eq', '!=': 'NotEq', '<': 'Lt', '<=': 'LtE', '>': 'Gt', '>=': 'GtE',
    'is': 'Is', 'is_not': 'IsNot', 'in': 'In', 'not_in': 'NotIn'}

var unary_ops = {unary_inv: 'Invert', unary_pos: 'UAdd', unary_neg: 'USub'}

var op_types = $B.op_types = [binary_ops, boolean_ops, comparison_ops, unary_ops]

var _b_ = $B.builtins

var ast = $B.ast = {}

for(var kl in $B.ast_classes){
    var args = $B.ast_classes[kl],
        js = ''
    if(typeof args == "string"){
        js = `ast.${kl} = function(${args.replace(/[*?]/g, '')}){
`
        if(args.length > 0){
            for(var arg of args.split(',')){
                if(arg.endsWith('*')){
                   arg = arg.substr(0, arg.length - 1)
                   js += ` this.${arg} = ${arg} === undefined ? [] : ${arg}
`
                }else if(arg.endsWith('?')){
                   arg = arg.substr(0, arg.length - 1)
                   js += ` this.${arg} = ${arg}
`
                }else{
                    js += ` this.${arg} = ${arg}
`
                }
            }
        }
        js += '}'
    }else{
        js = `ast.${kl} = [${args.map(x => 'ast.' + x).join(',')}]
`
    }
    try{
        eval(js)
    }catch(err){
        console.log('error', js)
        throw err
    }
    ast[kl].$name = kl
    if(typeof args == "string"){
        ast[kl]._fields = args.split(',')
    }
}

// Function that creates Python ast instances for ast objects generated by
// method .ast() of classes in py2js.js
$B.ast_js_to_py = function(obj){
    $B.create_python_ast_classes()
    if(obj === undefined){
        return _b_.None
    }else if(Array.isArray(obj)){
        return obj.map($B.ast_js_to_py)
    }else{
        var class_name = obj.constructor.$name,
            py_class = $B.python_ast_classes[class_name],
            py_ast_obj = {
                __class__: py_class
            }
        if(py_class === undefined){
            return obj
        }
        for(var field of py_class._fields){
            py_ast_obj[field] = $B.ast_js_to_py(obj[field])
        }
        py_ast_obj._attributes = $B.fast_tuple([])
        for(var loc of ['lineno', 'col_offset',
                        'end_lineno', 'end_col_offset']){
            if(obj[loc] !== undefined){
                py_ast_obj[loc] = obj[loc]
                py_ast_obj._attributes.push(loc)
            }
        }
        return py_ast_obj
    }
}

$B.ast_py_to_js = function(obj){
    if(obj === undefined || obj === _b_.None){
        return undefined
    }else if(Array.isArray(obj)){
        return obj.map($B.ast_py_to_js)
    }else if(typeof obj == "string"){
        return obj
    }else{
        var class_name = obj.__class__.$infos.__name__,
            js_class = $B.ast[class_name]
        if(js_class === undefined){
            return obj
        }
        var js_ast_obj = new js_class()
        for(var field of js_class._fields){
            if(field.endsWith('?') || field.endsWith('*')){
                field = field.substr(0, field.length - 1)
            }
            js_ast_obj[field] = $B.ast_py_to_js(obj[field])
        }
        for(var loc of ['lineno', 'col_offset',
                        'end_lineno', 'end_col_offset']){
            if(obj[loc] !== undefined){
                js_ast_obj[loc] = obj[loc]
            }
        }
        return js_ast_obj
    }
}

$B.create_python_ast_classes = function(){
    if($B.python_ast_classes){
        return
    }
    $B.python_ast_classes = {}
    for(var klass in $B.ast_classes){
        $B.python_ast_classes[klass] = (function(kl){
            var _fields,
                raw_fields
            if(typeof $B.ast_classes[kl] == "string"){
                if($B.ast_classes[kl] == ''){
                    raw_fields = _fields = []
                }else{
                    raw_fields = $B.ast_classes[kl].split(',')
                    _fields = raw_fields.map(x =>
                        (x.endsWith('*') || x.endsWith('?')) ?
                        x.substr(0, x.length - 1) : x)
                }
            }
            var cls = $B.make_class(kl),
                $defaults = {},
                slots = {},
                nb_args = 0
            if(raw_fields){
                for(var i = 0, len = _fields.length; i < len; i++){
                    var f = _fields[i],
                        rf = raw_fields[i]
                    nb_args++
                    slots[f] = null
                    if(rf.endsWith('*')){
                        $defaults[f] = []
                    }else if(rf.endsWith('?')){
                        $defaults[f] = _b_.None
                    }
                }
            }

            cls.$factory = function(){
                var $ = $B.args(klass, nb_args, $B.clone(slots), Object.keys(slots),
                        arguments, $B.clone($defaults), null, 'kw')
                var res = {
                    __class__: cls,
                    _attributes: $B.fast_tuple([])
                }
                for(var key in $){
                    if(key == 'kw'){
                        for(var key in $.kw.$string_dict){
                            res[key] = $.kw.$string_dict[key][0]
                        }
                    }else{
                        res[key] = $[key]
                    }
                }
                if(klass == "Constant"){
                    res.value = $B.AST.$convert($.value)
                }
                return res
            }
            if(_fields){
                cls._fields = _fields
            }
            cls.__mro__ = [$B.AST, _b_.object]
            cls.__module__ = 'ast'
            return cls
        })(klass)
    }
}

// Map operators to ast type (BinOp, etc.) and name (Add, etc.)
var op2ast_class = $B.op2ast_class = {},
    ast_types = [ast.BinOp, ast.BoolOp, ast.Compare, ast.UnaryOp]
for(var i = 0; i < 4; i++){
    for(var op in op_types[i]){
        op2ast_class[op] = [ast_types[i], ast[op_types[i][op]]]
    }
}

})(__BRYTHON__)
<commit_msg>Update py_ast.js based on Python 3.11 Python.asdl (add TryStar)<commit_after>// script generated by /scripts/make_ast_classes.py
(function($B){

// --- start AST classes
$B.ast_classes = {
Add:'',
And:'',
AnnAssign:'target,annotation,value?,simple',
Assert:'test,msg?',
Assign:'targets*,value,type_comment?',
AsyncFor:'target,iter,body*,orelse*,type_comment?',
AsyncFunctionDef:'name,args,body*,decorator_list*,returns?,type_comment?',
AsyncWith:'items*,body*,type_comment?',
Attribute:'value,attr,ctx',
AugAssign:'target,op,value',
Await:'value',
BinOp:'left,op,right',
BitAnd:'',
BitOr:'',
BitXor:'',
BoolOp:'op,values*',
Break:'',
Call:'func,args*,keywords*',
ClassDef:'name,bases*,keywords*,body*,decorator_list*',
Compare:'left,ops*,comparators*',
Constant:'value,kind?',
Continue:'',
Del:'',
Delete:'targets*',
Dict:'keys*,values*',
DictComp:'key,value,generators*',
Div:'',
Eq:'',
ExceptHandler:'type?,name?,body*',
Expr:'value',
Expression:'body',
FloorDiv:'',
For:'target,iter,body*,orelse*,type_comment?',
FormattedValue:'value,conversion,format_spec?',
FunctionDef:'name,args,body*,decorator_list*,returns?,type_comment?',
FunctionType:'argtypes*,returns',
GeneratorExp:'elt,generators*',
Global:'names*',
Gt:'',
GtE:'',
If:'test,body*,orelse*',
IfExp:'test,body,orelse',
Import:'names*',
ImportFrom:'module?,names*,level?',
In:'',
Interactive:'body*',
Invert:'',
Is:'',
IsNot:'',
JoinedStr:'values*',
LShift:'',
Lambda:'args,body',
List:'elts*,ctx',
ListComp:'elt,generators*',
Load:'',
Lt:'',
LtE:'',
MatMult:'',
Match:'subject,cases*',
MatchAs:'pattern?,name?',
MatchClass:'cls,patterns*,kwd_attrs*,kwd_patterns*',
MatchMapping:'keys*,patterns*,rest?',
MatchOr:'patterns*',
MatchSequence:'patterns*',
MatchSingleton:'value',
MatchStar:'name?',
MatchValue:'value',
Mod:'',
Module:'body*,type_ignores*',
Mult:'',
Name:'id,ctx',
NamedExpr:'target,value',
Nonlocal:'names*',
Not:'',
NotEq:'',
NotIn:'',
Or:'',
Pass:'',
Pow:'',
RShift:'',
Raise:'exc?,cause?',
Return:'value?',
Set:'elts*',
SetComp:'elt,generators*',
Slice:'lower?,upper?,step?',
Starred:'value,ctx',
Store:'',
Sub:'',
Subscript:'value,slice,ctx',
Try:'body*,handlers*,orelse*,finalbody*',
TryStar:'body*,handlers*,orelse*,finalbody*',
Tuple:'elts*,ctx',
TypeIgnore:'lineno,tag',
UAdd:'',
USub:'',
UnaryOp:'op,operand',
While:'test,body*,orelse*',
With:'items*,body*,type_comment?',
Yield:'value?',
YieldFrom:'value',
alias:'name,asname?',
arg:'arg,annotation?,type_comment?',
arguments:'posonlyargs*,args*,vararg?,kwonlyargs*,kw_defaults*,kwarg?,defaults*',
boolop:['And','Or'],
cmpop:['Eq','NotEq','Lt','LtE','Gt','GtE','Is','IsNot','In','NotIn'],
comprehension:'target,iter,ifs*,is_async',
excepthandler:['ExceptHandler'],
expr:['BoolOp','NamedExpr','BinOp','UnaryOp','Lambda','IfExp','Dict','Set','ListComp','SetComp','DictComp','GeneratorExp','Await','Yield','YieldFrom','Compare','Call','FormattedValue','JoinedStr','Constant','Attribute','Subscript','Starred','Name','List','Tuple','Slice'],
expr_context:['Load','Store','Del'],
keyword:'arg?,value',
match_case:'pattern,guard?,body*',
mod:['Module','Interactive','Expression','FunctionType'],
operator:['Add','Sub','Mult','MatMult','Div','Mod','Pow','LShift','RShift','BitOr','BitXor','BitAnd','FloorDiv'],
pattern:['MatchValue','MatchSingleton','MatchSequence','MatchMapping','MatchClass','MatchStar','MatchAs','MatchOr'],
stmt:['FunctionDef','AsyncFunctionDef','ClassDef','Return','Delete','Assign','AugAssign','AnnAssign','For','AsyncFor','While','If','With','AsyncWith','Match','Raise','Try','TryStar','Assert','Import','ImportFrom','Global','Nonlocal','Expr','Pass','Break','Continue'],
type_ignore:['TypeIgnore'],
unaryop:['Invert','Not','UAdd','USub'],
withitem:'context_expr,optional_vars?'
}
// --- end AST classes

// binary operator tokens
var binary_ops = {
    '+': 'Add', '-': 'Sub', '*': 'Mult', '/': 'Div', '//': 'FloorDiv',
    '%': 'Mod', '**': 'Pow', '<<': 'LShift', '>>': 'RShift', '|': 'BitOr',
    '^': 'BitXor', '&': 'BitAnd', '@': 'MatMult'
    }

// boolean operator tokens
var boolean_ops = {'and': 'And', 'or': 'Or'}

// comparison operator tokens
var comparison_ops = {
    '==': 'Eq', '!=': 'NotEq', '<': 'Lt', '<=': 'LtE', '>': 'Gt', '>=': 'GtE',
    'is': 'Is', 'is_not': 'IsNot', 'in': 'In', 'not_in': 'NotIn'}

var unary_ops = {unary_inv: 'Invert', unary_pos: 'UAdd', unary_neg: 'USub'}

var op_types = $B.op_types = [binary_ops, boolean_ops, comparison_ops, unary_ops]

var _b_ = $B.builtins

var ast = $B.ast = {}

for(var kl in $B.ast_classes){
    var args = $B.ast_classes[kl],
        js = ''
    if(typeof args == "string"){
        js = `ast.${kl} = function(${args.replace(/[*?]/g, '')}){
`
        if(args.length > 0){
            for(var arg of args.split(',')){
                if(arg.endsWith('*')){
                   arg = arg.substr(0, arg.length - 1)
                   js += ` this.${arg} = ${arg} === undefined ? [] : ${arg}
`
                }else if(arg.endsWith('?')){
                   arg = arg.substr(0, arg.length - 1)
                   js += ` this.${arg} = ${arg}
`
                }else{
                    js += ` this.${arg} = ${arg}
`
                }
            }
        }
        js += '}'
    }else{
        js = `ast.${kl} = [${args.map(x => 'ast.' + x).join(',')}]
`
    }
    try{
        eval(js)
    }catch(err){
        console.log('error', js)
        throw err
    }
    ast[kl].$name = kl
    if(typeof args == "string"){
        ast[kl]._fields = args.split(',')
    }
}

// Function that creates Python ast instances for ast objects generated by
// method .ast() of classes in py2js.js
$B.ast_js_to_py = function(obj){
    $B.create_python_ast_classes()
    if(obj === undefined){
        return _b_.None
    }else if(Array.isArray(obj)){
        return obj.map($B.ast_js_to_py)
    }else{
        var class_name = obj.constructor.$name,
            py_class = $B.python_ast_classes[class_name],
            py_ast_obj = {
                __class__: py_class
            }
        if(py_class === undefined){
            return obj
        }
        for(var field of py_class._fields){
            py_ast_obj[field] = $B.ast_js_to_py(obj[field])
        }
        py_ast_obj._attributes = $B.fast_tuple([])
        for(var loc of ['lineno', 'col_offset',
                        'end_lineno', 'end_col_offset']){
            if(obj[loc] !== undefined){
                py_ast_obj[loc] = obj[loc]
                py_ast_obj._attributes.push(loc)
            }
        }
        return py_ast_obj
    }
}

$B.ast_py_to_js = function(obj){
    if(obj === undefined || obj === _b_.None){
        return undefined
    }else if(Array.isArray(obj)){
        return obj.map($B.ast_py_to_js)
    }else if(typeof obj == "string"){
        return obj
    }else{
        var class_name = obj.__class__.$infos.__name__,
            js_class = $B.ast[class_name]
        if(js_class === undefined){
            return obj
        }
        var js_ast_obj = new js_class()
        for(var field of js_class._fields){
            if(field.endsWith('?') || field.endsWith('*')){
                field = field.substr(0, field.length - 1)
            }
            js_ast_obj[field] = $B.ast_py_to_js(obj[field])
        }
        for(var loc of ['lineno', 'col_offset',
                        'end_lineno', 'end_col_offset']){
            if(obj[loc] !== undefined){
                js_ast_obj[loc] = obj[loc]
            }
        }
        return js_ast_obj
    }
}

$B.create_python_ast_classes = function(){
    if($B.python_ast_classes){
        return
    }
    $B.python_ast_classes = {}
    for(var klass in $B.ast_classes){
        $B.python_ast_classes[klass] = (function(kl){
            var _fields,
                raw_fields
            if(typeof $B.ast_classes[kl] == "string"){
                if($B.ast_classes[kl] == ''){
                    raw_fields = _fields = []
                }else{
                    raw_fields = $B.ast_classes[kl].split(',')
                    _fields = raw_fields.map(x =>
                        (x.endsWith('*') || x.endsWith('?')) ?
                        x.substr(0, x.length - 1) : x)
                }
            }
            var cls = $B.make_class(kl),
                $defaults = {},
                slots = {},
                nb_args = 0
            if(raw_fields){
                for(var i = 0, len = _fields.length; i < len; i++){
                    var f = _fields[i],
                        rf = raw_fields[i]
                    nb_args++
                    slots[f] = null
                    if(rf.endsWith('*')){
                        $defaults[f] = []
                    }else if(rf.endsWith('?')){
                        $defaults[f] = _b_.None
                    }
                }
            }

            cls.$factory = function(){
                var $ = $B.args(klass, nb_args, $B.clone(slots), Object.keys(slots),
                        arguments, $B.clone($defaults), null, 'kw')
                var res = {
                    __class__: cls,
                    _attributes: $B.fast_tuple([])
                }
                for(var key in $){
                    if(key == 'kw'){
                        for(var key in $.kw.$string_dict){
                            res[key] = $.kw.$string_dict[key][0]
                        }
                    }else{
                        res[key] = $[key]
                    }
                }
                if(klass == "Constant"){
                    res.value = $B.AST.$convert($.value)
                }
                return res
            }
            if(_fields){
                cls._fields = _fields
            }
            cls.__mro__ = [$B.AST, _b_.object]
            cls.__module__ = 'ast'
            return cls
        })(klass)
    }
}

// Map operators to ast type (BinOp, etc.) and name (Add, etc.)
var op2ast_class = $B.op2ast_class = {},
    ast_types = [ast.BinOp, ast.BoolOp, ast.Compare, ast.UnaryOp]
for(var i = 0; i < 4; i++){
    for(var op in op_types[i]){
        op2ast_class[op] = [ast_types[i], ast[op_types[i][op]]]
    }
}

})(__BRYTHON__)
<|endoftext|>


<commit_before>var request = require('superagent');
const twilio = require('twilio')(process.env.TWILIO_SID, process.env.TWILIO_TOKEN);
const Restaurant = require('../models/Restaurant');
const Product = require('../models/Product');
const PhoneNumber = require('../models/PhoneNumber');

var mailchimpInstance   = process.env.MAILCHIMP_INSTANCE
    listUniqueId        = process.env.MAILCHIMP_UID,
    mailchimpApiKey     = process.env.MAILCHIMP_APIKEY;

/**
 * GET /
 * Home page.
 */
exports.index = (req, res) => {
  var start = new Date();
  start.setHours(0,0,0,0);
  var end = new Date();
  end.setHours(23,59,59,999);
  findProducts(16, 0, (err, products) => {
    if (err) {
      req.flash('errors', err);
        res.render('home', {
        title: 'Raddamaten'
      });
    } else {
      res.render('home', {
        title: 'Raddamaten',
        products: products
      });
    }
  });
};

/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items The array containing the items.
 */
function shuffle(array) {
    var a = array;
    for (let i = a.length; i; i--) {
        let j = Math.floor(Math.random() * i);
        [a[i - 1], a[j]] = [a[j], a[i - 1]];
    }
    return a;
}

/**
 * GET /products/5
 * Products list page.
 */
exports.getProducts = (req, res) => {
    var start = new Date();
    start.setHours(0,0,0,0);
    var end = new Date();
    end.setHours(23,59,59,999);
    const limit = parseInt(req.query.limit) || 16;
    const currentCount = parseInt(req.params.currentCount);
    findProducts(limit, currentCount, (err, products) => {
        if (err) {
            //callback function return error
            return res.sendStatus(500);
        } else {
            //successfully braunch
            res.render('products/products', {
                title: 'Produkter',
                products: products
            });
        }
    });
};

function findProducts(limit, currentCount, callback) {
    var start = new Date();
    start.setHours(0,0,0,0);
    var end = new Date();
    end.setHours(23,59,59,999);
    Product.find({$and:[{startdate:{$lte:end}},{enddate:{$gte:start}}]}, null,
    {limit: limit, skip: currentCount, sort: { enddate: 1 }}, (err, products) => {
        if (err) {
          return callback(err);
        } else {
          return callback(null, products);
        }
    });
}

/**
 * GET /about
 * About page.
 */
exports.about = (req, res) => {
  return res.render('about', {
    title: 'Om',
  });
};

/**
 * GET /terms
 * Terms page.
 */
exports.terms = (req, res) => {
  return res.render('terms', {
    title: 'Villkor',
  });
};

/**
 * GET /press
 * Press page.
 */
exports.press = (req, res) => {
  return res.render('press', {
    title: 'Press',
  });
};

/**
 * GET /faq
 * FAQ page.
 */
exports.faq = (req, res) => {
  return res.render('faq', {
    title: 'FAQ',
  });
};

/**
 * GET /connect
 * Connect Restaurant page.
 */
exports.connect = (req, res) => {
  return res.render('connect', {
    title: 'Anslut din restaurang',
  });
};

/**
 * GET /partners
 * View Partners Restaurant page.
 */
exports.getPartners = (req, res) => {
  Restaurant.find({}, (err, restaurants) => {
    return res.render('partners', {
      title: 'Anslutna restauranger',
      restaurants: restaurants
    })
  })
}

/**
 * POST /mailinglist/add
 * Add to mailinglist
 * This function should be called with ajax or similar
 */
exports.addToMailingList = (req, res) => {
  request
        .post('https://' + mailchimpInstance + '.api.mailchimp.com/3.0/lists/' + listUniqueId + '/members/')
        .set('Content-Type', 'application/json;charset=utf-8')
        .set('Authorization', 'Basic ' + new Buffer('any:' + mailchimpApiKey ).toString('base64'))
        .send({
          'email_address': req.body.email,
          'status': 'pending'
        }).end(function(err, response) {
          if (response.status < 300 || (response.status === 400 && response.body.title === "Member Exists")) {
            return res.sendStatus(200);
          } else {
            return res.sendStatus(400);
          }
      });
};

/**
 * GET /sms/add
 * Add to numbers (sms)
 * This function should be called with ajax or similar
 */
exports.addToSmsNumber = (req, res) => {
  const number = req.body.number;

  const phoneNumber = PhoneNumber({
    number: number
  });

  PhoneNumber.find({$and: [{number: number}, {isVerified: true}] },  (err, numbers) => {
    if (err) return res.sendStatus(400);
    if (numbers.length != 0) return res.sendStatus(400);
    phoneNumber.save((err) => {
      if (err) {
        return res.sendStatus(400);
      } else {
          const details = {
            to: number,
            from: '+', // Save in config
            body: 'Räddamaten kod: ' + phoneNumber._id.toString().substr(phoneNumber._id.toString().length - 4) + '. Gäller i 15 minuter.'
          };
          twilio.sendMessage(details, (err, responseData) => {
            if (err) {
              return res.sendStatus(400);
            }
            return res.sendStatus(200);
          })
      }
    });
  });
}

/**
 * GET /sms/verify
 * Add to numbers (sms)
 * This function should be called with ajax or similar
 */
exports.verifySmsNumber = (req, res) => {
  const code = req.body.code;
  var date = new Date();
  date.setMinutes(date.getMinutes() - 15);

  PhoneNumber.find({$and: [
      {objectId: new RegExp(code, "i")},
      {createdAt: {$gte: date}}
    ]}, (err, numbers) => {
        if (err) { return res.sendStatus(400); }
        if (numbers.length ==0) { return res.sendStatus(400); }
        const number = numbers.pop();
        number.isVerified = true;
        number.save((err) => {
          if (err) {
            return res.sendStatus(400);
          }
          return res.sendStatus(200);
        })
  });
}
<commit_msg>Fix for filter products<commit_after>var request = require('superagent');
const twilio = require('twilio')(process.env.TWILIO_SID, process.env.TWILIO_TOKEN);
const Restaurant = require('../models/Restaurant');
const Product = require('../models/Product');
const PhoneNumber = require('../models/PhoneNumber');

var mailchimpInstance   = process.env.MAILCHIMP_INSTANCE
    listUniqueId        = process.env.MAILCHIMP_UID,
    mailchimpApiKey     = process.env.MAILCHIMP_APIKEY;

/**
 * GET /
 * Home page.
 */
exports.index = (req, res) => {
  var start = new Date();
  start.setHours(0,0,0,0);
  var end = new Date();
  end.setHours(23,59,59,999);
  findProducts(16, 0, (err, products) => {
    if (err) {
      req.flash('errors', err);
        res.render('home', {
        title: 'Raddamaten'
      });
    } else {
      res.render('home', {
        title: 'Raddamaten',
        products: products
      });
    }
  });
};

/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items The array containing the items.
 */
function shuffle(array) {
    var a = array;
    for (let i = a.length; i; i--) {
        let j = Math.floor(Math.random() * i);
        [a[i - 1], a[j]] = [a[j], a[i - 1]];
    }
    return a;
}

/**
 * GET /products/5
 * Products list page.
 */
exports.getProducts = (req, res) => {
    var start = new Date();
    start.setHours(0,0,0,0);
    var end = new Date();
    end.setHours(23,59,59,999);
    const limit = parseInt(req.query.limit) || 16;
    const currentCount = parseInt(req.params.currentCount);
    findProducts(limit, currentCount, (err, products) => {
        if (err) {
            //callback function return error
            return res.sendStatus(500);
        } else {
            //successfully braunch

            // filter out startdate after now

            res.render('products/products', {
                title: 'Produkter',
                products: products
            });
        }
    });
};

function findProducts(limit, currentCount, callback) {
    var start = new Date();
    start.setHours(0,0,0,0);
    var end = new Date();
    end.setHours(23,59,59,999);
    Product.find({$and:[{startdate:{$lte:end}},{enddate:{$gte:start}}]}, null,
    {limit: limit, skip: currentCount, sort: { enddate: 1 }}, (err, products) => {
        if (err) {
          return callback(err);
        } else {
          return callback(null, products.filter(isEarlierThanStartDate));
        }
    });
}

function isEarlierThanStartDate(product) {
  return product.startdate < new Date();
}

/**
 * GET /about
 * About page.
 */
exports.about = (req, res) => {
  return res.render('about', {
    title: 'Om',
  });
};

/**
 * GET /terms
 * Terms page.
 */
exports.terms = (req, res) => {
  return res.render('terms', {
    title: 'Villkor',
  });
};

/**
 * GET /press
 * Press page.
 */
exports.press = (req, res) => {
  return res.render('press', {
    title: 'Press',
  });
};

/**
 * GET /faq
 * FAQ page.
 */
exports.faq = (req, res) => {
  return res.render('faq', {
    title: 'FAQ',
  });
};

/**
 * GET /connect
 * Connect Restaurant page.
 */
exports.connect = (req, res) => {
  return res.render('connect', {
    title: 'Anslut din restaurang',
  });
};

/**
 * GET /partners
 * View Partners Restaurant page.
 */
exports.getPartners = (req, res) => {
  Restaurant.find({}, (err, restaurants) => {
    return res.render('partners', {
      title: 'Anslutna restauranger',
      restaurants: restaurants
    })
  })
}

/**
 * POST /mailinglist/add
 * Add to mailinglist
 * This function should be called with ajax or similar
 */
exports.addToMailingList = (req, res) => {
  request
        .post('https://' + mailchimpInstance + '.api.mailchimp.com/3.0/lists/' + listUniqueId + '/members/')
        .set('Content-Type', 'application/json;charset=utf-8')
        .set('Authorization', 'Basic ' + new Buffer('any:' + mailchimpApiKey ).toString('base64'))
        .send({
          'email_address': req.body.email,
          'status': 'pending'
        }).end(function(err, response) {
          if (response.status < 300 || (response.status === 400 && response.body.title === "Member Exists")) {
            return res.sendStatus(200);
          } else {
            return res.sendStatus(400);
          }
      });
};

/**
 * GET /sms/add
 * Add to numbers (sms)
 * This function should be called with ajax or similar
 */
exports.addToSmsNumber = (req, res) => {
  const number = req.body.number;

  const phoneNumber = PhoneNumber({
    number: number
  });

  PhoneNumber.find({$and: [{number: number}, {isVerified: true}] },  (err, numbers) => {
    if (err) return res.sendStatus(400);
    if (numbers.length != 0) return res.sendStatus(400);
    phoneNumber.save((err) => {
      if (err) {
        return res.sendStatus(400);
      } else {
          const details = {
            to: number,
            from: '+', // Save in config
            body: 'Räddamaten kod: ' + phoneNumber._id.toString().substr(phoneNumber._id.toString().length - 4) + '. Gäller i 15 minuter.'
          };
          twilio.sendMessage(details, (err, responseData) => {
            if (err) {
              return res.sendStatus(400);
            }
            return res.sendStatus(200);
          })
      }
    });
  });
}

/**
 * GET /sms/verify
 * Add to numbers (sms)
 * This function should be called with ajax or similar
 */
exports.verifySmsNumber = (req, res) => {
  const code = req.body.code;
  var date = new Date();
  date.setMinutes(date.getMinutes() - 15);

  PhoneNumber.find({$and: [
      {objectId: new RegExp(code, "i")},
      {createdAt: {$gte: date}}
    ]}, (err, numbers) => {
        if (err) { return res.sendStatus(400); }
        if (numbers.length ==0) { return res.sendStatus(400); }
        const number = numbers.pop();
        number.isVerified = true;
        number.save((err) => {
          if (err) {
            return res.sendStatus(400);
          }
          return res.sendStatus(200);
        })
  });
}
<|endoftext|>


<commit_before>/*
 * This file is run each time the user clicks the Fluidinfo icon for
 * the extension.
 */

var data = [
    '
',
      'Visit this URL in Fluidinfo.',
      ' | #',
      '<form>',
        '
',
          '
',
            // Regular tag with name and value on this URL.
            '
',
              '',
                'Tag this URL:',
              '	',
              '',
                '
',
                  '
',
                    '
',
                      '',
                        'Tag name',
                      '	',
                      '',
                        '<input type="text" id="tagName1" />',
                      '	',
                    '
',
                    '
',
                      '',
                        'Tag value',
                      '	',
                      '',
                        '<input type="text" id="tagValue1" />',
                      '	',
                    '
',
                  '
',
                '
',
              '	',
            '
',

            // Keywords (tags with no value) on this URL.
            '
',
              '',
                'Keywords (tags with no value) for this URL:',
              '	',
              '',
                '
',
                  '
',
                    '
',
                      '',
                        'Keywords',
                      '	',
                      '',
                        '<input type="text" id="keywords" />',
                      '	',
                    '
',
                  '
',
                '
',
              '	',
            '
',

            // Read this URL later.
            '
',
              '',
                'Read this URL later?',
              '	',
              '',
                '
',
                  '
',
                    '
',
                      '',
                        'Read later?',
                      '	',
                      '',
                        '<input type="checkbox" id="readLater" />',
                      '	',
                    '
',
                  '
',
                '
',
              '	',
            '
',

            // Like this URL.
            '
',
              '',
                'Like this URL?',
              '	',
              '',
                '
',
                  '
',
                    '
',
                      '',
                        'Like:',
                      '	',
                      '',
                        '<input type="checkbox" id="like" />',
                      '	',
                    '
',
                  '
',
                '
',
              '	',
            '
',

            // Rate this URL.
            '
',
              '',
                'Give this URL a rating',
              '	',
              '',
                '
',
                  '
',
                    '
',
                      '',
                        'Rating:',
                      '	',
                      '',
                        '<input type="text" id="rating" />',
                      '	',
                    '
',
                  '
',
                '
',
              '	',
            '
',

            // Tag any object with this URL as the value.
            '
',
              '',
                'Tag something with this URL as a value.',
              '	',
              '',
                '
',
                  '
',
                    '
',
                      '',
                        'Tag name',
                      '	',
                      '',
                        '<input type="text" id="tagName2" />',
                      '	',
                    '
',
                    '
',
                      '',
                        'Thing',
                      '	',
                      '',
                        '<input type="text" id="about2" />',
                      '	',
                    '
',
                  '
',
                '
',
              '	',
            '
',

          '
',
        '
',

        '<input id="_fi_cancel" type="submit" value="Cancel" />',
        '<input id="_fi_save" type="submit" value="Save" />',
      '</form>',
      '

',
    '
'
].join('');

function trim(s){
    return s.replace(/^\s+|\s+$/g, '');
}

function parseFluidinfoValue(value){
    /*
     * Parse a string into one of the 5 types of values recognized by
     * Fluidinfo.
     *
     * param: value is a string
     *
     * return: a value of type
     *
     *             null | [string, string, ...] | float | bool | string
     */
    var numberRegex = /^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/;

    // convert empty string to null
    if (value === '') {
        return null;
    }

    // The value is a non-empty string of some sort. Check if it's a
    // list. (Found within [] and comma separated).
    if (value.match(/^\s*\[.*\]\s*$/)){
        value = trim(value);
        // Convert to Array
        var rawArray = value.slice(1, -1).split(',');
        var val = [];
        for (var i = 0; i < rawArray.length; i++) {
            val.push(trim(rawArray[i]));
        }
        return val;
    }

    if (value.match(numberRegex)){
        // A number.
        return parseFloat(value);
    }

    // Boolean / null value?
    var lower = value.toLowerCase();
    if (lower === 'true' || lower === 'false') {
        return lower === 'true';
    }

    if (lower === 'null') {
        return null;
    }

    // A plain old string.
    return value;
}

function save(){
    var tagName = document.getElementById('tagName1').value;
    var tagValue = document.getElementById('tagValue1').value;

    // Regular tag with name and value on this URL.
    if (tagName && tagValue){
        var tagNamesAndValues = {};
        tagNamesAndValues[tagName] = parseFluidinfoValue(tagValue);
        chrome.extension.sendRequest({
            action: 'tag',
            tagNamesAndValues: tagNamesAndValues,
            about: document.location.toString()
        }, function(response) {
            console.log(response);
        });
    }
    else if (tagName){
        alert("You've set a tag name, but not a tag value.");
    }
    else if (tagValue){
        alert("You've set a tag value, but not a tag name.");
    }

    // Keywords (tags with no value) on this URL.
    var keywordsStr = trim(document.getElementById('keywords').value);
    if (keywordsStr.length){
        var numberOfKeywords = 0;
        var tagNamesAndValues = {};
        var keywords = keywordsStr.split(',');
        console.log(keywords);
        for (var i = 0; i < keywords.length; i++){
            var keyword = trim(keywords[i]);
            console.log(keyword);
            if (/^[\w:\.-]+$/.test(keyword)){
                // Give all keywords a null value, for now (could use a date).
                tagNamesAndValues[keyword] = null;
                numberOfKeywords++;
            }
            else {
                alert("'" + keyword + "' is not a valid tag name, sorry.");
            }
        }
        if (numberOfKeywords){
            chrome.extension.sendRequest({
                action: 'tag',
                tagNamesAndValues: tagNamesAndValues,
                about: document.location.toString()
            }, function(response) {
                console.log(response);
            });
        }
    }

    // Read this URL later.
    var readLater = document.getElementById('readLater').value;

    if (readLater){
        chrome.extension.sendRequest({
            action: 'tag',
            tagNamesAndValues: { 'read-later': true },
            about: document.location.toString()
        }, function(response) {
            console.log(response);
        });
    }

    // Like this URL.
    var like = document.getElementById('like').value;

    if (like){
        chrome.extension.sendRequest({
            action: 'tag',
            tagNamesAndValues: { 'like': true },
            about: document.location.toString()
        }, function(response) {
            console.log(response);
        });
    }

    // Rate this URL.
    var rating = document.getElementById('rating').value;

    if (rating){
        chrome.extension.sendRequest({
            action: 'tag',
            tagNamesAndValues: { 'rating': parseFluidinfoValue(rating) },
            about: document.location.toString()
        }, function(response) {
            console.log(response);
        });
    }

    // Tag any object with this URL as the value.
    tagName = document.getElementById('tagName2').value;
    var about = document.getElementById('about2').value;

    if (tagName && about){
        var tagNamesAndValues = {};
        tagNamesAndValues[tagName] = document.location.toString();
        chrome.extension.sendRequest({
            action: 'tag',
            tagNamesAndValues: tagNamesAndValues,
            about: about
        }, function(response){
            if (response.success){
                var a = $('#_fi_thing_link');
                a.attr('href', 'http://fluidinfo.com/about/#!/' + encodeURIComponent(about));
                a.text('Visit "' + about + '" in Fluidinfo.');
                $('#_fi_thing').show();
            }
            console.log(response);
        });
    }
    else if (tagName){
        $('#_fi_thing').hide();
        alert("You've set a tag name, but not filled in the thing to tag.");
    }
    else if (about){
        $('#_fi_thing').hide();
        alert("You've told us what to tag, but not what tag name to use.");
    }
}

function show(){
    var a = $('#_fi_link');
    a.attr('href', 'http://fluidinfo.com/about/#!/' +
           encodeURIComponent(document.location.toString()));
    $('#_fi_tag').show();
}

function tag(){
    var div = $('#_fi_tag');
    if (div.length){
        if (div.is(':visible')){
            div.hide();
        }
        else {
            show();
        }
    }
    else {
        // Insert the Fluidinfo div, set event handlers, and show the div.
        var e = $(data);
        $('body').prepend(e);
        div = $('#_fi_tag');
        $('#_fi_cancel').click(function(){
            div.hide();
            return false;
        });
        $('#_fi_save').click(function(){
            save();
            return false;
        });
        show();
    }
}

tag();
<commit_msg>Added comment tag.<commit_after>/*
 * This file is run each time the user clicks the Fluidinfo icon for
 * the extension.
 */

var data = [
    '
',
      'Visit this URL in Fluidinfo.',
      ' | #',
      '<form>',
        '
',
          '
',
            // Regular tag with name and value on this URL.
            '
',
              '',
                'Tag this URL:',
              '	',
              '',
                '
',
                  '
',
                    '
',
                      '',
                        'Tag name',
                      '	',
                      '',
                        '<input type="text" id="tagName1" />',
                      '	',
                    '
',
                    '
',
                      '',
                        'Tag value',
                      '	',
                      '',
                        '<input type="text" id="tagValue1" />',
                      '	',
                    '
',
                  '
',
                '
',
              '	',
            '
',

            // Keywords (tags with no value) on this URL.
            '
',
              '',
                'Keywords (tags with no value) for this URL:',
              '	',
              '',
                '
',
                  '
',
                    '
',
                      '',
                        'Keywords',
                      '	',
                      '',
                        '<input type="text" id="keywords" />',
                      '	',
                    '
',
                  '
',
                '
',
              '	',
            '
',

            // Read this URL later.
            '
',
              '',
                'Read this URL later?',
              '	',
              '',
                '
',
                  '
',
                    '
',
                      '',
                        'Read later?',
                      '	',
                      '',
                        '<input type="checkbox" id="readLater" />',
                      '	',
                    '
',
                  '
',
                '
',
              '	',
            '
',

            // Like this URL.
            '
',
              '',
                'Like this URL?',
              '	',
              '',
                '
',
                  '
',
                    '
',
                      '',
                        'Like:',
                      '	',
                      '',
                        '<input type="checkbox" id="like" />',
                      '	',
                    '
',
                  '
',
                '
',
              '	',
            '
',

            // Rate this URL.
            '
',
              '',
                'Give this URL a rating',
              '	',
              '',
                '
',
                  '
',
                    '
',
                      '',
                        'Rating:',
                      '	',
                      '',
                        '<input type="text" id="rating" />',
                      '	',
                    '
',
                  '
',
                '
',
              '	',
            '
',

            // Comment on this URL.
            '
',
              '',
                'Comment on this URL',
              '	',
              '',
                '
',
                  '
',
                    '
',
                      '',
                        'Comment:',
                      '	',
                      '',
                        '<textarea id="comment" rows="3" />',
                      '	',
                    '
',
                  '
',
                '
',
              '	',
            '
',

            // Tag any object with this URL as the value.
            '
',
              '',
                'Tag something with this URL as a value.',
              '	',
              '',
                '
',
                  '
',
                    '
',
                      '',
                        'Tag name',
                      '	',
                      '',
                        '<input type="text" id="tagName2" />',
                      '	',
                    '
',
                    '
',
                      '',
                        'Thing',
                      '	',
                      '',
                        '<input type="text" id="about2" />',
                      '	',
                    '
',
                  '
',
                '
',
              '	',
            '
',

          '
',
        '
',

        '<input id="_fi_cancel" type="submit" value="Cancel" />',
        '<input id="_fi_save" type="submit" value="Save" />',
      '</form>',
      '

',
    '
'
].join('');

function trim(s){
    return s.replace(/^\s+|\s+$/g, '');
}

function parseFluidinfoValue(value){
    /*
     * Parse a string into one of the 5 types of values recognized by
     * Fluidinfo.
     *
     * param: value is a string
     *
     * return: a value of type
     *
     *             null | [string, string, ...] | float | bool | string
     */
    var numberRegex = /^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/;

    // convert empty string to null
    if (value === '') {
        return null;
    }

    // The value is a non-empty string of some sort. Check if it's a
    // list. (Found within [] and comma separated).
    if (value.match(/^\s*\[.*\]\s*$/)){
        value = trim(value);
        // Convert to Array
        var rawArray = value.slice(1, -1).split(',');
        var val = [];
        for (var i = 0; i < rawArray.length; i++) {
            val.push(trim(rawArray[i]));
        }
        return val;
    }

    if (value.match(numberRegex)){
        // A number.
        return parseFloat(value);
    }

    // Boolean / null value?
    var lower = value.toLowerCase();
    if (lower === 'true' || lower === 'false') {
        return lower === 'true';
    }

    if (lower === 'null') {
        return null;
    }

    // A plain old string.
    return value;
}

function save(){
    var tagName = document.getElementById('tagName1').value;
    var tagValue = document.getElementById('tagValue1').value;

    // Regular tag with name and value on this URL.
    if (tagName && tagValue){
        var tagNamesAndValues = {};
        tagNamesAndValues[tagName] = parseFluidinfoValue(tagValue);
        chrome.extension.sendRequest({
            action: 'tag',
            tagNamesAndValues: tagNamesAndValues,
            about: document.location.toString()
        }, function(response) {
            console.log(response);
        });
    }
    else if (tagName){
        alert("You've set a tag name, but not a tag value.");
    }
    else if (tagValue){
        alert("You've set a tag value, but not a tag name.");
    }

    // Keywords (tags with no value) on this URL.
    var keywordsStr = trim(document.getElementById('keywords').value);
    if (keywordsStr.length){
        var numberOfKeywords = 0;
        var tagNamesAndValues = {};
        var keywords = keywordsStr.split(',');
        console.log(keywords);
        for (var i = 0; i < keywords.length; i++){
            var keyword = trim(keywords[i]);
            console.log(keyword);
            if (/^[\w:\.-]+$/.test(keyword)){
                // Give all keywords a null value, for now (could use a date).
                tagNamesAndValues[keyword] = null;
                numberOfKeywords++;
            }
            else {
                alert("'" + keyword + "' is not a valid tag name, sorry.");
            }
        }
        if (numberOfKeywords){
            chrome.extension.sendRequest({
                action: 'tag',
                tagNamesAndValues: tagNamesAndValues,
                about: document.location.toString()
            }, function(response) {
                console.log(response);
            });
        }
    }

    // Read this URL later?
    if ($('#readLater').is(':checked')){
        chrome.extension.sendRequest({
            action: 'tag',
            tagNamesAndValues: { 'read-later': true },
            about: document.location.toString()
        }, function(response) {
            console.log(response);
        });
    }

    // Like this URL?
    if ($('#like').is(':checked')){
        chrome.extension.sendRequest({
            action: 'tag',
            tagNamesAndValues: { like: true },
            about: document.location.toString()
        }, function(response) {
            console.log(response);
        });
    }

    // Rate this URL.
    var rating = document.getElementById('rating').value;

    if (rating){
        chrome.extension.sendRequest({
            action: 'tag',
            tagNamesAndValues: { rating: parseFluidinfoValue(rating) },
            about: document.location.toString()
        }, function(response) {
            console.log(response);
        });
    }

    // Comment on this URL.
    var comment = document.getElementById('comment').value;

    if (comment){
        chrome.extension.sendRequest({
            action: 'tag',
            tagNamesAndValues: { comment: comment },
            about: document.location.toString()
        }, function(response) {
            console.log(response);
        });
    }

    // Tag any object with this URL as the value.
    tagName = document.getElementById('tagName2').value;
    var about = document.getElementById('about2').value;

    if (tagName && about){
        var tagNamesAndValues = {};
        tagNamesAndValues[tagName] = document.location.toString();
        chrome.extension.sendRequest({
            action: 'tag',
            tagNamesAndValues: tagNamesAndValues,
            about: about
        }, function(response){
            if (response.success){
                var a = $('#_fi_thing_link');
                a.attr('href', 'http://fluidinfo.com/about/#!/' + encodeURIComponent(about));
                a.text('Visit "' + about + '" in Fluidinfo.');
                $('#_fi_thing').show();
            }
            console.log(response);
        });
    }
    else if (tagName){
        $('#_fi_thing').hide();
        alert("You've set a tag name, but not filled in the thing to tag.");
    }
    else if (about){
        $('#_fi_thing').hide();
        alert("You've told us what to tag, but not what tag name to use.");
    }
}

function show(){
    var a = $('#_fi_link');
    a.attr('href', 'http://fluidinfo.com/about/#!/' +
           encodeURIComponent(document.location.toString()));
    $('#_fi_tag').show();
}

function tag(){
    var div = $('#_fi_tag');
    if (div.length){
        if (div.is(':visible')){
            div.hide();
        }
        else {
            show();
        }
    }
    else {
        // Insert the Fluidinfo div, set event handlers, and show the div.
        var e = $(data);
        $('body').prepend(e);
        div = $('#_fi_tag');
        $('#_fi_cancel').click(function(){
            div.hide();
            return false;
        });
        $('#_fi_save').click(function(){
            save();
            return false;
        });
        show();
    }
}

tag();
<|endoftext|>


<commit_before>const controlSet = new Set([
	'shift',
	'ctrl',
	'alt',
	'pause',
	'break',
	'capslock',
	'escape',
	'insert',
	'left',
	'right',
	'end',
	'home',
	'pageup',
	'pagedown',
	'up',
	'down',
	'f1',
	'f2',
	'f3',
	'f4',
	'f5',
	'f6',
	'f7',
	'f8',
	'f9',
	'f10',
	'f11',
	'f12',
	'numlock',
	'scrolllock'
]);

const nonPrintableSet = new Set([
	'enter'
]);

const codeMap = new Map()
	.set(8, 'backspace')
	.set(9, 'tab')
	.set(13, 'enter')
	.set(16, 'shift')
	.set(17, 'ctrl')
	.set(20, 'capslock')
	.set(27, 'escape')
	.set(32, 'space')
	.set(33, 'pageup')
	.set(34, 'pagedown')
	.set(35, 'end')
	.set(36, 'home')
	.set(37, 'left')
	.set(38, 'up')
	.set(39, 'right')
	.set(40, 'down')
	.set(45, 'insert')
	.set(46, 'delete')
	.set(112, 'f1')
	.set(113, 'f2')
	.set(114, 'f3')
	.set(115, 'f4')
	.set(116, 'f5')
	.set(117, 'f6')
	.set(118, 'f7')
	.set(119, 'f8')
	.set(120, 'f9')
	.set(121, 'f10')
	.set(122, 'f11')
	.set(123, 'f12')
	.set(144, 'numlock')
	.set(145, 'scrolllock');

const codeSet = new Set(codeMap.values());

const printableMap = new Map()
	.set('space', ' ');

export class Keyboard {
	static isPrintable(code) {
		return !nonPrintableSet.has(code) && !Keyboard.isControl(code);
	}

	static isControl(code) {
		return controlSet.has(code);
	}

	static stringify(code, key) {
		if (codeSet.has(code)) {
			return printableMap.get(code) || '';
		}

		return key;
	}

	static translate(code) {
		return codeMap.get(code) || String.fromCharCode(code);
	}
}

<commit_msg>add numpad buttons to keyboard handler<commit_after>const controlSet = new Set([
	'shift',
	'ctrl',
	'alt',
	'pause',
	'break',
	'capslock',
	'escape',
	'insert',
	'left',
	'right',
	'end',
	'home',
	'pageup',
	'pagedown',
	'up',
	'down',
	'f1',
	'f2',
	'f3',
	'f4',
	'f5',
	'f6',
	'f7',
	'f8',
	'f9',
	'f10',
	'f11',
	'f12',
	'numlock',
	'scrolllock'
]);

const nonPrintableSet = new Set([
	'enter'
]);

const codeMap = new Map()
	.set(8, 'backspace')
	.set(9, 'tab')
	.set(13, 'enter')
	.set(16, 'shift')
	.set(17, 'ctrl')
	.set(20, 'capslock')
	.set(27, 'escape')
	.set(32, 'space')
	.set(33, 'pageup')
	.set(34, 'pagedown')
	.set(35, 'end')
	.set(36, 'home')
	.set(37, 'left')
	.set(38, 'up')
	.set(39, 'right')
	.set(40, 'down')
	.set(45, 'insert')
	.set(46, 'delete')
	.set(96, 'numpad0')
	.set(97, 'numpad1')
	.set(98, 'numpad2')
	.set(99, 'numpad3')
	.set(100, 'numpad4')
	.set(101, 'numpad5')
	.set(102, 'numpad6')
	.set(103, 'numpad7')
	.set(104, 'numpad8')
	.set(105, 'numpad9')
	.set(112, 'f1')
	.set(113, 'f2')
	.set(114, 'f3')
	.set(115, 'f4')
	.set(116, 'f5')
	.set(117, 'f6')
	.set(118, 'f7')
	.set(119, 'f8')
	.set(120, 'f9')
	.set(121, 'f10')
	.set(122, 'f11')
	.set(123, 'f12')
	.set(144, 'numlock')
	.set(145, 'scrolllock');

const codeSet = new Set(codeMap.values());

const printableMap = new Map()
	.set('space', ' ');

export class Keyboard {
	static isPrintable(code) {
		return !nonPrintableSet.has(code) && !Keyboard.isControl(code);
	}

	static isControl(code) {
		return controlSet.has(code);
	}

	static stringify(code, key) {
		if (codeSet.has(code)) {
			return printableMap.get(code) || '';
		}

		return key;
	}

	static translate(code) {
		return codeMap.get(code) || String.fromCharCode(code);
	}
}

<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectCompletenessTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectCompletenessTitle");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.documents = ko.observableArray(ko.utils.arrayMap(documents, function(document) {
        return { description: document.description, amount_required: document.amount_required, weight: document.weight}
    }));

    gvm.addDocumentToSubmit = function(document) {
        gvm.documents.push({
            description: "",
            amount_required: "",
            weight: ""
        });
    };

    gvm.removeDocument = function(document) {
        gvm.documents.remove(document);
    };
}

function initPage() {
    viewModel.getProjectInfo();
}<commit_msg>completeness page<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectCompletenessTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectCompletenessTitle");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.documents = ko.observableArray(ko.utils.arrayMap(function(document) {
        return { description: document.description, amount_required: document.amount_required, weight: document.weight}
    }));

    gvm.addDocumentToSubmit = function(document) {
        gvm.documents.push({
            description: "",
            amount_required: "",
            weight: ""
        });
    };

    gvm.removeDocument = function(document) {
        gvm.documents.remove(document);
    };
}

function initPage() {
    viewModel.getProjectInfo();
}<|endoftext|>


<commit_before>var Card = require('../src/Card');

var CARD_NUMBERS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
var CARD_TYPES = ['Hearts', 'Diamonds', 'Clubs', 'Spades'];

/*
 * A trump card set has
 * - Hearts set of K ... A
 * - Diamonds set of K ... A
 * - Clubs set of K ... A
 * - Spades set of K ... A
 * - 2 Jokers
 */

/**
 * Represents a single trump card.
 */
var TrumpCard = function(id) {
  // TODO sanitize input
  this.id = id;
}

TrumpCard.prototype = Object.create(Card.prototype, {
  number: {
    get: function() {
      return CARD_NUMBERS[this.id%CARD_NUMBERS.length];
    }
  },

  numberRaw: {
    get: function() {
      return this.id%CARD_NUMBERS.length;
    }
  },

  type: {
    get: function() {
      return CARD_TYPES[this.id/CARD_NUMBERS.length|0];
    }
  },

  typeRaw: {
    get: function() {
      return this.id/CARD_NUMBERS.length|0;
    }
  }
});

TrumpCard.prototype.toString = function() {
  return this.type + ' ' + this.number + (this.direction ? ' (Fliped)': '');
}

TrumpCard.prototype.inspect = function() {
  return this.toString();
}
TrumpCard.prototype.constructor = TrumpCard;

module.exports = TrumpCard;
<commit_msg>Sanitize input of TrumpCard<commit_after>var Card = require('../src/Card');

var CARD_NUMBERS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
var CARD_TYPES = ['Hearts', 'Diamonds', 'Clubs', 'Spades'];

/*
 * A trump card set has
 * - Hearts set of K ... A
 * - Diamonds set of K ... A
 * - Clubs set of K ... A
 * - Spades set of K ... A
 * - 2 Jokers
 */

/**
 * Represents a single trump card.
 */
var TrumpCard = function(id) {
  if(typeof id != 'number') throw new Error('TrumpCard ID should be a number');
  if(id < 0 || id > 52) throw new Error('TrumpCard ID should be between 0 and 52');
  this.id = id|0;
}

TrumpCard.prototype = Object.create(Card.prototype, {
  number: {
    get: function() {
      return CARD_NUMBERS[this.id%CARD_NUMBERS.length];
    }
  },

  numberRaw: {
    get: function() {
      return this.id%CARD_NUMBERS.length;
    }
  },

  type: {
    get: function() {
      return CARD_TYPES[this.id/CARD_NUMBERS.length|0];
    }
  },

  typeRaw: {
    get: function() {
      return this.id/CARD_NUMBERS.length|0;
    }
  }
});

TrumpCard.prototype.toString = function() {
  return this.type + ' ' + this.number + (this.direction ? ' (Fliped)': '');
}

TrumpCard.prototype.inspect = function() {
  return this.toString();
}
TrumpCard.prototype.constructor = TrumpCard;

module.exports = TrumpCard;
<|endoftext|>


<commit_before>CRM.$(function ($) {

  CRM.SecureFilesWidget.formComplete = false;

  function uploadFileWithPromise(file, key, field) {

    var dfd = $.Deferred();

    var params = {
      Key: key,
      ContentType: file.type,
      Body: file
    };

    //server-side Encryption Settings
    if(CRM.SecureFilesWidget.useEncryption) {
      params.ServerSideEncryption = CRM.SecureFilesWidget.encryptionType;
    }

    CRM.SecureFilesWidget.Bucket.putObject(params, function (err, data) {
      if (err) {
        dfd.reject(err);
      } else {
        //Unset the file
        $(field).val("");

        //Resolve this promise
        dfd.resolve({"field": $(field).attr("name"), "name": key, "mime-type": file.type, "data": data});
      }
    });

    return dfd.promise();
  }

  $(".securefiles_upload").closest("form").submit(function(event) {
    var formObj = $(this);
    if(!CRM.SecureFilesWidget.formComplete) {
      event.preventDefault();
      if (CRM.SecureFilesWidget.useSTS) {
        //Upload the file using the JavaScript SDK
        CRM.SecureFilesWidget.promises = [];
        $(this).find(".securefiles_upload").each(function () {

          var i = 0;
          if(this.files[i]) {
            //Looks like we have something to upload
            var file = this.files[i];
            var fileTitle = CRM.SecureFilesWidget.S3Fields[$(this).attr("name")].filename || this.files[i].name;
            var objKey = CRM.SecureFilesWidget.currentContactId + '/' + fileTitle;

            CRM.SecureFilesWidget.promises.push(uploadFileWithPromise(this.files[i], objKey, this));

          }
        });

        $.when.apply($, CRM.SecureFilesWidget.promises).done(function(data) {
          CRM.SecureFilesWidget.formComplete = true;
          formObj.find(".securefiles-metadata").val(JSON.stringify(data));
          //Todo: Clear the file field so it doesn't attempt to upload
          formObj.submit();
        }).fail(function(err) {
          console.log(err);
        });

      }
    }
  });

  //Setup Creds for S3 if we need them.
  if(CRM.SecureFilesWidget.useSTS) {

    AWS.config.update({
      accessKeyId: CRM.SecureFilesWidget.Credentials.AccessKeyId,
      secretAccessKey: CRM.SecureFilesWidget.Credentials.SecretAccessKey,
      sessionToken: CRM.SecureFilesWidget.Credentials.SessionToken
    });

    AWS.config.region = CRM.SecureFilesWidget.S3Region;

    //This tells the js sdk to log debugging symbols to the console
    //AWS.config.logger = console;

    CRM.SecureFilesWidget.Bucket = new AWS.S3({
      params: {
        Bucket: CRM.SecureFilesWidget.S3Bucket
      }
    });
  }

});<commit_msg>Updated Amazon Widget<commit_after>CRM.$(function ($) {

  CRM.SecureFilesWidget.formComplete = false;

  function uploadFileWithPromise(file, key, field) {

    var dfd = $.Deferred();

    var params = {
      Key: key,
      ContentType: file.type,
      Body: file
    };

    //server-side Encryption Settings
    if(CRM.SecureFilesWidget.useEncryption) {
      params.ServerSideEncryption = CRM.SecureFilesWidget.encryptionType;
    }

    CRM.SecureFilesWidget.Bucket.putObject(params, function (err, data) {
      if (err) {
        dfd.reject(err);
      } else {
        //Unset the file
        $(field).val("");

        //Resolve this promise
        dfd.resolve({"field": $(field).attr("name"), "name": key, "mime_type": file.type, "data": data});
      }
    });

    return dfd.promise();
  }

  $(".securefiles_upload").closest("form").submit(function(event) {
    var formObj = $(this);
    if(!CRM.SecureFilesWidget.formComplete) {
      event.preventDefault();
      if (CRM.SecureFilesWidget.useSTS) {
        //Upload the file using the JavaScript SDK
        CRM.SecureFilesWidget.promises = [];
        $(this).find(".securefiles_upload").each(function () {

          var i = 0;
          if(this.files[i]) {
            //Looks like we have something to upload
            var file = this.files[i];
            var fileTitle = CRM.SecureFilesWidget.S3Fields[$(this).attr("name")].filename || this.files[i].name;
            var objKey = CRM.SecureFilesWidget.currentContactId + '/' + fileTitle;

            CRM.SecureFilesWidget.promises.push(uploadFileWithPromise(this.files[i], objKey, this));

          }
        });

        $.when.apply($, CRM.SecureFilesWidget.promises).done(function(data) {
          CRM.SecureFilesWidget.formComplete = true;
          formObj.find(".securefiles-metadata").val(JSON.stringify(data));
          //Todo: Clear the file field so it doesn't attempt to upload
          formObj.submit();
        }).fail(function(err) {
          console.log(err);
        });

      }
    }
  });

  //Setup Creds for S3 if we need them.
  if(CRM.SecureFilesWidget.useSTS) {

    AWS.config.update({
      accessKeyId: CRM.SecureFilesWidget.Credentials.AccessKeyId,
      secretAccessKey: CRM.SecureFilesWidget.Credentials.SecretAccessKey,
      sessionToken: CRM.SecureFilesWidget.Credentials.SessionToken
    });

    AWS.config.region = CRM.SecureFilesWidget.S3Region;

    //This tells the js sdk to log debugging symbols to the console
    //AWS.config.logger = console;

    CRM.SecureFilesWidget.Bucket = new AWS.S3({
      params: {
        Bucket: CRM.SecureFilesWidget.S3Bucket
      }
    });
  }

});<|endoftext|>