entities
listlengths
1
8.61k
max_stars_repo_path
stringlengths
7
172
max_stars_repo_name
stringlengths
5
89
max_stars_count
int64
0
82k
content
stringlengths
14
1.05M
id
stringlengths
2
6
new_content
stringlengths
15
1.05M
modified
bool
1 class
references
stringlengths
29
1.05M
[ { "context": "___/ /_____/ http://www.field.io\n\n Created by Marcus Wendt on 07/03/2013\n\n###\n\nutil = require './util'\n\nexte", "end": 251, "score": 0.9998607635498047, "start": 239, "tag": "NAME", "value": "Marcus Wendt" } ]
src/fieldkit.coffee
field/FieldKit.js
3
### _____ __ _____ __ ____ / ___/ / / /____/ / / / \ FieldKit / ___/ /_/ /____/ / /__ / / / (c) 2013, FIELD. All rights reserved. /_/ /____/ /____/ /_____/ http://www.field.io Created by Marcus Wendt on 07/03/2013 ### util = require './util' extend = -> switch arguments.length when 1 util.extend fk, arguments[0] when 2 pkg = arguments[0] fk[pkg] = {} if not fk[pkg]? util.extend fk[pkg], arguments[1] # Namespace fk = {} # # Core Library # extend require './color' extend require './time' # Math: Core extend 'math', require './math/math' extend 'math', require './math/random' extend 'math', require './math/noise' # Math: Geometry extend 'math', require './math/vector' extend 'math', require './math/rect' extend 'math', require './math/box' extend 'math', require './math/line' # Utilities extend 'util', util # # Independent Sub Libraries # extend 'physics', require './physics/physics' extend 'physics', require './physics/particle' extend 'physics', require './physics/behaviours' extend 'physics', require './physics/constraints' # client/browser specific libraries extend 'client', require './client/sketch' # # Exports # module.exports = fk # attach to global window object in browser based environments window.fk = fk if window?
75177
### _____ __ _____ __ ____ / ___/ / / /____/ / / / \ FieldKit / ___/ /_/ /____/ / /__ / / / (c) 2013, FIELD. All rights reserved. /_/ /____/ /____/ /_____/ http://www.field.io Created by <NAME> on 07/03/2013 ### util = require './util' extend = -> switch arguments.length when 1 util.extend fk, arguments[0] when 2 pkg = arguments[0] fk[pkg] = {} if not fk[pkg]? util.extend fk[pkg], arguments[1] # Namespace fk = {} # # Core Library # extend require './color' extend require './time' # Math: Core extend 'math', require './math/math' extend 'math', require './math/random' extend 'math', require './math/noise' # Math: Geometry extend 'math', require './math/vector' extend 'math', require './math/rect' extend 'math', require './math/box' extend 'math', require './math/line' # Utilities extend 'util', util # # Independent Sub Libraries # extend 'physics', require './physics/physics' extend 'physics', require './physics/particle' extend 'physics', require './physics/behaviours' extend 'physics', require './physics/constraints' # client/browser specific libraries extend 'client', require './client/sketch' # # Exports # module.exports = fk # attach to global window object in browser based environments window.fk = fk if window?
true
### _____ __ _____ __ ____ / ___/ / / /____/ / / / \ FieldKit / ___/ /_/ /____/ / /__ / / / (c) 2013, FIELD. All rights reserved. /_/ /____/ /____/ /_____/ http://www.field.io Created by PI:NAME:<NAME>END_PI on 07/03/2013 ### util = require './util' extend = -> switch arguments.length when 1 util.extend fk, arguments[0] when 2 pkg = arguments[0] fk[pkg] = {} if not fk[pkg]? util.extend fk[pkg], arguments[1] # Namespace fk = {} # # Core Library # extend require './color' extend require './time' # Math: Core extend 'math', require './math/math' extend 'math', require './math/random' extend 'math', require './math/noise' # Math: Geometry extend 'math', require './math/vector' extend 'math', require './math/rect' extend 'math', require './math/box' extend 'math', require './math/line' # Utilities extend 'util', util # # Independent Sub Libraries # extend 'physics', require './physics/physics' extend 'physics', require './physics/particle' extend 'physics', require './physics/behaviours' extend 'physics', require './physics/constraints' # client/browser specific libraries extend 'client', require './client/sketch' # # Exports # module.exports = fk # attach to global window object in browser based environments window.fk = fk if window?
[ { "context": "tes = [\n {\n path: '/',\n name: 'Hello',\n component: Hello\n },\n {\n ", "end": 320, "score": 0.5764933228492737, "start": 315, "tag": "NAME", "value": "Hello" }, { "context": " {\n path: 'music',\n name: 'Music',\n component: Music\n }\n ", "end": 602, "score": 0.5993626713752747, "start": 597, "tag": "NAME", "value": "Music" }, { "context": " },\n {\n path: 'music',\n name: 'Music',\n component: Music\n }\n ]\n \"\"\"\n", "end": 978, "score": 0.8764437437057495, "start": 973, "tag": "NAME", "value": "Music" }, { "context": "ody': \"\"\"\n {\n path: '/vr_1',\n name: 'Hello',\n component: Hello\n }\n \"\"\"\n 'one chi", "end": 1142, "score": 0.9818754196166992, "start": 1137, "tag": "NAME", "value": "Hello" }, { "context": "body': \"\"\"\n {\n path: 'vr_1',\n name: 'Hello',\n component: Hello\n }\n \"\"\"\n\n 'mode -", "end": 1305, "score": 0.991685688495636, "start": 1300, "tag": "NAME", "value": "Hello" } ]
snippets/router-js.cson
code4mk/atom-vue-router
1
'.source.js': 'pack -> vue-router': 'prefix': 'vr-pack', 'body': """ import Vue from 'vue' import Router from 'vue-router' import Hello from '@/components/Hello' import Sample from '@/components/Sample' Vue.use(Router) const routes = [ { path: '/', name: 'Hello', component: Hello }, { path: '/sample', name: 'Sample', component: Sample, children: [ { path: '/', redirect: 'music' }, { path: 'music', name: 'Music', component: Music } ] } ] export default new Router({ mode: 'history', //base: 'admin', routes }) """ 'children -> vue-router': 'prefix': 'vr-child', 'body': """ children: [ { path: '/', redirect: 'music' }, { path: 'music', name: 'Music', component: Music } ] """ 'one routes -> vue-router': 'prefix': 'vr-1', 'body': """ { path: '/vr_1', name: 'Hello', component: Hello } """ 'one child routes -> vue-router': 'prefix': 'vr-1child', 'body': """ { path: 'vr_1', name: 'Hello', component: Hello } """ 'mode -> vue-router': 'prefix': 'vr-mode', 'body': """ mode: 'history', """ 'base -> vue-router': 'prefix': 'vr-base', 'body': """ base: 'admin', """ 'routes -> vue-router (new)': 'prefix': 'vr-routes', 'body': """ routes """ 'redirect -> vue-router ': 'prefix': 'vr-redirect', 'body': """ redirect: 'music' """
121706
'.source.js': 'pack -> vue-router': 'prefix': 'vr-pack', 'body': """ import Vue from 'vue' import Router from 'vue-router' import Hello from '@/components/Hello' import Sample from '@/components/Sample' Vue.use(Router) const routes = [ { path: '/', name: '<NAME>', component: Hello }, { path: '/sample', name: 'Sample', component: Sample, children: [ { path: '/', redirect: 'music' }, { path: 'music', name: '<NAME>', component: Music } ] } ] export default new Router({ mode: 'history', //base: 'admin', routes }) """ 'children -> vue-router': 'prefix': 'vr-child', 'body': """ children: [ { path: '/', redirect: 'music' }, { path: 'music', name: '<NAME>', component: Music } ] """ 'one routes -> vue-router': 'prefix': 'vr-1', 'body': """ { path: '/vr_1', name: '<NAME>', component: Hello } """ 'one child routes -> vue-router': 'prefix': 'vr-1child', 'body': """ { path: 'vr_1', name: '<NAME>', component: Hello } """ 'mode -> vue-router': 'prefix': 'vr-mode', 'body': """ mode: 'history', """ 'base -> vue-router': 'prefix': 'vr-base', 'body': """ base: 'admin', """ 'routes -> vue-router (new)': 'prefix': 'vr-routes', 'body': """ routes """ 'redirect -> vue-router ': 'prefix': 'vr-redirect', 'body': """ redirect: 'music' """
true
'.source.js': 'pack -> vue-router': 'prefix': 'vr-pack', 'body': """ import Vue from 'vue' import Router from 'vue-router' import Hello from '@/components/Hello' import Sample from '@/components/Sample' Vue.use(Router) const routes = [ { path: '/', name: 'PI:NAME:<NAME>END_PI', component: Hello }, { path: '/sample', name: 'Sample', component: Sample, children: [ { path: '/', redirect: 'music' }, { path: 'music', name: 'PI:NAME:<NAME>END_PI', component: Music } ] } ] export default new Router({ mode: 'history', //base: 'admin', routes }) """ 'children -> vue-router': 'prefix': 'vr-child', 'body': """ children: [ { path: '/', redirect: 'music' }, { path: 'music', name: 'PI:NAME:<NAME>END_PI', component: Music } ] """ 'one routes -> vue-router': 'prefix': 'vr-1', 'body': """ { path: '/vr_1', name: 'PI:NAME:<NAME>END_PI', component: Hello } """ 'one child routes -> vue-router': 'prefix': 'vr-1child', 'body': """ { path: 'vr_1', name: 'PI:NAME:<NAME>END_PI', component: Hello } """ 'mode -> vue-router': 'prefix': 'vr-mode', 'body': """ mode: 'history', """ 'base -> vue-router': 'prefix': 'vr-base', 'body': """ base: 'admin', """ 'routes -> vue-router (new)': 'prefix': 'vr-routes', 'body': """ routes """ 'redirect -> vue-router ': 'prefix': 'vr-redirect', 'body': """ redirect: 'music' """
[ { "context": " {tokens} = grammar.tokenizeLine 'Go on mailto:doc.writer@example.com[] now'\n expect(tokens).toHaveLength 6\n ", "end": 6432, "score": 0.9996857643127441, "start": 6410, "tag": "EMAIL", "value": "doc.writer@example.com" }, { "context": "doc']\n expect(tokens[3]).toEqualJson value: 'doc.writer@example.com', scopes: ['source.asciidoc', 'markup.other.url.a", "end": 6871, "score": 0.9998774528503418, "start": 6849, "tag": "EMAIL", "value": "doc.writer@example.com" }, { "context": "il', ->\n {tokens} = grammar.tokenizeLine 'foo doc.writer@example.com bar'\n expect(tokens).toHaveLength 3\n ex", "end": 8833, "score": 0.9999119639396667, "start": 8811, "tag": "EMAIL", "value": "doc.writer@example.com" }, { "context": "doc']\n expect(tokens[1]).toEqualJson value: 'doc.writer@example.com', scopes: ['source.asciidoc', 'markup.link.email.", "end": 9020, "score": 0.9999122619628906, "start": 8998, "tag": "EMAIL", "value": "doc.writer@example.com" } ]
spec/inlines/link-grammar-spec.coffee
andrewcarver/atom-language-asciidoc
45
describe 'Should tokenizes text link when', -> grammar = null beforeEach -> waitsForPromise -> atom.packages.activatePackage 'language-asciidoc' runs -> grammar = atom.grammars.grammarForScopeName 'source.asciidoc' it 'parses the grammar', -> expect(grammar).toBeDefined() expect(grammar.scopeName).toBe 'source.asciidoc' describe 'URL pattern', -> it 'is a simple url with http', -> {tokens} = grammar.tokenizeLine 'http://www.docbook.org/[DocBook.org]' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'http://www.docbook.org/', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[1]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'DocBook.org', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[3]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] it 'is a simple url with http in phrase', -> {tokens} = grammar.tokenizeLine 'Go on http://foobar.com now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'Go on', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'http://foobar.com', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple url with https', -> {tokens} = grammar.tokenizeLine 'Go on https://foobar.com now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'Go on', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'https://foobar.com', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple url with file', -> {tokens} = grammar.tokenizeLine 'Go on file://foobar.txt now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'Go on', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'file://foobar.txt', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple url with ftp', -> {tokens} = grammar.tokenizeLine 'Go on ftp://foobar.txt now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'Go on', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'ftp://foobar.txt', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple url with irc', -> {tokens} = grammar.tokenizeLine 'Go on irc://foobar now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'Go on', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'irc://foobar', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple url in a bullet list', -> {tokens} = grammar.tokenizeLine '* https://foobar.com now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: '*', scopes: ['source.asciidoc', 'markup.list.asciidoc', 'markup.list.bullet.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'https://foobar.com', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'contains attribute reference', -> {tokens} = grammar.tokenizeLine 'http://foo{uri-repo}bar.com now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'http://foo', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[1]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[2]).toEqualJson value: 'bar.com', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] describe '"link:" & "mailto:" macro', -> it 'have optional link text and attributes', -> {tokens} = grammar.tokenizeLine 'Go on link:url[optional link text, optional target attribute, optional role attribute] now' expect(tokens).toHaveLength 8 expect(tokens[0]).toEqualJson value: 'Go on ', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: 'link', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'entity.name.function.asciidoc'] expect(tokens[2]).toEqualJson value: ':', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'url', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[4]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[5]).toEqualJson value: 'optional link text, optional target attribute, optional role attribute', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[6]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[7]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple mailto', -> {tokens} = grammar.tokenizeLine 'Go on mailto:doc.writer@example.com[] now' expect(tokens).toHaveLength 6 expect(tokens[0]).toEqualJson value: 'Go on ', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: 'mailto', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'entity.name.function.asciidoc'] expect(tokens[2]).toEqualJson value: ':', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'doc.writer@example.com', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[4]).toEqualJson value: '[]', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[5]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'contains attribute reference', -> {tokens} = grammar.tokenizeLine 'Go on link:http://{uri-repo}[label] now' expect(tokens).toHaveLength 9 expect(tokens[0]).toEqualJson value: 'Go on ', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: 'link', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'entity.name.function.asciidoc'] expect(tokens[2]).toEqualJson value: ':', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'http://', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[4]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[5]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[6]).toEqualJson value: 'label', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[7]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[8]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple url with https started with "link:" with missing square brackets ending (invalid context)', -> {tokens} = grammar.tokenizeLine 'Go on link:https://foobar.com now' expect(tokens).toHaveLength 1 expect(tokens[0]).toEqualJson value: 'Go on link:https://foobar.com now', scopes: ['source.asciidoc'] describe 'email pattern', -> it 'is a email', -> {tokens} = grammar.tokenizeLine 'foo doc.writer@example.com bar' expect(tokens).toHaveLength 3 expect(tokens[0]).toEqualJson value: 'foo ', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: 'doc.writer@example.com', scopes: ['source.asciidoc', 'markup.link.email.asciidoc'] expect(tokens[2]).toEqualJson value: ' bar', scopes: ['source.asciidoc'] describe 'pure attribute reference link', -> it 'start at the beginning of the line', -> {tokens} = grammar.tokenizeLine '{uri-repo}[Asciidoctor]' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[1]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'Asciidoctor', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[3]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] it 'start with "["', -> {tokens} = grammar.tokenizeLine '[{uri-repo}[Asciidoctor]' expect(tokens).toHaveLength 5 expect(tokens[0]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[1]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[2]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'Asciidoctor', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[4]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] it 'start with "("', -> {tokens} = grammar.tokenizeLine '({uri-repo}[Asciidoctor]' expect(tokens).toHaveLength 5 expect(tokens[0]).toEqualJson value: '(', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[1]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[2]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'Asciidoctor', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[4]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] it 'start with "<"', -> {tokens} = grammar.tokenizeLine '<{uri-repo}[Asciidoctor]' expect(tokens).toHaveLength 5 expect(tokens[0]).toEqualJson value: '<', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[1]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[2]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'Asciidoctor', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[4]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] it 'start with ">"', -> {tokens} = grammar.tokenizeLine '>{uri-repo}[Asciidoctor]' expect(tokens).toHaveLength 5 expect(tokens[0]).toEqualJson value: '>', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[1]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[2]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'Asciidoctor', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[4]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] it 'is in a phrase', -> {tokens} = grammar.tokenizeLine 'foo {uri-repo}[Asciidoctor] bar' expect(tokens).toHaveLength 7 expect(tokens[0]).toEqualJson value: 'foo', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[3]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[4]).toEqualJson value: 'Asciidoctor', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[5]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[6]).toEqualJson value: ' bar', scopes: ['source.asciidoc'] it 'attribute reference doesn\'t contains "uri-" (invalid context)', -> {tokens} = grammar.tokenizeLine 'foo {foo}[bar] bar' expect(tokens).toHaveLength 3 expect(tokens[0]).toEqualJson value: 'foo ', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: '{foo}', scopes: ['source.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[2]).toEqualJson value: '[bar] bar', scopes: ['source.asciidoc']
131830
describe 'Should tokenizes text link when', -> grammar = null beforeEach -> waitsForPromise -> atom.packages.activatePackage 'language-asciidoc' runs -> grammar = atom.grammars.grammarForScopeName 'source.asciidoc' it 'parses the grammar', -> expect(grammar).toBeDefined() expect(grammar.scopeName).toBe 'source.asciidoc' describe 'URL pattern', -> it 'is a simple url with http', -> {tokens} = grammar.tokenizeLine 'http://www.docbook.org/[DocBook.org]' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'http://www.docbook.org/', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[1]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'DocBook.org', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[3]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] it 'is a simple url with http in phrase', -> {tokens} = grammar.tokenizeLine 'Go on http://foobar.com now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'Go on', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'http://foobar.com', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple url with https', -> {tokens} = grammar.tokenizeLine 'Go on https://foobar.com now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'Go on', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'https://foobar.com', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple url with file', -> {tokens} = grammar.tokenizeLine 'Go on file://foobar.txt now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'Go on', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'file://foobar.txt', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple url with ftp', -> {tokens} = grammar.tokenizeLine 'Go on ftp://foobar.txt now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'Go on', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'ftp://foobar.txt', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple url with irc', -> {tokens} = grammar.tokenizeLine 'Go on irc://foobar now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'Go on', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'irc://foobar', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple url in a bullet list', -> {tokens} = grammar.tokenizeLine '* https://foobar.com now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: '*', scopes: ['source.asciidoc', 'markup.list.asciidoc', 'markup.list.bullet.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'https://foobar.com', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'contains attribute reference', -> {tokens} = grammar.tokenizeLine 'http://foo{uri-repo}bar.com now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'http://foo', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[1]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[2]).toEqualJson value: 'bar.com', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] describe '"link:" & "mailto:" macro', -> it 'have optional link text and attributes', -> {tokens} = grammar.tokenizeLine 'Go on link:url[optional link text, optional target attribute, optional role attribute] now' expect(tokens).toHaveLength 8 expect(tokens[0]).toEqualJson value: 'Go on ', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: 'link', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'entity.name.function.asciidoc'] expect(tokens[2]).toEqualJson value: ':', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'url', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[4]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[5]).toEqualJson value: 'optional link text, optional target attribute, optional role attribute', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[6]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[7]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple mailto', -> {tokens} = grammar.tokenizeLine 'Go on mailto:<EMAIL>[] now' expect(tokens).toHaveLength 6 expect(tokens[0]).toEqualJson value: 'Go on ', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: 'mailto', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'entity.name.function.asciidoc'] expect(tokens[2]).toEqualJson value: ':', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: '<EMAIL>', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[4]).toEqualJson value: '[]', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[5]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'contains attribute reference', -> {tokens} = grammar.tokenizeLine 'Go on link:http://{uri-repo}[label] now' expect(tokens).toHaveLength 9 expect(tokens[0]).toEqualJson value: 'Go on ', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: 'link', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'entity.name.function.asciidoc'] expect(tokens[2]).toEqualJson value: ':', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'http://', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[4]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[5]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[6]).toEqualJson value: 'label', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[7]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[8]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple url with https started with "link:" with missing square brackets ending (invalid context)', -> {tokens} = grammar.tokenizeLine 'Go on link:https://foobar.com now' expect(tokens).toHaveLength 1 expect(tokens[0]).toEqualJson value: 'Go on link:https://foobar.com now', scopes: ['source.asciidoc'] describe 'email pattern', -> it 'is a email', -> {tokens} = grammar.tokenizeLine 'foo <EMAIL> bar' expect(tokens).toHaveLength 3 expect(tokens[0]).toEqualJson value: 'foo ', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: '<EMAIL>', scopes: ['source.asciidoc', 'markup.link.email.asciidoc'] expect(tokens[2]).toEqualJson value: ' bar', scopes: ['source.asciidoc'] describe 'pure attribute reference link', -> it 'start at the beginning of the line', -> {tokens} = grammar.tokenizeLine '{uri-repo}[Asciidoctor]' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[1]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'Asciidoctor', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[3]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] it 'start with "["', -> {tokens} = grammar.tokenizeLine '[{uri-repo}[Asciidoctor]' expect(tokens).toHaveLength 5 expect(tokens[0]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[1]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[2]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'Asciidoctor', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[4]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] it 'start with "("', -> {tokens} = grammar.tokenizeLine '({uri-repo}[Asciidoctor]' expect(tokens).toHaveLength 5 expect(tokens[0]).toEqualJson value: '(', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[1]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[2]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'Asciidoctor', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[4]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] it 'start with "<"', -> {tokens} = grammar.tokenizeLine '<{uri-repo}[Asciidoctor]' expect(tokens).toHaveLength 5 expect(tokens[0]).toEqualJson value: '<', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[1]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[2]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'Asciidoctor', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[4]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] it 'start with ">"', -> {tokens} = grammar.tokenizeLine '>{uri-repo}[Asciidoctor]' expect(tokens).toHaveLength 5 expect(tokens[0]).toEqualJson value: '>', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[1]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[2]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'Asciidoctor', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[4]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] it 'is in a phrase', -> {tokens} = grammar.tokenizeLine 'foo {uri-repo}[Asciidoctor] bar' expect(tokens).toHaveLength 7 expect(tokens[0]).toEqualJson value: 'foo', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[3]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[4]).toEqualJson value: 'Asciidoctor', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[5]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[6]).toEqualJson value: ' bar', scopes: ['source.asciidoc'] it 'attribute reference doesn\'t contains "uri-" (invalid context)', -> {tokens} = grammar.tokenizeLine 'foo {foo}[bar] bar' expect(tokens).toHaveLength 3 expect(tokens[0]).toEqualJson value: 'foo ', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: '{foo}', scopes: ['source.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[2]).toEqualJson value: '[bar] bar', scopes: ['source.asciidoc']
true
describe 'Should tokenizes text link when', -> grammar = null beforeEach -> waitsForPromise -> atom.packages.activatePackage 'language-asciidoc' runs -> grammar = atom.grammars.grammarForScopeName 'source.asciidoc' it 'parses the grammar', -> expect(grammar).toBeDefined() expect(grammar.scopeName).toBe 'source.asciidoc' describe 'URL pattern', -> it 'is a simple url with http', -> {tokens} = grammar.tokenizeLine 'http://www.docbook.org/[DocBook.org]' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'http://www.docbook.org/', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[1]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'DocBook.org', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[3]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] it 'is a simple url with http in phrase', -> {tokens} = grammar.tokenizeLine 'Go on http://foobar.com now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'Go on', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'http://foobar.com', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple url with https', -> {tokens} = grammar.tokenizeLine 'Go on https://foobar.com now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'Go on', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'https://foobar.com', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple url with file', -> {tokens} = grammar.tokenizeLine 'Go on file://foobar.txt now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'Go on', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'file://foobar.txt', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple url with ftp', -> {tokens} = grammar.tokenizeLine 'Go on ftp://foobar.txt now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'Go on', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'ftp://foobar.txt', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple url with irc', -> {tokens} = grammar.tokenizeLine 'Go on irc://foobar now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'Go on', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'irc://foobar', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple url in a bullet list', -> {tokens} = grammar.tokenizeLine '* https://foobar.com now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: '*', scopes: ['source.asciidoc', 'markup.list.asciidoc', 'markup.list.bullet.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'https://foobar.com', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'contains attribute reference', -> {tokens} = grammar.tokenizeLine 'http://foo{uri-repo}bar.com now' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: 'http://foo', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[1]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[2]).toEqualJson value: 'bar.com', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[3]).toEqualJson value: ' now', scopes: ['source.asciidoc'] describe '"link:" & "mailto:" macro', -> it 'have optional link text and attributes', -> {tokens} = grammar.tokenizeLine 'Go on link:url[optional link text, optional target attribute, optional role attribute] now' expect(tokens).toHaveLength 8 expect(tokens[0]).toEqualJson value: 'Go on ', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: 'link', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'entity.name.function.asciidoc'] expect(tokens[2]).toEqualJson value: ':', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'url', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[4]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[5]).toEqualJson value: 'optional link text, optional target attribute, optional role attribute', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[6]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[7]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple mailto', -> {tokens} = grammar.tokenizeLine 'Go on mailto:PI:EMAIL:<EMAIL>END_PI[] now' expect(tokens).toHaveLength 6 expect(tokens[0]).toEqualJson value: 'Go on ', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: 'mailto', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'entity.name.function.asciidoc'] expect(tokens[2]).toEqualJson value: ':', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'PI:EMAIL:<EMAIL>END_PI', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[4]).toEqualJson value: '[]', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[5]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'contains attribute reference', -> {tokens} = grammar.tokenizeLine 'Go on link:http://{uri-repo}[label] now' expect(tokens).toHaveLength 9 expect(tokens[0]).toEqualJson value: 'Go on ', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: 'link', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'entity.name.function.asciidoc'] expect(tokens[2]).toEqualJson value: ':', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'http://', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc'] expect(tokens[4]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.link.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[5]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[6]).toEqualJson value: 'label', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[7]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[8]).toEqualJson value: ' now', scopes: ['source.asciidoc'] it 'is a simple url with https started with "link:" with missing square brackets ending (invalid context)', -> {tokens} = grammar.tokenizeLine 'Go on link:https://foobar.com now' expect(tokens).toHaveLength 1 expect(tokens[0]).toEqualJson value: 'Go on link:https://foobar.com now', scopes: ['source.asciidoc'] describe 'email pattern', -> it 'is a email', -> {tokens} = grammar.tokenizeLine 'foo PI:EMAIL:<EMAIL>END_PI bar' expect(tokens).toHaveLength 3 expect(tokens[0]).toEqualJson value: 'foo ', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: 'PI:EMAIL:<EMAIL>END_PI', scopes: ['source.asciidoc', 'markup.link.email.asciidoc'] expect(tokens[2]).toEqualJson value: ' bar', scopes: ['source.asciidoc'] describe 'pure attribute reference link', -> it 'start at the beginning of the line', -> {tokens} = grammar.tokenizeLine '{uri-repo}[Asciidoctor]' expect(tokens).toHaveLength 4 expect(tokens[0]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[1]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: 'Asciidoctor', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[3]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] it 'start with "["', -> {tokens} = grammar.tokenizeLine '[{uri-repo}[Asciidoctor]' expect(tokens).toHaveLength 5 expect(tokens[0]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[1]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[2]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'Asciidoctor', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[4]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] it 'start with "("', -> {tokens} = grammar.tokenizeLine '({uri-repo}[Asciidoctor]' expect(tokens).toHaveLength 5 expect(tokens[0]).toEqualJson value: '(', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[1]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[2]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'Asciidoctor', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[4]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] it 'start with "<"', -> {tokens} = grammar.tokenizeLine '<{uri-repo}[Asciidoctor]' expect(tokens).toHaveLength 5 expect(tokens[0]).toEqualJson value: '<', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[1]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[2]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'Asciidoctor', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[4]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] it 'start with ">"', -> {tokens} = grammar.tokenizeLine '>{uri-repo}[Asciidoctor]' expect(tokens).toHaveLength 5 expect(tokens[0]).toEqualJson value: '>', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[1]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[2]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[3]).toEqualJson value: 'Asciidoctor', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[4]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] it 'is in a phrase', -> {tokens} = grammar.tokenizeLine 'foo {uri-repo}[Asciidoctor] bar' expect(tokens).toHaveLength 7 expect(tokens[0]).toEqualJson value: 'foo', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: ' ', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[2]).toEqualJson value: '{uri-repo}', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[3]).toEqualJson value: '[', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[4]).toEqualJson value: 'Asciidoctor', scopes: ['source.asciidoc', 'markup.other.url.asciidoc', 'string.unquoted.asciidoc'] expect(tokens[5]).toEqualJson value: ']', scopes: ['source.asciidoc', 'markup.other.url.asciidoc'] expect(tokens[6]).toEqualJson value: ' bar', scopes: ['source.asciidoc'] it 'attribute reference doesn\'t contains "uri-" (invalid context)', -> {tokens} = grammar.tokenizeLine 'foo {foo}[bar] bar' expect(tokens).toHaveLength 3 expect(tokens[0]).toEqualJson value: 'foo ', scopes: ['source.asciidoc'] expect(tokens[1]).toEqualJson value: '{foo}', scopes: ['source.asciidoc', 'markup.substitution.attribute-reference.asciidoc'] expect(tokens[2]).toEqualJson value: '[bar] bar', scopes: ['source.asciidoc']
[ { "context": "###\nNicholas Clawson -2014\n\nTo be launched by an Atom Task, uses packa", "end": 20, "score": 0.9998179078102112, "start": 4, "tag": "NAME", "value": "Nicholas Clawson" } ]
lib/parse-config-task.coffee
dwelle/atom-grunt-runner
0
### Nicholas Clawson -2014 To be launched by an Atom Task, uses packages own grunt installation to parse a projects Gruntfile ### grunt = require 'grunt' # attempts to load the gruntfile module.exports = (path) -> var fn; try fn = require(path); catch e if !fn then return {error: "Gruntfile not found."} try fn(grunt) catch e error = e.code return {error: "Error parsing Gruntfile. " + e.message, tasks: Object.keys grunt.task._tasks}
53635
### <NAME> -2014 To be launched by an Atom Task, uses packages own grunt installation to parse a projects Gruntfile ### grunt = require 'grunt' # attempts to load the gruntfile module.exports = (path) -> var fn; try fn = require(path); catch e if !fn then return {error: "Gruntfile not found."} try fn(grunt) catch e error = e.code return {error: "Error parsing Gruntfile. " + e.message, tasks: Object.keys grunt.task._tasks}
true
### PI:NAME:<NAME>END_PI -2014 To be launched by an Atom Task, uses packages own grunt installation to parse a projects Gruntfile ### grunt = require 'grunt' # attempts to load the gruntfile module.exports = (path) -> var fn; try fn = require(path); catch e if !fn then return {error: "Gruntfile not found."} try fn(grunt) catch e error = e.code return {error: "Error parsing Gruntfile. " + e.message, tasks: Object.keys grunt.task._tasks}
[ { "context": "###\n* @author Andrew D.Laptev <a.d.laptev@gmail.com>\n###\n\n###global describe, b", "end": 29, "score": 0.9998903274536133, "start": 14, "tag": "NAME", "value": "Andrew D.Laptev" }, { "context": "###\n* @author Andrew D.Laptev <a.d.laptev@gmail.com>\n###\n\n###global describe, beforeEach, afterEach, ", "end": 51, "score": 0.9999344348907471, "start": 31, "tag": "EMAIL", "value": "a.d.laptev@gmail.com" } ]
test/test.order.coffee
agsh/boobst
16
### * @author Andrew D.Laptev <a.d.laptev@gmail.com> ### ###global describe, beforeEach, afterEach, it### assert = require 'assert' boobst = require '../boobst' BoobstSocket = boobst.BoobstSocket GLOBAL = '^test1'; describe 'order', () -> this.timeout 15000 bs = new BoobstSocket(require './test.config') # bs.on('debug', console.log); # uncomment for debug messages beforeEach (done) -> bs.connect (err) -> if err throw err this.set GLOBAL, [1, 'city'], 'Moscow' this.set GLOBAL, [2, 'city'], 'London' this.set GLOBAL, [3, 'city'], 'Paris' this.set GLOBAL, [4, 'city'], 'Detroit' this.set GLOBAL, [5, 'city'], 'Ottawa', () -> done() afterEach (done) -> bs.kill GLOBAL, () -> bs.disconnect () -> done() describe '#order test an empty string', () -> it 'should return first key', (done) -> bs.order GLOBAL, [''], (err, data) -> assert.equal err, null assert.equal data, '1' done() describe '#next method should work as order', () -> it 'should return first key', (done) -> bs.next GLOBAL, [''], (err, data) -> assert.equal err, null assert.equal data, '1' done() describe '#order test a first key', () -> it 'should return second key', (done) -> bs.order GLOBAL, ['1'], (err, data) -> assert.equal err, null assert.equal data, '2' done() describe '#order test last key', () -> it 'should return empty string', (done) -> bs.order GLOBAL, ['5'], (err, data) -> assert.equal err, null assert.equal data, '' done()
155667
### * @author <NAME> <<EMAIL>> ### ###global describe, beforeEach, afterEach, it### assert = require 'assert' boobst = require '../boobst' BoobstSocket = boobst.BoobstSocket GLOBAL = '^test1'; describe 'order', () -> this.timeout 15000 bs = new BoobstSocket(require './test.config') # bs.on('debug', console.log); # uncomment for debug messages beforeEach (done) -> bs.connect (err) -> if err throw err this.set GLOBAL, [1, 'city'], 'Moscow' this.set GLOBAL, [2, 'city'], 'London' this.set GLOBAL, [3, 'city'], 'Paris' this.set GLOBAL, [4, 'city'], 'Detroit' this.set GLOBAL, [5, 'city'], 'Ottawa', () -> done() afterEach (done) -> bs.kill GLOBAL, () -> bs.disconnect () -> done() describe '#order test an empty string', () -> it 'should return first key', (done) -> bs.order GLOBAL, [''], (err, data) -> assert.equal err, null assert.equal data, '1' done() describe '#next method should work as order', () -> it 'should return first key', (done) -> bs.next GLOBAL, [''], (err, data) -> assert.equal err, null assert.equal data, '1' done() describe '#order test a first key', () -> it 'should return second key', (done) -> bs.order GLOBAL, ['1'], (err, data) -> assert.equal err, null assert.equal data, '2' done() describe '#order test last key', () -> it 'should return empty string', (done) -> bs.order GLOBAL, ['5'], (err, data) -> assert.equal err, null assert.equal data, '' done()
true
### * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### ###global describe, beforeEach, afterEach, it### assert = require 'assert' boobst = require '../boobst' BoobstSocket = boobst.BoobstSocket GLOBAL = '^test1'; describe 'order', () -> this.timeout 15000 bs = new BoobstSocket(require './test.config') # bs.on('debug', console.log); # uncomment for debug messages beforeEach (done) -> bs.connect (err) -> if err throw err this.set GLOBAL, [1, 'city'], 'Moscow' this.set GLOBAL, [2, 'city'], 'London' this.set GLOBAL, [3, 'city'], 'Paris' this.set GLOBAL, [4, 'city'], 'Detroit' this.set GLOBAL, [5, 'city'], 'Ottawa', () -> done() afterEach (done) -> bs.kill GLOBAL, () -> bs.disconnect () -> done() describe '#order test an empty string', () -> it 'should return first key', (done) -> bs.order GLOBAL, [''], (err, data) -> assert.equal err, null assert.equal data, '1' done() describe '#next method should work as order', () -> it 'should return first key', (done) -> bs.next GLOBAL, [''], (err, data) -> assert.equal err, null assert.equal data, '1' done() describe '#order test a first key', () -> it 'should return second key', (done) -> bs.order GLOBAL, ['1'], (err, data) -> assert.equal err, null assert.equal data, '2' done() describe '#order test last key', () -> it 'should return empty string', (done) -> bs.order GLOBAL, ['5'], (err, data) -> assert.equal err, null assert.equal data, '' done()
[ { "context": "overview Tests for no-duplicate-imports.\n# @author Simen Bekkhus\n###\n\n'use strict'\n\n#-----------------------------", "end": 76, "score": 0.9998548626899719, "start": 63, "tag": "NAME", "value": "Simen Bekkhus" } ]
src/tests/rules/no-duplicate-imports.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for no-duplicate-imports. # @author Simen Bekkhus ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/no-duplicate-imports' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-duplicate-imports', rule, valid: [ 'import os from "os"\nimport fs from "fs"' 'import { merge } from "lodash-es"' 'import _, { merge } from "lodash-es"' 'import * as Foobar from "async"' 'import "foo"' 'import os from "os"\nexport { something } from "os"' , code: 'import os from "os"\nexport { hello } from "hello"' options: [includeExports: yes] , code: 'import os from "os"\nexport * from "hello"' options: [includeExports: yes] , code: 'import os from "os"\nexport { hello as hi } from "hello"' options: [includeExports: yes] , code: 'import os from "os"\nexport default ->' options: [includeExports: yes] , code: 'import { merge } from "lodash-es"\nexport { merge as lodashMerge }' options: [includeExports: yes] ] invalid: [ code: 'import "fs"\nimport "fs"' errors: [message: "'fs' import is duplicated.", type: 'ImportDeclaration'] , code: 'import { merge } from "lodash-es"\nimport { find } from "lodash-es"' errors: [ message: "'lodash-es' import is duplicated.", type: 'ImportDeclaration' ] , code: 'import { merge } from "lodash-es"\nimport _ from "lodash-es"' errors: [ message: "'lodash-es' import is duplicated.", type: 'ImportDeclaration' ] , code: 'export { os } from "os"\nexport { something } from "os"' options: [includeExports: yes] errors: [ message: "'os' export is duplicated.", type: 'ExportNamedDeclaration' ] , code: 'import os from "os"\nexport { os as foobar } from "os"\nexport { something } from "os"' options: [includeExports: yes] errors: [ message: "'os' export is duplicated as import." type: 'ExportNamedDeclaration' , message: "'os' export is duplicated.", type: 'ExportNamedDeclaration' , message: "'os' export is duplicated as import." type: 'ExportNamedDeclaration' ] , code: 'import os from "os"\nexport { something } from "os"' options: [includeExports: yes] errors: [ message: "'os' export is duplicated as import." type: 'ExportNamedDeclaration' ] , code: 'import os from "os"\nexport * from "os"' options: [includeExports: yes] errors: [ message: "'os' export is duplicated as import." type: 'ExportAllDeclaration' ] ]
110439
###* # @fileoverview Tests for no-duplicate-imports. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/no-duplicate-imports' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-duplicate-imports', rule, valid: [ 'import os from "os"\nimport fs from "fs"' 'import { merge } from "lodash-es"' 'import _, { merge } from "lodash-es"' 'import * as Foobar from "async"' 'import "foo"' 'import os from "os"\nexport { something } from "os"' , code: 'import os from "os"\nexport { hello } from "hello"' options: [includeExports: yes] , code: 'import os from "os"\nexport * from "hello"' options: [includeExports: yes] , code: 'import os from "os"\nexport { hello as hi } from "hello"' options: [includeExports: yes] , code: 'import os from "os"\nexport default ->' options: [includeExports: yes] , code: 'import { merge } from "lodash-es"\nexport { merge as lodashMerge }' options: [includeExports: yes] ] invalid: [ code: 'import "fs"\nimport "fs"' errors: [message: "'fs' import is duplicated.", type: 'ImportDeclaration'] , code: 'import { merge } from "lodash-es"\nimport { find } from "lodash-es"' errors: [ message: "'lodash-es' import is duplicated.", type: 'ImportDeclaration' ] , code: 'import { merge } from "lodash-es"\nimport _ from "lodash-es"' errors: [ message: "'lodash-es' import is duplicated.", type: 'ImportDeclaration' ] , code: 'export { os } from "os"\nexport { something } from "os"' options: [includeExports: yes] errors: [ message: "'os' export is duplicated.", type: 'ExportNamedDeclaration' ] , code: 'import os from "os"\nexport { os as foobar } from "os"\nexport { something } from "os"' options: [includeExports: yes] errors: [ message: "'os' export is duplicated as import." type: 'ExportNamedDeclaration' , message: "'os' export is duplicated.", type: 'ExportNamedDeclaration' , message: "'os' export is duplicated as import." type: 'ExportNamedDeclaration' ] , code: 'import os from "os"\nexport { something } from "os"' options: [includeExports: yes] errors: [ message: "'os' export is duplicated as import." type: 'ExportNamedDeclaration' ] , code: 'import os from "os"\nexport * from "os"' options: [includeExports: yes] errors: [ message: "'os' export is duplicated as import." type: 'ExportAllDeclaration' ] ]
true
###* # @fileoverview Tests for no-duplicate-imports. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/no-duplicate-imports' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-duplicate-imports', rule, valid: [ 'import os from "os"\nimport fs from "fs"' 'import { merge } from "lodash-es"' 'import _, { merge } from "lodash-es"' 'import * as Foobar from "async"' 'import "foo"' 'import os from "os"\nexport { something } from "os"' , code: 'import os from "os"\nexport { hello } from "hello"' options: [includeExports: yes] , code: 'import os from "os"\nexport * from "hello"' options: [includeExports: yes] , code: 'import os from "os"\nexport { hello as hi } from "hello"' options: [includeExports: yes] , code: 'import os from "os"\nexport default ->' options: [includeExports: yes] , code: 'import { merge } from "lodash-es"\nexport { merge as lodashMerge }' options: [includeExports: yes] ] invalid: [ code: 'import "fs"\nimport "fs"' errors: [message: "'fs' import is duplicated.", type: 'ImportDeclaration'] , code: 'import { merge } from "lodash-es"\nimport { find } from "lodash-es"' errors: [ message: "'lodash-es' import is duplicated.", type: 'ImportDeclaration' ] , code: 'import { merge } from "lodash-es"\nimport _ from "lodash-es"' errors: [ message: "'lodash-es' import is duplicated.", type: 'ImportDeclaration' ] , code: 'export { os } from "os"\nexport { something } from "os"' options: [includeExports: yes] errors: [ message: "'os' export is duplicated.", type: 'ExportNamedDeclaration' ] , code: 'import os from "os"\nexport { os as foobar } from "os"\nexport { something } from "os"' options: [includeExports: yes] errors: [ message: "'os' export is duplicated as import." type: 'ExportNamedDeclaration' , message: "'os' export is duplicated.", type: 'ExportNamedDeclaration' , message: "'os' export is duplicated as import." type: 'ExportNamedDeclaration' ] , code: 'import os from "os"\nexport { something } from "os"' options: [includeExports: yes] errors: [ message: "'os' export is duplicated as import." type: 'ExportNamedDeclaration' ] , code: 'import os from "os"\nexport * from "os"' options: [includeExports: yes] errors: [ message: "'os' export is duplicated as import." type: 'ExportAllDeclaration' ] ]
[ { "context": "module.exports = \"\"\"\n“Look, Mom, I made a moon!”\nShe holds aloft a crescent bitte", "end": 31, "score": 0.9016222953796387, "start": 28, "tag": "NAME", "value": "Mom" } ]
stories/crescent.coffee
STRd6/zine
12
module.exports = """ “Look, Mom, I made a moon!” She holds aloft a crescent bitten from cereal, and I feel a tug on my memory: not the usual familiarity of the Earth’s twirling, ever-changing little sister but something deeper, and more intimate, like a great truth, a resonance of great importance, had been uncovered within my mind as I slept, and was lost upon waking. And then she ate the moon. """
54612
module.exports = """ “Look, <NAME>, I made a moon!” She holds aloft a crescent bitten from cereal, and I feel a tug on my memory: not the usual familiarity of the Earth’s twirling, ever-changing little sister but something deeper, and more intimate, like a great truth, a resonance of great importance, had been uncovered within my mind as I slept, and was lost upon waking. And then she ate the moon. """
true
module.exports = """ “Look, PI:NAME:<NAME>END_PI, I made a moon!” She holds aloft a crescent bitten from cereal, and I feel a tug on my memory: not the usual familiarity of the Earth’s twirling, ever-changing little sister but something deeper, and more intimate, like a great truth, a resonance of great importance, had been uncovered within my mind as I slept, and was lost upon waking. And then she ate the moon. """
[ { "context": "d\n\n list.add_item {title: 'coffee', author: 'john'}\n\n item = list.where(title: 'coffee')[0]\n\n ", "end": 3836, "score": 0.9922918677330017, "start": 3832, "tag": "NAME", "value": "john" }, { "context": "r [ \n {id:1, name: 'Element 1', author: 'John'},\n {id:2, name: 'Element 2', author: 'B", "end": 5262, "score": 0.9997486472129822, "start": 5258, "tag": "NAME", "value": "John" }, { "context": "n'},\n {id:2, name: 'Element 2', author: 'Bob'},\n {id:3, name: 'Element 3', author: 'J", "end": 5314, "score": 0.9997355341911316, "start": 5311, "tag": "NAME", "value": "Bob" }, { "context": "b'},\n {id:3, name: 'Element 3', author: 'John'} \n ]\n expect(counter.text()).to.eq", "end": 5367, "score": 0.999739944934845, "start": 5363, "tag": "NAME", "value": "John" }, { "context": "der [ \n {id:1, name: 'Element 1', author: 'John'},\n {id:2, name: 'Element 2', author: 'Bob", "end": 5838, "score": 0.9997484087944031, "start": 5834, "tag": "NAME", "value": "John" }, { "context": "ohn'},\n {id:2, name: 'Element 2', author: 'Bob'},\n {id:3, name: 'Element 3', author: 'Joh", "end": 5888, "score": 0.9997637271881104, "start": 5885, "tag": "NAME", "value": "Bob" }, { "context": "Bob'},\n {id:3, name: 'Element 3', author: 'John'} \n ]\n expect(list.all('.item').length)", "end": 5939, "score": 0.9997994303703308, "start": 5935, "tag": "NAME", "value": "John" }, { "context": " expect(list.first('.author').text()).to.eq 'John'\n\n describe \"item_click\", ->\n it \"item after ", "end": 6052, "score": 0.9441231489181519, "start": 6048, "tag": "NAME", "value": "John" } ]
test/components/list/list_test.coffee
pieces-js/pieces-list
0
'use strict' h = require 'pieces-list/test/helpers' utils = pi.utils Nod = pi.Nod describe "List", -> root = h.test_cont(pi.Nod.body) after -> root.remove() test_div = list = null beforeEach -> test_div = Nod.create('div') test_div.style position:'relative' root.append test_div test_div.append """ <div class="pi test" data-component="list" data-pid="test" style="position:relative"> <ul class="list"> <li class="item" data-id="1" data-key="one">One<span class="tags">killer,puppy</span></li> <li class="item" data-id="2" data-key="someone">Two<span class="tags">puppy, coward</span></li> <li class="item" data-id="3" data-key="anyone">Tre<span class="tags">bully,zombopuppy</span></li> </ul> </div> """ pi.app.view.piecify() list = test_div.find('.test') afterEach -> test_div.remove_children() describe "basics", -> it "parse list items", -> expect(list.size).to.eq 3 it "add item", -> item = Nod.create('<li class="item" data-id="4" data-key="new">New</li>') el = list.add_item item expect(el.record.$index).to.eq 3 expect(list.size).to.eq 4 expect(test_div.find('.test').last('.item').text()).to.eq 'New' it "add item at index", -> item = Nod.create('<li class="item" data-id="4" data-key="new">New</li>') el = list.add_item_at item, 0 expect(el.record.$index).to.eq 0 expect(list.items[1].record.$index).to.eq 1 expect(list.size).to.eq 4 expect(test_div.find('.test').first('.item').text()).to.eq 'New' it "trigger update event on add", (done) -> item = Nod.create('<li class="item" data-id="4" data-key="new">New</li>') list.on 'update', (event) => expect(event.data.item.record.id).to.eq 4 done() list.add_item_at item, 0 it "remove element at", -> list.remove_item_at 0 expect(list.size).to.eq 2 expect(list.items[1].record.$index).to.eq 1 expect(test_div.find('.test').first('.item').data('id')).to.eq 2 it "remove many items", -> list.remove_items [list.items[0],list.items[2]] expect(list.size).to.eq 1 expect(test_div.find('.test').first('.item').data('id')).to.eq 2 it "update element and trigger item's events", (done) -> item = Nod.create('<li class="item" data-id="4" data-key="new">New</li>') old_item = list.items[0] old_item.disable() old_item.addClass 'is-fucked-up' old_item.on 'click', -> done() list.on 'update', (event) => expect(event.data.item).to.eq old_item expect(event.data.item.hasClass('is-disabled')).to.be.true expect(event.data.item.hasClass('is-fucked-up')).to.be.false expect(event.data.item.enabled).to.eq false expect(event.data.type).to.eq 'item_updated' expect(event.data.item.record.id).to.eq 4 expect(event.data.item.record.key).to.eq 'new' expect((test_div.find('.test').text()).trim()).to.eq 'NewTwopuppy, cowardTrebully,zombopuppy' event.data.item.enable() h.clickElement test_div.find(".test").first(".item").node list.update_item old_item, item it "clear all", -> list.clear() expect(test_div.find('.test').find('.item')).to.be.null it "create items nods as components", -> expect(list.items[0]).to.be.an.instanceof $c.Base it "peicify items nods", -> list.renderer = render: (data, _, host) -> nod = Nod.create("<div>#{ data.title }</div>") nod.addClass 'item' nod.append "<span class='author pi'>#{ data.author }</span>" nod = nod.piecify(host) pi.utils.extend nod, data nod list.add_item {title: 'coffee', author: 'john'} item = list.where(title: 'coffee')[0] expect(item).to.be.an.instanceof $c.Base expect(item.host).to.eq list expect(item.find('.author')).to.be.an.instanceof $c.Base describe "bindings", -> describe "size", -> counter = null beforeEach -> list.append """ <span class="pi counter" data-bind-text="host.size > 5 ? '5+' : host.size"></span> """ list.piecify() counter = list.find('.counter') afterEach -> counter.remove() it "init", -> expect(counter.text()).to.eq '3' it "handle item add", -> item = Nod.create('<li class="item" data-id="4" data-key="new">New</li>') list.add_item item expect(counter.text()).to.eq '4' it "handle remove item", -> list.remove_item_at 1 expect(counter.text()).to.eq '2' it "handle clear", -> list.clear() expect(counter.text()).to.eq '0' it "handle data_provider", -> list.renderer = render: (data) -> nod = Nod.create("<div>#{ data.name }</div>") nod.addClass 'item' nod.append "<span class='author'>#{ data.author }</span>" nod.record = data nod list.data_provider [] expect(counter.text()).to.eq '0' list.data_provider [ {id:1, name: 'Element 1', author: 'John'}, {id:2, name: 'Element 2', author: 'Bob'}, {id:3, name: 'Element 3', author: 'John'} ] expect(counter.text()).to.eq '3' describe "renderers", -> beforeEach -> list.renderer = render: (data) -> nod = Nod.create("<div>#{ data.name }</div>") nod.addClass 'item' nod.append "<span class='author'>#{ data.author }</span>" nod.record = data nod return it "render items", -> list.data_provider [ {id:1, name: 'Element 1', author: 'John'}, {id:2, name: 'Element 2', author: 'Bob'}, {id:3, name: 'Element 3', author: 'John'} ] expect(list.all('.item').length).to.eq 3 expect(list.first('.author').text()).to.eq 'John' describe "item_click", -> it "item after list modification", (done) -> list.remove_item_at 0 list.on 'item_click', (e) => expect(e.data.item.record.id).to.eq 2 done() h.clickElement test_div.find(".test").first(".item").node it "item when click on child element", (done) -> list.on 'item_click', (e) => expect(e.data.item.record.id).to.eq 2 done() h.clickElement test_div.find(".test").find(".item:nth-child(2) .tags").node it "don't trigger on clickable element", (done) -> list.add_item Nod.create "<div class='item'>hi<a href='#' class='linko'>click</a></div>" list.on 'item_click', (e) => expect(true).to.be.false done() utils.after 500, -> done() h.clickElement test_div.find(".test").find(".item .linko").node describe "where", -> it "find by simple one-key object", -> item = list.where(record:{id:1})[0] expect(item.record.key).to.eq 'one' it "find by object with string matcher", -> [item] = list.where(record:{key:'one'}) expect(item.record.id).to.eq 1 it "find by simple string query", -> item = list.where('Tre')[0] expect(item.record.key).to.eq 'anyone' it "find by nested string query", -> [item1,item2] = list.where('.tags:\\bpuppy\\b') expect(item1.record.key).to.eq 'one' expect(item2.record.key).to.eq 'someone'
54670
'use strict' h = require 'pieces-list/test/helpers' utils = pi.utils Nod = pi.Nod describe "List", -> root = h.test_cont(pi.Nod.body) after -> root.remove() test_div = list = null beforeEach -> test_div = Nod.create('div') test_div.style position:'relative' root.append test_div test_div.append """ <div class="pi test" data-component="list" data-pid="test" style="position:relative"> <ul class="list"> <li class="item" data-id="1" data-key="one">One<span class="tags">killer,puppy</span></li> <li class="item" data-id="2" data-key="someone">Two<span class="tags">puppy, coward</span></li> <li class="item" data-id="3" data-key="anyone">Tre<span class="tags">bully,zombopuppy</span></li> </ul> </div> """ pi.app.view.piecify() list = test_div.find('.test') afterEach -> test_div.remove_children() describe "basics", -> it "parse list items", -> expect(list.size).to.eq 3 it "add item", -> item = Nod.create('<li class="item" data-id="4" data-key="new">New</li>') el = list.add_item item expect(el.record.$index).to.eq 3 expect(list.size).to.eq 4 expect(test_div.find('.test').last('.item').text()).to.eq 'New' it "add item at index", -> item = Nod.create('<li class="item" data-id="4" data-key="new">New</li>') el = list.add_item_at item, 0 expect(el.record.$index).to.eq 0 expect(list.items[1].record.$index).to.eq 1 expect(list.size).to.eq 4 expect(test_div.find('.test').first('.item').text()).to.eq 'New' it "trigger update event on add", (done) -> item = Nod.create('<li class="item" data-id="4" data-key="new">New</li>') list.on 'update', (event) => expect(event.data.item.record.id).to.eq 4 done() list.add_item_at item, 0 it "remove element at", -> list.remove_item_at 0 expect(list.size).to.eq 2 expect(list.items[1].record.$index).to.eq 1 expect(test_div.find('.test').first('.item').data('id')).to.eq 2 it "remove many items", -> list.remove_items [list.items[0],list.items[2]] expect(list.size).to.eq 1 expect(test_div.find('.test').first('.item').data('id')).to.eq 2 it "update element and trigger item's events", (done) -> item = Nod.create('<li class="item" data-id="4" data-key="new">New</li>') old_item = list.items[0] old_item.disable() old_item.addClass 'is-fucked-up' old_item.on 'click', -> done() list.on 'update', (event) => expect(event.data.item).to.eq old_item expect(event.data.item.hasClass('is-disabled')).to.be.true expect(event.data.item.hasClass('is-fucked-up')).to.be.false expect(event.data.item.enabled).to.eq false expect(event.data.type).to.eq 'item_updated' expect(event.data.item.record.id).to.eq 4 expect(event.data.item.record.key).to.eq 'new' expect((test_div.find('.test').text()).trim()).to.eq 'NewTwopuppy, cowardTrebully,zombopuppy' event.data.item.enable() h.clickElement test_div.find(".test").first(".item").node list.update_item old_item, item it "clear all", -> list.clear() expect(test_div.find('.test').find('.item')).to.be.null it "create items nods as components", -> expect(list.items[0]).to.be.an.instanceof $c.Base it "peicify items nods", -> list.renderer = render: (data, _, host) -> nod = Nod.create("<div>#{ data.title }</div>") nod.addClass 'item' nod.append "<span class='author pi'>#{ data.author }</span>" nod = nod.piecify(host) pi.utils.extend nod, data nod list.add_item {title: 'coffee', author: '<NAME>'} item = list.where(title: 'coffee')[0] expect(item).to.be.an.instanceof $c.Base expect(item.host).to.eq list expect(item.find('.author')).to.be.an.instanceof $c.Base describe "bindings", -> describe "size", -> counter = null beforeEach -> list.append """ <span class="pi counter" data-bind-text="host.size > 5 ? '5+' : host.size"></span> """ list.piecify() counter = list.find('.counter') afterEach -> counter.remove() it "init", -> expect(counter.text()).to.eq '3' it "handle item add", -> item = Nod.create('<li class="item" data-id="4" data-key="new">New</li>') list.add_item item expect(counter.text()).to.eq '4' it "handle remove item", -> list.remove_item_at 1 expect(counter.text()).to.eq '2' it "handle clear", -> list.clear() expect(counter.text()).to.eq '0' it "handle data_provider", -> list.renderer = render: (data) -> nod = Nod.create("<div>#{ data.name }</div>") nod.addClass 'item' nod.append "<span class='author'>#{ data.author }</span>" nod.record = data nod list.data_provider [] expect(counter.text()).to.eq '0' list.data_provider [ {id:1, name: 'Element 1', author: '<NAME>'}, {id:2, name: 'Element 2', author: '<NAME>'}, {id:3, name: 'Element 3', author: '<NAME>'} ] expect(counter.text()).to.eq '3' describe "renderers", -> beforeEach -> list.renderer = render: (data) -> nod = Nod.create("<div>#{ data.name }</div>") nod.addClass 'item' nod.append "<span class='author'>#{ data.author }</span>" nod.record = data nod return it "render items", -> list.data_provider [ {id:1, name: 'Element 1', author: '<NAME>'}, {id:2, name: 'Element 2', author: '<NAME>'}, {id:3, name: 'Element 3', author: '<NAME>'} ] expect(list.all('.item').length).to.eq 3 expect(list.first('.author').text()).to.eq '<NAME>' describe "item_click", -> it "item after list modification", (done) -> list.remove_item_at 0 list.on 'item_click', (e) => expect(e.data.item.record.id).to.eq 2 done() h.clickElement test_div.find(".test").first(".item").node it "item when click on child element", (done) -> list.on 'item_click', (e) => expect(e.data.item.record.id).to.eq 2 done() h.clickElement test_div.find(".test").find(".item:nth-child(2) .tags").node it "don't trigger on clickable element", (done) -> list.add_item Nod.create "<div class='item'>hi<a href='#' class='linko'>click</a></div>" list.on 'item_click', (e) => expect(true).to.be.false done() utils.after 500, -> done() h.clickElement test_div.find(".test").find(".item .linko").node describe "where", -> it "find by simple one-key object", -> item = list.where(record:{id:1})[0] expect(item.record.key).to.eq 'one' it "find by object with string matcher", -> [item] = list.where(record:{key:'one'}) expect(item.record.id).to.eq 1 it "find by simple string query", -> item = list.where('Tre')[0] expect(item.record.key).to.eq 'anyone' it "find by nested string query", -> [item1,item2] = list.where('.tags:\\bpuppy\\b') expect(item1.record.key).to.eq 'one' expect(item2.record.key).to.eq 'someone'
true
'use strict' h = require 'pieces-list/test/helpers' utils = pi.utils Nod = pi.Nod describe "List", -> root = h.test_cont(pi.Nod.body) after -> root.remove() test_div = list = null beforeEach -> test_div = Nod.create('div') test_div.style position:'relative' root.append test_div test_div.append """ <div class="pi test" data-component="list" data-pid="test" style="position:relative"> <ul class="list"> <li class="item" data-id="1" data-key="one">One<span class="tags">killer,puppy</span></li> <li class="item" data-id="2" data-key="someone">Two<span class="tags">puppy, coward</span></li> <li class="item" data-id="3" data-key="anyone">Tre<span class="tags">bully,zombopuppy</span></li> </ul> </div> """ pi.app.view.piecify() list = test_div.find('.test') afterEach -> test_div.remove_children() describe "basics", -> it "parse list items", -> expect(list.size).to.eq 3 it "add item", -> item = Nod.create('<li class="item" data-id="4" data-key="new">New</li>') el = list.add_item item expect(el.record.$index).to.eq 3 expect(list.size).to.eq 4 expect(test_div.find('.test').last('.item').text()).to.eq 'New' it "add item at index", -> item = Nod.create('<li class="item" data-id="4" data-key="new">New</li>') el = list.add_item_at item, 0 expect(el.record.$index).to.eq 0 expect(list.items[1].record.$index).to.eq 1 expect(list.size).to.eq 4 expect(test_div.find('.test').first('.item').text()).to.eq 'New' it "trigger update event on add", (done) -> item = Nod.create('<li class="item" data-id="4" data-key="new">New</li>') list.on 'update', (event) => expect(event.data.item.record.id).to.eq 4 done() list.add_item_at item, 0 it "remove element at", -> list.remove_item_at 0 expect(list.size).to.eq 2 expect(list.items[1].record.$index).to.eq 1 expect(test_div.find('.test').first('.item').data('id')).to.eq 2 it "remove many items", -> list.remove_items [list.items[0],list.items[2]] expect(list.size).to.eq 1 expect(test_div.find('.test').first('.item').data('id')).to.eq 2 it "update element and trigger item's events", (done) -> item = Nod.create('<li class="item" data-id="4" data-key="new">New</li>') old_item = list.items[0] old_item.disable() old_item.addClass 'is-fucked-up' old_item.on 'click', -> done() list.on 'update', (event) => expect(event.data.item).to.eq old_item expect(event.data.item.hasClass('is-disabled')).to.be.true expect(event.data.item.hasClass('is-fucked-up')).to.be.false expect(event.data.item.enabled).to.eq false expect(event.data.type).to.eq 'item_updated' expect(event.data.item.record.id).to.eq 4 expect(event.data.item.record.key).to.eq 'new' expect((test_div.find('.test').text()).trim()).to.eq 'NewTwopuppy, cowardTrebully,zombopuppy' event.data.item.enable() h.clickElement test_div.find(".test").first(".item").node list.update_item old_item, item it "clear all", -> list.clear() expect(test_div.find('.test').find('.item')).to.be.null it "create items nods as components", -> expect(list.items[0]).to.be.an.instanceof $c.Base it "peicify items nods", -> list.renderer = render: (data, _, host) -> nod = Nod.create("<div>#{ data.title }</div>") nod.addClass 'item' nod.append "<span class='author pi'>#{ data.author }</span>" nod = nod.piecify(host) pi.utils.extend nod, data nod list.add_item {title: 'coffee', author: 'PI:NAME:<NAME>END_PI'} item = list.where(title: 'coffee')[0] expect(item).to.be.an.instanceof $c.Base expect(item.host).to.eq list expect(item.find('.author')).to.be.an.instanceof $c.Base describe "bindings", -> describe "size", -> counter = null beforeEach -> list.append """ <span class="pi counter" data-bind-text="host.size > 5 ? '5+' : host.size"></span> """ list.piecify() counter = list.find('.counter') afterEach -> counter.remove() it "init", -> expect(counter.text()).to.eq '3' it "handle item add", -> item = Nod.create('<li class="item" data-id="4" data-key="new">New</li>') list.add_item item expect(counter.text()).to.eq '4' it "handle remove item", -> list.remove_item_at 1 expect(counter.text()).to.eq '2' it "handle clear", -> list.clear() expect(counter.text()).to.eq '0' it "handle data_provider", -> list.renderer = render: (data) -> nod = Nod.create("<div>#{ data.name }</div>") nod.addClass 'item' nod.append "<span class='author'>#{ data.author }</span>" nod.record = data nod list.data_provider [] expect(counter.text()).to.eq '0' list.data_provider [ {id:1, name: 'Element 1', author: 'PI:NAME:<NAME>END_PI'}, {id:2, name: 'Element 2', author: 'PI:NAME:<NAME>END_PI'}, {id:3, name: 'Element 3', author: 'PI:NAME:<NAME>END_PI'} ] expect(counter.text()).to.eq '3' describe "renderers", -> beforeEach -> list.renderer = render: (data) -> nod = Nod.create("<div>#{ data.name }</div>") nod.addClass 'item' nod.append "<span class='author'>#{ data.author }</span>" nod.record = data nod return it "render items", -> list.data_provider [ {id:1, name: 'Element 1', author: 'PI:NAME:<NAME>END_PI'}, {id:2, name: 'Element 2', author: 'PI:NAME:<NAME>END_PI'}, {id:3, name: 'Element 3', author: 'PI:NAME:<NAME>END_PI'} ] expect(list.all('.item').length).to.eq 3 expect(list.first('.author').text()).to.eq 'PI:NAME:<NAME>END_PI' describe "item_click", -> it "item after list modification", (done) -> list.remove_item_at 0 list.on 'item_click', (e) => expect(e.data.item.record.id).to.eq 2 done() h.clickElement test_div.find(".test").first(".item").node it "item when click on child element", (done) -> list.on 'item_click', (e) => expect(e.data.item.record.id).to.eq 2 done() h.clickElement test_div.find(".test").find(".item:nth-child(2) .tags").node it "don't trigger on clickable element", (done) -> list.add_item Nod.create "<div class='item'>hi<a href='#' class='linko'>click</a></div>" list.on 'item_click', (e) => expect(true).to.be.false done() utils.after 500, -> done() h.clickElement test_div.find(".test").find(".item .linko").node describe "where", -> it "find by simple one-key object", -> item = list.where(record:{id:1})[0] expect(item.record.key).to.eq 'one' it "find by object with string matcher", -> [item] = list.where(record:{key:'one'}) expect(item.record.id).to.eq 1 it "find by simple string query", -> item = list.where('Tre')[0] expect(item.record.key).to.eq 'anyone' it "find by nested string query", -> [item1,item2] = list.where('.tags:\\bpuppy\\b') expect(item1.record.key).to.eq 'one' expect(item2.record.key).to.eq 'someone'
[ { "context": "anager\n device: {uuid: 'masseuse', token: 'assassin'}\n }\n return # promises\n\n shutItDown: ", "end": 1126, "score": 0.9936131834983826, "start": 1118, "tag": "PASSWORD", "value": "assassin" }, { "context": "port: 0xcafe\n uuid: 'masseuse'\n token: 'assassin'\n\n @connection.connect callback\n\n _workerFunc", "end": 1950, "score": 0.9969009757041931, "start": 1942, "tag": "PASSWORD", "value": "assassin" } ]
test/connect.coffee
octoblu/meshblu-core-protocol-adapter-xmpp
0
_ = require 'lodash' async = require 'async' UUID = require 'uuid' Redis = require 'ioredis' RedisNS = require '@octoblu/redis-ns' Server = require '../src/server' MeshbluXmpp = require 'meshblu-xmpp' { JobManagerResponder } = require 'meshblu-core-job-manager' class Connect constructor: ({@redisUri, @workerFunc}={}) -> queueId = UUID.v4() @requestQueueName = "test:request:queue:#{queueId}" @responseQueueName = "test:response:queue:#{queueId}" @namespace = 'ns' @redisUri = 'redis://localhost' @jobManager = new JobManagerResponder { @namespace @redisUri maxConnections: 1 jobTimeoutSeconds: 10 queueTimeoutSeconds: 10 jobLogSampleRate: 0 @requestQueueName @responseQueueName workerFunc: @_workerFunc } connect: (callback) => async.series [ @startJobManager @startServer @createConnection ], (error) => return callback error if error? callback null, { @sut @connection @jobManager device: {uuid: 'masseuse', token: 'assassin'} } return # promises shutItDown: (callback) => @connection.close() @jobManager.stop => @sut.stop callback startJobManager: (callback) => @jobManager.start callback startServer: (callback) => @sut = new Server { port: 0xcafe jobTimeoutSeconds: 10 jobLogQueue: 'sample-rate:1.00' jobLogSampleRate: '0.00' maxConnections: 100 jobLogRedisUri: @redisUri redisUri: @redisUri cacheRedisUri: @redisUri firehoseRedisUri: @redisUri namespace: @namespace firehoseNamespace: 'messages' @requestQueueName @responseQueueName } @sut.run callback createConnection: (callback) => @connection = new MeshbluXmpp hostname: 'localhost' port: 0xcafe uuid: 'masseuse' token: 'assassin' @connection.connect callback _workerFunc: (request, callback) => if _.get(request, 'metadata.jobType') == 'Authenticate' && _.get(request, 'metadata.auth.uuid') == 'masseuse' return callback null, metadata: code: 204 @workerFunc request, callback module.exports = Connect
147437
_ = require 'lodash' async = require 'async' UUID = require 'uuid' Redis = require 'ioredis' RedisNS = require '@octoblu/redis-ns' Server = require '../src/server' MeshbluXmpp = require 'meshblu-xmpp' { JobManagerResponder } = require 'meshblu-core-job-manager' class Connect constructor: ({@redisUri, @workerFunc}={}) -> queueId = UUID.v4() @requestQueueName = "test:request:queue:#{queueId}" @responseQueueName = "test:response:queue:#{queueId}" @namespace = 'ns' @redisUri = 'redis://localhost' @jobManager = new JobManagerResponder { @namespace @redisUri maxConnections: 1 jobTimeoutSeconds: 10 queueTimeoutSeconds: 10 jobLogSampleRate: 0 @requestQueueName @responseQueueName workerFunc: @_workerFunc } connect: (callback) => async.series [ @startJobManager @startServer @createConnection ], (error) => return callback error if error? callback null, { @sut @connection @jobManager device: {uuid: 'masseuse', token: '<PASSWORD>'} } return # promises shutItDown: (callback) => @connection.close() @jobManager.stop => @sut.stop callback startJobManager: (callback) => @jobManager.start callback startServer: (callback) => @sut = new Server { port: 0xcafe jobTimeoutSeconds: 10 jobLogQueue: 'sample-rate:1.00' jobLogSampleRate: '0.00' maxConnections: 100 jobLogRedisUri: @redisUri redisUri: @redisUri cacheRedisUri: @redisUri firehoseRedisUri: @redisUri namespace: @namespace firehoseNamespace: 'messages' @requestQueueName @responseQueueName } @sut.run callback createConnection: (callback) => @connection = new MeshbluXmpp hostname: 'localhost' port: 0xcafe uuid: 'masseuse' token: '<PASSWORD>' @connection.connect callback _workerFunc: (request, callback) => if _.get(request, 'metadata.jobType') == 'Authenticate' && _.get(request, 'metadata.auth.uuid') == 'masseuse' return callback null, metadata: code: 204 @workerFunc request, callback module.exports = Connect
true
_ = require 'lodash' async = require 'async' UUID = require 'uuid' Redis = require 'ioredis' RedisNS = require '@octoblu/redis-ns' Server = require '../src/server' MeshbluXmpp = require 'meshblu-xmpp' { JobManagerResponder } = require 'meshblu-core-job-manager' class Connect constructor: ({@redisUri, @workerFunc}={}) -> queueId = UUID.v4() @requestQueueName = "test:request:queue:#{queueId}" @responseQueueName = "test:response:queue:#{queueId}" @namespace = 'ns' @redisUri = 'redis://localhost' @jobManager = new JobManagerResponder { @namespace @redisUri maxConnections: 1 jobTimeoutSeconds: 10 queueTimeoutSeconds: 10 jobLogSampleRate: 0 @requestQueueName @responseQueueName workerFunc: @_workerFunc } connect: (callback) => async.series [ @startJobManager @startServer @createConnection ], (error) => return callback error if error? callback null, { @sut @connection @jobManager device: {uuid: 'masseuse', token: 'PI:PASSWORD:<PASSWORD>END_PI'} } return # promises shutItDown: (callback) => @connection.close() @jobManager.stop => @sut.stop callback startJobManager: (callback) => @jobManager.start callback startServer: (callback) => @sut = new Server { port: 0xcafe jobTimeoutSeconds: 10 jobLogQueue: 'sample-rate:1.00' jobLogSampleRate: '0.00' maxConnections: 100 jobLogRedisUri: @redisUri redisUri: @redisUri cacheRedisUri: @redisUri firehoseRedisUri: @redisUri namespace: @namespace firehoseNamespace: 'messages' @requestQueueName @responseQueueName } @sut.run callback createConnection: (callback) => @connection = new MeshbluXmpp hostname: 'localhost' port: 0xcafe uuid: 'masseuse' token: 'PI:PASSWORD:<PASSWORD>END_PI' @connection.connect callback _workerFunc: (request, callback) => if _.get(request, 'metadata.jobType') == 'Authenticate' && _.get(request, 'metadata.auth.uuid') == 'masseuse' return callback null, metadata: code: 204 @workerFunc request, callback module.exports = Connect
[ { "context": "\"2ZY48XPZ\",\\n \"quantity\": 1,\\n \"name\": \"New socks\",\\n \"price\": 1.25\\n }\\n ]\\n}'", "end": 1478, "score": 0.9743990898132324, "start": 1469, "tag": "NAME", "value": "New socks" } ]
node_modules/api-blueprint-http-formatter/test/fixtures/pairs.coffee
bootstraponline/swagger_poc
2
module.exports.post = request: method: 'POST' uri: '/shopping-cart' headers: 'User-Agent': 'curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8x zlib/1.2.5' 'Host': 'curltraceparser.apiary.io' 'Accept': '*/*' 'Content-Type': 'application/json' 'Content-Length': '39' body: '{ "product":"1AB23ORM", "quantity": 2 }' response: statusCode: '201' statusMessage: 'Created' headers: 'Content-Type': 'application/json' 'Date': 'Sun, 21 Jul 2009 14:51:09 GMT' 'X-Apiary-Ratelimit-Limit': '120' 'X-Apiary-Ratelimit-Remaining': '119' 'Content-Length': '50' 'Connection': 'keep-alive' body: '{ "status": "created", "url": "/shopping-cart/2" }' module.exports.get = request: method: 'GET' uri: '/shopping-cart' headers: 'User-Agent': 'curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8x zlib/1.2.5' 'Host': 'curltraceparser.apiary.io' 'Accept': '*/*' body: '' response: statusCode: '200' statusMessage: 'Created' headers: 'Content-Type': 'application/json' 'Date': 'Sun, 21 Jul 2009 14:51:09 GMT' 'X-Apiary-Ratelimit-Limit': '120' 'X-Apiary-Ratelimit-Remaining': '119' 'Content-Length': '50' 'Connection': 'keep-alive' body: '{\n "items": [\n {\n "url": "/shopping-cart/1",\n "product": "2ZY48XPZ",\n "quantity": 1,\n "name": "New socks",\n "price": 1.25\n }\n ]\n}'
72049
module.exports.post = request: method: 'POST' uri: '/shopping-cart' headers: 'User-Agent': 'curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8x zlib/1.2.5' 'Host': 'curltraceparser.apiary.io' 'Accept': '*/*' 'Content-Type': 'application/json' 'Content-Length': '39' body: '{ "product":"1AB23ORM", "quantity": 2 }' response: statusCode: '201' statusMessage: 'Created' headers: 'Content-Type': 'application/json' 'Date': 'Sun, 21 Jul 2009 14:51:09 GMT' 'X-Apiary-Ratelimit-Limit': '120' 'X-Apiary-Ratelimit-Remaining': '119' 'Content-Length': '50' 'Connection': 'keep-alive' body: '{ "status": "created", "url": "/shopping-cart/2" }' module.exports.get = request: method: 'GET' uri: '/shopping-cart' headers: 'User-Agent': 'curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8x zlib/1.2.5' 'Host': 'curltraceparser.apiary.io' 'Accept': '*/*' body: '' response: statusCode: '200' statusMessage: 'Created' headers: 'Content-Type': 'application/json' 'Date': 'Sun, 21 Jul 2009 14:51:09 GMT' 'X-Apiary-Ratelimit-Limit': '120' 'X-Apiary-Ratelimit-Remaining': '119' 'Content-Length': '50' 'Connection': 'keep-alive' body: '{\n "items": [\n {\n "url": "/shopping-cart/1",\n "product": "2ZY48XPZ",\n "quantity": 1,\n "name": "<NAME>",\n "price": 1.25\n }\n ]\n}'
true
module.exports.post = request: method: 'POST' uri: '/shopping-cart' headers: 'User-Agent': 'curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8x zlib/1.2.5' 'Host': 'curltraceparser.apiary.io' 'Accept': '*/*' 'Content-Type': 'application/json' 'Content-Length': '39' body: '{ "product":"1AB23ORM", "quantity": 2 }' response: statusCode: '201' statusMessage: 'Created' headers: 'Content-Type': 'application/json' 'Date': 'Sun, 21 Jul 2009 14:51:09 GMT' 'X-Apiary-Ratelimit-Limit': '120' 'X-Apiary-Ratelimit-Remaining': '119' 'Content-Length': '50' 'Connection': 'keep-alive' body: '{ "status": "created", "url": "/shopping-cart/2" }' module.exports.get = request: method: 'GET' uri: '/shopping-cart' headers: 'User-Agent': 'curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8x zlib/1.2.5' 'Host': 'curltraceparser.apiary.io' 'Accept': '*/*' body: '' response: statusCode: '200' statusMessage: 'Created' headers: 'Content-Type': 'application/json' 'Date': 'Sun, 21 Jul 2009 14:51:09 GMT' 'X-Apiary-Ratelimit-Limit': '120' 'X-Apiary-Ratelimit-Remaining': '119' 'Content-Length': '50' 'Connection': 'keep-alive' body: '{\n "items": [\n {\n "url": "/shopping-cart/1",\n "product": "2ZY48XPZ",\n "quantity": 1,\n "name": "PI:NAME:<NAME>END_PI",\n "price": 1.25\n }\n ]\n}'
[ { "context": "d: user.id\n email: user.email\n name: user.name\n created_at: (Date.parse(user.created_at) ", "end": 2767, "score": 0.8161744475364685, "start": 2758, "tag": "NAME", "value": "user.name" } ]
app/app.coffee
2947721120/travis-web
0
`import Ember from 'ember'` `import Resolver from 'ember/resolver'` `import loadInitializers from 'ember/load-initializers'` `import config from './config/environment'` Ember.MODEL_FACTORY_INJECTIONS = true Ember.LinkView.reopen( attributeBindings: ['alt'] ); App = Ember.Application.extend(Ember.Evented, LOG_TRANSITIONS: true LOG_TRANSITIONS_INTERNAL: true LOG_ACTIVE_GENERATION: true LOG_MODULE_RESOLVER: true LOG_VIEW_LOOKUPS: true #LOG_RESOLVER: true modulePrefix: config.modulePrefix podModulePrefix: config.podModulePrefix Resolver: Resolver lookup: -> @__container__.lookup.apply @__container__, arguments flash: (options) -> Travis.lookup('controller:flash').loadFlashes([options]) toggleSidebar: -> $('body').toggleClass('maximized') # TODO gotta force redraws here :/ element = $('<span></span>') $('#top .profile').append(element) Em.run.later (-> element.remove()), 10 element = $('<span></span>') $('#repo').append(element) Em.run.later (-> element.remove()), 10 ready: -> location.href = location.href.replace('#!/', '') if location.hash.slice(0, 2) == '#!' @on 'user:signed_in', (user) -> Travis.onUserUpdate(user) @on 'user:refreshed', (user) -> Travis.onUserUpdate(user) @on 'user:synced', (user) -> Travis.onUserUpdate(user) @on 'user:signed_out', () -> if config.userlike Travis.removeUserlike() currentDate: -> new Date() onUserUpdate: (user) -> if config.pro @identifyCustomer(user) if config.userlike @setupUserlike(user) @subscribePusher(user) subscribePusher: (user) -> return unless user.channels channels = user.channels if config.pro channels = channels.map (channel) -> if channel.match /^private-/ channel else "private-#{channel}" Travis.pusher.subscribeAll(channels) setupUserlike: (user) -> btn = document.getElementById('userlikeCustomTab') btn.classList.add("logged-in") userlikeData = window.userlikeData = {} userlikeData.user = {} userlikeData.user.name= user.login; userlikeData.user.email = user.email; unless document.getElementById('userlike-script') s = document.createElement('script') s.id = 'userlike-script' s.src = '//userlike-cdn-widgets.s3-eu-west-1.amazonaws.com/0327dbb23382ccbbb91b445b76e8a91d4b37d90ef9f2faf84e11177847ff7bb9.js' document.body.appendChild(s) removeUserlike: () -> btn = document.getElementById('userlikeCustomTab') btn.classList.remove("logged-in") identifyCustomer: (user) -> if _cio && _cio.identify _cio.identify id: user.id email: user.email name: user.name created_at: (Date.parse(user.created_at) / 1000) || null login: user.login ) loadInitializers(App, config.modulePrefix) `export default App`
22715
`import Ember from 'ember'` `import Resolver from 'ember/resolver'` `import loadInitializers from 'ember/load-initializers'` `import config from './config/environment'` Ember.MODEL_FACTORY_INJECTIONS = true Ember.LinkView.reopen( attributeBindings: ['alt'] ); App = Ember.Application.extend(Ember.Evented, LOG_TRANSITIONS: true LOG_TRANSITIONS_INTERNAL: true LOG_ACTIVE_GENERATION: true LOG_MODULE_RESOLVER: true LOG_VIEW_LOOKUPS: true #LOG_RESOLVER: true modulePrefix: config.modulePrefix podModulePrefix: config.podModulePrefix Resolver: Resolver lookup: -> @__container__.lookup.apply @__container__, arguments flash: (options) -> Travis.lookup('controller:flash').loadFlashes([options]) toggleSidebar: -> $('body').toggleClass('maximized') # TODO gotta force redraws here :/ element = $('<span></span>') $('#top .profile').append(element) Em.run.later (-> element.remove()), 10 element = $('<span></span>') $('#repo').append(element) Em.run.later (-> element.remove()), 10 ready: -> location.href = location.href.replace('#!/', '') if location.hash.slice(0, 2) == '#!' @on 'user:signed_in', (user) -> Travis.onUserUpdate(user) @on 'user:refreshed', (user) -> Travis.onUserUpdate(user) @on 'user:synced', (user) -> Travis.onUserUpdate(user) @on 'user:signed_out', () -> if config.userlike Travis.removeUserlike() currentDate: -> new Date() onUserUpdate: (user) -> if config.pro @identifyCustomer(user) if config.userlike @setupUserlike(user) @subscribePusher(user) subscribePusher: (user) -> return unless user.channels channels = user.channels if config.pro channels = channels.map (channel) -> if channel.match /^private-/ channel else "private-#{channel}" Travis.pusher.subscribeAll(channels) setupUserlike: (user) -> btn = document.getElementById('userlikeCustomTab') btn.classList.add("logged-in") userlikeData = window.userlikeData = {} userlikeData.user = {} userlikeData.user.name= user.login; userlikeData.user.email = user.email; unless document.getElementById('userlike-script') s = document.createElement('script') s.id = 'userlike-script' s.src = '//userlike-cdn-widgets.s3-eu-west-1.amazonaws.com/0327dbb23382ccbbb91b445b76e8a91d4b37d90ef9f2faf84e11177847ff7bb9.js' document.body.appendChild(s) removeUserlike: () -> btn = document.getElementById('userlikeCustomTab') btn.classList.remove("logged-in") identifyCustomer: (user) -> if _cio && _cio.identify _cio.identify id: user.id email: user.email name: <NAME> created_at: (Date.parse(user.created_at) / 1000) || null login: user.login ) loadInitializers(App, config.modulePrefix) `export default App`
true
`import Ember from 'ember'` `import Resolver from 'ember/resolver'` `import loadInitializers from 'ember/load-initializers'` `import config from './config/environment'` Ember.MODEL_FACTORY_INJECTIONS = true Ember.LinkView.reopen( attributeBindings: ['alt'] ); App = Ember.Application.extend(Ember.Evented, LOG_TRANSITIONS: true LOG_TRANSITIONS_INTERNAL: true LOG_ACTIVE_GENERATION: true LOG_MODULE_RESOLVER: true LOG_VIEW_LOOKUPS: true #LOG_RESOLVER: true modulePrefix: config.modulePrefix podModulePrefix: config.podModulePrefix Resolver: Resolver lookup: -> @__container__.lookup.apply @__container__, arguments flash: (options) -> Travis.lookup('controller:flash').loadFlashes([options]) toggleSidebar: -> $('body').toggleClass('maximized') # TODO gotta force redraws here :/ element = $('<span></span>') $('#top .profile').append(element) Em.run.later (-> element.remove()), 10 element = $('<span></span>') $('#repo').append(element) Em.run.later (-> element.remove()), 10 ready: -> location.href = location.href.replace('#!/', '') if location.hash.slice(0, 2) == '#!' @on 'user:signed_in', (user) -> Travis.onUserUpdate(user) @on 'user:refreshed', (user) -> Travis.onUserUpdate(user) @on 'user:synced', (user) -> Travis.onUserUpdate(user) @on 'user:signed_out', () -> if config.userlike Travis.removeUserlike() currentDate: -> new Date() onUserUpdate: (user) -> if config.pro @identifyCustomer(user) if config.userlike @setupUserlike(user) @subscribePusher(user) subscribePusher: (user) -> return unless user.channels channels = user.channels if config.pro channels = channels.map (channel) -> if channel.match /^private-/ channel else "private-#{channel}" Travis.pusher.subscribeAll(channels) setupUserlike: (user) -> btn = document.getElementById('userlikeCustomTab') btn.classList.add("logged-in") userlikeData = window.userlikeData = {} userlikeData.user = {} userlikeData.user.name= user.login; userlikeData.user.email = user.email; unless document.getElementById('userlike-script') s = document.createElement('script') s.id = 'userlike-script' s.src = '//userlike-cdn-widgets.s3-eu-west-1.amazonaws.com/0327dbb23382ccbbb91b445b76e8a91d4b37d90ef9f2faf84e11177847ff7bb9.js' document.body.appendChild(s) removeUserlike: () -> btn = document.getElementById('userlikeCustomTab') btn.classList.remove("logged-in") identifyCustomer: (user) -> if _cio && _cio.identify _cio.identify id: user.id email: user.email name: PI:NAME:<NAME>END_PI created_at: (Date.parse(user.created_at) / 1000) || null login: user.login ) loadInitializers(App, config.modulePrefix) `export default App`
[ { "context": "s\",\"Prov\",\"Eccl\",\"Song\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"", "end": 505, "score": 0.7880062460899353, "start": 502, "tag": "NAME", "value": "Dan" }, { "context": "ov\",\"Eccl\",\"Song\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"", "end": 511, "score": 0.6896846294403076, "start": 508, "tag": "NAME", "value": "Hos" }, { "context": "ccl\",\"Song\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"", "end": 518, "score": 0.8578065037727356, "start": 514, "tag": "NAME", "value": "Joel" }, { "context": "ong\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\"", "end": 522, "score": 0.576994001865387, "start": 521, "tag": "NAME", "value": "A" }, { "context": "sa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",", "end": 530, "score": 0.5764340758323669, "start": 528, "tag": "NAME", "value": "Ob" }, { "context": "r\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Mat", "end": 540, "score": 0.8576140403747559, "start": 535, "tag": "NAME", "value": "Jonah" }, { "context": ",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Ma", "end": 546, "score": 0.8191704154014587, "start": 543, "tag": "NAME", "value": "Mic" }, { "context": "\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",", "end": 550, "score": 0.6331985592842102, "start": 549, "tag": "NAME", "value": "N" }, { "context": "d\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",", "end": 584, "score": 0.607184648513794, "start": 581, "tag": "NAME", "value": "Mal" }, { "context": "nah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",\"2Cor\",", "end": 591, "score": 0.931102991104126, "start": 587, "tag": "NAME", "value": "Matt" }, { "context": "ic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",\"2Cor\",\"Gal\",\"", "end": 598, "score": 0.9509207010269165, "start": 594, "tag": "NAME", "value": "Mark" }, { "context": "h\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",\"2Cor\",\"Gal\",\"Eph\",\"P", "end": 605, "score": 0.8702282905578613, "start": 601, "tag": "NAME", "value": "Luke" }, { "context": "\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",\"2Cor\",\"Gal\",\"Eph\",\"Phil\",\"C", "end": 612, "score": 0.7003874182701111, "start": 608, "tag": "NAME", "value": "John" }, { "context": "al(\"Deut.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Josh (lt)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv", "end": 12777, "score": 0.9473060369491577, "start": 12776, "tag": "NAME", "value": "J" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: Josh (lt)\", ->\n\t\t`\n\t\texpect(p.parse(\"Jozues knyga 1", "end": 13036, "score": 0.9733173251152039, "start": 13035, "tag": "NAME", "value": "J" }, { "context": "handle book: 2Sam (lt)\", ->\n\t\t`\n\t\texpect(p.parse(\"Samuelio antra knyga 1:1\").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.pars", "end": 18446, "score": 0.9851301908493042, "start": 18426, "tag": "NAME", "value": "Samuelio antra knyga" }, { "context": "sis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.parse(\"2 Samuelio 1:1\").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.pars", "end": 18509, "score": 0.8891366124153137, "start": 18504, "tag": "NAME", "value": "uelio" }, { "context": "\")\n\t\tp.include_apocrypha(false)\n\t\texpect(p.parse(\"SAMUELIO ANTRA KNYGA 1:1\").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.pars", "end": 18726, "score": 0.9797894358634949, "start": 18706, "tag": "NAME", "value": "SAMUELIO ANTRA KNYGA" }, { "context": "handle book: 1Sam (lt)\", ->\n\t\t`\n\t\texpect(p.parse(\"Samuelio pirma knyga 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(", "end": 19285, "score": 0.965736448764801, "start": 19271, "tag": "NAME", "value": "Samuelio pirma" }, { "context": "sis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"1 Samuelio 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars", "end": 19354, "score": 0.7153061032295227, "start": 19349, "tag": "NAME", "value": "uelio" }, { "context": "\")\n\t\tp.include_apocrypha(false)\n\t\texpect(p.parse(\"SAMUELIO PIRMA KNYGA 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(", "end": 19565, "score": 0.8005093932151794, "start": 19551, "tag": "NAME", "value": "SAMUELIO PIRMA" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: Jer (lt)\", ->\n\t\t`\n\t\texpect(p.parse(\"Jeremijo knyga 1:", "end": 36200, "score": 0.6349391937255859, "start": 36197, "tag": "NAME", "value": "Jer" }, { "context": " handle book: Jer (lt)\", ->\n\t\t`\n\t\texpect(p.parse(\"Jeremijo knyga 1:1\").osis()).toEqual(\"Jer.1.1\")\n\t\texpect(p.parse", "end": 36247, "score": 0.8621200919151306, "start": 36233, "tag": "NAME", "value": "Jeremijo knyga" }, { "context": "\")\n\t\tp.include_apocrypha(false)\n\t\texpect(p.parse(\"JEREMIJO KNYGA 1:1\").osis()).toEqual(\"Jer.1.1\")\n\t\texpect(p.parse", "end": 36457, "score": 0.687281608581543, "start": 36443, "tag": "NAME", "value": "JEREMIJO KNYGA" }, { "context": "ual(\"Jer.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Ezek (lt)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv", "end": 36643, "score": 0.5225030779838562, "start": 36642, "tag": "NAME", "value": "E" }, { "context": "al(\"Ezek.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Dan (lt)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv_pa", "end": 37476, "score": 0.9808015823364258, "start": 37473, "tag": "NAME", "value": "Dan" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: Dan (lt)\", ->\n\t\t`\n\t\texpect(p.parse(\"Danieliaus knyga ", "end": 37734, "score": 0.9972079992294312, "start": 37731, "tag": "NAME", "value": "Dan" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: Jonah (lt)\", ->\n\t\t`\n\t\texpect(p.parse(\"Jonos knyga 1:1\")", "end": 41931, "score": 0.9276283979415894, "start": 41926, "tag": "NAME", "value": "Jonah" }, { "context": "\").osis()).toEqual(\"Jonah.1.1\")\n\t\texpect(p.parse(\"Jon 1:1\").osis()).toEqual(\"Jonah.1.1\")\n\t\tp.include_ap", "end": 42150, "score": 0.5610015392303467, "start": 42147, "tag": "NAME", "value": "Jon" }, { "context": "l(\"Jonah.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Mic (lt)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv_", "end": 42492, "score": 0.7920719385147095, "start": 42491, "tag": "NAME", "value": "M" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: Mic (lt)\", ->\n\t\t`\n\t\texpect(p.parse(\"Michejo knyga 1", "end": 42750, "score": 0.892266571521759, "start": 42749, "tag": "NAME", "value": "M" }, { "context": "ual(\"Mal.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Matt (lt)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv_pa", "end": 48350, "score": 0.8694980144500732, "start": 48346, "tag": "NAME", "value": "Matt" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: Matt (lt)\", ->\n\t\t`\n\t\texpect(p.parse(\"Evangelija pagal ", "end": 48609, "score": 0.8326902985572815, "start": 48605, "tag": "NAME", "value": "Matt" }, { "context": "(\"Mark.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Luke (lt)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv_pa", "end": 50314, "score": 0.7362920045852661, "start": 50311, "tag": "NAME", "value": "uke" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: Luke (lt)\", ->\n\t\t`\n\t\texpect(p.parse(\"Evangelija pagal ", "end": 50573, "score": 0.9280522465705872, "start": 50569, "tag": "NAME", "value": "Luke" }, { "context": "l(\"3John.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book John (lt)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv_pa", "end": 54564, "score": 0.8584562540054321, "start": 54560, "tag": "NAME", "value": "John" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: John (lt)\", ->\n\t\t`\n\t\texpect(p.parse(\"Evangelija pagal ", "end": 54823, "score": 0.9006345868110657, "start": 54819, "tag": "NAME", "value": "John" }, { "context": "1\").osis()).toEqual(\"John.1.1\")\n\t\texpect(p.parse(\"John 1:1\").osis()).toEqual(\"John.1.1\")\n\t\texpect(p.pars", "end": 55008, "score": 0.7535637021064758, "start": 55004, "tag": "NAME", "value": "John" }, { "context": "1\").osis()).toEqual(\"John.1.1\")\n\t\texpect(p.parse(\"JOHN 1:1\").osis()).toEqual(\"John.1.1\")\n\t\texpect(p.pars", "end": 55354, "score": 0.8560693860054016, "start": 55350, "tag": "NAME", "value": "JOHN" }, { "context": "ndle book: 2Tim (lt)\", ->\n\t\t`\n\t\texpect(p.parse(\"Antras laiskas Timotiejui 1:1\").osis()).toEqual(\"2Tim.1.1\")\n\t\texpect(p.pars", "end": 70454, "score": 0.8817618489265442, "start": 70431, "tag": "NAME", "value": "tras laiskas Timotiejui" }, { "context": ").osis()).toEqual(\"2Tim.1.1\")\n\t\texpect(p.parse(\"Antras laiškas Timotiejui 1:1\").osis()).toEqual(\"2Tim.1.1\")\n\t\texpect(p.pars", "end": 70532, "score": 0.8477889895439148, "start": 70509, "tag": "NAME", "value": "tras laiškas Timotiejui" }, { "context": "\")\n\t\tp.include_apocrypha(false)\n\t\texpect(p.parse(\"ANTRAS LAISKAS TIMOTIEJUI 1:1\").osis()).toEqual(\"2Tim.1.1\")\n\t\texpect(p.pars", "end": 70819, "score": 0.9512357115745544, "start": 70794, "tag": "NAME", "value": "ANTRAS LAISKAS TIMOTIEJUI" }, { "context": ").osis()).toEqual(\"2Tim.1.1\")\n\t\texpect(p.parse(\"ANTRAS LAIŠKAS TIMOTIEJUI 1:1\").osis()).toEqual(\"2Tim.1.1\")\n\t\texpect(p.pars", "end": 70897, "score": 0.8796328902244568, "start": 70874, "tag": "NAME", "value": "TRAS LAIŠKAS TIMOTIEJUI" }, { "context": "handle book: 1Tim (lt)\", ->\n\t\t`\n\t\texpect(p.parse(\"Pirmas laiskas Timotiejui 1:1\").osis()).toEqual(\"1Tim.1.1\")\n\t\texpect(p.pars", "end": 71469, "score": 0.8616160750389099, "start": 71444, "tag": "NAME", "value": "Pirmas laiskas Timotiejui" }, { "context": ".toEqual(\"1Tim.1.1\")\n\t\texpect(p.parse(\"Pirmas laiškas Timotiejui 1:1\").osis()).toEqual(\"1Tim.1.1\")\n\t\tex", "end": 71536, "score": 0.7161131501197815, "start": 71533, "tag": "NAME", "value": "kas" } ]
lib/bible-tools/lib/Bible-Passage-Reference-Parser/src/lt/spec.coffee
saiba-mais/bible-lessons
0
bcv_parser = require("../../js/lt_bcv_parser.js").bcv_parser describe "Parsing", -> p = {} beforeEach -> p = new bcv_parser p.options.osis_compaction_strategy = "b" p.options.sequence_combination_strategy = "combine" it "should round-trip OSIS references", -> p.set_options osis_compaction_strategy: "bc" books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","Dan","Hos","Joel","Amos","Obad","Jonah","Mic","Nah","Hab","Zeph","Hag","Zech","Mal","Matt","Mark","Luke","John","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range it "should round-trip OSIS Apocrypha references", -> p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b" p.include_apocrypha true books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range p.set_options ps151_strategy: "bc" expect(p.parse("Ps151.1").osis()).toEqual "Ps.151" expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1" expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2" p.include_apocrypha false for book in books bc = book + ".1" expect(p.parse(bc).osis()).toEqual "" it "should handle a preceding character", -> expect(p.parse(" Gen 1").osis()).toEqual "Gen.1" expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3" expect(p.parse("1Ps 1").osis()).toEqual "" expect(p.parse("11Sam 1").osis()).toEqual "" describe "Localized book Gen (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gen (lt)", -> ` expect(p.parse("Pradzios knyga 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Pradžios knyga 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Pradzios 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Pradžios 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Pr 1:1").osis()).toEqual("Gen.1.1") p.include_apocrypha(false) expect(p.parse("PRADZIOS KNYGA 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("PRADŽIOS KNYGA 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("PRADZIOS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("PRADŽIOS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("PR 1:1").osis()).toEqual("Gen.1.1") ` true describe "Localized book Exod (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Exod (lt)", -> ` expect(p.parse("Isejimo knyga 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Isėjimo knyga 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Išejimo knyga 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Išėjimo knyga 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Isejimo 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Isėjimo 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Išejimo 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Išėjimo 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Is 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Iš 1:1").osis()).toEqual("Exod.1.1") p.include_apocrypha(false) expect(p.parse("ISEJIMO KNYGA 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ISĖJIMO KNYGA 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("IŠEJIMO KNYGA 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("IŠĖJIMO KNYGA 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ISEJIMO 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ISĖJIMO 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("IŠEJIMO 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("IŠĖJIMO 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("IS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("IŠ 1:1").osis()).toEqual("Exod.1.1") ` true describe "Localized book Bel (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bel (lt)", -> ` expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1") ` true describe "Localized book Lev (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lev (lt)", -> ` expect(p.parse("Kunigu knyga 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Kunigų knyga 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Kunigu 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Kunigų 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Kun 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1") p.include_apocrypha(false) expect(p.parse("KUNIGU KNYGA 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("KUNIGŲ KNYGA 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("KUNIGU 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("KUNIGŲ 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("KUN 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1") ` true describe "Localized book Num (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Num (lt)", -> ` expect(p.parse("Skaiciu knyga 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaicių knyga 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaičiu knyga 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaičių knyga 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaiciu 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaicių 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaičiu 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaičių 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Sk 1:1").osis()).toEqual("Num.1.1") p.include_apocrypha(false) expect(p.parse("SKAICIU KNYGA 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAICIŲ KNYGA 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAIČIU KNYGA 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAIČIŲ KNYGA 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAICIU 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAICIŲ 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAIČIU 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAIČIŲ 1:1").osis()).toEqual("Num.1.1") expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SK 1:1").osis()).toEqual("Num.1.1") ` true describe "Localized book Sir (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sir (lt)", -> ` expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1") ` true describe "Localized book Wis (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Wis (lt)", -> ` expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1") ` true describe "Localized book Lam (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lam (lt)", -> ` expect(p.parse("Raudu knyga 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Raudų knyga 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Raudu 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Raudų 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Rd 1:1").osis()).toEqual("Lam.1.1") p.include_apocrypha(false) expect(p.parse("RAUDU KNYGA 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("RAUDŲ KNYGA 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("RAUDU 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("RAUDŲ 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("RD 1:1").osis()).toEqual("Lam.1.1") ` true describe "Localized book EpJer (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: EpJer (lt)", -> ` expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1") ` true describe "Localized book Rev (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rev (lt)", -> ` expect(p.parse("Apreiskimas Jonui 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Apreiškimas Jonui 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Apreiskimo Jonui 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Apreiškimo Jonui 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Apr 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1") p.include_apocrypha(false) expect(p.parse("APREISKIMAS JONUI 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("APREIŠKIMAS JONUI 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("APREISKIMO JONUI 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("APREIŠKIMO JONUI 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("APR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1") ` true describe "Localized book PrMan (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrMan (lt)", -> ` expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1") ` true describe "Localized book Deut (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Deut (lt)", -> ` expect(p.parse("Pakartoto Istatymo knyga 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Pakartoto Įstatymo knyga 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Pakartoto Istatymo 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Pakartoto Įstatymo 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Ist 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Įst 1:1").osis()).toEqual("Deut.1.1") p.include_apocrypha(false) expect(p.parse("PAKARTOTO ISTATYMO KNYGA 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("PAKARTOTO ĮSTATYMO KNYGA 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("PAKARTOTO ISTATYMO 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("PAKARTOTO ĮSTATYMO 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("IST 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("ĮST 1:1").osis()).toEqual("Deut.1.1") ` true describe "Localized book Josh (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Josh (lt)", -> ` expect(p.parse("Jozues knyga 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jozuės knyga 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jozues 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jozuės 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josh 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Joz 1:1").osis()).toEqual("Josh.1.1") p.include_apocrypha(false) expect(p.parse("JOZUES KNYGA 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOZUĖS KNYGA 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOZUES 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOZUĖS 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSH 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOZ 1:1").osis()).toEqual("Josh.1.1") ` true describe "Localized book Judg (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Judg (lt)", -> ` expect(p.parse("Teiseju knyga 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teisejų knyga 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teisėju knyga 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teisėjų knyga 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teiseju 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teisejų 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teisėju 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teisėjų 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Ts 1:1").osis()).toEqual("Judg.1.1") p.include_apocrypha(false) expect(p.parse("TEISEJU KNYGA 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISEJŲ KNYGA 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISĖJU KNYGA 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISĖJŲ KNYGA 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISEJU 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISEJŲ 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISĖJU 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISĖJŲ 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TS 1:1").osis()).toEqual("Judg.1.1") ` true describe "Localized book Ruth (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ruth (lt)", -> ` expect(p.parse("Rutos knyga 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rūtos knyga 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rutos 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rūtos 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rut 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rūt 1:1").osis()).toEqual("Ruth.1.1") p.include_apocrypha(false) expect(p.parse("RUTOS KNYGA 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RŪTOS KNYGA 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTOS 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RŪTOS 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTH 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUT 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RŪT 1:1").osis()).toEqual("Ruth.1.1") ` true describe "Localized book 1Esd (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Esd (lt)", -> ` expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1") ` true describe "Localized book 2Esd (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Esd (lt)", -> ` expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1") ` true describe "Localized book Isa (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Isa (lt)", -> ` expect(p.parse("Izaijo knyga 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Izaijo 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Iz 1:1").osis()).toEqual("Isa.1.1") p.include_apocrypha(false) expect(p.parse("IZAIJO KNYGA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("IZAIJO 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("IZ 1:1").osis()).toEqual("Isa.1.1") ` true describe "Localized book 2Sam (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Sam (lt)", -> ` expect(p.parse("Samuelio antra knyga 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Samuelio 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1") p.include_apocrypha(false) expect(p.parse("SAMUELIO ANTRA KNYGA 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAMUELIO 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1") ` true describe "Localized book 1Sam (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Sam (lt)", -> ` expect(p.parse("Samuelio pirma knyga 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Samuelio 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1") p.include_apocrypha(false) expect(p.parse("SAMUELIO PIRMA KNYGA 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAMUELIO 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1") ` true describe "Localized book 2Kgs (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Kgs (lt)", -> ` expect(p.parse("Karaliu antra knyga 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Karalių antra knyga 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Karaliu 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Karalių 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Kar 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1") p.include_apocrypha(false) expect(p.parse("KARALIU ANTRA KNYGA 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("KARALIŲ ANTRA KNYGA 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 KARALIU 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 KARALIŲ 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 KAR 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1") ` true describe "Localized book 1Kgs (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Kgs (lt)", -> ` expect(p.parse("Karaliu pirma knyga 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Karalių pirma knyga 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Karaliu 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Karalių 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Kar 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1") p.include_apocrypha(false) expect(p.parse("KARALIU PIRMA KNYGA 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("KARALIŲ PIRMA KNYGA 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 KARALIU 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 KARALIŲ 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 KAR 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1") ` true describe "Localized book 2Chr (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Chr (lt)", -> ` expect(p.parse("Metrasciu antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metrascių antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metrasčiu antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metrasčių antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metrašciu antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metrašcių antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metraščiu antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metraščių antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metrasciu 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metrascių 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metrasčiu 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metrasčių 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metrašciu 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metrašcių 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metraščiu 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metraščių 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Met 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2Chr 1:1").osis()).toEqual("2Chr.1.1") p.include_apocrypha(false) expect(p.parse("METRASCIU ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRASCIŲ ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRASČIU ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRASČIŲ ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRAŠCIU ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRAŠCIŲ ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRAŠČIU ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRAŠČIŲ ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRASCIU 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRASCIŲ 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRASČIU 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRASČIŲ 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRAŠCIU 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRAŠCIŲ 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRAŠČIU 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRAŠČIŲ 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 MET 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1") ` true describe "Localized book 1Chr (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Chr (lt)", -> ` expect(p.parse("Metrasciu pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metrascių pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metrasčiu pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metrasčių pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metrašciu pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metrašcių pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metraščiu pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metraščių pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metrasciu 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metrascių 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metrasčiu 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metrasčių 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metrašciu 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metrašcių 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metraščiu 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metraščių 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Met 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1Chr 1:1").osis()).toEqual("1Chr.1.1") p.include_apocrypha(false) expect(p.parse("METRASCIU PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRASCIŲ PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRASČIU PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRASČIŲ PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRAŠCIU PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRAŠCIŲ PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRAŠČIU PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRAŠČIŲ PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRASCIU 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRASCIŲ 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRASČIU 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRASČIŲ 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRAŠCIU 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRAŠCIŲ 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRAŠČIU 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRAŠČIŲ 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 MET 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1") ` true describe "Localized book Ezra (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezra (lt)", -> ` expect(p.parse("Ezros knyga 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezros 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezr 1:1").osis()).toEqual("Ezra.1.1") p.include_apocrypha(false) expect(p.parse("EZROS KNYGA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZROS 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZR 1:1").osis()).toEqual("Ezra.1.1") ` true describe "Localized book Neh (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Neh (lt)", -> ` expect(p.parse("Nehemijo knyga 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Nehemijo 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1") p.include_apocrypha(false) expect(p.parse("NEHEMIJO KNYGA 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEHEMIJO 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1") ` true describe "Localized book GkEsth (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: GkEsth (lt)", -> ` expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1") ` true describe "Localized book Esth (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Esth (lt)", -> ` expect(p.parse("Esteros knyga 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esteros 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esth 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Est 1:1").osis()).toEqual("Esth.1.1") p.include_apocrypha(false) expect(p.parse("ESTEROS KNYGA 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTEROS 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTH 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("EST 1:1").osis()).toEqual("Esth.1.1") ` true describe "Localized book Job (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Job (lt)", -> ` expect(p.parse("Jobo knyga 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Jobo 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1") p.include_apocrypha(false) expect(p.parse("JOBO KNYGA 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOBO 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1") ` true describe "Localized book Ps (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ps (lt)", -> ` expect(p.parse("Psalmynas 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Ps 1:1").osis()).toEqual("Ps.1.1") p.include_apocrypha(false) expect(p.parse("PSALMYNAS 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("PS 1:1").osis()).toEqual("Ps.1.1") ` true describe "Localized book PrAzar (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrAzar (lt)", -> ` expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1") ` true describe "Localized book Prov (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Prov (lt)", -> ` expect(p.parse("Patarliu knyga 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Patarlių knyga 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Patarliu 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Patarlių 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Pat 1:1").osis()).toEqual("Prov.1.1") p.include_apocrypha(false) expect(p.parse("PATARLIU KNYGA 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PATARLIŲ KNYGA 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PATARLIU 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PATARLIŲ 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PAT 1:1").osis()).toEqual("Prov.1.1") ` true describe "Localized book Eccl (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eccl (lt)", -> ` expect(p.parse("Mokytojo knyga 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Mokytojo 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Mok 1:1").osis()).toEqual("Eccl.1.1") p.include_apocrypha(false) expect(p.parse("MOKYTOJO KNYGA 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("MOKYTOJO 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("MOK 1:1").osis()).toEqual("Eccl.1.1") ` true describe "Localized book SgThree (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: SgThree (lt)", -> ` expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1") ` true describe "Localized book Song (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Song (lt)", -> ` expect(p.parse("Giesmiu giesmes knyga 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmiu giesmės knyga 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmių giesmes knyga 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmių giesmės knyga 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmiu giesmes 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmiu giesmės 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmių giesmes 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmių giesmės 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Gg 1:1").osis()).toEqual("Song.1.1") p.include_apocrypha(false) expect(p.parse("GIESMIU GIESMES KNYGA 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIU GIESMĖS KNYGA 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIŲ GIESMES KNYGA 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIŲ GIESMĖS KNYGA 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIU GIESMES 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIU GIESMĖS 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIŲ GIESMES 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIŲ GIESMĖS 1:1").osis()).toEqual("Song.1.1") expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GG 1:1").osis()).toEqual("Song.1.1") ` true describe "Localized book Jer (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jer (lt)", -> ` expect(p.parse("Jeremijo knyga 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jeremijo 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1") p.include_apocrypha(false) expect(p.parse("JEREMIJO KNYGA 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JEREMIJO 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1") ` true describe "Localized book Ezek (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezek (lt)", -> ` expect(p.parse("Ezechielio knyga 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ezechielio 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ez 1:1").osis()).toEqual("Ezek.1.1") p.include_apocrypha(false) expect(p.parse("EZECHIELIO KNYGA 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZECHIELIO 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZ 1:1").osis()).toEqual("Ezek.1.1") ` true describe "Localized book Dan (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Dan (lt)", -> ` expect(p.parse("Danieliaus knyga 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Danieliaus 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1") p.include_apocrypha(false) expect(p.parse("DANIELIAUS KNYGA 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DANIELIAUS 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DAN 1:1").osis()).toEqual("Dan.1.1") ` true describe "Localized book Hos (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hos (lt)", -> ` expect(p.parse("Ozejo knyga 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Ozėjo knyga 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Ozejo 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Ozėjo 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Oz 1:1").osis()).toEqual("Hos.1.1") p.include_apocrypha(false) expect(p.parse("OZEJO KNYGA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("OZĖJO KNYGA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("OZEJO 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("OZĖJO 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("OZ 1:1").osis()).toEqual("Hos.1.1") ` true describe "Localized book Joel (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Joel (lt)", -> ` expect(p.parse("Joelio knyga 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Joelio 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Jl 1:1").osis()).toEqual("Joel.1.1") p.include_apocrypha(false) expect(p.parse("JOELIO KNYGA 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JOELIO 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JOEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JL 1:1").osis()).toEqual("Joel.1.1") ` true describe "Localized book Amos (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Amos (lt)", -> ` expect(p.parse("Amoso knyga 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Amoso 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Am 1:1").osis()).toEqual("Amos.1.1") p.include_apocrypha(false) expect(p.parse("AMOSO KNYGA 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AMOSO 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AMOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AM 1:1").osis()).toEqual("Amos.1.1") ` true describe "Localized book Obad (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Obad (lt)", -> ` expect(p.parse("Abdijo knyga 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Abdijo 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Abd 1:1").osis()).toEqual("Obad.1.1") p.include_apocrypha(false) expect(p.parse("ABDIJO KNYGA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("ABDIJO 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("ABD 1:1").osis()).toEqual("Obad.1.1") ` true describe "Localized book Jonah (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jonah (lt)", -> ` expect(p.parse("Jonos knyga 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jonah 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jonos 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jon 1:1").osis()).toEqual("Jonah.1.1") p.include_apocrypha(false) expect(p.parse("JONOS KNYGA 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JONAH 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JONOS 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JON 1:1").osis()).toEqual("Jonah.1.1") ` true describe "Localized book Mic (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mic (lt)", -> ` expect(p.parse("Michejo knyga 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Michėjo knyga 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Michejo 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Michėjo 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mch 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1") p.include_apocrypha(false) expect(p.parse("MICHEJO KNYGA 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MICHĖJO KNYGA 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MICHEJO 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MICHĖJO 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MCH 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1") ` true describe "Localized book Nah (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Nah (lt)", -> ` expect(p.parse("Nahumo knyga 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nahumo 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1") p.include_apocrypha(false) expect(p.parse("NAHUMO KNYGA 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAHUMO 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1") ` true describe "Localized book Hab (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hab (lt)", -> ` expect(p.parse("Habakuko knyga 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Habakuko 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Hab 1:1").osis()).toEqual("Hab.1.1") p.include_apocrypha(false) expect(p.parse("HABAKUKO KNYGA 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HABAKUKO 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1") ` true describe "Localized book Zeph (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zeph (lt)", -> ` expect(p.parse("Sofonijo knyga 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sofonijo 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sof 1:1").osis()).toEqual("Zeph.1.1") p.include_apocrypha(false) expect(p.parse("SOFONIJO KNYGA 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SOFONIJO 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SOF 1:1").osis()).toEqual("Zeph.1.1") ` true describe "Localized book Hag (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hag (lt)", -> ` expect(p.parse("Agejo knyga 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Agėjo knyga 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Agejo 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Agėjo 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Ag 1:1").osis()).toEqual("Hag.1.1") p.include_apocrypha(false) expect(p.parse("AGEJO KNYGA 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("AGĖJO KNYGA 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("AGEJO 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("AGĖJO 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("AG 1:1").osis()).toEqual("Hag.1.1") ` true describe "Localized book Zech (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zech (lt)", -> ` expect(p.parse("Zacharijo knyga 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zacharijo 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zch 1:1").osis()).toEqual("Zech.1.1") p.include_apocrypha(false) expect(p.parse("ZACHARIJO KNYGA 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZACHARIJO 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZCH 1:1").osis()).toEqual("Zech.1.1") ` true describe "Localized book Mal (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mal (lt)", -> ` expect(p.parse("Malachijo knyga 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Malachijo 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1") p.include_apocrypha(false) expect(p.parse("MALACHIJO KNYGA 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MALACHIJO 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1") ` true describe "Localized book Matt (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Matt (lt)", -> ` expect(p.parse("Evangelija pagal Mata 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Evangelija pagal Matą 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Mato 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Matt 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Mt 1:1").osis()).toEqual("Matt.1.1") p.include_apocrypha(false) expect(p.parse("EVANGELIJA PAGAL MATA 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("EVANGELIJA PAGAL MATĄ 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATO 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATT 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MT 1:1").osis()).toEqual("Matt.1.1") ` true describe "Localized book Mark (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mark (lt)", -> ` expect(p.parse("Evangelija pagal Morku 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Evangelija pagal Morkų 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Morkaus 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mark 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mk 1:1").osis()).toEqual("Mark.1.1") p.include_apocrypha(false) expect(p.parse("EVANGELIJA PAGAL MORKU 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("EVANGELIJA PAGAL MORKŲ 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MORKAUS 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MARK 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MK 1:1").osis()).toEqual("Mark.1.1") ` true describe "Localized book Luke (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Luke (lt)", -> ` expect(p.parse("Evangelija pagal Luka 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Evangelija pagal Luką 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luko 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Lk 1:1").osis()).toEqual("Luke.1.1") p.include_apocrypha(false) expect(p.parse("EVANGELIJA PAGAL LUKA 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("EVANGELIJA PAGAL LUKĄ 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKO 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LK 1:1").osis()).toEqual("Luke.1.1") ` true describe "Localized book 1John (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1John (lt)", -> ` expect(p.parse("Jono pirmas laiskas 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Jono pirmas laiškas 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Jono 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Jn 1:1").osis()).toEqual("1John.1.1") p.include_apocrypha(false) expect(p.parse("JONO PIRMAS LAISKAS 1:1").osis()).toEqual("1John.1.1") expect(p.parse("JONO PIRMAS LAIŠKAS 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 JONO 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 JN 1:1").osis()).toEqual("1John.1.1") ` true describe "Localized book 2John (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2John (lt)", -> ` expect(p.parse("Jono antras laiskas 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Jono antras laiškas 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Jono 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Jn 1:1").osis()).toEqual("2John.1.1") p.include_apocrypha(false) expect(p.parse("JONO ANTRAS LAISKAS 1:1").osis()).toEqual("2John.1.1") expect(p.parse("JONO ANTRAS LAIŠKAS 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 JONO 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 JN 1:1").osis()).toEqual("2John.1.1") ` true describe "Localized book 3John (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3John (lt)", -> ` expect(p.parse("Jono trecias laiskas 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Jono trecias laiškas 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Jono trečias laiskas 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Jono trečias laiškas 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Jono 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Jn 1:1").osis()).toEqual("3John.1.1") p.include_apocrypha(false) expect(p.parse("JONO TRECIAS LAISKAS 1:1").osis()).toEqual("3John.1.1") expect(p.parse("JONO TRECIAS LAIŠKAS 1:1").osis()).toEqual("3John.1.1") expect(p.parse("JONO TREČIAS LAISKAS 1:1").osis()).toEqual("3John.1.1") expect(p.parse("JONO TREČIAS LAIŠKAS 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 JONO 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 JN 1:1").osis()).toEqual("3John.1.1") ` true describe "Localized book John (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: John (lt)", -> ` expect(p.parse("Evangelija pagal Jona 1:1").osis()).toEqual("John.1.1") expect(p.parse("Evangelija pagal Joną 1:1").osis()).toEqual("John.1.1") expect(p.parse("John 1:1").osis()).toEqual("John.1.1") expect(p.parse("Jono 1:1").osis()).toEqual("John.1.1") expect(p.parse("Jn 1:1").osis()).toEqual("John.1.1") p.include_apocrypha(false) expect(p.parse("EVANGELIJA PAGAL JONA 1:1").osis()).toEqual("John.1.1") expect(p.parse("EVANGELIJA PAGAL JONĄ 1:1").osis()).toEqual("John.1.1") expect(p.parse("JOHN 1:1").osis()).toEqual("John.1.1") expect(p.parse("JONO 1:1").osis()).toEqual("John.1.1") expect(p.parse("JN 1:1").osis()).toEqual("John.1.1") ` true describe "Localized book Acts (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Acts (lt)", -> ` expect(p.parse("Apastalu darbai 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apastalų darbai 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apaštalu darbai 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apaštalų darbai 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apastalu darbu 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apastalu darbų 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apastalų darbu 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apastalų darbų 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apaštalu darbu 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apaštalu darbų 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apaštalų darbu 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apaštalų darbų 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apd 1:1").osis()).toEqual("Acts.1.1") p.include_apocrypha(false) expect(p.parse("APASTALU DARBAI 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APASTALŲ DARBAI 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APAŠTALU DARBAI 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APAŠTALŲ DARBAI 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APASTALU DARBU 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APASTALU DARBŲ 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APASTALŲ DARBU 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APASTALŲ DARBŲ 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APAŠTALU DARBU 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APAŠTALU DARBŲ 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APAŠTALŲ DARBU 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APAŠTALŲ DARBŲ 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APD 1:1").osis()).toEqual("Acts.1.1") ` true describe "Localized book Rom (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rom (lt)", -> ` expect(p.parse("Laiskas romieciams 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Laiskas romiečiams 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Laiškas romieciams 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Laiškas romiečiams 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Romieciams 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Romiečiams 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS ROMIECIAMS 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("LAISKAS ROMIEČIAMS 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("LAIŠKAS ROMIECIAMS 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("LAIŠKAS ROMIEČIAMS 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROMIECIAMS 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROMIEČIAMS 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1") ` true describe "Localized book 2Cor (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Cor (lt)", -> ` expect(p.parse("Antras laiskas korintieciams 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Antras laiskas korintiečiams 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Antras laiškas korintieciams 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Antras laiškas korintiečiams 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Korintieciams 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Korintiečiams 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2Cor 1:1").osis()).toEqual("2Cor.1.1") p.include_apocrypha(false) expect(p.parse("ANTRAS LAISKAS KORINTIECIAMS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("ANTRAS LAISKAS KORINTIEČIAMS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("ANTRAS LAIŠKAS KORINTIECIAMS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("ANTRAS LAIŠKAS KORINTIEČIAMS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KORINTIECIAMS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KORINTIEČIAMS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1") ` true describe "Localized book 1Cor (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Cor (lt)", -> ` expect(p.parse("Pirmas laiskas korintieciams 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Pirmas laiskas korintiečiams 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Pirmas laiškas korintieciams 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Pirmas laiškas korintiečiams 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Korintieciams 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Korintiečiams 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1Cor 1:1").osis()).toEqual("1Cor.1.1") p.include_apocrypha(false) expect(p.parse("PIRMAS LAISKAS KORINTIECIAMS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("PIRMAS LAISKAS KORINTIEČIAMS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("PIRMAS LAIŠKAS KORINTIECIAMS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("PIRMAS LAIŠKAS KORINTIEČIAMS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KORINTIECIAMS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KORINTIEČIAMS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1") ` true describe "Localized book Gal (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gal (lt)", -> ` expect(p.parse("Laiskas galatams 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Laiškas galatams 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Galatams 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS GALATAMS 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("LAIŠKAS GALATAMS 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GALATAMS 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1") ` true describe "Localized book Eph (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eph (lt)", -> ` expect(p.parse("Laiskas efezieciams 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Laiskas efeziečiams 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Laiškas efezieciams 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Laiškas efeziečiams 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Efezieciams 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Efeziečiams 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Eph 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Ef 1:1").osis()).toEqual("Eph.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS EFEZIECIAMS 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("LAISKAS EFEZIEČIAMS 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("LAIŠKAS EFEZIECIAMS 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("LAIŠKAS EFEZIEČIAMS 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EFEZIECIAMS 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EFEZIEČIAMS 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EPH 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EF 1:1").osis()).toEqual("Eph.1.1") ` true describe "Localized book Phil (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phil (lt)", -> ` expect(p.parse("Laiskas filipieciams 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Laiskas filipiečiams 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Laiškas filipieciams 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Laiškas filipiečiams 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Filipieciams 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Filipiečiams 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Phil 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Fil 1:1").osis()).toEqual("Phil.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS FILIPIECIAMS 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("LAISKAS FILIPIEČIAMS 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("LAIŠKAS FILIPIECIAMS 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("LAIŠKAS FILIPIEČIAMS 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FILIPIECIAMS 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FILIPIEČIAMS 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("PHIL 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FIL 1:1").osis()).toEqual("Phil.1.1") ` true describe "Localized book Col (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Col (lt)", -> ` expect(p.parse("Laiskas kolosieciams 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Laiskas kolosiečiams 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Laiškas kolosieciams 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Laiškas kolosiečiams 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kolosieciams 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kolosiečiams 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kol 1:1").osis()).toEqual("Col.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS KOLOSIECIAMS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("LAISKAS KOLOSIEČIAMS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("LAIŠKAS KOLOSIECIAMS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("LAIŠKAS KOLOSIEČIAMS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOLOSIECIAMS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOLOSIEČIAMS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOL 1:1").osis()).toEqual("Col.1.1") ` true describe "Localized book 2Thess (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Thess (lt)", -> ` expect(p.parse("Antras laiskas tesalonikieciams 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Antras laiskas tesalonikiečiams 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Antras laiškas tesalonikieciams 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Antras laiškas tesalonikiečiams 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Tesalonikieciams 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Tesalonikiečiams 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Tes 1:1").osis()).toEqual("2Thess.1.1") p.include_apocrypha(false) expect(p.parse("ANTRAS LAISKAS TESALONIKIECIAMS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("ANTRAS LAISKAS TESALONIKIEČIAMS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("ANTRAS LAIŠKAS TESALONIKIECIAMS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("ANTRAS LAIŠKAS TESALONIKIEČIAMS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 TESALONIKIECIAMS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 TESALONIKIEČIAMS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 TES 1:1").osis()).toEqual("2Thess.1.1") ` true describe "Localized book 1Thess (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Thess (lt)", -> ` expect(p.parse("Pirmas laiskas tesalonikieciams 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Pirmas laiskas tesalonikiečiams 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Pirmas laiškas tesalonikieciams 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Pirmas laiškas tesalonikiečiams 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Tesalonikieciams 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Tesalonikiečiams 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Tes 1:1").osis()).toEqual("1Thess.1.1") p.include_apocrypha(false) expect(p.parse("PIRMAS LAISKAS TESALONIKIECIAMS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("PIRMAS LAISKAS TESALONIKIEČIAMS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("PIRMAS LAIŠKAS TESALONIKIECIAMS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("PIRMAS LAIŠKAS TESALONIKIEČIAMS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 TESALONIKIECIAMS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 TESALONIKIEČIAMS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 TES 1:1").osis()).toEqual("1Thess.1.1") ` true describe "Localized book 2Tim (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Tim (lt)", -> ` expect(p.parse("Antras laiskas Timotiejui 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Antras laiškas Timotiejui 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Timotiejui 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2Tim 1:1").osis()).toEqual("2Tim.1.1") p.include_apocrypha(false) expect(p.parse("ANTRAS LAISKAS TIMOTIEJUI 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("ANTRAS LAIŠKAS TIMOTIEJUI 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIMOTIEJUI 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1") ` true describe "Localized book 1Tim (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Tim (lt)", -> ` expect(p.parse("Pirmas laiskas Timotiejui 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Pirmas laiškas Timotiejui 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Timotiejui 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1Tim 1:1").osis()).toEqual("1Tim.1.1") p.include_apocrypha(false) expect(p.parse("PIRMAS LAISKAS TIMOTIEJUI 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("PIRMAS LAIŠKAS TIMOTIEJUI 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIMOTIEJUI 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1") ` true describe "Localized book Titus (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Titus (lt)", -> ` expect(p.parse("Laiskas Titui 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Laiškas Titui 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titui 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tit 1:1").osis()).toEqual("Titus.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS TITUI 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("LAIŠKAS TITUI 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUI 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TIT 1:1").osis()).toEqual("Titus.1.1") ` true describe "Localized book Phlm (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phlm (lt)", -> ` expect(p.parse("Laiskas Filemonui 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Laiškas Filemonui 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Filemonui 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Phlm 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Fm 1:1").osis()).toEqual("Phlm.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS FILEMONUI 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("LAIŠKAS FILEMONUI 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FILEMONUI 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("PHLM 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FM 1:1").osis()).toEqual("Phlm.1.1") ` true describe "Localized book Heb (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Heb (lt)", -> ` expect(p.parse("Laiskas hebrajams 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Laiškas hebrajams 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Hebrajams 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Hbr 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS HEBRAJAMS 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("LAIŠKAS HEBRAJAMS 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEBRAJAMS 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HBR 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1") ` true describe "Localized book Jas (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jas (lt)", -> ` expect(p.parse("Jokubo laiskas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jokubo laiškas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jokūbo laiskas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jokūbo laiškas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jokubo 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jokūbo 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jok 1:1").osis()).toEqual("Jas.1.1") p.include_apocrypha(false) expect(p.parse("JOKUBO LAISKAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JOKUBO LAIŠKAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JOKŪBO LAISKAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JOKŪBO LAIŠKAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JOKUBO 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JOKŪBO 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JOK 1:1").osis()).toEqual("Jas.1.1") ` true describe "Localized book 2Pet (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Pet (lt)", -> ` expect(p.parse("Petro antras laiskas 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Petro antras laiškas 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Pt 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1") p.include_apocrypha(false) expect(p.parse("PETRO ANTRAS LAISKAS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("PETRO ANTRAS LAIŠKAS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 PT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1") ` true describe "Localized book 1Pet (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Pet (lt)", -> ` expect(p.parse("Petro pirmas laiskas 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Petro pirmas laiškas 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Pt 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1") p.include_apocrypha(false) expect(p.parse("PETRO PIRMAS LAISKAS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("PETRO PIRMAS LAIŠKAS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 PT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1") ` true describe "Localized book Jude (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jude (lt)", -> ` expect(p.parse("Judo laiskas 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Judo laiškas 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jude 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Judo 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jud 1:1").osis()).toEqual("Jude.1.1") p.include_apocrypha(false) expect(p.parse("JUDO LAISKAS 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDO LAIŠKAS 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDE 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDO 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUD 1:1").osis()).toEqual("Jude.1.1") ` true describe "Localized book Tob (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Tob (lt)", -> ` expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1") ` true describe "Localized book Jdt (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jdt (lt)", -> ` expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1") ` true describe "Localized book Bar (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bar (lt)", -> ` expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1") ` true describe "Localized book Sus (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sus (lt)", -> ` expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1") ` true describe "Localized book 2Macc (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Macc (lt)", -> ` expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1") ` true describe "Localized book 3Macc (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3Macc (lt)", -> ` expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1") ` true describe "Localized book 4Macc (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 4Macc (lt)", -> ` expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1") ` true describe "Localized book 1Macc (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Macc (lt)", -> ` expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1") ` true describe "Miscellaneous tests", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore", book_sequence_strategy: "ignore", osis_compaction_strategy: "bc", captive_end_digits_strategy: "delete" p.include_apocrypha true it "should return the expected language", -> expect(p.languages).toEqual ["lt"] it "should handle ranges (lt)", -> expect(p.parse("Titus 1:1 iki 2").osis()).toEqual "Titus.1.1-Titus.1.2" expect(p.parse("Matt 1iki2").osis()).toEqual "Matt.1-Matt.2" expect(p.parse("Phlm 2 IKI 3").osis()).toEqual "Phlm.1.2-Phlm.1.3" it "should handle chapters (lt)", -> expect(p.parse("Titus 1:1, Skyrius 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 SKYRIUS 6").osis()).toEqual "Matt.3.4,Matt.6" it "should handle verses (lt)", -> expect(p.parse("Exod 1:1 eilutė 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm EILUTĖ 6").osis()).toEqual "Phlm.1.6" expect(p.parse("Exod 1:1 eilute 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm EILUTE 6").osis()).toEqual "Phlm.1.6" it "should handle 'and' (lt)", -> expect(p.parse("Exod 1:1 Ir 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 IR 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" it "should handle titles (lt)", -> expect(p.parse("Ps 3 title, 4:2, 5:title").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" expect(p.parse("PS 3 TITLE, 4:2, 5:TITLE").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" it "should handle 'ff' (lt)", -> expect(p.parse("Rev 3ff, 4:2ff").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" expect(p.parse("REV 3 FF, 4:2 FF").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" it "should handle translations (lt)", -> expect(p.parse("Lev 1 (lit)").osis_and_translations()).toEqual [["Lev.1", "lit"]] expect(p.parse("lev 1 lit").osis_and_translations()).toEqual [["Lev.1", "lit"]] it "should handle boundaries (lt)", -> p.set_options {book_alone_strategy: "full"} expect(p.parse("\u2014Matt\u2014").osis()).toEqual "Matt.1-Matt.28" expect(p.parse("\u201cMatt 1:1\u201d").osis()).toEqual "Matt.1.1"
138891
bcv_parser = require("../../js/lt_bcv_parser.js").bcv_parser describe "Parsing", -> p = {} beforeEach -> p = new bcv_parser p.options.osis_compaction_strategy = "b" p.options.sequence_combination_strategy = "combine" it "should round-trip OSIS references", -> p.set_options osis_compaction_strategy: "bc" books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","<NAME>","<NAME>","<NAME>","<NAME>mos","<NAME>ad","<NAME>","<NAME>","<NAME>ah","Hab","Zeph","Hag","Zech","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range it "should round-trip OSIS Apocrypha references", -> p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b" p.include_apocrypha true books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range p.set_options ps151_strategy: "bc" expect(p.parse("Ps151.1").osis()).toEqual "Ps.151" expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1" expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2" p.include_apocrypha false for book in books bc = book + ".1" expect(p.parse(bc).osis()).toEqual "" it "should handle a preceding character", -> expect(p.parse(" Gen 1").osis()).toEqual "Gen.1" expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3" expect(p.parse("1Ps 1").osis()).toEqual "" expect(p.parse("11Sam 1").osis()).toEqual "" describe "Localized book Gen (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gen (lt)", -> ` expect(p.parse("Pradzios knyga 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Pradžios knyga 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Pradzios 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Pradžios 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Pr 1:1").osis()).toEqual("Gen.1.1") p.include_apocrypha(false) expect(p.parse("PRADZIOS KNYGA 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("PRADŽIOS KNYGA 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("PRADZIOS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("PRADŽIOS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("PR 1:1").osis()).toEqual("Gen.1.1") ` true describe "Localized book Exod (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Exod (lt)", -> ` expect(p.parse("Isejimo knyga 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Isėjimo knyga 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Išejimo knyga 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Išėjimo knyga 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Isejimo 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Isėjimo 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Išejimo 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Išėjimo 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Is 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Iš 1:1").osis()).toEqual("Exod.1.1") p.include_apocrypha(false) expect(p.parse("ISEJIMO KNYGA 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ISĖJIMO KNYGA 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("IŠEJIMO KNYGA 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("IŠĖJIMO KNYGA 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ISEJIMO 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ISĖJIMO 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("IŠEJIMO 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("IŠĖJIMO 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("IS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("IŠ 1:1").osis()).toEqual("Exod.1.1") ` true describe "Localized book Bel (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bel (lt)", -> ` expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1") ` true describe "Localized book Lev (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lev (lt)", -> ` expect(p.parse("Kunigu knyga 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Kunigų knyga 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Kunigu 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Kunigų 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Kun 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1") p.include_apocrypha(false) expect(p.parse("KUNIGU KNYGA 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("KUNIGŲ KNYGA 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("KUNIGU 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("KUNIGŲ 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("KUN 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1") ` true describe "Localized book Num (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Num (lt)", -> ` expect(p.parse("Skaiciu knyga 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaicių knyga 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaičiu knyga 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaičių knyga 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaiciu 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaicių 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaičiu 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaičių 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Sk 1:1").osis()).toEqual("Num.1.1") p.include_apocrypha(false) expect(p.parse("SKAICIU KNYGA 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAICIŲ KNYGA 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAIČIU KNYGA 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAIČIŲ KNYGA 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAICIU 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAICIŲ 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAIČIU 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAIČIŲ 1:1").osis()).toEqual("Num.1.1") expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SK 1:1").osis()).toEqual("Num.1.1") ` true describe "Localized book Sir (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sir (lt)", -> ` expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1") ` true describe "Localized book Wis (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Wis (lt)", -> ` expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1") ` true describe "Localized book Lam (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lam (lt)", -> ` expect(p.parse("Raudu knyga 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Raudų knyga 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Raudu 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Raudų 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Rd 1:1").osis()).toEqual("Lam.1.1") p.include_apocrypha(false) expect(p.parse("RAUDU KNYGA 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("RAUDŲ KNYGA 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("RAUDU 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("RAUDŲ 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("RD 1:1").osis()).toEqual("Lam.1.1") ` true describe "Localized book EpJer (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: EpJer (lt)", -> ` expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1") ` true describe "Localized book Rev (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rev (lt)", -> ` expect(p.parse("Apreiskimas Jonui 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Apreiškimas Jonui 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Apreiskimo Jonui 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Apreiškimo Jonui 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Apr 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1") p.include_apocrypha(false) expect(p.parse("APREISKIMAS JONUI 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("APREIŠKIMAS JONUI 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("APREISKIMO JONUI 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("APREIŠKIMO JONUI 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("APR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1") ` true describe "Localized book PrMan (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrMan (lt)", -> ` expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1") ` true describe "Localized book Deut (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Deut (lt)", -> ` expect(p.parse("Pakartoto Istatymo knyga 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Pakartoto Įstatymo knyga 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Pakartoto Istatymo 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Pakartoto Įstatymo 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Ist 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Įst 1:1").osis()).toEqual("Deut.1.1") p.include_apocrypha(false) expect(p.parse("PAKARTOTO ISTATYMO KNYGA 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("PAKARTOTO ĮSTATYMO KNYGA 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("PAKARTOTO ISTATYMO 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("PAKARTOTO ĮSTATYMO 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("IST 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("ĮST 1:1").osis()).toEqual("Deut.1.1") ` true describe "Localized book <NAME>osh (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME>osh (lt)", -> ` expect(p.parse("Jozues knyga 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jozuės knyga 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jozues 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jozuės 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josh 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Joz 1:1").osis()).toEqual("Josh.1.1") p.include_apocrypha(false) expect(p.parse("JOZUES KNYGA 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOZUĖS KNYGA 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOZUES 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOZUĖS 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSH 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOZ 1:1").osis()).toEqual("Josh.1.1") ` true describe "Localized book Judg (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Judg (lt)", -> ` expect(p.parse("Teiseju knyga 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teisejų knyga 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teisėju knyga 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teisėjų knyga 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teiseju 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teisejų 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teisėju 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teisėjų 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Ts 1:1").osis()).toEqual("Judg.1.1") p.include_apocrypha(false) expect(p.parse("TEISEJU KNYGA 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISEJŲ KNYGA 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISĖJU KNYGA 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISĖJŲ KNYGA 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISEJU 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISEJŲ 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISĖJU 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISĖJŲ 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TS 1:1").osis()).toEqual("Judg.1.1") ` true describe "Localized book Ruth (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ruth (lt)", -> ` expect(p.parse("Rutos knyga 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rūtos knyga 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rutos 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rūtos 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rut 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rūt 1:1").osis()).toEqual("Ruth.1.1") p.include_apocrypha(false) expect(p.parse("RUTOS KNYGA 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RŪTOS KNYGA 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTOS 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RŪTOS 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTH 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUT 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RŪT 1:1").osis()).toEqual("Ruth.1.1") ` true describe "Localized book 1Esd (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Esd (lt)", -> ` expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1") ` true describe "Localized book 2Esd (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Esd (lt)", -> ` expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1") ` true describe "Localized book Isa (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Isa (lt)", -> ` expect(p.parse("Izaijo knyga 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Izaijo 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Iz 1:1").osis()).toEqual("Isa.1.1") p.include_apocrypha(false) expect(p.parse("IZAIJO KNYGA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("IZAIJO 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("IZ 1:1").osis()).toEqual("Isa.1.1") ` true describe "Localized book 2Sam (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Sam (lt)", -> ` expect(p.parse("<NAME> 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Sam<NAME> 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1") p.include_apocrypha(false) expect(p.parse("<NAME> 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAMUELIO 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1") ` true describe "Localized book 1Sam (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Sam (lt)", -> ` expect(p.parse("<NAME> knyga 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Sam<NAME> 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1") p.include_apocrypha(false) expect(p.parse("<NAME> KNYGA 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAMUELIO 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1") ` true describe "Localized book 2Kgs (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Kgs (lt)", -> ` expect(p.parse("Karaliu antra knyga 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Karalių antra knyga 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Karaliu 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Karalių 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Kar 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1") p.include_apocrypha(false) expect(p.parse("KARALIU ANTRA KNYGA 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("KARALIŲ ANTRA KNYGA 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 KARALIU 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 KARALIŲ 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 KAR 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1") ` true describe "Localized book 1Kgs (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Kgs (lt)", -> ` expect(p.parse("Karaliu pirma knyga 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Karalių pirma knyga 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Karaliu 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Karalių 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Kar 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1") p.include_apocrypha(false) expect(p.parse("KARALIU PIRMA KNYGA 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("KARALIŲ PIRMA KNYGA 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 KARALIU 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 KARALIŲ 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 KAR 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1") ` true describe "Localized book 2Chr (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Chr (lt)", -> ` expect(p.parse("Metrasciu antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metrascių antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metrasčiu antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metrasčių antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metrašciu antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metrašcių antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metraščiu antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metraščių antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metrasciu 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metrascių 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metrasčiu 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metrasčių 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metrašciu 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metrašcių 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metraščiu 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metraščių 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Met 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2Chr 1:1").osis()).toEqual("2Chr.1.1") p.include_apocrypha(false) expect(p.parse("METRASCIU ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRASCIŲ ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRASČIU ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRASČIŲ ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRAŠCIU ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRAŠCIŲ ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRAŠČIU ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRAŠČIŲ ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRASCIU 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRASCIŲ 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRASČIU 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRASČIŲ 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRAŠCIU 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRAŠCIŲ 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRAŠČIU 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRAŠČIŲ 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 MET 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1") ` true describe "Localized book 1Chr (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Chr (lt)", -> ` expect(p.parse("Metrasciu pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metrascių pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metrasčiu pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metrasčių pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metrašciu pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metrašcių pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metraščiu pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metraščių pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metrasciu 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metrascių 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metrasčiu 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metrasčių 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metrašciu 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metrašcių 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metraščiu 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metraščių 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Met 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1Chr 1:1").osis()).toEqual("1Chr.1.1") p.include_apocrypha(false) expect(p.parse("METRASCIU PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRASCIŲ PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRASČIU PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRASČIŲ PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRAŠCIU PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRAŠCIŲ PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRAŠČIU PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRAŠČIŲ PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRASCIU 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRASCIŲ 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRASČIU 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRASČIŲ 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRAŠCIU 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRAŠCIŲ 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRAŠČIU 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRAŠČIŲ 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 MET 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1") ` true describe "Localized book Ezra (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezra (lt)", -> ` expect(p.parse("Ezros knyga 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezros 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezr 1:1").osis()).toEqual("Ezra.1.1") p.include_apocrypha(false) expect(p.parse("EZROS KNYGA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZROS 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZR 1:1").osis()).toEqual("Ezra.1.1") ` true describe "Localized book Neh (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Neh (lt)", -> ` expect(p.parse("Nehemijo knyga 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Nehemijo 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1") p.include_apocrypha(false) expect(p.parse("NEHEMIJO KNYGA 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEHEMIJO 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1") ` true describe "Localized book GkEsth (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: GkEsth (lt)", -> ` expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1") ` true describe "Localized book Esth (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Esth (lt)", -> ` expect(p.parse("Esteros knyga 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esteros 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esth 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Est 1:1").osis()).toEqual("Esth.1.1") p.include_apocrypha(false) expect(p.parse("ESTEROS KNYGA 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTEROS 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTH 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("EST 1:1").osis()).toEqual("Esth.1.1") ` true describe "Localized book Job (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Job (lt)", -> ` expect(p.parse("Jobo knyga 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Jobo 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1") p.include_apocrypha(false) expect(p.parse("JOBO KNYGA 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOBO 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1") ` true describe "Localized book Ps (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ps (lt)", -> ` expect(p.parse("Psalmynas 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Ps 1:1").osis()).toEqual("Ps.1.1") p.include_apocrypha(false) expect(p.parse("PSALMYNAS 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("PS 1:1").osis()).toEqual("Ps.1.1") ` true describe "Localized book PrAzar (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrAzar (lt)", -> ` expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1") ` true describe "Localized book Prov (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Prov (lt)", -> ` expect(p.parse("Patarliu knyga 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Patarlių knyga 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Patarliu 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Patarlių 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Pat 1:1").osis()).toEqual("Prov.1.1") p.include_apocrypha(false) expect(p.parse("PATARLIU KNYGA 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PATARLIŲ KNYGA 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PATARLIU 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PATARLIŲ 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PAT 1:1").osis()).toEqual("Prov.1.1") ` true describe "Localized book Eccl (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eccl (lt)", -> ` expect(p.parse("Mokytojo knyga 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Mokytojo 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Mok 1:1").osis()).toEqual("Eccl.1.1") p.include_apocrypha(false) expect(p.parse("MOKYTOJO KNYGA 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("MOKYTOJO 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("MOK 1:1").osis()).toEqual("Eccl.1.1") ` true describe "Localized book SgThree (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: SgThree (lt)", -> ` expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1") ` true describe "Localized book Song (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Song (lt)", -> ` expect(p.parse("Giesmiu giesmes knyga 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmiu giesmės knyga 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmių giesmes knyga 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmių giesmės knyga 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmiu giesmes 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmiu giesmės 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmių giesmes 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmių giesmės 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Gg 1:1").osis()).toEqual("Song.1.1") p.include_apocrypha(false) expect(p.parse("GIESMIU GIESMES KNYGA 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIU GIESMĖS KNYGA 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIŲ GIESMES KNYGA 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIŲ GIESMĖS KNYGA 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIU GIESMES 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIU GIESMĖS 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIŲ GIESMES 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIŲ GIESMĖS 1:1").osis()).toEqual("Song.1.1") expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GG 1:1").osis()).toEqual("Song.1.1") ` true describe "Localized book Jer (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (lt)", -> ` expect(p.parse("<NAME> 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jeremijo 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1") p.include_apocrypha(false) expect(p.parse("<NAME> 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JEREMIJO 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1") ` true describe "Localized book <NAME>zek (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezek (lt)", -> ` expect(p.parse("Ezechielio knyga 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ezechielio 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ez 1:1").osis()).toEqual("Ezek.1.1") p.include_apocrypha(false) expect(p.parse("EZECHIELIO KNYGA 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZECHIELIO 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZ 1:1").osis()).toEqual("Ezek.1.1") ` true describe "Localized book <NAME> (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (lt)", -> ` expect(p.parse("Danieliaus knyga 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Danieliaus 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1") p.include_apocrypha(false) expect(p.parse("DANIELIAUS KNYGA 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DANIELIAUS 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DAN 1:1").osis()).toEqual("Dan.1.1") ` true describe "Localized book Hos (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hos (lt)", -> ` expect(p.parse("Ozejo knyga 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Ozėjo knyga 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Ozejo 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Ozėjo 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Oz 1:1").osis()).toEqual("Hos.1.1") p.include_apocrypha(false) expect(p.parse("OZEJO KNYGA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("OZĖJO KNYGA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("OZEJO 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("OZĖJO 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("OZ 1:1").osis()).toEqual("Hos.1.1") ` true describe "Localized book Joel (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Joel (lt)", -> ` expect(p.parse("Joelio knyga 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Joelio 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Jl 1:1").osis()).toEqual("Joel.1.1") p.include_apocrypha(false) expect(p.parse("JOELIO KNYGA 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JOELIO 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JOEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JL 1:1").osis()).toEqual("Joel.1.1") ` true describe "Localized book Amos (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Amos (lt)", -> ` expect(p.parse("Amoso knyga 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Amoso 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Am 1:1").osis()).toEqual("Amos.1.1") p.include_apocrypha(false) expect(p.parse("AMOSO KNYGA 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AMOSO 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AMOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AM 1:1").osis()).toEqual("Amos.1.1") ` true describe "Localized book Obad (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Obad (lt)", -> ` expect(p.parse("Abdijo knyga 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Abdijo 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Abd 1:1").osis()).toEqual("Obad.1.1") p.include_apocrypha(false) expect(p.parse("ABDIJO KNYGA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("ABDIJO 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("ABD 1:1").osis()).toEqual("Obad.1.1") ` true describe "Localized book Jonah (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (lt)", -> ` expect(p.parse("Jonos knyga 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jonah 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jonos 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("<NAME> 1:1").osis()).toEqual("Jonah.1.1") p.include_apocrypha(false) expect(p.parse("JONOS KNYGA 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JONAH 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JONOS 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JON 1:1").osis()).toEqual("Jonah.1.1") ` true describe "Localized book <NAME>ic (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME>ic (lt)", -> ` expect(p.parse("Michejo knyga 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Michėjo knyga 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Michejo 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Michėjo 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mch 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1") p.include_apocrypha(false) expect(p.parse("MICHEJO KNYGA 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MICHĖJO KNYGA 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MICHEJO 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MICHĖJO 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MCH 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1") ` true describe "Localized book Nah (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Nah (lt)", -> ` expect(p.parse("Nahumo knyga 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nahumo 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1") p.include_apocrypha(false) expect(p.parse("NAHUMO KNYGA 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAHUMO 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1") ` true describe "Localized book Hab (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hab (lt)", -> ` expect(p.parse("Habakuko knyga 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Habakuko 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Hab 1:1").osis()).toEqual("Hab.1.1") p.include_apocrypha(false) expect(p.parse("HABAKUKO KNYGA 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HABAKUKO 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1") ` true describe "Localized book Zeph (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zeph (lt)", -> ` expect(p.parse("Sofonijo knyga 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sofonijo 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sof 1:1").osis()).toEqual("Zeph.1.1") p.include_apocrypha(false) expect(p.parse("SOFONIJO KNYGA 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SOFONIJO 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SOF 1:1").osis()).toEqual("Zeph.1.1") ` true describe "Localized book Hag (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hag (lt)", -> ` expect(p.parse("Agejo knyga 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Agėjo knyga 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Agejo 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Agėjo 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Ag 1:1").osis()).toEqual("Hag.1.1") p.include_apocrypha(false) expect(p.parse("AGEJO KNYGA 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("AGĖJO KNYGA 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("AGEJO 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("AGĖJO 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("AG 1:1").osis()).toEqual("Hag.1.1") ` true describe "Localized book Zech (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zech (lt)", -> ` expect(p.parse("Zacharijo knyga 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zacharijo 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zch 1:1").osis()).toEqual("Zech.1.1") p.include_apocrypha(false) expect(p.parse("ZACHARIJO KNYGA 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZACHARIJO 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZCH 1:1").osis()).toEqual("Zech.1.1") ` true describe "Localized book Mal (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mal (lt)", -> ` expect(p.parse("Malachijo knyga 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Malachijo 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1") p.include_apocrypha(false) expect(p.parse("MALACHIJO KNYGA 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MALACHIJO 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1") ` true describe "Localized book <NAME> (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (lt)", -> ` expect(p.parse("Evangelija pagal Mata 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Evangelija pagal Matą 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Mato 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Matt 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Mt 1:1").osis()).toEqual("Matt.1.1") p.include_apocrypha(false) expect(p.parse("EVANGELIJA PAGAL MATA 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("EVANGELIJA PAGAL MATĄ 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATO 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATT 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MT 1:1").osis()).toEqual("Matt.1.1") ` true describe "Localized book Mark (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mark (lt)", -> ` expect(p.parse("Evangelija pagal Morku 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Evangelija pagal Morkų 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Morkaus 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mark 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mk 1:1").osis()).toEqual("Mark.1.1") p.include_apocrypha(false) expect(p.parse("EVANGELIJA PAGAL MORKU 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("EVANGELIJA PAGAL MORKŲ 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MORKAUS 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MARK 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MK 1:1").osis()).toEqual("Mark.1.1") ` true describe "Localized book L<NAME> (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (lt)", -> ` expect(p.parse("Evangelija pagal Luka 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Evangelija pagal Luką 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luko 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Lk 1:1").osis()).toEqual("Luke.1.1") p.include_apocrypha(false) expect(p.parse("EVANGELIJA PAGAL LUKA 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("EVANGELIJA PAGAL LUKĄ 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKO 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LK 1:1").osis()).toEqual("Luke.1.1") ` true describe "Localized book 1John (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1John (lt)", -> ` expect(p.parse("Jono pirmas laiskas 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Jono pirmas laiškas 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Jono 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Jn 1:1").osis()).toEqual("1John.1.1") p.include_apocrypha(false) expect(p.parse("JONO PIRMAS LAISKAS 1:1").osis()).toEqual("1John.1.1") expect(p.parse("JONO PIRMAS LAIŠKAS 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 JONO 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 JN 1:1").osis()).toEqual("1John.1.1") ` true describe "Localized book 2John (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2John (lt)", -> ` expect(p.parse("Jono antras laiskas 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Jono antras laiškas 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Jono 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Jn 1:1").osis()).toEqual("2John.1.1") p.include_apocrypha(false) expect(p.parse("JONO ANTRAS LAISKAS 1:1").osis()).toEqual("2John.1.1") expect(p.parse("JONO ANTRAS LAIŠKAS 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 JONO 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 JN 1:1").osis()).toEqual("2John.1.1") ` true describe "Localized book 3John (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3John (lt)", -> ` expect(p.parse("Jono trecias laiskas 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Jono trecias laiškas 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Jono trečias laiskas 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Jono trečias laiškas 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Jono 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Jn 1:1").osis()).toEqual("3John.1.1") p.include_apocrypha(false) expect(p.parse("JONO TRECIAS LAISKAS 1:1").osis()).toEqual("3John.1.1") expect(p.parse("JONO TRECIAS LAIŠKAS 1:1").osis()).toEqual("3John.1.1") expect(p.parse("JONO TREČIAS LAISKAS 1:1").osis()).toEqual("3John.1.1") expect(p.parse("JONO TREČIAS LAIŠKAS 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 JONO 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 JN 1:1").osis()).toEqual("3John.1.1") ` true describe "Localized book <NAME> (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (lt)", -> ` expect(p.parse("Evangelija pagal Jona 1:1").osis()).toEqual("John.1.1") expect(p.parse("Evangelija pagal Joną 1:1").osis()).toEqual("John.1.1") expect(p.parse("<NAME> 1:1").osis()).toEqual("John.1.1") expect(p.parse("Jono 1:1").osis()).toEqual("John.1.1") expect(p.parse("Jn 1:1").osis()).toEqual("John.1.1") p.include_apocrypha(false) expect(p.parse("EVANGELIJA PAGAL JONA 1:1").osis()).toEqual("John.1.1") expect(p.parse("EVANGELIJA PAGAL JONĄ 1:1").osis()).toEqual("John.1.1") expect(p.parse("<NAME> 1:1").osis()).toEqual("John.1.1") expect(p.parse("JONO 1:1").osis()).toEqual("John.1.1") expect(p.parse("JN 1:1").osis()).toEqual("John.1.1") ` true describe "Localized book Acts (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Acts (lt)", -> ` expect(p.parse("Apastalu darbai 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apastalų darbai 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apaštalu darbai 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apaštalų darbai 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apastalu darbu 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apastalu darbų 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apastalų darbu 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apastalų darbų 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apaštalu darbu 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apaštalu darbų 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apaštalų darbu 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apaštalų darbų 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apd 1:1").osis()).toEqual("Acts.1.1") p.include_apocrypha(false) expect(p.parse("APASTALU DARBAI 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APASTALŲ DARBAI 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APAŠTALU DARBAI 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APAŠTALŲ DARBAI 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APASTALU DARBU 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APASTALU DARBŲ 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APASTALŲ DARBU 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APASTALŲ DARBŲ 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APAŠTALU DARBU 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APAŠTALU DARBŲ 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APAŠTALŲ DARBU 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APAŠTALŲ DARBŲ 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APD 1:1").osis()).toEqual("Acts.1.1") ` true describe "Localized book Rom (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rom (lt)", -> ` expect(p.parse("Laiskas romieciams 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Laiskas romiečiams 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Laiškas romieciams 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Laiškas romiečiams 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Romieciams 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Romiečiams 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS ROMIECIAMS 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("LAISKAS ROMIEČIAMS 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("LAIŠKAS ROMIECIAMS 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("LAIŠKAS ROMIEČIAMS 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROMIECIAMS 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROMIEČIAMS 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1") ` true describe "Localized book 2Cor (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Cor (lt)", -> ` expect(p.parse("Antras laiskas korintieciams 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Antras laiskas korintiečiams 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Antras laiškas korintieciams 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Antras laiškas korintiečiams 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Korintieciams 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Korintiečiams 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2Cor 1:1").osis()).toEqual("2Cor.1.1") p.include_apocrypha(false) expect(p.parse("ANTRAS LAISKAS KORINTIECIAMS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("ANTRAS LAISKAS KORINTIEČIAMS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("ANTRAS LAIŠKAS KORINTIECIAMS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("ANTRAS LAIŠKAS KORINTIEČIAMS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KORINTIECIAMS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KORINTIEČIAMS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1") ` true describe "Localized book 1Cor (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Cor (lt)", -> ` expect(p.parse("Pirmas laiskas korintieciams 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Pirmas laiskas korintiečiams 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Pirmas laiškas korintieciams 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Pirmas laiškas korintiečiams 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Korintieciams 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Korintiečiams 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1Cor 1:1").osis()).toEqual("1Cor.1.1") p.include_apocrypha(false) expect(p.parse("PIRMAS LAISKAS KORINTIECIAMS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("PIRMAS LAISKAS KORINTIEČIAMS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("PIRMAS LAIŠKAS KORINTIECIAMS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("PIRMAS LAIŠKAS KORINTIEČIAMS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KORINTIECIAMS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KORINTIEČIAMS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1") ` true describe "Localized book Gal (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gal (lt)", -> ` expect(p.parse("Laiskas galatams 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Laiškas galatams 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Galatams 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS GALATAMS 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("LAIŠKAS GALATAMS 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GALATAMS 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1") ` true describe "Localized book Eph (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eph (lt)", -> ` expect(p.parse("Laiskas efezieciams 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Laiskas efeziečiams 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Laiškas efezieciams 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Laiškas efeziečiams 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Efezieciams 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Efeziečiams 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Eph 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Ef 1:1").osis()).toEqual("Eph.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS EFEZIECIAMS 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("LAISKAS EFEZIEČIAMS 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("LAIŠKAS EFEZIECIAMS 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("LAIŠKAS EFEZIEČIAMS 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EFEZIECIAMS 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EFEZIEČIAMS 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EPH 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EF 1:1").osis()).toEqual("Eph.1.1") ` true describe "Localized book Phil (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phil (lt)", -> ` expect(p.parse("Laiskas filipieciams 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Laiskas filipiečiams 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Laiškas filipieciams 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Laiškas filipiečiams 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Filipieciams 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Filipiečiams 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Phil 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Fil 1:1").osis()).toEqual("Phil.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS FILIPIECIAMS 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("LAISKAS FILIPIEČIAMS 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("LAIŠKAS FILIPIECIAMS 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("LAIŠKAS FILIPIEČIAMS 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FILIPIECIAMS 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FILIPIEČIAMS 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("PHIL 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FIL 1:1").osis()).toEqual("Phil.1.1") ` true describe "Localized book Col (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Col (lt)", -> ` expect(p.parse("Laiskas kolosieciams 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Laiskas kolosiečiams 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Laiškas kolosieciams 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Laiškas kolosiečiams 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kolosieciams 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kolosiečiams 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kol 1:1").osis()).toEqual("Col.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS KOLOSIECIAMS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("LAISKAS KOLOSIEČIAMS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("LAIŠKAS KOLOSIECIAMS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("LAIŠKAS KOLOSIEČIAMS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOLOSIECIAMS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOLOSIEČIAMS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOL 1:1").osis()).toEqual("Col.1.1") ` true describe "Localized book 2Thess (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Thess (lt)", -> ` expect(p.parse("Antras laiskas tesalonikieciams 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Antras laiskas tesalonikiečiams 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Antras laiškas tesalonikieciams 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Antras laiškas tesalonikiečiams 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Tesalonikieciams 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Tesalonikiečiams 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Tes 1:1").osis()).toEqual("2Thess.1.1") p.include_apocrypha(false) expect(p.parse("ANTRAS LAISKAS TESALONIKIECIAMS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("ANTRAS LAISKAS TESALONIKIEČIAMS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("ANTRAS LAIŠKAS TESALONIKIECIAMS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("ANTRAS LAIŠKAS TESALONIKIEČIAMS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 TESALONIKIECIAMS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 TESALONIKIEČIAMS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 TES 1:1").osis()).toEqual("2Thess.1.1") ` true describe "Localized book 1Thess (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Thess (lt)", -> ` expect(p.parse("Pirmas laiskas tesalonikieciams 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Pirmas laiskas tesalonikiečiams 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Pirmas laiškas tesalonikieciams 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Pirmas laiškas tesalonikiečiams 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Tesalonikieciams 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Tesalonikiečiams 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Tes 1:1").osis()).toEqual("1Thess.1.1") p.include_apocrypha(false) expect(p.parse("PIRMAS LAISKAS TESALONIKIECIAMS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("PIRMAS LAISKAS TESALONIKIEČIAMS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("PIRMAS LAIŠKAS TESALONIKIECIAMS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("PIRMAS LAIŠKAS TESALONIKIEČIAMS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 TESALONIKIECIAMS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 TESALONIKIEČIAMS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 TES 1:1").osis()).toEqual("1Thess.1.1") ` true describe "Localized book 2Tim (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Tim (lt)", -> ` expect(p.parse("An<NAME> 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("An<NAME> 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Timotiejui 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2Tim 1:1").osis()).toEqual("2Tim.1.1") p.include_apocrypha(false) expect(p.parse("<NAME> 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("AN<NAME> 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIMOTIEJUI 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1") ` true describe "Localized book 1Tim (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Tim (lt)", -> ` expect(p.parse("<NAME> 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Pirmas laiš<NAME> Timotiejui 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Timotiejui 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1Tim 1:1").osis()).toEqual("1Tim.1.1") p.include_apocrypha(false) expect(p.parse("PIRMAS LAISKAS TIMOTIEJUI 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("PIRMAS LAIŠKAS TIMOTIEJUI 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIMOTIEJUI 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1") ` true describe "Localized book Titus (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Titus (lt)", -> ` expect(p.parse("Laiskas Titui 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Laiškas Titui 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titui 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tit 1:1").osis()).toEqual("Titus.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS TITUI 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("LAIŠKAS TITUI 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUI 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TIT 1:1").osis()).toEqual("Titus.1.1") ` true describe "Localized book Phlm (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phlm (lt)", -> ` expect(p.parse("Laiskas Filemonui 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Laiškas Filemonui 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Filemonui 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Phlm 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Fm 1:1").osis()).toEqual("Phlm.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS FILEMONUI 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("LAIŠKAS FILEMONUI 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FILEMONUI 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("PHLM 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FM 1:1").osis()).toEqual("Phlm.1.1") ` true describe "Localized book Heb (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Heb (lt)", -> ` expect(p.parse("Laiskas hebrajams 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Laiškas hebrajams 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Hebrajams 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Hbr 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS HEBRAJAMS 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("LAIŠKAS HEBRAJAMS 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEBRAJAMS 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HBR 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1") ` true describe "Localized book Jas (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jas (lt)", -> ` expect(p.parse("Jokubo laiskas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jokubo laiškas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jokūbo laiskas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jokūbo laiškas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jokubo 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jokūbo 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jok 1:1").osis()).toEqual("Jas.1.1") p.include_apocrypha(false) expect(p.parse("JOKUBO LAISKAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JOKUBO LAIŠKAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JOKŪBO LAISKAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JOKŪBO LAIŠKAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JOKUBO 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JOKŪBO 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JOK 1:1").osis()).toEqual("Jas.1.1") ` true describe "Localized book 2Pet (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Pet (lt)", -> ` expect(p.parse("Petro antras laiskas 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Petro antras laiškas 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Pt 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1") p.include_apocrypha(false) expect(p.parse("PETRO ANTRAS LAISKAS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("PETRO ANTRAS LAIŠKAS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 PT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1") ` true describe "Localized book 1Pet (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Pet (lt)", -> ` expect(p.parse("Petro pirmas laiskas 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Petro pirmas laiškas 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Pt 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1") p.include_apocrypha(false) expect(p.parse("PETRO PIRMAS LAISKAS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("PETRO PIRMAS LAIŠKAS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 PT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1") ` true describe "Localized book Jude (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jude (lt)", -> ` expect(p.parse("Judo laiskas 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Judo laiškas 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jude 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Judo 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jud 1:1").osis()).toEqual("Jude.1.1") p.include_apocrypha(false) expect(p.parse("JUDO LAISKAS 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDO LAIŠKAS 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDE 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDO 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUD 1:1").osis()).toEqual("Jude.1.1") ` true describe "Localized book Tob (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Tob (lt)", -> ` expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1") ` true describe "Localized book Jdt (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jdt (lt)", -> ` expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1") ` true describe "Localized book Bar (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bar (lt)", -> ` expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1") ` true describe "Localized book Sus (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sus (lt)", -> ` expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1") ` true describe "Localized book 2Macc (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Macc (lt)", -> ` expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1") ` true describe "Localized book 3Macc (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3Macc (lt)", -> ` expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1") ` true describe "Localized book 4Macc (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 4Macc (lt)", -> ` expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1") ` true describe "Localized book 1Macc (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Macc (lt)", -> ` expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1") ` true describe "Miscellaneous tests", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore", book_sequence_strategy: "ignore", osis_compaction_strategy: "bc", captive_end_digits_strategy: "delete" p.include_apocrypha true it "should return the expected language", -> expect(p.languages).toEqual ["lt"] it "should handle ranges (lt)", -> expect(p.parse("Titus 1:1 iki 2").osis()).toEqual "Titus.1.1-Titus.1.2" expect(p.parse("Matt 1iki2").osis()).toEqual "Matt.1-Matt.2" expect(p.parse("Phlm 2 IKI 3").osis()).toEqual "Phlm.1.2-Phlm.1.3" it "should handle chapters (lt)", -> expect(p.parse("Titus 1:1, Skyrius 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 SKYRIUS 6").osis()).toEqual "Matt.3.4,Matt.6" it "should handle verses (lt)", -> expect(p.parse("Exod 1:1 eilutė 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm EILUTĖ 6").osis()).toEqual "Phlm.1.6" expect(p.parse("Exod 1:1 eilute 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm EILUTE 6").osis()).toEqual "Phlm.1.6" it "should handle 'and' (lt)", -> expect(p.parse("Exod 1:1 Ir 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 IR 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" it "should handle titles (lt)", -> expect(p.parse("Ps 3 title, 4:2, 5:title").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" expect(p.parse("PS 3 TITLE, 4:2, 5:TITLE").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" it "should handle 'ff' (lt)", -> expect(p.parse("Rev 3ff, 4:2ff").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" expect(p.parse("REV 3 FF, 4:2 FF").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" it "should handle translations (lt)", -> expect(p.parse("Lev 1 (lit)").osis_and_translations()).toEqual [["Lev.1", "lit"]] expect(p.parse("lev 1 lit").osis_and_translations()).toEqual [["Lev.1", "lit"]] it "should handle boundaries (lt)", -> p.set_options {book_alone_strategy: "full"} expect(p.parse("\u2014Matt\u2014").osis()).toEqual "Matt.1-Matt.28" expect(p.parse("\u201cMatt 1:1\u201d").osis()).toEqual "Matt.1.1"
true
bcv_parser = require("../../js/lt_bcv_parser.js").bcv_parser describe "Parsing", -> p = {} beforeEach -> p = new bcv_parser p.options.osis_compaction_strategy = "b" p.options.sequence_combination_strategy = "combine" it "should round-trip OSIS references", -> p.set_options osis_compaction_strategy: "bc" books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PImos","PI:NAME:<NAME>END_PIad","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PIah","Hab","Zeph","Hag","Zech","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range it "should round-trip OSIS Apocrypha references", -> p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b" p.include_apocrypha true books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range p.set_options ps151_strategy: "bc" expect(p.parse("Ps151.1").osis()).toEqual "Ps.151" expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1" expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2" p.include_apocrypha false for book in books bc = book + ".1" expect(p.parse(bc).osis()).toEqual "" it "should handle a preceding character", -> expect(p.parse(" Gen 1").osis()).toEqual "Gen.1" expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3" expect(p.parse("1Ps 1").osis()).toEqual "" expect(p.parse("11Sam 1").osis()).toEqual "" describe "Localized book Gen (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gen (lt)", -> ` expect(p.parse("Pradzios knyga 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Pradžios knyga 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Pradzios 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Pradžios 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Pr 1:1").osis()).toEqual("Gen.1.1") p.include_apocrypha(false) expect(p.parse("PRADZIOS KNYGA 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("PRADŽIOS KNYGA 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("PRADZIOS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("PRADŽIOS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("PR 1:1").osis()).toEqual("Gen.1.1") ` true describe "Localized book Exod (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Exod (lt)", -> ` expect(p.parse("Isejimo knyga 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Isėjimo knyga 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Išejimo knyga 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Išėjimo knyga 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Isejimo 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Isėjimo 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Išejimo 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Išėjimo 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Is 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Iš 1:1").osis()).toEqual("Exod.1.1") p.include_apocrypha(false) expect(p.parse("ISEJIMO KNYGA 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ISĖJIMO KNYGA 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("IŠEJIMO KNYGA 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("IŠĖJIMO KNYGA 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ISEJIMO 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ISĖJIMO 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("IŠEJIMO 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("IŠĖJIMO 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("IS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("IŠ 1:1").osis()).toEqual("Exod.1.1") ` true describe "Localized book Bel (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bel (lt)", -> ` expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1") ` true describe "Localized book Lev (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lev (lt)", -> ` expect(p.parse("Kunigu knyga 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Kunigų knyga 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Kunigu 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Kunigų 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Kun 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1") p.include_apocrypha(false) expect(p.parse("KUNIGU KNYGA 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("KUNIGŲ KNYGA 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("KUNIGU 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("KUNIGŲ 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("KUN 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1") ` true describe "Localized book Num (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Num (lt)", -> ` expect(p.parse("Skaiciu knyga 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaicių knyga 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaičiu knyga 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaičių knyga 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaiciu 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaicių 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaičiu 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Skaičių 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Sk 1:1").osis()).toEqual("Num.1.1") p.include_apocrypha(false) expect(p.parse("SKAICIU KNYGA 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAICIŲ KNYGA 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAIČIU KNYGA 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAIČIŲ KNYGA 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAICIU 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAICIŲ 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAIČIU 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SKAIČIŲ 1:1").osis()).toEqual("Num.1.1") expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1") expect(p.parse("SK 1:1").osis()).toEqual("Num.1.1") ` true describe "Localized book Sir (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sir (lt)", -> ` expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1") ` true describe "Localized book Wis (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Wis (lt)", -> ` expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1") ` true describe "Localized book Lam (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lam (lt)", -> ` expect(p.parse("Raudu knyga 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Raudų knyga 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Raudu 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Raudų 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Rd 1:1").osis()).toEqual("Lam.1.1") p.include_apocrypha(false) expect(p.parse("RAUDU KNYGA 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("RAUDŲ KNYGA 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("RAUDU 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("RAUDŲ 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("RD 1:1").osis()).toEqual("Lam.1.1") ` true describe "Localized book EpJer (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: EpJer (lt)", -> ` expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1") ` true describe "Localized book Rev (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rev (lt)", -> ` expect(p.parse("Apreiskimas Jonui 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Apreiškimas Jonui 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Apreiskimo Jonui 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Apreiškimo Jonui 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Apr 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1") p.include_apocrypha(false) expect(p.parse("APREISKIMAS JONUI 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("APREIŠKIMAS JONUI 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("APREISKIMO JONUI 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("APREIŠKIMO JONUI 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("APR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1") ` true describe "Localized book PrMan (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrMan (lt)", -> ` expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1") ` true describe "Localized book Deut (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Deut (lt)", -> ` expect(p.parse("Pakartoto Istatymo knyga 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Pakartoto Įstatymo knyga 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Pakartoto Istatymo 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Pakartoto Įstatymo 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Ist 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Įst 1:1").osis()).toEqual("Deut.1.1") p.include_apocrypha(false) expect(p.parse("PAKARTOTO ISTATYMO KNYGA 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("PAKARTOTO ĮSTATYMO KNYGA 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("PAKARTOTO ISTATYMO 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("PAKARTOTO ĮSTATYMO 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("IST 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("ĮST 1:1").osis()).toEqual("Deut.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PIosh (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PIosh (lt)", -> ` expect(p.parse("Jozues knyga 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jozuės knyga 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jozues 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jozuės 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josh 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Joz 1:1").osis()).toEqual("Josh.1.1") p.include_apocrypha(false) expect(p.parse("JOZUES KNYGA 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOZUĖS KNYGA 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOZUES 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOZUĖS 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSH 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOZ 1:1").osis()).toEqual("Josh.1.1") ` true describe "Localized book Judg (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Judg (lt)", -> ` expect(p.parse("Teiseju knyga 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teisejų knyga 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teisėju knyga 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teisėjų knyga 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teiseju 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teisejų 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teisėju 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Teisėjų 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Ts 1:1").osis()).toEqual("Judg.1.1") p.include_apocrypha(false) expect(p.parse("TEISEJU KNYGA 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISEJŲ KNYGA 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISĖJU KNYGA 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISĖJŲ KNYGA 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISEJU 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISEJŲ 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISĖJU 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TEISĖJŲ 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("TS 1:1").osis()).toEqual("Judg.1.1") ` true describe "Localized book Ruth (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ruth (lt)", -> ` expect(p.parse("Rutos knyga 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rūtos knyga 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rutos 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rūtos 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rut 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rūt 1:1").osis()).toEqual("Ruth.1.1") p.include_apocrypha(false) expect(p.parse("RUTOS KNYGA 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RŪTOS KNYGA 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTOS 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RŪTOS 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTH 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUT 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RŪT 1:1").osis()).toEqual("Ruth.1.1") ` true describe "Localized book 1Esd (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Esd (lt)", -> ` expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1") ` true describe "Localized book 2Esd (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Esd (lt)", -> ` expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1") ` true describe "Localized book Isa (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Isa (lt)", -> ` expect(p.parse("Izaijo knyga 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Izaijo 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Iz 1:1").osis()).toEqual("Isa.1.1") p.include_apocrypha(false) expect(p.parse("IZAIJO KNYGA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("IZAIJO 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("IZ 1:1").osis()).toEqual("Isa.1.1") ` true describe "Localized book 2Sam (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Sam (lt)", -> ` expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SamPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1") p.include_apocrypha(false) expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAMUELIO 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1") ` true describe "Localized book 1Sam (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Sam (lt)", -> ` expect(p.parse("PI:NAME:<NAME>END_PI knyga 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SamPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1") p.include_apocrypha(false) expect(p.parse("PI:NAME:<NAME>END_PI KNYGA 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAMUELIO 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1") ` true describe "Localized book 2Kgs (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Kgs (lt)", -> ` expect(p.parse("Karaliu antra knyga 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Karalių antra knyga 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Karaliu 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Karalių 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Kar 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1") p.include_apocrypha(false) expect(p.parse("KARALIU ANTRA KNYGA 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("KARALIŲ ANTRA KNYGA 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 KARALIU 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 KARALIŲ 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 KAR 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1") ` true describe "Localized book 1Kgs (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Kgs (lt)", -> ` expect(p.parse("Karaliu pirma knyga 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Karalių pirma knyga 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Karaliu 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Karalių 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Kar 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1") p.include_apocrypha(false) expect(p.parse("KARALIU PIRMA KNYGA 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("KARALIŲ PIRMA KNYGA 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 KARALIU 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 KARALIŲ 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 KAR 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1") ` true describe "Localized book 2Chr (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Chr (lt)", -> ` expect(p.parse("Metrasciu antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metrascių antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metrasčiu antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metrasčių antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metrašciu antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metrašcių antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metraščiu antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Metraščių antra knyga 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metrasciu 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metrascių 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metrasčiu 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metrasčių 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metrašciu 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metrašcių 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metraščiu 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Metraščių 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Met 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2Chr 1:1").osis()).toEqual("2Chr.1.1") p.include_apocrypha(false) expect(p.parse("METRASCIU ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRASCIŲ ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRASČIU ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRASČIŲ ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRAŠCIU ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRAŠCIŲ ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRAŠČIU ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("METRAŠČIŲ ANTRA KNYGA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRASCIU 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRASCIŲ 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRASČIU 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRASČIŲ 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRAŠCIU 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRAŠCIŲ 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRAŠČIU 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 METRAŠČIŲ 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 MET 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1") ` true describe "Localized book 1Chr (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Chr (lt)", -> ` expect(p.parse("Metrasciu pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metrascių pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metrasčiu pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metrasčių pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metrašciu pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metrašcių pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metraščiu pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Metraščių pirma knyga 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metrasciu 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metrascių 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metrasčiu 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metrasčių 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metrašciu 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metrašcių 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metraščiu 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Metraščių 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Met 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1Chr 1:1").osis()).toEqual("1Chr.1.1") p.include_apocrypha(false) expect(p.parse("METRASCIU PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRASCIŲ PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRASČIU PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRASČIŲ PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRAŠCIU PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRAŠCIŲ PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRAŠČIU PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("METRAŠČIŲ PIRMA KNYGA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRASCIU 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRASCIŲ 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRASČIU 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRASČIŲ 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRAŠCIU 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRAŠCIŲ 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRAŠČIU 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 METRAŠČIŲ 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 MET 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1") ` true describe "Localized book Ezra (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezra (lt)", -> ` expect(p.parse("Ezros knyga 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezros 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezr 1:1").osis()).toEqual("Ezra.1.1") p.include_apocrypha(false) expect(p.parse("EZROS KNYGA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZROS 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZR 1:1").osis()).toEqual("Ezra.1.1") ` true describe "Localized book Neh (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Neh (lt)", -> ` expect(p.parse("Nehemijo knyga 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Nehemijo 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1") p.include_apocrypha(false) expect(p.parse("NEHEMIJO KNYGA 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEHEMIJO 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1") ` true describe "Localized book GkEsth (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: GkEsth (lt)", -> ` expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1") ` true describe "Localized book Esth (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Esth (lt)", -> ` expect(p.parse("Esteros knyga 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esteros 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esth 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Est 1:1").osis()).toEqual("Esth.1.1") p.include_apocrypha(false) expect(p.parse("ESTEROS KNYGA 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTEROS 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTH 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("EST 1:1").osis()).toEqual("Esth.1.1") ` true describe "Localized book Job (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Job (lt)", -> ` expect(p.parse("Jobo knyga 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Jobo 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1") p.include_apocrypha(false) expect(p.parse("JOBO KNYGA 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOBO 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1") ` true describe "Localized book Ps (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ps (lt)", -> ` expect(p.parse("Psalmynas 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Ps 1:1").osis()).toEqual("Ps.1.1") p.include_apocrypha(false) expect(p.parse("PSALMYNAS 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("PS 1:1").osis()).toEqual("Ps.1.1") ` true describe "Localized book PrAzar (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrAzar (lt)", -> ` expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1") ` true describe "Localized book Prov (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Prov (lt)", -> ` expect(p.parse("Patarliu knyga 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Patarlių knyga 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Patarliu 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Patarlių 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Pat 1:1").osis()).toEqual("Prov.1.1") p.include_apocrypha(false) expect(p.parse("PATARLIU KNYGA 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PATARLIŲ KNYGA 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PATARLIU 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PATARLIŲ 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PAT 1:1").osis()).toEqual("Prov.1.1") ` true describe "Localized book Eccl (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eccl (lt)", -> ` expect(p.parse("Mokytojo knyga 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Mokytojo 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Mok 1:1").osis()).toEqual("Eccl.1.1") p.include_apocrypha(false) expect(p.parse("MOKYTOJO KNYGA 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("MOKYTOJO 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("MOK 1:1").osis()).toEqual("Eccl.1.1") ` true describe "Localized book SgThree (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: SgThree (lt)", -> ` expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1") ` true describe "Localized book Song (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Song (lt)", -> ` expect(p.parse("Giesmiu giesmes knyga 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmiu giesmės knyga 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmių giesmes knyga 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmių giesmės knyga 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmiu giesmes 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmiu giesmės 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmių giesmes 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Giesmių giesmės 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Gg 1:1").osis()).toEqual("Song.1.1") p.include_apocrypha(false) expect(p.parse("GIESMIU GIESMES KNYGA 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIU GIESMĖS KNYGA 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIŲ GIESMES KNYGA 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIŲ GIESMĖS KNYGA 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIU GIESMES 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIU GIESMĖS 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIŲ GIESMES 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GIESMIŲ GIESMĖS 1:1").osis()).toEqual("Song.1.1") expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GG 1:1").osis()).toEqual("Song.1.1") ` true describe "Localized book Jer (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (lt)", -> ` expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jeremijo 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1") p.include_apocrypha(false) expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JEREMIJO 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PIzek (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezek (lt)", -> ` expect(p.parse("Ezechielio knyga 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ezechielio 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ez 1:1").osis()).toEqual("Ezek.1.1") p.include_apocrypha(false) expect(p.parse("EZECHIELIO KNYGA 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZECHIELIO 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZ 1:1").osis()).toEqual("Ezek.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (lt)", -> ` expect(p.parse("Danieliaus knyga 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Danieliaus 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1") p.include_apocrypha(false) expect(p.parse("DANIELIAUS KNYGA 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DANIELIAUS 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DAN 1:1").osis()).toEqual("Dan.1.1") ` true describe "Localized book Hos (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hos (lt)", -> ` expect(p.parse("Ozejo knyga 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Ozėjo knyga 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Ozejo 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Ozėjo 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Oz 1:1").osis()).toEqual("Hos.1.1") p.include_apocrypha(false) expect(p.parse("OZEJO KNYGA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("OZĖJO KNYGA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("OZEJO 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("OZĖJO 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("OZ 1:1").osis()).toEqual("Hos.1.1") ` true describe "Localized book Joel (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Joel (lt)", -> ` expect(p.parse("Joelio knyga 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Joelio 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Jl 1:1").osis()).toEqual("Joel.1.1") p.include_apocrypha(false) expect(p.parse("JOELIO KNYGA 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JOELIO 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JOEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JL 1:1").osis()).toEqual("Joel.1.1") ` true describe "Localized book Amos (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Amos (lt)", -> ` expect(p.parse("Amoso knyga 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Amoso 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Am 1:1").osis()).toEqual("Amos.1.1") p.include_apocrypha(false) expect(p.parse("AMOSO KNYGA 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AMOSO 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AMOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AM 1:1").osis()).toEqual("Amos.1.1") ` true describe "Localized book Obad (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Obad (lt)", -> ` expect(p.parse("Abdijo knyga 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Abdijo 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Abd 1:1").osis()).toEqual("Obad.1.1") p.include_apocrypha(false) expect(p.parse("ABDIJO KNYGA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("ABDIJO 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("ABD 1:1").osis()).toEqual("Obad.1.1") ` true describe "Localized book Jonah (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (lt)", -> ` expect(p.parse("Jonos knyga 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jonah 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jonos 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Jonah.1.1") p.include_apocrypha(false) expect(p.parse("JONOS KNYGA 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JONAH 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JONOS 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JON 1:1").osis()).toEqual("Jonah.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PIic (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PIic (lt)", -> ` expect(p.parse("Michejo knyga 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Michėjo knyga 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Michejo 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Michėjo 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mch 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1") p.include_apocrypha(false) expect(p.parse("MICHEJO KNYGA 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MICHĖJO KNYGA 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MICHEJO 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MICHĖJO 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MCH 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1") ` true describe "Localized book Nah (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Nah (lt)", -> ` expect(p.parse("Nahumo knyga 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nahumo 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1") p.include_apocrypha(false) expect(p.parse("NAHUMO KNYGA 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAHUMO 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1") ` true describe "Localized book Hab (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hab (lt)", -> ` expect(p.parse("Habakuko knyga 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Habakuko 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Hab 1:1").osis()).toEqual("Hab.1.1") p.include_apocrypha(false) expect(p.parse("HABAKUKO KNYGA 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HABAKUKO 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1") ` true describe "Localized book Zeph (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zeph (lt)", -> ` expect(p.parse("Sofonijo knyga 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sofonijo 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sof 1:1").osis()).toEqual("Zeph.1.1") p.include_apocrypha(false) expect(p.parse("SOFONIJO KNYGA 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SOFONIJO 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SOF 1:1").osis()).toEqual("Zeph.1.1") ` true describe "Localized book Hag (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hag (lt)", -> ` expect(p.parse("Agejo knyga 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Agėjo knyga 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Agejo 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Agėjo 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Ag 1:1").osis()).toEqual("Hag.1.1") p.include_apocrypha(false) expect(p.parse("AGEJO KNYGA 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("AGĖJO KNYGA 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("AGEJO 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("AGĖJO 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("AG 1:1").osis()).toEqual("Hag.1.1") ` true describe "Localized book Zech (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zech (lt)", -> ` expect(p.parse("Zacharijo knyga 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zacharijo 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zch 1:1").osis()).toEqual("Zech.1.1") p.include_apocrypha(false) expect(p.parse("ZACHARIJO KNYGA 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZACHARIJO 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZCH 1:1").osis()).toEqual("Zech.1.1") ` true describe "Localized book Mal (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mal (lt)", -> ` expect(p.parse("Malachijo knyga 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Malachijo 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1") p.include_apocrypha(false) expect(p.parse("MALACHIJO KNYGA 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MALACHIJO 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (lt)", -> ` expect(p.parse("Evangelija pagal Mata 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Evangelija pagal Matą 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Mato 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Matt 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Mt 1:1").osis()).toEqual("Matt.1.1") p.include_apocrypha(false) expect(p.parse("EVANGELIJA PAGAL MATA 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("EVANGELIJA PAGAL MATĄ 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATO 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATT 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MT 1:1").osis()).toEqual("Matt.1.1") ` true describe "Localized book Mark (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mark (lt)", -> ` expect(p.parse("Evangelija pagal Morku 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Evangelija pagal Morkų 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Morkaus 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mark 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mk 1:1").osis()).toEqual("Mark.1.1") p.include_apocrypha(false) expect(p.parse("EVANGELIJA PAGAL MORKU 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("EVANGELIJA PAGAL MORKŲ 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MORKAUS 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MARK 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MK 1:1").osis()).toEqual("Mark.1.1") ` true describe "Localized book LPI:NAME:<NAME>END_PI (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (lt)", -> ` expect(p.parse("Evangelija pagal Luka 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Evangelija pagal Luką 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luko 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Lk 1:1").osis()).toEqual("Luke.1.1") p.include_apocrypha(false) expect(p.parse("EVANGELIJA PAGAL LUKA 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("EVANGELIJA PAGAL LUKĄ 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKO 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LK 1:1").osis()).toEqual("Luke.1.1") ` true describe "Localized book 1John (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1John (lt)", -> ` expect(p.parse("Jono pirmas laiskas 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Jono pirmas laiškas 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Jono 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Jn 1:1").osis()).toEqual("1John.1.1") p.include_apocrypha(false) expect(p.parse("JONO PIRMAS LAISKAS 1:1").osis()).toEqual("1John.1.1") expect(p.parse("JONO PIRMAS LAIŠKAS 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 JONO 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 JN 1:1").osis()).toEqual("1John.1.1") ` true describe "Localized book 2John (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2John (lt)", -> ` expect(p.parse("Jono antras laiskas 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Jono antras laiškas 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Jono 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Jn 1:1").osis()).toEqual("2John.1.1") p.include_apocrypha(false) expect(p.parse("JONO ANTRAS LAISKAS 1:1").osis()).toEqual("2John.1.1") expect(p.parse("JONO ANTRAS LAIŠKAS 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 JONO 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 JN 1:1").osis()).toEqual("2John.1.1") ` true describe "Localized book 3John (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3John (lt)", -> ` expect(p.parse("Jono trecias laiskas 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Jono trecias laiškas 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Jono trečias laiskas 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Jono trečias laiškas 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Jono 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Jn 1:1").osis()).toEqual("3John.1.1") p.include_apocrypha(false) expect(p.parse("JONO TRECIAS LAISKAS 1:1").osis()).toEqual("3John.1.1") expect(p.parse("JONO TRECIAS LAIŠKAS 1:1").osis()).toEqual("3John.1.1") expect(p.parse("JONO TREČIAS LAISKAS 1:1").osis()).toEqual("3John.1.1") expect(p.parse("JONO TREČIAS LAIŠKAS 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 JONO 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 JN 1:1").osis()).toEqual("3John.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (lt)", -> ` expect(p.parse("Evangelija pagal Jona 1:1").osis()).toEqual("John.1.1") expect(p.parse("Evangelija pagal Joną 1:1").osis()).toEqual("John.1.1") expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("John.1.1") expect(p.parse("Jono 1:1").osis()).toEqual("John.1.1") expect(p.parse("Jn 1:1").osis()).toEqual("John.1.1") p.include_apocrypha(false) expect(p.parse("EVANGELIJA PAGAL JONA 1:1").osis()).toEqual("John.1.1") expect(p.parse("EVANGELIJA PAGAL JONĄ 1:1").osis()).toEqual("John.1.1") expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("John.1.1") expect(p.parse("JONO 1:1").osis()).toEqual("John.1.1") expect(p.parse("JN 1:1").osis()).toEqual("John.1.1") ` true describe "Localized book Acts (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Acts (lt)", -> ` expect(p.parse("Apastalu darbai 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apastalų darbai 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apaštalu darbai 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apaštalų darbai 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apastalu darbu 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apastalu darbų 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apastalų darbu 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apastalų darbų 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apaštalu darbu 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apaštalu darbų 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apaštalų darbu 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apaštalų darbų 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Apd 1:1").osis()).toEqual("Acts.1.1") p.include_apocrypha(false) expect(p.parse("APASTALU DARBAI 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APASTALŲ DARBAI 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APAŠTALU DARBAI 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APAŠTALŲ DARBAI 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APASTALU DARBU 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APASTALU DARBŲ 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APASTALŲ DARBU 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APASTALŲ DARBŲ 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APAŠTALU DARBU 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APAŠTALU DARBŲ 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APAŠTALŲ DARBU 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APAŠTALŲ DARBŲ 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("APD 1:1").osis()).toEqual("Acts.1.1") ` true describe "Localized book Rom (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rom (lt)", -> ` expect(p.parse("Laiskas romieciams 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Laiskas romiečiams 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Laiškas romieciams 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Laiškas romiečiams 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Romieciams 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Romiečiams 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS ROMIECIAMS 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("LAISKAS ROMIEČIAMS 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("LAIŠKAS ROMIECIAMS 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("LAIŠKAS ROMIEČIAMS 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROMIECIAMS 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROMIEČIAMS 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1") ` true describe "Localized book 2Cor (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Cor (lt)", -> ` expect(p.parse("Antras laiskas korintieciams 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Antras laiskas korintiečiams 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Antras laiškas korintieciams 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Antras laiškas korintiečiams 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Korintieciams 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Korintiečiams 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2Cor 1:1").osis()).toEqual("2Cor.1.1") p.include_apocrypha(false) expect(p.parse("ANTRAS LAISKAS KORINTIECIAMS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("ANTRAS LAISKAS KORINTIEČIAMS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("ANTRAS LAIŠKAS KORINTIECIAMS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("ANTRAS LAIŠKAS KORINTIEČIAMS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KORINTIECIAMS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KORINTIEČIAMS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1") ` true describe "Localized book 1Cor (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Cor (lt)", -> ` expect(p.parse("Pirmas laiskas korintieciams 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Pirmas laiskas korintiečiams 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Pirmas laiškas korintieciams 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Pirmas laiškas korintiečiams 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Korintieciams 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Korintiečiams 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1Cor 1:1").osis()).toEqual("1Cor.1.1") p.include_apocrypha(false) expect(p.parse("PIRMAS LAISKAS KORINTIECIAMS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("PIRMAS LAISKAS KORINTIEČIAMS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("PIRMAS LAIŠKAS KORINTIECIAMS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("PIRMAS LAIŠKAS KORINTIEČIAMS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KORINTIECIAMS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KORINTIEČIAMS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1") ` true describe "Localized book Gal (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gal (lt)", -> ` expect(p.parse("Laiskas galatams 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Laiškas galatams 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Galatams 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS GALATAMS 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("LAIŠKAS GALATAMS 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GALATAMS 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1") ` true describe "Localized book Eph (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eph (lt)", -> ` expect(p.parse("Laiskas efezieciams 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Laiskas efeziečiams 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Laiškas efezieciams 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Laiškas efeziečiams 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Efezieciams 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Efeziečiams 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Eph 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Ef 1:1").osis()).toEqual("Eph.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS EFEZIECIAMS 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("LAISKAS EFEZIEČIAMS 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("LAIŠKAS EFEZIECIAMS 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("LAIŠKAS EFEZIEČIAMS 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EFEZIECIAMS 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EFEZIEČIAMS 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EPH 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EF 1:1").osis()).toEqual("Eph.1.1") ` true describe "Localized book Phil (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phil (lt)", -> ` expect(p.parse("Laiskas filipieciams 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Laiskas filipiečiams 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Laiškas filipieciams 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Laiškas filipiečiams 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Filipieciams 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Filipiečiams 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Phil 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Fil 1:1").osis()).toEqual("Phil.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS FILIPIECIAMS 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("LAISKAS FILIPIEČIAMS 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("LAIŠKAS FILIPIECIAMS 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("LAIŠKAS FILIPIEČIAMS 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FILIPIECIAMS 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FILIPIEČIAMS 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("PHIL 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FIL 1:1").osis()).toEqual("Phil.1.1") ` true describe "Localized book Col (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Col (lt)", -> ` expect(p.parse("Laiskas kolosieciams 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Laiskas kolosiečiams 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Laiškas kolosieciams 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Laiškas kolosiečiams 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kolosieciams 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kolosiečiams 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kol 1:1").osis()).toEqual("Col.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS KOLOSIECIAMS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("LAISKAS KOLOSIEČIAMS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("LAIŠKAS KOLOSIECIAMS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("LAIŠKAS KOLOSIEČIAMS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOLOSIECIAMS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOLOSIEČIAMS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOL 1:1").osis()).toEqual("Col.1.1") ` true describe "Localized book 2Thess (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Thess (lt)", -> ` expect(p.parse("Antras laiskas tesalonikieciams 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Antras laiskas tesalonikiečiams 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Antras laiškas tesalonikieciams 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Antras laiškas tesalonikiečiams 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Tesalonikieciams 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Tesalonikiečiams 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Tes 1:1").osis()).toEqual("2Thess.1.1") p.include_apocrypha(false) expect(p.parse("ANTRAS LAISKAS TESALONIKIECIAMS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("ANTRAS LAISKAS TESALONIKIEČIAMS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("ANTRAS LAIŠKAS TESALONIKIECIAMS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("ANTRAS LAIŠKAS TESALONIKIEČIAMS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 TESALONIKIECIAMS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 TESALONIKIEČIAMS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 TES 1:1").osis()).toEqual("2Thess.1.1") ` true describe "Localized book 1Thess (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Thess (lt)", -> ` expect(p.parse("Pirmas laiskas tesalonikieciams 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Pirmas laiskas tesalonikiečiams 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Pirmas laiškas tesalonikieciams 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Pirmas laiškas tesalonikiečiams 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Tesalonikieciams 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Tesalonikiečiams 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Tes 1:1").osis()).toEqual("1Thess.1.1") p.include_apocrypha(false) expect(p.parse("PIRMAS LAISKAS TESALONIKIECIAMS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("PIRMAS LAISKAS TESALONIKIEČIAMS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("PIRMAS LAIŠKAS TESALONIKIECIAMS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("PIRMAS LAIŠKAS TESALONIKIEČIAMS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 TESALONIKIECIAMS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 TESALONIKIEČIAMS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 TES 1:1").osis()).toEqual("1Thess.1.1") ` true describe "Localized book 2Tim (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Tim (lt)", -> ` expect(p.parse("AnPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("AnPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Timotiejui 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2Tim 1:1").osis()).toEqual("2Tim.1.1") p.include_apocrypha(false) expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("ANPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIMOTIEJUI 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1") ` true describe "Localized book 1Tim (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Tim (lt)", -> ` expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Pirmas laišPI:NAME:<NAME>END_PI Timotiejui 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Timotiejui 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1Tim 1:1").osis()).toEqual("1Tim.1.1") p.include_apocrypha(false) expect(p.parse("PIRMAS LAISKAS TIMOTIEJUI 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("PIRMAS LAIŠKAS TIMOTIEJUI 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIMOTIEJUI 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1") ` true describe "Localized book Titus (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Titus (lt)", -> ` expect(p.parse("Laiskas Titui 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Laiškas Titui 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titui 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tit 1:1").osis()).toEqual("Titus.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS TITUI 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("LAIŠKAS TITUI 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUI 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TIT 1:1").osis()).toEqual("Titus.1.1") ` true describe "Localized book Phlm (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phlm (lt)", -> ` expect(p.parse("Laiskas Filemonui 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Laiškas Filemonui 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Filemonui 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Phlm 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Fm 1:1").osis()).toEqual("Phlm.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS FILEMONUI 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("LAIŠKAS FILEMONUI 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FILEMONUI 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("PHLM 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FM 1:1").osis()).toEqual("Phlm.1.1") ` true describe "Localized book Heb (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Heb (lt)", -> ` expect(p.parse("Laiskas hebrajams 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Laiškas hebrajams 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Hebrajams 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Hbr 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1") p.include_apocrypha(false) expect(p.parse("LAISKAS HEBRAJAMS 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("LAIŠKAS HEBRAJAMS 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEBRAJAMS 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HBR 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1") ` true describe "Localized book Jas (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jas (lt)", -> ` expect(p.parse("Jokubo laiskas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jokubo laiškas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jokūbo laiskas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jokūbo laiškas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jokubo 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jokūbo 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jok 1:1").osis()).toEqual("Jas.1.1") p.include_apocrypha(false) expect(p.parse("JOKUBO LAISKAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JOKUBO LAIŠKAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JOKŪBO LAISKAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JOKŪBO LAIŠKAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JOKUBO 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JOKŪBO 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JOK 1:1").osis()).toEqual("Jas.1.1") ` true describe "Localized book 2Pet (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Pet (lt)", -> ` expect(p.parse("Petro antras laiskas 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Petro antras laiškas 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Pt 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1") p.include_apocrypha(false) expect(p.parse("PETRO ANTRAS LAISKAS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("PETRO ANTRAS LAIŠKAS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 PT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1") ` true describe "Localized book 1Pet (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Pet (lt)", -> ` expect(p.parse("Petro pirmas laiskas 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Petro pirmas laiškas 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Pt 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1") p.include_apocrypha(false) expect(p.parse("PETRO PIRMAS LAISKAS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("PETRO PIRMAS LAIŠKAS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 PT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1") ` true describe "Localized book Jude (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jude (lt)", -> ` expect(p.parse("Judo laiskas 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Judo laiškas 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jude 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Judo 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jud 1:1").osis()).toEqual("Jude.1.1") p.include_apocrypha(false) expect(p.parse("JUDO LAISKAS 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDO LAIŠKAS 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDE 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDO 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUD 1:1").osis()).toEqual("Jude.1.1") ` true describe "Localized book Tob (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Tob (lt)", -> ` expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1") ` true describe "Localized book Jdt (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jdt (lt)", -> ` expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1") ` true describe "Localized book Bar (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bar (lt)", -> ` expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1") ` true describe "Localized book Sus (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sus (lt)", -> ` expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1") ` true describe "Localized book 2Macc (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Macc (lt)", -> ` expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1") ` true describe "Localized book 3Macc (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3Macc (lt)", -> ` expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1") ` true describe "Localized book 4Macc (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 4Macc (lt)", -> ` expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1") ` true describe "Localized book 1Macc (lt)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Macc (lt)", -> ` expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1") ` true describe "Miscellaneous tests", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore", book_sequence_strategy: "ignore", osis_compaction_strategy: "bc", captive_end_digits_strategy: "delete" p.include_apocrypha true it "should return the expected language", -> expect(p.languages).toEqual ["lt"] it "should handle ranges (lt)", -> expect(p.parse("Titus 1:1 iki 2").osis()).toEqual "Titus.1.1-Titus.1.2" expect(p.parse("Matt 1iki2").osis()).toEqual "Matt.1-Matt.2" expect(p.parse("Phlm 2 IKI 3").osis()).toEqual "Phlm.1.2-Phlm.1.3" it "should handle chapters (lt)", -> expect(p.parse("Titus 1:1, Skyrius 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 SKYRIUS 6").osis()).toEqual "Matt.3.4,Matt.6" it "should handle verses (lt)", -> expect(p.parse("Exod 1:1 eilutė 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm EILUTĖ 6").osis()).toEqual "Phlm.1.6" expect(p.parse("Exod 1:1 eilute 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm EILUTE 6").osis()).toEqual "Phlm.1.6" it "should handle 'and' (lt)", -> expect(p.parse("Exod 1:1 Ir 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 IR 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" it "should handle titles (lt)", -> expect(p.parse("Ps 3 title, 4:2, 5:title").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" expect(p.parse("PS 3 TITLE, 4:2, 5:TITLE").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" it "should handle 'ff' (lt)", -> expect(p.parse("Rev 3ff, 4:2ff").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" expect(p.parse("REV 3 FF, 4:2 FF").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" it "should handle translations (lt)", -> expect(p.parse("Lev 1 (lit)").osis_and_translations()).toEqual [["Lev.1", "lit"]] expect(p.parse("lev 1 lit").osis_and_translations()).toEqual [["Lev.1", "lit"]] it "should handle boundaries (lt)", -> p.set_options {book_alone_strategy: "full"} expect(p.parse("\u2014Matt\u2014").osis()).toEqual "Matt.1-Matt.28" expect(p.parse("\u201cMatt 1:1\u201d").osis()).toEqual "Matt.1.1"
[ { "context": "name: Meteor.settings.ldap.bindCn,\n password: Meteor.settings.ldap.bindPassword\n attributes: {\n user", "end": 433, "score": 0.7388691902160645, "start": 418, "tag": "PASSWORD", "value": "Meteor.settings" }, { "context": "s.ldap.tlsOptions || {}\n });\n @username = @sanitize_for_search(username)\n\n sanitize_for_search: (s) -", "end": 645, "score": 0.7728260159492493, "start": 635, "tag": "USERNAME", "value": "@sanitize_" }, { "context": " () -> \n userFuture = new Future\n username = @username\n\n @ad.findUser @username, (err, userObj) ->\n ", "end": 996, "score": 0.9991828799247742, "start": 987, "tag": "USERNAME", "value": "@username" } ]
ldap_server.coffee
tcrowl/meteor-accounts-ldap
13
ActiveDirectory = Npm.require('activedirectory'); Future = Npm.require('fibers/future') assert = Npm.require('assert') if !Meteor.settings.ldap throw new Error('"ldap" not found in Meteor.settings') class UserQuery constructor: (username) -> @ad = ActiveDirectory({ url: Meteor.settings.ldap.url, baseDN: Meteor.settings.ldap.baseDn, username: Meteor.settings.ldap.bindCn, password: Meteor.settings.ldap.bindPassword attributes: { user: ["dn"].concat(Meteor.settings.ldap.autopublishFields), }, tlsOptions: Meteor.settings.ldap.tlsOptions || {} }); @username = @sanitize_for_search(username) sanitize_for_search: (s) -> # Escape search string for LDAP according to RFC4515 s = s.replace('\\', '\\5C') s = s.replace('\0', '\\00') s = s.replace('*','\\2A' ) s = s.replace('(','\\28' ) s = s.replace(')','\\29' ) return s findUser: () -> userFuture = new Future username = @username @ad.findUser @username, (err, userObj) -> if err if Meteor.settings.ldap.debug console.log 'ERROR: ' + JSON.stringify(err) userFuture.return false return if !userObj if Meteor.settings.ldap.debug console.log 'User: ' + username + ' not found.' userFuture.return false else if Meteor.settings.ldap.debug console.log JSON.stringify(userObj) userFuture.return userObj userObj = userFuture.wait() if not userObj throw new (Meteor.Error)(403, 'Invalid username') @userObj = userObj authenticate: (password) -> authenticateFuture = new Future @ad.authenticate @userObj.dn, password, (err, auth) -> if err if Meteor.settings.ldap.debug console.log 'ERROR: ' + JSON.stringify(err) authenticateFuture.return false return if auth if Meteor.settings.ldap.debug console.log 'Authenticated!' authenticateFuture.return true else if Meteor.settings.ldap.debug console.log 'Authentication failed!' authenticateFuture.return false return success = authenticateFuture.wait() if not success or password == '' throw new (Meteor.Error)(403, 'Invalid credentials') @authenticated = success return success getGroupMembershipForUser: () -> groupsFuture = new Future @ad.getGroupMembershipForUser @userObj.dn, (err, groups) -> if err console.log('ERROR: ' +JSON.stringify(err)); groupsFuture.return false return if not groups console.log('User: ' + @userObj.dn + ' not found.') groupsFuture.return false else if Meteor.settings.ldap.debug console.log('Groups found for ' + @userObj.dn + ': '+ JSON.stringify(groups)) groupsFuture.return groups return return groupsFuture.wait() isUserMemberOf: (groupName) -> isMemberFuture = new Future @ad.isUserMemberOf @userObj.dn, groupName, (err, isMember) -> if err console.log 'ERROR: ' + JSON.stringify(err) isMemberFuture.return false return if Meteor.settings.ldap.debug console.log @userObj.displayName + ' isMemberOf ' + groupName + ': ' + isMember isMemberFuture.return isMember return return isMemberFuture.wait() queryMembershipAndAddToMeteor: (callback) -> for groupName in Meteor.settings.ldap.groupMembership ad = @ad userObj = @userObj do (groupName) -> ad.isUserMemberOf userObj.dn, groupName, (err, isMember) -> do (groupName) -> if err if Meteor.settings.ldap.debug console.log 'ERROR: ' + JSON.stringify(err) else if Meteor.settings.ldap.debug console.log userObj.dn + ' isMemberOf ' + groupName + ': ' + isMember callback(groupName,isMember) Accounts.registerLoginHandler 'ldap', (request) -> return undefined if !request.ldap # 1. create query user_query = new UserQuery(request.username) if Meteor.settings.ldap.debug console.log 'LDAP authentication for ' + request.username user_query.findUser() # Allows both sAMAccountName and email # 2. authenticate user authenticated = user_query.authenticate(request.pass) if Meteor.settings.ldap.debug console.log('* AUTHENTICATED:',authenticated) # 3. update database userId = undefined userObj = user_query.userObj userObj.username = request.username user = Meteor.users.findOne(dn: userObj.dn) if user userId = user._id Meteor.users.update userId, $set: userObj else userId = Meteor.users.insert(userObj) if Meteor.settings.ldap.autopublishFields Accounts.addAutopublishFields forLoggedInUser: Meteor.settings.ldap.autopublishFields forOtherUsers: Meteor.settings.ldap.autopublishFields stampedToken = Accounts._generateStampedLoginToken() hashStampedToken = Accounts._hashStampedToken(stampedToken) Meteor.users.update userId, $push: 'services.resume.loginTokens': hashStampedToken # 4. update membership of groups (asynchronously, as this can be really slow) user_query.queryMembershipAndAddToMeteor Meteor.bindEnvironment (groupName,isMember) -> if isMember Meteor.users.update userId, $addToSet: 'memberOf': groupName Meteor.users.update userId, $pull: 'notMemberOf': groupName else Meteor.users.update userId, $pull: 'memberOf': groupName Meteor.users.update userId, $addToSet: 'notMemberOf': groupName { userId: userId token: stampedToken.token tokenExpires: Accounts._tokenExpiration(hashStampedToken.when) }
69740
ActiveDirectory = Npm.require('activedirectory'); Future = Npm.require('fibers/future') assert = Npm.require('assert') if !Meteor.settings.ldap throw new Error('"ldap" not found in Meteor.settings') class UserQuery constructor: (username) -> @ad = ActiveDirectory({ url: Meteor.settings.ldap.url, baseDN: Meteor.settings.ldap.baseDn, username: Meteor.settings.ldap.bindCn, password: <PASSWORD>.ldap.bindPassword attributes: { user: ["dn"].concat(Meteor.settings.ldap.autopublishFields), }, tlsOptions: Meteor.settings.ldap.tlsOptions || {} }); @username = @sanitize_for_search(username) sanitize_for_search: (s) -> # Escape search string for LDAP according to RFC4515 s = s.replace('\\', '\\5C') s = s.replace('\0', '\\00') s = s.replace('*','\\2A' ) s = s.replace('(','\\28' ) s = s.replace(')','\\29' ) return s findUser: () -> userFuture = new Future username = @username @ad.findUser @username, (err, userObj) -> if err if Meteor.settings.ldap.debug console.log 'ERROR: ' + JSON.stringify(err) userFuture.return false return if !userObj if Meteor.settings.ldap.debug console.log 'User: ' + username + ' not found.' userFuture.return false else if Meteor.settings.ldap.debug console.log JSON.stringify(userObj) userFuture.return userObj userObj = userFuture.wait() if not userObj throw new (Meteor.Error)(403, 'Invalid username') @userObj = userObj authenticate: (password) -> authenticateFuture = new Future @ad.authenticate @userObj.dn, password, (err, auth) -> if err if Meteor.settings.ldap.debug console.log 'ERROR: ' + JSON.stringify(err) authenticateFuture.return false return if auth if Meteor.settings.ldap.debug console.log 'Authenticated!' authenticateFuture.return true else if Meteor.settings.ldap.debug console.log 'Authentication failed!' authenticateFuture.return false return success = authenticateFuture.wait() if not success or password == '' throw new (Meteor.Error)(403, 'Invalid credentials') @authenticated = success return success getGroupMembershipForUser: () -> groupsFuture = new Future @ad.getGroupMembershipForUser @userObj.dn, (err, groups) -> if err console.log('ERROR: ' +JSON.stringify(err)); groupsFuture.return false return if not groups console.log('User: ' + @userObj.dn + ' not found.') groupsFuture.return false else if Meteor.settings.ldap.debug console.log('Groups found for ' + @userObj.dn + ': '+ JSON.stringify(groups)) groupsFuture.return groups return return groupsFuture.wait() isUserMemberOf: (groupName) -> isMemberFuture = new Future @ad.isUserMemberOf @userObj.dn, groupName, (err, isMember) -> if err console.log 'ERROR: ' + JSON.stringify(err) isMemberFuture.return false return if Meteor.settings.ldap.debug console.log @userObj.displayName + ' isMemberOf ' + groupName + ': ' + isMember isMemberFuture.return isMember return return isMemberFuture.wait() queryMembershipAndAddToMeteor: (callback) -> for groupName in Meteor.settings.ldap.groupMembership ad = @ad userObj = @userObj do (groupName) -> ad.isUserMemberOf userObj.dn, groupName, (err, isMember) -> do (groupName) -> if err if Meteor.settings.ldap.debug console.log 'ERROR: ' + JSON.stringify(err) else if Meteor.settings.ldap.debug console.log userObj.dn + ' isMemberOf ' + groupName + ': ' + isMember callback(groupName,isMember) Accounts.registerLoginHandler 'ldap', (request) -> return undefined if !request.ldap # 1. create query user_query = new UserQuery(request.username) if Meteor.settings.ldap.debug console.log 'LDAP authentication for ' + request.username user_query.findUser() # Allows both sAMAccountName and email # 2. authenticate user authenticated = user_query.authenticate(request.pass) if Meteor.settings.ldap.debug console.log('* AUTHENTICATED:',authenticated) # 3. update database userId = undefined userObj = user_query.userObj userObj.username = request.username user = Meteor.users.findOne(dn: userObj.dn) if user userId = user._id Meteor.users.update userId, $set: userObj else userId = Meteor.users.insert(userObj) if Meteor.settings.ldap.autopublishFields Accounts.addAutopublishFields forLoggedInUser: Meteor.settings.ldap.autopublishFields forOtherUsers: Meteor.settings.ldap.autopublishFields stampedToken = Accounts._generateStampedLoginToken() hashStampedToken = Accounts._hashStampedToken(stampedToken) Meteor.users.update userId, $push: 'services.resume.loginTokens': hashStampedToken # 4. update membership of groups (asynchronously, as this can be really slow) user_query.queryMembershipAndAddToMeteor Meteor.bindEnvironment (groupName,isMember) -> if isMember Meteor.users.update userId, $addToSet: 'memberOf': groupName Meteor.users.update userId, $pull: 'notMemberOf': groupName else Meteor.users.update userId, $pull: 'memberOf': groupName Meteor.users.update userId, $addToSet: 'notMemberOf': groupName { userId: userId token: stampedToken.token tokenExpires: Accounts._tokenExpiration(hashStampedToken.when) }
true
ActiveDirectory = Npm.require('activedirectory'); Future = Npm.require('fibers/future') assert = Npm.require('assert') if !Meteor.settings.ldap throw new Error('"ldap" not found in Meteor.settings') class UserQuery constructor: (username) -> @ad = ActiveDirectory({ url: Meteor.settings.ldap.url, baseDN: Meteor.settings.ldap.baseDn, username: Meteor.settings.ldap.bindCn, password: PI:PASSWORD:<PASSWORD>END_PI.ldap.bindPassword attributes: { user: ["dn"].concat(Meteor.settings.ldap.autopublishFields), }, tlsOptions: Meteor.settings.ldap.tlsOptions || {} }); @username = @sanitize_for_search(username) sanitize_for_search: (s) -> # Escape search string for LDAP according to RFC4515 s = s.replace('\\', '\\5C') s = s.replace('\0', '\\00') s = s.replace('*','\\2A' ) s = s.replace('(','\\28' ) s = s.replace(')','\\29' ) return s findUser: () -> userFuture = new Future username = @username @ad.findUser @username, (err, userObj) -> if err if Meteor.settings.ldap.debug console.log 'ERROR: ' + JSON.stringify(err) userFuture.return false return if !userObj if Meteor.settings.ldap.debug console.log 'User: ' + username + ' not found.' userFuture.return false else if Meteor.settings.ldap.debug console.log JSON.stringify(userObj) userFuture.return userObj userObj = userFuture.wait() if not userObj throw new (Meteor.Error)(403, 'Invalid username') @userObj = userObj authenticate: (password) -> authenticateFuture = new Future @ad.authenticate @userObj.dn, password, (err, auth) -> if err if Meteor.settings.ldap.debug console.log 'ERROR: ' + JSON.stringify(err) authenticateFuture.return false return if auth if Meteor.settings.ldap.debug console.log 'Authenticated!' authenticateFuture.return true else if Meteor.settings.ldap.debug console.log 'Authentication failed!' authenticateFuture.return false return success = authenticateFuture.wait() if not success or password == '' throw new (Meteor.Error)(403, 'Invalid credentials') @authenticated = success return success getGroupMembershipForUser: () -> groupsFuture = new Future @ad.getGroupMembershipForUser @userObj.dn, (err, groups) -> if err console.log('ERROR: ' +JSON.stringify(err)); groupsFuture.return false return if not groups console.log('User: ' + @userObj.dn + ' not found.') groupsFuture.return false else if Meteor.settings.ldap.debug console.log('Groups found for ' + @userObj.dn + ': '+ JSON.stringify(groups)) groupsFuture.return groups return return groupsFuture.wait() isUserMemberOf: (groupName) -> isMemberFuture = new Future @ad.isUserMemberOf @userObj.dn, groupName, (err, isMember) -> if err console.log 'ERROR: ' + JSON.stringify(err) isMemberFuture.return false return if Meteor.settings.ldap.debug console.log @userObj.displayName + ' isMemberOf ' + groupName + ': ' + isMember isMemberFuture.return isMember return return isMemberFuture.wait() queryMembershipAndAddToMeteor: (callback) -> for groupName in Meteor.settings.ldap.groupMembership ad = @ad userObj = @userObj do (groupName) -> ad.isUserMemberOf userObj.dn, groupName, (err, isMember) -> do (groupName) -> if err if Meteor.settings.ldap.debug console.log 'ERROR: ' + JSON.stringify(err) else if Meteor.settings.ldap.debug console.log userObj.dn + ' isMemberOf ' + groupName + ': ' + isMember callback(groupName,isMember) Accounts.registerLoginHandler 'ldap', (request) -> return undefined if !request.ldap # 1. create query user_query = new UserQuery(request.username) if Meteor.settings.ldap.debug console.log 'LDAP authentication for ' + request.username user_query.findUser() # Allows both sAMAccountName and email # 2. authenticate user authenticated = user_query.authenticate(request.pass) if Meteor.settings.ldap.debug console.log('* AUTHENTICATED:',authenticated) # 3. update database userId = undefined userObj = user_query.userObj userObj.username = request.username user = Meteor.users.findOne(dn: userObj.dn) if user userId = user._id Meteor.users.update userId, $set: userObj else userId = Meteor.users.insert(userObj) if Meteor.settings.ldap.autopublishFields Accounts.addAutopublishFields forLoggedInUser: Meteor.settings.ldap.autopublishFields forOtherUsers: Meteor.settings.ldap.autopublishFields stampedToken = Accounts._generateStampedLoginToken() hashStampedToken = Accounts._hashStampedToken(stampedToken) Meteor.users.update userId, $push: 'services.resume.loginTokens': hashStampedToken # 4. update membership of groups (asynchronously, as this can be really slow) user_query.queryMembershipAndAddToMeteor Meteor.bindEnvironment (groupName,isMember) -> if isMember Meteor.users.update userId, $addToSet: 'memberOf': groupName Meteor.users.update userId, $pull: 'notMemberOf': groupName else Meteor.users.update userId, $pull: 'memberOf': groupName Meteor.users.update userId, $addToSet: 'notMemberOf': groupName { userId: userId token: stampedToken.token tokenExpires: Accounts._tokenExpiration(hashStampedToken.when) }
[ { "context": "\tcredentials =\n\t\temail: env.TEST_EMAIL\n\t\tpassword: env.TEST_PASSWORD\n\t\tusername: env.TEST_USERNAME\n\t\tpaid:\n\t\t\temail: e", "end": 1041, "score": 0.9303552508354187, "start": 1024, "tag": "PASSWORD", "value": "env.TEST_PASSWORD" }, { "context": "\t\tpaid:\n\t\t\temail: env.TEST_PAID_EMAIL\n\t\t\tpassword: env.TEST_PAID_PASSWORD\n\t\tregister:\n\t\t\temail: env.TEST_REGISTER_EMAIL\n\t\t\t", "end": 1145, "score": 0.994964063167572, "start": 1123, "tag": "PASSWORD", "value": "env.TEST_PAID_PASSWORD" }, { "context": "er:\n\t\t\temail: env.TEST_REGISTER_EMAIL\n\t\t\tpassword: env.TEST_REGISTER_PASSWORD\n\t\t\tusername: env.TEST_REGISTER_", "end": 1213, "score": 0.7701199650764465, "start": 1205, "tag": "PASSWORD", "value": "env.TEST" }, { "context": "n\n\t\t\temail: exports.credentials.email\n\t\t\tpassword: exports.credentials.password\n\t\t.then ->\n\t\t\treturn balena.request.send\n\t\t\t\tmeth", "end": 2267, "score": 0.9990422129631042, "start": 2239, "tag": "PASSWORD", "value": "exports.credentials.password" }, { "context": "n\n\t\t\temail: exports.credentials.email\n\t\t\tpassword: exports.credentials.password\n\t\t.then(exports.resetUser)\n\n\tafterFn = if beforeF", "end": 2769, "score": 0.9972877502441406, "start": 2741, "tag": "PASSWORD", "value": "exports.credentials.password" }, { "context": "exports.credentials.paid.email\n\t\tpassword: exports.credentials.paid.password\n\nresetApplications = ->\n\tbalena.pine.delete\n\t\tres", "end": 3027, "score": 0.9527989029884338, "start": 3002, "tag": "PASSWORD", "value": "credentials.paid.password" }, { "context": "reset in here as well\n\t\t# See: https://github.com/mochajs/mocha/issues/3740\n\t\tresetApplications()\n\t\t.then -", "end": 3281, "score": 0.9991632699966431, "start": 3274, "tag": "USERNAME", "value": "mochajs" }, { "context": "->\n\t\t\tbalena.models.application.create\n\t\t\t\tname: 'FooBar'\n\t\t\t\tapplicationType: 'microservices-starter'\n\t\t\t", "end": 3386, "score": 0.9745854139328003, "start": 3380, "tag": "NAME", "value": "FooBar" }, { "context": "reset in here as well\n\t\t# See: https://github.com/mochajs/mocha/issues/3740\n\t\tresetDevices()\n\t\t.then =>\n\t\t\t", "end": 3865, "score": 0.9991916418075562, "start": 3858, "tag": "USERNAME", "value": "mochajs" }, { "context": "cation: @application.id\n\t\t\t\t\t\tis_created_by__user: userId\n\t\t\t\t\t\tcommit: 'old-release-commit'\n\t\t\t\t\t\tstatus: ", "end": 6965, "score": 0.9570901393890381, "start": 6959, "tag": "USERNAME", "value": "userId" }, { "context": "cation: @application.id\n\t\t\t\t\t\tis_created_by__user: userId\n\t\t\t\t\t\tcommit: 'new-release-commit'\n\t\t\t\t\t\tstatus: ", "end": 7219, "score": 0.9801183938980103, "start": 7213, "tag": "USERNAME", "value": "userId" } ]
tests/integration/setup.coffee
josecoelho/balena-sdk
1
Promise = require('bluebird') _ = require('lodash') { chai } = require('mochainon') chai.use(require('chai-samsam')) exports.IS_BROWSER = IS_BROWSER = window? if IS_BROWSER require('js-polyfills/es6') getSdk = window.balenaSdk env = window.__env__ apiUrl = env.TEST_API_URL || 'https://api.balena-cloud.com' opts = apiUrl: apiUrl builderUrl: env.TEST_BUILDER_URL || apiUrl.replace('api.', 'builder.') else getSdk = require('../..') settings = require('balena-settings-client') env = process.env apiUrl = env.TEST_API_URL || settings.get('apiUrl') opts = apiUrl: apiUrl builderUrl: env.TEST_BUILDER_URL || apiUrl.replace('api.', 'builder.') dataDirectory: settings.get('dataDirectory') _.assign opts, apiKey: null isBrowser: IS_BROWSER, retries: 3 console.log("Running SDK tests against: #{opts.apiUrl}") console.log("TEST_USERNAME: #{env?.TEST_USERNAME}") buildCredentials = -> if not env throw new Error('Missing environment object?!') credentials = email: env.TEST_EMAIL password: env.TEST_PASSWORD username: env.TEST_USERNAME paid: email: env.TEST_PAID_EMAIL password: env.TEST_PAID_PASSWORD register: email: env.TEST_REGISTER_EMAIL password: env.TEST_REGISTER_PASSWORD username: env.TEST_REGISTER_USERNAME if not _.every [ credentials.email? credentials.password? credentials.username? credentials.register.email? credentials.register.password? credentials.register.username? ] throw new Error('Missing environment credentials') return credentials exports.getSdk = getSdk exports.sdkOpts = opts exports.balena = balena = getSdk(opts) exports.resetUser = -> return balena.auth.isLoggedIn().then (isLoggedIn) -> return if not isLoggedIn Promise.all [ balena.pine.delete resource: 'application' balena.pine.delete resource: 'user__has__public_key' balena.pine.delete resource: 'api_key' # only delete named user api keys options: $filter: name: $ne: null # Api keys can't delete api keys, just ignore failures here .catchReturn() ] exports.credentials = buildCredentials() exports.givenLoggedInUserWithApiKey = (beforeFn) -> beforeFn -> balena.auth.login email: exports.credentials.email password: exports.credentials.password .then -> return balena.request.send method: 'POST' url: '/api-key/user/full' baseUrl: opts.apiUrl body: name: 'apiKey' .get('body') .tap(balena.auth.logout) .then(balena.auth.loginWithToken) .then(exports.resetUser) afterFn = if beforeFn == beforeEach then afterEach else after afterFn -> exports.resetUser() exports.givenLoggedInUser = (beforeFn) -> beforeFn -> balena.auth.login email: exports.credentials.email password: exports.credentials.password .then(exports.resetUser) afterFn = if beforeFn == beforeEach then afterEach else after afterFn -> exports.resetUser() exports.loginPaidUser = -> balena.auth.login email: exports.credentials.paid.email password: exports.credentials.paid.password resetApplications = -> balena.pine.delete resource: 'application' exports.givenAnApplication = (beforeFn) -> beforeFn -> # calling this.skip() doesn't trigger afterEach, # so we need to reset in here as well # See: https://github.com/mochajs/mocha/issues/3740 resetApplications() .then -> balena.models.application.create name: 'FooBar' applicationType: 'microservices-starter' deviceType: 'raspberry-pi' .then (application) => @application = application afterFn = if beforeFn == beforeEach then afterEach else after afterFn resetApplications resetDevices = -> balena.pine.delete resource: 'device' exports.givenADevice = (beforeFn, extraDeviceProps) -> beforeFn -> # calling this.skip() doesn't trigger afterEach, # so we need to reset in here as well # See: https://github.com/mochajs/mocha/issues/3740 resetDevices() .then => uuid = balena.models.device.generateUniqueKey() balena.models.device.register(@application.app_name, uuid) .tap (deviceInfo) => if !@currentRelease || !@currentRelease.commit return balena.pine.patch resource: 'device' body: is_on__commit: @currentRelease.commit options: $filter: uuid: deviceInfo.uuid .tap (deviceInfo) -> if !extraDeviceProps return balena.pine.patch resource: 'device' body: extraDeviceProps options: $filter: uuid: deviceInfo.uuid .then (deviceInfo) -> balena.models.device.get(deviceInfo.uuid) .then (device) => @device = device .tap (device) => if !@currentRelease || !@currentRelease.commit return Promise.all [ # Create image installs for the images on the device balena.pine.post resource: 'image_install' body: installs__image: @oldWebImage.id is_provided_by__release: @oldRelease.id device: device.id download_progress: 100 status: 'running' install_date: '2017-10-01' , balena.pine.post resource: 'image_install' body: installs__image: @newWebImage.id is_provided_by__release: @currentRelease.id device: device.id download_progress: 50, status: 'downloading' install_date: '2017-10-30' , balena.pine.post resource: 'image_install' body: installs__image: @oldDbImage.id is_provided_by__release: @oldRelease.id device: device.id download_progress: 100, status: 'deleted', install_date: '2017-09-30' , balena.pine.post resource: 'image_install' body: installs__image: @newDbImage.id is_provided_by__release: @currentRelease.id device: device.id download_progress: 100, status: 'running', install_date: '2017-10-30' ] .spread (oldWebInstall, newWebInstall, oldDbInstall, newDbInstall) => @oldWebInstall = oldWebInstall @newWebInstall = newWebInstall @newDbInstall = newDbInstall afterFn = if beforeFn == beforeEach then afterEach else after afterFn resetDevices exports.givenAnApplicationWithADevice = (beforeFn) -> exports.givenAnApplication(beforeFn) exports.givenADevice(beforeFn) exports.givenMulticontainerApplicationWithADevice = (beforeFn) -> exports.givenMulticontainerApplication(beforeFn) exports.givenADevice(beforeFn) exports.givenMulticontainerApplication = (beforeFn) -> exports.givenAnApplication(beforeFn) beforeFn -> Promise.try => userId = @application.user.__id Promise.all [ # Register web & DB services balena.pine.post resource: 'service' body: application: @application.id service_name: 'web' , balena.pine.post resource: 'service' body: application: @application.id service_name: 'db' , # Register an old & new release of this application Promise.mapSeries [ resource: 'release' body: belongs_to__application: @application.id is_created_by__user: userId commit: 'old-release-commit' status: 'success' source: 'cloud' composition: {} start_timestamp: 1234 , resource: 'release' body: belongs_to__application: @application.id is_created_by__user: userId commit: 'new-release-commit' status: 'success' source: 'cloud' composition: {} start_timestamp: 54321 ], (pineParams) -> balena.pine.post pineParams ] .spread (webService, dbService, [oldRelease, newRelease]) => @webService = webService @dbService = dbService @oldRelease = oldRelease @currentRelease = newRelease Promise.all [ # Register an old & new web image build from the old and new # releases, a db build in the new release only balena.pine.post resource: 'image' body: is_a_build_of__service: webService.id project_type: 'dockerfile' content_hash: 'abc' build_log: 'old web log' start_timestamp: 1234 push_timestamp: 1234 status: 'success' , balena.pine.post resource: 'image' body: is_a_build_of__service: webService.id project_type: 'dockerfile' content_hash: 'def' build_log: 'new web log' start_timestamp: 54321 push_timestamp: 54321 status: 'success' , balena.pine.post resource: 'image' body: is_a_build_of__service: dbService.id project_type: 'dockerfile' content_hash: 'jkl' build_log: 'old db log' start_timestamp: 123 push_timestamp: 123 status: 'success' , balena.pine.post resource: 'image' body: is_a_build_of__service: dbService.id project_type: 'dockerfile' content_hash: 'ghi' build_log: 'new db log' start_timestamp: 54321 push_timestamp: 54321 status: 'success' ] .spread (oldWebImage, newWebImage, oldDbImage, newDbImage) => @oldWebImage = oldWebImage @newWebImage = newWebImage @oldDbImage = oldDbImage @newDbImage = newDbImage Promise.all [ # Tie the images to their corresponding releases balena.pine.post resource: 'image__is_part_of__release' body: image: oldWebImage.id is_part_of__release: oldRelease.id , balena.pine.post resource: 'image__is_part_of__release' body: image: oldDbImage.id is_part_of__release: oldRelease.id , balena.pine.post resource: 'image__is_part_of__release' body: image: newWebImage.id is_part_of__release: newRelease.id , balena.pine.post resource: 'image__is_part_of__release' body: image: newDbImage.id is_part_of__release: newRelease.id , ] afterFn = if beforeFn == beforeEach then afterEach else after afterFn -> @currentRelease = null
158566
Promise = require('bluebird') _ = require('lodash') { chai } = require('mochainon') chai.use(require('chai-samsam')) exports.IS_BROWSER = IS_BROWSER = window? if IS_BROWSER require('js-polyfills/es6') getSdk = window.balenaSdk env = window.__env__ apiUrl = env.TEST_API_URL || 'https://api.balena-cloud.com' opts = apiUrl: apiUrl builderUrl: env.TEST_BUILDER_URL || apiUrl.replace('api.', 'builder.') else getSdk = require('../..') settings = require('balena-settings-client') env = process.env apiUrl = env.TEST_API_URL || settings.get('apiUrl') opts = apiUrl: apiUrl builderUrl: env.TEST_BUILDER_URL || apiUrl.replace('api.', 'builder.') dataDirectory: settings.get('dataDirectory') _.assign opts, apiKey: null isBrowser: IS_BROWSER, retries: 3 console.log("Running SDK tests against: #{opts.apiUrl}") console.log("TEST_USERNAME: #{env?.TEST_USERNAME}") buildCredentials = -> if not env throw new Error('Missing environment object?!') credentials = email: env.TEST_EMAIL password: <PASSWORD> username: env.TEST_USERNAME paid: email: env.TEST_PAID_EMAIL password: <PASSWORD> register: email: env.TEST_REGISTER_EMAIL password: <PASSWORD>_REGISTER_PASSWORD username: env.TEST_REGISTER_USERNAME if not _.every [ credentials.email? credentials.password? credentials.username? credentials.register.email? credentials.register.password? credentials.register.username? ] throw new Error('Missing environment credentials') return credentials exports.getSdk = getSdk exports.sdkOpts = opts exports.balena = balena = getSdk(opts) exports.resetUser = -> return balena.auth.isLoggedIn().then (isLoggedIn) -> return if not isLoggedIn Promise.all [ balena.pine.delete resource: 'application' balena.pine.delete resource: 'user__has__public_key' balena.pine.delete resource: 'api_key' # only delete named user api keys options: $filter: name: $ne: null # Api keys can't delete api keys, just ignore failures here .catchReturn() ] exports.credentials = buildCredentials() exports.givenLoggedInUserWithApiKey = (beforeFn) -> beforeFn -> balena.auth.login email: exports.credentials.email password: <PASSWORD> .then -> return balena.request.send method: 'POST' url: '/api-key/user/full' baseUrl: opts.apiUrl body: name: 'apiKey' .get('body') .tap(balena.auth.logout) .then(balena.auth.loginWithToken) .then(exports.resetUser) afterFn = if beforeFn == beforeEach then afterEach else after afterFn -> exports.resetUser() exports.givenLoggedInUser = (beforeFn) -> beforeFn -> balena.auth.login email: exports.credentials.email password: <PASSWORD> .then(exports.resetUser) afterFn = if beforeFn == beforeEach then afterEach else after afterFn -> exports.resetUser() exports.loginPaidUser = -> balena.auth.login email: exports.credentials.paid.email password: exports.<PASSWORD> resetApplications = -> balena.pine.delete resource: 'application' exports.givenAnApplication = (beforeFn) -> beforeFn -> # calling this.skip() doesn't trigger afterEach, # so we need to reset in here as well # See: https://github.com/mochajs/mocha/issues/3740 resetApplications() .then -> balena.models.application.create name: '<NAME>' applicationType: 'microservices-starter' deviceType: 'raspberry-pi' .then (application) => @application = application afterFn = if beforeFn == beforeEach then afterEach else after afterFn resetApplications resetDevices = -> balena.pine.delete resource: 'device' exports.givenADevice = (beforeFn, extraDeviceProps) -> beforeFn -> # calling this.skip() doesn't trigger afterEach, # so we need to reset in here as well # See: https://github.com/mochajs/mocha/issues/3740 resetDevices() .then => uuid = balena.models.device.generateUniqueKey() balena.models.device.register(@application.app_name, uuid) .tap (deviceInfo) => if !@currentRelease || !@currentRelease.commit return balena.pine.patch resource: 'device' body: is_on__commit: @currentRelease.commit options: $filter: uuid: deviceInfo.uuid .tap (deviceInfo) -> if !extraDeviceProps return balena.pine.patch resource: 'device' body: extraDeviceProps options: $filter: uuid: deviceInfo.uuid .then (deviceInfo) -> balena.models.device.get(deviceInfo.uuid) .then (device) => @device = device .tap (device) => if !@currentRelease || !@currentRelease.commit return Promise.all [ # Create image installs for the images on the device balena.pine.post resource: 'image_install' body: installs__image: @oldWebImage.id is_provided_by__release: @oldRelease.id device: device.id download_progress: 100 status: 'running' install_date: '2017-10-01' , balena.pine.post resource: 'image_install' body: installs__image: @newWebImage.id is_provided_by__release: @currentRelease.id device: device.id download_progress: 50, status: 'downloading' install_date: '2017-10-30' , balena.pine.post resource: 'image_install' body: installs__image: @oldDbImage.id is_provided_by__release: @oldRelease.id device: device.id download_progress: 100, status: 'deleted', install_date: '2017-09-30' , balena.pine.post resource: 'image_install' body: installs__image: @newDbImage.id is_provided_by__release: @currentRelease.id device: device.id download_progress: 100, status: 'running', install_date: '2017-10-30' ] .spread (oldWebInstall, newWebInstall, oldDbInstall, newDbInstall) => @oldWebInstall = oldWebInstall @newWebInstall = newWebInstall @newDbInstall = newDbInstall afterFn = if beforeFn == beforeEach then afterEach else after afterFn resetDevices exports.givenAnApplicationWithADevice = (beforeFn) -> exports.givenAnApplication(beforeFn) exports.givenADevice(beforeFn) exports.givenMulticontainerApplicationWithADevice = (beforeFn) -> exports.givenMulticontainerApplication(beforeFn) exports.givenADevice(beforeFn) exports.givenMulticontainerApplication = (beforeFn) -> exports.givenAnApplication(beforeFn) beforeFn -> Promise.try => userId = @application.user.__id Promise.all [ # Register web & DB services balena.pine.post resource: 'service' body: application: @application.id service_name: 'web' , balena.pine.post resource: 'service' body: application: @application.id service_name: 'db' , # Register an old & new release of this application Promise.mapSeries [ resource: 'release' body: belongs_to__application: @application.id is_created_by__user: userId commit: 'old-release-commit' status: 'success' source: 'cloud' composition: {} start_timestamp: 1234 , resource: 'release' body: belongs_to__application: @application.id is_created_by__user: userId commit: 'new-release-commit' status: 'success' source: 'cloud' composition: {} start_timestamp: 54321 ], (pineParams) -> balena.pine.post pineParams ] .spread (webService, dbService, [oldRelease, newRelease]) => @webService = webService @dbService = dbService @oldRelease = oldRelease @currentRelease = newRelease Promise.all [ # Register an old & new web image build from the old and new # releases, a db build in the new release only balena.pine.post resource: 'image' body: is_a_build_of__service: webService.id project_type: 'dockerfile' content_hash: 'abc' build_log: 'old web log' start_timestamp: 1234 push_timestamp: 1234 status: 'success' , balena.pine.post resource: 'image' body: is_a_build_of__service: webService.id project_type: 'dockerfile' content_hash: 'def' build_log: 'new web log' start_timestamp: 54321 push_timestamp: 54321 status: 'success' , balena.pine.post resource: 'image' body: is_a_build_of__service: dbService.id project_type: 'dockerfile' content_hash: 'jkl' build_log: 'old db log' start_timestamp: 123 push_timestamp: 123 status: 'success' , balena.pine.post resource: 'image' body: is_a_build_of__service: dbService.id project_type: 'dockerfile' content_hash: 'ghi' build_log: 'new db log' start_timestamp: 54321 push_timestamp: 54321 status: 'success' ] .spread (oldWebImage, newWebImage, oldDbImage, newDbImage) => @oldWebImage = oldWebImage @newWebImage = newWebImage @oldDbImage = oldDbImage @newDbImage = newDbImage Promise.all [ # Tie the images to their corresponding releases balena.pine.post resource: 'image__is_part_of__release' body: image: oldWebImage.id is_part_of__release: oldRelease.id , balena.pine.post resource: 'image__is_part_of__release' body: image: oldDbImage.id is_part_of__release: oldRelease.id , balena.pine.post resource: 'image__is_part_of__release' body: image: newWebImage.id is_part_of__release: newRelease.id , balena.pine.post resource: 'image__is_part_of__release' body: image: newDbImage.id is_part_of__release: newRelease.id , ] afterFn = if beforeFn == beforeEach then afterEach else after afterFn -> @currentRelease = null
true
Promise = require('bluebird') _ = require('lodash') { chai } = require('mochainon') chai.use(require('chai-samsam')) exports.IS_BROWSER = IS_BROWSER = window? if IS_BROWSER require('js-polyfills/es6') getSdk = window.balenaSdk env = window.__env__ apiUrl = env.TEST_API_URL || 'https://api.balena-cloud.com' opts = apiUrl: apiUrl builderUrl: env.TEST_BUILDER_URL || apiUrl.replace('api.', 'builder.') else getSdk = require('../..') settings = require('balena-settings-client') env = process.env apiUrl = env.TEST_API_URL || settings.get('apiUrl') opts = apiUrl: apiUrl builderUrl: env.TEST_BUILDER_URL || apiUrl.replace('api.', 'builder.') dataDirectory: settings.get('dataDirectory') _.assign opts, apiKey: null isBrowser: IS_BROWSER, retries: 3 console.log("Running SDK tests against: #{opts.apiUrl}") console.log("TEST_USERNAME: #{env?.TEST_USERNAME}") buildCredentials = -> if not env throw new Error('Missing environment object?!') credentials = email: env.TEST_EMAIL password: PI:PASSWORD:<PASSWORD>END_PI username: env.TEST_USERNAME paid: email: env.TEST_PAID_EMAIL password: PI:PASSWORD:<PASSWORD>END_PI register: email: env.TEST_REGISTER_EMAIL password: PI:PASSWORD:<PASSWORD>END_PI_REGISTER_PASSWORD username: env.TEST_REGISTER_USERNAME if not _.every [ credentials.email? credentials.password? credentials.username? credentials.register.email? credentials.register.password? credentials.register.username? ] throw new Error('Missing environment credentials') return credentials exports.getSdk = getSdk exports.sdkOpts = opts exports.balena = balena = getSdk(opts) exports.resetUser = -> return balena.auth.isLoggedIn().then (isLoggedIn) -> return if not isLoggedIn Promise.all [ balena.pine.delete resource: 'application' balena.pine.delete resource: 'user__has__public_key' balena.pine.delete resource: 'api_key' # only delete named user api keys options: $filter: name: $ne: null # Api keys can't delete api keys, just ignore failures here .catchReturn() ] exports.credentials = buildCredentials() exports.givenLoggedInUserWithApiKey = (beforeFn) -> beforeFn -> balena.auth.login email: exports.credentials.email password: PI:PASSWORD:<PASSWORD>END_PI .then -> return balena.request.send method: 'POST' url: '/api-key/user/full' baseUrl: opts.apiUrl body: name: 'apiKey' .get('body') .tap(balena.auth.logout) .then(balena.auth.loginWithToken) .then(exports.resetUser) afterFn = if beforeFn == beforeEach then afterEach else after afterFn -> exports.resetUser() exports.givenLoggedInUser = (beforeFn) -> beforeFn -> balena.auth.login email: exports.credentials.email password: PI:PASSWORD:<PASSWORD>END_PI .then(exports.resetUser) afterFn = if beforeFn == beforeEach then afterEach else after afterFn -> exports.resetUser() exports.loginPaidUser = -> balena.auth.login email: exports.credentials.paid.email password: exports.PI:PASSWORD:<PASSWORD>END_PI resetApplications = -> balena.pine.delete resource: 'application' exports.givenAnApplication = (beforeFn) -> beforeFn -> # calling this.skip() doesn't trigger afterEach, # so we need to reset in here as well # See: https://github.com/mochajs/mocha/issues/3740 resetApplications() .then -> balena.models.application.create name: 'PI:NAME:<NAME>END_PI' applicationType: 'microservices-starter' deviceType: 'raspberry-pi' .then (application) => @application = application afterFn = if beforeFn == beforeEach then afterEach else after afterFn resetApplications resetDevices = -> balena.pine.delete resource: 'device' exports.givenADevice = (beforeFn, extraDeviceProps) -> beforeFn -> # calling this.skip() doesn't trigger afterEach, # so we need to reset in here as well # See: https://github.com/mochajs/mocha/issues/3740 resetDevices() .then => uuid = balena.models.device.generateUniqueKey() balena.models.device.register(@application.app_name, uuid) .tap (deviceInfo) => if !@currentRelease || !@currentRelease.commit return balena.pine.patch resource: 'device' body: is_on__commit: @currentRelease.commit options: $filter: uuid: deviceInfo.uuid .tap (deviceInfo) -> if !extraDeviceProps return balena.pine.patch resource: 'device' body: extraDeviceProps options: $filter: uuid: deviceInfo.uuid .then (deviceInfo) -> balena.models.device.get(deviceInfo.uuid) .then (device) => @device = device .tap (device) => if !@currentRelease || !@currentRelease.commit return Promise.all [ # Create image installs for the images on the device balena.pine.post resource: 'image_install' body: installs__image: @oldWebImage.id is_provided_by__release: @oldRelease.id device: device.id download_progress: 100 status: 'running' install_date: '2017-10-01' , balena.pine.post resource: 'image_install' body: installs__image: @newWebImage.id is_provided_by__release: @currentRelease.id device: device.id download_progress: 50, status: 'downloading' install_date: '2017-10-30' , balena.pine.post resource: 'image_install' body: installs__image: @oldDbImage.id is_provided_by__release: @oldRelease.id device: device.id download_progress: 100, status: 'deleted', install_date: '2017-09-30' , balena.pine.post resource: 'image_install' body: installs__image: @newDbImage.id is_provided_by__release: @currentRelease.id device: device.id download_progress: 100, status: 'running', install_date: '2017-10-30' ] .spread (oldWebInstall, newWebInstall, oldDbInstall, newDbInstall) => @oldWebInstall = oldWebInstall @newWebInstall = newWebInstall @newDbInstall = newDbInstall afterFn = if beforeFn == beforeEach then afterEach else after afterFn resetDevices exports.givenAnApplicationWithADevice = (beforeFn) -> exports.givenAnApplication(beforeFn) exports.givenADevice(beforeFn) exports.givenMulticontainerApplicationWithADevice = (beforeFn) -> exports.givenMulticontainerApplication(beforeFn) exports.givenADevice(beforeFn) exports.givenMulticontainerApplication = (beforeFn) -> exports.givenAnApplication(beforeFn) beforeFn -> Promise.try => userId = @application.user.__id Promise.all [ # Register web & DB services balena.pine.post resource: 'service' body: application: @application.id service_name: 'web' , balena.pine.post resource: 'service' body: application: @application.id service_name: 'db' , # Register an old & new release of this application Promise.mapSeries [ resource: 'release' body: belongs_to__application: @application.id is_created_by__user: userId commit: 'old-release-commit' status: 'success' source: 'cloud' composition: {} start_timestamp: 1234 , resource: 'release' body: belongs_to__application: @application.id is_created_by__user: userId commit: 'new-release-commit' status: 'success' source: 'cloud' composition: {} start_timestamp: 54321 ], (pineParams) -> balena.pine.post pineParams ] .spread (webService, dbService, [oldRelease, newRelease]) => @webService = webService @dbService = dbService @oldRelease = oldRelease @currentRelease = newRelease Promise.all [ # Register an old & new web image build from the old and new # releases, a db build in the new release only balena.pine.post resource: 'image' body: is_a_build_of__service: webService.id project_type: 'dockerfile' content_hash: 'abc' build_log: 'old web log' start_timestamp: 1234 push_timestamp: 1234 status: 'success' , balena.pine.post resource: 'image' body: is_a_build_of__service: webService.id project_type: 'dockerfile' content_hash: 'def' build_log: 'new web log' start_timestamp: 54321 push_timestamp: 54321 status: 'success' , balena.pine.post resource: 'image' body: is_a_build_of__service: dbService.id project_type: 'dockerfile' content_hash: 'jkl' build_log: 'old db log' start_timestamp: 123 push_timestamp: 123 status: 'success' , balena.pine.post resource: 'image' body: is_a_build_of__service: dbService.id project_type: 'dockerfile' content_hash: 'ghi' build_log: 'new db log' start_timestamp: 54321 push_timestamp: 54321 status: 'success' ] .spread (oldWebImage, newWebImage, oldDbImage, newDbImage) => @oldWebImage = oldWebImage @newWebImage = newWebImage @oldDbImage = oldDbImage @newDbImage = newDbImage Promise.all [ # Tie the images to their corresponding releases balena.pine.post resource: 'image__is_part_of__release' body: image: oldWebImage.id is_part_of__release: oldRelease.id , balena.pine.post resource: 'image__is_part_of__release' body: image: oldDbImage.id is_part_of__release: oldRelease.id , balena.pine.post resource: 'image__is_part_of__release' body: image: newWebImage.id is_part_of__release: newRelease.id , balena.pine.post resource: 'image__is_part_of__release' body: image: newDbImage.id is_part_of__release: newRelease.id , ] afterFn = if beforeFn == beforeEach then afterEach else after afterFn -> @currentRelease = null
[ { "context": "#!\n# api.prabhatkumar.org® [v0.0.1]\n# @author : Prabhat Kumar [http://prabhatkumar.org/]\n# @copyright : Prabhat", "end": 66, "score": 0.9998878240585327, "start": 53, "tag": "NAME", "value": "Prabhat Kumar" }, { "context": "at Kumar [http://prabhatkumar.org/]\n# @copyright : Prabhat Kumar [http://prabhatkumar.org/]\n###\n\n\n\n### ", "end": 111, "score": 0.6569446921348572, "start": 109, "tag": "NAME", "value": "Pr" }, { "context": " = config.accounts[i]\n if account.username == username and account.password == password\n return d", "end": 962, "score": 0.9969209432601929, "start": 954, "tag": "USERNAME", "value": "username" }, { "context": "count.username == username and account.password == password\n return done(null, account)\n i++\n do", "end": 995, "score": 0.9983071088790894, "start": 987, "tag": "PASSWORD", "value": "password" } ]
source/API/code/assets/coffee/app.coffee
iammachine/prabhatkumar.org
1
###! # api.prabhatkumar.org® [v0.0.1] # @author : Prabhat Kumar [http://prabhatkumar.org/] # @copyright : Prabhat Kumar [http://prabhatkumar.org/] ### ### @Invoking strict mode ### 'use strict' ### API server for api.prabhatkumar.org/ ### http = require('http') https = require('https') fs = require('fs') express = require('express') passport = require('passport') BasicStrategy = require('passport-http').BasicStrategy forceSSL = require('express-force-ssl') bodyParser = require('body-parser') ### API Server Options. ### options = key: fs.readFileSync('keys/api.key') cert: fs.readFileSync('keys/api_prabhatkumar_org.crt') app = express() module.exports = app app.set 'config', require('./config') # @passport.use passport.use new BasicStrategy((username, password, done) -> config = app.get('config') if config.accounts i = 0 while i < config.accounts.length account = config.accounts[i] if account.username == username and account.password == password return done(null, account) i++ done null, false ) # See:- http://blog.cloudflare.com/introducing-universal-ssl/ app.use (req, res, next) -> host = req.headers.host if host.slice(0, 4) != 'api.' return res.redirect('http://' + host + req.originalUrl) next() return app.use forceSSL app.use passport.initialize() app.use bodyParser.urlencoded(extended: true) require './routes/repository' require './routes/status' app.use '/axis', axis # https.createServer(options, app).listen(443);
3013
###! # api.prabhatkumar.org® [v0.0.1] # @author : <NAME> [http://prabhatkumar.org/] # @copyright : <NAME>abhat Kumar [http://prabhatkumar.org/] ### ### @Invoking strict mode ### 'use strict' ### API server for api.prabhatkumar.org/ ### http = require('http') https = require('https') fs = require('fs') express = require('express') passport = require('passport') BasicStrategy = require('passport-http').BasicStrategy forceSSL = require('express-force-ssl') bodyParser = require('body-parser') ### API Server Options. ### options = key: fs.readFileSync('keys/api.key') cert: fs.readFileSync('keys/api_prabhatkumar_org.crt') app = express() module.exports = app app.set 'config', require('./config') # @passport.use passport.use new BasicStrategy((username, password, done) -> config = app.get('config') if config.accounts i = 0 while i < config.accounts.length account = config.accounts[i] if account.username == username and account.password == <PASSWORD> return done(null, account) i++ done null, false ) # See:- http://blog.cloudflare.com/introducing-universal-ssl/ app.use (req, res, next) -> host = req.headers.host if host.slice(0, 4) != 'api.' return res.redirect('http://' + host + req.originalUrl) next() return app.use forceSSL app.use passport.initialize() app.use bodyParser.urlencoded(extended: true) require './routes/repository' require './routes/status' app.use '/axis', axis # https.createServer(options, app).listen(443);
true
###! # api.prabhatkumar.org® [v0.0.1] # @author : PI:NAME:<NAME>END_PI [http://prabhatkumar.org/] # @copyright : PI:NAME:<NAME>END_PIabhat Kumar [http://prabhatkumar.org/] ### ### @Invoking strict mode ### 'use strict' ### API server for api.prabhatkumar.org/ ### http = require('http') https = require('https') fs = require('fs') express = require('express') passport = require('passport') BasicStrategy = require('passport-http').BasicStrategy forceSSL = require('express-force-ssl') bodyParser = require('body-parser') ### API Server Options. ### options = key: fs.readFileSync('keys/api.key') cert: fs.readFileSync('keys/api_prabhatkumar_org.crt') app = express() module.exports = app app.set 'config', require('./config') # @passport.use passport.use new BasicStrategy((username, password, done) -> config = app.get('config') if config.accounts i = 0 while i < config.accounts.length account = config.accounts[i] if account.username == username and account.password == PI:PASSWORD:<PASSWORD>END_PI return done(null, account) i++ done null, false ) # See:- http://blog.cloudflare.com/introducing-universal-ssl/ app.use (req, res, next) -> host = req.headers.host if host.slice(0, 4) != 'api.' return res.redirect('http://' + host + req.originalUrl) next() return app.use forceSSL app.use passport.initialize() app.use bodyParser.urlencoded(extended: true) require './routes/repository' require './routes/status' app.use '/axis', axis # https.createServer(options, app).listen(443);
[ { "context": " @mail.parse('holaAThotmail.com').should.eql('hola@hotmail.com')\n\n it 'when DOT is before the AT', ->\n @", "end": 1018, "score": 0.9989503026008606, "start": 1002, "tag": "EMAIL", "value": "hola@hotmail.com" }, { "context": "rse('email emailATdomainDOTcom').should.eql('email email@domain.com')\n\n it 'when two string when the first contain", "end": 1301, "score": 0.9630880355834961, "start": 1285, "tag": "EMAIL", "value": "email@domain.com" }, { "context": "ng holaATholaDOTcom').should.eql('holaAT something hola@hola.com')\n\n it 'when replace when email have a point i", "end": 1648, "score": 0.996071994304657, "start": 1635, "tag": "EMAIL", "value": "hola@hola.com" }, { "context": " @mail.parse('holaAThotmailDOTcom').should.eql('hola@hotmail.com')\n @mail.parse('holaDOTkikoATdomainDOTcom').", "end": 1787, "score": 0.9999037384986877, "start": 1771, "tag": "EMAIL", "value": "hola@hotmail.com" }, { "context": "il.parse('holaDOTkikoATdomainDOTcom').should.eql('hola.kiko@domain.com')\n\n it 'when replace when email use a more tha", "end": 1869, "score": 0.9998888373374939, "start": 1849, "tag": "EMAIL", "value": "hola.kiko@domain.com" }, { "context": "il.parse('holaDOTkikoATdomainDOTcom').should.eql('hola.kiko@domain.com')\n @mail.parse('hol@DOTkikoATdomainDOTcom').", "end": 2031, "score": 0.999872088432312, "start": 2011, "tag": "EMAIL", "value": "hola.kiko@domain.com" }, { "context": "ld.eql('hola.kiko@domain.com')\n @mail.parse('hol@DOTkikoATdomainDOTcom').should.eql('hol@.kiko@domain.com')\n", "end": 2078, "score": 0.9994298219680786, "start": 2053, "tag": "EMAIL", "value": "hol@DOTkikoATdomainDOTcom" }, { "context": "il.parse('hol@DOTkikoATdomainDOTcom').should.eql('hol@.kiko@domain.com')\n", "end": 2113, "score": 0.9997849464416504, "start": 2093, "tag": "EMAIL", "value": "hol@.kiko@domain.com" } ]
test/test.coffee
Kikobeats/kata_email
0
### Dependencies ### MailNormalizer = require '../' should = require 'should' ### Test ### describe 'MailNormalizer :: ', -> before -> @mail = new MailNormalizer() describe 'helpers', -> it 'count number of character in a string', -> @mail._countNumberOfCharacter('hola.que.tal', '.').should.eql(2) it 'replace all ocurrences of a character', -> @mail._replaceAll('holaDOTqueDOTtal', 'DOT', '.').should.eql('hola.que.tal') describe 'parse', -> it 'when the same word if doesnt contains a valid email', -> @mail.parse('hola').should.eql('hola') it 'when the same word if the string is AT', -> @mail.parse('AT').should.eql('AT') it 'when the same word if the string is DOT', -> @mail.parse('DOT').should.eql('DOT') it 'when AT between two words is not a valid email', -> @mail.parse('holaAThola').should.eql('holaAThola') it 'when AT in a valid email', -> @mail.parse('holaAThotmail.com').should.eql('hola@hotmail.com') it 'when DOT is before the AT', -> @mail.parse('holaDOTcom').should.eql('holaDOTcom') @mail.parse('ATholaDOTcom').should.eql('ATholaDOTcom') it 'when the mail in a prhrase', -> @mail.parse('email emailATdomainDOTcom').should.eql('email email@domain.com') it 'when two string when the first contain AT and the second string content a DOT', -> @mail.parse('holaAThola holaDOThola').should.eql('holaAThola holaDOThola') it 'when three different strings and the last one is an email', -> @mail.parse('holaAT something holaATholaDOTcom').should.eql('holaAT something hola@hola.com') it 'when replace when email have a point in the address', -> @mail.parse('holaAThotmailDOTcom').should.eql('hola@hotmail.com') @mail.parse('holaDOTkikoATdomainDOTcom').should.eql('hola.kiko@domain.com') it 'when replace when email use a more than one point in the address', -> @mail.parse('holaDOTkikoATdomainDOTcom').should.eql('hola.kiko@domain.com') @mail.parse('hol@DOTkikoATdomainDOTcom').should.eql('hol@.kiko@domain.com')
116043
### Dependencies ### MailNormalizer = require '../' should = require 'should' ### Test ### describe 'MailNormalizer :: ', -> before -> @mail = new MailNormalizer() describe 'helpers', -> it 'count number of character in a string', -> @mail._countNumberOfCharacter('hola.que.tal', '.').should.eql(2) it 'replace all ocurrences of a character', -> @mail._replaceAll('holaDOTqueDOTtal', 'DOT', '.').should.eql('hola.que.tal') describe 'parse', -> it 'when the same word if doesnt contains a valid email', -> @mail.parse('hola').should.eql('hola') it 'when the same word if the string is AT', -> @mail.parse('AT').should.eql('AT') it 'when the same word if the string is DOT', -> @mail.parse('DOT').should.eql('DOT') it 'when AT between two words is not a valid email', -> @mail.parse('holaAThola').should.eql('holaAThola') it 'when AT in a valid email', -> @mail.parse('holaAThotmail.com').should.eql('<EMAIL>') it 'when DOT is before the AT', -> @mail.parse('holaDOTcom').should.eql('holaDOTcom') @mail.parse('ATholaDOTcom').should.eql('ATholaDOTcom') it 'when the mail in a prhrase', -> @mail.parse('email emailATdomainDOTcom').should.eql('email <EMAIL>') it 'when two string when the first contain AT and the second string content a DOT', -> @mail.parse('holaAThola holaDOThola').should.eql('holaAThola holaDOThola') it 'when three different strings and the last one is an email', -> @mail.parse('holaAT something holaATholaDOTcom').should.eql('holaAT something <EMAIL>') it 'when replace when email have a point in the address', -> @mail.parse('holaAThotmailDOTcom').should.eql('<EMAIL>') @mail.parse('holaDOTkikoATdomainDOTcom').should.eql('<EMAIL>') it 'when replace when email use a more than one point in the address', -> @mail.parse('holaDOTkikoATdomainDOTcom').should.eql('<EMAIL>') @mail.parse('<EMAIL>').should.eql('<EMAIL>')
true
### Dependencies ### MailNormalizer = require '../' should = require 'should' ### Test ### describe 'MailNormalizer :: ', -> before -> @mail = new MailNormalizer() describe 'helpers', -> it 'count number of character in a string', -> @mail._countNumberOfCharacter('hola.que.tal', '.').should.eql(2) it 'replace all ocurrences of a character', -> @mail._replaceAll('holaDOTqueDOTtal', 'DOT', '.').should.eql('hola.que.tal') describe 'parse', -> it 'when the same word if doesnt contains a valid email', -> @mail.parse('hola').should.eql('hola') it 'when the same word if the string is AT', -> @mail.parse('AT').should.eql('AT') it 'when the same word if the string is DOT', -> @mail.parse('DOT').should.eql('DOT') it 'when AT between two words is not a valid email', -> @mail.parse('holaAThola').should.eql('holaAThola') it 'when AT in a valid email', -> @mail.parse('holaAThotmail.com').should.eql('PI:EMAIL:<EMAIL>END_PI') it 'when DOT is before the AT', -> @mail.parse('holaDOTcom').should.eql('holaDOTcom') @mail.parse('ATholaDOTcom').should.eql('ATholaDOTcom') it 'when the mail in a prhrase', -> @mail.parse('email emailATdomainDOTcom').should.eql('email PI:EMAIL:<EMAIL>END_PI') it 'when two string when the first contain AT and the second string content a DOT', -> @mail.parse('holaAThola holaDOThola').should.eql('holaAThola holaDOThola') it 'when three different strings and the last one is an email', -> @mail.parse('holaAT something holaATholaDOTcom').should.eql('holaAT something PI:EMAIL:<EMAIL>END_PI') it 'when replace when email have a point in the address', -> @mail.parse('holaAThotmailDOTcom').should.eql('PI:EMAIL:<EMAIL>END_PI') @mail.parse('holaDOTkikoATdomainDOTcom').should.eql('PI:EMAIL:<EMAIL>END_PI') it 'when replace when email use a more than one point in the address', -> @mail.parse('holaDOTkikoATdomainDOTcom').should.eql('PI:EMAIL:<EMAIL>END_PI') @mail.parse('PI:EMAIL:<EMAIL>END_PI').should.eql('PI:EMAIL:<EMAIL>END_PI')
[ { "context": "tle : title\n body : body\n author : author\n siteName: @config.siteName\n siteURL : ", "end": 15098, "score": 0.5072568655014038, "start": 15092, "tag": "NAME", "value": "author" } ]
server.coffee
iizukanao/bitter
4
fs = require 'fs' path = require 'path' http = require 'http' events = require 'events' ejs = require 'ejs' marked = require 'marked' compression = require 'compression' responseTime = require 'response-time' express = require 'express' # Markdown formatting options marked.setOptions gfm : true tables : true breaks : true pedantic : false sanitize : false smartLists: true langPrefix: 'lang-' class BitterServer extends events.EventEmitter constructor: (opts) -> @constructorOpts = opts # Base directory of entries @basedir = opts?.basedir ? path.normalize "#{process.cwd()}/notes" # Port to listen (default is 1341) @port = opts?.port ? process.env.PORT ? 1341 # Path to config.json @configFilename = opts?.configFilename ? "#{@basedir}/config/config.json" # EJS template for formatting pages @pageTemplateFilename = "#{@basedir}/config/page.ejs" # Existence of this file means that # the index is needed to be generated again. @reindexCheckFilename = "#{@basedir}/reindex-needed" # config.json is loaded to this variable @config = null # Object for storing index @recentInfo = {} # EJS Template for each page @pageTemplate = null # Ensure config.json exists if not fs.existsSync @configFilename console.log "Error: #{@configFilename} does not exist" process.exit 1 err = @loadConfig() if err? process.exit 1 @app = express() @httpServer = http.createServer @app # Log requests #@app.use express.logger() # gzip/deflate response @app.use compression() # Add X-Response-Time to response header @app.use responseTime() # Serve static files in #{@basedir}/public @app.use express.static "#{@basedir}/public" # Single entry (e.g. /2013/05/26/how_i_learned_javascript) @app.get /^\/(\d{4})\/(\d{2})\/(\d+)(-\d+)?\/(.*)$/, (req, res, next) => year = req.params[0] month = req.params[1] date = req.params[2] part = req.params[3] ? '' slug = req.params[4] datepart = date + part filepath = "#{@basedir}/#{year}/#{month}/#{datepart}-#{slug}.md" fs.exists filepath, (exists) => if not exists # Find static file that matches URL staticPath = "#{@basedir}/#{year}/#{month}/#{slug}" fs.stat staticPath, (err, stats) => if err @respondWithNotFound res else if stats.isDirectory() next() # Will match the next route else res.sendFile staticPath return fs.readFile filepath, {encoding:'utf8'}, (err, markdown) => if err @logMessage err @respondWithServerError res return @formatPage { markdown: markdown link : "/#{year}/#{month}/#{datepart}/#{slug}" year : year month : month date : date }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html # Redirect /2013/05/27/ to /2013/05/ (after matching against the previous route) @app.get /^\/(\d{4})\/(\d{2})\/[\d-]+\/?/, (req, res) -> year = req.params[0] month = req.params[1] res.redirect "/#{year}/#{month}/" # List of years @app.get '/archives', (req, res) => years = @listYears() markdown = """ ## Archives """ for year in years markdown += "[#{year}](/#{year}/)\n" @formatPage { markdown : markdown noTitleLink: true noAuthor : true }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html # Archives for a year (e.g. /2013/) @app.get /^\/(\d{4})\/?$/, (req, res) => year = req.params[0] try months = @listMonths year catch e @respondWithNotFound res return markdown = """ ## Archives for #{year} """ for month in months markdown += "[#{year}-#{month}](/#{year}/#{month}/)\n" @formatPage { markdown : markdown noTitleLink: true noAuthor : true }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html # Archives for a month (e.g. /2013/05/) @app.get /^\/(\d{4})\/(\d{2})\/?$/, (req, res) => year = req.params[0] month = req.params[1] try files = @listEntries year, month catch e @respondWithNotFound res return markdown = """ ## Archives for [#{year}](/#{year}/)-#{month} """ for file in files match = /^(\d+)(-\d+)?-(.*)\.md$/.exec file date = match[1] part = match[2] ? '' slug = match[3] datepart = date + part filepath = "#{@basedir}/#{year}/#{month}/#{file}" content = fs.readFileSync filepath, {encoding:'utf8'} lex = marked.Lexer.lex(content) title = @findTitleFromLex(lex) ? '' markdown += "#{@formatDate year, month, date} " + \ "[#{title or '(untitled)'}](/#{year}/#{month}/#{datepart}/#{slug})\n" @formatPage { markdown : markdown title : "Archives for #{year}-#{month}" noTitleLink: true noAuthor : true }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html # Recent entries @app.get '/recents', (req, res) => numRecents = @config.numRecents ? @recentInfo.recentFiles.length markdown = """ ## Recent Entries """ for file in @recentInfo.recentFiles[...numRecents] entryUrl = "/#{file.year}/#{file.month}/#{file.datepart}/#{file.slug}" ymd = @formatDate file.year, file.month, file.date markdown += "#{ymd} [#{file.title or '(untitled)'}](#{entryUrl})\n" markdown += "\n\n[Archives](/archives)" @formatPage { markdown : markdown noTitleLink: true noAuthor : true }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html # Atom feed @app.get '/index.atom', (req, res) => buf = """ <?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <title>#{@config.siteName}</title> <link href="#{@config.siteURL}/index.atom" rel="self" /> <link href="#{@config.siteURL}" /> <id>#{@escapeTags @config.siteURL + '/'}</id> <updated>#{new Date(@recentInfo.generatedTime).toISOString()}</updated> """ numRecents = @config.numRecents ? @recentInfo.recentFiles.length for file in @recentInfo.recentFiles[...numRecents] html = @convertToAbsoluteLinks file.body, { year : file.year month : file.month date : file.date absoluteURL: true } entryUrl = "#{@config.siteURL}/#{file.year}/#{file.month}/#{file.datepart}/#{file.slug}" title = file.title if (not title?) or (title is '') title = '(untitled)' buf += """ <entry> <title>#{@escapeTags title}</title> <link href="#{entryUrl}" /> <id>#{entryUrl}</id> <updated>#{new Date(file.time).toISOString()}</updated> <content type="html">#{@escapeTags html}</content> <author> <name>#{@escapeTags @config.authorName}</name> <uri>#{@escapeTags @config.authorLink}</uri> """ if @config.authorEmail buf += " <email>#{@config.authorEmail}</email>" buf += """ </author> </entry> """ buf += "\n</feed>\n" res.set 'Content-Type', 'text/xml; charset=utf-8' res.send buf # Homepage @app.get '/', (req, res) => if @config.homepage is 'recents' @serveRecents req, res else @serveMostRecentEntry req, res # Not found @app.get '*', (req, res) => @respondWithNotFound res # Log unhandled errors @app.use (err, req, res, next) -> console.error err.stack next err if opts?.autoStart @start() start: (callback) -> if fs.existsSync @reindexCheckFilename fs.unlink @reindexCheckFilename # Watch reindex-needed to be created fs.watchFile @reindexCheckFilename, (curr, prev) => if curr.nlink > 0 fs.unlink @reindexCheckFilename, => @createIndex() @emit 'updateIndex' # Watch config.json to be updated fs.watchFile @configFilename, (curr, prev) => err = @loadConfig() if not err? @logMessage "loaded #{path.basename @configFilename}" @createIndex() # Load page template and watch it for change @pageTemplate = fs.readFileSync @pageTemplateFilename, {encoding:'utf8'} fs.watchFile @pageTemplateFilename, (curr, prev) => fs.readFile @pageTemplateFilename, {encoding:'utf8'}, (err, data) => if err @logMessage "#{@pageTemplateFilename} read error: #{err}" return @pageTemplate = data @logMessage "loaded #{path.basename @pageTemplateFilename}" @createIndex() @httpServer.listen @port @httpServer.on 'listening', => @logMessage "Server started on port #{@httpServer.address().port}" stop: -> fs.unwatchFile @reindexCheckFilename fs.unwatchFile @configFilename fs.unwatchFile @pageTemplateFilename @httpServer.close => @logMessage "Server closed" # Log message to stdout logMessage: (str, opts) -> if @constructorOpts?.quiet return buf = '' if not opts?.noTime d = new Date buf += "[#{d.toDateString()} #{d.toLocaleTimeString()}] " buf += str if not opts?.noNewline buf += "\n" process.stdout.write buf monthNames: [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] formatDate: (year, month, date) -> "#{@monthNames[month-1]} #{parseInt date}, #{year}" # Obfuscate email address obfuscateEmail: (str) -> buf = '' for i in [0...str.length] buf += "&##{str.charCodeAt i};" buf # Escape HTML/XML tags escapeTags: (str) -> str.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') # Load config.json loadConfig: -> try @config = JSON.parse fs.readFileSync @configFilename catch e @logMessage "#{@configFilename} read error: #{e}" return e @config.siteURL = @config.siteURL.replace /\/$/, '' @config.authorEmail = @obfuscateEmail @config.authorEmail null # no error # 500 Server Error respondWithServerError: (res) -> markdown = """ ## Server Error Please try again later. """ @formatPage {markdown:markdown, noTitleLink:true, noAuthor:true}, (err, html) => if err @logMessage err res.status(500).send('Server error') return res.set 'Content-Type', 'text/html; charset=utf-8' res.status(500).send(html) # 404 Not Found respondWithNotFound: (res) -> markdown = """ ## Not Found The requested document was not found. """ @formatPage {markdown:markdown, noTitleLink:true, noAuthor:true}, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.status(404).send(html) # Find first heading from lex object findTitleFromLex: (lex) -> for component in lex if component.type is 'heading' return component.text null # not found # Convert links in HTML to absolute URL # html (string): HTML # params: { # year (string): entry's year # month (string): entry's month # date (string): entry's date # absoluteURL (boolean): If true, prepend @config.siteURL # If false, start with / # } convertToAbsoluteLinks: (html, params) -> html = html.replace /(<a href|<img src)="(.*?)"/g, (match, p1, p2) => p2 = p2.replace /^\.\.\/(?!\.\.)/g, "/#{params.year}/#{params.month}/" p2 = p2.replace /^\.\.\/\.\.\/(?!\.\.)/g, "/#{params.year}/" p2 = p2.replace /^\.\.\/\.\.\/\.\.\/(?!\.\.)/g, "/" if p2.indexOf('://') is -1 if p2[0] isnt '/' p2 = "/#{params.year}/#{params.month}/#{params.date}/#{p2}" if params.absoluteURL p2 = "#{@config.siteURL}#{p2}" "#{p1}=\"#{p2}\"" html # Format Markdown content into HTML formatPage: (input, callback) -> lex = marked.Lexer.lex(input.markdown) # Title title = input.title ? null if not title? lexTitle = @findTitleFromLex lex if lexTitle? title = lexTitle if not title? title = '(untitled)' body = marked.Parser.parse(lex) # Convert relative links to absolute if input.absolutePath or input.absoluteURL body = @convertToAbsoluteLinks body, input # Date if input.year? and input.month? and input.date? buf = "<div class=\"date\">" if not input.noTitleLink buf += "<a href=\"#{input.link}\">" buf += "#{@formatDate input.year, input.month, input.date}" if not input.noTitleLink buf += "</a>" buf += "</div>\n" body = buf + body # Author author = undefined if not input.noAuthor author = "<div class=\"author\">Posted by " + \ "<a href=\"#{@config.authorLink}\">#{@config.authorName}</a>" if @config.authorEmail author += " &lt;<a href=\"mailto:#{@config.authorEmail}\">" + \ "#{@config.authorEmail}</a>&gt;" author += "</div>" # Link title if not input.noTitleLink body = body.replace /<(h\d)([^>]*)>(.*?)<\/\1>/, \ "<$1$2><a href=\"#{input.link}\">$3</a></$1>" # Create anchors for headings if input.anchorHeading isnt false headingCount = -1 body = body.replace /<(h\d)([^>]*)>(.*?)<\/\1>/g, (match, p1, p2, p3) -> if ++headingCount > 0 "<#{p1}#{p2} class=\"anchor\" id=\"heading_#{headingCount}\">" + \ "<a href=\"#heading_#{headingCount}\">#{p3}</a></#{p1}>" else match body = body.replace /<(h\d)([^>]*)>/, "<$1$2 class=\"title\">" body = body.replace /(<h\d) id="[^"]*"/g, '$1' # Object to be passed to template opts = title : title body : body author : author siteName: @config.siteName siteURL : @config.siteURL if input.noTitle opts.title = undefined # Apply page.ejs to page contents html = ejs.render @pageTemplate, opts callback null, html # List all years listYears: -> years = fs.readdirSync @basedir years = (year for year in years when /\d{4}/.test year) years.sort (a, b) -> b - a years # List all months for the given year listMonths: (year) -> months = fs.readdirSync "#{@basedir}/#{year}" months = (month for month in months when /\d{2}/.test month) months.sort (a, b) -> b - a months # List all entries for the given year/month listEntries: (year, month) -> files = fs.readdirSync "#{@basedir}/#{year}/#{month}" files = (file for file in files when /\.md$/.test file) files.sort (a, b) -> intA = parseInt a intB = parseInt b cmp = intB - intA if cmp is 0 subintA = 0 subintB = 0 if (match = /^\d+-(\d+)-/.exec a)? subintA = parseInt match[1] if (match = /^\d+-(\d+)-/.exec b)? subintB = parseInt match[1] cmp = subintB - subintA if cmp is 0 cmp = b.localeCompare a cmp files # Scan entries and update index createIndex: (numRecents) -> if not numRecents? numRecents = @config.numRecents ? 15 if @config.numHomepageRecents? numRecents = Math.max @config.numHomepageRecents, numRecents @logMessage "indexing...", noNewline:true startTime = new Date().getTime() count = 0 recentFiles = [] years = @listYears() for year in years break if count >= numRecents months = @listMonths year for month in months break if count >= numRecents files = @listEntries year, month for file in files match = /^(\d+)(-\d+)?-(.*)\.md$/.exec file if not match? continue filepath = "#{@basedir}/#{year}/#{month}/#{file}" markdown = fs.readFileSync filepath, {encoding:'utf8'} lex = marked.Lexer.lex(markdown) title = @findTitleFromLex(lex) ? '' body = marked.Parser.parse(lex) date = match[1] part = match[2] ? '' slug = match[3] recentFiles.push time : new Date("#{year}-#{month}-#{date} 00:00:00").getTime() title : title body : body year : year month : month date : date part : part datepart: date + part slug : slug if ++count >= numRecents break # Hold index in recentInfo @recentInfo = recentFiles: recentFiles generatedTime: new Date().getTime() elapsedTime = new Date().getTime() - startTime @logMessage "done (#{elapsedTime} ms)", noTime:true # Serve homepage in recents style serveRecents: (req, res) -> numRecents = @config.numHomepageRecents ? @config.numRecents ? 5 markdown = '' for file in @recentInfo.recentFiles[...numRecents] entryUrl = "/#{file.year}/#{file.month}/#{file.datepart}/#{file.slug}" markdown += "[#{file.title or '(untitled)'}](#{entryUrl})\n" @formatPage { markdown : markdown noTitleLink: true noAuthor : true noTitle : true }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html # Show the most recent entry on homepage serveMostRecentEntry: (req, res) -> file = @recentInfo.recentFiles[0] if not file? res.set 'Content-Type', 'text/plain; charset=utf-8' # Empty content message res.send """ This is the place where your content will appear. Add a first entry like this: mkdir -p 2013/05 echo "# Test\\n\\nHello World" > 2013/05/27-test.md git add . git commit -m "add test entry" git push origin master Finished? Then reload this page slowly. """ return filepath = "#{@basedir}/#{file.year}/#{file.month}/#{file.datepart}-#{file.slug}.md" fs.readFile filepath, {encoding:'utf8'}, (err, markdown) => if err @logMessage err @respondWithServerError res return url = "/#{file.year}/#{file.month}/#{file.datepart}/#{file.slug}" @formatPage { markdown : markdown link : url year : file.year month : file.month date : file.date noTitle : true absolutePath: true }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html module.exports = BitterServer if not module.parent? # This script is being run directly new BitterServer autoStart:true
152919
fs = require 'fs' path = require 'path' http = require 'http' events = require 'events' ejs = require 'ejs' marked = require 'marked' compression = require 'compression' responseTime = require 'response-time' express = require 'express' # Markdown formatting options marked.setOptions gfm : true tables : true breaks : true pedantic : false sanitize : false smartLists: true langPrefix: 'lang-' class BitterServer extends events.EventEmitter constructor: (opts) -> @constructorOpts = opts # Base directory of entries @basedir = opts?.basedir ? path.normalize "#{process.cwd()}/notes" # Port to listen (default is 1341) @port = opts?.port ? process.env.PORT ? 1341 # Path to config.json @configFilename = opts?.configFilename ? "#{@basedir}/config/config.json" # EJS template for formatting pages @pageTemplateFilename = "#{@basedir}/config/page.ejs" # Existence of this file means that # the index is needed to be generated again. @reindexCheckFilename = "#{@basedir}/reindex-needed" # config.json is loaded to this variable @config = null # Object for storing index @recentInfo = {} # EJS Template for each page @pageTemplate = null # Ensure config.json exists if not fs.existsSync @configFilename console.log "Error: #{@configFilename} does not exist" process.exit 1 err = @loadConfig() if err? process.exit 1 @app = express() @httpServer = http.createServer @app # Log requests #@app.use express.logger() # gzip/deflate response @app.use compression() # Add X-Response-Time to response header @app.use responseTime() # Serve static files in #{@basedir}/public @app.use express.static "#{@basedir}/public" # Single entry (e.g. /2013/05/26/how_i_learned_javascript) @app.get /^\/(\d{4})\/(\d{2})\/(\d+)(-\d+)?\/(.*)$/, (req, res, next) => year = req.params[0] month = req.params[1] date = req.params[2] part = req.params[3] ? '' slug = req.params[4] datepart = date + part filepath = "#{@basedir}/#{year}/#{month}/#{datepart}-#{slug}.md" fs.exists filepath, (exists) => if not exists # Find static file that matches URL staticPath = "#{@basedir}/#{year}/#{month}/#{slug}" fs.stat staticPath, (err, stats) => if err @respondWithNotFound res else if stats.isDirectory() next() # Will match the next route else res.sendFile staticPath return fs.readFile filepath, {encoding:'utf8'}, (err, markdown) => if err @logMessage err @respondWithServerError res return @formatPage { markdown: markdown link : "/#{year}/#{month}/#{datepart}/#{slug}" year : year month : month date : date }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html # Redirect /2013/05/27/ to /2013/05/ (after matching against the previous route) @app.get /^\/(\d{4})\/(\d{2})\/[\d-]+\/?/, (req, res) -> year = req.params[0] month = req.params[1] res.redirect "/#{year}/#{month}/" # List of years @app.get '/archives', (req, res) => years = @listYears() markdown = """ ## Archives """ for year in years markdown += "[#{year}](/#{year}/)\n" @formatPage { markdown : markdown noTitleLink: true noAuthor : true }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html # Archives for a year (e.g. /2013/) @app.get /^\/(\d{4})\/?$/, (req, res) => year = req.params[0] try months = @listMonths year catch e @respondWithNotFound res return markdown = """ ## Archives for #{year} """ for month in months markdown += "[#{year}-#{month}](/#{year}/#{month}/)\n" @formatPage { markdown : markdown noTitleLink: true noAuthor : true }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html # Archives for a month (e.g. /2013/05/) @app.get /^\/(\d{4})\/(\d{2})\/?$/, (req, res) => year = req.params[0] month = req.params[1] try files = @listEntries year, month catch e @respondWithNotFound res return markdown = """ ## Archives for [#{year}](/#{year}/)-#{month} """ for file in files match = /^(\d+)(-\d+)?-(.*)\.md$/.exec file date = match[1] part = match[2] ? '' slug = match[3] datepart = date + part filepath = "#{@basedir}/#{year}/#{month}/#{file}" content = fs.readFileSync filepath, {encoding:'utf8'} lex = marked.Lexer.lex(content) title = @findTitleFromLex(lex) ? '' markdown += "#{@formatDate year, month, date} " + \ "[#{title or '(untitled)'}](/#{year}/#{month}/#{datepart}/#{slug})\n" @formatPage { markdown : markdown title : "Archives for #{year}-#{month}" noTitleLink: true noAuthor : true }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html # Recent entries @app.get '/recents', (req, res) => numRecents = @config.numRecents ? @recentInfo.recentFiles.length markdown = """ ## Recent Entries """ for file in @recentInfo.recentFiles[...numRecents] entryUrl = "/#{file.year}/#{file.month}/#{file.datepart}/#{file.slug}" ymd = @formatDate file.year, file.month, file.date markdown += "#{ymd} [#{file.title or '(untitled)'}](#{entryUrl})\n" markdown += "\n\n[Archives](/archives)" @formatPage { markdown : markdown noTitleLink: true noAuthor : true }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html # Atom feed @app.get '/index.atom', (req, res) => buf = """ <?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <title>#{@config.siteName}</title> <link href="#{@config.siteURL}/index.atom" rel="self" /> <link href="#{@config.siteURL}" /> <id>#{@escapeTags @config.siteURL + '/'}</id> <updated>#{new Date(@recentInfo.generatedTime).toISOString()}</updated> """ numRecents = @config.numRecents ? @recentInfo.recentFiles.length for file in @recentInfo.recentFiles[...numRecents] html = @convertToAbsoluteLinks file.body, { year : file.year month : file.month date : file.date absoluteURL: true } entryUrl = "#{@config.siteURL}/#{file.year}/#{file.month}/#{file.datepart}/#{file.slug}" title = file.title if (not title?) or (title is '') title = '(untitled)' buf += """ <entry> <title>#{@escapeTags title}</title> <link href="#{entryUrl}" /> <id>#{entryUrl}</id> <updated>#{new Date(file.time).toISOString()}</updated> <content type="html">#{@escapeTags html}</content> <author> <name>#{@escapeTags @config.authorName}</name> <uri>#{@escapeTags @config.authorLink}</uri> """ if @config.authorEmail buf += " <email>#{@config.authorEmail}</email>" buf += """ </author> </entry> """ buf += "\n</feed>\n" res.set 'Content-Type', 'text/xml; charset=utf-8' res.send buf # Homepage @app.get '/', (req, res) => if @config.homepage is 'recents' @serveRecents req, res else @serveMostRecentEntry req, res # Not found @app.get '*', (req, res) => @respondWithNotFound res # Log unhandled errors @app.use (err, req, res, next) -> console.error err.stack next err if opts?.autoStart @start() start: (callback) -> if fs.existsSync @reindexCheckFilename fs.unlink @reindexCheckFilename # Watch reindex-needed to be created fs.watchFile @reindexCheckFilename, (curr, prev) => if curr.nlink > 0 fs.unlink @reindexCheckFilename, => @createIndex() @emit 'updateIndex' # Watch config.json to be updated fs.watchFile @configFilename, (curr, prev) => err = @loadConfig() if not err? @logMessage "loaded #{path.basename @configFilename}" @createIndex() # Load page template and watch it for change @pageTemplate = fs.readFileSync @pageTemplateFilename, {encoding:'utf8'} fs.watchFile @pageTemplateFilename, (curr, prev) => fs.readFile @pageTemplateFilename, {encoding:'utf8'}, (err, data) => if err @logMessage "#{@pageTemplateFilename} read error: #{err}" return @pageTemplate = data @logMessage "loaded #{path.basename @pageTemplateFilename}" @createIndex() @httpServer.listen @port @httpServer.on 'listening', => @logMessage "Server started on port #{@httpServer.address().port}" stop: -> fs.unwatchFile @reindexCheckFilename fs.unwatchFile @configFilename fs.unwatchFile @pageTemplateFilename @httpServer.close => @logMessage "Server closed" # Log message to stdout logMessage: (str, opts) -> if @constructorOpts?.quiet return buf = '' if not opts?.noTime d = new Date buf += "[#{d.toDateString()} #{d.toLocaleTimeString()}] " buf += str if not opts?.noNewline buf += "\n" process.stdout.write buf monthNames: [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] formatDate: (year, month, date) -> "#{@monthNames[month-1]} #{parseInt date}, #{year}" # Obfuscate email address obfuscateEmail: (str) -> buf = '' for i in [0...str.length] buf += "&##{str.charCodeAt i};" buf # Escape HTML/XML tags escapeTags: (str) -> str.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') # Load config.json loadConfig: -> try @config = JSON.parse fs.readFileSync @configFilename catch e @logMessage "#{@configFilename} read error: #{e}" return e @config.siteURL = @config.siteURL.replace /\/$/, '' @config.authorEmail = @obfuscateEmail @config.authorEmail null # no error # 500 Server Error respondWithServerError: (res) -> markdown = """ ## Server Error Please try again later. """ @formatPage {markdown:markdown, noTitleLink:true, noAuthor:true}, (err, html) => if err @logMessage err res.status(500).send('Server error') return res.set 'Content-Type', 'text/html; charset=utf-8' res.status(500).send(html) # 404 Not Found respondWithNotFound: (res) -> markdown = """ ## Not Found The requested document was not found. """ @formatPage {markdown:markdown, noTitleLink:true, noAuthor:true}, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.status(404).send(html) # Find first heading from lex object findTitleFromLex: (lex) -> for component in lex if component.type is 'heading' return component.text null # not found # Convert links in HTML to absolute URL # html (string): HTML # params: { # year (string): entry's year # month (string): entry's month # date (string): entry's date # absoluteURL (boolean): If true, prepend @config.siteURL # If false, start with / # } convertToAbsoluteLinks: (html, params) -> html = html.replace /(<a href|<img src)="(.*?)"/g, (match, p1, p2) => p2 = p2.replace /^\.\.\/(?!\.\.)/g, "/#{params.year}/#{params.month}/" p2 = p2.replace /^\.\.\/\.\.\/(?!\.\.)/g, "/#{params.year}/" p2 = p2.replace /^\.\.\/\.\.\/\.\.\/(?!\.\.)/g, "/" if p2.indexOf('://') is -1 if p2[0] isnt '/' p2 = "/#{params.year}/#{params.month}/#{params.date}/#{p2}" if params.absoluteURL p2 = "#{@config.siteURL}#{p2}" "#{p1}=\"#{p2}\"" html # Format Markdown content into HTML formatPage: (input, callback) -> lex = marked.Lexer.lex(input.markdown) # Title title = input.title ? null if not title? lexTitle = @findTitleFromLex lex if lexTitle? title = lexTitle if not title? title = '(untitled)' body = marked.Parser.parse(lex) # Convert relative links to absolute if input.absolutePath or input.absoluteURL body = @convertToAbsoluteLinks body, input # Date if input.year? and input.month? and input.date? buf = "<div class=\"date\">" if not input.noTitleLink buf += "<a href=\"#{input.link}\">" buf += "#{@formatDate input.year, input.month, input.date}" if not input.noTitleLink buf += "</a>" buf += "</div>\n" body = buf + body # Author author = undefined if not input.noAuthor author = "<div class=\"author\">Posted by " + \ "<a href=\"#{@config.authorLink}\">#{@config.authorName}</a>" if @config.authorEmail author += " &lt;<a href=\"mailto:#{@config.authorEmail}\">" + \ "#{@config.authorEmail}</a>&gt;" author += "</div>" # Link title if not input.noTitleLink body = body.replace /<(h\d)([^>]*)>(.*?)<\/\1>/, \ "<$1$2><a href=\"#{input.link}\">$3</a></$1>" # Create anchors for headings if input.anchorHeading isnt false headingCount = -1 body = body.replace /<(h\d)([^>]*)>(.*?)<\/\1>/g, (match, p1, p2, p3) -> if ++headingCount > 0 "<#{p1}#{p2} class=\"anchor\" id=\"heading_#{headingCount}\">" + \ "<a href=\"#heading_#{headingCount}\">#{p3}</a></#{p1}>" else match body = body.replace /<(h\d)([^>]*)>/, "<$1$2 class=\"title\">" body = body.replace /(<h\d) id="[^"]*"/g, '$1' # Object to be passed to template opts = title : title body : body author : <NAME> siteName: @config.siteName siteURL : @config.siteURL if input.noTitle opts.title = undefined # Apply page.ejs to page contents html = ejs.render @pageTemplate, opts callback null, html # List all years listYears: -> years = fs.readdirSync @basedir years = (year for year in years when /\d{4}/.test year) years.sort (a, b) -> b - a years # List all months for the given year listMonths: (year) -> months = fs.readdirSync "#{@basedir}/#{year}" months = (month for month in months when /\d{2}/.test month) months.sort (a, b) -> b - a months # List all entries for the given year/month listEntries: (year, month) -> files = fs.readdirSync "#{@basedir}/#{year}/#{month}" files = (file for file in files when /\.md$/.test file) files.sort (a, b) -> intA = parseInt a intB = parseInt b cmp = intB - intA if cmp is 0 subintA = 0 subintB = 0 if (match = /^\d+-(\d+)-/.exec a)? subintA = parseInt match[1] if (match = /^\d+-(\d+)-/.exec b)? subintB = parseInt match[1] cmp = subintB - subintA if cmp is 0 cmp = b.localeCompare a cmp files # Scan entries and update index createIndex: (numRecents) -> if not numRecents? numRecents = @config.numRecents ? 15 if @config.numHomepageRecents? numRecents = Math.max @config.numHomepageRecents, numRecents @logMessage "indexing...", noNewline:true startTime = new Date().getTime() count = 0 recentFiles = [] years = @listYears() for year in years break if count >= numRecents months = @listMonths year for month in months break if count >= numRecents files = @listEntries year, month for file in files match = /^(\d+)(-\d+)?-(.*)\.md$/.exec file if not match? continue filepath = "#{@basedir}/#{year}/#{month}/#{file}" markdown = fs.readFileSync filepath, {encoding:'utf8'} lex = marked.Lexer.lex(markdown) title = @findTitleFromLex(lex) ? '' body = marked.Parser.parse(lex) date = match[1] part = match[2] ? '' slug = match[3] recentFiles.push time : new Date("#{year}-#{month}-#{date} 00:00:00").getTime() title : title body : body year : year month : month date : date part : part datepart: date + part slug : slug if ++count >= numRecents break # Hold index in recentInfo @recentInfo = recentFiles: recentFiles generatedTime: new Date().getTime() elapsedTime = new Date().getTime() - startTime @logMessage "done (#{elapsedTime} ms)", noTime:true # Serve homepage in recents style serveRecents: (req, res) -> numRecents = @config.numHomepageRecents ? @config.numRecents ? 5 markdown = '' for file in @recentInfo.recentFiles[...numRecents] entryUrl = "/#{file.year}/#{file.month}/#{file.datepart}/#{file.slug}" markdown += "[#{file.title or '(untitled)'}](#{entryUrl})\n" @formatPage { markdown : markdown noTitleLink: true noAuthor : true noTitle : true }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html # Show the most recent entry on homepage serveMostRecentEntry: (req, res) -> file = @recentInfo.recentFiles[0] if not file? res.set 'Content-Type', 'text/plain; charset=utf-8' # Empty content message res.send """ This is the place where your content will appear. Add a first entry like this: mkdir -p 2013/05 echo "# Test\\n\\nHello World" > 2013/05/27-test.md git add . git commit -m "add test entry" git push origin master Finished? Then reload this page slowly. """ return filepath = "#{@basedir}/#{file.year}/#{file.month}/#{file.datepart}-#{file.slug}.md" fs.readFile filepath, {encoding:'utf8'}, (err, markdown) => if err @logMessage err @respondWithServerError res return url = "/#{file.year}/#{file.month}/#{file.datepart}/#{file.slug}" @formatPage { markdown : markdown link : url year : file.year month : file.month date : file.date noTitle : true absolutePath: true }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html module.exports = BitterServer if not module.parent? # This script is being run directly new BitterServer autoStart:true
true
fs = require 'fs' path = require 'path' http = require 'http' events = require 'events' ejs = require 'ejs' marked = require 'marked' compression = require 'compression' responseTime = require 'response-time' express = require 'express' # Markdown formatting options marked.setOptions gfm : true tables : true breaks : true pedantic : false sanitize : false smartLists: true langPrefix: 'lang-' class BitterServer extends events.EventEmitter constructor: (opts) -> @constructorOpts = opts # Base directory of entries @basedir = opts?.basedir ? path.normalize "#{process.cwd()}/notes" # Port to listen (default is 1341) @port = opts?.port ? process.env.PORT ? 1341 # Path to config.json @configFilename = opts?.configFilename ? "#{@basedir}/config/config.json" # EJS template for formatting pages @pageTemplateFilename = "#{@basedir}/config/page.ejs" # Existence of this file means that # the index is needed to be generated again. @reindexCheckFilename = "#{@basedir}/reindex-needed" # config.json is loaded to this variable @config = null # Object for storing index @recentInfo = {} # EJS Template for each page @pageTemplate = null # Ensure config.json exists if not fs.existsSync @configFilename console.log "Error: #{@configFilename} does not exist" process.exit 1 err = @loadConfig() if err? process.exit 1 @app = express() @httpServer = http.createServer @app # Log requests #@app.use express.logger() # gzip/deflate response @app.use compression() # Add X-Response-Time to response header @app.use responseTime() # Serve static files in #{@basedir}/public @app.use express.static "#{@basedir}/public" # Single entry (e.g. /2013/05/26/how_i_learned_javascript) @app.get /^\/(\d{4})\/(\d{2})\/(\d+)(-\d+)?\/(.*)$/, (req, res, next) => year = req.params[0] month = req.params[1] date = req.params[2] part = req.params[3] ? '' slug = req.params[4] datepart = date + part filepath = "#{@basedir}/#{year}/#{month}/#{datepart}-#{slug}.md" fs.exists filepath, (exists) => if not exists # Find static file that matches URL staticPath = "#{@basedir}/#{year}/#{month}/#{slug}" fs.stat staticPath, (err, stats) => if err @respondWithNotFound res else if stats.isDirectory() next() # Will match the next route else res.sendFile staticPath return fs.readFile filepath, {encoding:'utf8'}, (err, markdown) => if err @logMessage err @respondWithServerError res return @formatPage { markdown: markdown link : "/#{year}/#{month}/#{datepart}/#{slug}" year : year month : month date : date }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html # Redirect /2013/05/27/ to /2013/05/ (after matching against the previous route) @app.get /^\/(\d{4})\/(\d{2})\/[\d-]+\/?/, (req, res) -> year = req.params[0] month = req.params[1] res.redirect "/#{year}/#{month}/" # List of years @app.get '/archives', (req, res) => years = @listYears() markdown = """ ## Archives """ for year in years markdown += "[#{year}](/#{year}/)\n" @formatPage { markdown : markdown noTitleLink: true noAuthor : true }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html # Archives for a year (e.g. /2013/) @app.get /^\/(\d{4})\/?$/, (req, res) => year = req.params[0] try months = @listMonths year catch e @respondWithNotFound res return markdown = """ ## Archives for #{year} """ for month in months markdown += "[#{year}-#{month}](/#{year}/#{month}/)\n" @formatPage { markdown : markdown noTitleLink: true noAuthor : true }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html # Archives for a month (e.g. /2013/05/) @app.get /^\/(\d{4})\/(\d{2})\/?$/, (req, res) => year = req.params[0] month = req.params[1] try files = @listEntries year, month catch e @respondWithNotFound res return markdown = """ ## Archives for [#{year}](/#{year}/)-#{month} """ for file in files match = /^(\d+)(-\d+)?-(.*)\.md$/.exec file date = match[1] part = match[2] ? '' slug = match[3] datepart = date + part filepath = "#{@basedir}/#{year}/#{month}/#{file}" content = fs.readFileSync filepath, {encoding:'utf8'} lex = marked.Lexer.lex(content) title = @findTitleFromLex(lex) ? '' markdown += "#{@formatDate year, month, date} " + \ "[#{title or '(untitled)'}](/#{year}/#{month}/#{datepart}/#{slug})\n" @formatPage { markdown : markdown title : "Archives for #{year}-#{month}" noTitleLink: true noAuthor : true }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html # Recent entries @app.get '/recents', (req, res) => numRecents = @config.numRecents ? @recentInfo.recentFiles.length markdown = """ ## Recent Entries """ for file in @recentInfo.recentFiles[...numRecents] entryUrl = "/#{file.year}/#{file.month}/#{file.datepart}/#{file.slug}" ymd = @formatDate file.year, file.month, file.date markdown += "#{ymd} [#{file.title or '(untitled)'}](#{entryUrl})\n" markdown += "\n\n[Archives](/archives)" @formatPage { markdown : markdown noTitleLink: true noAuthor : true }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html # Atom feed @app.get '/index.atom', (req, res) => buf = """ <?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <title>#{@config.siteName}</title> <link href="#{@config.siteURL}/index.atom" rel="self" /> <link href="#{@config.siteURL}" /> <id>#{@escapeTags @config.siteURL + '/'}</id> <updated>#{new Date(@recentInfo.generatedTime).toISOString()}</updated> """ numRecents = @config.numRecents ? @recentInfo.recentFiles.length for file in @recentInfo.recentFiles[...numRecents] html = @convertToAbsoluteLinks file.body, { year : file.year month : file.month date : file.date absoluteURL: true } entryUrl = "#{@config.siteURL}/#{file.year}/#{file.month}/#{file.datepart}/#{file.slug}" title = file.title if (not title?) or (title is '') title = '(untitled)' buf += """ <entry> <title>#{@escapeTags title}</title> <link href="#{entryUrl}" /> <id>#{entryUrl}</id> <updated>#{new Date(file.time).toISOString()}</updated> <content type="html">#{@escapeTags html}</content> <author> <name>#{@escapeTags @config.authorName}</name> <uri>#{@escapeTags @config.authorLink}</uri> """ if @config.authorEmail buf += " <email>#{@config.authorEmail}</email>" buf += """ </author> </entry> """ buf += "\n</feed>\n" res.set 'Content-Type', 'text/xml; charset=utf-8' res.send buf # Homepage @app.get '/', (req, res) => if @config.homepage is 'recents' @serveRecents req, res else @serveMostRecentEntry req, res # Not found @app.get '*', (req, res) => @respondWithNotFound res # Log unhandled errors @app.use (err, req, res, next) -> console.error err.stack next err if opts?.autoStart @start() start: (callback) -> if fs.existsSync @reindexCheckFilename fs.unlink @reindexCheckFilename # Watch reindex-needed to be created fs.watchFile @reindexCheckFilename, (curr, prev) => if curr.nlink > 0 fs.unlink @reindexCheckFilename, => @createIndex() @emit 'updateIndex' # Watch config.json to be updated fs.watchFile @configFilename, (curr, prev) => err = @loadConfig() if not err? @logMessage "loaded #{path.basename @configFilename}" @createIndex() # Load page template and watch it for change @pageTemplate = fs.readFileSync @pageTemplateFilename, {encoding:'utf8'} fs.watchFile @pageTemplateFilename, (curr, prev) => fs.readFile @pageTemplateFilename, {encoding:'utf8'}, (err, data) => if err @logMessage "#{@pageTemplateFilename} read error: #{err}" return @pageTemplate = data @logMessage "loaded #{path.basename @pageTemplateFilename}" @createIndex() @httpServer.listen @port @httpServer.on 'listening', => @logMessage "Server started on port #{@httpServer.address().port}" stop: -> fs.unwatchFile @reindexCheckFilename fs.unwatchFile @configFilename fs.unwatchFile @pageTemplateFilename @httpServer.close => @logMessage "Server closed" # Log message to stdout logMessage: (str, opts) -> if @constructorOpts?.quiet return buf = '' if not opts?.noTime d = new Date buf += "[#{d.toDateString()} #{d.toLocaleTimeString()}] " buf += str if not opts?.noNewline buf += "\n" process.stdout.write buf monthNames: [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] formatDate: (year, month, date) -> "#{@monthNames[month-1]} #{parseInt date}, #{year}" # Obfuscate email address obfuscateEmail: (str) -> buf = '' for i in [0...str.length] buf += "&##{str.charCodeAt i};" buf # Escape HTML/XML tags escapeTags: (str) -> str.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') # Load config.json loadConfig: -> try @config = JSON.parse fs.readFileSync @configFilename catch e @logMessage "#{@configFilename} read error: #{e}" return e @config.siteURL = @config.siteURL.replace /\/$/, '' @config.authorEmail = @obfuscateEmail @config.authorEmail null # no error # 500 Server Error respondWithServerError: (res) -> markdown = """ ## Server Error Please try again later. """ @formatPage {markdown:markdown, noTitleLink:true, noAuthor:true}, (err, html) => if err @logMessage err res.status(500).send('Server error') return res.set 'Content-Type', 'text/html; charset=utf-8' res.status(500).send(html) # 404 Not Found respondWithNotFound: (res) -> markdown = """ ## Not Found The requested document was not found. """ @formatPage {markdown:markdown, noTitleLink:true, noAuthor:true}, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.status(404).send(html) # Find first heading from lex object findTitleFromLex: (lex) -> for component in lex if component.type is 'heading' return component.text null # not found # Convert links in HTML to absolute URL # html (string): HTML # params: { # year (string): entry's year # month (string): entry's month # date (string): entry's date # absoluteURL (boolean): If true, prepend @config.siteURL # If false, start with / # } convertToAbsoluteLinks: (html, params) -> html = html.replace /(<a href|<img src)="(.*?)"/g, (match, p1, p2) => p2 = p2.replace /^\.\.\/(?!\.\.)/g, "/#{params.year}/#{params.month}/" p2 = p2.replace /^\.\.\/\.\.\/(?!\.\.)/g, "/#{params.year}/" p2 = p2.replace /^\.\.\/\.\.\/\.\.\/(?!\.\.)/g, "/" if p2.indexOf('://') is -1 if p2[0] isnt '/' p2 = "/#{params.year}/#{params.month}/#{params.date}/#{p2}" if params.absoluteURL p2 = "#{@config.siteURL}#{p2}" "#{p1}=\"#{p2}\"" html # Format Markdown content into HTML formatPage: (input, callback) -> lex = marked.Lexer.lex(input.markdown) # Title title = input.title ? null if not title? lexTitle = @findTitleFromLex lex if lexTitle? title = lexTitle if not title? title = '(untitled)' body = marked.Parser.parse(lex) # Convert relative links to absolute if input.absolutePath or input.absoluteURL body = @convertToAbsoluteLinks body, input # Date if input.year? and input.month? and input.date? buf = "<div class=\"date\">" if not input.noTitleLink buf += "<a href=\"#{input.link}\">" buf += "#{@formatDate input.year, input.month, input.date}" if not input.noTitleLink buf += "</a>" buf += "</div>\n" body = buf + body # Author author = undefined if not input.noAuthor author = "<div class=\"author\">Posted by " + \ "<a href=\"#{@config.authorLink}\">#{@config.authorName}</a>" if @config.authorEmail author += " &lt;<a href=\"mailto:#{@config.authorEmail}\">" + \ "#{@config.authorEmail}</a>&gt;" author += "</div>" # Link title if not input.noTitleLink body = body.replace /<(h\d)([^>]*)>(.*?)<\/\1>/, \ "<$1$2><a href=\"#{input.link}\">$3</a></$1>" # Create anchors for headings if input.anchorHeading isnt false headingCount = -1 body = body.replace /<(h\d)([^>]*)>(.*?)<\/\1>/g, (match, p1, p2, p3) -> if ++headingCount > 0 "<#{p1}#{p2} class=\"anchor\" id=\"heading_#{headingCount}\">" + \ "<a href=\"#heading_#{headingCount}\">#{p3}</a></#{p1}>" else match body = body.replace /<(h\d)([^>]*)>/, "<$1$2 class=\"title\">" body = body.replace /(<h\d) id="[^"]*"/g, '$1' # Object to be passed to template opts = title : title body : body author : PI:NAME:<NAME>END_PI siteName: @config.siteName siteURL : @config.siteURL if input.noTitle opts.title = undefined # Apply page.ejs to page contents html = ejs.render @pageTemplate, opts callback null, html # List all years listYears: -> years = fs.readdirSync @basedir years = (year for year in years when /\d{4}/.test year) years.sort (a, b) -> b - a years # List all months for the given year listMonths: (year) -> months = fs.readdirSync "#{@basedir}/#{year}" months = (month for month in months when /\d{2}/.test month) months.sort (a, b) -> b - a months # List all entries for the given year/month listEntries: (year, month) -> files = fs.readdirSync "#{@basedir}/#{year}/#{month}" files = (file for file in files when /\.md$/.test file) files.sort (a, b) -> intA = parseInt a intB = parseInt b cmp = intB - intA if cmp is 0 subintA = 0 subintB = 0 if (match = /^\d+-(\d+)-/.exec a)? subintA = parseInt match[1] if (match = /^\d+-(\d+)-/.exec b)? subintB = parseInt match[1] cmp = subintB - subintA if cmp is 0 cmp = b.localeCompare a cmp files # Scan entries and update index createIndex: (numRecents) -> if not numRecents? numRecents = @config.numRecents ? 15 if @config.numHomepageRecents? numRecents = Math.max @config.numHomepageRecents, numRecents @logMessage "indexing...", noNewline:true startTime = new Date().getTime() count = 0 recentFiles = [] years = @listYears() for year in years break if count >= numRecents months = @listMonths year for month in months break if count >= numRecents files = @listEntries year, month for file in files match = /^(\d+)(-\d+)?-(.*)\.md$/.exec file if not match? continue filepath = "#{@basedir}/#{year}/#{month}/#{file}" markdown = fs.readFileSync filepath, {encoding:'utf8'} lex = marked.Lexer.lex(markdown) title = @findTitleFromLex(lex) ? '' body = marked.Parser.parse(lex) date = match[1] part = match[2] ? '' slug = match[3] recentFiles.push time : new Date("#{year}-#{month}-#{date} 00:00:00").getTime() title : title body : body year : year month : month date : date part : part datepart: date + part slug : slug if ++count >= numRecents break # Hold index in recentInfo @recentInfo = recentFiles: recentFiles generatedTime: new Date().getTime() elapsedTime = new Date().getTime() - startTime @logMessage "done (#{elapsedTime} ms)", noTime:true # Serve homepage in recents style serveRecents: (req, res) -> numRecents = @config.numHomepageRecents ? @config.numRecents ? 5 markdown = '' for file in @recentInfo.recentFiles[...numRecents] entryUrl = "/#{file.year}/#{file.month}/#{file.datepart}/#{file.slug}" markdown += "[#{file.title or '(untitled)'}](#{entryUrl})\n" @formatPage { markdown : markdown noTitleLink: true noAuthor : true noTitle : true }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html # Show the most recent entry on homepage serveMostRecentEntry: (req, res) -> file = @recentInfo.recentFiles[0] if not file? res.set 'Content-Type', 'text/plain; charset=utf-8' # Empty content message res.send """ This is the place where your content will appear. Add a first entry like this: mkdir -p 2013/05 echo "# Test\\n\\nHello World" > 2013/05/27-test.md git add . git commit -m "add test entry" git push origin master Finished? Then reload this page slowly. """ return filepath = "#{@basedir}/#{file.year}/#{file.month}/#{file.datepart}-#{file.slug}.md" fs.readFile filepath, {encoding:'utf8'}, (err, markdown) => if err @logMessage err @respondWithServerError res return url = "/#{file.year}/#{file.month}/#{file.datepart}/#{file.slug}" @formatPage { markdown : markdown link : url year : file.year month : file.month date : file.date noTitle : true absolutePath: true }, (err, html) => if err @logMessage err @respondWithServerError res return res.set 'Content-Type', 'text/html; charset=utf-8' res.send html module.exports = BitterServer if not module.parent? # This script is being run directly new BitterServer autoStart:true
[ { "context": "iv class=\"dashboard__container\">\n <div id=\"macy\"\n infinite-scroll=\"$ctrl.posts.next", "end": 1175, "score": 0.7299165725708008, "start": 1174, "tag": "NAME", "value": "m" }, { "context": "v class=\"dashboard__container\">\n <div id=\"macy\"\n infinite-scroll=\"$ctrl.posts.nextPag", "end": 1178, "score": 0.4709445536136627, "start": 1175, "tag": "NAME", "value": "acy" } ]
src/app/public/front/coffee/components/dashboard/dashboard.coffee
eiurur/Kawpaa
3
angular.module "myApp.directives" .directive 'dashboard', -> restrict: 'E' scope: {} template: """ <div class="dashboard__controls"> <div class="selectable-buttons"> <span class="button button--active" ng-click="$ctrl.changeFilter('danbooru.donmai.us')" data-hostname="danbooru.donmai.us">Danbooru</span> <span class="button" ng-click="$ctrl.changeFilter('chan.sankakucomplex.com')" data-hostname="chan.sankakucomplex.com">Sankaku Complex</span> <span class="button" ng-click="$ctrl.changeFilter('yande.re')" data-hostname="yande.re">yande.re</span> <span class="button" ng-click="$ctrl.changeFilter('www.pixiv.net')" data-hostname="www.pixiv.net">pixiv</span> <span class="button" ng-click="$ctrl.changeFilter('twitter.com')" data-hostname="twitter.com">Twitter</span> <span class="button" ng-click="$ctrl.changeFilter('tweetdeck.twitter.com')" data-hostname="tweetdeck.twitter.com">TweetDeck</span> </div> </div> <zoom-image-viewer page-type="$ctrl.pageType" posts="$ctrl.posts.items"></zoom-image-viewer> <div class="dashboard__container"> <div id="macy" infinite-scroll="$ctrl.posts.nextPage()" infinite-scroll-disabled="$ctrl.posts.busy" infinite-scroll-distance="5"> <div ng-repeat="post in $ctrl.posts.items" class="dashboard__post item" > <img class="dashboard__img" ng-src="data/thumbnails/{{::post.fromImgSrc}}" to-img-src="data/thumbnails/{{::post.toImgSrc}}" img-src="data/images/{{::post.images.original}}" pipe-low-to-high-image="pipe-low-to-high-image" post="post" open-zoom-image-viewer="open-zoom-image-viewer" id="{{::post._id}}"> <div class="dashboard__post__body"> <a href="{{::post.siteUrl}}" target="_blank" class="dashboard__link"> <div class="dashboard__post__description"> {{::post.title}} </div> </a> </div> <div class="dashboard__post__footer"> <span class="clickable dashboard__link" ng-click="$ctrl.addInbox(post._id)"> <i post-object-id="{{::post._id}}" class="fa fa-inbox icon-inbox"></i> Inbox </span> <span class="dashboard__post__via"> <a href="{{::post.siteUrl}}" target="_blank"> <img ng-src="{{::post.favicon}}"> </a> </span> </div> </div> </div> <span class="dashboard__loading" ng-if="$ctrl.posts.busy"> <img src="front/images/loaders/puff.svg" /> </span> </div> <go-to-top></go-to-top> """ bindToController: {} controller: DashboardController controllerAs: "$ctrl" class DashboardController constructor: (@$scope, @DashboardPost, @KawpaaLocalStorageService, @PromiseService, @PostManageService) -> @pageType = 'dashboard' @setFilters() @changeFilter() setFilters: -> if @KawpaaLocalStorageService.isEmpty('explore.actives') @filters = @DEFAULT_FILTERS else @filters = @KawpaaLocalStorageService.get('explore.actives').split(',') changeFilter: (hostname) -> if hostname if @filters.includes(hostname) @filters = @filters.filter (h, i) => h isnt hostname else @filters.push(hostname) @filters = Array.from(new Set(@filters)) if @filters.length < 1 @filters.push(hostname) @fillActive() @load() @KawpaaLocalStorageService.set('explore.actives', @filters.join(',')) load: -> @posts = new @DashboardPost(@filters) @posts.nextPage() # MinMasonryとの相性が悪いのか、次が読み込まれない場合あるので fillActive: -> buttons = angular.element('.selectable-buttons').find('.button') angular.forEach buttons, (element) => ele = angular.element(element) ele.removeClass('button--active') if @filters.includes(ele.data('hostname')) then ele.addClass('button--active') addInbox: (postObjectId) -> params = postObjectId: postObjectId @PostManageService.addInbox params .then (data) -> console.log data .catch (err) -> console.log err DEFAULT_FILTERS: [ 'twitter.com' 'tweetdeck.twitter.com' 'www.pixiv.net' 'danbooru.donmai.us' 'chan.sankakucomplex.com' 'yande.re' ] DashboardController.$inject = ['$scope', 'DashboardPost', 'KawpaaLocalStorageService', 'PromiseService', 'PostManageService']
39267
angular.module "myApp.directives" .directive 'dashboard', -> restrict: 'E' scope: {} template: """ <div class="dashboard__controls"> <div class="selectable-buttons"> <span class="button button--active" ng-click="$ctrl.changeFilter('danbooru.donmai.us')" data-hostname="danbooru.donmai.us">Danbooru</span> <span class="button" ng-click="$ctrl.changeFilter('chan.sankakucomplex.com')" data-hostname="chan.sankakucomplex.com">Sankaku Complex</span> <span class="button" ng-click="$ctrl.changeFilter('yande.re')" data-hostname="yande.re">yande.re</span> <span class="button" ng-click="$ctrl.changeFilter('www.pixiv.net')" data-hostname="www.pixiv.net">pixiv</span> <span class="button" ng-click="$ctrl.changeFilter('twitter.com')" data-hostname="twitter.com">Twitter</span> <span class="button" ng-click="$ctrl.changeFilter('tweetdeck.twitter.com')" data-hostname="tweetdeck.twitter.com">TweetDeck</span> </div> </div> <zoom-image-viewer page-type="$ctrl.pageType" posts="$ctrl.posts.items"></zoom-image-viewer> <div class="dashboard__container"> <div id="<NAME> <NAME>" infinite-scroll="$ctrl.posts.nextPage()" infinite-scroll-disabled="$ctrl.posts.busy" infinite-scroll-distance="5"> <div ng-repeat="post in $ctrl.posts.items" class="dashboard__post item" > <img class="dashboard__img" ng-src="data/thumbnails/{{::post.fromImgSrc}}" to-img-src="data/thumbnails/{{::post.toImgSrc}}" img-src="data/images/{{::post.images.original}}" pipe-low-to-high-image="pipe-low-to-high-image" post="post" open-zoom-image-viewer="open-zoom-image-viewer" id="{{::post._id}}"> <div class="dashboard__post__body"> <a href="{{::post.siteUrl}}" target="_blank" class="dashboard__link"> <div class="dashboard__post__description"> {{::post.title}} </div> </a> </div> <div class="dashboard__post__footer"> <span class="clickable dashboard__link" ng-click="$ctrl.addInbox(post._id)"> <i post-object-id="{{::post._id}}" class="fa fa-inbox icon-inbox"></i> Inbox </span> <span class="dashboard__post__via"> <a href="{{::post.siteUrl}}" target="_blank"> <img ng-src="{{::post.favicon}}"> </a> </span> </div> </div> </div> <span class="dashboard__loading" ng-if="$ctrl.posts.busy"> <img src="front/images/loaders/puff.svg" /> </span> </div> <go-to-top></go-to-top> """ bindToController: {} controller: DashboardController controllerAs: "$ctrl" class DashboardController constructor: (@$scope, @DashboardPost, @KawpaaLocalStorageService, @PromiseService, @PostManageService) -> @pageType = 'dashboard' @setFilters() @changeFilter() setFilters: -> if @KawpaaLocalStorageService.isEmpty('explore.actives') @filters = @DEFAULT_FILTERS else @filters = @KawpaaLocalStorageService.get('explore.actives').split(',') changeFilter: (hostname) -> if hostname if @filters.includes(hostname) @filters = @filters.filter (h, i) => h isnt hostname else @filters.push(hostname) @filters = Array.from(new Set(@filters)) if @filters.length < 1 @filters.push(hostname) @fillActive() @load() @KawpaaLocalStorageService.set('explore.actives', @filters.join(',')) load: -> @posts = new @DashboardPost(@filters) @posts.nextPage() # MinMasonryとの相性が悪いのか、次が読み込まれない場合あるので fillActive: -> buttons = angular.element('.selectable-buttons').find('.button') angular.forEach buttons, (element) => ele = angular.element(element) ele.removeClass('button--active') if @filters.includes(ele.data('hostname')) then ele.addClass('button--active') addInbox: (postObjectId) -> params = postObjectId: postObjectId @PostManageService.addInbox params .then (data) -> console.log data .catch (err) -> console.log err DEFAULT_FILTERS: [ 'twitter.com' 'tweetdeck.twitter.com' 'www.pixiv.net' 'danbooru.donmai.us' 'chan.sankakucomplex.com' 'yande.re' ] DashboardController.$inject = ['$scope', 'DashboardPost', 'KawpaaLocalStorageService', 'PromiseService', 'PostManageService']
true
angular.module "myApp.directives" .directive 'dashboard', -> restrict: 'E' scope: {} template: """ <div class="dashboard__controls"> <div class="selectable-buttons"> <span class="button button--active" ng-click="$ctrl.changeFilter('danbooru.donmai.us')" data-hostname="danbooru.donmai.us">Danbooru</span> <span class="button" ng-click="$ctrl.changeFilter('chan.sankakucomplex.com')" data-hostname="chan.sankakucomplex.com">Sankaku Complex</span> <span class="button" ng-click="$ctrl.changeFilter('yande.re')" data-hostname="yande.re">yande.re</span> <span class="button" ng-click="$ctrl.changeFilter('www.pixiv.net')" data-hostname="www.pixiv.net">pixiv</span> <span class="button" ng-click="$ctrl.changeFilter('twitter.com')" data-hostname="twitter.com">Twitter</span> <span class="button" ng-click="$ctrl.changeFilter('tweetdeck.twitter.com')" data-hostname="tweetdeck.twitter.com">TweetDeck</span> </div> </div> <zoom-image-viewer page-type="$ctrl.pageType" posts="$ctrl.posts.items"></zoom-image-viewer> <div class="dashboard__container"> <div id="PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI" infinite-scroll="$ctrl.posts.nextPage()" infinite-scroll-disabled="$ctrl.posts.busy" infinite-scroll-distance="5"> <div ng-repeat="post in $ctrl.posts.items" class="dashboard__post item" > <img class="dashboard__img" ng-src="data/thumbnails/{{::post.fromImgSrc}}" to-img-src="data/thumbnails/{{::post.toImgSrc}}" img-src="data/images/{{::post.images.original}}" pipe-low-to-high-image="pipe-low-to-high-image" post="post" open-zoom-image-viewer="open-zoom-image-viewer" id="{{::post._id}}"> <div class="dashboard__post__body"> <a href="{{::post.siteUrl}}" target="_blank" class="dashboard__link"> <div class="dashboard__post__description"> {{::post.title}} </div> </a> </div> <div class="dashboard__post__footer"> <span class="clickable dashboard__link" ng-click="$ctrl.addInbox(post._id)"> <i post-object-id="{{::post._id}}" class="fa fa-inbox icon-inbox"></i> Inbox </span> <span class="dashboard__post__via"> <a href="{{::post.siteUrl}}" target="_blank"> <img ng-src="{{::post.favicon}}"> </a> </span> </div> </div> </div> <span class="dashboard__loading" ng-if="$ctrl.posts.busy"> <img src="front/images/loaders/puff.svg" /> </span> </div> <go-to-top></go-to-top> """ bindToController: {} controller: DashboardController controllerAs: "$ctrl" class DashboardController constructor: (@$scope, @DashboardPost, @KawpaaLocalStorageService, @PromiseService, @PostManageService) -> @pageType = 'dashboard' @setFilters() @changeFilter() setFilters: -> if @KawpaaLocalStorageService.isEmpty('explore.actives') @filters = @DEFAULT_FILTERS else @filters = @KawpaaLocalStorageService.get('explore.actives').split(',') changeFilter: (hostname) -> if hostname if @filters.includes(hostname) @filters = @filters.filter (h, i) => h isnt hostname else @filters.push(hostname) @filters = Array.from(new Set(@filters)) if @filters.length < 1 @filters.push(hostname) @fillActive() @load() @KawpaaLocalStorageService.set('explore.actives', @filters.join(',')) load: -> @posts = new @DashboardPost(@filters) @posts.nextPage() # MinMasonryとの相性が悪いのか、次が読み込まれない場合あるので fillActive: -> buttons = angular.element('.selectable-buttons').find('.button') angular.forEach buttons, (element) => ele = angular.element(element) ele.removeClass('button--active') if @filters.includes(ele.data('hostname')) then ele.addClass('button--active') addInbox: (postObjectId) -> params = postObjectId: postObjectId @PostManageService.addInbox params .then (data) -> console.log data .catch (err) -> console.log err DEFAULT_FILTERS: [ 'twitter.com' 'tweetdeck.twitter.com' 'www.pixiv.net' 'danbooru.donmai.us' 'chan.sankakucomplex.com' 'yande.re' ] DashboardController.$inject = ['$scope', 'DashboardPost', 'KawpaaLocalStorageService', 'PromiseService', 'PostManageService']
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999133348464966, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/react/admin/contest.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { UserEntryList } from './contest/user-entry-list' reactTurbolinks.registerPersistent 'admin-contest-user-entry-list', UserEntryList, true, (el) -> container: el contest: osu.parseJson('json-contest') entries: osu.parseJson('json-contest-entries')
110266
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { UserEntryList } from './contest/user-entry-list' reactTurbolinks.registerPersistent 'admin-contest-user-entry-list', UserEntryList, true, (el) -> container: el contest: osu.parseJson('json-contest') entries: osu.parseJson('json-contest-entries')
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { UserEntryList } from './contest/user-entry-list' reactTurbolinks.registerPersistent 'admin-contest-user-entry-list', UserEntryList, true, (el) -> container: el contest: osu.parseJson('json-contest') entries: osu.parseJson('json-contest-entries')
[ { "context": "ctive - Lists all active torrents.\n#\n# Author:\n# hbc <me@hbc.rocks>\n\nTransmission = require 'transmiss", "end": 683, "score": 0.9997026920318604, "start": 680, "tag": "USERNAME", "value": "hbc" }, { "context": "- Lists all active torrents.\n#\n# Author:\n# hbc <me@hbc.rocks>\n\nTransmission = require 'transmission'\n\n\nsetOptW", "end": 697, "score": 0.9999141693115234, "start": 685, "tag": "EMAIL", "value": "me@hbc.rocks" }, { "context": " setOptWhenEnvDefined opts, 'TRANSMISSION_USER', 'username'\n opts = setOptWhenEnvDefined opts, 'TRANSMISSIO", "end": 2265, "score": 0.9994614720344543, "start": 2257, "tag": "USERNAME", "value": "username" }, { "context": " setOptWhenEnvDefined opts, 'TRANSMISSION_PASS', 'password'\n opts = setOptWhenEnvDefined opts, 'TRANSMISSIO", "end": 2333, "score": 0.9980668425559998, "start": 2325, "tag": "PASSWORD", "value": "password" } ]
src/transmission.coffee
bcho/hubot-transmission
0
# Description: # Interacting with Transmission with hubot. # # Configuration: # TRANSMISSION_USER - Username for Transmission connection # TRANSMISSION_PASS - Password for Transmission connection # TRANSMISSION_HOST - Transmission connection host # TRANSMISSION_PORT - Transmission connection port # TRANSMISSION_USE_SSL - Should use SSL for connection # TRANSMISSION_URL - Transmission connection url # # Commands: # hubot trs add-magnet <magnet-url> - Adds a torrent from magnet. # hubot trs start <torrent-id> - Starts a torrent. # hubot trs stat <torrent-id> - Gets stat of a torrent. # hubot trs list-active - Lists all active torrents. # # Author: # hbc <me@hbc.rocks> Transmission = require 'transmission' setOptWhenEnvDefined = (opts, envvar, assignVar) -> if process.env[envvar]? o = {} o[assignVar] = process.env[envvar] Object.assign {}, opts, o else opts class HubotTransmission constructor: (opts) -> @trs = new Transmission opts parseTorrenStat: (stat) -> return { id: stat.id name: stat.name downloadRate: stat.rateDownload / 1000 uploadRate: stat.rateUpload / 1000 completed: stat.percentDone * 100 etaInSeconds: stat.eta status: @trs.statusArray[stat.status] } addFromMagnet: (url) -> new Promise (resolve, reject) => @trs.addUrl url, (err, rv) -> return reject err if err resolve rv start: (id) -> id = parseInt(id, 10) new Promise (resolve, reject) => @trs.start [id], (err, rv) -> return reject err if err resolve id: id getStat: (id) -> id = parseInt(id, 10) new Promise (resolve, reject) => @trs.get id, (err, rv) => return reject err if err return reject "torrent #{id} not found" unless rv.torrents?.length > 0 stat = rv.torrents[0] resolve @parseTorrenStat stat listActive: () -> new Promise (resolve, reject) => @trs.active (err, rv) => return reject err if err return resolve [] unless rv.torrents?.length > 0 resolve rv.torrents.map (t) => @parseTorrenStat t module.exports = (robot) -> opts = {} opts = setOptWhenEnvDefined opts, 'TRANSMISSION_USER', 'username' opts = setOptWhenEnvDefined opts, 'TRANSMISSION_PASS', 'password' opts = setOptWhenEnvDefined opts, 'TRANSMISSION_HOST', 'host' opts = setOptWhenEnvDefined opts, 'TRANSMISSION_PORT', 'port' opts = setOptWhenEnvDefined opts, 'TRANSMISSION_USE_SSL', 'ssl' opts = setOptWhenEnvDefined opts, 'TRANSMISSION_URL', 'url' trs = new HubotTransmission opts robot.hear /trs add\-magnet (.*)/i, (res) -> trs.addFromMagnet(res.match[1].trim()) .then (torrent) -> res.reply [ "torrent #{torrent.name} added. " "You can start with `trs start #{torrent.id}`" ].join('') .catch (err) -> res.reply "add torrent from magnet failed: #{err}" robot.hear /trs start (.*)/i, (res) -> trs.start(res.match[1].trim()) .then (torrent) -> res.reply "torrent #{torrent.id} started" .catch (err) -> res.reply "start torrent #{id} failed: #{err}" robot.hear /trs stat (.*)/i, (res) -> trs.getStat(res.match[1].trim()) .then (stat) -> reply = [ "torrent #{stat.name} (#{stat.status}):" "download rate: #{stat.downloadRate}" "upload rate: #{stat.uploadRate}" "%: #{stat.completed}" "ETA: #{stat.etaInSeconds}s" ].join('\n') res.reply reply .catch (err) -> res.reply err robot.hear /trs list-active/i, (res) -> trs.listActive() .then (torrents) -> if torrents.length > 0 ts = torrents.map (t) -> "- #{t.id} #{t.name} (#{t.status}/#{t.etaInSeconds}/#{t.completed})" res.reply ts.join('\n') else res.reply 'no active torrents' .catch (err) -> resp.reply err
80984
# Description: # Interacting with Transmission with hubot. # # Configuration: # TRANSMISSION_USER - Username for Transmission connection # TRANSMISSION_PASS - Password for Transmission connection # TRANSMISSION_HOST - Transmission connection host # TRANSMISSION_PORT - Transmission connection port # TRANSMISSION_USE_SSL - Should use SSL for connection # TRANSMISSION_URL - Transmission connection url # # Commands: # hubot trs add-magnet <magnet-url> - Adds a torrent from magnet. # hubot trs start <torrent-id> - Starts a torrent. # hubot trs stat <torrent-id> - Gets stat of a torrent. # hubot trs list-active - Lists all active torrents. # # Author: # hbc <<EMAIL>> Transmission = require 'transmission' setOptWhenEnvDefined = (opts, envvar, assignVar) -> if process.env[envvar]? o = {} o[assignVar] = process.env[envvar] Object.assign {}, opts, o else opts class HubotTransmission constructor: (opts) -> @trs = new Transmission opts parseTorrenStat: (stat) -> return { id: stat.id name: stat.name downloadRate: stat.rateDownload / 1000 uploadRate: stat.rateUpload / 1000 completed: stat.percentDone * 100 etaInSeconds: stat.eta status: @trs.statusArray[stat.status] } addFromMagnet: (url) -> new Promise (resolve, reject) => @trs.addUrl url, (err, rv) -> return reject err if err resolve rv start: (id) -> id = parseInt(id, 10) new Promise (resolve, reject) => @trs.start [id], (err, rv) -> return reject err if err resolve id: id getStat: (id) -> id = parseInt(id, 10) new Promise (resolve, reject) => @trs.get id, (err, rv) => return reject err if err return reject "torrent #{id} not found" unless rv.torrents?.length > 0 stat = rv.torrents[0] resolve @parseTorrenStat stat listActive: () -> new Promise (resolve, reject) => @trs.active (err, rv) => return reject err if err return resolve [] unless rv.torrents?.length > 0 resolve rv.torrents.map (t) => @parseTorrenStat t module.exports = (robot) -> opts = {} opts = setOptWhenEnvDefined opts, 'TRANSMISSION_USER', 'username' opts = setOptWhenEnvDefined opts, 'TRANSMISSION_PASS', '<PASSWORD>' opts = setOptWhenEnvDefined opts, 'TRANSMISSION_HOST', 'host' opts = setOptWhenEnvDefined opts, 'TRANSMISSION_PORT', 'port' opts = setOptWhenEnvDefined opts, 'TRANSMISSION_USE_SSL', 'ssl' opts = setOptWhenEnvDefined opts, 'TRANSMISSION_URL', 'url' trs = new HubotTransmission opts robot.hear /trs add\-magnet (.*)/i, (res) -> trs.addFromMagnet(res.match[1].trim()) .then (torrent) -> res.reply [ "torrent #{torrent.name} added. " "You can start with `trs start #{torrent.id}`" ].join('') .catch (err) -> res.reply "add torrent from magnet failed: #{err}" robot.hear /trs start (.*)/i, (res) -> trs.start(res.match[1].trim()) .then (torrent) -> res.reply "torrent #{torrent.id} started" .catch (err) -> res.reply "start torrent #{id} failed: #{err}" robot.hear /trs stat (.*)/i, (res) -> trs.getStat(res.match[1].trim()) .then (stat) -> reply = [ "torrent #{stat.name} (#{stat.status}):" "download rate: #{stat.downloadRate}" "upload rate: #{stat.uploadRate}" "%: #{stat.completed}" "ETA: #{stat.etaInSeconds}s" ].join('\n') res.reply reply .catch (err) -> res.reply err robot.hear /trs list-active/i, (res) -> trs.listActive() .then (torrents) -> if torrents.length > 0 ts = torrents.map (t) -> "- #{t.id} #{t.name} (#{t.status}/#{t.etaInSeconds}/#{t.completed})" res.reply ts.join('\n') else res.reply 'no active torrents' .catch (err) -> resp.reply err
true
# Description: # Interacting with Transmission with hubot. # # Configuration: # TRANSMISSION_USER - Username for Transmission connection # TRANSMISSION_PASS - Password for Transmission connection # TRANSMISSION_HOST - Transmission connection host # TRANSMISSION_PORT - Transmission connection port # TRANSMISSION_USE_SSL - Should use SSL for connection # TRANSMISSION_URL - Transmission connection url # # Commands: # hubot trs add-magnet <magnet-url> - Adds a torrent from magnet. # hubot trs start <torrent-id> - Starts a torrent. # hubot trs stat <torrent-id> - Gets stat of a torrent. # hubot trs list-active - Lists all active torrents. # # Author: # hbc <PI:EMAIL:<EMAIL>END_PI> Transmission = require 'transmission' setOptWhenEnvDefined = (opts, envvar, assignVar) -> if process.env[envvar]? o = {} o[assignVar] = process.env[envvar] Object.assign {}, opts, o else opts class HubotTransmission constructor: (opts) -> @trs = new Transmission opts parseTorrenStat: (stat) -> return { id: stat.id name: stat.name downloadRate: stat.rateDownload / 1000 uploadRate: stat.rateUpload / 1000 completed: stat.percentDone * 100 etaInSeconds: stat.eta status: @trs.statusArray[stat.status] } addFromMagnet: (url) -> new Promise (resolve, reject) => @trs.addUrl url, (err, rv) -> return reject err if err resolve rv start: (id) -> id = parseInt(id, 10) new Promise (resolve, reject) => @trs.start [id], (err, rv) -> return reject err if err resolve id: id getStat: (id) -> id = parseInt(id, 10) new Promise (resolve, reject) => @trs.get id, (err, rv) => return reject err if err return reject "torrent #{id} not found" unless rv.torrents?.length > 0 stat = rv.torrents[0] resolve @parseTorrenStat stat listActive: () -> new Promise (resolve, reject) => @trs.active (err, rv) => return reject err if err return resolve [] unless rv.torrents?.length > 0 resolve rv.torrents.map (t) => @parseTorrenStat t module.exports = (robot) -> opts = {} opts = setOptWhenEnvDefined opts, 'TRANSMISSION_USER', 'username' opts = setOptWhenEnvDefined opts, 'TRANSMISSION_PASS', 'PI:PASSWORD:<PASSWORD>END_PI' opts = setOptWhenEnvDefined opts, 'TRANSMISSION_HOST', 'host' opts = setOptWhenEnvDefined opts, 'TRANSMISSION_PORT', 'port' opts = setOptWhenEnvDefined opts, 'TRANSMISSION_USE_SSL', 'ssl' opts = setOptWhenEnvDefined opts, 'TRANSMISSION_URL', 'url' trs = new HubotTransmission opts robot.hear /trs add\-magnet (.*)/i, (res) -> trs.addFromMagnet(res.match[1].trim()) .then (torrent) -> res.reply [ "torrent #{torrent.name} added. " "You can start with `trs start #{torrent.id}`" ].join('') .catch (err) -> res.reply "add torrent from magnet failed: #{err}" robot.hear /trs start (.*)/i, (res) -> trs.start(res.match[1].trim()) .then (torrent) -> res.reply "torrent #{torrent.id} started" .catch (err) -> res.reply "start torrent #{id} failed: #{err}" robot.hear /trs stat (.*)/i, (res) -> trs.getStat(res.match[1].trim()) .then (stat) -> reply = [ "torrent #{stat.name} (#{stat.status}):" "download rate: #{stat.downloadRate}" "upload rate: #{stat.uploadRate}" "%: #{stat.completed}" "ETA: #{stat.etaInSeconds}s" ].join('\n') res.reply reply .catch (err) -> res.reply err robot.hear /trs list-active/i, (res) -> trs.listActive() .then (torrents) -> if torrents.length > 0 ts = torrents.map (t) -> "- #{t.id} #{t.name} (#{t.status}/#{t.etaInSeconds}/#{t.completed})" res.reply ts.join('\n') else res.reply 'no active torrents' .catch (err) -> resp.reply err
[ { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ", "end": 38, "score": 0.9998872876167297, "start": 25, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino Garcia <jespin", "end": 52, "score": 0.9999305605888367, "start": 40, "tag": "EMAIL", "value": "niwi@niwi.be" }, { "context": " Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David B", "end": 94, "score": 0.999881386756897, "start": 75, "tag": "NAME", "value": "Jesús Espino Garcia" }, { "context": "iwi.be>\n# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David Barragán Merino <bame", "end": 114, "score": 0.9999348521232605, "start": 96, "tag": "EMAIL", "value": "jespinog@gmail.com" }, { "context": "o Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>\n#\n# This program is free s", "end": 158, "score": 0.9998840093612671, "start": 137, "tag": "NAME", "value": "David Barragán Merino" }, { "context": ".com>\n# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>\n#\n# This program is free software: you can redis", "end": 180, "score": 0.9999351501464844, "start": 160, "tag": "EMAIL", "value": "bameda@dbarragan.com" } ]
public/taiga-front/app/coffee/modules/wiki/main.coffee
mabotech/maboss
0
### # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com> # Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com> # # 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/>. # # File: modules/wiki/detail.coffee ### taiga = @.taiga mixOf = @.taiga.mixOf groupBy = @.taiga.groupBy bindOnce = @.taiga.bindOnce unslugify = @.taiga.unslugify debounce = @.taiga.debounce module = angular.module("taigaWiki") ############################################################################# ## Wiki Detail Controller ############################################################################# class WikiDetailController extends mixOf(taiga.Controller, taiga.PageMixin) @.$inject = [ "$scope", "$rootScope", "$tgRepo", "$tgModel", "$tgConfirm", "$tgResources", "$routeParams", "$q", "$tgLocation", "$filter", "$log", "$appTitle", "$tgNavUrls", "$tgAnalytics", "tgLoader" ] constructor: (@scope, @rootscope, @repo, @model, @confirm, @rs, @params, @q, @location, @filter, @log, @appTitle, @navUrls, @analytics, tgLoader) -> @scope.projectSlug = @params.pslug @scope.wikiSlug = @params.slug @scope.sectionName = "Wiki" promise = @.loadInitialData() # On Success promise.then () => @appTitle.set("Wiki - " + @scope.project.name) tgLoader.pageLoaded() # On Error promise.then null, @.onInitialDataError.bind(@) loadProject: -> return @rs.projects.get(@scope.projectId).then (project) => @scope.project = project @scope.$emit('project:loaded', project) @scope.membersById = groupBy(project.memberships, (x) -> x.user) return project loadWiki: -> if @scope.wikiId return @rs.wiki.get(@scope.wikiId).then (wiki) => @scope.wiki = wiki return wiki if @scope.project.my_permissions.indexOf("add_wiki_page") == -1 return null data = { project: @scope.projectId slug: @scope.wikiSlug content: "" } @scope.wiki = @model.make_model("wiki", data) return @scope.wiki loadWikiLinks: -> return @rs.wiki.listLinks(@scope.projectId).then (wikiLinks) => @scope.wikiLinks = wikiLinks loadInitialData: -> params = { pslug: @params.pslug wikipage: @params.slug } # Resolve project slug promise = @repo.resolve({pslug: @params.pslug}).then (data) => @scope.projectId = data.project return data # Resolve wiki slug # This should be done in two steps because is not same thing # not found response for project and not found for wiki page # and they should be hendled separately. promise = promise.then => prom = @repo.resolve({wikipage: @params.slug, pslug: @params.pslug}) prom = prom.then (data) => @scope.wikiId = data.wikipage return prom.then null, (xhr) => @scope.wikiId = null return promise.then(=> @.loadProject()) .then(=> @.loadUsersAndRoles()) .then(=> @q.all([@.loadWikiLinks(), @.loadWiki()])) delete: -> # TODO: i18n title = "Delete Wiki Page" message = unslugify(@scope.wiki.slug) @confirm.askOnDelete(title, message).then (finish) => onSuccess = => finish() ctx = {project: @scope.projectSlug} @location.path(@navUrls.resolve("project-wiki", ctx)) @confirm.notify("success") onError = => finish(false) @confirm.notify("error") @repo.remove(@scope.wiki).then onSuccess, onError module.controller("WikiDetailController", WikiDetailController) ############################################################################# ## Wiki Summary Directive ############################################################################# WikiSummaryDirective = ($log) -> template = _.template(""" <ul> <li> <span class="number"><%- totalEditions %></span> <span class="description">times <br />edited</span> </li> <li> <span class="number"><%- lastModifiedDate %></span> <span class="description"> last <br />edit</span> </li> <li class="username-edition"> <figure class="avatar"> <img src="<%- user.imgUrl %>" alt="<%- user.name %>"> </figure> <span class="description">last modification</span> <span class="username"><%- user.name %></span> </li> </ul> """) link = ($scope, $el, $attrs, $model) -> render = (wiki) -> if not $scope.usersById? $log.error "WikiSummaryDirective requires userById set in scope." else user = $scope.usersById[wiki.last_modifier] if user is undefined user = {name: "unknown", imgUrl: "/images/unnamed.png"} else user = {name: user.full_name_display, imgUrl: user.photo} ctx = { totalEditions: wiki.editions lastModifiedDate: moment(wiki.modified_date).format("DD MMM YYYY HH:mm") user: user } html = template(ctx) $el.html(html) $scope.$watch $attrs.ngModel, (wikiPage) -> return if not wikiPage render(wikiPage) $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" } module.directive("tgWikiSummary", ["$log", WikiSummaryDirective]) ############################################################################# ## Editable Wiki Content Directive ############################################################################# EditableWikiContentDirective = ($window, $document, $repo, $confirm, $loading, $location, $navUrls, $analytics, $qqueue) -> template = """ <div class="view-wiki-content"> <section class="wysiwyg" tg-bind-html="wiki.html"></section> <span class="edit icon icon-edit" title="Edit"></span> </div> <div class="edit-wiki-content" style="display: none;"> <textarea placeholder="Write your wiki page here" ng-model="wiki.content" tg-markitup="tg-markitup"></textarea> <a class="help-markdown" href="https://taiga.io/support/taiga-markdown-syntax/" target="_blank" title="Mardown syntax help"> <span class="icon icon-help"></span> <span>Markdown syntax help</span> </a> <span class="action-container"> <a class="save icon icon-floppy" href="" title="Save" /> <a class="cancel icon icon-delete" href="" title="Cancel" /> </span> </div> """ # TODO: i18n link = ($scope, $el, $attrs, $model) -> isEditable = -> return $scope.project.my_permissions.indexOf("modify_wiki_page") != -1 switchToEditMode = -> $el.find('.edit-wiki-content').show() $el.find('.view-wiki-content').hide() $el.find('textarea').focus() switchToReadMode = -> $el.find('.edit-wiki-content').hide() $el.find('.view-wiki-content').show() disableEdition = -> $el.find(".view-wiki-content .edit").remove() $el.find(".edit-wiki-content").remove() cancelEdition = -> return if !$scope.wiki.html if $scope.wiki.id $scope.$apply () => $scope.wiki.revert() switchToReadMode() else ctx = {project: $scope.projectSlug} $location.path($navUrls.resolve("project-wiki", ctx)) getSelectedText = -> if $window.getSelection return $window.getSelection().toString() else if $document.selection return $document.selection.createRange().text return null save = $qqueue.bindAdd (wiki) -> onSuccess = (wikiPage) -> if not wiki.id? $analytics.trackEvent("wikipage", "create", "create wiki page", 1) $scope.wiki = wikiPage $model.setModelValue = wiki $confirm.notify("success") switchToReadMode() onError = -> $confirm.notify("error") $loading.start($el.find('.save-container')) if wiki.id? promise = $repo.save(wiki).then(onSuccess, onError) else promise = $repo.create("wiki", wiki).then(onSuccess, onError) promise.finally -> $loading.finish($el.find('.save-container')) $el.on "mouseup", ".view-wiki-content", (event) -> # We want to dettect the a inside the div so we use the target and # not the currentTarget target = angular.element(event.target) return if not isEditable() return if target.is('a') return if getSelectedText() switchToEditMode() $el.on "click", ".save", debounce 2000, -> save($scope.wiki) $el.on "click", ".cancel", -> cancelEdition() $el.on "keydown", "textarea", (event) -> if event.keyCode == 27 cancelEdition() $scope.$watch $attrs.ngModel, (wikiPage) -> return if not wikiPage $scope.wiki = wikiPage if isEditable() $el.addClass('editable') if not wikiPage.id? switchToEditMode() else disableEdition() $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" template: template } module.directive("tgEditableWikiContent", ["$window", "$document", "$tgRepo", "$tgConfirm", "$tgLoading", "$tgLocation", "$tgNavUrls", "$tgAnalytics", "$tgQqueue", EditableWikiContentDirective])
133084
### # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # # 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/>. # # File: modules/wiki/detail.coffee ### taiga = @.taiga mixOf = @.taiga.mixOf groupBy = @.taiga.groupBy bindOnce = @.taiga.bindOnce unslugify = @.taiga.unslugify debounce = @.taiga.debounce module = angular.module("taigaWiki") ############################################################################# ## Wiki Detail Controller ############################################################################# class WikiDetailController extends mixOf(taiga.Controller, taiga.PageMixin) @.$inject = [ "$scope", "$rootScope", "$tgRepo", "$tgModel", "$tgConfirm", "$tgResources", "$routeParams", "$q", "$tgLocation", "$filter", "$log", "$appTitle", "$tgNavUrls", "$tgAnalytics", "tgLoader" ] constructor: (@scope, @rootscope, @repo, @model, @confirm, @rs, @params, @q, @location, @filter, @log, @appTitle, @navUrls, @analytics, tgLoader) -> @scope.projectSlug = @params.pslug @scope.wikiSlug = @params.slug @scope.sectionName = "Wiki" promise = @.loadInitialData() # On Success promise.then () => @appTitle.set("Wiki - " + @scope.project.name) tgLoader.pageLoaded() # On Error promise.then null, @.onInitialDataError.bind(@) loadProject: -> return @rs.projects.get(@scope.projectId).then (project) => @scope.project = project @scope.$emit('project:loaded', project) @scope.membersById = groupBy(project.memberships, (x) -> x.user) return project loadWiki: -> if @scope.wikiId return @rs.wiki.get(@scope.wikiId).then (wiki) => @scope.wiki = wiki return wiki if @scope.project.my_permissions.indexOf("add_wiki_page") == -1 return null data = { project: @scope.projectId slug: @scope.wikiSlug content: "" } @scope.wiki = @model.make_model("wiki", data) return @scope.wiki loadWikiLinks: -> return @rs.wiki.listLinks(@scope.projectId).then (wikiLinks) => @scope.wikiLinks = wikiLinks loadInitialData: -> params = { pslug: @params.pslug wikipage: @params.slug } # Resolve project slug promise = @repo.resolve({pslug: @params.pslug}).then (data) => @scope.projectId = data.project return data # Resolve wiki slug # This should be done in two steps because is not same thing # not found response for project and not found for wiki page # and they should be hendled separately. promise = promise.then => prom = @repo.resolve({wikipage: @params.slug, pslug: @params.pslug}) prom = prom.then (data) => @scope.wikiId = data.wikipage return prom.then null, (xhr) => @scope.wikiId = null return promise.then(=> @.loadProject()) .then(=> @.loadUsersAndRoles()) .then(=> @q.all([@.loadWikiLinks(), @.loadWiki()])) delete: -> # TODO: i18n title = "Delete Wiki Page" message = unslugify(@scope.wiki.slug) @confirm.askOnDelete(title, message).then (finish) => onSuccess = => finish() ctx = {project: @scope.projectSlug} @location.path(@navUrls.resolve("project-wiki", ctx)) @confirm.notify("success") onError = => finish(false) @confirm.notify("error") @repo.remove(@scope.wiki).then onSuccess, onError module.controller("WikiDetailController", WikiDetailController) ############################################################################# ## Wiki Summary Directive ############################################################################# WikiSummaryDirective = ($log) -> template = _.template(""" <ul> <li> <span class="number"><%- totalEditions %></span> <span class="description">times <br />edited</span> </li> <li> <span class="number"><%- lastModifiedDate %></span> <span class="description"> last <br />edit</span> </li> <li class="username-edition"> <figure class="avatar"> <img src="<%- user.imgUrl %>" alt="<%- user.name %>"> </figure> <span class="description">last modification</span> <span class="username"><%- user.name %></span> </li> </ul> """) link = ($scope, $el, $attrs, $model) -> render = (wiki) -> if not $scope.usersById? $log.error "WikiSummaryDirective requires userById set in scope." else user = $scope.usersById[wiki.last_modifier] if user is undefined user = {name: "unknown", imgUrl: "/images/unnamed.png"} else user = {name: user.full_name_display, imgUrl: user.photo} ctx = { totalEditions: wiki.editions lastModifiedDate: moment(wiki.modified_date).format("DD MMM YYYY HH:mm") user: user } html = template(ctx) $el.html(html) $scope.$watch $attrs.ngModel, (wikiPage) -> return if not wikiPage render(wikiPage) $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" } module.directive("tgWikiSummary", ["$log", WikiSummaryDirective]) ############################################################################# ## Editable Wiki Content Directive ############################################################################# EditableWikiContentDirective = ($window, $document, $repo, $confirm, $loading, $location, $navUrls, $analytics, $qqueue) -> template = """ <div class="view-wiki-content"> <section class="wysiwyg" tg-bind-html="wiki.html"></section> <span class="edit icon icon-edit" title="Edit"></span> </div> <div class="edit-wiki-content" style="display: none;"> <textarea placeholder="Write your wiki page here" ng-model="wiki.content" tg-markitup="tg-markitup"></textarea> <a class="help-markdown" href="https://taiga.io/support/taiga-markdown-syntax/" target="_blank" title="Mardown syntax help"> <span class="icon icon-help"></span> <span>Markdown syntax help</span> </a> <span class="action-container"> <a class="save icon icon-floppy" href="" title="Save" /> <a class="cancel icon icon-delete" href="" title="Cancel" /> </span> </div> """ # TODO: i18n link = ($scope, $el, $attrs, $model) -> isEditable = -> return $scope.project.my_permissions.indexOf("modify_wiki_page") != -1 switchToEditMode = -> $el.find('.edit-wiki-content').show() $el.find('.view-wiki-content').hide() $el.find('textarea').focus() switchToReadMode = -> $el.find('.edit-wiki-content').hide() $el.find('.view-wiki-content').show() disableEdition = -> $el.find(".view-wiki-content .edit").remove() $el.find(".edit-wiki-content").remove() cancelEdition = -> return if !$scope.wiki.html if $scope.wiki.id $scope.$apply () => $scope.wiki.revert() switchToReadMode() else ctx = {project: $scope.projectSlug} $location.path($navUrls.resolve("project-wiki", ctx)) getSelectedText = -> if $window.getSelection return $window.getSelection().toString() else if $document.selection return $document.selection.createRange().text return null save = $qqueue.bindAdd (wiki) -> onSuccess = (wikiPage) -> if not wiki.id? $analytics.trackEvent("wikipage", "create", "create wiki page", 1) $scope.wiki = wikiPage $model.setModelValue = wiki $confirm.notify("success") switchToReadMode() onError = -> $confirm.notify("error") $loading.start($el.find('.save-container')) if wiki.id? promise = $repo.save(wiki).then(onSuccess, onError) else promise = $repo.create("wiki", wiki).then(onSuccess, onError) promise.finally -> $loading.finish($el.find('.save-container')) $el.on "mouseup", ".view-wiki-content", (event) -> # We want to dettect the a inside the div so we use the target and # not the currentTarget target = angular.element(event.target) return if not isEditable() return if target.is('a') return if getSelectedText() switchToEditMode() $el.on "click", ".save", debounce 2000, -> save($scope.wiki) $el.on "click", ".cancel", -> cancelEdition() $el.on "keydown", "textarea", (event) -> if event.keyCode == 27 cancelEdition() $scope.$watch $attrs.ngModel, (wikiPage) -> return if not wikiPage $scope.wiki = wikiPage if isEditable() $el.addClass('editable') if not wikiPage.id? switchToEditMode() else disableEdition() $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" template: template } module.directive("tgEditableWikiContent", ["$window", "$document", "$tgRepo", "$tgConfirm", "$tgLoading", "$tgLocation", "$tgNavUrls", "$tgAnalytics", "$tgQqueue", EditableWikiContentDirective])
true
### # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # 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/>. # # File: modules/wiki/detail.coffee ### taiga = @.taiga mixOf = @.taiga.mixOf groupBy = @.taiga.groupBy bindOnce = @.taiga.bindOnce unslugify = @.taiga.unslugify debounce = @.taiga.debounce module = angular.module("taigaWiki") ############################################################################# ## Wiki Detail Controller ############################################################################# class WikiDetailController extends mixOf(taiga.Controller, taiga.PageMixin) @.$inject = [ "$scope", "$rootScope", "$tgRepo", "$tgModel", "$tgConfirm", "$tgResources", "$routeParams", "$q", "$tgLocation", "$filter", "$log", "$appTitle", "$tgNavUrls", "$tgAnalytics", "tgLoader" ] constructor: (@scope, @rootscope, @repo, @model, @confirm, @rs, @params, @q, @location, @filter, @log, @appTitle, @navUrls, @analytics, tgLoader) -> @scope.projectSlug = @params.pslug @scope.wikiSlug = @params.slug @scope.sectionName = "Wiki" promise = @.loadInitialData() # On Success promise.then () => @appTitle.set("Wiki - " + @scope.project.name) tgLoader.pageLoaded() # On Error promise.then null, @.onInitialDataError.bind(@) loadProject: -> return @rs.projects.get(@scope.projectId).then (project) => @scope.project = project @scope.$emit('project:loaded', project) @scope.membersById = groupBy(project.memberships, (x) -> x.user) return project loadWiki: -> if @scope.wikiId return @rs.wiki.get(@scope.wikiId).then (wiki) => @scope.wiki = wiki return wiki if @scope.project.my_permissions.indexOf("add_wiki_page") == -1 return null data = { project: @scope.projectId slug: @scope.wikiSlug content: "" } @scope.wiki = @model.make_model("wiki", data) return @scope.wiki loadWikiLinks: -> return @rs.wiki.listLinks(@scope.projectId).then (wikiLinks) => @scope.wikiLinks = wikiLinks loadInitialData: -> params = { pslug: @params.pslug wikipage: @params.slug } # Resolve project slug promise = @repo.resolve({pslug: @params.pslug}).then (data) => @scope.projectId = data.project return data # Resolve wiki slug # This should be done in two steps because is not same thing # not found response for project and not found for wiki page # and they should be hendled separately. promise = promise.then => prom = @repo.resolve({wikipage: @params.slug, pslug: @params.pslug}) prom = prom.then (data) => @scope.wikiId = data.wikipage return prom.then null, (xhr) => @scope.wikiId = null return promise.then(=> @.loadProject()) .then(=> @.loadUsersAndRoles()) .then(=> @q.all([@.loadWikiLinks(), @.loadWiki()])) delete: -> # TODO: i18n title = "Delete Wiki Page" message = unslugify(@scope.wiki.slug) @confirm.askOnDelete(title, message).then (finish) => onSuccess = => finish() ctx = {project: @scope.projectSlug} @location.path(@navUrls.resolve("project-wiki", ctx)) @confirm.notify("success") onError = => finish(false) @confirm.notify("error") @repo.remove(@scope.wiki).then onSuccess, onError module.controller("WikiDetailController", WikiDetailController) ############################################################################# ## Wiki Summary Directive ############################################################################# WikiSummaryDirective = ($log) -> template = _.template(""" <ul> <li> <span class="number"><%- totalEditions %></span> <span class="description">times <br />edited</span> </li> <li> <span class="number"><%- lastModifiedDate %></span> <span class="description"> last <br />edit</span> </li> <li class="username-edition"> <figure class="avatar"> <img src="<%- user.imgUrl %>" alt="<%- user.name %>"> </figure> <span class="description">last modification</span> <span class="username"><%- user.name %></span> </li> </ul> """) link = ($scope, $el, $attrs, $model) -> render = (wiki) -> if not $scope.usersById? $log.error "WikiSummaryDirective requires userById set in scope." else user = $scope.usersById[wiki.last_modifier] if user is undefined user = {name: "unknown", imgUrl: "/images/unnamed.png"} else user = {name: user.full_name_display, imgUrl: user.photo} ctx = { totalEditions: wiki.editions lastModifiedDate: moment(wiki.modified_date).format("DD MMM YYYY HH:mm") user: user } html = template(ctx) $el.html(html) $scope.$watch $attrs.ngModel, (wikiPage) -> return if not wikiPage render(wikiPage) $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" } module.directive("tgWikiSummary", ["$log", WikiSummaryDirective]) ############################################################################# ## Editable Wiki Content Directive ############################################################################# EditableWikiContentDirective = ($window, $document, $repo, $confirm, $loading, $location, $navUrls, $analytics, $qqueue) -> template = """ <div class="view-wiki-content"> <section class="wysiwyg" tg-bind-html="wiki.html"></section> <span class="edit icon icon-edit" title="Edit"></span> </div> <div class="edit-wiki-content" style="display: none;"> <textarea placeholder="Write your wiki page here" ng-model="wiki.content" tg-markitup="tg-markitup"></textarea> <a class="help-markdown" href="https://taiga.io/support/taiga-markdown-syntax/" target="_blank" title="Mardown syntax help"> <span class="icon icon-help"></span> <span>Markdown syntax help</span> </a> <span class="action-container"> <a class="save icon icon-floppy" href="" title="Save" /> <a class="cancel icon icon-delete" href="" title="Cancel" /> </span> </div> """ # TODO: i18n link = ($scope, $el, $attrs, $model) -> isEditable = -> return $scope.project.my_permissions.indexOf("modify_wiki_page") != -1 switchToEditMode = -> $el.find('.edit-wiki-content').show() $el.find('.view-wiki-content').hide() $el.find('textarea').focus() switchToReadMode = -> $el.find('.edit-wiki-content').hide() $el.find('.view-wiki-content').show() disableEdition = -> $el.find(".view-wiki-content .edit").remove() $el.find(".edit-wiki-content").remove() cancelEdition = -> return if !$scope.wiki.html if $scope.wiki.id $scope.$apply () => $scope.wiki.revert() switchToReadMode() else ctx = {project: $scope.projectSlug} $location.path($navUrls.resolve("project-wiki", ctx)) getSelectedText = -> if $window.getSelection return $window.getSelection().toString() else if $document.selection return $document.selection.createRange().text return null save = $qqueue.bindAdd (wiki) -> onSuccess = (wikiPage) -> if not wiki.id? $analytics.trackEvent("wikipage", "create", "create wiki page", 1) $scope.wiki = wikiPage $model.setModelValue = wiki $confirm.notify("success") switchToReadMode() onError = -> $confirm.notify("error") $loading.start($el.find('.save-container')) if wiki.id? promise = $repo.save(wiki).then(onSuccess, onError) else promise = $repo.create("wiki", wiki).then(onSuccess, onError) promise.finally -> $loading.finish($el.find('.save-container')) $el.on "mouseup", ".view-wiki-content", (event) -> # We want to dettect the a inside the div so we use the target and # not the currentTarget target = angular.element(event.target) return if not isEditable() return if target.is('a') return if getSelectedText() switchToEditMode() $el.on "click", ".save", debounce 2000, -> save($scope.wiki) $el.on "click", ".cancel", -> cancelEdition() $el.on "keydown", "textarea", (event) -> if event.keyCode == 27 cancelEdition() $scope.$watch $attrs.ngModel, (wikiPage) -> return if not wikiPage $scope.wiki = wikiPage if isEditable() $el.addClass('editable') if not wikiPage.id? switchToEditMode() else disableEdition() $scope.$on "$destroy", -> $el.off() return { link: link restrict: "EA" require: "ngModel" template: template } module.directive("tgEditableWikiContent", ["$window", "$document", "$tgRepo", "$tgConfirm", "$tgLoading", "$tgLocation", "$tgNavUrls", "$tgAnalytics", "$tgQqueue", EditableWikiContentDirective])
[ { "context": "odel = new DotLedger.Models.Account\n name: 'Some Account'\n type: 'Savings'\n number: '123'\n ", "end": 197, "score": 0.9974921345710754, "start": 185, "tag": "NAME", "value": "Some Account" } ]
spec/javascripts/dot_ledger/views/accounts/show_spec.js.coffee
timobleeker/dotledger
0
$.plot = $.noop describe "DotLedger.Views.Accounts.Show", -> createView = -> balances = new DotLedger.Collections.Balances model = new DotLedger.Models.Account name: 'Some Account' type: 'Savings' number: '123' id: 1 unsorted_transaction_count: 5 sorted_transaction_count: 10 review_transaction_count: 15 balance: 123.45 view = new DotLedger.Views.Accounts.Show model: model balances: balances view it "should be defined", -> expect(DotLedger.Views.Accounts.Show).toBeDefined() it "should use the correct template", -> expect(DotLedger.Views.Accounts.Show).toUseTemplate('accounts/show') it "can be rendered", -> view = createView() expect(view.render).not.toThrow() it "renders the account name", -> view = createView().render() expect(view.$el).toHaveText(/Some Account/) it "renders the account type", -> view = createView().render() expect(view.$el).toHaveText(/Savings/) it "renders the account number", -> view = createView().render() expect(view.$el).toHaveText(/123/) it "renders the account balance", -> view = createView().render() expect(view.$el).toHaveText(/\$123.45/) it "renders the account edit link", -> view = createView().render() expect(view.$el).toContainElement('a[href="/accounts/1/edit"]') it "renders the statement import link", -> view = createView().render() expect(view.$el).toContainElement('a[href="/accounts/1/import"]') it "renders the sorted transactions tab link", -> view = createView().render() expect(view.$el).toContainElement('a[href="/accounts/1/sorted"]') it "renders the sorted transactions tab label with count", -> view = createView().render() expect(view.$el).toContainText(/Sorted 10/) it "renders the review transactions tab link", -> view = createView().render() expect(view.$el).toContainElement('a[href="/accounts/1/review"]') it "renders the unsorted transactions tab label with count", -> view = createView().render() expect(view.$el).toContainText(/Unsorted 5/) it "renders the unsorted transactions tab link", -> view = createView().render() expect(view.$el).toContainElement('a[href="/accounts/1/unsorted"]') it "renders the review transactions tab label with count", -> view = createView().render() expect(view.$el).toContainText(/Review 15/)
96030
$.plot = $.noop describe "DotLedger.Views.Accounts.Show", -> createView = -> balances = new DotLedger.Collections.Balances model = new DotLedger.Models.Account name: '<NAME>' type: 'Savings' number: '123' id: 1 unsorted_transaction_count: 5 sorted_transaction_count: 10 review_transaction_count: 15 balance: 123.45 view = new DotLedger.Views.Accounts.Show model: model balances: balances view it "should be defined", -> expect(DotLedger.Views.Accounts.Show).toBeDefined() it "should use the correct template", -> expect(DotLedger.Views.Accounts.Show).toUseTemplate('accounts/show') it "can be rendered", -> view = createView() expect(view.render).not.toThrow() it "renders the account name", -> view = createView().render() expect(view.$el).toHaveText(/Some Account/) it "renders the account type", -> view = createView().render() expect(view.$el).toHaveText(/Savings/) it "renders the account number", -> view = createView().render() expect(view.$el).toHaveText(/123/) it "renders the account balance", -> view = createView().render() expect(view.$el).toHaveText(/\$123.45/) it "renders the account edit link", -> view = createView().render() expect(view.$el).toContainElement('a[href="/accounts/1/edit"]') it "renders the statement import link", -> view = createView().render() expect(view.$el).toContainElement('a[href="/accounts/1/import"]') it "renders the sorted transactions tab link", -> view = createView().render() expect(view.$el).toContainElement('a[href="/accounts/1/sorted"]') it "renders the sorted transactions tab label with count", -> view = createView().render() expect(view.$el).toContainText(/Sorted 10/) it "renders the review transactions tab link", -> view = createView().render() expect(view.$el).toContainElement('a[href="/accounts/1/review"]') it "renders the unsorted transactions tab label with count", -> view = createView().render() expect(view.$el).toContainText(/Unsorted 5/) it "renders the unsorted transactions tab link", -> view = createView().render() expect(view.$el).toContainElement('a[href="/accounts/1/unsorted"]') it "renders the review transactions tab label with count", -> view = createView().render() expect(view.$el).toContainText(/Review 15/)
true
$.plot = $.noop describe "DotLedger.Views.Accounts.Show", -> createView = -> balances = new DotLedger.Collections.Balances model = new DotLedger.Models.Account name: 'PI:NAME:<NAME>END_PI' type: 'Savings' number: '123' id: 1 unsorted_transaction_count: 5 sorted_transaction_count: 10 review_transaction_count: 15 balance: 123.45 view = new DotLedger.Views.Accounts.Show model: model balances: balances view it "should be defined", -> expect(DotLedger.Views.Accounts.Show).toBeDefined() it "should use the correct template", -> expect(DotLedger.Views.Accounts.Show).toUseTemplate('accounts/show') it "can be rendered", -> view = createView() expect(view.render).not.toThrow() it "renders the account name", -> view = createView().render() expect(view.$el).toHaveText(/Some Account/) it "renders the account type", -> view = createView().render() expect(view.$el).toHaveText(/Savings/) it "renders the account number", -> view = createView().render() expect(view.$el).toHaveText(/123/) it "renders the account balance", -> view = createView().render() expect(view.$el).toHaveText(/\$123.45/) it "renders the account edit link", -> view = createView().render() expect(view.$el).toContainElement('a[href="/accounts/1/edit"]') it "renders the statement import link", -> view = createView().render() expect(view.$el).toContainElement('a[href="/accounts/1/import"]') it "renders the sorted transactions tab link", -> view = createView().render() expect(view.$el).toContainElement('a[href="/accounts/1/sorted"]') it "renders the sorted transactions tab label with count", -> view = createView().render() expect(view.$el).toContainText(/Sorted 10/) it "renders the review transactions tab link", -> view = createView().render() expect(view.$el).toContainElement('a[href="/accounts/1/review"]') it "renders the unsorted transactions tab label with count", -> view = createView().render() expect(view.$el).toContainText(/Unsorted 5/) it "renders the unsorted transactions tab link", -> view = createView().render() expect(view.$el).toContainElement('a[href="/accounts/1/unsorted"]') it "renders the review transactions tab label with count", -> view = createView().render() expect(view.$el).toContainText(/Review 15/)
[ { "context": "S_HOST)\n\npubnub = PUBNUB.init(\n subscribe_key : 'demo' # you should change this!\n publish_key : 'dem", "end": 682, "score": 0.9012205004692078, "start": 678, "tag": "KEY", "value": "demo" }, { "context": "emo' # you should change this!\n publish_key : 'demo' # you should change this!\n)\n\n#\n# Set up a client", "end": 733, "score": 0.8416771292686462, "start": 729, "tag": "KEY", "value": "demo" } ]
src/pubnub-redis-listen-proxy.coffee
sunnygleason/pubnub-persistence-redis
2
# # PubNub Persistence: node.js replication proxy listener # # "Connecting your worldwide apps to redis updates within 250ms" # # Usage: coffee src/pubnub-redis-listen-proxy.coffee CHANNEL_NAME REDIS_ADDR # - where CHANNEL_NAME is the Redis channel to receive updates # - where REDIS_ADDR is the host:port # PUBNUB = require('../deps/pubnub-javascript/node.js/pubnub.js') redis = require('../deps/node_redis/index.js') CHANNEL = process.argv[2] REDIS_ADDR = (process.argv[3] || 'localhost:6379').split(":") REDIS_HOST = REDIS_ADDR[0] REDIS_PORT = REDIS_ADDR[1] client = redis.createClient(REDIS_PORT, REDIS_HOST) pubnub = PUBNUB.init( subscribe_key : 'demo' # you should change this! publish_key : 'demo' # you should change this! ) # # Set up a client replicator - we replay updates to the redis client # pubnub.subscribe({ channel:CHANNEL message: (command) => commandStr = JSON.stringify(command) if command.type == "entity" console.log "updating redis with entity:", commandStr client.set(command.entity[1], command.entity[2]) else console.log "updating redis with command:", commandStr client.send_command(command.command, command.args) }) console.log "Listening to PubNub redis channel \##{CHANNEL}, replaying to redis instance at #{REDIS_ADDR}"
109762
# # PubNub Persistence: node.js replication proxy listener # # "Connecting your worldwide apps to redis updates within 250ms" # # Usage: coffee src/pubnub-redis-listen-proxy.coffee CHANNEL_NAME REDIS_ADDR # - where CHANNEL_NAME is the Redis channel to receive updates # - where REDIS_ADDR is the host:port # PUBNUB = require('../deps/pubnub-javascript/node.js/pubnub.js') redis = require('../deps/node_redis/index.js') CHANNEL = process.argv[2] REDIS_ADDR = (process.argv[3] || 'localhost:6379').split(":") REDIS_HOST = REDIS_ADDR[0] REDIS_PORT = REDIS_ADDR[1] client = redis.createClient(REDIS_PORT, REDIS_HOST) pubnub = PUBNUB.init( subscribe_key : '<KEY>' # you should change this! publish_key : '<KEY>' # you should change this! ) # # Set up a client replicator - we replay updates to the redis client # pubnub.subscribe({ channel:CHANNEL message: (command) => commandStr = JSON.stringify(command) if command.type == "entity" console.log "updating redis with entity:", commandStr client.set(command.entity[1], command.entity[2]) else console.log "updating redis with command:", commandStr client.send_command(command.command, command.args) }) console.log "Listening to PubNub redis channel \##{CHANNEL}, replaying to redis instance at #{REDIS_ADDR}"
true
# # PubNub Persistence: node.js replication proxy listener # # "Connecting your worldwide apps to redis updates within 250ms" # # Usage: coffee src/pubnub-redis-listen-proxy.coffee CHANNEL_NAME REDIS_ADDR # - where CHANNEL_NAME is the Redis channel to receive updates # - where REDIS_ADDR is the host:port # PUBNUB = require('../deps/pubnub-javascript/node.js/pubnub.js') redis = require('../deps/node_redis/index.js') CHANNEL = process.argv[2] REDIS_ADDR = (process.argv[3] || 'localhost:6379').split(":") REDIS_HOST = REDIS_ADDR[0] REDIS_PORT = REDIS_ADDR[1] client = redis.createClient(REDIS_PORT, REDIS_HOST) pubnub = PUBNUB.init( subscribe_key : 'PI:KEY:<KEY>END_PI' # you should change this! publish_key : 'PI:KEY:<KEY>END_PI' # you should change this! ) # # Set up a client replicator - we replay updates to the redis client # pubnub.subscribe({ channel:CHANNEL message: (command) => commandStr = JSON.stringify(command) if command.type == "entity" console.log "updating redis with entity:", commandStr client.set(command.entity[1], command.entity[2]) else console.log "updating redis with command:", commandStr client.send_command(command.command, command.args) }) console.log "Listening to PubNub redis channel \##{CHANNEL}, replaying to redis instance at #{REDIS_ADDR}"
[ { "context": "\n summoner: Mithril #the Greater Power\n name: 'Mithril' # his name\n Component: class Component\n c", "end": 298, "score": 0.9932987093925476, "start": 291, "tag": "NAME", "value": "Mithril" } ]
src/halvalla-mithril.coffee
jahbini/halvalla
2
# Mithril=require 'mithril' # # Halvalla.render defaults to HTML via internal teacup rendering engine # which is smart enough to recognize mithril's quirks # use Halvalla.render to get server-side, Mithril.render to get client side. Oracle = summoner: Mithril #the Greater Power name: 'Mithril' # his name Component: class Component constructor: (vnode)-> for key,value of vnode @key=value return null createElement: Mithril #he creates without hassle, but requires us to preInstantiate: true # instantiate the whole virtual DOM before rendering getChildren: (element)->element.children getProp: (element)->element.attrs # where does mithril stash this info? propertyName: 'attrs' getName: (element)->element._Halvalla?.tagName|| element.tagName || element.tag trust: (text)-> Mithril.trust text # how to specify unescaped text #require the Halvalla engine, but throw away it's default Oracle's tags {Halvalla} = require '../lib/halvalla' # create a new Halvalla with new overrides #export identically to the original Halvalla module.exports= (new Halvalla Oracle).tags() module.exports.Halvalla =Halvalla
67471
# Mithril=require 'mithril' # # Halvalla.render defaults to HTML via internal teacup rendering engine # which is smart enough to recognize mithril's quirks # use Halvalla.render to get server-side, Mithril.render to get client side. Oracle = summoner: Mithril #the Greater Power name: '<NAME>' # his name Component: class Component constructor: (vnode)-> for key,value of vnode @key=value return null createElement: Mithril #he creates without hassle, but requires us to preInstantiate: true # instantiate the whole virtual DOM before rendering getChildren: (element)->element.children getProp: (element)->element.attrs # where does mithril stash this info? propertyName: 'attrs' getName: (element)->element._Halvalla?.tagName|| element.tagName || element.tag trust: (text)-> Mithril.trust text # how to specify unescaped text #require the Halvalla engine, but throw away it's default Oracle's tags {Halvalla} = require '../lib/halvalla' # create a new Halvalla with new overrides #export identically to the original Halvalla module.exports= (new Halvalla Oracle).tags() module.exports.Halvalla =Halvalla
true
# Mithril=require 'mithril' # # Halvalla.render defaults to HTML via internal teacup rendering engine # which is smart enough to recognize mithril's quirks # use Halvalla.render to get server-side, Mithril.render to get client side. Oracle = summoner: Mithril #the Greater Power name: 'PI:NAME:<NAME>END_PI' # his name Component: class Component constructor: (vnode)-> for key,value of vnode @key=value return null createElement: Mithril #he creates without hassle, but requires us to preInstantiate: true # instantiate the whole virtual DOM before rendering getChildren: (element)->element.children getProp: (element)->element.attrs # where does mithril stash this info? propertyName: 'attrs' getName: (element)->element._Halvalla?.tagName|| element.tagName || element.tag trust: (text)-> Mithril.trust text # how to specify unescaped text #require the Halvalla engine, but throw away it's default Oracle's tags {Halvalla} = require '../lib/halvalla' # create a new Halvalla with new overrides #export identically to the original Halvalla module.exports= (new Halvalla Oracle).tags() module.exports.Halvalla =Halvalla
[ { "context": "ModifierCostEqualGeneralHealth\"\n\n\t@modifierName: \"Raging Taura\"\n\t@description:\"This minion's cost is equal to yo", "end": 197, "score": 0.999642014503479, "start": 185, "tag": "NAME", "value": "Raging Taura" } ]
app/sdk/modifiers/modifierCostEqualGeneralHealth.coffee
willroberts/duelyst
5
Modifier = require './modifier' class ModifierCostEqualGeneralHealth extends Modifier type:"ModifierCostEqualGeneralHealth" @type:"ModifierCostEqualGeneralHealth" @modifierName: "Raging Taura" @description:"This minion's cost is equal to your General's Health" activeInDeck: false activeInHand: true activeInSignatureCards: false activeOnBoard: true maxStacks: 1 constructor: (gameSession) -> super(gameSession) @attributeBuffsAbsolute = ["manaCost"] @attributeBuffsFixed = ["manaCost"] getPrivateDefaults: (gameSession) -> p = super(gameSession) p.cachedManaCost = 0 return p getBuffedAttribute: (attributeValue, buffKey) -> if buffKey == "manaCost" return @_private.cachedManaCost else return super(attributeValue, buffKey) getBuffsAttributes: () -> return true getBuffsAttribute: (buffKey) -> return buffKey == "manaCost" or super(buffKey) updateCachedStateAfterActive: () -> super() card = @getCard() owner = card?.getOwner() general = @getGameSession().getGeneralForPlayer(owner) manaCost = 0 if general? manaCost = Math.max(0, general.getHP()) else manaCost = 0 if @_private.cachedManaCost != manaCost @_private.cachedManaCost = manaCost @getCard().flushCachedAttribute("manaCost") module.exports = ModifierCostEqualGeneralHealth
98431
Modifier = require './modifier' class ModifierCostEqualGeneralHealth extends Modifier type:"ModifierCostEqualGeneralHealth" @type:"ModifierCostEqualGeneralHealth" @modifierName: "<NAME>" @description:"This minion's cost is equal to your General's Health" activeInDeck: false activeInHand: true activeInSignatureCards: false activeOnBoard: true maxStacks: 1 constructor: (gameSession) -> super(gameSession) @attributeBuffsAbsolute = ["manaCost"] @attributeBuffsFixed = ["manaCost"] getPrivateDefaults: (gameSession) -> p = super(gameSession) p.cachedManaCost = 0 return p getBuffedAttribute: (attributeValue, buffKey) -> if buffKey == "manaCost" return @_private.cachedManaCost else return super(attributeValue, buffKey) getBuffsAttributes: () -> return true getBuffsAttribute: (buffKey) -> return buffKey == "manaCost" or super(buffKey) updateCachedStateAfterActive: () -> super() card = @getCard() owner = card?.getOwner() general = @getGameSession().getGeneralForPlayer(owner) manaCost = 0 if general? manaCost = Math.max(0, general.getHP()) else manaCost = 0 if @_private.cachedManaCost != manaCost @_private.cachedManaCost = manaCost @getCard().flushCachedAttribute("manaCost") module.exports = ModifierCostEqualGeneralHealth
true
Modifier = require './modifier' class ModifierCostEqualGeneralHealth extends Modifier type:"ModifierCostEqualGeneralHealth" @type:"ModifierCostEqualGeneralHealth" @modifierName: "PI:NAME:<NAME>END_PI" @description:"This minion's cost is equal to your General's Health" activeInDeck: false activeInHand: true activeInSignatureCards: false activeOnBoard: true maxStacks: 1 constructor: (gameSession) -> super(gameSession) @attributeBuffsAbsolute = ["manaCost"] @attributeBuffsFixed = ["manaCost"] getPrivateDefaults: (gameSession) -> p = super(gameSession) p.cachedManaCost = 0 return p getBuffedAttribute: (attributeValue, buffKey) -> if buffKey == "manaCost" return @_private.cachedManaCost else return super(attributeValue, buffKey) getBuffsAttributes: () -> return true getBuffsAttribute: (buffKey) -> return buffKey == "manaCost" or super(buffKey) updateCachedStateAfterActive: () -> super() card = @getCard() owner = card?.getOwner() general = @getGameSession().getGeneralForPlayer(owner) manaCost = 0 if general? manaCost = Math.max(0, general.getHP()) else manaCost = 0 if @_private.cachedManaCost != manaCost @_private.cachedManaCost = manaCost @getCard().flushCachedAttribute("manaCost") module.exports = ModifierCostEqualGeneralHealth
[ { "context": "lves({\n branch: \"master\",\n author: \"brian\",\n email: \"brian@cypress.io\",\n mess", "end": 2436, "score": 0.9775152802467346, "start": 2431, "tag": "USERNAME", "value": "brian" }, { "context": "master\",\n author: \"brian\",\n email: \"brian@cypress.io\",\n message: \"such hax\",\n sha: \"sha-", "end": 2471, "score": 0.9999215006828308, "start": 2455, "tag": "EMAIL", "value": "brian@cypress.io" }, { "context": "i.createRun with the right args\", ->\n key = \"recordKey\"\n projectId = \"pId123\"\n specPattern ", "end": 2705, "score": 0.5349992513656616, "start": 2699, "tag": "KEY", "value": "record" }, { "context": " branch: \"master\",\n authorName: \"brian\",\n authorEmail: \"brian@cypress.io\",\n ", "end": 3937, "score": 0.9943622946739197, "start": 3932, "tag": "USERNAME", "value": "brian" }, { "context": " authorName: \"brian\",\n authorEmail: \"brian@cypress.io\",\n message: \"such hax\",\n re", "end": 3982, "score": 0.9999220967292786, "start": 3966, "tag": "EMAIL", "value": "brian@cypress.io" } ]
packages/server/test/unit/modes/record_spec.coffee
Manduro/cypress
0
require("../../spec_helper") _ = require("lodash") os = require("os") commitInfo = require("@cypress/commit-info") api = require("#{root}../lib/api") errors = require("#{root}../lib/errors") logger = require("#{root}../lib/logger") upload = require("#{root}../lib/upload") browsers = require("#{root}../lib/browsers") recordMode = require("#{root}../lib/modes/record") system = require("#{root}../lib/util/system") ciProvider = require("#{root}../lib/util/ci_provider") initialEnv = _.clone(process.env) ## NOTE: the majority of the logic of record_spec is ## tested as an e2e/record_spec describe "lib/modes/record", -> ## QUESTION: why are these tests here when ## this is a module... ? context "commitInfo.getBranch", -> beforeEach -> delete process.env.CIRCLE_BRANCH delete process.env.TRAVIS_BRANCH delete process.env.BUILDKITE_BRANCH delete process.env.CI_BRANCH afterEach -> process.env = initialEnv it "gets branch from process.env.CIRCLE_BRANCH", -> process.env.CIRCLE_BRANCH = "bem/circle" process.env.TRAVIS_BRANCH = "bem/travis" process.env.CI_BRANCH = "bem/ci" commitInfo.getBranch().then (ret) -> expect(ret).to.eq("bem/circle") it "gets branch from process.env.TRAVIS_BRANCH", -> process.env.TRAVIS_BRANCH = "bem/travis" process.env.CI_BRANCH = "bem/ci" commitInfo.getBranch().then (ret) -> expect(ret).to.eq("bem/travis") it "gets branch from process.env.BUILDKITE_BRANCH", -> process.env.BUILDKITE_BRANCH = "bem/buildkite" process.env.CI_BRANCH = "bem/ci" commitInfo.getBranch().then (ret) -> expect(ret).to.eq("bem/buildkite") it "gets branch from process.env.CI_BRANCH", -> process.env.CI_BRANCH = "bem/ci" commitInfo.getBranch().then (ret) -> expect(ret).to.eq("bem/ci") it "gets branch from git" # this is tested inside @cypress/commit-info context ".createRunAndRecordSpecs", -> specs = [ { path: "path/to/spec/a" }, { path: "path/to/spec/b" } ] beforeEach -> sinon.stub(ciProvider, "name").returns("circle") sinon.stub(ciProvider, "params").returns({foo: "bar"}) sinon.stub(ciProvider, "buildNum").returns("build-123") sinon.stub(commitInfo, "commitInfo").resolves({ branch: "master", author: "brian", email: "brian@cypress.io", message: "such hax", sha: "sha-123", remote: "https://github.com/foo/bar.git" }) sinon.stub(api, "createRun").resolves() it "calls api.createRun with the right args", -> key = "recordKey" projectId = "pId123" specPattern = ["spec/pattern1", "spec/pattern2"] projectRoot = "project/root" runAllSpecs = sinon.stub() sys = { osCpus: 1 osName: 2 osMemory: 3 osVersion: 4 } browser = { displayName: "chrome" version: "59" } recordMode.createRunAndRecordSpecs({ key sys specs browser projectId projectRoot specPattern runAllSpecs }) .then -> expect(commitInfo.commitInfo).to.be.calledWith(projectRoot) expect(api.createRun).to.be.calledWith({ projectId recordKey: key specPattern: "spec/pattern1,spec/pattern2" specs: ["path/to/spec/a", "path/to/spec/b"] platform: { osCpus: 1 osName: 2 osMemory: 3 osVersion: 4 browserName: "chrome" browserVersion: "59" } ci: { params: {foo: "bar"} provider: "circle" buildNumber: "build-123" } commit: { sha: "sha-123", branch: "master", authorName: "brian", authorEmail: "brian@cypress.io", message: "such hax", remoteOrigin: "https://github.com/foo/bar.git" } }) context ".updateInstanceStdout", -> beforeEach -> sinon.stub(api, "updateInstanceStdout") it "calls api.updateInstanceStdout", -> api.updateInstanceStdout.resolves() options = { instanceId: "id-123" captured: { toString: -> "foobarbaz\n" } } recordMode.updateInstanceStdout(options) .then -> expect(api.updateInstanceStdout).to.be.calledWith({ instanceId: "id-123" stdout: "foobarbaz\n" }) it "does not createException when statusCode is 503", -> err = new Error("foo") err.statusCode = 503 sinon.spy(logger, "createException") api.updateInstanceStdout.rejects(err) options = { instanceId: "id-123" captured: { toString: -> "foobarbaz\n" } } recordMode.updateInstanceStdout(options) .then -> expect(logger.createException).not.to.be.called context ".createInstance", -> beforeEach -> sinon.stub(api, "createInstance") it "calls api.createInstance", -> api.createInstance.resolves() recordMode.createInstance({ runId: "run-123", groupId: "group-123" machineId: "machine-123" platform: {} spec: { path: "cypress/integration/app_spec.coffee" } }) .then -> expect(api.createInstance).to.be.calledWith({ runId: "run-123", groupId: "group-123" machineId: "machine-123" platform: {} spec: "cypress/integration/app_spec.coffee" }) it "does not createException when statusCode is 503", -> err = new Error("foo") err.statusCode = 503 sinon.spy(logger, "createException") api.createInstance.rejects(err) recordMode.createInstance({ runId: "run-123", groupId: "group-123" machineId: "machine-123" platform: {} spec: { path: "cypress/integration/app_spec.coffee" } }) .then (ret) -> expect(ret).to.be.null expect(logger.createException).not.to.be.called
198179
require("../../spec_helper") _ = require("lodash") os = require("os") commitInfo = require("@cypress/commit-info") api = require("#{root}../lib/api") errors = require("#{root}../lib/errors") logger = require("#{root}../lib/logger") upload = require("#{root}../lib/upload") browsers = require("#{root}../lib/browsers") recordMode = require("#{root}../lib/modes/record") system = require("#{root}../lib/util/system") ciProvider = require("#{root}../lib/util/ci_provider") initialEnv = _.clone(process.env) ## NOTE: the majority of the logic of record_spec is ## tested as an e2e/record_spec describe "lib/modes/record", -> ## QUESTION: why are these tests here when ## this is a module... ? context "commitInfo.getBranch", -> beforeEach -> delete process.env.CIRCLE_BRANCH delete process.env.TRAVIS_BRANCH delete process.env.BUILDKITE_BRANCH delete process.env.CI_BRANCH afterEach -> process.env = initialEnv it "gets branch from process.env.CIRCLE_BRANCH", -> process.env.CIRCLE_BRANCH = "bem/circle" process.env.TRAVIS_BRANCH = "bem/travis" process.env.CI_BRANCH = "bem/ci" commitInfo.getBranch().then (ret) -> expect(ret).to.eq("bem/circle") it "gets branch from process.env.TRAVIS_BRANCH", -> process.env.TRAVIS_BRANCH = "bem/travis" process.env.CI_BRANCH = "bem/ci" commitInfo.getBranch().then (ret) -> expect(ret).to.eq("bem/travis") it "gets branch from process.env.BUILDKITE_BRANCH", -> process.env.BUILDKITE_BRANCH = "bem/buildkite" process.env.CI_BRANCH = "bem/ci" commitInfo.getBranch().then (ret) -> expect(ret).to.eq("bem/buildkite") it "gets branch from process.env.CI_BRANCH", -> process.env.CI_BRANCH = "bem/ci" commitInfo.getBranch().then (ret) -> expect(ret).to.eq("bem/ci") it "gets branch from git" # this is tested inside @cypress/commit-info context ".createRunAndRecordSpecs", -> specs = [ { path: "path/to/spec/a" }, { path: "path/to/spec/b" } ] beforeEach -> sinon.stub(ciProvider, "name").returns("circle") sinon.stub(ciProvider, "params").returns({foo: "bar"}) sinon.stub(ciProvider, "buildNum").returns("build-123") sinon.stub(commitInfo, "commitInfo").resolves({ branch: "master", author: "brian", email: "<EMAIL>", message: "such hax", sha: "sha-123", remote: "https://github.com/foo/bar.git" }) sinon.stub(api, "createRun").resolves() it "calls api.createRun with the right args", -> key = "<KEY>Key" projectId = "pId123" specPattern = ["spec/pattern1", "spec/pattern2"] projectRoot = "project/root" runAllSpecs = sinon.stub() sys = { osCpus: 1 osName: 2 osMemory: 3 osVersion: 4 } browser = { displayName: "chrome" version: "59" } recordMode.createRunAndRecordSpecs({ key sys specs browser projectId projectRoot specPattern runAllSpecs }) .then -> expect(commitInfo.commitInfo).to.be.calledWith(projectRoot) expect(api.createRun).to.be.calledWith({ projectId recordKey: key specPattern: "spec/pattern1,spec/pattern2" specs: ["path/to/spec/a", "path/to/spec/b"] platform: { osCpus: 1 osName: 2 osMemory: 3 osVersion: 4 browserName: "chrome" browserVersion: "59" } ci: { params: {foo: "bar"} provider: "circle" buildNumber: "build-123" } commit: { sha: "sha-123", branch: "master", authorName: "brian", authorEmail: "<EMAIL>", message: "such hax", remoteOrigin: "https://github.com/foo/bar.git" } }) context ".updateInstanceStdout", -> beforeEach -> sinon.stub(api, "updateInstanceStdout") it "calls api.updateInstanceStdout", -> api.updateInstanceStdout.resolves() options = { instanceId: "id-123" captured: { toString: -> "foobarbaz\n" } } recordMode.updateInstanceStdout(options) .then -> expect(api.updateInstanceStdout).to.be.calledWith({ instanceId: "id-123" stdout: "foobarbaz\n" }) it "does not createException when statusCode is 503", -> err = new Error("foo") err.statusCode = 503 sinon.spy(logger, "createException") api.updateInstanceStdout.rejects(err) options = { instanceId: "id-123" captured: { toString: -> "foobarbaz\n" } } recordMode.updateInstanceStdout(options) .then -> expect(logger.createException).not.to.be.called context ".createInstance", -> beforeEach -> sinon.stub(api, "createInstance") it "calls api.createInstance", -> api.createInstance.resolves() recordMode.createInstance({ runId: "run-123", groupId: "group-123" machineId: "machine-123" platform: {} spec: { path: "cypress/integration/app_spec.coffee" } }) .then -> expect(api.createInstance).to.be.calledWith({ runId: "run-123", groupId: "group-123" machineId: "machine-123" platform: {} spec: "cypress/integration/app_spec.coffee" }) it "does not createException when statusCode is 503", -> err = new Error("foo") err.statusCode = 503 sinon.spy(logger, "createException") api.createInstance.rejects(err) recordMode.createInstance({ runId: "run-123", groupId: "group-123" machineId: "machine-123" platform: {} spec: { path: "cypress/integration/app_spec.coffee" } }) .then (ret) -> expect(ret).to.be.null expect(logger.createException).not.to.be.called
true
require("../../spec_helper") _ = require("lodash") os = require("os") commitInfo = require("@cypress/commit-info") api = require("#{root}../lib/api") errors = require("#{root}../lib/errors") logger = require("#{root}../lib/logger") upload = require("#{root}../lib/upload") browsers = require("#{root}../lib/browsers") recordMode = require("#{root}../lib/modes/record") system = require("#{root}../lib/util/system") ciProvider = require("#{root}../lib/util/ci_provider") initialEnv = _.clone(process.env) ## NOTE: the majority of the logic of record_spec is ## tested as an e2e/record_spec describe "lib/modes/record", -> ## QUESTION: why are these tests here when ## this is a module... ? context "commitInfo.getBranch", -> beforeEach -> delete process.env.CIRCLE_BRANCH delete process.env.TRAVIS_BRANCH delete process.env.BUILDKITE_BRANCH delete process.env.CI_BRANCH afterEach -> process.env = initialEnv it "gets branch from process.env.CIRCLE_BRANCH", -> process.env.CIRCLE_BRANCH = "bem/circle" process.env.TRAVIS_BRANCH = "bem/travis" process.env.CI_BRANCH = "bem/ci" commitInfo.getBranch().then (ret) -> expect(ret).to.eq("bem/circle") it "gets branch from process.env.TRAVIS_BRANCH", -> process.env.TRAVIS_BRANCH = "bem/travis" process.env.CI_BRANCH = "bem/ci" commitInfo.getBranch().then (ret) -> expect(ret).to.eq("bem/travis") it "gets branch from process.env.BUILDKITE_BRANCH", -> process.env.BUILDKITE_BRANCH = "bem/buildkite" process.env.CI_BRANCH = "bem/ci" commitInfo.getBranch().then (ret) -> expect(ret).to.eq("bem/buildkite") it "gets branch from process.env.CI_BRANCH", -> process.env.CI_BRANCH = "bem/ci" commitInfo.getBranch().then (ret) -> expect(ret).to.eq("bem/ci") it "gets branch from git" # this is tested inside @cypress/commit-info context ".createRunAndRecordSpecs", -> specs = [ { path: "path/to/spec/a" }, { path: "path/to/spec/b" } ] beforeEach -> sinon.stub(ciProvider, "name").returns("circle") sinon.stub(ciProvider, "params").returns({foo: "bar"}) sinon.stub(ciProvider, "buildNum").returns("build-123") sinon.stub(commitInfo, "commitInfo").resolves({ branch: "master", author: "brian", email: "PI:EMAIL:<EMAIL>END_PI", message: "such hax", sha: "sha-123", remote: "https://github.com/foo/bar.git" }) sinon.stub(api, "createRun").resolves() it "calls api.createRun with the right args", -> key = "PI:KEY:<KEY>END_PIKey" projectId = "pId123" specPattern = ["spec/pattern1", "spec/pattern2"] projectRoot = "project/root" runAllSpecs = sinon.stub() sys = { osCpus: 1 osName: 2 osMemory: 3 osVersion: 4 } browser = { displayName: "chrome" version: "59" } recordMode.createRunAndRecordSpecs({ key sys specs browser projectId projectRoot specPattern runAllSpecs }) .then -> expect(commitInfo.commitInfo).to.be.calledWith(projectRoot) expect(api.createRun).to.be.calledWith({ projectId recordKey: key specPattern: "spec/pattern1,spec/pattern2" specs: ["path/to/spec/a", "path/to/spec/b"] platform: { osCpus: 1 osName: 2 osMemory: 3 osVersion: 4 browserName: "chrome" browserVersion: "59" } ci: { params: {foo: "bar"} provider: "circle" buildNumber: "build-123" } commit: { sha: "sha-123", branch: "master", authorName: "brian", authorEmail: "PI:EMAIL:<EMAIL>END_PI", message: "such hax", remoteOrigin: "https://github.com/foo/bar.git" } }) context ".updateInstanceStdout", -> beforeEach -> sinon.stub(api, "updateInstanceStdout") it "calls api.updateInstanceStdout", -> api.updateInstanceStdout.resolves() options = { instanceId: "id-123" captured: { toString: -> "foobarbaz\n" } } recordMode.updateInstanceStdout(options) .then -> expect(api.updateInstanceStdout).to.be.calledWith({ instanceId: "id-123" stdout: "foobarbaz\n" }) it "does not createException when statusCode is 503", -> err = new Error("foo") err.statusCode = 503 sinon.spy(logger, "createException") api.updateInstanceStdout.rejects(err) options = { instanceId: "id-123" captured: { toString: -> "foobarbaz\n" } } recordMode.updateInstanceStdout(options) .then -> expect(logger.createException).not.to.be.called context ".createInstance", -> beforeEach -> sinon.stub(api, "createInstance") it "calls api.createInstance", -> api.createInstance.resolves() recordMode.createInstance({ runId: "run-123", groupId: "group-123" machineId: "machine-123" platform: {} spec: { path: "cypress/integration/app_spec.coffee" } }) .then -> expect(api.createInstance).to.be.calledWith({ runId: "run-123", groupId: "group-123" machineId: "machine-123" platform: {} spec: "cypress/integration/app_spec.coffee" }) it "does not createException when statusCode is 503", -> err = new Error("foo") err.statusCode = 503 sinon.spy(logger, "createException") api.createInstance.rejects(err) recordMode.createInstance({ runId: "run-123", groupId: "group-123" machineId: "machine-123" platform: {} spec: { path: "cypress/integration/app_spec.coffee" } }) .then (ret) -> expect(ret).to.be.null expect(logger.createException).not.to.be.called
[ { "context": "constructor: (username, password) ->\n\t\t@username = username\n\t\t@password = password\n\n\t# Get the basic info of ", "end": 548, "score": 0.9849773645401001, "start": 540, "tag": "USERNAME", "value": "username" }, { "context": " password) ->\n\t\t@username = username\n\t\t@password = password\n\n\t# Get the basic info of the list\n\tgetInfo: (suc", "end": 571, "score": 0.9981276392936707, "start": 563, "tag": "PASSWORD", "value": "password" }, { "context": "/\" + path \\\n\t\t\t+ \"?username=\" + encodeURIComponent(@username) \\\n\t\t\t+ \"&password=\" + encodeURIComponent(@passwo", "end": 1900, "score": 0.9994399547576904, "start": 1891, "tag": "USERNAME", "value": "@username" }, { "context": "username) \\\n\t\t\t+ \"&password=\" + encodeURIComponent(@password) \\\n\t\t\t+ (if data then \"&\" + data else \"\")\n\n\t\t# Re", "end": 1952, "score": 0.9861523509025574, "start": 1943, "tag": "PASSWORD", "value": "@password" }, { "context": "min.set \"credentials\",\n\t\tusername: \"\",\n\t\tpassword: \"\"\n\tDb.shared.set \"lastSync\",\n\t\tinfo: 0,\n\t\tnoticeboa", "end": 4048, "score": 0.9114997982978821, "start": 4048, "tag": "PASSWORD", "value": "" } ]
server.coffee
basilfx/Happening-eetlijst
0
Db = require "db" Plugin = require "plugin" Http = require "http" Event = require "event" Timer = require "timer" TIMEOUT_INFO = (1000 * 60 * 60) TIMEOUT_STATUS = (1000 * 60 * 5) TIMEOUT_NOTICEBOARD = (1000 * 60 * 5) # Temporary solution for the lack of scraping and requests support in Happening. # Uses external proxy to convert results into JSON format class ProxiedEetlijst # API URl without trailing slash API_URL = "http://eetlijst.apps.basilfx.net" # Construct new instance. constructor: (username, password) -> @username = username @password = password # Get the basic info of the list getInfo: (success, error) -> @get("info", null, success, error) # Get the contents of the noticeboard. The response is a string. getNoticeboard: (success, error) -> @get("noticeboard", null, success, error) # Set the contents of the noticeboard. setNoticeboard: (content, success, error) -> data = "content=" + encodeURIComponent(content) @post("noticeboard", data, success, error) # Get the status getStatus: (success, error) -> @get("status", null, success, error) # Set the status setStatus: (resident, value, timestamp, success, error) -> data = "resident=" + encodeURIComponent(resident) \ + "&value=" + encodeURIComponent(value) \ + "&timestamp=" + encodeURIComponent(timestamp) @post("status", data, success, error) # Shortcut for request(Http.get, path, data) get: (path, data, success, error) -> m = (d) -> Http.get(d) @request(m, path, data, success, error) # Shortcut for request(Http.post, path, data) post: (path, data, success, error) -> m = (d) -> Http.post(d) @request(m, path, data, success, error) # Invoke a request. Build URL and add username/password. Data should be a # encoded querystring. request: (method, path, data, success, error) !-> url = API_URL + "/" + path \ + "?username=" + encodeURIComponent(@username) \ + "&password=" + encodeURIComponent(@password) \ + (if data then "&" + data else "") # Request response log "Calling URL: " + url # Invoke method try response = method url: url args: [success, error] catch log "Could not invoke request" exports[error]() # Build a new Eetlijst instance, with the given credentials, or the ones stored # in the shared database. Returns a new instance, or none if username and/or # password not configured. getInstance = (credentials) -> credentials = credentials or Db.admin.get("credentials") if not credentials or not credentials.username or not credentials.password log "Missing username and/or password" return new ProxiedEetlijst(credentials.username, credentials.password) # Update Eetlijst data update = !-> # Create Eetlijst instance eetlijst = getInstance() if not eetlijst return # Synchronize general information lastSync = new Date().getTime() - Db.shared.get("lastSync", "info") if lastSync > TIMEOUT_INFO eetlijst.getInfo "onInfo", "onError" # Synchronize noticeboard lastSync = new Date().getTime() - Db.shared.get("lastSync", "noticeboard") if lastSync > TIMEOUT_NOTICEBOARD eetlijst.getNoticeboard "onNoticeboard", "onError" # Synchronize status row and merge it with the residents to provide todays # view. lastSync = new Date().getTime() - Db.shared.get("lastSync", "status") if lastSync > TIMEOUT_STATUS eetlijst.getStatus "onStatus", "onError" # Temporary solution to handle incoming response data exports.onHttpResponse = (success, error, response) !-> if not response log "Expected a response" else # Parse as JSON try result = JSON.parse(response) catch result = null # Parse response if not result or not result.result log "Could not decode response." if error exports[error]() else if result.error log "Server returned error: " + result.error if error exports[error](result.error) else if success exports[success](result.result) # Initialize default values for the database. exports.onInstall = !-> Db.admin.set "credentials", username: "", password: "" Db.shared.set "lastSync", info: 0, noticeboard: 0, status: 0 # This effectively removes the keys, which is what we want if the caller is # exports.client_clearAll. Db.shared.set "info", null Db.shared.set "today", null Db.shared.set "status", null Db.shared.set "noticeboard", null Db.shared.set "mapping", null # Get the credentials, for the settings screen. Can only be invoked by plugin # admin. exports.client_getCredentials = (cb) !-> Plugin.assertAdmin() cb.reply Db.admin.get("credentials") # Set the credentials, and validate them. Can only be invoked by plugin admin. exports.client_setCredentials = (credentials, cb) !-> Plugin.assertAdmin() Db.admin.merge("credentials", credentials) cb.reply Db.admin.get("credentials") # Check if the stored credentials are valid and can be used for signing in. # Returns true on success, false otherwise. Can only be invoked by plugin admin. exports.client_checkCredentials = (cb) !-> Plugin.assertAdmin() eetlijst = getInstance() if eetlijst eetlijst.isValid(cb.reply) else cb.reply(false) # Change the content of the noticeboard exports.client_setNoticeboard = (content) !-> eetlijst = getInstance() eetlijst.setNoticeboard(content) Db.shared.set("noticeboard", content) # Set the status of a resident at a certain timestamp exports.client_setStatus = (resident, value, timestamp) !-> eetlijst = getInstance() eetlijst.setStatus(resident, value, timestamp) Db.shared.set("today", "statuses", resident, "value", value) Db.shared.set("today", "statuses", resident, "lastChanged", (new Date().getTime() / 1000)) # Record for event notification Db.shared.set("today", "changes", resident, value) Timer.set(1000 * 60 * 5, "onTimer") #Timer.set(5000, "onTimer") # Connect a resident with a certain userId exports.client_setUser = (resident, userId) !-> # An userId cannot be associated with two residents for k, v of Db.shared.get("mapping") if v == userId Db.shared.set "mapping", k, null # Set new mapping Db.shared.set "mapping", resident, userId # Clear all data exports.client_clearAll = !-> Plugin.assertAdmin() exports.onInstall() # (Re)load data from Eetlijst. Not all parts are refreshed at once, but only if # they are expired (see TIMEOUT constants on top). exports.client_refresh = (cb) !-> update() # Set last visit time now = (new Date().getTime() / 1000) cb.reply Db.personal(Plugin.userId()).get("lastVisit") or now Db.personal(Plugin.userId()).set("lastVisit", now) # Cronjob exports.hourly = !-> update() # Event timer exports.onTimer = !-> residents = Db.shared.get("info", "residents") changes = Db.shared.get("today", "changes") mapping = Db.shared.get("mapping") if not changes return # Gather names names = [] for resident, value of changes if mapping[resident] names.push(Plugin.userName(mapping[resident])) else names.push(residents[resident]) # Build message if names.length == 0 return if names.length == 1 message = names[0] + " has changed his dinner status" else last = names.pop() message = names.join(", ") + " and " + last + " have changed their dinner status" # Send event Event.create unit: "new" text: message # Clear tracked changes Db.shared.set("today", "changes", null) # HTTP API callbacks exports.onError = (reason) !-> Db.shared.set("info", "error", true) exports.onInfo = (result) !-> Db.shared.set("info", result) Db.shared.set("lastSync", "info", new Date().getTime()) exports.onNoticeboard = (result) !-> Db.shared.set("noticeboard", result) Db.shared.set("lastSync", "noticeboard", new Date().getTime()) exports.onStatus = (result) !-> Db.shared.set("status", result[0]) Db.shared.set("lastSync", "status", new Date().getTime()) residents = Db.shared.get("info", "residents") statusRow = Db.shared.get("status") statuses = {} for resident, index in residents statuses[index] = resident: resident, value: statusRow.statuses[index].value, lastChanged: statusRow.statuses[index].last_changed # Save data for today Db.shared.set("today", deadline: statusRow.deadline, timestamp: statusRow.timestamp, statuses: statuses )
61456
Db = require "db" Plugin = require "plugin" Http = require "http" Event = require "event" Timer = require "timer" TIMEOUT_INFO = (1000 * 60 * 60) TIMEOUT_STATUS = (1000 * 60 * 5) TIMEOUT_NOTICEBOARD = (1000 * 60 * 5) # Temporary solution for the lack of scraping and requests support in Happening. # Uses external proxy to convert results into JSON format class ProxiedEetlijst # API URl without trailing slash API_URL = "http://eetlijst.apps.basilfx.net" # Construct new instance. constructor: (username, password) -> @username = username @password = <PASSWORD> # Get the basic info of the list getInfo: (success, error) -> @get("info", null, success, error) # Get the contents of the noticeboard. The response is a string. getNoticeboard: (success, error) -> @get("noticeboard", null, success, error) # Set the contents of the noticeboard. setNoticeboard: (content, success, error) -> data = "content=" + encodeURIComponent(content) @post("noticeboard", data, success, error) # Get the status getStatus: (success, error) -> @get("status", null, success, error) # Set the status setStatus: (resident, value, timestamp, success, error) -> data = "resident=" + encodeURIComponent(resident) \ + "&value=" + encodeURIComponent(value) \ + "&timestamp=" + encodeURIComponent(timestamp) @post("status", data, success, error) # Shortcut for request(Http.get, path, data) get: (path, data, success, error) -> m = (d) -> Http.get(d) @request(m, path, data, success, error) # Shortcut for request(Http.post, path, data) post: (path, data, success, error) -> m = (d) -> Http.post(d) @request(m, path, data, success, error) # Invoke a request. Build URL and add username/password. Data should be a # encoded querystring. request: (method, path, data, success, error) !-> url = API_URL + "/" + path \ + "?username=" + encodeURIComponent(@username) \ + "&password=" + encodeURIComponent(<PASSWORD>) \ + (if data then "&" + data else "") # Request response log "Calling URL: " + url # Invoke method try response = method url: url args: [success, error] catch log "Could not invoke request" exports[error]() # Build a new Eetlijst instance, with the given credentials, or the ones stored # in the shared database. Returns a new instance, or none if username and/or # password not configured. getInstance = (credentials) -> credentials = credentials or Db.admin.get("credentials") if not credentials or not credentials.username or not credentials.password log "Missing username and/or password" return new ProxiedEetlijst(credentials.username, credentials.password) # Update Eetlijst data update = !-> # Create Eetlijst instance eetlijst = getInstance() if not eetlijst return # Synchronize general information lastSync = new Date().getTime() - Db.shared.get("lastSync", "info") if lastSync > TIMEOUT_INFO eetlijst.getInfo "onInfo", "onError" # Synchronize noticeboard lastSync = new Date().getTime() - Db.shared.get("lastSync", "noticeboard") if lastSync > TIMEOUT_NOTICEBOARD eetlijst.getNoticeboard "onNoticeboard", "onError" # Synchronize status row and merge it with the residents to provide todays # view. lastSync = new Date().getTime() - Db.shared.get("lastSync", "status") if lastSync > TIMEOUT_STATUS eetlijst.getStatus "onStatus", "onError" # Temporary solution to handle incoming response data exports.onHttpResponse = (success, error, response) !-> if not response log "Expected a response" else # Parse as JSON try result = JSON.parse(response) catch result = null # Parse response if not result or not result.result log "Could not decode response." if error exports[error]() else if result.error log "Server returned error: " + result.error if error exports[error](result.error) else if success exports[success](result.result) # Initialize default values for the database. exports.onInstall = !-> Db.admin.set "credentials", username: "", password:<PASSWORD> "" Db.shared.set "lastSync", info: 0, noticeboard: 0, status: 0 # This effectively removes the keys, which is what we want if the caller is # exports.client_clearAll. Db.shared.set "info", null Db.shared.set "today", null Db.shared.set "status", null Db.shared.set "noticeboard", null Db.shared.set "mapping", null # Get the credentials, for the settings screen. Can only be invoked by plugin # admin. exports.client_getCredentials = (cb) !-> Plugin.assertAdmin() cb.reply Db.admin.get("credentials") # Set the credentials, and validate them. Can only be invoked by plugin admin. exports.client_setCredentials = (credentials, cb) !-> Plugin.assertAdmin() Db.admin.merge("credentials", credentials) cb.reply Db.admin.get("credentials") # Check if the stored credentials are valid and can be used for signing in. # Returns true on success, false otherwise. Can only be invoked by plugin admin. exports.client_checkCredentials = (cb) !-> Plugin.assertAdmin() eetlijst = getInstance() if eetlijst eetlijst.isValid(cb.reply) else cb.reply(false) # Change the content of the noticeboard exports.client_setNoticeboard = (content) !-> eetlijst = getInstance() eetlijst.setNoticeboard(content) Db.shared.set("noticeboard", content) # Set the status of a resident at a certain timestamp exports.client_setStatus = (resident, value, timestamp) !-> eetlijst = getInstance() eetlijst.setStatus(resident, value, timestamp) Db.shared.set("today", "statuses", resident, "value", value) Db.shared.set("today", "statuses", resident, "lastChanged", (new Date().getTime() / 1000)) # Record for event notification Db.shared.set("today", "changes", resident, value) Timer.set(1000 * 60 * 5, "onTimer") #Timer.set(5000, "onTimer") # Connect a resident with a certain userId exports.client_setUser = (resident, userId) !-> # An userId cannot be associated with two residents for k, v of Db.shared.get("mapping") if v == userId Db.shared.set "mapping", k, null # Set new mapping Db.shared.set "mapping", resident, userId # Clear all data exports.client_clearAll = !-> Plugin.assertAdmin() exports.onInstall() # (Re)load data from Eetlijst. Not all parts are refreshed at once, but only if # they are expired (see TIMEOUT constants on top). exports.client_refresh = (cb) !-> update() # Set last visit time now = (new Date().getTime() / 1000) cb.reply Db.personal(Plugin.userId()).get("lastVisit") or now Db.personal(Plugin.userId()).set("lastVisit", now) # Cronjob exports.hourly = !-> update() # Event timer exports.onTimer = !-> residents = Db.shared.get("info", "residents") changes = Db.shared.get("today", "changes") mapping = Db.shared.get("mapping") if not changes return # Gather names names = [] for resident, value of changes if mapping[resident] names.push(Plugin.userName(mapping[resident])) else names.push(residents[resident]) # Build message if names.length == 0 return if names.length == 1 message = names[0] + " has changed his dinner status" else last = names.pop() message = names.join(", ") + " and " + last + " have changed their dinner status" # Send event Event.create unit: "new" text: message # Clear tracked changes Db.shared.set("today", "changes", null) # HTTP API callbacks exports.onError = (reason) !-> Db.shared.set("info", "error", true) exports.onInfo = (result) !-> Db.shared.set("info", result) Db.shared.set("lastSync", "info", new Date().getTime()) exports.onNoticeboard = (result) !-> Db.shared.set("noticeboard", result) Db.shared.set("lastSync", "noticeboard", new Date().getTime()) exports.onStatus = (result) !-> Db.shared.set("status", result[0]) Db.shared.set("lastSync", "status", new Date().getTime()) residents = Db.shared.get("info", "residents") statusRow = Db.shared.get("status") statuses = {} for resident, index in residents statuses[index] = resident: resident, value: statusRow.statuses[index].value, lastChanged: statusRow.statuses[index].last_changed # Save data for today Db.shared.set("today", deadline: statusRow.deadline, timestamp: statusRow.timestamp, statuses: statuses )
true
Db = require "db" Plugin = require "plugin" Http = require "http" Event = require "event" Timer = require "timer" TIMEOUT_INFO = (1000 * 60 * 60) TIMEOUT_STATUS = (1000 * 60 * 5) TIMEOUT_NOTICEBOARD = (1000 * 60 * 5) # Temporary solution for the lack of scraping and requests support in Happening. # Uses external proxy to convert results into JSON format class ProxiedEetlijst # API URl without trailing slash API_URL = "http://eetlijst.apps.basilfx.net" # Construct new instance. constructor: (username, password) -> @username = username @password = PI:PASSWORD:<PASSWORD>END_PI # Get the basic info of the list getInfo: (success, error) -> @get("info", null, success, error) # Get the contents of the noticeboard. The response is a string. getNoticeboard: (success, error) -> @get("noticeboard", null, success, error) # Set the contents of the noticeboard. setNoticeboard: (content, success, error) -> data = "content=" + encodeURIComponent(content) @post("noticeboard", data, success, error) # Get the status getStatus: (success, error) -> @get("status", null, success, error) # Set the status setStatus: (resident, value, timestamp, success, error) -> data = "resident=" + encodeURIComponent(resident) \ + "&value=" + encodeURIComponent(value) \ + "&timestamp=" + encodeURIComponent(timestamp) @post("status", data, success, error) # Shortcut for request(Http.get, path, data) get: (path, data, success, error) -> m = (d) -> Http.get(d) @request(m, path, data, success, error) # Shortcut for request(Http.post, path, data) post: (path, data, success, error) -> m = (d) -> Http.post(d) @request(m, path, data, success, error) # Invoke a request. Build URL and add username/password. Data should be a # encoded querystring. request: (method, path, data, success, error) !-> url = API_URL + "/" + path \ + "?username=" + encodeURIComponent(@username) \ + "&password=" + encodeURIComponent(PI:PASSWORD:<PASSWORD>END_PI) \ + (if data then "&" + data else "") # Request response log "Calling URL: " + url # Invoke method try response = method url: url args: [success, error] catch log "Could not invoke request" exports[error]() # Build a new Eetlijst instance, with the given credentials, or the ones stored # in the shared database. Returns a new instance, or none if username and/or # password not configured. getInstance = (credentials) -> credentials = credentials or Db.admin.get("credentials") if not credentials or not credentials.username or not credentials.password log "Missing username and/or password" return new ProxiedEetlijst(credentials.username, credentials.password) # Update Eetlijst data update = !-> # Create Eetlijst instance eetlijst = getInstance() if not eetlijst return # Synchronize general information lastSync = new Date().getTime() - Db.shared.get("lastSync", "info") if lastSync > TIMEOUT_INFO eetlijst.getInfo "onInfo", "onError" # Synchronize noticeboard lastSync = new Date().getTime() - Db.shared.get("lastSync", "noticeboard") if lastSync > TIMEOUT_NOTICEBOARD eetlijst.getNoticeboard "onNoticeboard", "onError" # Synchronize status row and merge it with the residents to provide todays # view. lastSync = new Date().getTime() - Db.shared.get("lastSync", "status") if lastSync > TIMEOUT_STATUS eetlijst.getStatus "onStatus", "onError" # Temporary solution to handle incoming response data exports.onHttpResponse = (success, error, response) !-> if not response log "Expected a response" else # Parse as JSON try result = JSON.parse(response) catch result = null # Parse response if not result or not result.result log "Could not decode response." if error exports[error]() else if result.error log "Server returned error: " + result.error if error exports[error](result.error) else if success exports[success](result.result) # Initialize default values for the database. exports.onInstall = !-> Db.admin.set "credentials", username: "", password:PI:PASSWORD:<PASSWORD>END_PI "" Db.shared.set "lastSync", info: 0, noticeboard: 0, status: 0 # This effectively removes the keys, which is what we want if the caller is # exports.client_clearAll. Db.shared.set "info", null Db.shared.set "today", null Db.shared.set "status", null Db.shared.set "noticeboard", null Db.shared.set "mapping", null # Get the credentials, for the settings screen. Can only be invoked by plugin # admin. exports.client_getCredentials = (cb) !-> Plugin.assertAdmin() cb.reply Db.admin.get("credentials") # Set the credentials, and validate them. Can only be invoked by plugin admin. exports.client_setCredentials = (credentials, cb) !-> Plugin.assertAdmin() Db.admin.merge("credentials", credentials) cb.reply Db.admin.get("credentials") # Check if the stored credentials are valid and can be used for signing in. # Returns true on success, false otherwise. Can only be invoked by plugin admin. exports.client_checkCredentials = (cb) !-> Plugin.assertAdmin() eetlijst = getInstance() if eetlijst eetlijst.isValid(cb.reply) else cb.reply(false) # Change the content of the noticeboard exports.client_setNoticeboard = (content) !-> eetlijst = getInstance() eetlijst.setNoticeboard(content) Db.shared.set("noticeboard", content) # Set the status of a resident at a certain timestamp exports.client_setStatus = (resident, value, timestamp) !-> eetlijst = getInstance() eetlijst.setStatus(resident, value, timestamp) Db.shared.set("today", "statuses", resident, "value", value) Db.shared.set("today", "statuses", resident, "lastChanged", (new Date().getTime() / 1000)) # Record for event notification Db.shared.set("today", "changes", resident, value) Timer.set(1000 * 60 * 5, "onTimer") #Timer.set(5000, "onTimer") # Connect a resident with a certain userId exports.client_setUser = (resident, userId) !-> # An userId cannot be associated with two residents for k, v of Db.shared.get("mapping") if v == userId Db.shared.set "mapping", k, null # Set new mapping Db.shared.set "mapping", resident, userId # Clear all data exports.client_clearAll = !-> Plugin.assertAdmin() exports.onInstall() # (Re)load data from Eetlijst. Not all parts are refreshed at once, but only if # they are expired (see TIMEOUT constants on top). exports.client_refresh = (cb) !-> update() # Set last visit time now = (new Date().getTime() / 1000) cb.reply Db.personal(Plugin.userId()).get("lastVisit") or now Db.personal(Plugin.userId()).set("lastVisit", now) # Cronjob exports.hourly = !-> update() # Event timer exports.onTimer = !-> residents = Db.shared.get("info", "residents") changes = Db.shared.get("today", "changes") mapping = Db.shared.get("mapping") if not changes return # Gather names names = [] for resident, value of changes if mapping[resident] names.push(Plugin.userName(mapping[resident])) else names.push(residents[resident]) # Build message if names.length == 0 return if names.length == 1 message = names[0] + " has changed his dinner status" else last = names.pop() message = names.join(", ") + " and " + last + " have changed their dinner status" # Send event Event.create unit: "new" text: message # Clear tracked changes Db.shared.set("today", "changes", null) # HTTP API callbacks exports.onError = (reason) !-> Db.shared.set("info", "error", true) exports.onInfo = (result) !-> Db.shared.set("info", result) Db.shared.set("lastSync", "info", new Date().getTime()) exports.onNoticeboard = (result) !-> Db.shared.set("noticeboard", result) Db.shared.set("lastSync", "noticeboard", new Date().getTime()) exports.onStatus = (result) !-> Db.shared.set("status", result[0]) Db.shared.set("lastSync", "status", new Date().getTime()) residents = Db.shared.get("info", "residents") statusRow = Db.shared.get("status") statuses = {} for resident, index in residents statuses[index] = resident: resident, value: statusRow.statuses[index].value, lastChanged: statusRow.statuses[index].last_changed # Save data for today Db.shared.set("today", deadline: statusRow.deadline, timestamp: statusRow.timestamp, statuses: statuses )
[ { "context": "Formbuilder.registerField 'email',\n\n name: 'Email'\n\n order: 40\n\n view: \"\"\"\n <input type='text'", "end": 50, "score": 0.6060811877250671, "start": 45, "tag": "NAME", "value": "Email" } ]
src/scripts/fields/email.coffee
ahashmi929/formbuilder
0
Formbuilder.registerField 'email', name: 'Email' order: 40 view: """ <input type='text' class='rf-size-<%= rf.get(Formbuilder.options.mappings.SIZE) %>' /> """ edit: "" addButton: """ <span class="fa fa-envelope-o"></span> Email """
31854
Formbuilder.registerField 'email', name: '<NAME>' order: 40 view: """ <input type='text' class='rf-size-<%= rf.get(Formbuilder.options.mappings.SIZE) %>' /> """ edit: "" addButton: """ <span class="fa fa-envelope-o"></span> Email """
true
Formbuilder.registerField 'email', name: 'PI:NAME:<NAME>END_PI' order: 40 view: """ <input type='text' class='rf-size-<%= rf.get(Formbuilder.options.mappings.SIZE) %>' /> """ edit: "" addButton: """ <span class="fa fa-envelope-o"></span> Email """
[ { "context": "see? <picture>\n#\n# Notes:\n# None\n#\n# Author:\n# Mike Lanyon\n\ncrypto = require 'crypto'\nknox = req", "end": 524, "score": 0.9998552203178406, "start": 513, "tag": "NAME", "value": "Mike Lanyon" } ]
src/rekognition.coffee
lanyonm/hubot-rekognition
1
# Description: # Give Hubot an image and it'll tell you what it sees in the image. # # Dependencies: # None # # Configuration: # HUBOT_S3_BUCKET - the S3 bucket you'd like to upload images to # HUBOT_AWS_ACCESS_KEY_ID - an AWS access key for S3 and Rekognition # HUBOT_AWS_SECRET_ACCESS_KEY - a matching AWS secret key for S3 and Rekognition # HUBOT_AWS_REGION - the AWS region you'd like to use. eg: 'us-west-2' # # Commands: # @hubot What do you see? <picture> # # Notes: # None # # Author: # Mike Lanyon crypto = require 'crypto' knox = require 'knox' Rekognition = require 'aws-sdk/clients/rekognition' request = require 'request' module.exports = (robot) -> s3_bucket = process.env.HUBOT_S3_BUCKET aws_access_key = process.env.HUBOT_AWS_ACCESS_KEY_ID aws_secret_key = process.env.HUBOT_AWS_SECRET_ACCESS_KEY aws_region = process.env.HUBOT_AWS_REGION robot.respond /What have you seen?/i, (msg) -> callRekog msg, 'father-and-son.jpg' robot.respond /What do you see?/i, (msg) -> robot.logger.debug "hubot-rekognition: trying to figure out what's in this image..." if /uploads.hipchat.com/.test(msg.message.text) imageUrl = msg.message.text.split('https://s3.amazonaws.com/uploads.hipchat.com/')[1] if !imageUrl msg.send 'Sorry - I can\'t seem to parse that image url. :(' robot.logger.debug "hubot-rekognition: uploading this to s3: https://s3.amazonaws.com/uploads.hipchat.com/#{imageUrl}" s3FetchAndUpload msg, "https://s3.amazonaws.com/uploads.hipchat.com/#{imageUrl}", imageUrl.split('.')[1] else robot.logger.warning 'hubot-rekognition: doesn\'t look like an image was provided' msg.send 'Sorry - it doesn\'t look like you gave me an image to look at.' sendRobotResponse = (msg, title, image, link) -> msg.send "#{title}: #{image} - #{link}" # Pick a random filename s3UploadPath = (ext) -> "#{crypto.randomBytes(20).toString('hex')}.#{ext}" s3FetchAndUpload = (msg, url, ext) -> requestHeaders = encoding: null request.get url, requestHeaders, (err, res, body) -> if err || res.statusCode != 200 robot.logger.warning "hubot-rekognition: could not successfully fetch the image; res.statusCode: #{res.statusCode}, err: #{err}" msg.send "Something bad happened... I was not able to successfully fetch the image..." else robot.logger.debug "hubot-rekognition: uploading file: #{body.length} bytes, content-type[#{res.headers['content-type']}]" uploadToS3(msg, ext, body, body.length, res.headers['content-type']) callRekog = (msg, filename) -> rekogParams = Image: S3Object: Bucket: s3_bucket Name: filename MaxLabels: 15 MinConfidence: 30.0 rekog = new Rekognition({ apiVersion: '2016-06-27', region: aws_region, accessKeyId: aws_access_key, secretAccessKey: aws_secret_key }) rekog.detectLabels rekogParams, (err, data) -> if err robot.logger.error "hubot-rekognition: #{err}\nrekogParams are: #{require('util').inspect(rekogParams)}" msg.send "Something bad happened... Although I was able to receive the image, I'm blind to it..." else labelArray = [] for label in data.Labels labelArray.push "#{label.Name} (#{label.Confidence.toFixed(1)}%)" msg.send "I think I see: #{labelArray.join(', ')}" # Upload image to S3 uploadToS3 = (msg, ext, content, length, content_type) -> client = knox.createClient { key : aws_access_key secret : aws_secret_key, bucket : s3_bucket, region : aws_region } headers = { 'Content-Length' : length, 'Content-Type' : content_type, 'x-amz-acl' : 'public-read', 'encoding' : null } filename = s3UploadPath(ext) req = client.put(filename, headers) req.on 'response', (res) -> if (200 == res.statusCode) robot.logger.debug "hubot-rekognition: file successfully uploaded here: #{client.https(filename)}" callRekog msg, filename else robot.logger.debug "hubot-rekognition: #{res}" robot.logger.error "hubot-rekognition: upload error - res.statusCode: #{res.statusCode}" sendRobotResponse msg, title, '[Upload Error]', link req.end(content)
153163
# Description: # Give Hubot an image and it'll tell you what it sees in the image. # # Dependencies: # None # # Configuration: # HUBOT_S3_BUCKET - the S3 bucket you'd like to upload images to # HUBOT_AWS_ACCESS_KEY_ID - an AWS access key for S3 and Rekognition # HUBOT_AWS_SECRET_ACCESS_KEY - a matching AWS secret key for S3 and Rekognition # HUBOT_AWS_REGION - the AWS region you'd like to use. eg: 'us-west-2' # # Commands: # @hubot What do you see? <picture> # # Notes: # None # # Author: # <NAME> crypto = require 'crypto' knox = require 'knox' Rekognition = require 'aws-sdk/clients/rekognition' request = require 'request' module.exports = (robot) -> s3_bucket = process.env.HUBOT_S3_BUCKET aws_access_key = process.env.HUBOT_AWS_ACCESS_KEY_ID aws_secret_key = process.env.HUBOT_AWS_SECRET_ACCESS_KEY aws_region = process.env.HUBOT_AWS_REGION robot.respond /What have you seen?/i, (msg) -> callRekog msg, 'father-and-son.jpg' robot.respond /What do you see?/i, (msg) -> robot.logger.debug "hubot-rekognition: trying to figure out what's in this image..." if /uploads.hipchat.com/.test(msg.message.text) imageUrl = msg.message.text.split('https://s3.amazonaws.com/uploads.hipchat.com/')[1] if !imageUrl msg.send 'Sorry - I can\'t seem to parse that image url. :(' robot.logger.debug "hubot-rekognition: uploading this to s3: https://s3.amazonaws.com/uploads.hipchat.com/#{imageUrl}" s3FetchAndUpload msg, "https://s3.amazonaws.com/uploads.hipchat.com/#{imageUrl}", imageUrl.split('.')[1] else robot.logger.warning 'hubot-rekognition: doesn\'t look like an image was provided' msg.send 'Sorry - it doesn\'t look like you gave me an image to look at.' sendRobotResponse = (msg, title, image, link) -> msg.send "#{title}: #{image} - #{link}" # Pick a random filename s3UploadPath = (ext) -> "#{crypto.randomBytes(20).toString('hex')}.#{ext}" s3FetchAndUpload = (msg, url, ext) -> requestHeaders = encoding: null request.get url, requestHeaders, (err, res, body) -> if err || res.statusCode != 200 robot.logger.warning "hubot-rekognition: could not successfully fetch the image; res.statusCode: #{res.statusCode}, err: #{err}" msg.send "Something bad happened... I was not able to successfully fetch the image..." else robot.logger.debug "hubot-rekognition: uploading file: #{body.length} bytes, content-type[#{res.headers['content-type']}]" uploadToS3(msg, ext, body, body.length, res.headers['content-type']) callRekog = (msg, filename) -> rekogParams = Image: S3Object: Bucket: s3_bucket Name: filename MaxLabels: 15 MinConfidence: 30.0 rekog = new Rekognition({ apiVersion: '2016-06-27', region: aws_region, accessKeyId: aws_access_key, secretAccessKey: aws_secret_key }) rekog.detectLabels rekogParams, (err, data) -> if err robot.logger.error "hubot-rekognition: #{err}\nrekogParams are: #{require('util').inspect(rekogParams)}" msg.send "Something bad happened... Although I was able to receive the image, I'm blind to it..." else labelArray = [] for label in data.Labels labelArray.push "#{label.Name} (#{label.Confidence.toFixed(1)}%)" msg.send "I think I see: #{labelArray.join(', ')}" # Upload image to S3 uploadToS3 = (msg, ext, content, length, content_type) -> client = knox.createClient { key : aws_access_key secret : aws_secret_key, bucket : s3_bucket, region : aws_region } headers = { 'Content-Length' : length, 'Content-Type' : content_type, 'x-amz-acl' : 'public-read', 'encoding' : null } filename = s3UploadPath(ext) req = client.put(filename, headers) req.on 'response', (res) -> if (200 == res.statusCode) robot.logger.debug "hubot-rekognition: file successfully uploaded here: #{client.https(filename)}" callRekog msg, filename else robot.logger.debug "hubot-rekognition: #{res}" robot.logger.error "hubot-rekognition: upload error - res.statusCode: #{res.statusCode}" sendRobotResponse msg, title, '[Upload Error]', link req.end(content)
true
# Description: # Give Hubot an image and it'll tell you what it sees in the image. # # Dependencies: # None # # Configuration: # HUBOT_S3_BUCKET - the S3 bucket you'd like to upload images to # HUBOT_AWS_ACCESS_KEY_ID - an AWS access key for S3 and Rekognition # HUBOT_AWS_SECRET_ACCESS_KEY - a matching AWS secret key for S3 and Rekognition # HUBOT_AWS_REGION - the AWS region you'd like to use. eg: 'us-west-2' # # Commands: # @hubot What do you see? <picture> # # Notes: # None # # Author: # PI:NAME:<NAME>END_PI crypto = require 'crypto' knox = require 'knox' Rekognition = require 'aws-sdk/clients/rekognition' request = require 'request' module.exports = (robot) -> s3_bucket = process.env.HUBOT_S3_BUCKET aws_access_key = process.env.HUBOT_AWS_ACCESS_KEY_ID aws_secret_key = process.env.HUBOT_AWS_SECRET_ACCESS_KEY aws_region = process.env.HUBOT_AWS_REGION robot.respond /What have you seen?/i, (msg) -> callRekog msg, 'father-and-son.jpg' robot.respond /What do you see?/i, (msg) -> robot.logger.debug "hubot-rekognition: trying to figure out what's in this image..." if /uploads.hipchat.com/.test(msg.message.text) imageUrl = msg.message.text.split('https://s3.amazonaws.com/uploads.hipchat.com/')[1] if !imageUrl msg.send 'Sorry - I can\'t seem to parse that image url. :(' robot.logger.debug "hubot-rekognition: uploading this to s3: https://s3.amazonaws.com/uploads.hipchat.com/#{imageUrl}" s3FetchAndUpload msg, "https://s3.amazonaws.com/uploads.hipchat.com/#{imageUrl}", imageUrl.split('.')[1] else robot.logger.warning 'hubot-rekognition: doesn\'t look like an image was provided' msg.send 'Sorry - it doesn\'t look like you gave me an image to look at.' sendRobotResponse = (msg, title, image, link) -> msg.send "#{title}: #{image} - #{link}" # Pick a random filename s3UploadPath = (ext) -> "#{crypto.randomBytes(20).toString('hex')}.#{ext}" s3FetchAndUpload = (msg, url, ext) -> requestHeaders = encoding: null request.get url, requestHeaders, (err, res, body) -> if err || res.statusCode != 200 robot.logger.warning "hubot-rekognition: could not successfully fetch the image; res.statusCode: #{res.statusCode}, err: #{err}" msg.send "Something bad happened... I was not able to successfully fetch the image..." else robot.logger.debug "hubot-rekognition: uploading file: #{body.length} bytes, content-type[#{res.headers['content-type']}]" uploadToS3(msg, ext, body, body.length, res.headers['content-type']) callRekog = (msg, filename) -> rekogParams = Image: S3Object: Bucket: s3_bucket Name: filename MaxLabels: 15 MinConfidence: 30.0 rekog = new Rekognition({ apiVersion: '2016-06-27', region: aws_region, accessKeyId: aws_access_key, secretAccessKey: aws_secret_key }) rekog.detectLabels rekogParams, (err, data) -> if err robot.logger.error "hubot-rekognition: #{err}\nrekogParams are: #{require('util').inspect(rekogParams)}" msg.send "Something bad happened... Although I was able to receive the image, I'm blind to it..." else labelArray = [] for label in data.Labels labelArray.push "#{label.Name} (#{label.Confidence.toFixed(1)}%)" msg.send "I think I see: #{labelArray.join(', ')}" # Upload image to S3 uploadToS3 = (msg, ext, content, length, content_type) -> client = knox.createClient { key : aws_access_key secret : aws_secret_key, bucket : s3_bucket, region : aws_region } headers = { 'Content-Length' : length, 'Content-Type' : content_type, 'x-amz-acl' : 'public-read', 'encoding' : null } filename = s3UploadPath(ext) req = client.put(filename, headers) req.on 'response', (res) -> if (200 == res.statusCode) robot.logger.debug "hubot-rekognition: file successfully uploaded here: #{client.https(filename)}" callRekog msg, filename else robot.logger.debug "hubot-rekognition: #{res}" robot.logger.error "hubot-rekognition: upload error - res.statusCode: #{res.statusCode}" sendRobotResponse msg, title, '[Upload Error]', link req.end(content)
[ { "context": ":\n element: 'string'\n content: 'bar2'\n value:\n element: 'number'\n ", "end": 2138, "score": 0.8740135431289673, "start": 2134, "tag": "KEY", "value": "bar2" }, { "context": " element: 'string'\n content: 'bar2'\n content:\n element: 'str", "end": 3343, "score": 0.5269442796707153, "start": 3342, "tag": "KEY", "value": "2" }, { "context": " element: 'string'\n content: 'bar2'\n value:\n element: 'number'\n ", "end": 4710, "score": 0.5521581172943115, "start": 4706, "tag": "KEY", "value": "bar2" }, { "context": "userName'\n defaultValue {element: 'string'}, ['username']\n expect(faker.internet.userName.called).to.b", "end": 8551, "score": 0.9922248125076294, "start": 8543, "tag": "USERNAME", "value": "username" } ]
test/eidolon.coffee
danielgtaylor/eidolon
8
eidolon = require '../src/eidolon' dereference = require '../src/dereference' {expect} = require 'chai' faker = require 'faker/locale/en' fs = require 'fs' glob = require 'glob' path = require 'path' sinon = require 'sinon' {defaultValue, Eidolon} = eidolon # Make `glob` and `require` all work from the same path process.chdir __dirname # Test each fixture against its expected example and schema output glob.sync('./fixtures/*-refract.json').forEach (filename) -> describe path.basename(filename, '-refract.json'), -> input = require filename structures = {} exists = false structuresFilename = filename.replace(/-refract\.json/, '-structures.json') try fs.statSync structuresFilename exists = true if exists # If any data structures are defined, get them. This is useful for # resolving references. structures = require structuresFilename instance = new Eidolon structures it 'Generates an example', -> expected = require filename.replace(/-refract\.json/, '-example.json') example = instance.example input expect(example).to.deep.equal(expected) it 'Generates a schema', -> expected = require filename.replace(/-refract\.json/, '-schema.json') schema = instance.schema input expect(schema).to.deep.equal(expected) describe 'Defaults', -> refract = element: 'object' content: [ element: 'member' content: key: element: 'string' content: 'one' , element: 'member' content: key: element: 'string' content: 'two' value: element: 'number' ] example = null before -> example = eidolon.example refract it 'treats a member with no value as a string', -> expect(example.one).to.be.a('string') it 'generates a value if there is no content', -> expect(example.two).to.be.a('number') describe 'Dereferencing', -> refract = element: 'MyType' content: [ element: 'member' content: key: element: 'string' content: 'bar2' value: element: 'number' content: 5 ] dataStructures = MyType: element: 'object' meta: id: 'MyType' content: [ element: 'member' content: key: element: 'string' content: 'foo' value: element: 'FooType' content: null , element: 'ref' content: href: 'BarType' , element: 'member' content: key: element: 'string' content: 'baz' value: element: 'boolean' content: true ] FooType: element: 'number' meta: id: 'FooType' content: 5 BarType: element: 'object' meta: id: 'BarType' content: [ element: 'member' content: key: element: 'string' content: 'bar' value: element: 'string' content: 'Hello' , element: 'member' content: key: element: 'string' content: 'bar2' content: element: 'string' ] expected = element: 'object' meta: ref: 'MyType' links: [ { relation: 'origin' href: 'http://refract.link/inherited/' } ] content: [ element: 'member' meta: ref: 'MyType' links: [ { relation: 'origin' href: 'http://refract.link/inherited-member/' } ] content: key: element: 'string' content: 'foo' value: element: 'number' meta: ref: 'FooType' links: [ { relation: 'origin' href: 'http://refract.link/inherited/' } ] content: 5 , element: 'member' meta: ref: 'BarType' links: [ { relation: 'origin' href: 'http://refract.link/included-member/' } ] content: key: element: 'string' content: 'bar' value: element: 'string' content: 'Hello' , element: 'member' content: key: element: 'string' content: 'bar2' value: element: 'number' content: 5 , element: 'member' meta: ref: 'MyType' links: [ { relation: 'origin' href: 'http://refract.link/inherited-member/' } ] content: key: element: 'string' content: 'baz' value: element: 'boolean' content: true ] eidolon = new Eidolon dataStructures dereferenced = eidolon.dereference refract it 'Dereferences element name', -> expect(dereferenced).to.deep.equal(expected) describe 'Dereferencing an empty ‘Include’', -> refract = { element: 'object', meta: { id: 'TreeItem3' }, content: [ { element: 'ref', content: { href: '', path: 'content', } } ] } eidolon = new Eidolon([]) dereferenced = eidolon.dereference(refract) it 'Dereferences element name', -> expect(dereferenced).to.deep.equal(refract) describe 'Dereferencing a data structure with sourcemaps', -> refract = { element: 'array', meta: { id: { element: 'string', content: 'A' } }, content: [ { element: 'A' } ] } it 'Dereferences element name', -> dereferenced = dereference(refract, {}) expect(dereferenced.content).to.have.lengthOf(1) expect(dereferenced.content[0].meta.links).to.have.lengthOf(1) describe 'Dereferencing a data structure with sourcemaps when it is known', -> refract = { element: 'object', meta: { id: { element: 'string', content: 'A' } }, content: [] } it 'should contain links', -> dereferenced = dereference(refract, {}, ['A']) expect(dereferenced.meta.links).to.have.lengthOf(1) describe 'Defaults', -> beforeEach -> faker.seed(1) it 'can generate a boolean', -> expect(defaultValue {element: 'boolean'}, []).to.be.a('boolean') it 'can generate a number', -> expect(defaultValue {element: 'number'}, []).to.be.a('number') it 'can generate a random string', -> sinon.spy faker.lorem, 'words' defaultValue {element: 'string'}, [] expect(faker.lorem.words.called).to.be.true faker.lorem.words.restore() it 'can generate a unique ID', -> sinon.spy faker.random, 'uuid' expect(defaultValue {element: 'string'}, ['id']).to.match( /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/) expect(faker.random.uuid.called).to.be.true faker.random.uuid.restore() it 'can generate a first name', -> sinon.spy faker.name, 'firstName' defaultValue {element: 'string'}, ['firstname'] expect(faker.name.firstName.called).to.be.true faker.name.firstName.restore() it 'can generate a last name', -> sinon.spy faker.name, 'lastName' defaultValue {element: 'string'}, ['lastname'] expect(faker.name.lastName.called).to.be.true faker.name.lastName.restore() it 'can generate a customer name', -> sinon.spy faker.name, 'findName' defaultValue {element: 'string'}, ['user', 'name'] expect(faker.name.findName.called).to.be.true faker.name.findName.restore() it 'can generate a company name', -> sinon.spy faker.company, 'companyName' defaultValue {element: 'string'}, ['company', 'name'] expect(faker.company.companyName.called).to.be.true faker.company.companyName.restore() it 'can generate some other name', -> sinon.spy faker.lorem, 'words' defaultValue {element: 'string'}, ['widget', 'name'] expect(faker.lorem.words.called).to.be.true faker.lorem.words.restore() it 'can generate a username', -> sinon.spy faker.internet, 'userName' defaultValue {element: 'string'}, ['username'] expect(faker.internet.userName.called).to.be.true faker.internet.userName.restore() it 'can generate an email', -> sinon.spy faker.internet, 'email' defaultValue {element: 'string'}, ['email'] expect(faker.internet.email.called).to.be.true faker.internet.email.restore() it 'can generate a URL', -> sinon.spy faker.internet, 'url' defaultValue {element: 'string'}, ['url'] expect(faker.internet.url.called).to.be.true faker.internet.url.restore() it 'can generate a random password', -> sinon.spy faker.internet, 'password' defaultValue {element: 'string'}, ['password'] expect(faker.internet.password.called).to.be.true faker.internet.password.restore() it 'can generate an avatar URL', -> sinon.spy faker.image, 'image' defaultValue {element: 'string'}, ['user', 'avatar'] expect(faker.image.image.called).to.be.true faker.image.image.restore() it 'can generate a street address', -> sinon.spy faker.address, 'streetAddress' defaultValue {element: 'string'}, ['address'] expect(faker.address.streetAddress.called).to.be.true faker.address.streetAddress.restore() it 'can generate a city', -> sinon.spy faker.address, 'city' defaultValue {element: 'string'}, ['city'] expect(faker.address.city.called).to.be.true faker.address.city.restore() it 'can generate a state', -> sinon.spy faker.address, 'stateAbbr' defaultValue {element: 'string'}, ['state'] expect(faker.address.stateAbbr.called).to.be.true faker.address.stateAbbr.restore() it 'can generate a zip code', -> sinon.spy faker.address, 'zipCode' defaultValue {element: 'string'}, ['zip'] expect(faker.address.zipCode.called).to.be.true faker.address.zipCode.restore() it 'can generate a country code', -> sinon.spy faker.address, 'countryCode' defaultValue {element: 'string'}, ['country'] expect(faker.address.countryCode.called).to.be.true faker.address.countryCode.restore() it 'can generate a latitude position', -> sinon.spy faker.address, 'latitude' defaultValue {element: 'string'}, ['lat'] expect(faker.address.latitude.called).to.be.true faker.address.latitude.restore() it 'can generate a longitude position', -> sinon.spy faker.address, 'longitude' defaultValue {element: 'string'}, ['lng'] expect(faker.address.longitude.called).to.be.true faker.address.longitude.restore() it 'can generate a date', -> sinon.spy faker.date, 'past' defaultValue {element: 'string'}, ['date'] expect(faker.date.past.called).to.be.true faker.date.past.restore() it 'can generate a date when a member ends with `date`', -> sinon.spy faker.date, 'past' defaultValue {element: 'string'}, ['login_date'] expect(faker.date.past.called).to.be.true faker.date.past.restore() it 'can generate a cost', -> sinon.spy faker.finance, 'amount' defaultValue {element: 'string'}, ['cost'] expect(faker.finance.amount.called).to.be.true faker.finance.amount.restore() it 'can generate a currency', -> sinon.spy faker.finance, 'currencyCode' defaultValue {element: 'string'}, ['currency'] expect(faker.finance.currencyCode.called).to.be.true faker.finance.currencyCode.restore() # Reset for other tooling like coverage! process.chdir '..'
206002
eidolon = require '../src/eidolon' dereference = require '../src/dereference' {expect} = require 'chai' faker = require 'faker/locale/en' fs = require 'fs' glob = require 'glob' path = require 'path' sinon = require 'sinon' {defaultValue, Eidolon} = eidolon # Make `glob` and `require` all work from the same path process.chdir __dirname # Test each fixture against its expected example and schema output glob.sync('./fixtures/*-refract.json').forEach (filename) -> describe path.basename(filename, '-refract.json'), -> input = require filename structures = {} exists = false structuresFilename = filename.replace(/-refract\.json/, '-structures.json') try fs.statSync structuresFilename exists = true if exists # If any data structures are defined, get them. This is useful for # resolving references. structures = require structuresFilename instance = new Eidolon structures it 'Generates an example', -> expected = require filename.replace(/-refract\.json/, '-example.json') example = instance.example input expect(example).to.deep.equal(expected) it 'Generates a schema', -> expected = require filename.replace(/-refract\.json/, '-schema.json') schema = instance.schema input expect(schema).to.deep.equal(expected) describe 'Defaults', -> refract = element: 'object' content: [ element: 'member' content: key: element: 'string' content: 'one' , element: 'member' content: key: element: 'string' content: 'two' value: element: 'number' ] example = null before -> example = eidolon.example refract it 'treats a member with no value as a string', -> expect(example.one).to.be.a('string') it 'generates a value if there is no content', -> expect(example.two).to.be.a('number') describe 'Dereferencing', -> refract = element: 'MyType' content: [ element: 'member' content: key: element: 'string' content: '<KEY>' value: element: 'number' content: 5 ] dataStructures = MyType: element: 'object' meta: id: 'MyType' content: [ element: 'member' content: key: element: 'string' content: 'foo' value: element: 'FooType' content: null , element: 'ref' content: href: 'BarType' , element: 'member' content: key: element: 'string' content: 'baz' value: element: 'boolean' content: true ] FooType: element: 'number' meta: id: 'FooType' content: 5 BarType: element: 'object' meta: id: 'BarType' content: [ element: 'member' content: key: element: 'string' content: 'bar' value: element: 'string' content: 'Hello' , element: 'member' content: key: element: 'string' content: 'bar<KEY>' content: element: 'string' ] expected = element: 'object' meta: ref: 'MyType' links: [ { relation: 'origin' href: 'http://refract.link/inherited/' } ] content: [ element: 'member' meta: ref: 'MyType' links: [ { relation: 'origin' href: 'http://refract.link/inherited-member/' } ] content: key: element: 'string' content: 'foo' value: element: 'number' meta: ref: 'FooType' links: [ { relation: 'origin' href: 'http://refract.link/inherited/' } ] content: 5 , element: 'member' meta: ref: 'BarType' links: [ { relation: 'origin' href: 'http://refract.link/included-member/' } ] content: key: element: 'string' content: 'bar' value: element: 'string' content: 'Hello' , element: 'member' content: key: element: 'string' content: '<KEY>' value: element: 'number' content: 5 , element: 'member' meta: ref: 'MyType' links: [ { relation: 'origin' href: 'http://refract.link/inherited-member/' } ] content: key: element: 'string' content: 'baz' value: element: 'boolean' content: true ] eidolon = new Eidolon dataStructures dereferenced = eidolon.dereference refract it 'Dereferences element name', -> expect(dereferenced).to.deep.equal(expected) describe 'Dereferencing an empty ‘Include’', -> refract = { element: 'object', meta: { id: 'TreeItem3' }, content: [ { element: 'ref', content: { href: '', path: 'content', } } ] } eidolon = new Eidolon([]) dereferenced = eidolon.dereference(refract) it 'Dereferences element name', -> expect(dereferenced).to.deep.equal(refract) describe 'Dereferencing a data structure with sourcemaps', -> refract = { element: 'array', meta: { id: { element: 'string', content: 'A' } }, content: [ { element: 'A' } ] } it 'Dereferences element name', -> dereferenced = dereference(refract, {}) expect(dereferenced.content).to.have.lengthOf(1) expect(dereferenced.content[0].meta.links).to.have.lengthOf(1) describe 'Dereferencing a data structure with sourcemaps when it is known', -> refract = { element: 'object', meta: { id: { element: 'string', content: 'A' } }, content: [] } it 'should contain links', -> dereferenced = dereference(refract, {}, ['A']) expect(dereferenced.meta.links).to.have.lengthOf(1) describe 'Defaults', -> beforeEach -> faker.seed(1) it 'can generate a boolean', -> expect(defaultValue {element: 'boolean'}, []).to.be.a('boolean') it 'can generate a number', -> expect(defaultValue {element: 'number'}, []).to.be.a('number') it 'can generate a random string', -> sinon.spy faker.lorem, 'words' defaultValue {element: 'string'}, [] expect(faker.lorem.words.called).to.be.true faker.lorem.words.restore() it 'can generate a unique ID', -> sinon.spy faker.random, 'uuid' expect(defaultValue {element: 'string'}, ['id']).to.match( /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/) expect(faker.random.uuid.called).to.be.true faker.random.uuid.restore() it 'can generate a first name', -> sinon.spy faker.name, 'firstName' defaultValue {element: 'string'}, ['firstname'] expect(faker.name.firstName.called).to.be.true faker.name.firstName.restore() it 'can generate a last name', -> sinon.spy faker.name, 'lastName' defaultValue {element: 'string'}, ['lastname'] expect(faker.name.lastName.called).to.be.true faker.name.lastName.restore() it 'can generate a customer name', -> sinon.spy faker.name, 'findName' defaultValue {element: 'string'}, ['user', 'name'] expect(faker.name.findName.called).to.be.true faker.name.findName.restore() it 'can generate a company name', -> sinon.spy faker.company, 'companyName' defaultValue {element: 'string'}, ['company', 'name'] expect(faker.company.companyName.called).to.be.true faker.company.companyName.restore() it 'can generate some other name', -> sinon.spy faker.lorem, 'words' defaultValue {element: 'string'}, ['widget', 'name'] expect(faker.lorem.words.called).to.be.true faker.lorem.words.restore() it 'can generate a username', -> sinon.spy faker.internet, 'userName' defaultValue {element: 'string'}, ['username'] expect(faker.internet.userName.called).to.be.true faker.internet.userName.restore() it 'can generate an email', -> sinon.spy faker.internet, 'email' defaultValue {element: 'string'}, ['email'] expect(faker.internet.email.called).to.be.true faker.internet.email.restore() it 'can generate a URL', -> sinon.spy faker.internet, 'url' defaultValue {element: 'string'}, ['url'] expect(faker.internet.url.called).to.be.true faker.internet.url.restore() it 'can generate a random password', -> sinon.spy faker.internet, 'password' defaultValue {element: 'string'}, ['password'] expect(faker.internet.password.called).to.be.true faker.internet.password.restore() it 'can generate an avatar URL', -> sinon.spy faker.image, 'image' defaultValue {element: 'string'}, ['user', 'avatar'] expect(faker.image.image.called).to.be.true faker.image.image.restore() it 'can generate a street address', -> sinon.spy faker.address, 'streetAddress' defaultValue {element: 'string'}, ['address'] expect(faker.address.streetAddress.called).to.be.true faker.address.streetAddress.restore() it 'can generate a city', -> sinon.spy faker.address, 'city' defaultValue {element: 'string'}, ['city'] expect(faker.address.city.called).to.be.true faker.address.city.restore() it 'can generate a state', -> sinon.spy faker.address, 'stateAbbr' defaultValue {element: 'string'}, ['state'] expect(faker.address.stateAbbr.called).to.be.true faker.address.stateAbbr.restore() it 'can generate a zip code', -> sinon.spy faker.address, 'zipCode' defaultValue {element: 'string'}, ['zip'] expect(faker.address.zipCode.called).to.be.true faker.address.zipCode.restore() it 'can generate a country code', -> sinon.spy faker.address, 'countryCode' defaultValue {element: 'string'}, ['country'] expect(faker.address.countryCode.called).to.be.true faker.address.countryCode.restore() it 'can generate a latitude position', -> sinon.spy faker.address, 'latitude' defaultValue {element: 'string'}, ['lat'] expect(faker.address.latitude.called).to.be.true faker.address.latitude.restore() it 'can generate a longitude position', -> sinon.spy faker.address, 'longitude' defaultValue {element: 'string'}, ['lng'] expect(faker.address.longitude.called).to.be.true faker.address.longitude.restore() it 'can generate a date', -> sinon.spy faker.date, 'past' defaultValue {element: 'string'}, ['date'] expect(faker.date.past.called).to.be.true faker.date.past.restore() it 'can generate a date when a member ends with `date`', -> sinon.spy faker.date, 'past' defaultValue {element: 'string'}, ['login_date'] expect(faker.date.past.called).to.be.true faker.date.past.restore() it 'can generate a cost', -> sinon.spy faker.finance, 'amount' defaultValue {element: 'string'}, ['cost'] expect(faker.finance.amount.called).to.be.true faker.finance.amount.restore() it 'can generate a currency', -> sinon.spy faker.finance, 'currencyCode' defaultValue {element: 'string'}, ['currency'] expect(faker.finance.currencyCode.called).to.be.true faker.finance.currencyCode.restore() # Reset for other tooling like coverage! process.chdir '..'
true
eidolon = require '../src/eidolon' dereference = require '../src/dereference' {expect} = require 'chai' faker = require 'faker/locale/en' fs = require 'fs' glob = require 'glob' path = require 'path' sinon = require 'sinon' {defaultValue, Eidolon} = eidolon # Make `glob` and `require` all work from the same path process.chdir __dirname # Test each fixture against its expected example and schema output glob.sync('./fixtures/*-refract.json').forEach (filename) -> describe path.basename(filename, '-refract.json'), -> input = require filename structures = {} exists = false structuresFilename = filename.replace(/-refract\.json/, '-structures.json') try fs.statSync structuresFilename exists = true if exists # If any data structures are defined, get them. This is useful for # resolving references. structures = require structuresFilename instance = new Eidolon structures it 'Generates an example', -> expected = require filename.replace(/-refract\.json/, '-example.json') example = instance.example input expect(example).to.deep.equal(expected) it 'Generates a schema', -> expected = require filename.replace(/-refract\.json/, '-schema.json') schema = instance.schema input expect(schema).to.deep.equal(expected) describe 'Defaults', -> refract = element: 'object' content: [ element: 'member' content: key: element: 'string' content: 'one' , element: 'member' content: key: element: 'string' content: 'two' value: element: 'number' ] example = null before -> example = eidolon.example refract it 'treats a member with no value as a string', -> expect(example.one).to.be.a('string') it 'generates a value if there is no content', -> expect(example.two).to.be.a('number') describe 'Dereferencing', -> refract = element: 'MyType' content: [ element: 'member' content: key: element: 'string' content: 'PI:KEY:<KEY>END_PI' value: element: 'number' content: 5 ] dataStructures = MyType: element: 'object' meta: id: 'MyType' content: [ element: 'member' content: key: element: 'string' content: 'foo' value: element: 'FooType' content: null , element: 'ref' content: href: 'BarType' , element: 'member' content: key: element: 'string' content: 'baz' value: element: 'boolean' content: true ] FooType: element: 'number' meta: id: 'FooType' content: 5 BarType: element: 'object' meta: id: 'BarType' content: [ element: 'member' content: key: element: 'string' content: 'bar' value: element: 'string' content: 'Hello' , element: 'member' content: key: element: 'string' content: 'barPI:KEY:<KEY>END_PI' content: element: 'string' ] expected = element: 'object' meta: ref: 'MyType' links: [ { relation: 'origin' href: 'http://refract.link/inherited/' } ] content: [ element: 'member' meta: ref: 'MyType' links: [ { relation: 'origin' href: 'http://refract.link/inherited-member/' } ] content: key: element: 'string' content: 'foo' value: element: 'number' meta: ref: 'FooType' links: [ { relation: 'origin' href: 'http://refract.link/inherited/' } ] content: 5 , element: 'member' meta: ref: 'BarType' links: [ { relation: 'origin' href: 'http://refract.link/included-member/' } ] content: key: element: 'string' content: 'bar' value: element: 'string' content: 'Hello' , element: 'member' content: key: element: 'string' content: 'PI:KEY:<KEY>END_PI' value: element: 'number' content: 5 , element: 'member' meta: ref: 'MyType' links: [ { relation: 'origin' href: 'http://refract.link/inherited-member/' } ] content: key: element: 'string' content: 'baz' value: element: 'boolean' content: true ] eidolon = new Eidolon dataStructures dereferenced = eidolon.dereference refract it 'Dereferences element name', -> expect(dereferenced).to.deep.equal(expected) describe 'Dereferencing an empty ‘Include’', -> refract = { element: 'object', meta: { id: 'TreeItem3' }, content: [ { element: 'ref', content: { href: '', path: 'content', } } ] } eidolon = new Eidolon([]) dereferenced = eidolon.dereference(refract) it 'Dereferences element name', -> expect(dereferenced).to.deep.equal(refract) describe 'Dereferencing a data structure with sourcemaps', -> refract = { element: 'array', meta: { id: { element: 'string', content: 'A' } }, content: [ { element: 'A' } ] } it 'Dereferences element name', -> dereferenced = dereference(refract, {}) expect(dereferenced.content).to.have.lengthOf(1) expect(dereferenced.content[0].meta.links).to.have.lengthOf(1) describe 'Dereferencing a data structure with sourcemaps when it is known', -> refract = { element: 'object', meta: { id: { element: 'string', content: 'A' } }, content: [] } it 'should contain links', -> dereferenced = dereference(refract, {}, ['A']) expect(dereferenced.meta.links).to.have.lengthOf(1) describe 'Defaults', -> beforeEach -> faker.seed(1) it 'can generate a boolean', -> expect(defaultValue {element: 'boolean'}, []).to.be.a('boolean') it 'can generate a number', -> expect(defaultValue {element: 'number'}, []).to.be.a('number') it 'can generate a random string', -> sinon.spy faker.lorem, 'words' defaultValue {element: 'string'}, [] expect(faker.lorem.words.called).to.be.true faker.lorem.words.restore() it 'can generate a unique ID', -> sinon.spy faker.random, 'uuid' expect(defaultValue {element: 'string'}, ['id']).to.match( /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/) expect(faker.random.uuid.called).to.be.true faker.random.uuid.restore() it 'can generate a first name', -> sinon.spy faker.name, 'firstName' defaultValue {element: 'string'}, ['firstname'] expect(faker.name.firstName.called).to.be.true faker.name.firstName.restore() it 'can generate a last name', -> sinon.spy faker.name, 'lastName' defaultValue {element: 'string'}, ['lastname'] expect(faker.name.lastName.called).to.be.true faker.name.lastName.restore() it 'can generate a customer name', -> sinon.spy faker.name, 'findName' defaultValue {element: 'string'}, ['user', 'name'] expect(faker.name.findName.called).to.be.true faker.name.findName.restore() it 'can generate a company name', -> sinon.spy faker.company, 'companyName' defaultValue {element: 'string'}, ['company', 'name'] expect(faker.company.companyName.called).to.be.true faker.company.companyName.restore() it 'can generate some other name', -> sinon.spy faker.lorem, 'words' defaultValue {element: 'string'}, ['widget', 'name'] expect(faker.lorem.words.called).to.be.true faker.lorem.words.restore() it 'can generate a username', -> sinon.spy faker.internet, 'userName' defaultValue {element: 'string'}, ['username'] expect(faker.internet.userName.called).to.be.true faker.internet.userName.restore() it 'can generate an email', -> sinon.spy faker.internet, 'email' defaultValue {element: 'string'}, ['email'] expect(faker.internet.email.called).to.be.true faker.internet.email.restore() it 'can generate a URL', -> sinon.spy faker.internet, 'url' defaultValue {element: 'string'}, ['url'] expect(faker.internet.url.called).to.be.true faker.internet.url.restore() it 'can generate a random password', -> sinon.spy faker.internet, 'password' defaultValue {element: 'string'}, ['password'] expect(faker.internet.password.called).to.be.true faker.internet.password.restore() it 'can generate an avatar URL', -> sinon.spy faker.image, 'image' defaultValue {element: 'string'}, ['user', 'avatar'] expect(faker.image.image.called).to.be.true faker.image.image.restore() it 'can generate a street address', -> sinon.spy faker.address, 'streetAddress' defaultValue {element: 'string'}, ['address'] expect(faker.address.streetAddress.called).to.be.true faker.address.streetAddress.restore() it 'can generate a city', -> sinon.spy faker.address, 'city' defaultValue {element: 'string'}, ['city'] expect(faker.address.city.called).to.be.true faker.address.city.restore() it 'can generate a state', -> sinon.spy faker.address, 'stateAbbr' defaultValue {element: 'string'}, ['state'] expect(faker.address.stateAbbr.called).to.be.true faker.address.stateAbbr.restore() it 'can generate a zip code', -> sinon.spy faker.address, 'zipCode' defaultValue {element: 'string'}, ['zip'] expect(faker.address.zipCode.called).to.be.true faker.address.zipCode.restore() it 'can generate a country code', -> sinon.spy faker.address, 'countryCode' defaultValue {element: 'string'}, ['country'] expect(faker.address.countryCode.called).to.be.true faker.address.countryCode.restore() it 'can generate a latitude position', -> sinon.spy faker.address, 'latitude' defaultValue {element: 'string'}, ['lat'] expect(faker.address.latitude.called).to.be.true faker.address.latitude.restore() it 'can generate a longitude position', -> sinon.spy faker.address, 'longitude' defaultValue {element: 'string'}, ['lng'] expect(faker.address.longitude.called).to.be.true faker.address.longitude.restore() it 'can generate a date', -> sinon.spy faker.date, 'past' defaultValue {element: 'string'}, ['date'] expect(faker.date.past.called).to.be.true faker.date.past.restore() it 'can generate a date when a member ends with `date`', -> sinon.spy faker.date, 'past' defaultValue {element: 'string'}, ['login_date'] expect(faker.date.past.called).to.be.true faker.date.past.restore() it 'can generate a cost', -> sinon.spy faker.finance, 'amount' defaultValue {element: 'string'}, ['cost'] expect(faker.finance.amount.called).to.be.true faker.finance.amount.restore() it 'can generate a currency', -> sinon.spy faker.finance, 'currencyCode' defaultValue {element: 'string'}, ['currency'] expect(faker.finance.currencyCode.called).to.be.true faker.finance.currencyCode.restore() # Reset for other tooling like coverage! process.chdir '..'
[ { "context": " taskDuration = '1 hour'\n task =\n name: taskName\n dueDate: timestamp\n estimate: task", "end": 2010, "score": 0.8149203062057495, "start": 2006, "tag": "NAME", "value": "task" }, { "context": "askDuration = '1 hour'\n task =\n name: taskName\n dueDate: timestamp\n estimate: taskDura", "end": 2014, "score": 0.5118287205696106, "start": 2010, "tag": "NAME", "value": "Name" } ]
client/views/days/day.coffee
ryleehansen/h
0
Template.day.helpers( heatmap: ()-> #me me = this.parent.first[this.index] dayBeginning = me.timestamp dayEnd = me.timestamp + 86400 mongoQuery = { dueDate: { $gte: dayBeginning, $lt: dayEnd} } tasks = Tasks.find(mongoQuery, { sort: { due: -1 } }).fetch() totalTime = 0 for task in tasks totalTime += task.duration color = switch when totalTime is 0 then 'free' when totalTime < 3601 then 'onehour' when totalTime < 7201 then 'twohours' when totalTime < 10801 then 'threehours' when totalTime < 14401 then 'fourhours' else 'fivehours' color todayTasks: ()-> me = this.parent.first[this.index] dayBeginning = me.timestamp dayEnd = me.timestamp + 86400 # build query mongoQuery = { dueDate: { $gte: dayBeginning, $lt: dayEnd} } # find relevant tasks tasks = Tasks.find(mongoQuery, { sort: { due: -1 } }).fetch() this.count = tasks.length tasks today: ()-> me = this.parent.first[this.index] if me.today ' TODAY' else '' name: ()-> me = this.parent.first[this.index] me.name # taskCount: ()-> # # 5 - the number of tasks with a minimum of 1 # tmp = 5 - this.count # if tmp <= 0 # [0...1] # else # [0...tmp] ) swapBack = (e, which, timestamp)-> if which is 'keypress' $day = $(e.currentTarget).parent().parent() else if which is 'cover' $day = $(e.currentTarget).parent() else console.log 'invalid' return $herp = $($day.children()[$day.children().length-3]) $inputter = $($day.children()[$day.children().length-2]) $cover = $($day.children()[$day.children().length-1]) # get task info taskName = $inputter.children()[0].value taskDuration = $inputter.children()[1].value if taskName == '' # if no name, exit without doing anything $herp.show() $inputter.hide() $cover.hide() else if taskDuration == '' taskDuration = '1 hour' task = name: taskName dueDate: timestamp estimate: taskDuration # make a new task Meteor.call 'makeTask', task, (error, id)-> if error Errors.throw(error.reason) if error.error is 302 Meteor.Router.to('home', error.details) # task should be reactively inserted!! :O :O # heat should be reactively inserted!! # wrap up $($inputter.children()[0]).val('') $($inputter.children()[1]).val('') $herp.show() $inputter.hide() $cover.hide() Template.day.events( 'click .herp': (e)-> $day = $(e.currentTarget).parent() $herp = $($day.children()[$day.children().length-3]) $inputter = $($day.children()[$day.children().length-2]) $cover = $($day.children()[$day.children().length-1]) $herp.hide() $inputter.show() $inputter.children()[0].focus() $cover.show() 'click .dayInputCover': (e)-> me = this.parent.first[this.index] swapBack(e, 'cover', me.timestamp) 'keypress .checker': (e)-> me = this.parent.first[this.index] if (e.keyCode == 13) swapBack(e, 'keypress', me.timestamp) )
160505
Template.day.helpers( heatmap: ()-> #me me = this.parent.first[this.index] dayBeginning = me.timestamp dayEnd = me.timestamp + 86400 mongoQuery = { dueDate: { $gte: dayBeginning, $lt: dayEnd} } tasks = Tasks.find(mongoQuery, { sort: { due: -1 } }).fetch() totalTime = 0 for task in tasks totalTime += task.duration color = switch when totalTime is 0 then 'free' when totalTime < 3601 then 'onehour' when totalTime < 7201 then 'twohours' when totalTime < 10801 then 'threehours' when totalTime < 14401 then 'fourhours' else 'fivehours' color todayTasks: ()-> me = this.parent.first[this.index] dayBeginning = me.timestamp dayEnd = me.timestamp + 86400 # build query mongoQuery = { dueDate: { $gte: dayBeginning, $lt: dayEnd} } # find relevant tasks tasks = Tasks.find(mongoQuery, { sort: { due: -1 } }).fetch() this.count = tasks.length tasks today: ()-> me = this.parent.first[this.index] if me.today ' TODAY' else '' name: ()-> me = this.parent.first[this.index] me.name # taskCount: ()-> # # 5 - the number of tasks with a minimum of 1 # tmp = 5 - this.count # if tmp <= 0 # [0...1] # else # [0...tmp] ) swapBack = (e, which, timestamp)-> if which is 'keypress' $day = $(e.currentTarget).parent().parent() else if which is 'cover' $day = $(e.currentTarget).parent() else console.log 'invalid' return $herp = $($day.children()[$day.children().length-3]) $inputter = $($day.children()[$day.children().length-2]) $cover = $($day.children()[$day.children().length-1]) # get task info taskName = $inputter.children()[0].value taskDuration = $inputter.children()[1].value if taskName == '' # if no name, exit without doing anything $herp.show() $inputter.hide() $cover.hide() else if taskDuration == '' taskDuration = '1 hour' task = name: <NAME> <NAME> dueDate: timestamp estimate: taskDuration # make a new task Meteor.call 'makeTask', task, (error, id)-> if error Errors.throw(error.reason) if error.error is 302 Meteor.Router.to('home', error.details) # task should be reactively inserted!! :O :O # heat should be reactively inserted!! # wrap up $($inputter.children()[0]).val('') $($inputter.children()[1]).val('') $herp.show() $inputter.hide() $cover.hide() Template.day.events( 'click .herp': (e)-> $day = $(e.currentTarget).parent() $herp = $($day.children()[$day.children().length-3]) $inputter = $($day.children()[$day.children().length-2]) $cover = $($day.children()[$day.children().length-1]) $herp.hide() $inputter.show() $inputter.children()[0].focus() $cover.show() 'click .dayInputCover': (e)-> me = this.parent.first[this.index] swapBack(e, 'cover', me.timestamp) 'keypress .checker': (e)-> me = this.parent.first[this.index] if (e.keyCode == 13) swapBack(e, 'keypress', me.timestamp) )
true
Template.day.helpers( heatmap: ()-> #me me = this.parent.first[this.index] dayBeginning = me.timestamp dayEnd = me.timestamp + 86400 mongoQuery = { dueDate: { $gte: dayBeginning, $lt: dayEnd} } tasks = Tasks.find(mongoQuery, { sort: { due: -1 } }).fetch() totalTime = 0 for task in tasks totalTime += task.duration color = switch when totalTime is 0 then 'free' when totalTime < 3601 then 'onehour' when totalTime < 7201 then 'twohours' when totalTime < 10801 then 'threehours' when totalTime < 14401 then 'fourhours' else 'fivehours' color todayTasks: ()-> me = this.parent.first[this.index] dayBeginning = me.timestamp dayEnd = me.timestamp + 86400 # build query mongoQuery = { dueDate: { $gte: dayBeginning, $lt: dayEnd} } # find relevant tasks tasks = Tasks.find(mongoQuery, { sort: { due: -1 } }).fetch() this.count = tasks.length tasks today: ()-> me = this.parent.first[this.index] if me.today ' TODAY' else '' name: ()-> me = this.parent.first[this.index] me.name # taskCount: ()-> # # 5 - the number of tasks with a minimum of 1 # tmp = 5 - this.count # if tmp <= 0 # [0...1] # else # [0...tmp] ) swapBack = (e, which, timestamp)-> if which is 'keypress' $day = $(e.currentTarget).parent().parent() else if which is 'cover' $day = $(e.currentTarget).parent() else console.log 'invalid' return $herp = $($day.children()[$day.children().length-3]) $inputter = $($day.children()[$day.children().length-2]) $cover = $($day.children()[$day.children().length-1]) # get task info taskName = $inputter.children()[0].value taskDuration = $inputter.children()[1].value if taskName == '' # if no name, exit without doing anything $herp.show() $inputter.hide() $cover.hide() else if taskDuration == '' taskDuration = '1 hour' task = name: PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI dueDate: timestamp estimate: taskDuration # make a new task Meteor.call 'makeTask', task, (error, id)-> if error Errors.throw(error.reason) if error.error is 302 Meteor.Router.to('home', error.details) # task should be reactively inserted!! :O :O # heat should be reactively inserted!! # wrap up $($inputter.children()[0]).val('') $($inputter.children()[1]).val('') $herp.show() $inputter.hide() $cover.hide() Template.day.events( 'click .herp': (e)-> $day = $(e.currentTarget).parent() $herp = $($day.children()[$day.children().length-3]) $inputter = $($day.children()[$day.children().length-2]) $cover = $($day.children()[$day.children().length-1]) $herp.hide() $inputter.show() $inputter.children()[0].focus() $cover.show() 'click .dayInputCover': (e)-> me = this.parent.first[this.index] swapBack(e, 'cover', me.timestamp) 'keypress .checker': (e)-> me = this.parent.first[this.index] if (e.keyCode == 13) swapBack(e, 'keypress', me.timestamp) )
[ { "context": "= @keys.SL5.unlock(password)\n @masterPassword = password if success\n success\n\n locked: ->\n !@master", "end": 390, "score": 0.5138348937034607, "start": 382, "tag": "PASSWORD", "value": "password" } ]
lib/encryption_keys.coffee
jacobmarshall-etc/1pass
0
{GibberishAES} = require './vendor' class EncryptionKeys constructor: (data) -> @masterPassword = null @keys = {} for item in data.list if data[item.level] == item.identifier @keys[item.level] = new EncryptionKeys.Key(item) @keys unlock: (password) -> return false if !@keys.SL5 success = @keys.SL5.unlock(password) @masterPassword = password if success success locked: -> !@masterPassword get: (securityLevel) -> throw 'database is locked' if @locked() key = @keys[securityLevel] return null if !key key.unlock(@masterPassword) key class EncryptionKeys.Key constructor: (data) -> for name, value of data this[name] = value unlock: (password) -> iterations = Math.max(1000, parseInt(@iterations || 0, 10)) decrypted = GibberishAES.decryptUsingPBKDF2(@data, password, iterations) return false if !decrypted verification = GibberishAES.decryptBase64UsingKey(@validation, GibberishAES.s2a(decrypted)) success = verification == decrypted @value = decrypted if success success module.exports = EncryptionKeys
166020
{GibberishAES} = require './vendor' class EncryptionKeys constructor: (data) -> @masterPassword = null @keys = {} for item in data.list if data[item.level] == item.identifier @keys[item.level] = new EncryptionKeys.Key(item) @keys unlock: (password) -> return false if !@keys.SL5 success = @keys.SL5.unlock(password) @masterPassword = <PASSWORD> if success success locked: -> !@masterPassword get: (securityLevel) -> throw 'database is locked' if @locked() key = @keys[securityLevel] return null if !key key.unlock(@masterPassword) key class EncryptionKeys.Key constructor: (data) -> for name, value of data this[name] = value unlock: (password) -> iterations = Math.max(1000, parseInt(@iterations || 0, 10)) decrypted = GibberishAES.decryptUsingPBKDF2(@data, password, iterations) return false if !decrypted verification = GibberishAES.decryptBase64UsingKey(@validation, GibberishAES.s2a(decrypted)) success = verification == decrypted @value = decrypted if success success module.exports = EncryptionKeys
true
{GibberishAES} = require './vendor' class EncryptionKeys constructor: (data) -> @masterPassword = null @keys = {} for item in data.list if data[item.level] == item.identifier @keys[item.level] = new EncryptionKeys.Key(item) @keys unlock: (password) -> return false if !@keys.SL5 success = @keys.SL5.unlock(password) @masterPassword = PI:PASSWORD:<PASSWORD>END_PI if success success locked: -> !@masterPassword get: (securityLevel) -> throw 'database is locked' if @locked() key = @keys[securityLevel] return null if !key key.unlock(@masterPassword) key class EncryptionKeys.Key constructor: (data) -> for name, value of data this[name] = value unlock: (password) -> iterations = Math.max(1000, parseInt(@iterations || 0, 10)) decrypted = GibberishAES.decryptUsingPBKDF2(@data, password, iterations) return false if !decrypted verification = GibberishAES.decryptBase64UsingKey(@validation, GibberishAES.s2a(decrypted)) success = verification == decrypted @value = decrypted if success success module.exports = EncryptionKeys
[ { "context": "uction']\n type: @type.title()\n name: @name\n opcode: @opcode\n parameters: @", "end": 958, "score": 0.9169440865516663, "start": 958, "tag": "NAME", "value": "" }, { "context": "tion']\n type: @type.title()\n name: @name\n opcode: @opcode\n parameters: @para", "end": 964, "score": 0.4978089928627014, "start": 960, "tag": "NAME", "value": "name" } ]
lib/furnace-xray/app/assets/javascripts/lib/nodes/instruction.js.coffee
evilmartians/furnace-xray
4
class @InstructionNode extends Node constructor: (data, map) -> super @blocks = Object.extended() linkBlock: (block) -> @blocks[block.id] = block @operands?.each (x) => x.linkBlock(block) if x['linkBlock']? unlinkBlock: (block) -> delete @blocks[block.id] @operands?.each (x) => x.unlinkBlock(block) if x['unlinkBlock']? attachedFunctions: -> result = {} @blocks.values().each (x) -> Object.merge result, x.attachedFunctions() result update: (data, map) -> @type = @locate(data['type'], map) @name = data['name'] @opcode = data['opcode'] @parameters = data['parameters'] if data['operand_ids'] @updateOperands(data['operand_ids'], map) else @operands = null updateOperands: (data, map) -> @operands = data.map (x) => @locate(x, map) title: -> if @type && !@type.void() JST['nodes/instruction'] type: @type.title() name: @name opcode: @opcode parameters: @parameters operands: @titleizeOperands() else JST['nodes/instruction_void'] opcode: @opcode parameters: @parameters operands: @titleizeOperands() titleizeOperands: -> return "<DETACHED>" unless @operands @operands.map((x) -> x.operandTitle()).join(', ') operandTitle: -> JST['nodes/operands/instruction'] name: @name
130340
class @InstructionNode extends Node constructor: (data, map) -> super @blocks = Object.extended() linkBlock: (block) -> @blocks[block.id] = block @operands?.each (x) => x.linkBlock(block) if x['linkBlock']? unlinkBlock: (block) -> delete @blocks[block.id] @operands?.each (x) => x.unlinkBlock(block) if x['unlinkBlock']? attachedFunctions: -> result = {} @blocks.values().each (x) -> Object.merge result, x.attachedFunctions() result update: (data, map) -> @type = @locate(data['type'], map) @name = data['name'] @opcode = data['opcode'] @parameters = data['parameters'] if data['operand_ids'] @updateOperands(data['operand_ids'], map) else @operands = null updateOperands: (data, map) -> @operands = data.map (x) => @locate(x, map) title: -> if @type && !@type.void() JST['nodes/instruction'] type: @type.title() name:<NAME> @<NAME> opcode: @opcode parameters: @parameters operands: @titleizeOperands() else JST['nodes/instruction_void'] opcode: @opcode parameters: @parameters operands: @titleizeOperands() titleizeOperands: -> return "<DETACHED>" unless @operands @operands.map((x) -> x.operandTitle()).join(', ') operandTitle: -> JST['nodes/operands/instruction'] name: @name
true
class @InstructionNode extends Node constructor: (data, map) -> super @blocks = Object.extended() linkBlock: (block) -> @blocks[block.id] = block @operands?.each (x) => x.linkBlock(block) if x['linkBlock']? unlinkBlock: (block) -> delete @blocks[block.id] @operands?.each (x) => x.unlinkBlock(block) if x['unlinkBlock']? attachedFunctions: -> result = {} @blocks.values().each (x) -> Object.merge result, x.attachedFunctions() result update: (data, map) -> @type = @locate(data['type'], map) @name = data['name'] @opcode = data['opcode'] @parameters = data['parameters'] if data['operand_ids'] @updateOperands(data['operand_ids'], map) else @operands = null updateOperands: (data, map) -> @operands = data.map (x) => @locate(x, map) title: -> if @type && !@type.void() JST['nodes/instruction'] type: @type.title() name:PI:NAME:<NAME>END_PI @PI:NAME:<NAME>END_PI opcode: @opcode parameters: @parameters operands: @titleizeOperands() else JST['nodes/instruction_void'] opcode: @opcode parameters: @parameters operands: @titleizeOperands() titleizeOperands: -> return "<DETACHED>" unless @operands @operands.map((x) -> x.operandTitle()).join(', ') operandTitle: -> JST['nodes/operands/instruction'] name: @name
[ { "context": "=================================\n# Copyright 2014 Hatio, Lab.\n# Licensed under The MIT License\n# http", "end": 63, "score": 0.6132062077522278, "start": 62, "tag": "NAME", "value": "H" } ]
src/debug.coffee
heartyoh/dou
1
# ========================================== # Copyright 2014 Hatio, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [], -> "use strict" # ========================================== # Search object model # ========================================== global = if typeof(window) is 'undefined' then {} else window traverse = (comparator, clue, options) -> options = options or {} obj = options.obj or global path = options.path or (if obj is global then 'global' else '') for own prop of obj if (tests[comparator] or comparator)(clue, obj, prop) console.log "#{path}.#{prop} -> (#{typeof obj[prop]})", obj[prop] if obj[prop] and typeof obj[prop] is 'object' and obj[prop] isnt obj traverse comparator, clue, { obj: obj[prop], path: "#{path}.#{prop}" } search = (comparator, expected, clue, options) -> if !expected or typeof clue is expected traverse comparator, clue, options else console.error "#{clue} must be #{expected}" tests = name: (clue, obj, prop) -> clue is prop nameContains: (clue, obj, prop) -> prop.indexOf(clue) > -1 type: (clue, obj, prop) -> obj[prop] instanceof clue value: (clue, obj, prop) -> obj[prop] is clue valueCoerced: (clue, obj, prop) -> `obj[prop] == clue` byName = (clue, options) -> search('name', 'string', clue, options) byNameContains = (clue, options) -> search('nameContains', 'string', clue, options) byType = (clue, options) -> search('type', 'function', clue, options) byValue = (clue, options) -> search('value', null, clue, options) byValueCoerced = (clue, options) -> search('valueCoerced', null, clue, options) custom = (comparator, options) -> traverse(comparator, null, options) # ========================================== # Event logging # ========================================== filterEventLogsByAction = -> actions = [].slice.call(arguments) logFilter.eventNames.length || (logFilter.eventNames = ALL) logFilter.actions = if actions.length then actions else ALL saveLogFilter() filterEventLogsByName = -> eventNames = [].slice.call(arguments) logFilter.actions.length || (logFilter.actions = ALL) logFilter.eventNames = if eventNames.length then eventNames else ALL saveLogFilter() hideAllEventLogs = -> logFilter.actions = [] logFilter.eventNames = [] saveLogFilter() showAllEventLogs = -> logFilter.actions = ALL logFilter.eventNames = ALL saveLogFilter() saveLogFilter = -> if (global.localStorage) global.localStorage.setItem('logFilter_eventNames', logFilter.eventNames) global.localStorage.setItem('logFilter_actions', logFilter.actions) retrieveLogFilter = -> result = eventNames: (global.localStorage && global.localStorage.getItem('logFilter_eventNames')) || defaultEventNamesFilter actions: (global.localStorage && global.localStorage.getItem('logFilter_actions')) || defaultActionsFilter # reconstitute arrays result[key] = value.split('.') for own key, value of result when typeof value == 'string' and value isnt ALL result ALL = 'all'; # no filter # no logging by default defaultEventNamesFilter = [] defaultActionsFilter = [] logFilter = retrieveLogFilter() { enable: (enable) -> this.enabled = !! enable if (enable && global.console) console.info 'Booting in DEBUG mode' console.info 'You can configure event logging with DEBUG.events.logAll()/logNone()/logByName()/logByAction()' global.DEBUG = this find: byName: byName byNameContains: byNameContains byType: byType byValue: byValue byValueCoerced: byValueCoerced custom: custom events: logFilter: logFilter # Accepts any number of action args # e.g. DEBUG.events.logByAction("on", "off") logByAction: filterEventLogsByAction # Accepts any number of event name args (inc. regex or wildcards) # e.g. DEBUG.events.logByName(/ui.*/, "*Thread*"); logByName: filterEventLogsByName logAll: showAllEventLogs, logNone: hideAllEventLogs }
82168
# ========================================== # Copyright 2014 <NAME>atio, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [], -> "use strict" # ========================================== # Search object model # ========================================== global = if typeof(window) is 'undefined' then {} else window traverse = (comparator, clue, options) -> options = options or {} obj = options.obj or global path = options.path or (if obj is global then 'global' else '') for own prop of obj if (tests[comparator] or comparator)(clue, obj, prop) console.log "#{path}.#{prop} -> (#{typeof obj[prop]})", obj[prop] if obj[prop] and typeof obj[prop] is 'object' and obj[prop] isnt obj traverse comparator, clue, { obj: obj[prop], path: "#{path}.#{prop}" } search = (comparator, expected, clue, options) -> if !expected or typeof clue is expected traverse comparator, clue, options else console.error "#{clue} must be #{expected}" tests = name: (clue, obj, prop) -> clue is prop nameContains: (clue, obj, prop) -> prop.indexOf(clue) > -1 type: (clue, obj, prop) -> obj[prop] instanceof clue value: (clue, obj, prop) -> obj[prop] is clue valueCoerced: (clue, obj, prop) -> `obj[prop] == clue` byName = (clue, options) -> search('name', 'string', clue, options) byNameContains = (clue, options) -> search('nameContains', 'string', clue, options) byType = (clue, options) -> search('type', 'function', clue, options) byValue = (clue, options) -> search('value', null, clue, options) byValueCoerced = (clue, options) -> search('valueCoerced', null, clue, options) custom = (comparator, options) -> traverse(comparator, null, options) # ========================================== # Event logging # ========================================== filterEventLogsByAction = -> actions = [].slice.call(arguments) logFilter.eventNames.length || (logFilter.eventNames = ALL) logFilter.actions = if actions.length then actions else ALL saveLogFilter() filterEventLogsByName = -> eventNames = [].slice.call(arguments) logFilter.actions.length || (logFilter.actions = ALL) logFilter.eventNames = if eventNames.length then eventNames else ALL saveLogFilter() hideAllEventLogs = -> logFilter.actions = [] logFilter.eventNames = [] saveLogFilter() showAllEventLogs = -> logFilter.actions = ALL logFilter.eventNames = ALL saveLogFilter() saveLogFilter = -> if (global.localStorage) global.localStorage.setItem('logFilter_eventNames', logFilter.eventNames) global.localStorage.setItem('logFilter_actions', logFilter.actions) retrieveLogFilter = -> result = eventNames: (global.localStorage && global.localStorage.getItem('logFilter_eventNames')) || defaultEventNamesFilter actions: (global.localStorage && global.localStorage.getItem('logFilter_actions')) || defaultActionsFilter # reconstitute arrays result[key] = value.split('.') for own key, value of result when typeof value == 'string' and value isnt ALL result ALL = 'all'; # no filter # no logging by default defaultEventNamesFilter = [] defaultActionsFilter = [] logFilter = retrieveLogFilter() { enable: (enable) -> this.enabled = !! enable if (enable && global.console) console.info 'Booting in DEBUG mode' console.info 'You can configure event logging with DEBUG.events.logAll()/logNone()/logByName()/logByAction()' global.DEBUG = this find: byName: byName byNameContains: byNameContains byType: byType byValue: byValue byValueCoerced: byValueCoerced custom: custom events: logFilter: logFilter # Accepts any number of action args # e.g. DEBUG.events.logByAction("on", "off") logByAction: filterEventLogsByAction # Accepts any number of event name args (inc. regex or wildcards) # e.g. DEBUG.events.logByName(/ui.*/, "*Thread*"); logByName: filterEventLogsByName logAll: showAllEventLogs, logNone: hideAllEventLogs }
true
# ========================================== # Copyright 2014 PI:NAME:<NAME>END_PIatio, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [], -> "use strict" # ========================================== # Search object model # ========================================== global = if typeof(window) is 'undefined' then {} else window traverse = (comparator, clue, options) -> options = options or {} obj = options.obj or global path = options.path or (if obj is global then 'global' else '') for own prop of obj if (tests[comparator] or comparator)(clue, obj, prop) console.log "#{path}.#{prop} -> (#{typeof obj[prop]})", obj[prop] if obj[prop] and typeof obj[prop] is 'object' and obj[prop] isnt obj traverse comparator, clue, { obj: obj[prop], path: "#{path}.#{prop}" } search = (comparator, expected, clue, options) -> if !expected or typeof clue is expected traverse comparator, clue, options else console.error "#{clue} must be #{expected}" tests = name: (clue, obj, prop) -> clue is prop nameContains: (clue, obj, prop) -> prop.indexOf(clue) > -1 type: (clue, obj, prop) -> obj[prop] instanceof clue value: (clue, obj, prop) -> obj[prop] is clue valueCoerced: (clue, obj, prop) -> `obj[prop] == clue` byName = (clue, options) -> search('name', 'string', clue, options) byNameContains = (clue, options) -> search('nameContains', 'string', clue, options) byType = (clue, options) -> search('type', 'function', clue, options) byValue = (clue, options) -> search('value', null, clue, options) byValueCoerced = (clue, options) -> search('valueCoerced', null, clue, options) custom = (comparator, options) -> traverse(comparator, null, options) # ========================================== # Event logging # ========================================== filterEventLogsByAction = -> actions = [].slice.call(arguments) logFilter.eventNames.length || (logFilter.eventNames = ALL) logFilter.actions = if actions.length then actions else ALL saveLogFilter() filterEventLogsByName = -> eventNames = [].slice.call(arguments) logFilter.actions.length || (logFilter.actions = ALL) logFilter.eventNames = if eventNames.length then eventNames else ALL saveLogFilter() hideAllEventLogs = -> logFilter.actions = [] logFilter.eventNames = [] saveLogFilter() showAllEventLogs = -> logFilter.actions = ALL logFilter.eventNames = ALL saveLogFilter() saveLogFilter = -> if (global.localStorage) global.localStorage.setItem('logFilter_eventNames', logFilter.eventNames) global.localStorage.setItem('logFilter_actions', logFilter.actions) retrieveLogFilter = -> result = eventNames: (global.localStorage && global.localStorage.getItem('logFilter_eventNames')) || defaultEventNamesFilter actions: (global.localStorage && global.localStorage.getItem('logFilter_actions')) || defaultActionsFilter # reconstitute arrays result[key] = value.split('.') for own key, value of result when typeof value == 'string' and value isnt ALL result ALL = 'all'; # no filter # no logging by default defaultEventNamesFilter = [] defaultActionsFilter = [] logFilter = retrieveLogFilter() { enable: (enable) -> this.enabled = !! enable if (enable && global.console) console.info 'Booting in DEBUG mode' console.info 'You can configure event logging with DEBUG.events.logAll()/logNone()/logByName()/logByAction()' global.DEBUG = this find: byName: byName byNameContains: byNameContains byType: byType byValue: byValue byValueCoerced: byValueCoerced custom: custom events: logFilter: logFilter # Accepts any number of action args # e.g. DEBUG.events.logByAction("on", "off") logByAction: filterEventLogsByAction # Accepts any number of event name args (inc. regex or wildcards) # e.g. DEBUG.events.logByName(/ui.*/, "*Thread*"); logByName: filterEventLogsByName logAll: showAllEventLogs, logNone: hideAllEventLogs }
[ { "context": "import() with the given key\", (done) ->\n\n key = '1234567'\n gdocImportStub = sinon.stub(GDocIndicatorImpor", "end": 1517, "score": 0.9996476769447327, "start": 1510, "tag": "KEY", "value": "1234567" } ]
server/test/units/controllers/indicator.coffee
unepwcmc/NRT
0
assert = require('chai').assert helpers = require '../../helpers' sinon = require('sinon') Promise = require('bluebird') IndicatorController = require('../../../controllers/indicators') GDocIndicatorImporter = require('../../../lib/gdoc_indicator_importer') Permissions = require('../../../lib/services/permissions') suite('Indicator Controller') test(".show redirects back if trying to create a draft when Permissions::canEdit returns false", (done) -> canEditStub = sinon.stub(Permissions::, 'canEdit', -> return false ) fakeReq = path: '/indicators/432523/draft' fakeRes = redirect: (action) -> try assert.strictEqual action, "back", "Expected to be redirected back" done() catch err done(err) finally canEditStub.restore() IndicatorController.show(fakeReq, fakeRes) canEditStub.restore() ) test(".publishDraft redirects back if Permissions::canEdit returns false", (done) -> canEditStub = sinon.stub(Permissions::, 'canEdit', -> return false ) fakeReq = path: '/indicators/432523/draft' fakeRes = redirect: (action) -> try assert.strictEqual action, "back", "Expected to be redirected back" done() catch err done(err) finally canEditStub.restore() IndicatorController.publishDraft(fakeReq, fakeRes) canEditStub.restore() ) test(".importGdoc calls GDocIndicatorImporter.import() with the given key", (done) -> key = '1234567' gdocImportStub = sinon.stub(GDocIndicatorImporter, 'import', (key) -> Promise.resolve() ) fakeReq = path: '/indicators/import_gdoc' body: spreadsheetKey: key fakeRes = send: (code, body) -> try assert.strictEqual code, 201, "Expected response code to be 201" assert.strictEqual gdocImportStub.callCount, 1, "Expected GDocIndicatorImporter.import to be called once" assert.isTrue gdocImportStub.calledWith(key), "Expected GDocIndicatorImporter.import to be called with the given key" done() catch err done(err) finally gdocImportStub.restore() IndicatorController.importGdoc(fakeReq, fakeRes) if gdocImportStub.restore? # Only restore if not restored already gdocImportStub.restore() )
154933
assert = require('chai').assert helpers = require '../../helpers' sinon = require('sinon') Promise = require('bluebird') IndicatorController = require('../../../controllers/indicators') GDocIndicatorImporter = require('../../../lib/gdoc_indicator_importer') Permissions = require('../../../lib/services/permissions') suite('Indicator Controller') test(".show redirects back if trying to create a draft when Permissions::canEdit returns false", (done) -> canEditStub = sinon.stub(Permissions::, 'canEdit', -> return false ) fakeReq = path: '/indicators/432523/draft' fakeRes = redirect: (action) -> try assert.strictEqual action, "back", "Expected to be redirected back" done() catch err done(err) finally canEditStub.restore() IndicatorController.show(fakeReq, fakeRes) canEditStub.restore() ) test(".publishDraft redirects back if Permissions::canEdit returns false", (done) -> canEditStub = sinon.stub(Permissions::, 'canEdit', -> return false ) fakeReq = path: '/indicators/432523/draft' fakeRes = redirect: (action) -> try assert.strictEqual action, "back", "Expected to be redirected back" done() catch err done(err) finally canEditStub.restore() IndicatorController.publishDraft(fakeReq, fakeRes) canEditStub.restore() ) test(".importGdoc calls GDocIndicatorImporter.import() with the given key", (done) -> key = '<KEY>' gdocImportStub = sinon.stub(GDocIndicatorImporter, 'import', (key) -> Promise.resolve() ) fakeReq = path: '/indicators/import_gdoc' body: spreadsheetKey: key fakeRes = send: (code, body) -> try assert.strictEqual code, 201, "Expected response code to be 201" assert.strictEqual gdocImportStub.callCount, 1, "Expected GDocIndicatorImporter.import to be called once" assert.isTrue gdocImportStub.calledWith(key), "Expected GDocIndicatorImporter.import to be called with the given key" done() catch err done(err) finally gdocImportStub.restore() IndicatorController.importGdoc(fakeReq, fakeRes) if gdocImportStub.restore? # Only restore if not restored already gdocImportStub.restore() )
true
assert = require('chai').assert helpers = require '../../helpers' sinon = require('sinon') Promise = require('bluebird') IndicatorController = require('../../../controllers/indicators') GDocIndicatorImporter = require('../../../lib/gdoc_indicator_importer') Permissions = require('../../../lib/services/permissions') suite('Indicator Controller') test(".show redirects back if trying to create a draft when Permissions::canEdit returns false", (done) -> canEditStub = sinon.stub(Permissions::, 'canEdit', -> return false ) fakeReq = path: '/indicators/432523/draft' fakeRes = redirect: (action) -> try assert.strictEqual action, "back", "Expected to be redirected back" done() catch err done(err) finally canEditStub.restore() IndicatorController.show(fakeReq, fakeRes) canEditStub.restore() ) test(".publishDraft redirects back if Permissions::canEdit returns false", (done) -> canEditStub = sinon.stub(Permissions::, 'canEdit', -> return false ) fakeReq = path: '/indicators/432523/draft' fakeRes = redirect: (action) -> try assert.strictEqual action, "back", "Expected to be redirected back" done() catch err done(err) finally canEditStub.restore() IndicatorController.publishDraft(fakeReq, fakeRes) canEditStub.restore() ) test(".importGdoc calls GDocIndicatorImporter.import() with the given key", (done) -> key = 'PI:KEY:<KEY>END_PI' gdocImportStub = sinon.stub(GDocIndicatorImporter, 'import', (key) -> Promise.resolve() ) fakeReq = path: '/indicators/import_gdoc' body: spreadsheetKey: key fakeRes = send: (code, body) -> try assert.strictEqual code, 201, "Expected response code to be 201" assert.strictEqual gdocImportStub.callCount, 1, "Expected GDocIndicatorImporter.import to be called once" assert.isTrue gdocImportStub.calledWith(key), "Expected GDocIndicatorImporter.import to be called with the given key" done() catch err done(err) finally gdocImportStub.restore() IndicatorController.importGdoc(fakeReq, fakeRes) if gdocImportStub.restore? # Only restore if not restored already gdocImportStub.restore() )
[ { "context": " ContactName\n key: contact.get('_id')\n contact: contact\n _t", "end": 2170, "score": 0.8915245532989502, "start": 2162, "tag": "KEY", "value": "get('_id" } ]
talk-web/client/app/panel-chat.coffee
ikingye/talk-os
3,084
React = require 'react' Immutable = require 'immutable' cx = require 'classnames' recorder = require 'actions-recorder' PureRenderMixin = require 'react-addons-pure-render-mixin' query = require '../query' mixinQuery = require '../mixin/query' detect = require '../util/detect' search = require '../util/search' orders = require '../util/orders' analytics = require '../util/analytics' lang = require '../locales/lang' contactActions = require '../actions/contact' Permission = require '../module/permission' routerHandlers = require '../handlers/router' ContactName = React.createFactory require './contact-name' SearchBox = React.createFactory require('react-lite-misc').SearchBox { a, p, div, span, input, textarea } = React.DOM T = React.PropTypes module.exports = React.createClass displayName: 'panel-chat' mixins: [PureRenderMixin, mixinQuery] propTypes: _teamId: T.string.isRequired contacts: T.instanceOf(Immutable.List).isRequired leftContacts: T.instanceOf(Immutable.List).isRequired onClose: T.func getInitialState: -> showForm: false value: '' filterList: (list) -> search.forMembers list, @state.value, getAlias: @getContactAlias .sort orders.byPinyin onAddClick: -> @setState showForm: (not @state.showForm) onChange: (value) -> @setState { value } onItemClick: (contact) -> _userId = query.userId(recorder.getState()) if contact.get('_id') isnt _userId routerHandlers.chat @props._teamId, contact.get('_id'), {}, @props.onClose analytics.enterChatFromStory() renderContacts: (type) -> if type is 'leftContacts' filteredList = @filterList(@props.leftContacts) info = lang.getText('contact-quitted') else filteredList = @filterList(@props.contacts) info = lang.getText('members-list') if filteredList.size > 0 div className: 'item-list contact-list', p className: 'info muted', "#{info} (#{filteredList.size})" if filteredList.size > 0 filteredList.map (contact) => onItemClick = => @onItemClick contact ContactName key: contact.get('_id') contact: contact _teamId: @props._teamId onClick: onItemClick renderHeader: -> div className: 'header', SearchBox value: @state.value onChange: @onChange locale: lang.getText('search-members') autoFocus: not detect.isIPad() render: -> div className: 'panel-chat', @renderHeader() @renderContacts() @renderContacts('leftContacts')
100146
React = require 'react' Immutable = require 'immutable' cx = require 'classnames' recorder = require 'actions-recorder' PureRenderMixin = require 'react-addons-pure-render-mixin' query = require '../query' mixinQuery = require '../mixin/query' detect = require '../util/detect' search = require '../util/search' orders = require '../util/orders' analytics = require '../util/analytics' lang = require '../locales/lang' contactActions = require '../actions/contact' Permission = require '../module/permission' routerHandlers = require '../handlers/router' ContactName = React.createFactory require './contact-name' SearchBox = React.createFactory require('react-lite-misc').SearchBox { a, p, div, span, input, textarea } = React.DOM T = React.PropTypes module.exports = React.createClass displayName: 'panel-chat' mixins: [PureRenderMixin, mixinQuery] propTypes: _teamId: T.string.isRequired contacts: T.instanceOf(Immutable.List).isRequired leftContacts: T.instanceOf(Immutable.List).isRequired onClose: T.func getInitialState: -> showForm: false value: '' filterList: (list) -> search.forMembers list, @state.value, getAlias: @getContactAlias .sort orders.byPinyin onAddClick: -> @setState showForm: (not @state.showForm) onChange: (value) -> @setState { value } onItemClick: (contact) -> _userId = query.userId(recorder.getState()) if contact.get('_id') isnt _userId routerHandlers.chat @props._teamId, contact.get('_id'), {}, @props.onClose analytics.enterChatFromStory() renderContacts: (type) -> if type is 'leftContacts' filteredList = @filterList(@props.leftContacts) info = lang.getText('contact-quitted') else filteredList = @filterList(@props.contacts) info = lang.getText('members-list') if filteredList.size > 0 div className: 'item-list contact-list', p className: 'info muted', "#{info} (#{filteredList.size})" if filteredList.size > 0 filteredList.map (contact) => onItemClick = => @onItemClick contact ContactName key: contact.<KEY>') contact: contact _teamId: @props._teamId onClick: onItemClick renderHeader: -> div className: 'header', SearchBox value: @state.value onChange: @onChange locale: lang.getText('search-members') autoFocus: not detect.isIPad() render: -> div className: 'panel-chat', @renderHeader() @renderContacts() @renderContacts('leftContacts')
true
React = require 'react' Immutable = require 'immutable' cx = require 'classnames' recorder = require 'actions-recorder' PureRenderMixin = require 'react-addons-pure-render-mixin' query = require '../query' mixinQuery = require '../mixin/query' detect = require '../util/detect' search = require '../util/search' orders = require '../util/orders' analytics = require '../util/analytics' lang = require '../locales/lang' contactActions = require '../actions/contact' Permission = require '../module/permission' routerHandlers = require '../handlers/router' ContactName = React.createFactory require './contact-name' SearchBox = React.createFactory require('react-lite-misc').SearchBox { a, p, div, span, input, textarea } = React.DOM T = React.PropTypes module.exports = React.createClass displayName: 'panel-chat' mixins: [PureRenderMixin, mixinQuery] propTypes: _teamId: T.string.isRequired contacts: T.instanceOf(Immutable.List).isRequired leftContacts: T.instanceOf(Immutable.List).isRequired onClose: T.func getInitialState: -> showForm: false value: '' filterList: (list) -> search.forMembers list, @state.value, getAlias: @getContactAlias .sort orders.byPinyin onAddClick: -> @setState showForm: (not @state.showForm) onChange: (value) -> @setState { value } onItemClick: (contact) -> _userId = query.userId(recorder.getState()) if contact.get('_id') isnt _userId routerHandlers.chat @props._teamId, contact.get('_id'), {}, @props.onClose analytics.enterChatFromStory() renderContacts: (type) -> if type is 'leftContacts' filteredList = @filterList(@props.leftContacts) info = lang.getText('contact-quitted') else filteredList = @filterList(@props.contacts) info = lang.getText('members-list') if filteredList.size > 0 div className: 'item-list contact-list', p className: 'info muted', "#{info} (#{filteredList.size})" if filteredList.size > 0 filteredList.map (contact) => onItemClick = => @onItemClick contact ContactName key: contact.PI:KEY:<KEY>END_PI') contact: contact _teamId: @props._teamId onClick: onItemClick renderHeader: -> div className: 'header', SearchBox value: @state.value onChange: @onChange locale: lang.getText('search-members') autoFocus: not detect.isIPad() render: -> div className: 'panel-chat', @renderHeader() @renderContacts() @renderContacts('leftContacts')
[ { "context": " * BracketsExtensionTweetBot\n * http://github.com/ingorichter/BracketsExtensionTweetBot\n *\n * Copyright (c) 201", "end": 65, "score": 0.9996579885482788, "start": 54, "tag": "USERNAME", "value": "ingorichter" }, { "context": "BracketsExtensionTweetBot\n *\n * Copyright (c) 2014 Ingo Richter\n * Licensed under the MIT license.\n###\n# jslint v", "end": 129, "score": 0.9998809099197388, "start": 117, "tag": "NAME", "value": "Ingo Richter" } ]
src/TwitterPublisher.coffee
ingorichter/BracketsExtensionTweetBot
0
### * BracketsExtensionTweetBot * http://github.com/ingorichter/BracketsExtensionTweetBot * * Copyright (c) 2014 Ingo Richter * Licensed under the MIT license. ### # jslint vars: true, plusplus: true, devel: true, node: true, nomen: true, indent: 4, maxerr: 50 'use strict' Promise = require 'bluebird' Twit = require 'twit' module.exports = class TwitterPublisher constructor: (config) -> @twitterClient = new Twit(config) setClient: (client) -> @twitterClient = client post: (tweet) -> new Promise (resolve, reject) => @twitterClient.post 'statuses/update', { status: tweet }, (err, reply, response) -> if err reject err else resolve reply # https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline # count - default is 20 defined by the twitter API # @param {?String} max_id - results lower or equal to max_id (to get older posts) userTimeLine: (max_id, count) -> new Promise (resolve, reject) => options = {} options.max_id = max_id if max_id? options.count = count if count? @twitterClient.get 'statuses/home_timeline', options, (err, reply, response) -> if err reject err else resolve reply search: (query, untilDate) -> new Promise (resolve, reject) => options = {} options.q = query options.until = untilDate if untilDate @twitterClient.get 'search/tweets', options, (err, reply, response) -> if err reject err else resolve reply
157194
### * BracketsExtensionTweetBot * http://github.com/ingorichter/BracketsExtensionTweetBot * * Copyright (c) 2014 <NAME> * Licensed under the MIT license. ### # jslint vars: true, plusplus: true, devel: true, node: true, nomen: true, indent: 4, maxerr: 50 'use strict' Promise = require 'bluebird' Twit = require 'twit' module.exports = class TwitterPublisher constructor: (config) -> @twitterClient = new Twit(config) setClient: (client) -> @twitterClient = client post: (tweet) -> new Promise (resolve, reject) => @twitterClient.post 'statuses/update', { status: tweet }, (err, reply, response) -> if err reject err else resolve reply # https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline # count - default is 20 defined by the twitter API # @param {?String} max_id - results lower or equal to max_id (to get older posts) userTimeLine: (max_id, count) -> new Promise (resolve, reject) => options = {} options.max_id = max_id if max_id? options.count = count if count? @twitterClient.get 'statuses/home_timeline', options, (err, reply, response) -> if err reject err else resolve reply search: (query, untilDate) -> new Promise (resolve, reject) => options = {} options.q = query options.until = untilDate if untilDate @twitterClient.get 'search/tweets', options, (err, reply, response) -> if err reject err else resolve reply
true
### * BracketsExtensionTweetBot * http://github.com/ingorichter/BracketsExtensionTweetBot * * Copyright (c) 2014 PI:NAME:<NAME>END_PI * Licensed under the MIT license. ### # jslint vars: true, plusplus: true, devel: true, node: true, nomen: true, indent: 4, maxerr: 50 'use strict' Promise = require 'bluebird' Twit = require 'twit' module.exports = class TwitterPublisher constructor: (config) -> @twitterClient = new Twit(config) setClient: (client) -> @twitterClient = client post: (tweet) -> new Promise (resolve, reject) => @twitterClient.post 'statuses/update', { status: tweet }, (err, reply, response) -> if err reject err else resolve reply # https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline # count - default is 20 defined by the twitter API # @param {?String} max_id - results lower or equal to max_id (to get older posts) userTimeLine: (max_id, count) -> new Promise (resolve, reject) => options = {} options.max_id = max_id if max_id? options.count = count if count? @twitterClient.get 'statuses/home_timeline', options, (err, reply, response) -> if err reject err else resolve reply search: (query, untilDate) -> new Promise (resolve, reject) => options = {} options.q = query options.until = untilDate if untilDate @twitterClient.get 'search/tweets', options, (err, reply, response) -> if err reject err else resolve reply
[ { "context": "# @file bubbles.coffee\n# @Copyright (c) 2016 Taylor Siviter\n# This source code is licensed under the MIT Lice", "end": 59, "score": 0.999773383140564, "start": 45, "tag": "NAME", "value": "Taylor Siviter" } ]
examples/bubbles/bubbles.coffee
siviter-t/lampyridae.coffee
4
# @file bubbles.coffee # @Copyright (c) 2016 Taylor Siviter # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. ### # Example usage of lampyridae.coffee ### require 'particle/firefly' canvas = new Lampyridae.Canvas 'world' Lampyridae.Firefly::hueMax = 225 Lampyridae.Firefly::hueMin = 180 Lampyridae.Firefly::lightness = '65%' Lampyridae.Firefly::opacity = 0.15 Lampyridae.Firefly::radiusMax = 150 Lampyridae.Firefly::radiusMin = 15 Lampyridae.Firefly::speedMax = 15 Lampyridae.Firefly::speedMin = 5 Lampyridae.Firefly::turningAngle = 0.2 * Math.PI total = 50 bubbles = [] createBubble = () -> for i in [0...total] bubble = new Lampyridae.Firefly canvas bubbles.push bubble update = () -> bubbles[i].update() for i in [0...total] createBubble() canvas.addUpdate canvas.draw.clear canvas.addUpdate update canvas.animate()
82591
# @file bubbles.coffee # @Copyright (c) 2016 <NAME> # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. ### # Example usage of lampyridae.coffee ### require 'particle/firefly' canvas = new Lampyridae.Canvas 'world' Lampyridae.Firefly::hueMax = 225 Lampyridae.Firefly::hueMin = 180 Lampyridae.Firefly::lightness = '65%' Lampyridae.Firefly::opacity = 0.15 Lampyridae.Firefly::radiusMax = 150 Lampyridae.Firefly::radiusMin = 15 Lampyridae.Firefly::speedMax = 15 Lampyridae.Firefly::speedMin = 5 Lampyridae.Firefly::turningAngle = 0.2 * Math.PI total = 50 bubbles = [] createBubble = () -> for i in [0...total] bubble = new Lampyridae.Firefly canvas bubbles.push bubble update = () -> bubbles[i].update() for i in [0...total] createBubble() canvas.addUpdate canvas.draw.clear canvas.addUpdate update canvas.animate()
true
# @file bubbles.coffee # @Copyright (c) 2016 PI:NAME:<NAME>END_PI # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. ### # Example usage of lampyridae.coffee ### require 'particle/firefly' canvas = new Lampyridae.Canvas 'world' Lampyridae.Firefly::hueMax = 225 Lampyridae.Firefly::hueMin = 180 Lampyridae.Firefly::lightness = '65%' Lampyridae.Firefly::opacity = 0.15 Lampyridae.Firefly::radiusMax = 150 Lampyridae.Firefly::radiusMin = 15 Lampyridae.Firefly::speedMax = 15 Lampyridae.Firefly::speedMin = 5 Lampyridae.Firefly::turningAngle = 0.2 * Math.PI total = 50 bubbles = [] createBubble = () -> for i in [0...total] bubble = new Lampyridae.Firefly canvas bubbles.push bubble update = () -> bubbles[i].update() for i in [0...total] createBubble() canvas.addUpdate canvas.draw.clear canvas.addUpdate update canvas.animate()
[ { "context": "###\n\n2015 - 2016 (c) by Marcel Kapfer (mmk2410)\n\nLicensed under MIT License\n\nRangitaki ", "end": 37, "score": 0.9998801946640015, "start": 24, "tag": "NAME", "value": "Marcel Kapfer" }, { "context": "###\n\n2015 - 2016 (c) by Marcel Kapfer (mmk2410)\n\nLicensed under MIT License\n\nRangitaki Gulp File", "end": 46, "score": 0.9990355968475342, "start": 39, "tag": "USERNAME", "value": "mmk2410" } ]
gulpfile.coffee
vishal2612200/rangitaki
0
### 2015 - 2016 (c) by Marcel Kapfer (mmk2410) Licensed under MIT License Rangitaki Gulp File ### gulp = require 'gulp' sass = require 'gulp-sass' sourcemaps = require 'gulp-sourcemaps' minifyCss = require 'gulp-csso' coffee = require 'gulp-coffee' coffeelint = require 'gulp-coffeelint' uglify = require 'gulp-uglify' merge = require 'merge-stream' del = require 'del' size = require 'gulp-size' gulp.task 'coffee', -> main = gulp.src './src/coffee/*.coffee' .pipe coffeelint() .pipe coffeelint.reporter() .pipe coffee() .pipe uglify() .pipe gulp.dest './res/js/' extensions = gulp.src './src/coffee-extensions/*.coffee' .pipe coffeelint() .pipe coffeelint.reporter() .pipe coffee() .pipe uglify() .pipe gulp.dest './extensions/' merge(main, extensions) .pipe size {title: 'Coffee'} gulp.task 'sass', -> main = gulp.src './src/sass/*.sass' .pipe sourcemaps.init() .pipe sass { outputStyle: 'compressed' } .pipe sourcemaps.write './' .pipe gulp.dest './res/css/' theme = gulp.src './src/sass-themes/*.sass' .pipe sourcemaps.init() .pipe sass { outputStyle: 'compressed' } .pipe sourcemaps.write './' .pipe gulp.dest './themes/' merge(theme, main) .pipe size {title: 'SASS'} gulp.task 'clean', del.bind null, ['res/css/no-nav.css', 'res/css/rangitaki.css', 'themes/', 'res/js/app.js'] gulp.task 'init', ['coffee', 'sass'] gulp.task 'default', -> gulp.watch './src/**/*.sass', ['sass'] gulp.watch './src/**/*.coffee', ['coffee']
33895
### 2015 - 2016 (c) by <NAME> (mmk2410) Licensed under MIT License Rangitaki Gulp File ### gulp = require 'gulp' sass = require 'gulp-sass' sourcemaps = require 'gulp-sourcemaps' minifyCss = require 'gulp-csso' coffee = require 'gulp-coffee' coffeelint = require 'gulp-coffeelint' uglify = require 'gulp-uglify' merge = require 'merge-stream' del = require 'del' size = require 'gulp-size' gulp.task 'coffee', -> main = gulp.src './src/coffee/*.coffee' .pipe coffeelint() .pipe coffeelint.reporter() .pipe coffee() .pipe uglify() .pipe gulp.dest './res/js/' extensions = gulp.src './src/coffee-extensions/*.coffee' .pipe coffeelint() .pipe coffeelint.reporter() .pipe coffee() .pipe uglify() .pipe gulp.dest './extensions/' merge(main, extensions) .pipe size {title: 'Coffee'} gulp.task 'sass', -> main = gulp.src './src/sass/*.sass' .pipe sourcemaps.init() .pipe sass { outputStyle: 'compressed' } .pipe sourcemaps.write './' .pipe gulp.dest './res/css/' theme = gulp.src './src/sass-themes/*.sass' .pipe sourcemaps.init() .pipe sass { outputStyle: 'compressed' } .pipe sourcemaps.write './' .pipe gulp.dest './themes/' merge(theme, main) .pipe size {title: 'SASS'} gulp.task 'clean', del.bind null, ['res/css/no-nav.css', 'res/css/rangitaki.css', 'themes/', 'res/js/app.js'] gulp.task 'init', ['coffee', 'sass'] gulp.task 'default', -> gulp.watch './src/**/*.sass', ['sass'] gulp.watch './src/**/*.coffee', ['coffee']
true
### 2015 - 2016 (c) by PI:NAME:<NAME>END_PI (mmk2410) Licensed under MIT License Rangitaki Gulp File ### gulp = require 'gulp' sass = require 'gulp-sass' sourcemaps = require 'gulp-sourcemaps' minifyCss = require 'gulp-csso' coffee = require 'gulp-coffee' coffeelint = require 'gulp-coffeelint' uglify = require 'gulp-uglify' merge = require 'merge-stream' del = require 'del' size = require 'gulp-size' gulp.task 'coffee', -> main = gulp.src './src/coffee/*.coffee' .pipe coffeelint() .pipe coffeelint.reporter() .pipe coffee() .pipe uglify() .pipe gulp.dest './res/js/' extensions = gulp.src './src/coffee-extensions/*.coffee' .pipe coffeelint() .pipe coffeelint.reporter() .pipe coffee() .pipe uglify() .pipe gulp.dest './extensions/' merge(main, extensions) .pipe size {title: 'Coffee'} gulp.task 'sass', -> main = gulp.src './src/sass/*.sass' .pipe sourcemaps.init() .pipe sass { outputStyle: 'compressed' } .pipe sourcemaps.write './' .pipe gulp.dest './res/css/' theme = gulp.src './src/sass-themes/*.sass' .pipe sourcemaps.init() .pipe sass { outputStyle: 'compressed' } .pipe sourcemaps.write './' .pipe gulp.dest './themes/' merge(theme, main) .pipe size {title: 'SASS'} gulp.task 'clean', del.bind null, ['res/css/no-nav.css', 'res/css/rangitaki.css', 'themes/', 'res/js/app.js'] gulp.task 'init', ['coffee', 'sass'] gulp.task 'default', -> gulp.watch './src/**/*.sass', ['sass'] gulp.watch './src/**/*.coffee', ['coffee']
[ { "context": "ach ->\n model = new Backbone.Model({name: 'Test <b>Name</b>'})\n\n describe 'html and text helpe", "end": 167, "score": 0.8112860918045044, "start": 163, "tag": "NAME", "value": "Test" } ]
test/html-text.coffee
redexp/backbone-dom-view
13
define ['chai', 'backbone', 'backbone-dom-view'], ({expect}, Backbone, DomView) -> model = null beforeEach -> model = new Backbone.Model({name: 'Test <b>Name</b>'}) describe 'html and text helpers', -> it 'should render as html', -> View = DomView.extend template: 'root': html: '=name' view = new View model: model el = view.$el expect(el).to.have.html 'Test <b>Name</b>' it 'should render as text', -> View = DomView.extend template: 'root': text: '=name' view = new View model: model el = view.$el expect(el).to.have.text 'Test <b>Name</b>' it 'should render null and undefined as empty text', -> View = DomView.extend template: 'root': text: '@name' view = new View model: model el = view.$el model.set('name', null); expect(el).to.have.text '' model.set('name', 0); expect(el).to.have.text '0' model.set('name', undefined); expect(el).to.have.text '' model.set('name', false); expect(el).to.have.text 'false' it 'should render as safe html', -> View = DomView.extend template: 'root': safeHtml: '=name' model.set('name', 'Test <script src="app.js"/> <script src="app.js"></script> <div onclick = "1 > 2; \'<div>\'; alert()" class="test" onkeyup=><font color="red" onclick = alert onkeyup=\'alert()\'>Name</font></div>') view = new View model: model el = view.$el expect(el).to.have.html 'Test <div style="display: none;" src="app.js"></div> <div style="display: none;" src="app.js"></div> <div x-click="1 > 2; \'<div>\'; alert()" class="test" x-keyup=""><font color="red" x-click="alert" x-keyup="alert()">Name</font></div>'
4657
define ['chai', 'backbone', 'backbone-dom-view'], ({expect}, Backbone, DomView) -> model = null beforeEach -> model = new Backbone.Model({name: '<NAME> <b>Name</b>'}) describe 'html and text helpers', -> it 'should render as html', -> View = DomView.extend template: 'root': html: '=name' view = new View model: model el = view.$el expect(el).to.have.html 'Test <b>Name</b>' it 'should render as text', -> View = DomView.extend template: 'root': text: '=name' view = new View model: model el = view.$el expect(el).to.have.text 'Test <b>Name</b>' it 'should render null and undefined as empty text', -> View = DomView.extend template: 'root': text: '@name' view = new View model: model el = view.$el model.set('name', null); expect(el).to.have.text '' model.set('name', 0); expect(el).to.have.text '0' model.set('name', undefined); expect(el).to.have.text '' model.set('name', false); expect(el).to.have.text 'false' it 'should render as safe html', -> View = DomView.extend template: 'root': safeHtml: '=name' model.set('name', 'Test <script src="app.js"/> <script src="app.js"></script> <div onclick = "1 > 2; \'<div>\'; alert()" class="test" onkeyup=><font color="red" onclick = alert onkeyup=\'alert()\'>Name</font></div>') view = new View model: model el = view.$el expect(el).to.have.html 'Test <div style="display: none;" src="app.js"></div> <div style="display: none;" src="app.js"></div> <div x-click="1 > 2; \'<div>\'; alert()" class="test" x-keyup=""><font color="red" x-click="alert" x-keyup="alert()">Name</font></div>'
true
define ['chai', 'backbone', 'backbone-dom-view'], ({expect}, Backbone, DomView) -> model = null beforeEach -> model = new Backbone.Model({name: 'PI:NAME:<NAME>END_PI <b>Name</b>'}) describe 'html and text helpers', -> it 'should render as html', -> View = DomView.extend template: 'root': html: '=name' view = new View model: model el = view.$el expect(el).to.have.html 'Test <b>Name</b>' it 'should render as text', -> View = DomView.extend template: 'root': text: '=name' view = new View model: model el = view.$el expect(el).to.have.text 'Test <b>Name</b>' it 'should render null and undefined as empty text', -> View = DomView.extend template: 'root': text: '@name' view = new View model: model el = view.$el model.set('name', null); expect(el).to.have.text '' model.set('name', 0); expect(el).to.have.text '0' model.set('name', undefined); expect(el).to.have.text '' model.set('name', false); expect(el).to.have.text 'false' it 'should render as safe html', -> View = DomView.extend template: 'root': safeHtml: '=name' model.set('name', 'Test <script src="app.js"/> <script src="app.js"></script> <div onclick = "1 > 2; \'<div>\'; alert()" class="test" onkeyup=><font color="red" onclick = alert onkeyup=\'alert()\'>Name</font></div>') view = new View model: model el = view.$el expect(el).to.have.html 'Test <div style="display: none;" src="app.js"></div> <div style="display: none;" src="app.js"></div> <div x-click="1 > 2; \'<div>\'; alert()" class="test" x-keyup=""><font color="red" x-click="alert" x-keyup="alert()">Name</font></div>'
[ { "context": "_bits * POW_NEG_26) * POW_NEG_27\n\n setstate: ([@_next_gauss, state...]) =>\n # Set the state of the PRN", "end": 2166, "score": 0.9750388860702515, "start": 2154, "tag": "USERNAME", "value": "@_next_gauss" }, { "context": " suitable for passing into `@setstate`.\n [@_next_gauss, @_getstate()...]\n\n _bits = {}\n _randbelow:", "end": 2488, "score": 0.9757410883903503, "start": 2478, "tag": "USERNAME", "value": "next_gauss" }, { "context": " #\n # Based upon an algorithm published in: Fisher, N.I.,\n # \"Statistical Analysis of Circular Dat", "end": 6956, "score": 0.9590254426002502, "start": 6945, "tag": "NAME", "value": "Fisher, N.I" }, { "context": " = @random\n if alpha > 1\n # Uses R.C.H. Cheng, \"The generation of Gamma\n # variables", "end": 8289, "score": 0.9998481273651123, "start": 8277, "tag": "NAME", "value": "R.C.H. Cheng" }, { "context": "pow -log u, 1 / beta) # Jain, pg. 499; bug fix by Bill Arms\n\n\nclass Random extends BaseRandom\n # Use a Mul", "end": 10452, "score": 0.9885175824165344, "start": 10443, "tag": "NAME", "value": "Bill Arms" } ]
random.coffee
jrus/random-js
7
### A fairly direct port of the Python `random` module to JavaScript ### {log, sqrt, cos, acos, floor, pow, LOG2E, exp} = Math POW_32 = pow 2, 32 POW_NEG_32 = pow 2, -32 lg = (x) -> # The log base 2, rounded down to the integer below (LOG2E * log x + 1e-10) >> 0 mod = (x, y) -> unless (jsmod = x % y) and (x > 0 ^ y > 0) then jsmod else jsmod + y extend = (target, sources...) -> for obj in sources target[name] = method for name, method of obj target bind = (fn, obj) -> -> fn.apply obj, arguments class NotImplementedError extends Error class BaseRandom ## Override these first four methods in a custom Random class. _randint32: -> # Override this method to generate a pseudorandom number throw new NotImplementedError _getstate: -> # Override this method to fetch the internal PRNG state. Should # return an Array. throw new NotImplementedError _setstate: (state) -> # Override this method to set the internal PRNG state from the # argument `state`, an Array. throw new NotImplementedError _seed: (args...) -> # Override this method to seed the PRNG throw new NotImplementedError ## Generally no need to override the methods below in a custom class. ## (Under some circumstances it might make sense to implement a custom ## version of the `random` method or add to the constructor.) constructor: -> # bind `normalvariate` (def. below as a `gauss` alias) to the instance @normalvariate = bind @normalvariate, @ # By default, just seed the PRNG with the date. Some PRNGs # can take longer and more complex seeds. @_next_gauss = null @seed +new Date seed: (args...) => # Seed the PRNG. @_seed args... POW_NEG_26 = pow 2, -26 POW_NEG_27 = pow 2, -27 random: => # Return a random float in the range [0, 1), with a full 53 # bits of entropy. low_bits = @_randint32() >>> 6 high_bits = @_randint32() >>> 5 (high_bits + low_bits * POW_NEG_26) * POW_NEG_27 setstate: ([@_next_gauss, state...]) => # Set the state of the PRNG. Should accept the output of `@getstate` # as its only argument. @_setstate state getstate: => # Get the internal state of the PRNG. Returns an array of state # information suitable for passing into `@setstate`. [@_next_gauss, @_getstate()...] _bits = {} _randbelow: (n) -> # Return a random int in the range [0,n). # If n > 2^32, then use floating point math if n <= 0x100000000 bits = _bits[n] or= (lg n - 1) + 1 # memoize values for `bits` loop r = @_randint32() >>> (32 - bits) r += POW_32 if r < 0 break if r < n r else floor @random() * n uniform: (a, b) => # Return a random floating point number N such that a <= N <= b for # a <= b and b <= N <= a for b < a. a + @random() * (b - a) randrange: (start, stop, step) => # Return a random integer N in range `[start...stop] by step` unless stop? @_randbelow start else unless step start + @_randbelow stop - start else start + step * @_randbelow floor (stop - start) / step randint: (a, b) => # Return a random integer N in range `[a..b]` a + @_randbelow 1 + b - a choice: (seq) => # Return a random element from the non-empty sequence `seq`. seq[@_randbelow seq.length] sample: (population, k=1) => # Return a `k` length list of unique elements chosen from the # `population` sequence. Used for random sampling without replacement. n = population.length if k > n throw new Error "can't take a sample bigger than the population" if k * 3 > n # for large samples, copy the pool = [population...] # population as a new array for i in [n...n - k] by -1 j = @_randbelow i val = pool[j] pool[j] = pool[i - 1] # move non-chosen item into vacancy val else # for small samples, treat an Array selected = [] # as a set to keep track of selection for i in [0...k] by 1 loop break if (j = @_randbelow n) not in selected selected.push j population[j] shuffle: (x) => # Shuffle the sequence x in place. for i in [x.length - 1..1] by -1 j = @_randbelow i + 1 tmp = x[i]; x[i] = x[j]; x[j] = tmp # swap x[i], x[j] x gauss: (mu=0, sigma=1) => # Gaussian distribution. `mu` is the mean, and `sigma` is the standard # deviation. Notes: # * uses the "polar method" # * we generate pairs; keep one in a cache for next time if (z = @_next_gauss)? then @_next_gauss = null else until s and s < 1 u = 2 * @random() - 1 v = 2 * @random() - 1 s = u*u + v*v w = sqrt -2 * (log s) / s z = u * w; @_next_gauss = v * w mu + z * sigma normalvariate: @::gauss # Alias for the `gauss` function triangular: (low, high, mode) => # Triangular distribution. See wikipedia unless low? then high = 1; low = 0 else unless high? then high = low; low = 0 unless mode? c = 0.5 else c = (mode - low) / (high - low) u = @random() if u <= c low + (high - low) * sqrt u * c else high - (high - low) * sqrt (1 - u) * (1 - c) lognormvariate: (mu, sigma) => # Log normal distribution. exp @normalvariate mu, sigma expovariate: (lambda) => # Exponential distribution. # # `lambda` is 1.0 divided by the desired mean. It should be nonzero. # Returned values range from 0 to positive infinity if lambda is positive, # and from negative infinity to 0 if lambda is negative. # # we use 1 - random() instead of random() to preclude the # possibility of taking the log of zero. (- log 1 - @random()) / lambda TAU = 2 * Math.PI vonmisesvariate: (mu, kappa) => # Circular data distribution. # # mu is the mean angle, expressed in radians between 0 and 2*pi, and # kappa is the concentration parameter, which must be greater than or # equal to zero. If kappa is equal to zero, this distribution reduces # to a uniform random angle over the range 0 to 2*pi. # # Based upon an algorithm published in: Fisher, N.I., # "Statistical Analysis of Circular Data", Cambridge # University Press, 1993. rand = @random return TAU * rand() if kappa <= 1e-6 a = 1 + sqrt 1 + 4 * kappa*kappa b = (1 - sqrt 2) * a / 2 / kappa r = (1 + b*b) / 2 / b loop u1 = rand() z = cos TAU * u1 / 2 f = (1 + r * z) / (r + z) c = kappa * (r - f) u2 = rand() break if u2 < c * (2 - c) or u2 <= c * exp 1 - c u3 = rand() (mod mu, TAU) + (if u3 > 0.5 then acos f else -acos f) LOG4 = log 4 SG_MAGICCONST = 1 + log 4.5 E = {Math} gammavariate: (alpha, beta) => # Gamma distribution. Not the gamma function! # # Conditions on the parameters are alpha > 0 and beta > 0. # # The probability distribution function is: # # x ** (alpha - 1) * exp( -x / beta) # pdf(x) = ---------------------------------- # gamma(alpha) * beta ** alpha # alpha > 0, beta > 0, mean is alpha * beta, variance is alpha * beta**2 # # Warning: a few older sources define the gamma distribution in terms # of alpha > -1 rand = @random if alpha > 1 # Uses R.C.H. Cheng, "The generation of Gamma # variables with non-integral shape parameters", # Applied Statistics, (1977), 26, No. 1, p71-74 ainv = sqrt 2 * alpha - 1 bbb = alpha - LOG4 ccc = alpha + ainv loop u1 = rand() continue unless 1e-7 < u1 < 1 - 1e-7 u2 = 1 - rand() v = (log u1 / (1 - u1)) / ainv x = alpha * exp v z = u1 * u1 * u2 r = bbb + ccc * v - x break if r + SG_MAGICCONST - 4.5 * z >= 0.0 or r >= log z beta * x else if alpha == 1 # expovariate(1) loop u = rand() break if u > 1e-7 -beta * log u else # alpha is between 0 and 1 (exclusive) # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle loop u1 = rand() b = (E + alpha) / E p = b * u1 u2 = rand() if p > 1 x = - log (b - p) / alpha break if u2 <= pow x, alpha - 1 else x = pow p, 1 / alpha break if u2 <= exp -x beta * x betavariate: (alpha, beta) => # Beta distribution. # # Conditions on the parameters are alpha > 0 and beta > 0. # Returned values range between 0 and 1. # This version due to Janne Sinkkonen, and matches all the std # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution"). y = @gammavariate alpha, 1 if y == 0 then 0 else y / (y + @gammavariate beta, 1) paretovariate: (alpha) => # Pareto distribution. alpha is the shape parameter. u = 1 - @random() 1 / (pow u, 1 / alpha) # Jain, pg. 495 weibullvariate: (alpha, beta) => # Weibull distribution. # # alpha is the scale parameter and beta is the shape parameter. u = 1 - @random() alpha * (pow -log u, 1 / beta) # Jain, pg. 499; bug fix by Bill Arms class Random extends BaseRandom # Use a Multiply With Carry PRNG, with an XOR-shift successor # Both from Numerical Recipes, 3rd Edition [H1, G1] _randint32: -> @x = 62904 * (@x & 0xffff) + (@x >>> 16) @y = 41874 * (@y & 0xffff) + (@y >>> 16) z = (@x << 16) + @y z ^= z >>> 13; z ^= z << 17; z ^= z >>> 5 z _seed: (j) -> # these two numbers were arbitrarily chosen @x = 3395989511 ^ j @y = 1716319410 ^ j _getstate: -> [@x, @y] _setstate: ([@x, @y]) -> class HighQualityRandom extends BaseRandom # From Numerical Recipes, 3rd Edition _randint32: -> x = @u = @u * 2891336453 + 1640531513 v = @v; v ^= v >>> 13; v ^= v << 17; v ^= v >>> 5; @v = v y = @w1 = 33378 * (@w1 & 0xffff) + (@w1 >>> 16) @w2 = 57225 * (@w2 & 0xffff) + (@w2 >>> 16) x ^= x << 9; x ^= x >>> 17; x ^= x << 6 y ^= y << 17; y ^= y >>> 15; y ^= y << 5 (x + v) ^ (y + @w2) _seed: (j) -> @w1 = 521288629 @w2 = 362436069 @v = @u = j ^ 2244614371 _getstate: -> [@u, @v, @w1, @w2] _setstate: ([@u, @v, @w1, @w2]) -> class BuiltinRandom extends BaseRandom # Use the built-in PRNG. Note that with the built-in # PRNG, which is implementation dependant, there is no # way to set the seed or save/restore state. _seed: (j) => # ignore seed # Test to see if our JavaScript engine creates random numbers # with more than 32 bits of entropy. If so, just use it directly. # Otherwise, combine two calls to `random` into each invocation. _rand = Math.random _lowbits = -> (_rand() * pow 2, 64) | 0 # `| 0` will chop out bits > 32 if _lowbits() | _lowbits() | _lowbits() # ~1e-18 chance of false negative random: _rand else random: -> _rand() * POW_NEG_32 + _rand() _randint32: -> (_rand() * POW_32) | 0 exports = exports or window or this extend exports, { NotImplementedError BaseRandom Random HighQualityRandom BuiltinRandom}
129320
### A fairly direct port of the Python `random` module to JavaScript ### {log, sqrt, cos, acos, floor, pow, LOG2E, exp} = Math POW_32 = pow 2, 32 POW_NEG_32 = pow 2, -32 lg = (x) -> # The log base 2, rounded down to the integer below (LOG2E * log x + 1e-10) >> 0 mod = (x, y) -> unless (jsmod = x % y) and (x > 0 ^ y > 0) then jsmod else jsmod + y extend = (target, sources...) -> for obj in sources target[name] = method for name, method of obj target bind = (fn, obj) -> -> fn.apply obj, arguments class NotImplementedError extends Error class BaseRandom ## Override these first four methods in a custom Random class. _randint32: -> # Override this method to generate a pseudorandom number throw new NotImplementedError _getstate: -> # Override this method to fetch the internal PRNG state. Should # return an Array. throw new NotImplementedError _setstate: (state) -> # Override this method to set the internal PRNG state from the # argument `state`, an Array. throw new NotImplementedError _seed: (args...) -> # Override this method to seed the PRNG throw new NotImplementedError ## Generally no need to override the methods below in a custom class. ## (Under some circumstances it might make sense to implement a custom ## version of the `random` method or add to the constructor.) constructor: -> # bind `normalvariate` (def. below as a `gauss` alias) to the instance @normalvariate = bind @normalvariate, @ # By default, just seed the PRNG with the date. Some PRNGs # can take longer and more complex seeds. @_next_gauss = null @seed +new Date seed: (args...) => # Seed the PRNG. @_seed args... POW_NEG_26 = pow 2, -26 POW_NEG_27 = pow 2, -27 random: => # Return a random float in the range [0, 1), with a full 53 # bits of entropy. low_bits = @_randint32() >>> 6 high_bits = @_randint32() >>> 5 (high_bits + low_bits * POW_NEG_26) * POW_NEG_27 setstate: ([@_next_gauss, state...]) => # Set the state of the PRNG. Should accept the output of `@getstate` # as its only argument. @_setstate state getstate: => # Get the internal state of the PRNG. Returns an array of state # information suitable for passing into `@setstate`. [@_next_gauss, @_getstate()...] _bits = {} _randbelow: (n) -> # Return a random int in the range [0,n). # If n > 2^32, then use floating point math if n <= 0x100000000 bits = _bits[n] or= (lg n - 1) + 1 # memoize values for `bits` loop r = @_randint32() >>> (32 - bits) r += POW_32 if r < 0 break if r < n r else floor @random() * n uniform: (a, b) => # Return a random floating point number N such that a <= N <= b for # a <= b and b <= N <= a for b < a. a + @random() * (b - a) randrange: (start, stop, step) => # Return a random integer N in range `[start...stop] by step` unless stop? @_randbelow start else unless step start + @_randbelow stop - start else start + step * @_randbelow floor (stop - start) / step randint: (a, b) => # Return a random integer N in range `[a..b]` a + @_randbelow 1 + b - a choice: (seq) => # Return a random element from the non-empty sequence `seq`. seq[@_randbelow seq.length] sample: (population, k=1) => # Return a `k` length list of unique elements chosen from the # `population` sequence. Used for random sampling without replacement. n = population.length if k > n throw new Error "can't take a sample bigger than the population" if k * 3 > n # for large samples, copy the pool = [population...] # population as a new array for i in [n...n - k] by -1 j = @_randbelow i val = pool[j] pool[j] = pool[i - 1] # move non-chosen item into vacancy val else # for small samples, treat an Array selected = [] # as a set to keep track of selection for i in [0...k] by 1 loop break if (j = @_randbelow n) not in selected selected.push j population[j] shuffle: (x) => # Shuffle the sequence x in place. for i in [x.length - 1..1] by -1 j = @_randbelow i + 1 tmp = x[i]; x[i] = x[j]; x[j] = tmp # swap x[i], x[j] x gauss: (mu=0, sigma=1) => # Gaussian distribution. `mu` is the mean, and `sigma` is the standard # deviation. Notes: # * uses the "polar method" # * we generate pairs; keep one in a cache for next time if (z = @_next_gauss)? then @_next_gauss = null else until s and s < 1 u = 2 * @random() - 1 v = 2 * @random() - 1 s = u*u + v*v w = sqrt -2 * (log s) / s z = u * w; @_next_gauss = v * w mu + z * sigma normalvariate: @::gauss # Alias for the `gauss` function triangular: (low, high, mode) => # Triangular distribution. See wikipedia unless low? then high = 1; low = 0 else unless high? then high = low; low = 0 unless mode? c = 0.5 else c = (mode - low) / (high - low) u = @random() if u <= c low + (high - low) * sqrt u * c else high - (high - low) * sqrt (1 - u) * (1 - c) lognormvariate: (mu, sigma) => # Log normal distribution. exp @normalvariate mu, sigma expovariate: (lambda) => # Exponential distribution. # # `lambda` is 1.0 divided by the desired mean. It should be nonzero. # Returned values range from 0 to positive infinity if lambda is positive, # and from negative infinity to 0 if lambda is negative. # # we use 1 - random() instead of random() to preclude the # possibility of taking the log of zero. (- log 1 - @random()) / lambda TAU = 2 * Math.PI vonmisesvariate: (mu, kappa) => # Circular data distribution. # # mu is the mean angle, expressed in radians between 0 and 2*pi, and # kappa is the concentration parameter, which must be greater than or # equal to zero. If kappa is equal to zero, this distribution reduces # to a uniform random angle over the range 0 to 2*pi. # # Based upon an algorithm published in: <NAME>., # "Statistical Analysis of Circular Data", Cambridge # University Press, 1993. rand = @random return TAU * rand() if kappa <= 1e-6 a = 1 + sqrt 1 + 4 * kappa*kappa b = (1 - sqrt 2) * a / 2 / kappa r = (1 + b*b) / 2 / b loop u1 = rand() z = cos TAU * u1 / 2 f = (1 + r * z) / (r + z) c = kappa * (r - f) u2 = rand() break if u2 < c * (2 - c) or u2 <= c * exp 1 - c u3 = rand() (mod mu, TAU) + (if u3 > 0.5 then acos f else -acos f) LOG4 = log 4 SG_MAGICCONST = 1 + log 4.5 E = {Math} gammavariate: (alpha, beta) => # Gamma distribution. Not the gamma function! # # Conditions on the parameters are alpha > 0 and beta > 0. # # The probability distribution function is: # # x ** (alpha - 1) * exp( -x / beta) # pdf(x) = ---------------------------------- # gamma(alpha) * beta ** alpha # alpha > 0, beta > 0, mean is alpha * beta, variance is alpha * beta**2 # # Warning: a few older sources define the gamma distribution in terms # of alpha > -1 rand = @random if alpha > 1 # Uses <NAME>, "The generation of Gamma # variables with non-integral shape parameters", # Applied Statistics, (1977), 26, No. 1, p71-74 ainv = sqrt 2 * alpha - 1 bbb = alpha - LOG4 ccc = alpha + ainv loop u1 = rand() continue unless 1e-7 < u1 < 1 - 1e-7 u2 = 1 - rand() v = (log u1 / (1 - u1)) / ainv x = alpha * exp v z = u1 * u1 * u2 r = bbb + ccc * v - x break if r + SG_MAGICCONST - 4.5 * z >= 0.0 or r >= log z beta * x else if alpha == 1 # expovariate(1) loop u = rand() break if u > 1e-7 -beta * log u else # alpha is between 0 and 1 (exclusive) # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle loop u1 = rand() b = (E + alpha) / E p = b * u1 u2 = rand() if p > 1 x = - log (b - p) / alpha break if u2 <= pow x, alpha - 1 else x = pow p, 1 / alpha break if u2 <= exp -x beta * x betavariate: (alpha, beta) => # Beta distribution. # # Conditions on the parameters are alpha > 0 and beta > 0. # Returned values range between 0 and 1. # This version due to Janne Sinkkonen, and matches all the std # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution"). y = @gammavariate alpha, 1 if y == 0 then 0 else y / (y + @gammavariate beta, 1) paretovariate: (alpha) => # Pareto distribution. alpha is the shape parameter. u = 1 - @random() 1 / (pow u, 1 / alpha) # Jain, pg. 495 weibullvariate: (alpha, beta) => # Weibull distribution. # # alpha is the scale parameter and beta is the shape parameter. u = 1 - @random() alpha * (pow -log u, 1 / beta) # Jain, pg. 499; bug fix by <NAME> class Random extends BaseRandom # Use a Multiply With Carry PRNG, with an XOR-shift successor # Both from Numerical Recipes, 3rd Edition [H1, G1] _randint32: -> @x = 62904 * (@x & 0xffff) + (@x >>> 16) @y = 41874 * (@y & 0xffff) + (@y >>> 16) z = (@x << 16) + @y z ^= z >>> 13; z ^= z << 17; z ^= z >>> 5 z _seed: (j) -> # these two numbers were arbitrarily chosen @x = 3395989511 ^ j @y = 1716319410 ^ j _getstate: -> [@x, @y] _setstate: ([@x, @y]) -> class HighQualityRandom extends BaseRandom # From Numerical Recipes, 3rd Edition _randint32: -> x = @u = @u * 2891336453 + 1640531513 v = @v; v ^= v >>> 13; v ^= v << 17; v ^= v >>> 5; @v = v y = @w1 = 33378 * (@w1 & 0xffff) + (@w1 >>> 16) @w2 = 57225 * (@w2 & 0xffff) + (@w2 >>> 16) x ^= x << 9; x ^= x >>> 17; x ^= x << 6 y ^= y << 17; y ^= y >>> 15; y ^= y << 5 (x + v) ^ (y + @w2) _seed: (j) -> @w1 = 521288629 @w2 = 362436069 @v = @u = j ^ 2244614371 _getstate: -> [@u, @v, @w1, @w2] _setstate: ([@u, @v, @w1, @w2]) -> class BuiltinRandom extends BaseRandom # Use the built-in PRNG. Note that with the built-in # PRNG, which is implementation dependant, there is no # way to set the seed or save/restore state. _seed: (j) => # ignore seed # Test to see if our JavaScript engine creates random numbers # with more than 32 bits of entropy. If so, just use it directly. # Otherwise, combine two calls to `random` into each invocation. _rand = Math.random _lowbits = -> (_rand() * pow 2, 64) | 0 # `| 0` will chop out bits > 32 if _lowbits() | _lowbits() | _lowbits() # ~1e-18 chance of false negative random: _rand else random: -> _rand() * POW_NEG_32 + _rand() _randint32: -> (_rand() * POW_32) | 0 exports = exports or window or this extend exports, { NotImplementedError BaseRandom Random HighQualityRandom BuiltinRandom}
true
### A fairly direct port of the Python `random` module to JavaScript ### {log, sqrt, cos, acos, floor, pow, LOG2E, exp} = Math POW_32 = pow 2, 32 POW_NEG_32 = pow 2, -32 lg = (x) -> # The log base 2, rounded down to the integer below (LOG2E * log x + 1e-10) >> 0 mod = (x, y) -> unless (jsmod = x % y) and (x > 0 ^ y > 0) then jsmod else jsmod + y extend = (target, sources...) -> for obj in sources target[name] = method for name, method of obj target bind = (fn, obj) -> -> fn.apply obj, arguments class NotImplementedError extends Error class BaseRandom ## Override these first four methods in a custom Random class. _randint32: -> # Override this method to generate a pseudorandom number throw new NotImplementedError _getstate: -> # Override this method to fetch the internal PRNG state. Should # return an Array. throw new NotImplementedError _setstate: (state) -> # Override this method to set the internal PRNG state from the # argument `state`, an Array. throw new NotImplementedError _seed: (args...) -> # Override this method to seed the PRNG throw new NotImplementedError ## Generally no need to override the methods below in a custom class. ## (Under some circumstances it might make sense to implement a custom ## version of the `random` method or add to the constructor.) constructor: -> # bind `normalvariate` (def. below as a `gauss` alias) to the instance @normalvariate = bind @normalvariate, @ # By default, just seed the PRNG with the date. Some PRNGs # can take longer and more complex seeds. @_next_gauss = null @seed +new Date seed: (args...) => # Seed the PRNG. @_seed args... POW_NEG_26 = pow 2, -26 POW_NEG_27 = pow 2, -27 random: => # Return a random float in the range [0, 1), with a full 53 # bits of entropy. low_bits = @_randint32() >>> 6 high_bits = @_randint32() >>> 5 (high_bits + low_bits * POW_NEG_26) * POW_NEG_27 setstate: ([@_next_gauss, state...]) => # Set the state of the PRNG. Should accept the output of `@getstate` # as its only argument. @_setstate state getstate: => # Get the internal state of the PRNG. Returns an array of state # information suitable for passing into `@setstate`. [@_next_gauss, @_getstate()...] _bits = {} _randbelow: (n) -> # Return a random int in the range [0,n). # If n > 2^32, then use floating point math if n <= 0x100000000 bits = _bits[n] or= (lg n - 1) + 1 # memoize values for `bits` loop r = @_randint32() >>> (32 - bits) r += POW_32 if r < 0 break if r < n r else floor @random() * n uniform: (a, b) => # Return a random floating point number N such that a <= N <= b for # a <= b and b <= N <= a for b < a. a + @random() * (b - a) randrange: (start, stop, step) => # Return a random integer N in range `[start...stop] by step` unless stop? @_randbelow start else unless step start + @_randbelow stop - start else start + step * @_randbelow floor (stop - start) / step randint: (a, b) => # Return a random integer N in range `[a..b]` a + @_randbelow 1 + b - a choice: (seq) => # Return a random element from the non-empty sequence `seq`. seq[@_randbelow seq.length] sample: (population, k=1) => # Return a `k` length list of unique elements chosen from the # `population` sequence. Used for random sampling without replacement. n = population.length if k > n throw new Error "can't take a sample bigger than the population" if k * 3 > n # for large samples, copy the pool = [population...] # population as a new array for i in [n...n - k] by -1 j = @_randbelow i val = pool[j] pool[j] = pool[i - 1] # move non-chosen item into vacancy val else # for small samples, treat an Array selected = [] # as a set to keep track of selection for i in [0...k] by 1 loop break if (j = @_randbelow n) not in selected selected.push j population[j] shuffle: (x) => # Shuffle the sequence x in place. for i in [x.length - 1..1] by -1 j = @_randbelow i + 1 tmp = x[i]; x[i] = x[j]; x[j] = tmp # swap x[i], x[j] x gauss: (mu=0, sigma=1) => # Gaussian distribution. `mu` is the mean, and `sigma` is the standard # deviation. Notes: # * uses the "polar method" # * we generate pairs; keep one in a cache for next time if (z = @_next_gauss)? then @_next_gauss = null else until s and s < 1 u = 2 * @random() - 1 v = 2 * @random() - 1 s = u*u + v*v w = sqrt -2 * (log s) / s z = u * w; @_next_gauss = v * w mu + z * sigma normalvariate: @::gauss # Alias for the `gauss` function triangular: (low, high, mode) => # Triangular distribution. See wikipedia unless low? then high = 1; low = 0 else unless high? then high = low; low = 0 unless mode? c = 0.5 else c = (mode - low) / (high - low) u = @random() if u <= c low + (high - low) * sqrt u * c else high - (high - low) * sqrt (1 - u) * (1 - c) lognormvariate: (mu, sigma) => # Log normal distribution. exp @normalvariate mu, sigma expovariate: (lambda) => # Exponential distribution. # # `lambda` is 1.0 divided by the desired mean. It should be nonzero. # Returned values range from 0 to positive infinity if lambda is positive, # and from negative infinity to 0 if lambda is negative. # # we use 1 - random() instead of random() to preclude the # possibility of taking the log of zero. (- log 1 - @random()) / lambda TAU = 2 * Math.PI vonmisesvariate: (mu, kappa) => # Circular data distribution. # # mu is the mean angle, expressed in radians between 0 and 2*pi, and # kappa is the concentration parameter, which must be greater than or # equal to zero. If kappa is equal to zero, this distribution reduces # to a uniform random angle over the range 0 to 2*pi. # # Based upon an algorithm published in: PI:NAME:<NAME>END_PI., # "Statistical Analysis of Circular Data", Cambridge # University Press, 1993. rand = @random return TAU * rand() if kappa <= 1e-6 a = 1 + sqrt 1 + 4 * kappa*kappa b = (1 - sqrt 2) * a / 2 / kappa r = (1 + b*b) / 2 / b loop u1 = rand() z = cos TAU * u1 / 2 f = (1 + r * z) / (r + z) c = kappa * (r - f) u2 = rand() break if u2 < c * (2 - c) or u2 <= c * exp 1 - c u3 = rand() (mod mu, TAU) + (if u3 > 0.5 then acos f else -acos f) LOG4 = log 4 SG_MAGICCONST = 1 + log 4.5 E = {Math} gammavariate: (alpha, beta) => # Gamma distribution. Not the gamma function! # # Conditions on the parameters are alpha > 0 and beta > 0. # # The probability distribution function is: # # x ** (alpha - 1) * exp( -x / beta) # pdf(x) = ---------------------------------- # gamma(alpha) * beta ** alpha # alpha > 0, beta > 0, mean is alpha * beta, variance is alpha * beta**2 # # Warning: a few older sources define the gamma distribution in terms # of alpha > -1 rand = @random if alpha > 1 # Uses PI:NAME:<NAME>END_PI, "The generation of Gamma # variables with non-integral shape parameters", # Applied Statistics, (1977), 26, No. 1, p71-74 ainv = sqrt 2 * alpha - 1 bbb = alpha - LOG4 ccc = alpha + ainv loop u1 = rand() continue unless 1e-7 < u1 < 1 - 1e-7 u2 = 1 - rand() v = (log u1 / (1 - u1)) / ainv x = alpha * exp v z = u1 * u1 * u2 r = bbb + ccc * v - x break if r + SG_MAGICCONST - 4.5 * z >= 0.0 or r >= log z beta * x else if alpha == 1 # expovariate(1) loop u = rand() break if u > 1e-7 -beta * log u else # alpha is between 0 and 1 (exclusive) # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle loop u1 = rand() b = (E + alpha) / E p = b * u1 u2 = rand() if p > 1 x = - log (b - p) / alpha break if u2 <= pow x, alpha - 1 else x = pow p, 1 / alpha break if u2 <= exp -x beta * x betavariate: (alpha, beta) => # Beta distribution. # # Conditions on the parameters are alpha > 0 and beta > 0. # Returned values range between 0 and 1. # This version due to Janne Sinkkonen, and matches all the std # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution"). y = @gammavariate alpha, 1 if y == 0 then 0 else y / (y + @gammavariate beta, 1) paretovariate: (alpha) => # Pareto distribution. alpha is the shape parameter. u = 1 - @random() 1 / (pow u, 1 / alpha) # Jain, pg. 495 weibullvariate: (alpha, beta) => # Weibull distribution. # # alpha is the scale parameter and beta is the shape parameter. u = 1 - @random() alpha * (pow -log u, 1 / beta) # Jain, pg. 499; bug fix by PI:NAME:<NAME>END_PI class Random extends BaseRandom # Use a Multiply With Carry PRNG, with an XOR-shift successor # Both from Numerical Recipes, 3rd Edition [H1, G1] _randint32: -> @x = 62904 * (@x & 0xffff) + (@x >>> 16) @y = 41874 * (@y & 0xffff) + (@y >>> 16) z = (@x << 16) + @y z ^= z >>> 13; z ^= z << 17; z ^= z >>> 5 z _seed: (j) -> # these two numbers were arbitrarily chosen @x = 3395989511 ^ j @y = 1716319410 ^ j _getstate: -> [@x, @y] _setstate: ([@x, @y]) -> class HighQualityRandom extends BaseRandom # From Numerical Recipes, 3rd Edition _randint32: -> x = @u = @u * 2891336453 + 1640531513 v = @v; v ^= v >>> 13; v ^= v << 17; v ^= v >>> 5; @v = v y = @w1 = 33378 * (@w1 & 0xffff) + (@w1 >>> 16) @w2 = 57225 * (@w2 & 0xffff) + (@w2 >>> 16) x ^= x << 9; x ^= x >>> 17; x ^= x << 6 y ^= y << 17; y ^= y >>> 15; y ^= y << 5 (x + v) ^ (y + @w2) _seed: (j) -> @w1 = 521288629 @w2 = 362436069 @v = @u = j ^ 2244614371 _getstate: -> [@u, @v, @w1, @w2] _setstate: ([@u, @v, @w1, @w2]) -> class BuiltinRandom extends BaseRandom # Use the built-in PRNG. Note that with the built-in # PRNG, which is implementation dependant, there is no # way to set the seed or save/restore state. _seed: (j) => # ignore seed # Test to see if our JavaScript engine creates random numbers # with more than 32 bits of entropy. If so, just use it directly. # Otherwise, combine two calls to `random` into each invocation. _rand = Math.random _lowbits = -> (_rand() * pow 2, 64) | 0 # `| 0` will chop out bits > 32 if _lowbits() | _lowbits() | _lowbits() # ~1e-18 chance of false negative random: _rand else random: -> _rand() * POW_NEG_32 + _rand() _randint32: -> (_rand() * POW_32) | 0 exports = exports or window or this extend exports, { NotImplementedError BaseRandom Random HighQualityRandom BuiltinRandom}
[ { "context": " @xession.login user.getProperties(\"email\", \"password\")\n .then =>\n @notify.success \"Success", "end": 310, "score": 0.9832990765571594, "start": 302, "tag": "PASSWORD", "value": "password" } ]
tests/dummy/app/routes/register.coffee
simwms/ember-material-dashboard
0
`import Ember from 'ember'` Route = Ember.Route.extend beforeModel: -> if @xession.get("loggedIn") @transitionTo "dashboard" model: -> @store.createRecord "user" actions: register: (user) -> user.save() .then => @xession.login user.getProperties("email", "password") .then => @notify.success "Success! You've been registered" @transitionTo "user" `export default Route`
113015
`import Ember from 'ember'` Route = Ember.Route.extend beforeModel: -> if @xession.get("loggedIn") @transitionTo "dashboard" model: -> @store.createRecord "user" actions: register: (user) -> user.save() .then => @xession.login user.getProperties("email", "<PASSWORD>") .then => @notify.success "Success! You've been registered" @transitionTo "user" `export default Route`
true
`import Ember from 'ember'` Route = Ember.Route.extend beforeModel: -> if @xession.get("loggedIn") @transitionTo "dashboard" model: -> @store.createRecord "user" actions: register: (user) -> user.save() .then => @xession.login user.getProperties("email", "PI:PASSWORD:<PASSWORD>END_PI") .then => @notify.success "Success! You've been registered" @transitionTo "user" `export default Route`
[ { "context": "\n{User} = require '../../lib/data'\n\nexports.donnie = new User {\n display_name : \"outofelement.io/do", "end": 50, "score": 0.9735084176063538, "start": 44, "tag": "USERNAME", "value": "donnie" }, { "context": "ie = new User {\n display_name : \"outofelement.io/donnie\"\n is_me : true\n public_key : \"\"\"\n-----BEGIN PGP", "end": 104, "score": 0.9984949827194214, "start": 98, "tag": "USERNAME", "value": "donnie" }, { "context": "(Darwin)\nComment: GPGTools - https://gpgtools.org\n\nmQENBFN+YH8BCACpPJOdWTS5T8fobGFOHyGXJi5sxX8Jr35+XVI3qebEgV9k9NA4\nq0DgjWYamWKm6kB4sLsKL2HFF/2Mm9jHAkRChnO6BlaSbbdg/OstxvPXarkzCNmH\nXhxQenqJRTpg7Tv/6LVq8dvrzKoRRzaruzrIE041WXX+viTdxIE4+uL2ibuA9Kly\nERbrSkDrBHf/4ufFDI7zPEX1pTq90GgkQQajukPPbI95AgnslbAUCyL/Q+qezY1y\nNZ46QhrxG+Q44xex1hZtI7E4B23FtLybx1yzGkuE74c9Zi1OJUziS5UWkE06W38g\nYY+tlA7jhlCPrhN0cKppBYkfPHlaimndnmUFABEBAAG0H0Rvbm5pZSA8ZG9ubmll\nQG91dG9mZWxlbWVudC5pbz6JATgEEwEKACIFAlN+YH8CGwMGCwkIBwMCBhUIAgkK\nCwQWAgMBAh4BAheAAAoJEIl2syWmeuaP4h4H/3hA0nTwS0g9nVkHctDNgPBVasJr\na+lQMZ4UyBmISf1r8iqbQ/AfmcFgjlga8E+IyGKUrKIBZ8Cv0Dl/SbQNgCv0PkfU\nCfogeTi4ad2unaj+zYlhvCClvCMlpXHo1w8RqwTXkBRnzM6AH", "end": 843, "score": 0.9991503357887268, "start": 259, "tag": "KEY", "value": "mQENBFN+YH8BCACpPJOdWTS5T8fobGFOHyGXJi5sxX8Jr35+XVI3qebEgV9k9NA4\nq0DgjWYamWKm6kB4sLsKL2HFF/2Mm9jHAkRChnO6BlaSbbdg/OstxvPXarkzCNmH\nXhxQenqJRTpg7Tv/6LVq8dvrzKoRRzaruzrIE041WXX+viTdxIE4+uL2ibuA9Kly\nERbrSkDrBHf/4ufFDI7zPEX1pTq90GgkQQajukPPbI95AgnslbAUCyL/Q+qezY1y\nNZ46QhrxG+Q44xex1hZtI7E4B23FtLybx1yzGkuE74c9Zi1OJUziS5UWkE06W38g\nYY+tlA7jhlCPrhN0cKppBYkfPHlaimndnmUFABEBAAG0H0Rvbm5pZSA8ZG9ubmll\nQG91dG9mZWxlbWVudC5pbz6JATgEEwEKACIFAlN+YH8CGwMGCwkIBwMCBhUIAgkK\nCwQWAgMBAh4BAheAAAoJEIl2syWmeuaP4h4H/3hA0nTwS0g9nVkHctDNgPBVasJr\na+lQMZ4UyBmISf1r8iqbQ/AfmcFgjlga8E+IyGKUrKIBZ8Cv0Dl/SbQNgCv0PkfU" }, { "context": "8iqbQ/AfmcFgjlga8E+IyGKUrKIBZ8Cv0Dl/SbQNgCv0PkfU\nCfogeTi4ad2unaj+zYlhvCClvCMlpXHo1w8RqwTXkBRnzM6AHSEJ7ac4K/WSdnEo\nTG0zKZsDZDsqy3JwqOhtRiLu9R1Ru6qZ8xsQkA7KURx1nvfhBssaEzMKrXHVXkpV\nWs+LCi8X02L/GyXqUWmlynrOhpR9QmU7rK0Gu9VfR61SGPklMWFZtYWaaJs/xMWM\nWNU0b06iHX1YsHdeXXNlulg9gblkgwuOl58sGzGrQxhSvbKhPdRvpByfTuS5AQ0E\nU35gfwEIAMmGh9YczcghtVeuXK+Qnk48t5U3PPGdF1fAu2qQVv10xnXpbZpAKc+z\nMoCgCfE+eeM1nxbK5R3pU+zfbeEeRuEVBUtDknEdu3QJ7y7ELeqczzLn7EsupyyV\nz54r9cOiMJv1NS3c3wKK61/sj1QbPW0rSqkxN/f3K+9Arg9wZinQi4DgjL7VSZuV\nt9RacIJ2+77FHHXs65hSVQekN779CrQQEoJi7CUBaoVyyL5rBWEkbHyB/ki1JW0A\noMZ6AtWWgYkA/G6WEEvb+rMBEq9GEkPMmxwonOs1/gmjEvjeGk4dgDnKcpWXnByX\n2/4mMyNuQN2k0yzYzKFK91Py+q0y6Q8AEQEAAYkBHwQYAQoACQUCU35gfwIbDAAK\nCRCJdrMlpnrmj1ouB/4sWefDp29qM/AA0HaVCb/DVSuIeVbzo6nGEAFOAoPRhEwX\nXHnS7z6EutYwFV97QgYo27eoYKGDDozNLoi5qUQqq6J/ALNFQUnVcOO74SrznJDQ\nzx5ilG9AlmBJiWIu2XzgDEKXhSOZJMCNdTIY8PybAKc/D+pRDoQTY5SxypDDn15Y\nTwUqX/3/i2S9LpIGbNWepA1ZuQvmMdhPbB3GyX/+z16tZ+6irs787dvZ+/E9uABR\neeWvuBoFu+q3DLL2q9zHMac3ZsjFP8zePZi1QaazLuBapmJsdVeWLbh2m/hf79/p\nLEbxeJK54YE4IHCZJNhV7BEbXcPju7pzmTP4xXDv\n=57/x\n-----END PGP PUBLIC KEY BLOCK-----\n\"\"\"\n private_", "end": 1865, "score": 0.9995818734169006, "start": 845, "tag": "KEY", "value": "fogeTi4ad2unaj+zYlhvCClvCMlpXHo1w8RqwTXkBRnzM6AHSEJ7ac4K/WSdnEo\nTG0zKZsDZDsqy3JwqOhtRiLu9R1Ru6qZ8xsQkA7KURx1nvfhBssaEzMKrXHVXkpV\nWs+LCi8X02L/GyXqUWmlynrOhpR9QmU7rK0Gu9VfR61SGPklMWFZtYWaaJs/xMWM\nWNU0b06iHX1YsHdeXXNlulg9gblkgwuOl58sGzGrQxhSvbKhPdRvpByfTuS5AQ0E\nU35gfwEIAMmGh9YczcghtVeuXK+Qnk48t5U3PPGdF1fAu2qQVv10xnXpbZpAKc+z\nMoCgCfE+eeM1nxbK5R3pU+zfbeEeRuEVBUtDknEdu3QJ7y7ELeqczzLn7EsupyyV\nz54r9cOiMJv1NS3c3wKK61/sj1QbPW0rSqkxN/f3K+9Arg9wZinQi4DgjL7VSZuV\nt9RacIJ2+77FHHXs65hSVQekN779CrQQEoJi7CUBaoVyyL5rBWEkbHyB/ki1JW0A\noMZ6AtWWgYkA/G6WEEvb+rMBEq9GEkPMmxwonOs1/gmjEvjeGk4dgDnKcpWXnByX\n2/4mMyNuQN2k0yzYzKFK91Py+q0y6Q8AEQEAAYkBHwQYAQoACQUCU35gfwIbDAAK\nCRCJdrMlpnrmj1ouB/4sWefDp29qM/AA0HaVCb/DVSuIeVbzo6nGEAFOAoPRhEwX\nXHnS7z6EutYwFV97QgYo27eoYKGDDozNLoi5qUQqq6J/ALNFQUnVcOO74SrznJDQ\nzx5ilG9AlmBJiWIu2XzgDEKXhSOZJMCNdTIY8PybAKc/D+pRDoQTY5SxypDDn15Y\nTwUqX/3/i2S9LpIGbNWepA1ZuQvmMdhPbB3GyX/+z16tZ+6irs787dvZ+/E9uABR\neeWvuBoFu+q3DLL2q9zHMac3ZsjFP8zePZi1QaazLuBapmJsdVeWLbh2m/hf79/p\nLEbxeJK54YE4IHCZJNhV7BEbXcPju7pzmTP4xXDv\n=57/x" }, { "context": "(Darwin)\nComment: GPGTools - https://gpgtools.org\n\nlQOYBFN+YH8BCACpPJOdWTS5T8fobGFOHyGXJi5sxX8Jr35+XVI3qebEgV9k9NA4\nq0DgjWYamWKm6kB4sLsKL2HFF/2Mm9jHAkRChnO6BlaSbbdg/OstxvPXarkzCNmH\nXhxQenqJRTpg7Tv/6LVq8dvrzKoRRzaruzrIE041WXX+viTdxIE4+uL2ibuA9Kly\nERbrSkDrBHf/4ufFDI7zPEX1pTq90GgkQQajukPPbI95AgnslbAUCyL/Q+qezY1y\nNZ46QhrxG+Q44xex1hZtI7E4B23FtLybx1yzGkuE74c9Zi1OJUziS5UWkE06W38g\nYY+tlA7jhlCPrhN0cKppBYkfPHlaimndnmUFABEBAAEAB/9MWj", "end": 2369, "score": 0.9994757771492004, "start": 2045, "tag": "KEY", "value": "lQOYBFN+YH8BCACpPJOdWTS5T8fobGFOHyGXJi5sxX8Jr35+XVI3qebEgV9k9NA4\nq0DgjWYamWKm6kB4sLsKL2HFF/2Mm9jHAkRChnO6BlaSbbdg/OstxvPXarkzCNmH\nXhxQenqJRTpg7Tv/6LVq8dvrzKoRRzaruzrIE041WXX+viTdxIE4+uL2ibuA9Kly\nERbrSkDrBHf/4ufFDI7zPEX1pTq90GgkQQajukPPbI95AgnslbAUCyL/Q+qezY1y\nNZ46QhrxG+Q44xex1hZtI7E4B23FtLybx1yzGkuE74c9Zi1OJUziS5UWkE06W38g" }, { "context": "x1hZtI7E4B23FtLybx1yzGkuE74c9Zi1OJUziS5UWkE06W38g\nYY+tlA7jhlCPrhN0cKppBYkfPHlaimndnmUFABEBAAEAB/9MWjOhAE+csYVX85m8\n9KejeUrlsP69IGuZ2EGRMnqWOmYO9rKAdqb5CGJB6uTKuJHowZdJI5JhKQ8v4lod\ngwTH3MAWc+iX/J8Ix2LVTtbRX+l5QGtfutJcbr2c89pAQ5fXv6Ylv0OAsWAjFnVw\najK9dJRK1nc5PJEGarMAQZSnNEWKhhR6lwlU5i3KRAJNRqs2AFmTxMLJtmSI4ThT\ne/W4+7bakM2DptJk6qzDAyZo5HTYnKp4psO+3LUDAg078DrYh1L9jVVcH0znCFfT\nYoPGdgWa7WbukMJwdOgIeoMbM36ujzipOWzJOYmf7NiJSOMuWhvAjIzaOTkt1NX2\naYdLBADFWZmNqFpyloA6CF5AWnaIEjJ1EZ9zDnv1ufsc/px6WFMqPMtWZ0oJoSHt\neh/V8K82fz1fH9olGewC83iYdiotzSrRcSnsbg924nzM/iLgu2MvuJ2NfpNZOsdW\nT4z5PzBI06YYUjZ+/cz6wwRY38QDVVoJ66157AIGFcqJYfpeBwQA24gcFxORP36b\no6IQxc+FAIbXjysAIeQ8zfi9aIJoeLx7rWrA14FT/8KcBN+cAYb01CYzF5HVITkp\n+ihAtS/OhZ3YBfeLUUAljttheGvcCJkSBeFk4/mJg/Secv8JOnPZRFqssr8aL570\n1X1o8h+IFVBzSjfpX9b87jsvu76IoZMD/2wwf9w321XIzfiYQIqj/VsRA06SUJAI\nOVVlgNPXfvBhqZbZu/s9tB1RudtoAObZ71c/nwKcH2eFQK5t0D2dj1wpIqVQZXzL\nWYcWdOexi6SZwKBuKTCJb0sGUs9IIZY5uhDsz7N9B+Qc+ec0naE3QwGBi7Qrq2GQ\nJosXoa8KRQD+P+e0H0Rvbm5pZSA8ZG9ubmllQG91dG9mZWxlbWVudC5pbz6JATgE\nEwEKACIFAlN+YH8CGwMGCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEIl2syWm\neuaP4h4H/3hA0nTwS0g9nVkHctDNgPBVasJra+lQMZ4UyBmISf1r8iqbQ/AfmcFg\njlga8E+IyGKUrKIBZ8Cv0Dl/SbQNgCv0PkfUCfogeTi4ad2unaj+zYlhvCClvCMl\npXHo1w8RqwTXkBRnzM6AHSEJ7ac4K/WSdnEoTG0zKZsDZDsqy3JwqOhtRiLu9R1R\nu6qZ8xsQkA7KURx1nvfhBssaEzMKrXHVXkpVWs+LCi8X02L/GyXqUWmlynrOhpR9\nQmU7rK0Gu9VfR61SGPklMWFZtYWaaJs/xMWMWNU0b06iHX1YsHdeXXNlulg9gblk\ngwuOl58sGzGrQxhSvbKhPdRvpByfTuSdA5gEU35gfwEIAMmGh9YczcghtVeuXK+Q\nnk48t5U3PPGdF1fAu2qQVv10xnXpbZpAKc+zMoCgCfE+eeM1nxbK5R3pU+zfbeEe\nRuEVBUtDknEdu3QJ7y7ELeqczzLn7EsupyyVz54r9cOiMJv1NS3c3wKK61/sj1Qb\nPW0rSqkxN/f3K+9Arg9wZinQi4DgjL7VSZuVt9RacIJ2+77FHHXs65hSVQekN779\nCrQQEoJi7CUBaoVyyL5rBWEkbHyB/ki1JW0AoMZ6AtWWgYkA/G6WEEvb+rMBEq9G\nEkPMmxwonOs1/gmjEvjeGk4dgDnKcpWXnByX2/4mMyNuQN2k0yzYzKFK91Py+q0y\n6Q8AEQEAAQAH/AmrparXwavFVeH2Xc4H2a1VqsfR2W5iR+HP6kri0IK5ILeSdrHA\nO13aZGyuz5JwfQ/6JIZxsoJF1W2cCygEIwm0szGrLjZ71P2lZw+Oj8kQli8EEhgQ\nnCppVDKIO0g/If0hBWbvyYPT8WznMoCqRtvispthNNAhX9wgoDmoGyJ/WZ1y7BT0\nJzxu/cGpsLG/Va4jwZOv86LmHGboW5eL7UbzwoBkYF1qMwwsPeBSdqOEIwSnDXft\nOM87eFvneWSue2lqazWtCWarSGqo40JYO0R5zh5jrAeBuYZ9hI/WJcl9FEaFZlXG\nmnRuVW7WAnlgr/lcnpEk04m850UWzJ1FWQEEAN5dGcSdzA1vdf2jXRu8946LbONS\n5Fz80KaT3zyT2kINTyB/PbMCa9qgAQFlC8unMgFd52HCiDQC7H2PXBFhZpRplXXr\ngjFBaGOL2+USjmED3qRx/BeLbX0M5y/PILszXzB4ybo3p8MxeOT6TEgFCN7uY+EH\nNbaCgASVSyOkw6RnBADoAnwOivKuKN4Q0nazEAX8PUkNHdgPdfSkRoU/e0ZHxAvc\ni8ZfoMib0rB9iPSVRy3xbDgtd2mpx6ZnpNL75ZTI4UwJCWzNFYCwbajkoUgFvdo3\nQ5H8broX1aqii9pKcJ1/ppnLbYafALEMFZaFAAm9ltIsNwQZIaawA41c/yhtGQQA\nmJJs1kruErjhFXzIVAVELcRD4p63qBRjSJ6RFDi6JNQXMdbIk3gPshzeF0iOGYhc\n3EgqUOQg2geMqe/fy6OxUBfY63DuvAaihvaLUHTOKIEl1PLX50QVOkTCHGKWTB2D\nwj46IAMDrS0sG+cS9fuO8Iihg1E6dNWPOWGi+ZiqaXM5LYkBHwQYAQoACQUCU35g\nfwIbDAAKCRCJdrMlpnrmj1ouB/4sWefDp29qM/AA0HaVCb/DVSuIeVbzo6nGEAFO\nAoPRhEwXXHnS7z6EutYwFV97QgYo27eoYKGDDozNLoi5qUQqq6J/ALNFQUnVcOO7\n4SrznJDQzx5ilG9AlmBJiWIu2XzgDEKXhSOZJMCNdTIY8PybAKc/D+pRDoQTY5Sx\nypDDn15YTwUqX/3/i2S9LpIGbNWepA1ZuQvmMdhPbB3GyX/+z16tZ+6irs787dvZ\n+/E9uABReeWvuBoFu+q3DLL2q9zHMac3ZsjFP8zePZi1QaazLuBapmJsdVeWLbh2\nm/hf79/pLEbxeJK54YE4IHCZJNhV7BEbXcPju7pzmTP4xXDv\n=i8iC\n-----END PGP PRIVATE KEY BLOCK-----\n\"\"\"\n\n}\n\nexpor", "end": 5414, "score": 0.9994140863418579, "start": 2370, "tag": "KEY", "value": "YY+tlA7jhlCPrhN0cKppBYkfPHlaimndnmUFABEBAAEAB/9MWjOhAE+csYVX85m8\n9KejeUrlsP69IGuZ2EGRMnqWOmYO9rKAdqb5CGJB6uTKuJHowZdJI5JhKQ8v4lod\ngwTH3MAWc+iX/J8Ix2LVTtbRX+l5QGtfutJcbr2c89pAQ5fXv6Ylv0OAsWAjFnVw\najK9dJRK1nc5PJEGarMAQZSnNEWKhhR6lwlU5i3KRAJNRqs2AFmTxMLJtmSI4ThT\ne/W4+7bakM2DptJk6qzDAyZo5HTYnKp4psO+3LUDAg078DrYh1L9jVVcH0znCFfT\nYoPGdgWa7WbukMJwdOgIeoMbM36ujzipOWzJOYmf7NiJSOMuWhvAjIzaOTkt1NX2\naYdLBADFWZmNqFpyloA6CF5AWnaIEjJ1EZ9zDnv1ufsc/px6WFMqPMtWZ0oJoSHt\neh/V8K82fz1fH9olGewC83iYdiotzSrRcSnsbg924nzM/iLgu2MvuJ2NfpNZOsdW\nT4z5PzBI06YYUjZ+/cz6wwRY38QDVVoJ66157AIGFcqJYfpeBwQA24gcFxORP36b\no6IQxc+FAIbXjysAIeQ8zfi9aIJoeLx7rWrA14FT/8KcBN+cAYb01CYzF5HVITkp\n+ihAtS/OhZ3YBfeLUUAljttheGvcCJkSBeFk4/mJg/Secv8JOnPZRFqssr8aL570\n1X1o8h+IFVBzSjfpX9b87jsvu76IoZMD/2wwf9w321XIzfiYQIqj/VsRA06SUJAI\nOVVlgNPXfvBhqZbZu/s9tB1RudtoAObZ71c/nwKcH2eFQK5t0D2dj1wpIqVQZXzL\nWYcWdOexi6SZwKBuKTCJb0sGUs9IIZY5uhDsz7N9B+Qc+ec0naE3QwGBi7Qrq2GQ\nJosXoa8KRQD+P+e0H0Rvbm5pZSA8ZG9ubmllQG91dG9mZWxlbWVudC5pbz6JATgE\nEwEKACIFAlN+YH8CGwMGCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEIl2syWm\neuaP4h4H/3hA0nTwS0g9nVkHctDNgPBVasJra+lQMZ4UyBmISf1r8iqbQ/AfmcFg\njlga8E+IyGKUrKIBZ8Cv0Dl/SbQNgCv0PkfUCfogeTi4ad2unaj+zYlhvCClvCMl\npXHo1w8RqwTXkBRnzM6AHSEJ7ac4K/WSdnEoTG0zKZsDZDsqy3JwqOhtRiLu9R1R\nu6qZ8xsQkA7KURx1nvfhBssaEzMKrXHVXkpVWs+LCi8X02L/GyXqUWmlynrOhpR9\nQmU7rK0Gu9VfR61SGPklMWFZtYWaaJs/xMWMWNU0b06iHX1YsHdeXXNlulg9gblk\ngwuOl58sGzGrQxhSvbKhPdRvpByfTuSdA5gEU35gfwEIAMmGh9YczcghtVeuXK+Q\nnk48t5U3PPGdF1fAu2qQVv10xnXpbZpAKc+zMoCgCfE+eeM1nxbK5R3pU+zfbeEe\nRuEVBUtDknEdu3QJ7y7ELeqczzLn7EsupyyVz54r9cOiMJv1NS3c3wKK61/sj1Qb\nPW0rSqkxN/f3K+9Arg9wZinQi4DgjL7VSZuVt9RacIJ2+77FHHXs65hSVQekN779\nCrQQEoJi7CUBaoVyyL5rBWEkbHyB/ki1JW0AoMZ6AtWWgYkA/G6WEEvb+rMBEq9G\nEkPMmxwonOs1/gmjEvjeGk4dgDnKcpWXnByX2/4mMyNuQN2k0yzYzKFK91Py+q0y\n6Q8AEQEAAQAH/AmrparXwavFVeH2Xc4H2a1VqsfR2W5iR+HP6kri0IK5ILeSdrHA\nO13aZGyuz5JwfQ/6JIZxsoJF1W2cCygEIwm0szGrLjZ71P2lZw+Oj8kQli8EEhgQ\nnCppVDKIO0g/If0hBWbvyYPT8WznMoCqRtvispthNNAhX9wgoDmoGyJ/WZ1y7BT0\nJzxu/cGpsLG/Va4jwZOv86LmHGboW5eL7UbzwoBkYF1qMwwsPeBSdqOEIwSnDXft\nOM87eFvneWSue2lqazWtCWarSGqo40JYO0R5zh5jrAeBuYZ9hI/WJcl9FEaFZlXG\nmnRuVW7WAnlgr/lcnpEk04m850UWzJ1FWQEEAN5dGcSdzA1vdf2jXRu8946LbONS\n5Fz80KaT3zyT2kINTyB/PbMCa9qgAQFlC8unMgFd52HCiDQC7H2PXBFhZpRplXXr\ngjFBaGOL2+USjmED3qRx/BeLbX0M5y/PILszXzB4ybo3p8MxeOT6TEgFCN7uY+EH\nNbaCgASVSyOkw6RnBADoAnwOivKuKN4Q0nazEAX8PUkNHdgPdfSkRoU/e0ZHxAvc\ni8ZfoMib0rB9iPSVRy3xbDgtd2mpx6ZnpNL75ZTI4UwJCWzNFYCwbajkoUgFvdo3\nQ5H8broX1aqii9pKcJ1/ppnLbYafALEMFZaFAAm9ltIsNwQZIaawA41c/yhtGQQA\nmJJs1kruErjhFXzIVAVELcRD4p63qBRjSJ6RFDi6JNQXMdbIk3gPshzeF0iOGYhc\n3EgqUOQg2geMqe/fy6OxUBfY63DuvAaihvaLUHTOKIEl1PLX50QVOkTCHGKWTB2D\nwj46IAMDrS0sG+cS9fuO8Iihg1E6dNWPOWGi+ZiqaXM5LYkBHwQYAQoACQUCU35g\nfwIbDAAKCRCJdrMlpnrmj1ouB/4sWefDp29qM/AA0HaVCb/DVSuIeVbzo6nGEAFO\nAoPRhEwXXHnS7z6EutYwFV97QgYo27eoYKGDDozNLoi5qUQqq6J/ALNFQUnVcOO7\n4SrznJDQzx5ilG9AlmBJiWIu2XzgDEKXhSOZJMCNdTIY8PybAKc/D+pRDoQTY5Sx\nypDDn15YTwUqX/3/i2S9LpIGbNWepA1ZuQvmMdhPbB3GyX/+z16tZ+6irs787dvZ\n+/E9uABReeWvuBoFu+q3DLL2q9zHMac3ZsjFP8zePZi1QaazLuBapmJsdVeWLbh2\nm/hf79/pLEbxeJK54YE4IHCZJNhV7BEbXcPju7pzmTP4xXDv\n=i8iC" }, { "context": "s.chris = new User {\n display_name : \"keybase.io/chris\"\n public_key : \"\"\"\n-----BEGIN PGP PUBLIC KEY BLO", "end": 5520, "score": 0.9991079568862915, "start": 5515, "tag": "USERNAME", "value": "chris" }, { "context": "(Darwin)\nComment: GPGTools - https://gpgtools.org\n\nmQINBFJS084BEADG1jpg0YCEakf3VPbQTB8Sgthxh/SlisDcSsIqM33gjINJmWYz\n6l8YbLRRfr0bNB1KSiEdCBbbx1eUZ6qlhbE+xXmpnxNkD3pauVyo5KMWMaDVgpDP\nHcKH0hSiNmvR+DiOjn9dCQorx1rkB6NHkdKsVaEGPgdDuHTmQM9nRNw5/vTuyHkq\nDBCFmYHsouCCDxBsEf0IQmIGabU3d8JWWnWbW1L1f9t/raaO9BIRv8WovsvJKGzw\nPU5Qz9g0TQ3edl+tCPXEjj6RYOwGqy3d1LS73mRNTlCuOhwkvOMsfvKH5bwByeM4\n60Ib/ZtKfpgop77ZTFyIPcP/YiToe5v2ts4Quwb8wy5akYr1aB4xzN/HucnJ8QGi\nHYGNTCpyIIYHaomS4nAqnMhs4UWBE2WF/2rWKCTvWtd3m6jBUgcsP9eazJgUmgKj\nhBEz9bsfcLPSH9lnfcj00AgEW8EF9bBNMAYc/BX4hAk0RRhh/dBf9ow4kRZBqgR/\nc/f5nyOmCvQK7km5dz9jmMvMBIQZ4cqJP4NrEdRQh/xzio1wk4", "end": 6179, "score": 0.9993045926094055, "start": 5660, "tag": "KEY", "value": "mQINBFJS084BEADG1jpg0YCEakf3VPbQTB8Sgthxh/SlisDcSsIqM33gjINJmWYz\n6l8YbLRRfr0bNB1KSiEdCBbbx1eUZ6qlhbE+xXmpnxNkD3pauVyo5KMWMaDVgpDP\nHcKH0hSiNmvR+DiOjn9dCQorx1rkB6NHkdKsVaEGPgdDuHTmQM9nRNw5/vTuyHkq\nDBCFmYHsouCCDxBsEf0IQmIGabU3d8JWWnWbW1L1f9t/raaO9BIRv8WovsvJKGzw\nPU5Qz9g0TQ3edl+tCPXEjj6RYOwGqy3d1LS73mRNTlCuOhwkvOMsfvKH5bwByeM4\n60Ib/ZtKfpgop77ZTFyIPcP/YiToe5v2ts4Quwb8wy5akYr1aB4xzN/HucnJ8QGi\nHYGNTCpyIIYHaomS4nAqnMhs4UWBE2WF/2rWKCTvWtd3m6jBUgcsP9eazJgUmgKj\nhBEz9bsfcLPSH9lnfcj00AgEW8EF9bBNMAYc/BX4hAk0RRhh/dBf9ow4kRZBqgR/" }, { "context": "nfcj00AgEW8EF9bBNMAYc/BX4hAk0RRhh/dBf9ow4kRZBqgR/\nc/f5nyOmCvQK7km5dz9jmMvMBIQZ4cqJP4NrEdRQh/xzio1wk40PKziZQwBlx1mS\niNPRgkeclwCaumxds9671gyHQjEGa7moPHfe/6zvduZ28yzbhq8ydZkfpq6YUrc8\nGRtP/isXqlhSJ0dpsYA5njnIJE0GuhkNAYw7PUsLxQH0KP8Obu2ahnnu9wARAQAB\ntCJDaHJpcyBDb3luZSA8Y2hyaXNAY2hyaXNjb3luZS5jb20+iQI+BBMBAgAoBQJS\nUtPOAhsvBQkHhh+ABgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRD7wH1qlwFs\ns6M7D/9UayLmZoIkNY266Wnl6wu5lcpxJ+c7v5/+VQEEmpI++D8HMURiHU+MXVFX\nHxQEUm5KcoFDX81hl+G4KKlQlpcnX7QkkF7ZT9FFQj5SeKPkNmQxsqNhQNdfIboT\nWcNmrQHcQu/EJRjFdWHpD5wKDFwIrsTNAiVzwMIue69MgDuw3xXJiF2xjM9GvWlI\nCPiiOPTWoYCjhR3g0eYqyUTAuSfEkExDarKciBzOjGbOsUz5SjSqOu3GKQDAYhXd\nUZ3VVEz+B5kxvggqs8WXo86vzYI1OvGO2N61JysQpnE6dtMmKKh91YYKoEKPY4iz\nxSEssQLlCFJMU73eotlgqOwbsjsD/XoWCUvRKzAf4MuL3wsJcc5cdY6wk08GWk71\n/Qm74jiAxqSGH/5znmPYfTCzvxcxm4Me9zEbRSmaZscDiZluaImJHErDNXH4CxPl\norP8yaEbTuqDVuJx5DEjnWemCVbN3u1U2FCjxloeV5aOdH3jh", "end": 6959, "score": 0.998673677444458, "start": 6180, "tag": "KEY", "value": "c/f5nyOmCvQK7km5dz9jmMvMBIQZ4cqJP4NrEdRQh/xzio1wk40PKziZQwBlx1mS\niNPRgkeclwCaumxds9671gyHQjEGa7moPHfe/6zvduZ28yzbhq8ydZkfpq6YUrc8\nGRtP/isXqlhSJ0dpsYA5njnIJE0GuhkNAYw7PUsLxQH0KP8Obu2ahnnu9wARAQAB\ntCJDaHJpcyBDb3luZSA8Y2hyaXNAY2hyaXNjb3luZS5jb20+iQI+BBMBAgAoBQJS\nUtPOAhsvBQkHhh+ABgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRD7wH1qlwFs\ns6M7D/9UayLmZoIkNY266Wnl6wu5lcpxJ+c7v5/+VQEEmpI++D8HMURiHU+MXVFX\nHxQEUm5KcoFDX81hl+G4KKlQlpcnX7QkkF7ZT9FFQj5SeKPkNmQxsqNhQNdfIboT\nWcNmrQHcQu/EJRjFdWHpD5wKDFwIrsTNAiVzwMIue69MgDuw3xXJiF2xjM9GvWlI\nCPiiOPTWoYCjhR3g0eYqyUTAuSfEkExDarKciBzOjGbOsUz5SjSqOu3GKQDAYhXd\nUZ3VVEz+B5kxvggqs8WXo86vzYI1OvGO2N61JysQpnE6dtMmKKh91YYKoEKPY4iz\nxSEssQLlCFJMU73eotlgqOwbsjsD/XoWCUvRKzAf4MuL3wsJcc5cdY6wk08GWk71\n/Qm74jiAxqSGH/5znmPYfTCzvxcxm4Me9zEbRSmaZscDiZluaImJHErDNXH4CxPl" }, { "context": "mPYfTCzvxcxm4Me9zEbRSmaZscDiZluaImJHErDNXH4CxPl\norP8yaEbTuqDVuJx5DEjnWemCVbN3u1U2FCjxloeV5aOdH3jhlMrCY5mO6rw8Vh/\nDI1zro3A7/PJ+tCsj3luJwhthD4TLmZlQqeAqaZ6gNinVGNwSeQT9num0DBUPBtQ\nhqS3/KR1eaIb7XiQXNj2VLqiEKwib5EeaS0OsZZDtdq59UidEKhcuIByKone5TBT\nJbbXpPz1VCM31kMyyJZ9jl2Uh9/Eq2gYpkVjoRBzsZE8REEPgokBHAQQAQgABgUC\nUvJEugAKCRDYTCX/YUiGLk6DCACBDyCSFRF7zCl5OmF6F800mG2xtkJgmhMXKhlA\n7EumOiXI9Egx7fA7+wdn+NVE1Nu/jtfeqtVohZWT6U126zVc3tuJGZT/y/PIR+VR\nLmJiPcmucHhfw/AWBwjq9FWMVU71LP+QRsHMzEwMz/WDQmN+lsKrRFP9/2XemD8J\nd/VPlJVb6ieSoZnR+Mp94HD6ti/Avk68V1KUr1z7K2SUX+gWwkVMC6ZvTWsjWHgF\nQUPpS6MLxYRVezgJo1uU0u4DWIVaUTSwd7wdOWJ5YzRZeca2dkdp3W4R/WEtFBAI\njktM+dRRD9GVFES10xVNa3RpXaBIgbv/sqw0ObNK+zFW3KTBiQIcBBABAgAGBQJS\n8jU9AAoJECiO20czYWA1ib0P/ja2WJG7260C6L4jvcT/zLFJd8ajNi4ZygrnaBuM\nq1AhwSqZ8ySGo+XezcIcRIMKMOw6bVyGm0cMP5LDdQUdRhje9ZZwnBGlWNGWhHuV\n1HWKr/hOr1kBJr+bvXh254Z54LZsko4IursU6UadanwpxmBDs10eOTmyJwBRRhAl\nd6EZHSCH1ptTEqtAPVZOBu4yXsO1dF+hdHs+8vCmvkbuLWdWQ+Niwr1wr0H8vSQw\nteCiuin7QtJDDS57wH8OOdlKwM9jj6Y5nkquwkhBFEeOpWtpknso+mYidDFnJQ35\n/knP5/nMnM5x+02JQaj+qyaWmXzAjlY/CEZRGFt3TDZyoqNnoWucqQXdReIo4RRF\nYfQ7NVboq3pouk1vDX5Fo8CEqtEughRdM/4og3tmDqzsZ2+4UHZIry3K1kHSohIp\n5sPPMaQiyqcnFbv9+BzJMgAqzZTljCcyXmwruFe4+pV/5j/eIZjWYfyEyy+HyIGR\nfYMpO2hD0kFRH1pdLsVwoBxFOPs2i/t6f7bWX5LDc4V9f9yBMRAa/Lbmkr3mnbRA\ngwgry2EaTCiUql8UgdJ/0/A1OxTF7SHC5Cf+xFOV41+xmT3WsVrlLczQbV6q+mMW\nd9mFv/WKCM+Lgias9RG5Q4/63rExtj27r4cgKl2a4NcDW5MNjtbycFQExU2yxOqZ\nwwPauQINBFJS084BEADQqjovf9wk26L+OOmoylr0UyU2a0IAWYn0GFw+mbpTi2Xg\nhPYlvzfynYyKKK/CyupU84JlIhWTTzXPYpzJMrsRtpbpFFqPWVAms4vsUdu80yVr\nTf4/cRUvHQkti7QQUd0ln5IUkZIo2gqFwxJHzDPMjXF+rqxF60KwLpTDNlLC02Ic\nQ0v942fJSJLovLxRb5aGFwJKxJ0XkO7+/7v7pvMX4o8aF1eWcwUm9dFQt8xsO45m\nIUY1pr0JuC0wBJeHbLX2V/AD9iZIKbaIi8GNLVYeA5LSo4hfkaIubo81zjy8PWWL\n/q89xyRNKW0yyULRpXS3rUNuj0BKxQZQpU45JKx+NQGikHxystR6tPKUvn43kaAk\nRwL1PUVdiwbbx9Wmd3pNSJLg2zHLQRSL+k3Y+aUTaYwnnk7j+wYsXnsS8BPghMgs\nk4fOiZiMjj4oZu5QoelIgpi8Hqbqdiv+co5MHEyIiq60l2TbHmYDwavNw5ER6KJX\nAHGDIJNVvCYRIkjFtmsO/GgvlKGJLBrtOR9nGVjehcojgtei1pe1Li3f3sivamHD\nPCLo9BDeoWaky5eAEXLpq2mQq4qQS2AKqaR7V1yN9C7NcWOSaSSWmVC5Purl9Zfc\n9OzIpW7dIN2xIG0RxBV51qWMzE7oyQG46cQ1Ke5C3YS+uKqtKXE0CByeTGDeKQAR\nAQABiQREBBgBAgAPBQJSUtPOAhsuBQkHhh+AAikJEPvAfWqXAWyzwV0gBBkBAgAG\nBQJSUtPOAAoJENIkQTsc+mSQDLcP+wa9/m0tc9EgKytVBb21k8cXHSJtGc2Q9I0H\nHw8XjQrCjT3toqGvZqMT2bO1N+x3pFSRYutwxFp+TO9UZnAveGF82USjzbQ4731e\nD9TGf9HTmoarPbtxD092Boh2kIiUx9qpkMW6NaotZ4q52orACs3HFcQVZ4PzTXgU\nj/bydFJBRoRWb7b+MnSYExh5c4JBPA4a9CwvrdAqgR/3ZZI2bvVUFl5WwsLMSEWb\n0VUhyjMVjG8oRj3iV4jkD4nDSyuSo3HW4cjB/VHjEmFnr9CVS4yMPwufur08DP0D\nl3XOuGV5tPE7C1S+zO0t3OHj3EaVT4Z8MCq6Ii2AxxFaTAh+ktDJPzT9UNbk8ZOF\nCUn5B98BxZLv7IjoZnLFWmZJknWSCEey+rXQMV3WKLZlMA9wVLVhvSobC6mVpsue\nCOOa+h/o4KMCL4DfjQtHLSq6GKIbK/wUPXfb3/drmFzJFz5okWI4VfnYmCrwT/nu\nrVLu8Cvh8MzzzKWgl86OCfbG+2+5k3mmubYQUEWggkbet7qLVRduNCtmSqfEWMil\nWGLRbGkSF9aEu375ISAMGveNRTBet7M0lEqyvcjkKtO3ez9tlqEKnJkHdYrvszVk\np9rLgz0EyXFiwCmDPuR3GACihke/7/+AmM3aRD8kK0uQH4zM8cY221zquUc/BZuu\nBPQHhZZ8sN8QAKsd5NgODLfwAIGiyEzc2d46MvP9jjMYF+RqZHpIByjWHxscY0Q0\nk7q1x090FLebCZ1WcYgGUCtr2gGdcDmO4+CTuBK69jhC1Y060m", "end": 9884, "score": 0.9994182586669922, "start": 6962, "tag": "KEY", "value": "P8yaEbTuqDVuJx5DEjnWemCVbN3u1U2FCjxloeV5aOdH3jhlMrCY5mO6rw8Vh/\nDI1zro3A7/PJ+tCsj3luJwhthD4TLmZlQqeAqaZ6gNinVGNwSeQT9num0DBUPBtQ\nhqS3/KR1eaIb7XiQXNj2VLqiEKwib5EeaS0OsZZDtdq59UidEKhcuIByKone5TBT\nJbbXpPz1VCM31kMyyJZ9jl2Uh9/Eq2gYpkVjoRBzsZE8REEPgokBHAQQAQgABgUC\nUvJEugAKCRDYTCX/YUiGLk6DCACBDyCSFRF7zCl5OmF6F800mG2xtkJgmhMXKhlA\n7EumOiXI9Egx7fA7+wdn+NVE1Nu/jtfeqtVohZWT6U126zVc3tuJGZT/y/PIR+VR\nLmJiPcmucHhfw/AWBwjq9FWMVU71LP+QRsHMzEwMz/WDQmN+lsKrRFP9/2XemD8J\nd/VPlJVb6ieSoZnR+Mp94HD6ti/Avk68V1KUr1z7K2SUX+gWwkVMC6ZvTWsjWHgF\nQUPpS6MLxYRVezgJo1uU0u4DWIVaUTSwd7wdOWJ5YzRZeca2dkdp3W4R/WEtFBAI\njktM+dRRD9GVFES10xVNa3RpXaBIgbv/sqw0ObNK+zFW3KTBiQIcBBABAgAGBQJS\n8jU9AAoJECiO20czYWA1ib0P/ja2WJG7260C6L4jvcT/zLFJd8ajNi4ZygrnaBuM\nq1AhwSqZ8ySGo+XezcIcRIMKMOw6bVyGm0cMP5LDdQUdRhje9ZZwnBGlWNGWhHuV\n1HWKr/hOr1kBJr+bvXh254Z54LZsko4IursU6UadanwpxmBDs10eOTmyJwBRRhAl\nd6EZHSCH1ptTEqtAPVZOBu4yXsO1dF+hdHs+8vCmvkbuLWdWQ+Niwr1wr0H8vSQw\nteCiuin7QtJDDS57wH8OOdlKwM9jj6Y5nkquwkhBFEeOpWtpknso+mYidDFnJQ35\n/knP5/nMnM5x+02JQaj+qyaWmXzAjlY/CEZRGFt3TDZyoqNnoWucqQXdReIo4RRF\nYfQ7NVboq3pouk1vDX5Fo8CEqtEughRdM/4og3tmDqzsZ2+4UHZIry3K1kHSohIp\n5sPPMaQiyqcnFbv9+BzJMgAqzZTljCcyXmwruFe4+pV/5j/eIZjWYfyEyy+HyIGR\nfYMpO2hD0kFRH1pdLsVwoBxFOPs2i/t6f7bWX5LDc4V9f9yBMRAa/Lbmkr3mnbRA\ngwgry2EaTCiUql8UgdJ/0/A1OxTF7SHC5Cf+xFOV41+xmT3WsVrlLczQbV6q+mMW\nd9mFv/WKCM+Lgias9RG5Q4/63rExtj27r4cgKl2a4NcDW5MNjtbycFQExU2yxOqZ\nwwPauQINBFJS084BEADQqjovf9wk26L+OOmoylr0UyU2a0IAWYn0GFw+mbpTi2Xg\nhPYlvzfynYyKKK/CyupU84JlIhWTTzXPYpzJMrsRtpbpFFqPWVAms4vsUdu80yVr\nTf4/cRUvHQkti7QQUd0ln5IUkZIo2gqFwxJHzDPMjXF+rqxF60KwLpTDNlLC02Ic\nQ0v942fJSJLovLxRb5aGFwJKxJ0XkO7+/7v7pvMX4o8aF1eWcwUm9dFQt8xsO45m\nIUY1pr0JuC0wBJeHbLX2V/AD9iZIKbaIi8GNLVYeA5LSo4hfkaIubo81zjy8PWWL\n/q89xyRNKW0yyULRpXS3rUNuj0BKxQZQpU45JKx+NQGikHxystR6tPKUvn43kaAk\nRwL1PUVdiwbbx9Wmd3pNSJLg2zHLQRSL+k3Y+aUTaYwnnk7j+wYsXnsS8BPghMgs\nk4fOiZiMjj4oZu5QoelIgpi8Hqbqdiv+co5MHEyIiq60l2TbHmYDwavNw5ER6KJX\nAHGDIJNVvCYRIkjFtmsO/GgvlKGJLBrtOR9nGVjehcojgtei1pe1Li3f3sivamHD\nPCLo9BDeoWaky5eAEXLpq2mQq4qQS2AKqaR7V1yN9C7NcWOSaSSWmVC5Purl9Zfc\n9OzIpW7dIN2xIG0RxBV51qWMzE7oyQG46cQ1Ke5C3YS+uKqtKXE0CByeTGDeKQAR\nAQABiQREBBgBAgAPBQJSUtPOAhsuBQkHhh+AAikJEPvAfWqXAWyzwV0gBBkBAgAG\nBQJSUtPOAAoJENIkQTsc+mSQDLcP+wa9/m0tc9EgKytVBb21k8cXHSJtGc2Q9I0H\nHw8XjQrCjT3toqGvZqMT2bO1N+x3pFSRYutwxFp+TO9UZnAveGF82USjzbQ4731e\nD9TGf9HTmoarPbtxD092Boh2kIiUx9qpkMW6NaotZ4q52orACs3HFcQVZ4PzTXgU\nj/bydFJBRoRWb7b+MnSYExh5c4JBPA4a9CwvrdAqgR/3ZZI2bvVUFl5WwsLMSEWb\n0VUhyjMVjG8oRj3iV4jkD4nDSyuSo3HW4cjB/VHjEmFnr9CVS4yMPwufur08DP0D\nl3XOuGV5tPE7C1S+zO0t3OHj3EaVT4Z8MCq6Ii2AxxFaTAh+ktDJPzT9UNbk8ZOF\nCUn5B98BxZLv7IjoZnLFWmZJknWSCEey+rXQMV3WKLZlMA9wVLVhvSobC6mVpsue\nCOOa+h/o4KMCL4DfjQtHLSq6GKIbK/wUPXfb3/drmFzJFz5okWI4VfnYmCrwT/nu\nrVLu8Cvh8MzzzKWgl86OCfbG+2+5k3mmubYQUEWggkbet7qLVRduNCtmSqfEWMil\nWGLRbGkSF9aEu375ISAMGveNRTBet7M0lEqyvcjkKtO3ez9tlqEKnJkHdYrvszVk\np9rLgz0EyXFiwCmDPuR3GACihke/7/+AmM3aRD8kK0uQH4zM8cY221zquUc/BZuu\nBPQHhZZ8sN8QAKsd5NgODLfwAIGiyEzc2d46MvP9jjMYF+RqZHpIByjWHxscY0Q0" }, { "context": "ODLfwAIGiyEzc2d46MvP9jjMYF+RqZHpIByjWHxscY0Q0\nk7q1x090FLebCZ1WcYgGUCtr2gGdcDmO4+CTuBK69jhC1Y060mqe6+0", "end": 9890, "score": 0.5302008390426636, "start": 9889, "tag": "KEY", "value": "x" }, { "context": "wAIGiyEzc2d46MvP9jjMYF+RqZHpIByjWHxscY0Q0\nk7q1x090FLebCZ1WcYgGUCtr2gGdcDmO4+CTuBK69jhC1Y060mqe6+0V5cPC3ezO\n/MYWqccWKgrsYNAhZ5yviRnJgJ+Q3J1KVifUOUE8VymCfXfWsZO5UgA0UZ8idNjp\ntPMgIQ2ItA1e9t+1v6Rfg2IwOUnpluES5nv00SZA/+aSPcKfkp8Knj69DsI2sCFC\nN3yJMXOAt3cOFPQo9OK7XGASD4XPGPY9kduJtGOmi1h5TFTcSCarsA6V0pWlmHQ1\nQqNcrdAmqHbqJDBhKNACVe3DJ7Wp5jBGPkmcglB0sLbnxch06UgCzDJ/kzpOpSKe\nIWS3CGeVtCaKRMWSlzt9qfYoQ3zajDC+iPnyKR4T7d94qgwZOUEFEEXkD8qjb/QQ\n4JzaGlmF4vQPE85ewIbEul5aKnMbuVSZD0XA8DCuLhXtEqR0cf+Sjc2UDIIhX+8s\nspAkTA/8Tpi2KKdM8YgvE00HokXz6DNA7kcfnWVaBfriSSPYkjdSYBl0DVCl5bZm\n/lkyqRydeDzcLzznYP8bIAijZO0echU03oVl2ZoAcQFv+KdmQjwohjthAL7Ye0AN\nky44+lS810RL54YxfZ1fMaLCNdVDXaepuCbyusHSBA0Cq1tNioFai1eT\n=MqTh\n-----END PGP PUBLIC KEY BLOCK-----\n\"\"\"\n}\n\nexports", "end": 10532, "score": 0.9995788335800171, "start": 9893, "tag": "KEY", "value": "FLebCZ1WcYgGUCtr2gGdcDmO4+CTuBK69jhC1Y060mqe6+0V5cPC3ezO\n/MYWqccWKgrsYNAhZ5yviRnJgJ+Q3J1KVifUOUE8VymCfXfWsZO5UgA0UZ8idNjp\ntPMgIQ2ItA1e9t+1v6Rfg2IwOUnpluES5nv00SZA/+aSPcKfkp8Knj69DsI2sCFC\nN3yJMXOAt3cOFPQo9OK7XGASD4XPGPY9kduJtGOmi1h5TFTcSCarsA6V0pWlmHQ1\nQqNcrdAmqHbqJDBhKNACVe3DJ7Wp5jBGPkmcglB0sLbnxch06UgCzDJ/kzpOpSKe\nIWS3CGeVtCaKRMWSlzt9qfYoQ3zajDC+iPnyKR4T7d94qgwZOUEFEEXkD8qjb/QQ\n4JzaGlmF4vQPE85ewIbEul5aKnMbuVSZD0XA8DCuLhXtEqR0cf+Sjc2UDIIhX+8s\nspAkTA/8Tpi2KKdM8YgvE00HokXz6DNA7kcfnWVaBfriSSPYkjdSYBl0DVCl5bZm\n/lkyqRydeDzcLzznYP8bIAijZO0echU03oVl2ZoAcQFv+KdmQjwohjthAL7Ye0AN\nky44+lS810RL54YxfZ1fMaLCNdVDXaepuCbyusHSBA0Cq1tNioFai1eT\n=MqTh" }, { "context": "(Darwin)\nComment: GPGTools - https://gpgtools.org\n\nmQINBFLyu3wBEAC1zq7+3kmHy1hF9aCr47PCPBkkbADzNAEp5KB0/9p4DOmTcDnW\n5AQW/rh9wH8ilDhZKPPH/xOqlKa0XSn7JscT/KpigweYu9WvpnB2nnPpX2j7tBD/\nx8/jtoroJxrni+s5grZo0Md3q5MsePOwFdJCrr8ezQHaBAVVg8LNVMcY37H3+UbN\n/NzC8iUYl5+VNA3eap/bHRi6gWK2RFADL/ECSxcxcvoTBCwo/f2UXs8VGy229lHG\nYc4K7VWcIUOdSdUVJ2MA/5HizgEUte9GLBfDpRKm599OMwiQTbo4IRleUPYT6/0a\nklsh9mtPzneNWXa1qEJ5ei+Wk7ZiXt0ujAL9Ynk5DGo6qCBWU7hMv7KOeEjhHr01\nJVof+i3g286KUQYk0N6do4E9hE5jRwJQp+50sj9E5yLj0+pEWQ0x/+2C3uuf9otr\nvRWYk6XC799ZvI3C+0tPEDsTakgTQJm6ceUtUXGtK/TPAen7hwAM4x9VXjQc7dCZ\nBZijo8GR1iMaktQpysva0N9ewN86+FiddXtyad6K4WelZQQRrj5tizehjLTm18G1\nGv/R4BCMIFgbE8naBBB+1fcLDc7SiK5wUWv00YDRilX8zjh/3/0dBZwY7Alz9jtw\nXRA1Tbjlr5FSc5x5woCrSX5cyCwWfMrODN+uoTSn4Awt8T01pioSgHVp1wARAQAB\ntChrZXliYXNlLmlvL21heCAodjAuMC4xKSA8bWF4QGtleWJhc2UuaW8+iQI2BBAB\nCgAgAhsvBQkSzAMAAwsJBwMVCggCHgECF4AFAlMjPAICGQEACgkQYFKyrTGmYxwQ\nNhAAjetKZUC2wPQPAMRGz2ROE1CX2Z2Smndyp7fSijhG2GsD4OP5w8Mj5lUoOyOX\nB8Bo3rlMwL+rH2eHgyP6D0an5qj8GbGRuiqSngIpfxvtkfiiZYMYy2+6H7pK58ly\ny9qgTjx6sHuryWOkvxE7PpavUlFdJXqV9bbnRDoOSNWjCI16nd4V0VErdlLsJCcn\n9KMOXz9T1nLjpX/Lg0xiuGNu4IXH9AaJtWTqs7E8kJIbnxux8SB4pQzBcgYybKgg\nVWebqJQNMgUNnzKlgH3RV0PzulCt39eKfT2k1eangCzotk50bhViJWcHpuWSArKE\nEFUdTiv9s3w1QZCtXWF6enIyxHo4z3bkmN+ddsraXCkboFeT/vwNHzkNxWv1ELmN\nx5UzsmNURo3Iegs1tal7kRuFLHL+Z0Kh7ag7z+MTIXFCwZhn1pSWQwKVgEsgVvAR\nAFArXOr3PRkkDfx9cd6qq2I7kwJl4bMzYusOSMqRZu86l9vktAcb11HZkPaFvpZS\n7vvhuuYLW95CMA01bDCxhriERjpZqw19e2DktFPnQ5DpKzmLjB1eAmJQ1h9atsCw\nUV37IA4hFz8xSySqdRRZ0D9QPZ6AmHsLS8qXzbARlPQx5k+jSPTtFBaSm8uoTN44\nP0L1UfztgFPEJqKnk1deG3daFXhtUjax4vq/KhC32tOQgMe0IE1heHdlbGwgS3Jv\naG4gPHRoZW1heEBnbWFpbC5jb20+iQI9BBMBCgAnBQJTIzvgAhsvBQkSzAMABQsJ\nCAcDBRUKCQgLBRYCAwEAAh4BAheAAAoJEGBSsq0xpmMcaCoP+wTS5G4zUI8BotXi\n16CR9ELGkMJbnVmWVLBTFqdnv63BzFQ0HruBE1qr/b5xPQsEFvAgjQ9F9TbajaLH\n7qpTxjlPgdAl0Sb3lwycMZ9pe/04xRcCJwY3RdMPIv2ByW/3k0GJ5/c3rebLk/8d\n0UqFYwZ3ZVnuGGP5vltuk8aPoXnLs4LJdCDESTFj99TEq1+0VzDfkQJf5WpCbzJZ\n02g/v/JgaMKlia44EdVihbVh45Bj9Rwd4MPV0gE4PdQXKvijIva8NL30KGqJjswu\nrQDpMmTO92fkv7G7DgxhP/BeDytmEBAPMz4SubHzKQj2gjRdlWqDIGe8yg4zHY9X\nEfyj+9oj9d+6ezmSRplV/8HVNOsR5DxUHQMc2vRDxXqMD0AK8/k7VtA40JVpNOYH\nHih6rmM3EskLZNAwUoudGOTud8BM2JCMtMgRj3Yrc7BfoWcZ6Ck8eNZkj4AW4+FZ\nETu77LoU3s1wVbCcAb/ip+hQcdb1colUO/vYIivTuz72NbxxwPxWFgbFhXxmtuR2\nChuO250hF1JrjpqpqiOCN2wVIuxU5hOIJhCHKTTHhJRVMrA1zHJndRxkp0PKQjnC\nbKUKELF4NebuejOMJXIGw7EYNZGxukeDCwFmF49nFXkeRxalpilsEGBGEng2Cuzj\nQz6yn/VoBxH0/o78PXCNxh+b+uP6tBxNYXh3ZWxsIEtyb2huIDxtYXhAbWF4ay5v\ncmc+iQI9BBMBCgAnBQJTIzv6AhsvBQkSzAMABQsJCAcDBRUKCQgLBRYCAwEAAh4B\nAheAAAoJEGBSsq0xpmMcPk0P/i0Dax4AuTswj0MxvYBjTAncNjHdNEnJmYy1PNPK\nWjtQRS9LyRQ9MpZadQpEsWeb5FjQcxoSgJ1DGa6NTrAXmhKxOlWBLLJ1IuqFS8kl\npM5ybFSGEBdgwPgWIACpxXQuVGkzR+8lCncnQ9+tOY2mfcXLkiGaBYEl6FCaZZso\nf6JWStCOEp5GCyMg1k1P78V+52E878UPcYohGJycZPwGfAg1F2ogfqj5C8QR4FVF\n6EMUOmLu9+qEcaVYIMBYhbvURjZn8nfHSzru4FmOmGoRIhr4s/2VmISeNjxmwl6F\nWC+415x/4pXzOgZ+TPeDXiWHQULtKrklRUHlo6x466aK0oLZIsZfGcDdj/56wlOH\nqi4QBhVHNVimcAIYScRihly5U/jhzA+xlkf2GdwAOEq1EIzK9Oo14Yrzmbv4tCzB\n3G/w+e6SQXzrdWEQMZjuovpk6vAWxcnbQld+RclBXYSRw4z4rSnzgng7UpCvk6Kp\nxf2/mBxKB1ukKpEAlUIbu3K9By4SJYFq/2OnMSAMQYkVorFVz/R593WI9t//Htnt\nLN0LShkhLOcQpP0mXNYRJs0Jti7LnPUuAS3xjPm6Nwz062BBO7eXjKq/KnkExV+H\noyXp1Kii6bsE4AX9WjuXF86/KrO5it7LjiXnvxH3MYqelrcAEZt0uN/MvYxZc+4b\nc3rztB1NYXh3ZWxsIEtyb2huIDxrcm9obkBtaXQuZWR1PokCPQQTAQoAJwUCUzBx\nVwIbLwUJEswDAAULCQgHAwUVCgkICwUWAgMBAAIeAQIXgAAKCRBgUrKtMaZjHImA\nEACVkhpJbAC0r26HndJQ/m9CiKLxAJhqZPbonGTIzxQU8ZvBnyvYwI2MMD4foTyM\neJvDvIdFEArV2eV7t+nvewezrsNFMTisoGS9omtQFVp8Y00h5/vm3f+RsG0Tkx3L\nyn6iPFDxQUm73va62dev6E8eyr+4nAHSulLj4HZJgTQzsHdyZLzPvoGLV0RSKj4e\n9zHU8e2DTqZWaYlZCm/Rv6w7m+CWFzp6XNC1ujEblCRaZ7X4D7G7ssxm7MCuTZXE\nf6OEpSn206lP73LtYXlj/Xi78NRsacrIn8fnxc6Elk7LjeUuqFAAf9yN0N6TdV6w\n18ra0mAddk6qtVmfG7Pn7nFMJh0G5mu8iECNI0tv18RCigyZd93YCmwIYQViJ1A+\nHrCZ7Y72b3Yq3ERs10F704JLH0VqTEMfQAhsaaGaL81orvLJR7K7/icvoFedLrM9\nqiakOQLyL4Ngr5VqVy6bV8/CYUV5MvBtJpdmLi/wlK6Nw7cEO4OFAYIvP47zgKEf\nmRdpAlOj5bZtGGy6H+eJJxcH60YXQ+QApOAAXnUW+elsmwq/XeFv9cop8DNJLn5h\nPC9emD/tF0VAveIz/J1NIt8c3uOr4hHL5g3fZopNXI1lo3OkJlQO8+cS4hSMDGpF\nWn4j8ACdLx5nNzLiPOBH4DrEDPujog8OtnSk5DxBcl8ytrQmTWF4d2VsbCBLcm9o\nbiA8a3JvaG5AcG9zdC5oYXJ2YXJkLmVkdT6JAj0EEwEKACcFAlMwcXQCGy8FCRLM\nAwAFCwkIBwMFFQoJCAsFFgIDAQACHgECF4AACgkQYFKyrTGmYxxG6g/9HvzgQFXJ\nRdcjMdRKKDewgBRjqbPhxEUmBOHGLMKbDCfIXWXWV7DmkGc9aeVprgwszYbaH+fo\n0HcT+g+MhK1dPGtWq+G3E6L/LhMBhHBa5AqW3FWaN0fWiZjCqHnD5DtGkXLBxcju\nSMZ08rSnPEAoqv+20vepp2yECiuNGo+3SYIGJWRmmNxS56wTDImXnIA8+hNrTAeL\nUWMcwqXpgo8lPRHHkDqBsJUo/1sfFBT8qbsVfisAXAeoFN1U0sZK2jRB8b/O7fEy\nvar/W9mT7pz5DEVfTXpbVONPAb1TMsRb4LvGJvMRc3Yy1KMAz2vRwpEph3AOu2Mr\nN+T1hGJddeJ4Goc4K7lGeWYwxlmOqVD2BVL4j29IinBt2GXaitA4YStx4H7WJEyd\nrF992iGCoEhtQCgXnXJE30g9dkn+CPIlZ2jth1gkwUJrkdpRZ8zlMZE6yx4nTmIh\nMfzZ+YAszqumcnEZH0Iz5BFbXGJJ+OfG1r4zWI8zzU6pZXmK9pSRR+OhB16WQUX/\na1hxTmbe3MPrpFksdXzT3URm6vZ3DFhG/2gnoQCGj83bW1szv7jrCIZnFHz0VPQy\nDkMGZf/O58xoZO1ETHQERspau0H74542V7wWA7y9W7DAQHrylqGCHf8Sw2vc5tUd\nkhx5LolObkVS3ElxNnvBX9EYgu1rJjLDRMG0Ik1heHdlbGwgS3JvaG4gPGtyb2hu\nQGFsdW0ubWl0LmVkdT6JAj0EEwEKACcFAlMwcbsCGy8FCRLMAwAFCwkIBwMFFQoJ\nCAsFFgIDAQACHgECF4AACgkQYFKyrTGmYxzhaRAAitV34CP2hSEAm/EtQalqzu7o\nTuMDiuLAxhJ0UMh9TdhJpZ8b9/eA1I219GWQfAyggkorPVB+L6sN8s4gTmSmOXVb\ntmbo/TbuOSYARriPc6yx4nai5EMjuXJrD2L5956dYrd6cyvMO9eIZroaPBc7sIMF\n3YkMiAJP5wNuH1eWcMB8f+GZWGkynBiYP2AE+pOXXJkgyu2wnuJmWmpiYsoyW1ul\nfGrSt8wFoDoLQZ+wIPhckGrBfa/TZvuxE9lz+tS2MLMLbyCEdn3s8qSAwi++7GMG\nSXHiUeopzs6hto9Egwhv5934+kCkgL3PWdSCNu1mg1aNTsauomzG5QsDM4tNTZQ8\nItsfksMVOhgVdAXtQlHPewVZ6liabyaQTYQPzUU29HM3u7WkxNvImImVz+bR6Ru5\nCU2toDKs/OtxQwMat1p3a8yENn4T8030EFAUi5/hL4zvu27YEyJQc28o3a3rd30+\ntihjJ86UguBvk1AJXKnmy/fr5tFuw1Izy7zfjznyyh4mhb7uA4hZElz9rR68c6aT\neAyK/kjXVIhfteKe0El3rLJRDY7W56fv/NIxF4ozKqliarLhclP4WArIo8WVO6m1\ntglyulpRppQpvFOaDXmYZufVKNMMOtQlSyLEMBk02EhzFf7MxupsOHsuxS1zZ17k\nxrSUvn7r//I6BOvdXQO5AQ0EUvK7fAEIAMw3F9CU/IaCeOneMAiHAUlsrkMgmBk5\n0KH8h23I+zLK+jxLWKtohsmGn0jnczn0p4uiEdhqRE464T/emSFHEbAQd8r9bgcJ\nE033hKJ3FXrm1HnAeCeFwVNxiS2cWRgnUP6w17YXk2Zdq2X9uDPyKUhp2pRKlic/\nFkhEpz1makzKvm6lUUptq9/xUzYpXUDo2xqqT4fAf0Dwv0h4um5jd87irXZ1Txc0\nQMBeFyWWuKvmnL5bdCGWedLyTp3ULCXexuu7Gd7AdDUU5icDLSe/Hpyst/Ss9Us4\nvTZu6hiKsLBnrR/O/4VREnnmEAmJMmx1pZvYFSVoXDzWBirG4LhMcAsAEQEAAYkD\nRAQYAQoADwUCUvK7fAUJAeEzgAIbLgEpCRBgUrKtMaZjHMBdIAQZAQoABgUCUvK7\nfAAKCRCYCj8NAf4E34z7B/9Xj+EEWbn01l2cvPMMmnsH5vFYqHkbvk9T8CXE/QeJ\nuyMgldPj0LKGHCcAP7pUlUxLlAMNAJE8Nd+evzXaNsTqjF3akidZnqjKX/URoj1d\nlRVHet7u01sAjzNYiMa3ysWRB6FDrQsp36iz1kR+lGVpieZNn8gC+ylQz09SVHFT\nrZux6XHHJe23GrFZOmjyJniTDfQ/qNtnoAOK/T1lHXgec6lxB9rcah1ggBKhier/\n+s19dLUnwwTG16z9f5dtGD7k4vL+IYSkZkRLTNW3eKiIRJd7fthHRsVOPDhOCAzP\n2b82p7KiR7EtrMDFiHpXxKcBQVjeOscss7oUurX7lhKFp/gP/0B+mdvSPXF5axkr\nITrwmjkW760yJgs24qKmudnUqisNBQtkWYeNUW+/ws3zL2uH/1xwKQpRjRdtxDhK\naREZSzIUGxKVW1ztuwnZyUHDBDitzSSqXjRf0Y46zsTaK6VxpvH2DQrXkM7sDmqe\nHLGe0mEHrzrhm731ZTaAFEp9+hUWOdnUHGjMX4LjWVwR44qW9gaZkJEpWJpCtEhC\nguz/LvVoQcX0zbx9ke8SmREyNydwvVFrX8v8LTYOFUjpZDMmaaV/KF9E/5EL5m0Y\nKYR3pXrRykJnJVeRqomhpz1vdP8tsYqK8+kPSJCFDn5bhqlBnFLtJWaFAKAsesFC\n6/C1DUKuHhGH9eKRDEOhLjNX2Fc7D5t+Oni9AVyJ16Qku3sigo3E8IynXobEgYxg\nxdzDAKKugxnXx+jHE04zt0WWoxZJ99GVyRuZwBoJ0tVxWEaI40Tz0zqcqgFw1f19\n5yQY9MysQh2Pr/Zlec4Y3dvW4+wMJKnijwKoCFHRr9FbQogvPnyKAFX1xYMxrS9v\n1eWTQ9DN7bsS86d2BvqoOIX+Th7/7oBWvDXOJK0NGjQ8m4uL2B5a3CTdABlYdKb6\nh/fESNPk3DN7y8horMo6LbCytKzttBKcPZzjVoqrlM+TJLElpe/iG4ReyMzfHwBx\nM3ORWFncu87+HH//p4VSw0MfvjIz\n=lhzE\n-----END PGP PUBLIC KEY BLOCK-----\n\"\"\"\n}", "end": 17956, "score": 0.9994677901268005, "start": 10772, "tag": "KEY", "value": "mQINBFLyu3wBEAC1zq7+3kmHy1hF9aCr47PCPBkkbADzNAEp5KB0/9p4DOmTcDnW\n5AQW/rh9wH8ilDhZKPPH/xOqlKa0XSn7JscT/KpigweYu9WvpnB2nnPpX2j7tBD/\nx8/jtoroJxrni+s5grZo0Md3q5MsePOwFdJCrr8ezQHaBAVVg8LNVMcY37H3+UbN\n/NzC8iUYl5+VNA3eap/bHRi6gWK2RFADL/ECSxcxcvoTBCwo/f2UXs8VGy229lHG\nYc4K7VWcIUOdSdUVJ2MA/5HizgEUte9GLBfDpRKm599OMwiQTbo4IRleUPYT6/0a\nklsh9mtPzneNWXa1qEJ5ei+Wk7ZiXt0ujAL9Ynk5DGo6qCBWU7hMv7KOeEjhHr01\nJVof+i3g286KUQYk0N6do4E9hE5jRwJQp+50sj9E5yLj0+pEWQ0x/+2C3uuf9otr\nvRWYk6XC799ZvI3C+0tPEDsTakgTQJm6ceUtUXGtK/TPAen7hwAM4x9VXjQc7dCZ\nBZijo8GR1iMaktQpysva0N9ewN86+FiddXtyad6K4WelZQQRrj5tizehjLTm18G1\nGv/R4BCMIFgbE8naBBB+1fcLDc7SiK5wUWv00YDRilX8zjh/3/0dBZwY7Alz9jtw\nXRA1Tbjlr5FSc5x5woCrSX5cyCwWfMrODN+uoTSn4Awt8T01pioSgHVp1wARAQAB\ntChrZXliYXNlLmlvL21heCAodjAuMC4xKSA8bWF4QGtleWJhc2UuaW8+iQI2BBAB\nCgAgAhsvBQkSzAMAAwsJBwMVCggCHgECF4AFAlMjPAICGQEACgkQYFKyrTGmYxwQ\nNhAAjetKZUC2wPQPAMRGz2ROE1CX2Z2Smndyp7fSijhG2GsD4OP5w8Mj5lUoOyOX\nB8Bo3rlMwL+rH2eHgyP6D0an5qj8GbGRuiqSngIpfxvtkfiiZYMYy2+6H7pK58ly\ny9qgTjx6sHuryWOkvxE7PpavUlFdJXqV9bbnRDoOSNWjCI16nd4V0VErdlLsJCcn\n9KMOXz9T1nLjpX/Lg0xiuGNu4IXH9AaJtWTqs7E8kJIbnxux8SB4pQzBcgYybKgg\nVWebqJQNMgUNnzKlgH3RV0PzulCt39eKfT2k1eangCzotk50bhViJWcHpuWSArKE\nEFUdTiv9s3w1QZCtXWF6enIyxHo4z3bkmN+ddsraXCkboFeT/vwNHzkNxWv1ELmN\nx5UzsmNURo3Iegs1tal7kRuFLHL+Z0Kh7ag7z+MTIXFCwZhn1pSWQwKVgEsgVvAR\nAFArXOr3PRkkDfx9cd6qq2I7kwJl4bMzYusOSMqRZu86l9vktAcb11HZkPaFvpZS\n7vvhuuYLW95CMA01bDCxhriERjpZqw19e2DktFPnQ5DpKzmLjB1eAmJQ1h9atsCw\nUV37IA4hFz8xSySqdRRZ0D9QPZ6AmHsLS8qXzbARlPQx5k+jSPTtFBaSm8uoTN44\nP0L1UfztgFPEJqKnk1deG3daFXhtUjax4vq/KhC32tOQgMe0IE1heHdlbGwgS3Jv\naG4gPHRoZW1heEBnbWFpbC5jb20+iQI9BBMBCgAnBQJTIzvgAhsvBQkSzAMABQsJ\nCAcDBRUKCQgLBRYCAwEAAh4BAheAAAoJEGBSsq0xpmMcaCoP+wTS5G4zUI8BotXi\n16CR9ELGkMJbnVmWVLBTFqdnv63BzFQ0HruBE1qr/b5xPQsEFvAgjQ9F9TbajaLH\n7qpTxjlPgdAl0Sb3lwycMZ9pe/04xRcCJwY3RdMPIv2ByW/3k0GJ5/c3rebLk/8d\n0UqFYwZ3ZVnuGGP5vltuk8aPoXnLs4LJdCDESTFj99TEq1+0VzDfkQJf5WpCbzJZ\n02g/v/JgaMKlia44EdVihbVh45Bj9Rwd4MPV0gE4PdQXKvijIva8NL30KGqJjswu\nrQDpMmTO92fkv7G7DgxhP/BeDytmEBAPMz4SubHzKQj2gjRdlWqDIGe8yg4zHY9X\nEfyj+9oj9d+6ezmSRplV/8HVNOsR5DxUHQMc2vRDxXqMD0AK8/k7VtA40JVpNOYH\nHih6rmM3EskLZNAwUoudGOTud8BM2JCMtMgRj3Yrc7BfoWcZ6Ck8eNZkj4AW4+FZ\nETu77LoU3s1wVbCcAb/ip+hQcdb1colUO/vYIivTuz72NbxxwPxWFgbFhXxmtuR2\nChuO250hF1JrjpqpqiOCN2wVIuxU5hOIJhCHKTTHhJRVMrA1zHJndRxkp0PKQjnC\nbKUKELF4NebuejOMJXIGw7EYNZGxukeDCwFmF49nFXkeRxalpilsEGBGEng2Cuzj\nQz6yn/VoBxH0/o78PXCNxh+b+uP6tBxNYXh3ZWxsIEtyb2huIDxtYXhAbWF4ay5v\ncmc+iQI9BBMBCgAnBQJTIzv6AhsvBQkSzAMABQsJCAcDBRUKCQgLBRYCAwEAAh4B\nAheAAAoJEGBSsq0xpmMcPk0P/i0Dax4AuTswj0MxvYBjTAncNjHdNEnJmYy1PNPK\nWjtQRS9LyRQ9MpZadQpEsWeb5FjQcxoSgJ1DGa6NTrAXmhKxOlWBLLJ1IuqFS8kl\npM5ybFSGEBdgwPgWIACpxXQuVGkzR+8lCncnQ9+tOY2mfcXLkiGaBYEl6FCaZZso\nf6JWStCOEp5GCyMg1k1P78V+52E878UPcYohGJycZPwGfAg1F2ogfqj5C8QR4FVF\n6EMUOmLu9+qEcaVYIMBYhbvURjZn8nfHSzru4FmOmGoRIhr4s/2VmISeNjxmwl6F\nWC+415x/4pXzOgZ+TPeDXiWHQULtKrklRUHlo6x466aK0oLZIsZfGcDdj/56wlOH\nqi4QBhVHNVimcAIYScRihly5U/jhzA+xlkf2GdwAOEq1EIzK9Oo14Yrzmbv4tCzB\n3G/w+e6SQXzrdWEQMZjuovpk6vAWxcnbQld+RclBXYSRw4z4rSnzgng7UpCvk6Kp\nxf2/mBxKB1ukKpEAlUIbu3K9By4SJYFq/2OnMSAMQYkVorFVz/R593WI9t//Htnt\nLN0LShkhLOcQpP0mXNYRJs0Jti7LnPUuAS3xjPm6Nwz062BBO7eXjKq/KnkExV+H\noyXp1Kii6bsE4AX9WjuXF86/KrO5it7LjiXnvxH3MYqelrcAEZt0uN/MvYxZc+4b\nc3rztB1NYXh3ZWxsIEtyb2huIDxrcm9obkBtaXQuZWR1PokCPQQTAQoAJwUCUzBx\nVwIbLwUJEswDAAULCQgHAwUVCgkICwUWAgMBAAIeAQIXgAAKCRBgUrKtMaZjHImA\nEACVkhpJbAC0r26HndJQ/m9CiKLxAJhqZPbonGTIzxQU8ZvBnyvYwI2MMD4foTyM\neJvDvIdFEArV2eV7t+nvewezrsNFMTisoGS9omtQFVp8Y00h5/vm3f+RsG0Tkx3L\nyn6iPFDxQUm73va62dev6E8eyr+4nAHSulLj4HZJgTQzsHdyZLzPvoGLV0RSKj4e\n9zHU8e2DTqZWaYlZCm/Rv6w7m+CWFzp6XNC1ujEblCRaZ7X4D7G7ssxm7MCuTZXE\nf6OEpSn206lP73LtYXlj/Xi78NRsacrIn8fnxc6Elk7LjeUuqFAAf9yN0N6TdV6w\n18ra0mAddk6qtVmfG7Pn7nFMJh0G5mu8iECNI0tv18RCigyZd93YCmwIYQViJ1A+\nHrCZ7Y72b3Yq3ERs10F704JLH0VqTEMfQAhsaaGaL81orvLJR7K7/icvoFedLrM9\nqiakOQLyL4Ngr5VqVy6bV8/CYUV5MvBtJpdmLi/wlK6Nw7cEO4OFAYIvP47zgKEf\nmRdpAlOj5bZtGGy6H+eJJxcH60YXQ+QApOAAXnUW+elsmwq/XeFv9cop8DNJLn5h\nPC9emD/tF0VAveIz/J1NIt8c3uOr4hHL5g3fZopNXI1lo3OkJlQO8+cS4hSMDGpF\nWn4j8ACdLx5nNzLiPOBH4DrEDPujog8OtnSk5DxBcl8ytrQmTWF4d2VsbCBLcm9o\nbiA8a3JvaG5AcG9zdC5oYXJ2YXJkLmVkdT6JAj0EEwEKACcFAlMwcXQCGy8FCRLM\nAwAFCwkIBwMFFQoJCAsFFgIDAQACHgECF4AACgkQYFKyrTGmYxxG6g/9HvzgQFXJ\nRdcjMdRKKDewgBRjqbPhxEUmBOHGLMKbDCfIXWXWV7DmkGc9aeVprgwszYbaH+fo\n0HcT+g+MhK1dPGtWq+G3E6L/LhMBhHBa5AqW3FWaN0fWiZjCqHnD5DtGkXLBxcju\nSMZ08rSnPEAoqv+20vepp2yECiuNGo+3SYIGJWRmmNxS56wTDImXnIA8+hNrTAeL\nUWMcwqXpgo8lPRHHkDqBsJUo/1sfFBT8qbsVfisAXAeoFN1U0sZK2jRB8b/O7fEy\nvar/W9mT7pz5DEVfTXpbVONPAb1TMsRb4LvGJvMRc3Yy1KMAz2vRwpEph3AOu2Mr\nN+T1hGJddeJ4Goc4K7lGeWYwxlmOqVD2BVL4j29IinBt2GXaitA4YStx4H7WJEyd\nrF992iGCoEhtQCgXnXJE30g9dkn+CPIlZ2jth1gkwUJrkdpRZ8zlMZE6yx4nTmIh\nMfzZ+YAszqumcnEZH0Iz5BFbXGJJ+OfG1r4zWI8zzU6pZXmK9pSRR+OhB16WQUX/\na1hxTmbe3MPrpFksdXzT3URm6vZ3DFhG/2gnoQCGj83bW1szv7jrCIZnFHz0VPQy\nDkMGZf/O58xoZO1ETHQERspau0H74542V7wWA7y9W7DAQHrylqGCHf8Sw2vc5tUd\nkhx5LolObkVS3ElxNnvBX9EYgu1rJjLDRMG0Ik1heHdlbGwgS3JvaG4gPGtyb2hu\nQGFsdW0ubWl0LmVkdT6JAj0EEwEKACcFAlMwcbsCGy8FCRLMAwAFCwkIBwMFFQoJ\nCAsFFgIDAQACHgECF4AACgkQYFKyrTGmYxzhaRAAitV34CP2hSEAm/EtQalqzu7o\nTuMDiuLAxhJ0UMh9TdhJpZ8b9/eA1I219GWQfAyggkorPVB+L6sN8s4gTmSmOXVb\ntmbo/TbuOSYARriPc6yx4nai5EMjuXJrD2L5956dYrd6cyvMO9eIZroaPBc7sIMF\n3YkMiAJP5wNuH1eWcMB8f+GZWGkynBiYP2AE+pOXXJkgyu2wnuJmWmpiYsoyW1ul\nfGrSt8wFoDoLQZ+wIPhckGrBfa/TZvuxE9lz+tS2MLMLbyCEdn3s8qSAwi++7GMG\nSXHiUeopzs6hto9Egwhv5934+kCkgL3PWdSCNu1mg1aNTsauomzG5QsDM4tNTZQ8\nItsfksMVOhgVdAXtQlHPewVZ6liabyaQTYQPzUU29HM3u7WkxNvImImVz+bR6Ru5\nCU2toDKs/OtxQwMat1p3a8yENn4T8030EFAUi5/hL4zvu27YEyJQc28o3a3rd30+\ntihjJ86UguBvk1AJXKnmy/fr5tFuw1Izy7zfjznyyh4mhb7uA4hZElz9rR68c6aT\neAyK/kjXVIhfteKe0El3rLJRDY7W56fv/NIxF4ozKqliarLhclP4WArIo8WVO6m1\ntglyulpRppQpvFOaDXmYZufVKNMMOtQlSyLEMBk02EhzFf7MxupsOHsuxS1zZ17k\nxrSUvn7r//I6BOvdXQO5AQ0EUvK7fAEIAMw3F9CU/IaCeOneMAiHAUlsrkMgmBk5\n0KH8h23I+zLK+jxLWKtohsmGn0jnczn0p4uiEdhqRE464T/emSFHEbAQd8r9bgcJ\nE033hKJ3FXrm1HnAeCeFwVNxiS2cWRgnUP6w17YXk2Zdq2X9uDPyKUhp2pRKlic/\nFkhEpz1makzKvm6lUUptq9/xUzYpXUDo2xqqT4fAf0Dwv0h4um5jd87irXZ1Txc0\nQMBeFyWWuKvmnL5bdCGWedLyTp3ULCXexuu7Gd7AdDUU5icDLSe/Hpyst/Ss9Us4\nvTZu6hiKsLBnrR/O/4VREnnmEAmJMmx1pZvYFSVoXDzWBirG4LhMcAsAEQEAAYkD\nRAQYAQoADwUCUvK7fAUJAeEzgAIbLgEpCRBgUrKtMaZjHMBdIAQZAQoABgUCUvK7\nfAAKCRCYCj8NAf4E34z7B/9Xj+EEWbn01l2cvPMMmnsH5vFYqHkbvk9T8CXE/QeJ\nuyMgldPj0LKGHCcAP7pUlUxLlAMNAJE8Nd+evzXaNsTqjF3akidZnqjKX/URoj1d\nlRVHet7u01sAjzNYiMa3ysWRB6FDrQsp36iz1kR+lGVpieZNn8gC+ylQz09SVHFT\nrZux6XHHJe23GrFZOmjyJniTDfQ/qNtnoAOK/T1lHXgec6lxB9rcah1ggBKhier/\n+s19dLUnwwTG16z9f5dtGD7k4vL+IYSkZkRLTNW3eKiIRJd7fthHRsVOPDhOCAzP\n2b82p7KiR7EtrMDFiHpXxKcBQVjeOscss7oUurX7lhKFp/gP/0B+mdvSPXF5axkr\nITrwmjkW760yJgs24qKmudnUqisNBQtkWYeNUW+/ws3zL2uH/1xwKQpRjRdtxDhK\naREZSzIUGxKVW1ztuwnZyUHDBDitzSSqXjRf0Y46zsTaK6VxpvH2DQrXkM7sDmqe\nHLGe0mEHrzrhm731ZTaAFEp9+hUWOdnUHGjMX4LjWVwR44qW9gaZkJEpWJpCtEhC\nguz/LvVoQcX0zbx9ke8SmREyNydwvVFrX8v8LTYOFUjpZDMmaaV/KF9E/5EL5m0Y\nKYR3pXrRykJnJVeRqomhpz1vdP8tsYqK8+kPSJCFDn5bhqlBnFLtJWaFAKAsesFC\n6/C1DUKuHhGH9eKRDEOhLjNX2Fc7D5t+Oni9AVyJ16Qku3sigo3E8IynXobEgYxg\nxdzDAKKugxnXx+jHE04zt0WWoxZJ99GVyRuZwBoJ0tVxWEaI40Tz0zqcqgFw1f19\n5yQY9MysQh2Pr/Zlec4Y3dvW4+wMJKnijwKoCFHRr9FbQogvPnyKAFX1xYMxrS9v\n1eWTQ9DN7bsS86d2BvqoOIX+Th7/7oBWvDXOJK0NGjQ8m4uL2B5a3CTdABlYdKb6\nh/fESNPk3DN7y8horMo6LbCytKzttBKcPZzjVoqrlM+TJLElpe/iG4ReyMzfHwBx\nM3ORWFncu87+HH//p4VSw0MfvjIz\n=lhzE" } ]
test/data/users.iced
AngelKey/Angelkey.messengerclient
0
{User} = require '../../lib/data' exports.donnie = new User { display_name : "outofelement.io/donnie" is_me : true public_key : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org mQENBFN+YH8BCACpPJOdWTS5T8fobGFOHyGXJi5sxX8Jr35+XVI3qebEgV9k9NA4 q0DgjWYamWKm6kB4sLsKL2HFF/2Mm9jHAkRChnO6BlaSbbdg/OstxvPXarkzCNmH XhxQenqJRTpg7Tv/6LVq8dvrzKoRRzaruzrIE041WXX+viTdxIE4+uL2ibuA9Kly ERbrSkDrBHf/4ufFDI7zPEX1pTq90GgkQQajukPPbI95AgnslbAUCyL/Q+qezY1y NZ46QhrxG+Q44xex1hZtI7E4B23FtLybx1yzGkuE74c9Zi1OJUziS5UWkE06W38g YY+tlA7jhlCPrhN0cKppBYkfPHlaimndnmUFABEBAAG0H0Rvbm5pZSA8ZG9ubmll QG91dG9mZWxlbWVudC5pbz6JATgEEwEKACIFAlN+YH8CGwMGCwkIBwMCBhUIAgkK CwQWAgMBAh4BAheAAAoJEIl2syWmeuaP4h4H/3hA0nTwS0g9nVkHctDNgPBVasJr a+lQMZ4UyBmISf1r8iqbQ/AfmcFgjlga8E+IyGKUrKIBZ8Cv0Dl/SbQNgCv0PkfU CfogeTi4ad2unaj+zYlhvCClvCMlpXHo1w8RqwTXkBRnzM6AHSEJ7ac4K/WSdnEo TG0zKZsDZDsqy3JwqOhtRiLu9R1Ru6qZ8xsQkA7KURx1nvfhBssaEzMKrXHVXkpV Ws+LCi8X02L/GyXqUWmlynrOhpR9QmU7rK0Gu9VfR61SGPklMWFZtYWaaJs/xMWM WNU0b06iHX1YsHdeXXNlulg9gblkgwuOl58sGzGrQxhSvbKhPdRvpByfTuS5AQ0E U35gfwEIAMmGh9YczcghtVeuXK+Qnk48t5U3PPGdF1fAu2qQVv10xnXpbZpAKc+z MoCgCfE+eeM1nxbK5R3pU+zfbeEeRuEVBUtDknEdu3QJ7y7ELeqczzLn7EsupyyV z54r9cOiMJv1NS3c3wKK61/sj1QbPW0rSqkxN/f3K+9Arg9wZinQi4DgjL7VSZuV t9RacIJ2+77FHHXs65hSVQekN779CrQQEoJi7CUBaoVyyL5rBWEkbHyB/ki1JW0A oMZ6AtWWgYkA/G6WEEvb+rMBEq9GEkPMmxwonOs1/gmjEvjeGk4dgDnKcpWXnByX 2/4mMyNuQN2k0yzYzKFK91Py+q0y6Q8AEQEAAYkBHwQYAQoACQUCU35gfwIbDAAK CRCJdrMlpnrmj1ouB/4sWefDp29qM/AA0HaVCb/DVSuIeVbzo6nGEAFOAoPRhEwX XHnS7z6EutYwFV97QgYo27eoYKGDDozNLoi5qUQqq6J/ALNFQUnVcOO74SrznJDQ zx5ilG9AlmBJiWIu2XzgDEKXhSOZJMCNdTIY8PybAKc/D+pRDoQTY5SxypDDn15Y TwUqX/3/i2S9LpIGbNWepA1ZuQvmMdhPbB3GyX/+z16tZ+6irs787dvZ+/E9uABR eeWvuBoFu+q3DLL2q9zHMac3ZsjFP8zePZi1QaazLuBapmJsdVeWLbh2m/hf79/p LEbxeJK54YE4IHCZJNhV7BEbXcPju7pzmTP4xXDv =57/x -----END PGP PUBLIC KEY BLOCK----- """ private_key : """ -----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org lQOYBFN+YH8BCACpPJOdWTS5T8fobGFOHyGXJi5sxX8Jr35+XVI3qebEgV9k9NA4 q0DgjWYamWKm6kB4sLsKL2HFF/2Mm9jHAkRChnO6BlaSbbdg/OstxvPXarkzCNmH XhxQenqJRTpg7Tv/6LVq8dvrzKoRRzaruzrIE041WXX+viTdxIE4+uL2ibuA9Kly ERbrSkDrBHf/4ufFDI7zPEX1pTq90GgkQQajukPPbI95AgnslbAUCyL/Q+qezY1y NZ46QhrxG+Q44xex1hZtI7E4B23FtLybx1yzGkuE74c9Zi1OJUziS5UWkE06W38g YY+tlA7jhlCPrhN0cKppBYkfPHlaimndnmUFABEBAAEAB/9MWjOhAE+csYVX85m8 9KejeUrlsP69IGuZ2EGRMnqWOmYO9rKAdqb5CGJB6uTKuJHowZdJI5JhKQ8v4lod gwTH3MAWc+iX/J8Ix2LVTtbRX+l5QGtfutJcbr2c89pAQ5fXv6Ylv0OAsWAjFnVw ajK9dJRK1nc5PJEGarMAQZSnNEWKhhR6lwlU5i3KRAJNRqs2AFmTxMLJtmSI4ThT e/W4+7bakM2DptJk6qzDAyZo5HTYnKp4psO+3LUDAg078DrYh1L9jVVcH0znCFfT YoPGdgWa7WbukMJwdOgIeoMbM36ujzipOWzJOYmf7NiJSOMuWhvAjIzaOTkt1NX2 aYdLBADFWZmNqFpyloA6CF5AWnaIEjJ1EZ9zDnv1ufsc/px6WFMqPMtWZ0oJoSHt eh/V8K82fz1fH9olGewC83iYdiotzSrRcSnsbg924nzM/iLgu2MvuJ2NfpNZOsdW T4z5PzBI06YYUjZ+/cz6wwRY38QDVVoJ66157AIGFcqJYfpeBwQA24gcFxORP36b o6IQxc+FAIbXjysAIeQ8zfi9aIJoeLx7rWrA14FT/8KcBN+cAYb01CYzF5HVITkp +ihAtS/OhZ3YBfeLUUAljttheGvcCJkSBeFk4/mJg/Secv8JOnPZRFqssr8aL570 1X1o8h+IFVBzSjfpX9b87jsvu76IoZMD/2wwf9w321XIzfiYQIqj/VsRA06SUJAI OVVlgNPXfvBhqZbZu/s9tB1RudtoAObZ71c/nwKcH2eFQK5t0D2dj1wpIqVQZXzL WYcWdOexi6SZwKBuKTCJb0sGUs9IIZY5uhDsz7N9B+Qc+ec0naE3QwGBi7Qrq2GQ JosXoa8KRQD+P+e0H0Rvbm5pZSA8ZG9ubmllQG91dG9mZWxlbWVudC5pbz6JATgE EwEKACIFAlN+YH8CGwMGCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEIl2syWm euaP4h4H/3hA0nTwS0g9nVkHctDNgPBVasJra+lQMZ4UyBmISf1r8iqbQ/AfmcFg jlga8E+IyGKUrKIBZ8Cv0Dl/SbQNgCv0PkfUCfogeTi4ad2unaj+zYlhvCClvCMl pXHo1w8RqwTXkBRnzM6AHSEJ7ac4K/WSdnEoTG0zKZsDZDsqy3JwqOhtRiLu9R1R u6qZ8xsQkA7KURx1nvfhBssaEzMKrXHVXkpVWs+LCi8X02L/GyXqUWmlynrOhpR9 QmU7rK0Gu9VfR61SGPklMWFZtYWaaJs/xMWMWNU0b06iHX1YsHdeXXNlulg9gblk gwuOl58sGzGrQxhSvbKhPdRvpByfTuSdA5gEU35gfwEIAMmGh9YczcghtVeuXK+Q nk48t5U3PPGdF1fAu2qQVv10xnXpbZpAKc+zMoCgCfE+eeM1nxbK5R3pU+zfbeEe RuEVBUtDknEdu3QJ7y7ELeqczzLn7EsupyyVz54r9cOiMJv1NS3c3wKK61/sj1Qb PW0rSqkxN/f3K+9Arg9wZinQi4DgjL7VSZuVt9RacIJ2+77FHHXs65hSVQekN779 CrQQEoJi7CUBaoVyyL5rBWEkbHyB/ki1JW0AoMZ6AtWWgYkA/G6WEEvb+rMBEq9G EkPMmxwonOs1/gmjEvjeGk4dgDnKcpWXnByX2/4mMyNuQN2k0yzYzKFK91Py+q0y 6Q8AEQEAAQAH/AmrparXwavFVeH2Xc4H2a1VqsfR2W5iR+HP6kri0IK5ILeSdrHA O13aZGyuz5JwfQ/6JIZxsoJF1W2cCygEIwm0szGrLjZ71P2lZw+Oj8kQli8EEhgQ nCppVDKIO0g/If0hBWbvyYPT8WznMoCqRtvispthNNAhX9wgoDmoGyJ/WZ1y7BT0 Jzxu/cGpsLG/Va4jwZOv86LmHGboW5eL7UbzwoBkYF1qMwwsPeBSdqOEIwSnDXft OM87eFvneWSue2lqazWtCWarSGqo40JYO0R5zh5jrAeBuYZ9hI/WJcl9FEaFZlXG mnRuVW7WAnlgr/lcnpEk04m850UWzJ1FWQEEAN5dGcSdzA1vdf2jXRu8946LbONS 5Fz80KaT3zyT2kINTyB/PbMCa9qgAQFlC8unMgFd52HCiDQC7H2PXBFhZpRplXXr gjFBaGOL2+USjmED3qRx/BeLbX0M5y/PILszXzB4ybo3p8MxeOT6TEgFCN7uY+EH NbaCgASVSyOkw6RnBADoAnwOivKuKN4Q0nazEAX8PUkNHdgPdfSkRoU/e0ZHxAvc i8ZfoMib0rB9iPSVRy3xbDgtd2mpx6ZnpNL75ZTI4UwJCWzNFYCwbajkoUgFvdo3 Q5H8broX1aqii9pKcJ1/ppnLbYafALEMFZaFAAm9ltIsNwQZIaawA41c/yhtGQQA mJJs1kruErjhFXzIVAVELcRD4p63qBRjSJ6RFDi6JNQXMdbIk3gPshzeF0iOGYhc 3EgqUOQg2geMqe/fy6OxUBfY63DuvAaihvaLUHTOKIEl1PLX50QVOkTCHGKWTB2D wj46IAMDrS0sG+cS9fuO8Iihg1E6dNWPOWGi+ZiqaXM5LYkBHwQYAQoACQUCU35g fwIbDAAKCRCJdrMlpnrmj1ouB/4sWefDp29qM/AA0HaVCb/DVSuIeVbzo6nGEAFO AoPRhEwXXHnS7z6EutYwFV97QgYo27eoYKGDDozNLoi5qUQqq6J/ALNFQUnVcOO7 4SrznJDQzx5ilG9AlmBJiWIu2XzgDEKXhSOZJMCNdTIY8PybAKc/D+pRDoQTY5Sx ypDDn15YTwUqX/3/i2S9LpIGbNWepA1ZuQvmMdhPbB3GyX/+z16tZ+6irs787dvZ +/E9uABReeWvuBoFu+q3DLL2q9zHMac3ZsjFP8zePZi1QaazLuBapmJsdVeWLbh2 m/hf79/pLEbxeJK54YE4IHCZJNhV7BEbXcPju7pzmTP4xXDv =i8iC -----END PGP PRIVATE KEY BLOCK----- """ } exports.chris = new User { display_name : "keybase.io/chris" public_key : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org mQINBFJS084BEADG1jpg0YCEakf3VPbQTB8Sgthxh/SlisDcSsIqM33gjINJmWYz 6l8YbLRRfr0bNB1KSiEdCBbbx1eUZ6qlhbE+xXmpnxNkD3pauVyo5KMWMaDVgpDP HcKH0hSiNmvR+DiOjn9dCQorx1rkB6NHkdKsVaEGPgdDuHTmQM9nRNw5/vTuyHkq DBCFmYHsouCCDxBsEf0IQmIGabU3d8JWWnWbW1L1f9t/raaO9BIRv8WovsvJKGzw PU5Qz9g0TQ3edl+tCPXEjj6RYOwGqy3d1LS73mRNTlCuOhwkvOMsfvKH5bwByeM4 60Ib/ZtKfpgop77ZTFyIPcP/YiToe5v2ts4Quwb8wy5akYr1aB4xzN/HucnJ8QGi HYGNTCpyIIYHaomS4nAqnMhs4UWBE2WF/2rWKCTvWtd3m6jBUgcsP9eazJgUmgKj hBEz9bsfcLPSH9lnfcj00AgEW8EF9bBNMAYc/BX4hAk0RRhh/dBf9ow4kRZBqgR/ c/f5nyOmCvQK7km5dz9jmMvMBIQZ4cqJP4NrEdRQh/xzio1wk40PKziZQwBlx1mS iNPRgkeclwCaumxds9671gyHQjEGa7moPHfe/6zvduZ28yzbhq8ydZkfpq6YUrc8 GRtP/isXqlhSJ0dpsYA5njnIJE0GuhkNAYw7PUsLxQH0KP8Obu2ahnnu9wARAQAB tCJDaHJpcyBDb3luZSA8Y2hyaXNAY2hyaXNjb3luZS5jb20+iQI+BBMBAgAoBQJS UtPOAhsvBQkHhh+ABgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRD7wH1qlwFs s6M7D/9UayLmZoIkNY266Wnl6wu5lcpxJ+c7v5/+VQEEmpI++D8HMURiHU+MXVFX HxQEUm5KcoFDX81hl+G4KKlQlpcnX7QkkF7ZT9FFQj5SeKPkNmQxsqNhQNdfIboT WcNmrQHcQu/EJRjFdWHpD5wKDFwIrsTNAiVzwMIue69MgDuw3xXJiF2xjM9GvWlI CPiiOPTWoYCjhR3g0eYqyUTAuSfEkExDarKciBzOjGbOsUz5SjSqOu3GKQDAYhXd UZ3VVEz+B5kxvggqs8WXo86vzYI1OvGO2N61JysQpnE6dtMmKKh91YYKoEKPY4iz xSEssQLlCFJMU73eotlgqOwbsjsD/XoWCUvRKzAf4MuL3wsJcc5cdY6wk08GWk71 /Qm74jiAxqSGH/5znmPYfTCzvxcxm4Me9zEbRSmaZscDiZluaImJHErDNXH4CxPl orP8yaEbTuqDVuJx5DEjnWemCVbN3u1U2FCjxloeV5aOdH3jhlMrCY5mO6rw8Vh/ DI1zro3A7/PJ+tCsj3luJwhthD4TLmZlQqeAqaZ6gNinVGNwSeQT9num0DBUPBtQ hqS3/KR1eaIb7XiQXNj2VLqiEKwib5EeaS0OsZZDtdq59UidEKhcuIByKone5TBT JbbXpPz1VCM31kMyyJZ9jl2Uh9/Eq2gYpkVjoRBzsZE8REEPgokBHAQQAQgABgUC UvJEugAKCRDYTCX/YUiGLk6DCACBDyCSFRF7zCl5OmF6F800mG2xtkJgmhMXKhlA 7EumOiXI9Egx7fA7+wdn+NVE1Nu/jtfeqtVohZWT6U126zVc3tuJGZT/y/PIR+VR LmJiPcmucHhfw/AWBwjq9FWMVU71LP+QRsHMzEwMz/WDQmN+lsKrRFP9/2XemD8J d/VPlJVb6ieSoZnR+Mp94HD6ti/Avk68V1KUr1z7K2SUX+gWwkVMC6ZvTWsjWHgF QUPpS6MLxYRVezgJo1uU0u4DWIVaUTSwd7wdOWJ5YzRZeca2dkdp3W4R/WEtFBAI jktM+dRRD9GVFES10xVNa3RpXaBIgbv/sqw0ObNK+zFW3KTBiQIcBBABAgAGBQJS 8jU9AAoJECiO20czYWA1ib0P/ja2WJG7260C6L4jvcT/zLFJd8ajNi4ZygrnaBuM q1AhwSqZ8ySGo+XezcIcRIMKMOw6bVyGm0cMP5LDdQUdRhje9ZZwnBGlWNGWhHuV 1HWKr/hOr1kBJr+bvXh254Z54LZsko4IursU6UadanwpxmBDs10eOTmyJwBRRhAl d6EZHSCH1ptTEqtAPVZOBu4yXsO1dF+hdHs+8vCmvkbuLWdWQ+Niwr1wr0H8vSQw teCiuin7QtJDDS57wH8OOdlKwM9jj6Y5nkquwkhBFEeOpWtpknso+mYidDFnJQ35 /knP5/nMnM5x+02JQaj+qyaWmXzAjlY/CEZRGFt3TDZyoqNnoWucqQXdReIo4RRF YfQ7NVboq3pouk1vDX5Fo8CEqtEughRdM/4og3tmDqzsZ2+4UHZIry3K1kHSohIp 5sPPMaQiyqcnFbv9+BzJMgAqzZTljCcyXmwruFe4+pV/5j/eIZjWYfyEyy+HyIGR fYMpO2hD0kFRH1pdLsVwoBxFOPs2i/t6f7bWX5LDc4V9f9yBMRAa/Lbmkr3mnbRA gwgry2EaTCiUql8UgdJ/0/A1OxTF7SHC5Cf+xFOV41+xmT3WsVrlLczQbV6q+mMW d9mFv/WKCM+Lgias9RG5Q4/63rExtj27r4cgKl2a4NcDW5MNjtbycFQExU2yxOqZ wwPauQINBFJS084BEADQqjovf9wk26L+OOmoylr0UyU2a0IAWYn0GFw+mbpTi2Xg hPYlvzfynYyKKK/CyupU84JlIhWTTzXPYpzJMrsRtpbpFFqPWVAms4vsUdu80yVr Tf4/cRUvHQkti7QQUd0ln5IUkZIo2gqFwxJHzDPMjXF+rqxF60KwLpTDNlLC02Ic Q0v942fJSJLovLxRb5aGFwJKxJ0XkO7+/7v7pvMX4o8aF1eWcwUm9dFQt8xsO45m IUY1pr0JuC0wBJeHbLX2V/AD9iZIKbaIi8GNLVYeA5LSo4hfkaIubo81zjy8PWWL /q89xyRNKW0yyULRpXS3rUNuj0BKxQZQpU45JKx+NQGikHxystR6tPKUvn43kaAk RwL1PUVdiwbbx9Wmd3pNSJLg2zHLQRSL+k3Y+aUTaYwnnk7j+wYsXnsS8BPghMgs k4fOiZiMjj4oZu5QoelIgpi8Hqbqdiv+co5MHEyIiq60l2TbHmYDwavNw5ER6KJX AHGDIJNVvCYRIkjFtmsO/GgvlKGJLBrtOR9nGVjehcojgtei1pe1Li3f3sivamHD PCLo9BDeoWaky5eAEXLpq2mQq4qQS2AKqaR7V1yN9C7NcWOSaSSWmVC5Purl9Zfc 9OzIpW7dIN2xIG0RxBV51qWMzE7oyQG46cQ1Ke5C3YS+uKqtKXE0CByeTGDeKQAR AQABiQREBBgBAgAPBQJSUtPOAhsuBQkHhh+AAikJEPvAfWqXAWyzwV0gBBkBAgAG BQJSUtPOAAoJENIkQTsc+mSQDLcP+wa9/m0tc9EgKytVBb21k8cXHSJtGc2Q9I0H Hw8XjQrCjT3toqGvZqMT2bO1N+x3pFSRYutwxFp+TO9UZnAveGF82USjzbQ4731e D9TGf9HTmoarPbtxD092Boh2kIiUx9qpkMW6NaotZ4q52orACs3HFcQVZ4PzTXgU j/bydFJBRoRWb7b+MnSYExh5c4JBPA4a9CwvrdAqgR/3ZZI2bvVUFl5WwsLMSEWb 0VUhyjMVjG8oRj3iV4jkD4nDSyuSo3HW4cjB/VHjEmFnr9CVS4yMPwufur08DP0D l3XOuGV5tPE7C1S+zO0t3OHj3EaVT4Z8MCq6Ii2AxxFaTAh+ktDJPzT9UNbk8ZOF CUn5B98BxZLv7IjoZnLFWmZJknWSCEey+rXQMV3WKLZlMA9wVLVhvSobC6mVpsue COOa+h/o4KMCL4DfjQtHLSq6GKIbK/wUPXfb3/drmFzJFz5okWI4VfnYmCrwT/nu rVLu8Cvh8MzzzKWgl86OCfbG+2+5k3mmubYQUEWggkbet7qLVRduNCtmSqfEWMil WGLRbGkSF9aEu375ISAMGveNRTBet7M0lEqyvcjkKtO3ez9tlqEKnJkHdYrvszVk p9rLgz0EyXFiwCmDPuR3GACihke/7/+AmM3aRD8kK0uQH4zM8cY221zquUc/BZuu BPQHhZZ8sN8QAKsd5NgODLfwAIGiyEzc2d46MvP9jjMYF+RqZHpIByjWHxscY0Q0 k7q1x090FLebCZ1WcYgGUCtr2gGdcDmO4+CTuBK69jhC1Y060mqe6+0V5cPC3ezO /MYWqccWKgrsYNAhZ5yviRnJgJ+Q3J1KVifUOUE8VymCfXfWsZO5UgA0UZ8idNjp tPMgIQ2ItA1e9t+1v6Rfg2IwOUnpluES5nv00SZA/+aSPcKfkp8Knj69DsI2sCFC N3yJMXOAt3cOFPQo9OK7XGASD4XPGPY9kduJtGOmi1h5TFTcSCarsA6V0pWlmHQ1 QqNcrdAmqHbqJDBhKNACVe3DJ7Wp5jBGPkmcglB0sLbnxch06UgCzDJ/kzpOpSKe IWS3CGeVtCaKRMWSlzt9qfYoQ3zajDC+iPnyKR4T7d94qgwZOUEFEEXkD8qjb/QQ 4JzaGlmF4vQPE85ewIbEul5aKnMbuVSZD0XA8DCuLhXtEqR0cf+Sjc2UDIIhX+8s spAkTA/8Tpi2KKdM8YgvE00HokXz6DNA7kcfnWVaBfriSSPYkjdSYBl0DVCl5bZm /lkyqRydeDzcLzznYP8bIAijZO0echU03oVl2ZoAcQFv+KdmQjwohjthAL7Ye0AN ky44+lS810RL54YxfZ1fMaLCNdVDXaepuCbyusHSBA0Cq1tNioFai1eT =MqTh -----END PGP PUBLIC KEY BLOCK----- """ } exports.max = new User { display_name : "keybase.io/max" public_key : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org mQINBFLyu3wBEAC1zq7+3kmHy1hF9aCr47PCPBkkbADzNAEp5KB0/9p4DOmTcDnW 5AQW/rh9wH8ilDhZKPPH/xOqlKa0XSn7JscT/KpigweYu9WvpnB2nnPpX2j7tBD/ x8/jtoroJxrni+s5grZo0Md3q5MsePOwFdJCrr8ezQHaBAVVg8LNVMcY37H3+UbN /NzC8iUYl5+VNA3eap/bHRi6gWK2RFADL/ECSxcxcvoTBCwo/f2UXs8VGy229lHG Yc4K7VWcIUOdSdUVJ2MA/5HizgEUte9GLBfDpRKm599OMwiQTbo4IRleUPYT6/0a klsh9mtPzneNWXa1qEJ5ei+Wk7ZiXt0ujAL9Ynk5DGo6qCBWU7hMv7KOeEjhHr01 JVof+i3g286KUQYk0N6do4E9hE5jRwJQp+50sj9E5yLj0+pEWQ0x/+2C3uuf9otr vRWYk6XC799ZvI3C+0tPEDsTakgTQJm6ceUtUXGtK/TPAen7hwAM4x9VXjQc7dCZ BZijo8GR1iMaktQpysva0N9ewN86+FiddXtyad6K4WelZQQRrj5tizehjLTm18G1 Gv/R4BCMIFgbE8naBBB+1fcLDc7SiK5wUWv00YDRilX8zjh/3/0dBZwY7Alz9jtw XRA1Tbjlr5FSc5x5woCrSX5cyCwWfMrODN+uoTSn4Awt8T01pioSgHVp1wARAQAB tChrZXliYXNlLmlvL21heCAodjAuMC4xKSA8bWF4QGtleWJhc2UuaW8+iQI2BBAB CgAgAhsvBQkSzAMAAwsJBwMVCggCHgECF4AFAlMjPAICGQEACgkQYFKyrTGmYxwQ NhAAjetKZUC2wPQPAMRGz2ROE1CX2Z2Smndyp7fSijhG2GsD4OP5w8Mj5lUoOyOX B8Bo3rlMwL+rH2eHgyP6D0an5qj8GbGRuiqSngIpfxvtkfiiZYMYy2+6H7pK58ly y9qgTjx6sHuryWOkvxE7PpavUlFdJXqV9bbnRDoOSNWjCI16nd4V0VErdlLsJCcn 9KMOXz9T1nLjpX/Lg0xiuGNu4IXH9AaJtWTqs7E8kJIbnxux8SB4pQzBcgYybKgg VWebqJQNMgUNnzKlgH3RV0PzulCt39eKfT2k1eangCzotk50bhViJWcHpuWSArKE EFUdTiv9s3w1QZCtXWF6enIyxHo4z3bkmN+ddsraXCkboFeT/vwNHzkNxWv1ELmN x5UzsmNURo3Iegs1tal7kRuFLHL+Z0Kh7ag7z+MTIXFCwZhn1pSWQwKVgEsgVvAR AFArXOr3PRkkDfx9cd6qq2I7kwJl4bMzYusOSMqRZu86l9vktAcb11HZkPaFvpZS 7vvhuuYLW95CMA01bDCxhriERjpZqw19e2DktFPnQ5DpKzmLjB1eAmJQ1h9atsCw UV37IA4hFz8xSySqdRRZ0D9QPZ6AmHsLS8qXzbARlPQx5k+jSPTtFBaSm8uoTN44 P0L1UfztgFPEJqKnk1deG3daFXhtUjax4vq/KhC32tOQgMe0IE1heHdlbGwgS3Jv aG4gPHRoZW1heEBnbWFpbC5jb20+iQI9BBMBCgAnBQJTIzvgAhsvBQkSzAMABQsJ CAcDBRUKCQgLBRYCAwEAAh4BAheAAAoJEGBSsq0xpmMcaCoP+wTS5G4zUI8BotXi 16CR9ELGkMJbnVmWVLBTFqdnv63BzFQ0HruBE1qr/b5xPQsEFvAgjQ9F9TbajaLH 7qpTxjlPgdAl0Sb3lwycMZ9pe/04xRcCJwY3RdMPIv2ByW/3k0GJ5/c3rebLk/8d 0UqFYwZ3ZVnuGGP5vltuk8aPoXnLs4LJdCDESTFj99TEq1+0VzDfkQJf5WpCbzJZ 02g/v/JgaMKlia44EdVihbVh45Bj9Rwd4MPV0gE4PdQXKvijIva8NL30KGqJjswu rQDpMmTO92fkv7G7DgxhP/BeDytmEBAPMz4SubHzKQj2gjRdlWqDIGe8yg4zHY9X Efyj+9oj9d+6ezmSRplV/8HVNOsR5DxUHQMc2vRDxXqMD0AK8/k7VtA40JVpNOYH Hih6rmM3EskLZNAwUoudGOTud8BM2JCMtMgRj3Yrc7BfoWcZ6Ck8eNZkj4AW4+FZ ETu77LoU3s1wVbCcAb/ip+hQcdb1colUO/vYIivTuz72NbxxwPxWFgbFhXxmtuR2 ChuO250hF1JrjpqpqiOCN2wVIuxU5hOIJhCHKTTHhJRVMrA1zHJndRxkp0PKQjnC bKUKELF4NebuejOMJXIGw7EYNZGxukeDCwFmF49nFXkeRxalpilsEGBGEng2Cuzj Qz6yn/VoBxH0/o78PXCNxh+b+uP6tBxNYXh3ZWxsIEtyb2huIDxtYXhAbWF4ay5v cmc+iQI9BBMBCgAnBQJTIzv6AhsvBQkSzAMABQsJCAcDBRUKCQgLBRYCAwEAAh4B AheAAAoJEGBSsq0xpmMcPk0P/i0Dax4AuTswj0MxvYBjTAncNjHdNEnJmYy1PNPK WjtQRS9LyRQ9MpZadQpEsWeb5FjQcxoSgJ1DGa6NTrAXmhKxOlWBLLJ1IuqFS8kl pM5ybFSGEBdgwPgWIACpxXQuVGkzR+8lCncnQ9+tOY2mfcXLkiGaBYEl6FCaZZso f6JWStCOEp5GCyMg1k1P78V+52E878UPcYohGJycZPwGfAg1F2ogfqj5C8QR4FVF 6EMUOmLu9+qEcaVYIMBYhbvURjZn8nfHSzru4FmOmGoRIhr4s/2VmISeNjxmwl6F WC+415x/4pXzOgZ+TPeDXiWHQULtKrklRUHlo6x466aK0oLZIsZfGcDdj/56wlOH qi4QBhVHNVimcAIYScRihly5U/jhzA+xlkf2GdwAOEq1EIzK9Oo14Yrzmbv4tCzB 3G/w+e6SQXzrdWEQMZjuovpk6vAWxcnbQld+RclBXYSRw4z4rSnzgng7UpCvk6Kp xf2/mBxKB1ukKpEAlUIbu3K9By4SJYFq/2OnMSAMQYkVorFVz/R593WI9t//Htnt LN0LShkhLOcQpP0mXNYRJs0Jti7LnPUuAS3xjPm6Nwz062BBO7eXjKq/KnkExV+H oyXp1Kii6bsE4AX9WjuXF86/KrO5it7LjiXnvxH3MYqelrcAEZt0uN/MvYxZc+4b c3rztB1NYXh3ZWxsIEtyb2huIDxrcm9obkBtaXQuZWR1PokCPQQTAQoAJwUCUzBx VwIbLwUJEswDAAULCQgHAwUVCgkICwUWAgMBAAIeAQIXgAAKCRBgUrKtMaZjHImA EACVkhpJbAC0r26HndJQ/m9CiKLxAJhqZPbonGTIzxQU8ZvBnyvYwI2MMD4foTyM eJvDvIdFEArV2eV7t+nvewezrsNFMTisoGS9omtQFVp8Y00h5/vm3f+RsG0Tkx3L yn6iPFDxQUm73va62dev6E8eyr+4nAHSulLj4HZJgTQzsHdyZLzPvoGLV0RSKj4e 9zHU8e2DTqZWaYlZCm/Rv6w7m+CWFzp6XNC1ujEblCRaZ7X4D7G7ssxm7MCuTZXE f6OEpSn206lP73LtYXlj/Xi78NRsacrIn8fnxc6Elk7LjeUuqFAAf9yN0N6TdV6w 18ra0mAddk6qtVmfG7Pn7nFMJh0G5mu8iECNI0tv18RCigyZd93YCmwIYQViJ1A+ HrCZ7Y72b3Yq3ERs10F704JLH0VqTEMfQAhsaaGaL81orvLJR7K7/icvoFedLrM9 qiakOQLyL4Ngr5VqVy6bV8/CYUV5MvBtJpdmLi/wlK6Nw7cEO4OFAYIvP47zgKEf mRdpAlOj5bZtGGy6H+eJJxcH60YXQ+QApOAAXnUW+elsmwq/XeFv9cop8DNJLn5h PC9emD/tF0VAveIz/J1NIt8c3uOr4hHL5g3fZopNXI1lo3OkJlQO8+cS4hSMDGpF Wn4j8ACdLx5nNzLiPOBH4DrEDPujog8OtnSk5DxBcl8ytrQmTWF4d2VsbCBLcm9o biA8a3JvaG5AcG9zdC5oYXJ2YXJkLmVkdT6JAj0EEwEKACcFAlMwcXQCGy8FCRLM AwAFCwkIBwMFFQoJCAsFFgIDAQACHgECF4AACgkQYFKyrTGmYxxG6g/9HvzgQFXJ RdcjMdRKKDewgBRjqbPhxEUmBOHGLMKbDCfIXWXWV7DmkGc9aeVprgwszYbaH+fo 0HcT+g+MhK1dPGtWq+G3E6L/LhMBhHBa5AqW3FWaN0fWiZjCqHnD5DtGkXLBxcju SMZ08rSnPEAoqv+20vepp2yECiuNGo+3SYIGJWRmmNxS56wTDImXnIA8+hNrTAeL UWMcwqXpgo8lPRHHkDqBsJUo/1sfFBT8qbsVfisAXAeoFN1U0sZK2jRB8b/O7fEy var/W9mT7pz5DEVfTXpbVONPAb1TMsRb4LvGJvMRc3Yy1KMAz2vRwpEph3AOu2Mr N+T1hGJddeJ4Goc4K7lGeWYwxlmOqVD2BVL4j29IinBt2GXaitA4YStx4H7WJEyd rF992iGCoEhtQCgXnXJE30g9dkn+CPIlZ2jth1gkwUJrkdpRZ8zlMZE6yx4nTmIh MfzZ+YAszqumcnEZH0Iz5BFbXGJJ+OfG1r4zWI8zzU6pZXmK9pSRR+OhB16WQUX/ a1hxTmbe3MPrpFksdXzT3URm6vZ3DFhG/2gnoQCGj83bW1szv7jrCIZnFHz0VPQy DkMGZf/O58xoZO1ETHQERspau0H74542V7wWA7y9W7DAQHrylqGCHf8Sw2vc5tUd khx5LolObkVS3ElxNnvBX9EYgu1rJjLDRMG0Ik1heHdlbGwgS3JvaG4gPGtyb2hu QGFsdW0ubWl0LmVkdT6JAj0EEwEKACcFAlMwcbsCGy8FCRLMAwAFCwkIBwMFFQoJ CAsFFgIDAQACHgECF4AACgkQYFKyrTGmYxzhaRAAitV34CP2hSEAm/EtQalqzu7o TuMDiuLAxhJ0UMh9TdhJpZ8b9/eA1I219GWQfAyggkorPVB+L6sN8s4gTmSmOXVb tmbo/TbuOSYARriPc6yx4nai5EMjuXJrD2L5956dYrd6cyvMO9eIZroaPBc7sIMF 3YkMiAJP5wNuH1eWcMB8f+GZWGkynBiYP2AE+pOXXJkgyu2wnuJmWmpiYsoyW1ul fGrSt8wFoDoLQZ+wIPhckGrBfa/TZvuxE9lz+tS2MLMLbyCEdn3s8qSAwi++7GMG SXHiUeopzs6hto9Egwhv5934+kCkgL3PWdSCNu1mg1aNTsauomzG5QsDM4tNTZQ8 ItsfksMVOhgVdAXtQlHPewVZ6liabyaQTYQPzUU29HM3u7WkxNvImImVz+bR6Ru5 CU2toDKs/OtxQwMat1p3a8yENn4T8030EFAUi5/hL4zvu27YEyJQc28o3a3rd30+ tihjJ86UguBvk1AJXKnmy/fr5tFuw1Izy7zfjznyyh4mhb7uA4hZElz9rR68c6aT eAyK/kjXVIhfteKe0El3rLJRDY7W56fv/NIxF4ozKqliarLhclP4WArIo8WVO6m1 tglyulpRppQpvFOaDXmYZufVKNMMOtQlSyLEMBk02EhzFf7MxupsOHsuxS1zZ17k xrSUvn7r//I6BOvdXQO5AQ0EUvK7fAEIAMw3F9CU/IaCeOneMAiHAUlsrkMgmBk5 0KH8h23I+zLK+jxLWKtohsmGn0jnczn0p4uiEdhqRE464T/emSFHEbAQd8r9bgcJ E033hKJ3FXrm1HnAeCeFwVNxiS2cWRgnUP6w17YXk2Zdq2X9uDPyKUhp2pRKlic/ FkhEpz1makzKvm6lUUptq9/xUzYpXUDo2xqqT4fAf0Dwv0h4um5jd87irXZ1Txc0 QMBeFyWWuKvmnL5bdCGWedLyTp3ULCXexuu7Gd7AdDUU5icDLSe/Hpyst/Ss9Us4 vTZu6hiKsLBnrR/O/4VREnnmEAmJMmx1pZvYFSVoXDzWBirG4LhMcAsAEQEAAYkD RAQYAQoADwUCUvK7fAUJAeEzgAIbLgEpCRBgUrKtMaZjHMBdIAQZAQoABgUCUvK7 fAAKCRCYCj8NAf4E34z7B/9Xj+EEWbn01l2cvPMMmnsH5vFYqHkbvk9T8CXE/QeJ uyMgldPj0LKGHCcAP7pUlUxLlAMNAJE8Nd+evzXaNsTqjF3akidZnqjKX/URoj1d lRVHet7u01sAjzNYiMa3ysWRB6FDrQsp36iz1kR+lGVpieZNn8gC+ylQz09SVHFT rZux6XHHJe23GrFZOmjyJniTDfQ/qNtnoAOK/T1lHXgec6lxB9rcah1ggBKhier/ +s19dLUnwwTG16z9f5dtGD7k4vL+IYSkZkRLTNW3eKiIRJd7fthHRsVOPDhOCAzP 2b82p7KiR7EtrMDFiHpXxKcBQVjeOscss7oUurX7lhKFp/gP/0B+mdvSPXF5axkr ITrwmjkW760yJgs24qKmudnUqisNBQtkWYeNUW+/ws3zL2uH/1xwKQpRjRdtxDhK aREZSzIUGxKVW1ztuwnZyUHDBDitzSSqXjRf0Y46zsTaK6VxpvH2DQrXkM7sDmqe HLGe0mEHrzrhm731ZTaAFEp9+hUWOdnUHGjMX4LjWVwR44qW9gaZkJEpWJpCtEhC guz/LvVoQcX0zbx9ke8SmREyNydwvVFrX8v8LTYOFUjpZDMmaaV/KF9E/5EL5m0Y KYR3pXrRykJnJVeRqomhpz1vdP8tsYqK8+kPSJCFDn5bhqlBnFLtJWaFAKAsesFC 6/C1DUKuHhGH9eKRDEOhLjNX2Fc7D5t+Oni9AVyJ16Qku3sigo3E8IynXobEgYxg xdzDAKKugxnXx+jHE04zt0WWoxZJ99GVyRuZwBoJ0tVxWEaI40Tz0zqcqgFw1f19 5yQY9MysQh2Pr/Zlec4Y3dvW4+wMJKnijwKoCFHRr9FbQogvPnyKAFX1xYMxrS9v 1eWTQ9DN7bsS86d2BvqoOIX+Th7/7oBWvDXOJK0NGjQ8m4uL2B5a3CTdABlYdKb6 h/fESNPk3DN7y8horMo6LbCytKzttBKcPZzjVoqrlM+TJLElpe/iG4ReyMzfHwBx M3ORWFncu87+HH//p4VSw0MfvjIz =lhzE -----END PGP PUBLIC KEY BLOCK----- """ }
99720
{User} = require '../../lib/data' exports.donnie = new User { display_name : "outofelement.io/donnie" is_me : true public_key : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org <KEY> C<KEY> -----END PGP PUBLIC KEY BLOCK----- """ private_key : """ -----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org <KEY> <KEY> -----END PGP PRIVATE KEY BLOCK----- """ } exports.chris = new User { display_name : "keybase.io/chris" public_key : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org <KEY> <KEY> or<KEY> k7q1<KEY>090<KEY> -----END PGP PUBLIC KEY BLOCK----- """ } exports.max = new User { display_name : "keybase.io/max" public_key : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org <KEY> -----END PGP PUBLIC KEY BLOCK----- """ }
true
{User} = require '../../lib/data' exports.donnie = new User { display_name : "outofelement.io/donnie" is_me : true public_key : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org PI:KEY:<KEY>END_PI CPI:KEY:<KEY>END_PI -----END PGP PUBLIC KEY BLOCK----- """ private_key : """ -----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI -----END PGP PRIVATE KEY BLOCK----- """ } exports.chris = new User { display_name : "keybase.io/chris" public_key : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI orPI:KEY:<KEY>END_PI k7q1PI:KEY:<KEY>END_PI090PI:KEY:<KEY>END_PI -----END PGP PUBLIC KEY BLOCK----- """ } exports.max = new User { display_name : "keybase.io/max" public_key : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org PI:KEY:<KEY>END_PI -----END PGP PUBLIC KEY BLOCK----- """ }
[ { "context": "--------------------------------------\n # Bummed. Steve Jobs just died. 2011 Oct 5.\n # ----------------------", "end": 22541, "score": 0.9996496438980103, "start": 22531, "tag": "NAME", "value": "Steve Jobs" }, { "context": "\n\n @soundCounter ||= 0\n @soundKeys = [\"countDown_0\", \"countDown_1\", \"countDown_2\", \"countDown_3\", \"", "end": 69854, "score": 0.6117441654205322, "start": 69849, "tag": "KEY", "value": "Down_" }, { "context": "nter ||= 0\n @soundKeys = [\"countDown_0\", \"countDown_1\", \"countDown_2\", \"countDown_3\", \"countDown_4\"]\n\n", "end": 69869, "score": 0.5792084336280823, "start": 69864, "tag": "KEY", "value": "Down_" }, { "context": "@soundKeys = [\"countDown_0\", \"countDown_1\", \"countDown_2\", \"countDown_3\", \"countDown_4\"]\n\n @nSounds =", "end": 69883, "score": 0.5688705444335938, "start": 69879, "tag": "KEY", "value": "Down" }, { "context": "ge.animateOut(true)),\n animateIn: @defaultAnimateIn,\n },\n {\n oldState: [PageS", "end": 101343, "score": 0.8528741002082825, "start": 101326, "tag": "USERNAME", "value": "@defaultAnimateIn" }, { "context": "PageState.Start], \n animateOut: @defaultAnimateOut,\n animateIn: @defaultAnimateIn,\n", "end": 101507, "score": 0.9476747512817383, "start": 101490, "tag": "USERNAME", "value": "defaultAnimateOut" }, { "context": "@defaultAnimateOut,\n animateIn: @defaultAnimateIn,\n },\n {\n oldState: [PageS", "end": 101555, "score": 0.9308454394340515, "start": 101539, "tag": "USERNAME", "value": "defaultAnimateIn" }, { "context": ", PageState.About],\n animateOut: @defaultAnimateOut,\n animateIn: @defaultAnimateIn,\n", "end": 101747, "score": 0.9684600234031677, "start": 101730, "tag": "USERNAME", "value": "defaultAnimateOut" }, { "context": "@defaultAnimateOut,\n animateIn: @defaultAnimateIn,\n },\n {\n oldState: [PageS", "end": 101795, "score": 0.9614729881286621, "start": 101779, "tag": "USERNAME", "value": "defaultAnimateIn" }, { "context": ", PageState.UCCInfo],\n animateOut: @defaultAnimateOut,\n animateIn: @defaultAnimateIn,\n", "end": 101991, "score": 0.926550567150116, "start": 101973, "tag": "USERNAME", "value": "@defaultAnimateOut" }, { "context": " @defaultAnimateOut,\n animateIn: @defaultAnimateIn,\n },\n {\n oldState: [PageS", "end": 102039, "score": 0.9111654758453369, "start": 102022, "tag": "USERNAME", "value": "@defaultAnimateIn" }, { "context": "eState.JoinCodeInfo],\n animateOut: @defaultAnimateOut,\n animateIn: @defaultAnimateIn,\n", "end": 102245, "score": 0.8684846758842468, "start": 102227, "tag": "USERNAME", "value": "@defaultAnimateOut" }, { "context": " @defaultAnimateOut,\n animateIn: @defaultAnimateIn,\n }\n ]\n\n gInstance = null\n\n # -------------", "end": 102293, "score": 0.8656359314918518, "start": 102276, "tag": "USERNAME", "value": "@defaultAnimateIn" } ]
app-src/pages.coffee
hyperbotic/crowdgame-trivially
0
# ================================================================================================================== class CountdownTicker # ---------------------------------------------------------------------------------------------------------------- constructor: (@fnInitView, @fnUpdateView, @fnCompleted, @fnSound)-> this # ---------------------------------------------------------------------------------------------------------------- init: (@value, startingDelay)-> @startValue = @value this.clearTimers() this.display true fnTick = ()=> this.tick() f = ()=> this.display false @countdownInterval = setInterval fnTick, 1000 @startingDelay = null if startingDelay > 0 @startingDelay = Hy.Utils.Deferral.create startingDelay, f else f() this # ---------------------------------------------------------------------------------------------------------------- getValue: ()-> @value # ---------------------------------------------------------------------------------------------------------------- clearTimers: ()-> if @countdownInterval? clearInterval(@countdownInterval) @countdownInterval = null if @startingDelay? @startingDelay.clear() @startingDelay = null this # ---------------------------------------------------------------------------------------------------------------- display: (init)-> if init @fnInitView @value else @fnSound @value @fnUpdateView @value this # ---------------------------------------------------------------------------------------------------------------- exit: ()-> this.pause() @value = null null # ---------------------------------------------------------------------------------------------------------------- pause: ()-> this.clearTimers() this # ---------------------------------------------------------------------------------------------------------------- continue_: ()-> this.init(@value||@startValue, 0) # ---------------------------------------------------------------------------------------------------------------- reset: ()-> @value = @startValue || 10 # TODO: should get default value from app # ---------------------------------------------------------------------------------------------------------------- tick: ()-> @value -= 1 if @value >= 0 this.display false if @value <= 0 this.exit() @fnCompleted(source:this) this # ================================================================================================================== # # # zIndex scheme: # windows: 1-10 # page-owned stuff: 50-100 # overlays, buttons, other clickbale stuff: 101+ # # Lifecycle of a Page: # created # initialize # open # start # ... # close # stop # # also: # pause # resumed # class Page gInstanceCount = 0 gPages = [] # ---------------------------------------------------------------------------------------------------------------- @findPage: (pageClass)-> for page in gPages if page.constructor.name is pageClass.name return page null # ---------------------------------------------------------------------------------------------------------------- @getPage: (pageMap)-> p = (Page.findPage(pageMap.pageClass)) || new pageMap.pageClass(pageMap.state, Hy.ConsoleApp.get()) p # ---------------------------------------------------------------------------------------------------------------- # NOT IMPLEMENTED @doneWithPage: (pageMap)-> if (p = Page.findPage(pageMap.pageClass)) gPages = gPages.reject(p) p.doneWithPage() null # ---------------------------------------------------------------------------------------------------------------- constructor: (@state, @app)-> @instance = ++gInstanceCount gPages.push this options = fullscreen: true zIndex: 2 orientationModes: [Ti.UI.LANDSCAPE_LEFT, Ti.UI.LANDSCAPE_RIGHT] opacity: 0 _tag: "Main Window" @window = new Hy.UI.WindowProxy(options) @window.addChild(@container = new Hy.UI.ViewProxy(this.containerOptions())) @container.addChild(this.createAnimationContainer()) # @window.setTrace("opacity") this # ---------------------------------------------------------------------------------------------------------------- initialize: ()-> # We do this here since a page's state can change (since pages can be reused, such as Question) @container.setUIProperty("backgroundImage", if (background = PageState.getPageMap(this.getState()).background)? then background else null) @allowEvents = false true # ---------------------------------------------------------------------------------------------------------------- getAllowEvents: ()-> @allowEvents # ---------------------------------------------------------------------------------------------------------------- getState: ()-> @state # ---------------------------------------------------------------------------------------------------------------- setState: (state)-> @state = state # ---------------------------------------------------------------------------------------------------------------- getWindow: ()->@window # ---------------------------------------------------------------------------------------------------------------- getApp: ()-> @app # ---------------------------------------------------------------------------------------------------------------- obs_networkChanged: (reason)-> this # ---------------------------------------------------------------------------------------------------------------- openWindow: (options={})-> @window.open(options) this # ---------------------------------------------------------------------------------------------------------------- closeWindow: (options={})-> @window.close() this # ---------------------------------------------------------------------------------------------------------------- animateWindow: (options)-> # 2.5.0 @window.animate(options) this # ---------------------------------------------------------------------------------------------------------------- start: ()-> @allowEvents = true this.setStopAnimating(false) this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> @allowEvents = false this.setStopAnimating(true) this # ---------------------------------------------------------------------------------------------------------------- pause: ()-> this # ---------------------------------------------------------------------------------------------------------------- resumed: ()-> this # ---------------------------------------------------------------------------------------------------------------- containerOptions: ()-> top: 0 left: 0 width: Hy.UI.iPad.screenWidth # must set these, else _layout{vertical, horizontal} directives wont work height: Hy.UI.iPad.screenHeight zIndex: 101 _tag: "Main Container" # ---------------------------------------------------------------------------------------------------------------- createAnimationContainer: ()-> animationContainerOptions = top: 0 left: 0 right: 0 bottom: 0 zIndex: 200 opacity: 1 _tag: "Animation Container" @animationContainer = new Hy.UI.ViewProxy(animationContainerOptions) @animationContainer.hide() @animationContainerHidden = true @animationContainer # ---------------------------------------------------------------------------------------------------------------- buildAnimationFromScenes: (scenes, previousScenes = null)-> sceneTotalDuration = 0 currentStart = 0 for scene in scenes sceneDuration = 0 sceneCurrentStart = 0 sceneFirstStart = null for animationOption in scene.animationOptions sceneCurrentStart += animationOption._incrementalDelay if not sceneFirstStart? sceneFirstStart = sceneCurrentStart if not animationOption.duration? animationOption.duration = 0 sceneDuration = Math.max(sceneDuration, sceneCurrentStart + animationOption.duration) aOptions = delay: currentStart + sceneCurrentStart animationOption._animationObjectOptions = Hy.UI.ViewProxy.mergeOptions(animationOption, aOptions) computedOptions = Hy.UI.ViewProxy.mergeOptions(scene.imageOptions, {}) #make a copy createdNewScene = true if previousScenes? if(existingScene = _.detect(previousScenes, (s)=>s.image is scene.image))? createdNewScene = false scene._view = existingScene._view scene._view.setUIProperties(computedOptions) if not scene._view? computedOptions._tag = "Animation" if scene.image? computedOptions.image = "assets/bkgnds/animations/#{scene.image}.png" scene._view = new Hy.UI.ImageViewProxy(computedOptions) else if scene.method? scene._view = scene.method(computedOptions) else Hy.Trace.debug "Page::buildAnimationFromScenes (NO SCENE IMAGE OR METHOD)" # STOP events don't seem to be getting fired. The below callback is never called. if scene._view? and createdNewScene scene._view.addEventListener("stop", (evt, view)=>Hy.Trace.debug("ANIMATION STOP EVENT (#{scene.image} view=#{view?.getTag()}")) sceneTotalDuration = Math.max(sceneTotalDuration, currentStart + sceneDuration) currentStart += sceneFirstStart [scenes, sceneTotalDuration] # ---------------------------------------------------------------------------------------------------------------- setStopAnimating: (flag)-> @stopAnimating = flag # ---------------------------------------------------------------------------------------------------------------- clearAnimation: ()-> Hy.Trace.debug "Page::hideAnimation (CLEARING ANIMATION CONTAINER)" this.hideAnimation() @animationContainer.removeChildren() this # ---------------------------------------------------------------------------------------------------------------- hideAnimation: ()-> Hy.Trace.debug "Page::hideAnimation (HIDING ANIMATION CONTAINER)" @animationContainer?.hide() @animationContainerHidden = true this # ---------------------------------------------------------------------------------------------------------------- animateScenes: (scenes)-> this.setStopAnimating(false) @animationOpenedWindow = false for scene in scenes this.animateScene(scenes, scene, 0) this # ---------------------------------------------------------------------------------------------------------------- animateScene: (scenes, scene, index)-> animationOption = scene.animationOptions[index] animationOption._animationObject = null #TEST imageOptions = {} if animationOption._startOpacity? imageOptions.opacity = animationOption._startOpacity else if animationOption.opacity? imageOptions.opacity = 0 scene._view.setUIProperties(imageOptions) if @animationContainerHidden @animationContainerHidden = false @animationContainer.show() if not @animationContainer.hasChild(scene._view) @animationContainer.addChild(scene._view) Hy.Trace.debug "Page::animateScene (BEGIN ANIMATE #{scene.image} ##{index})" if not @animationOpenedWindow @window.setUIProperty("opacity", 1.0) this.openWindow() @animationOpenedWindow = true animateFn = ()=> Hy.Trace.debug "Page::animateScene (CONTINUING ANIMATION #{scene.image})" animationOption._animationObject = Ti.UI.createAnimation(animationOption._animationObjectOptions) animationOption._animationObject.addEventListener("complete", (evt)=>this.animateCompleteEvent(evt.source, scenes)) scene._view.animate(animationOption._animationObject) null # Note that this is a hack and won't work as intended if there are multiple scenes to be animated if (fn = animationOption._waitForWindowFn)? Hy.Utils.Deferral.create(0, ()=>fn(animateFn)) else animateFn() this # ---------------------------------------------------------------------------------------------------------------- # TODO: it's possible that our version of the properties of an object that's been animated may no longer # reflect reality, at the end of an animation. Should really set UIProperties at the end, here. animateCompleteEvent: (animationObject, scenes)-> for scene in scenes index = -1 for animationOption in scene.animationOptions index++ if animationOption._animationObject is animationObject if index < (_.size(scene.animationOptions)-1) if @stopAnimating Hy.Trace.debug "Page::animateCompleteEvent (ANIMATION STOPPED #{scene.image})" else Hy.Trace.debug "Page::animateCompleteEvent (ANIMATION COMPLETED FOR #{scene.image} ##{index}, continuing)" this.animateScene(scenes, scene, index+1) else # if we're here, we're done with this scene. But we can't necessarily remove the scene's view. Hy.Trace.debug "Page::animateCompleteEvent (ANIMATION COMPLETED #{scene.image})" # @animationContainer.removeChild(scene._view) return this this # ================================================================================================================== class SplashPage extends Page # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app # @container.addChild(this.createJewelContainer()) this # ---------------------------------------------------------------------------------------------------------------- createJewelContainer: ()-> defaultOptions = image: "assets/icons/trivially-01.png" height: 100 width: 100 _tag: "Jewel Container" @jewelView = new Hy.UI.ImageViewProxy(defaultOptions) @jewelView # ---------------------------------------------------------------------------------------------------------------- initialize: (fnReady)-> super true # ---------------------------------------------------------------------------------------------------------------- start: ()-> super this # ================================================================================================================== class IntroPage extends Page # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app this.webViewPanelCreate() this.addClick() this # ---------------------------------------------------------------------------------------------------------------- openWindow: (options={})-> super options @webView?.open() this # ---------------------------------------------------------------------------------------------------------------- closeWindow: (options={})-> @webViewPanel?.close() super this # ---------------------------------------------------------------------------------------------------------------- initialize: (fnReady)-> super @fnReady = fnReady @clicked = false @clickAllowed = true @finishingUp = false @finishedAnimatingIn = false # apparently, the window has to be open in order for the webview to work... # @window.setUIProperty("opacity", 0) this.openWindow() @webViewPanel?.initialize( (event)=>Hy.Utils.Deferral.create(0, ()=>PageState.get().resumed()) ) @introPanel?.initialize() # Not likely false # Wait # ---------------------------------------------------------------------------------------------------------------- start: ()-> super # @clickAllowed = true @webView?.start() this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> @clickAllowed = false @webView?.stop() super this # ---------------------------------------------------------------------------------------------------------------- resumed: ()-> super this # ---------------------------------------------------------------------------------------------------------------- obs_networkChanged: (reason)-> super @introPanel?.obs_networkChanged(reason) this # ---------------------------------------------------------------------------------------------------------------- setStopAnimating: (flag)-> super if not @finishedAnimatingIn @webViewPanel?.fireEvent({kind: "stopAnimating"}, (event)=>this.animateInFinished()) this # ---------------------------------------------------------------------------------------------------------------- addClick: ()-> options = top: 0 bottom: 0 right: 0 left: 0 zIndex: @animationContainer.getUIProperty("zIndex") + 1 _tag: "Click Container" @container.addChild(v = new Hy.UI.ViewProxy(options)) fnClick = (evt)=> if not @clicked and @clickAllowed @clicked = true @finishingUp = true if (pageState = PageState.get()).isTransitioning() Hy.Trace.debug("IntroPage::addClick (WAITING FOR TRANSITION)") pageState.addPostTransitionAction(()=>@fnReady?()) this.setStopAnimating(true) else Hy.Trace.debug("IntroPage::addClick (NOT TRANSITIONING)") this.animateOutIntroPanelAndTitle() @fnReady?() null v.addEventListener("click", fnClick) this # ---------------------------------------------------------------------------------------------------------------- addTitle: ()-> options = top: 140 # 170 # 2.5.0 left: (Hy.UI.iPad.screenWidth-315)/2 image: "assets/bkgnds/animations/label-Trivially.png" width: 315 height: 100 zIndex: 102 opacity: 0 _tag: "Title" @container.addChild(@title = new Hy.UI.ImageViewProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- addIntroPanel: ()-> options = top: 260 # 290 # 2.5.0 zIndex: 102 touchEnabled: false opacity: 0 @container.addChild(@introPanel = new Hy.Panels.IntroPanel(options)) @introPanel.initialize() this # ---------------------------------------------------------------------------------------------------------------- animateInFinished: ()-> if not @finishingUp and not @introPanel? this.addTitle() this.addIntroPanel() this.animateInIntroPanelAndTitle() @finishedAnimatingIn = true Hy.Utils.Deferral.create(0, ()=>PageState.get().resumed()) # ---------------------------------------------------------------------------------------------------------------- animateIn: ()-> @webViewPanel?.fireEvent({kind: "animateIn"}, (event)=>this.animateInFinished()) this.animateWindow({opacity: 1, duration: 0}) return -1 # ---------------------------------------------------------------------------------------------------------------- animateInIntroPanelAndTitle: ()-> @introPanel?.animate({opacity:1, duration: 100}) @title?.animate({opacity:1, duration: 100}) this # ---------------------------------------------------------------------------------------------------------------- animateOutIntroPanelAndTitle: (fnDone = null)-> Hy.Trace.debug("IntroPage::animateOutIntroPanelAndTitle") animateCount = 0 fn = (evt)=> Hy.Trace.debug("IntroPage::animateOutIntroPanelAndTitle (#{animateCount})") if ++animateCount is 2 fnDone?() null if true @introPanel?.animate({opacity:0, duration: 50}, fn) @title?.animate({opacity:0, duration: 50}, fn) else @introPanel?.setUIProperty("opacity", 0) @title?.setUIProperty("opacity", 0) fnDone?() this # ---------------------------------------------------------------------------------------------------------------- animateOut: ()-> Hy.Trace.debug("IntroPage::animateOut") @clickAllowed = false fn = ()=> @webViewPanel?.fireEvent({kind: "animateOut"}, (event)=>this.animateOutFinished()) null this.animateOutIntroPanelAndTitle(fn) return -1 # ---------------------------------------------------------------------------------------------------------------- animateOut2: ()-> @clickAllowed = false @webViewPanel?.fireEvent({kind: "animateOut"}, (event)=>this.animateOutFinished()) @introPanel?.animate({opacity:0, duration: 100}) @title?.animate({opacity:0, duration: 100}) return -1 # ---------------------------------------------------------------------------------------------------------------- animateOutFinished: ()-> duration = 0 this.animateWindow({opacity: 0, duration: duration}) # 2.5.0 Hy.Utils.Deferral.create(duration, ()=>PageState.get().resumed()) this # ---------------------------------------------------------------------------------------------------------------- webViewPanelCreate: ()-> options = this.containerOptions() options._tag = "WebViewPanel" # options.borderWidth = 10 # options.borderColor = Hy.UI.Colors.green webViewOptions = top: options.top left: options.left width: options.width height: options.height _tag: "Intro Page Web View" scalesPageToFit:false url: "html-intro-page.html" zIndex: 50 #@zIndexPassive backgroundColor:'transparent' # http://developer.appcelerator.com/question/45491/can-i-change-the-white-background-that-shows-when-a-web-view-is-loading @container.addChild(@webViewPanel = new Hy.Panels.WebViewPanel(options, webViewOptions)) this # ---------------------------------------------------------------------------------------------------------------- # Bummed. Steve Jobs just died. 2011 Oct 5. # ---------------------------------------------------------------------------------------------------------------- # ================================================================================================================== class UtilityPage extends Page # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> @subpanels = [] super state, app this.addCrowdGameLogo() .addTitle() this # ---------------------------------------------------------------------------------------------------------------- addSubpanel: (subpanel)-> @container.addChild(subpanel) @subpanels.push subpanel this # ---------------------------------------------------------------------------------------------------------------- containerOptions: ()-> options = super options.zIndex = 90 options # ---------------------------------------------------------------------------------------------------------------- initialize: ()-> super for panel in @subpanels panel.initialize() true # ---------------------------------------------------------------------------------------------------------------- obs_networkChanged: (reason)-> super for panel in @subpanels panel.obs_networkChanged(reason) this # ---------------------------------------------------------------------------------------------------------------- addCrowdGameLogo: ()-> options = top: 20 left: 30 image: "assets/icons/CrowdGame.png" width: 215 height: 50 _tag: "Logo" @container.addChild(new Hy.UI.ImageViewProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- addTitle: ()-> options = top: 20 left: (Hy.UI.iPad.screenWidth-316)/2 image: "assets/icons/label-Trivially.png" width: 316 height: 101 _tag: "Title" @container.addChild(new Hy.UI.ImageViewProxy(options)) this # ================================================================================================================== class AboutPage extends UtilityPage # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app @restored = false this.addSubpanel(this.addAboutPanel()) this # ---------------------------------------------------------------------------------------------------------------- addAboutPanel: ()-> fnClickDone = ()=> # If we did a restore, we need to reinitialize the content list on the Start Page r = @restored @restored = false this.getApp().showStartPage(if r then [((page)=>page.updateContentOptionsPanel())] else []) null fnUpdateClicked = (evt, clickedView)=> if evt.index is 0 Hy.Content.ContentManager.get()?.updateManifests() null fnClickRestore = ()=> # Must be online if Hy.Network.NetworkService.isOnline() # If an update is available, force it first if Hy.Content.ContentManifestUpdate.getUpdate()? options = message: "Trivially requires an update before purchases can be restored.\nTap \"update\" to begin" buttonNames: ["update", "cancel"] cancel: 1 dialog = new Hy.UI.AlertDialog(options) dialog.addEventListener("click", fnUpdateClicked) else @restored = true Hy.Content.ContentManager.get()?.restore() # Let's present the restore UI on the About page # this.getApp().restoreAction() else new Hy.UI.AlertDialog("Please connect to Wifi and try again") null fnClickJoinHelp = ()=> this.getApp().showJoinCodeInfoPage() null new Hy.Panels.AboutPanel({}, fnClickDone, fnClickRestore, fnClickJoinHelp) # ================================================================================================================== class UserCreatedContentInfoPage extends UtilityPage # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app this.addSubpanel(this.addInfoPanel()) this # ---------------------------------------------------------------------------------------------------------------- addInfoPanel: ()-> fnClickDone = ()=> this.getApp().showStartPage() null fnClickBuy = ()=> this.getApp().userCreatedContentAction("buy", null, true) null new Hy.Panels.UserCreatedContentInfoPanel({}, fnClickDone, fnClickBuy) # ================================================================================================================== class JoinCodeInfoPage extends UtilityPage # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app this.addSubpanel(this.addInfoPanel()) this # ---------------------------------------------------------------------------------------------------------------- addInfoPanel: ()-> fnClickDone = ()=> this.getApp().showStartPage() null new Hy.Panels.JoinCodeInfoPanel({}, fnClickDone) # ================================================================================================================== class StartPage extends Page _.extend StartPage, Hy.Utils.Observable # For changes to the state of the Start button # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app @pageEnabled = true @startEnabled = {state: false, reason: null} fnStart = (evt)=>this.startClicked() this.addCrowdGameLogo() .addTitle() .addAboutPageButton() .addGameOptionPanels() .addContentOptionsPanel() .addStartButton(fnStart) .addStartButtonText() .addContentOptionsInfo() .addJoinCodeInfo() .addUpdateAvailableInfo() @message = new Hy.Panels.MessageMarquee(this, @container) this.createCheckInCritterPanel() @fnContentPacksChanged = (evt)=>this.contentPacksChanged(evt) Hy.Pages.StartPage.addObserver this # For tracking changes to Start Button state this # ---------------------------------------------------------------------------------------------------------------- isPageEnabled: ()-> @pageEnabled # ---------------------------------------------------------------------------------------------------------------- setPageEnabled: (enabled)-> @pageEnabled = enabled for panel in [@aboutPanel, @joinCodeInfoPanel, @updateAvailablePanel] if enabled panel?.initialize() else panel?.setEnabled(false) StartPage.notifyObservers (observer)=>observer.obs_startPagePageEnabledStateChange?(@pageEnabled) this.updateUCCInfo() this # ---------------------------------------------------------------------------------------------------------------- containerOptions: ()-> options = super options.zIndex = 90 options # ---------------------------------------------------------------------------------------------------------------- openWindow: (options={})-> super options @contentOptionsPanel.open(options) this # ---------------------------------------------------------------------------------------------------------------- closeWindow: (options={})-> @contentOptionsPanel.close(options) super this # ---------------------------------------------------------------------------------------------------------------- animateWindow: (options)-> # 2.5.0 @contentOptionsPanel.animate(options) super options this # ---------------------------------------------------------------------------------------------------------------- start: ()-> super Hy.Options.contentPacks.addEventListener 'change', @fnContentPacksChanged Hy.Content.ContentManager.addObserver this # Tracking inventory changes Hy.Content.ContentManagerActivity.addObserver this # ContentPack updates Hy.Update.Update.addObserver this # as updates become available: "obs_updateAvailable" @contentOptionsPanel.start() @message.start() @checkInCritterPanel.start() # Check for required or strongly-urged content or app updates, which appear to the user # as a popover, which either allows dismissal, with frequent reminders, or which can't be dismissed, in # the case of required updates. # First, make sure we're online and not otherwise busy if not Hy.Pages.PageState.get().hasPostFunctions() and Hy.Network.NetworkService.isOnline() if not Hy.Content.ContentManager.get().doUpdateChecks() # Do update checks first if not Hy.Update.ConsoleAppUpdate.getUpdate()?.doRequiredUpdateCheck() # Then app updates Hy.Update.RateAppReminder.getUpdate()?.doRateAppReminderCheck() # Then rate app requests this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> Hy.Options.contentPacks.removeEventListener 'change', @fnContentPacksChanged Hy.Content.ContentManager.removeObserver this Hy.Content.ContentManagerActivity.removeObserver this Hy.Update.Update.removeObserver this @contentOptionsPanel.stop() @message.stop() @checkInCritterPanel.stop() super this # ---------------------------------------------------------------------------------------------------------------- pause: ()-> @message.pause() @checkInCritterPanel.pause() super this # ---------------------------------------------------------------------------------------------------------------- resumed: ()-> super @message.resumed() @checkInCritterPanel.resumed() # If our state shows that the Start Button was clicked, and we're being resumed, then # it's likely that we were backgrounded while preparing a contest. So just reset state and let # the user tap the button again if so inclined if this.startButtonIsClicked() this.resetStartButtonClicked() this # ---------------------------------------------------------------------------------------------------------------- initialize: ()-> super this.updateStartButtonEnabledState() this.resetStartButtonClicked() @aboutPanelButtonClicked = false @joinCodeInfoPanelButtonClicked = false @updateAvailablePanelButtonClicked = false @aboutPanel.initialize() @updateAvailablePanel.initialize() @joinCodeInfoPanel.initialize() if @panelSound? @panelSound.syncCurrentChoiceWithAppOption() @checkInCritterPanel.initialize() @contentOptionsPanel.initialize() this.updateUCCInfo() true # ---------------------------------------------------------------------------------------------------------------- obs_networkChanged: (reason)-> super if this.isPageEnabled() @joinCodeInfoPanel.obs_networkChanged(reason) @updateAvailablePanel.obs_networkChanged(reason) this # ---------------------------------------------------------------------------------------------------------------- obs_updateAvailable: (update)-> if this.isPageEnabled() if update.isContentManifestUpdate() or update.isConsoleAppUpdate() @updateAvailablePanel.obs_updateAvailable() this # ---------------------------------------------------------------------------------------------------------------- updateUCCInfo: ()-> buyButton = @panelUCCInfo.findButtonViewByValue(Hy.Config.Content.kThirdPartyContentBuyText) addButton = @panelUCCInfo.findButtonViewByValue(Hy.Config.Content.kThirdPartyContentNewText) infoButton = @panelUCCInfo.findButtonViewByValue(Hy.Config.Content.kThirdPartyContentInfoText) if this.isPageEnabled() isPurchased = Hy.Content.ContentManager.get().getUCCPurchaseItem().isPurchased() buyButton?.setEnabled(not isPurchased) addButton?.setEnabled(isPurchased) infoButton?.setEnabled(true) else buyButton?.setEnabled(false) addButton?.setEnabled(false) infoButton?.setEnabled(false) this # ---------------------------------------------------------------------------------------------------------------- addCrowdGameLogo: ()-> options = top: 20 left: 30 image: "assets/icons/CrowdGame.png" width: 215 height: 50 _tag: "Logo" @container.addChild(@crowdGameLogoView = new Hy.UI.ImageViewProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- addTitle: ()-> options = top: 20 left: (Hy.UI.iPad.screenWidth-316)/2 image: "assets/icons/label-Trivially.png" width: 315 height: 100 _tag: "Title" @container.addChild(@titleView = new Hy.UI.ImageViewProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- # addAboutPageButton: ()-> @aboutPanelButtonClicked = false fnClick = ()=> if @aboutPanel.isEnabled() and not @aboutPanelButtonClicked @aboutPanelButtonClicked = true this.getApp().showAboutPage() null # We take our cues from other screen elements: CrowdGame Logo image, Trivially label options = top: @titleView.getUIProperty("top") right: @crowdGameLogoView.getUIProperty("left") title: "?" font: Hy.UI.Fonts.specBigNormal _tag: "About Button" buttonOptions = title: "?" font: Hy.UI.Fonts.specBigNormal topTextOptions = {} bottomTextOptions = {text: "Help"} @container.addChild(@aboutPanel = new Hy.Panels.LabeledButtonPanel(options, buttonOptions, fnClick, topTextOptions, bottomTextOptions)) this # ---------------------------------------------------------------------------------------------------------------- obs_contentUpdateSessionStarted: (label, report)-> # @message.startAdHocSession(label) this.updateStartButtonEnabledState() this.setPageEnabled(false) # if report? # @message.addAdHoc(report) this # ---------------------------------------------------------------------------------------------------------------- obs_contentUpdateSessionProgressReport: (report, percentDone = -1)-> Hy.Trace.debug "StartPage::contentUpdateSessionProgressReport (#{report} / #{percentDone})" if percentDone isnt -1 report += " (#{percentDone}% done)" # if report? # @message.addAdHoc report this # ---------------------------------------------------------------------------------------------------------------- obs_contentUpdateSessionCompleted: (report, changes)-> Hy.Trace.debug "StartPage::contentUpdateSessionCompleted #{report}" # @message.addAdHoc(report) # @message.endAdHocSession() this.updateStartButtonEnabledState() this.setPageEnabled(true) @updateAvailablePanel.initialize() this # ---------------------------------------------------------------------------------------------------------------- obs_inventoryInitiated: ()-> @message.startAdHocSession("Syncing with Apple App Store") @message.addAdHoc("Contacting Store") this # ---------------------------------------------------------------------------------------------------------------- obs_inventoryUpdate: (status, message)-> if message? @message.addAdHoc(message) this # ---------------------------------------------------------------------------------------------------------------- obs_inventoryCompleted: (status, message)-> if message? @message.addAdHoc(message) @message.endAdHocSession() this # ---------------------------------------------------------------------------------------------------------------- obs_purchaseInitiated: (label, report)-> this.updateStartButtonEnabledState() this.setPageEnabled(false) # @message.startAdHocSession(label) # if report? # @message.addAdHoc(report) this # ---------------------------------------------------------------------------------------------------------------- obs_purchaseProgressReport: (report)-> Hy.Trace.debug "StartPage::purchaseProgressReport #{report}" # if report? # @message.addAdHoc(report) null # ---------------------------------------------------------------------------------------------------------------- obs_purchaseCompleted: (report)-> this.updateStartButtonEnabledState() this.setPageEnabled(true) this.updateUCCInfo() # if report? # @message.addAdHoc(report) # @message.endAdHocSession() null # ---------------------------------------------------------------------------------------------------------------- obs_restoreInitiated: (report)-> this.updateStartButtonEnabledState() this.setPageEnabled(false) # @message.startAdHocSession("Restore of purchases") # if report? # @message.addAdHoc(report) null # ---------------------------------------------------------------------------------------------------------------- obs_restoreProgressReport: (report)-> # if report? # @message.addAdHoc(report) null # ---------------------------------------------------------------------------------------------------------------- obs_restoreCompleted: (report)-> this.updateStartButtonEnabledState() this.setPageEnabled(true) # if report? # @message.addAdHoc(report) # @message.endAdHocSession() null # ---------------------------------------------------------------------------------------------------------------- addStartButton: (fn)-> options = height: 110 width: 110 top: 415 left: 277 zIndex: 101 backgroundImage: "assets/icons/button-play.png" backgroundSelectedImage: "assets/icons/button-play-selected.png" _tag: "Start Button" @container.addChild(@startButton = new Hy.UI.ButtonProxy(options)) this.resetStartButtonClicked() @fnClickStartGame = (evt)=> if @startEnabled.state if not this.startButtonIsClicked() this.setStartButtonClicked() fn() null @startButton.addEventListener 'click', @fnClickStartGame this # ---------------------------------------------------------------------------------------------------------------- startButtonIsClicked: ()-> @startButtonClicked # ---------------------------------------------------------------------------------------------------------------- setStartButtonClicked: ()-> @startButtonClicked = true # ---------------------------------------------------------------------------------------------------------------- resetStartButtonClicked: ()-> @startButtonClicked = false # ---------------------------------------------------------------------------------------------------------------- getStartEnabled: ()-> [@startEnabled.state, @startEnabled.reason] # ---------------------------------------------------------------------------------------------------------------- setStartEnabled: (state, reason)-> @startEnabled.state = state @startEnabled.reason = reason @startButton.setEnabled(state) this.setContentOptionsInfo(state, reason) StartPage.notifyObservers (observer)=>observer.obs_startPageStartButtonStateChanged?(state, reason) this # ---------------------------------------------------------------------------------------------------------------- addStartButtonText: ()-> width = 200 options = top: @startButton.getUIProperty("top") + 120 left: @startButton.getUIProperty("left") - ((width-@startButton.getUIProperty("width"))/2) width: width height: 50 text: "Start Game" font: Hy.UI.Fonts.specMediumMrF zIndex:@startButton.getUIProperty("zIndex") textAlign: 'center' _tag: "Start Game Label" @container.addChild(@startButtonTextView = new Hy.UI.LabelProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- # "1 topic selected", etc # addContentOptionsInfo: ()-> width = 70 options = top: @startButton.getUIProperty("top") left: @startButton.getUIProperty("left") - (width + 20) width: width height: @startButton.getUIProperty("height") font: Hy.UI.Fonts.specMinisculeNormal color: Hy.UI.Colors.black zIndex:@startButton.getUIProperty("zIndex") textAlign: 'center' _tag: "Content Options Info" # borderColor: Hy.UI.Colors.white @container.addChild(@contentOptionsPanelInfoView = new Hy.UI.LabelProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- setContentOptionsInfo: (state, info = null)-> @contentOptionsPanelInfoView.setUIProperty("color", if state then Hy.UI.Colors.black else Hy.UI.Colors.MrF.Red) @contentOptionsPanelInfoView.setUIProperty("text", info) this # ---------------------------------------------------------------------------------------------------------------- # We position this relative to the ? About Page Button... # addJoinCodeInfo: ()-> @joinCodeInfoPanelButtonClicked = false fnClick = ()=> if @joinCodeInfoPanel.isEnabled() and not @joinCodeInfoPanelButtonClicked @joinCodeInfoPanelButtonClicked = true this.getApp().showJoinCodeInfoPage() null options = bottom: @startButtonTextView.getUIProperty("bottom") - 20 left: 50 @container.addChild(@joinCodeInfoPanel = new Hy.Panels.CodePanel(options, fnClick)) this # ---------------------------------------------------------------------------------------------------------------- # We position this relative to the ? About Page Button... # addUpdateAvailableInfo: ()-> @updateAvailablePanelButtonClicked = false fnClick = (e, v)=> if @updateAvailablePanel.isEnabled() and not @updateAvailablePanelButtonClicked @updateAvailablePanelButtonClicked = true if Hy.Network.NetworkService.isOnline() # Check for Content Update, then App Update if Hy.Content.ContentManifestUpdate.getUpdate()? Hy.Content.ContentManager.get()?.updateManifests() else if (update = Hy.Update.ConsoleAppUpdate.getUpdate())? update.doURL() @updateAvailablePanelButtonClicked = false null options = top: @startButton.getUIProperty("top") - 20 left: 50 @container.addChild(@updateAvailablePanel = new Hy.Panels.UpdateAvailablePanel(options, fnClick)) this # ---------------------------------------------------------------------------------------------------------------- addGameOptionPanels: ()-> top = 93 #130 #155 left = 85 #75 padding = 55 panelSpecs = [ {varName: "panelSound", fnName: "createSoundPanel", options: {left: left}}, {varName: "panelNumberOfQuestions", fnName: "createNumberOfQuestionsPanel", options: {left: left}}, {varName: "panelSecondsPerQuestion", fnName: "createSecondsPerQuestionPanel", options: {left: left}}, {varName: "panelFirstCorrect", fnName: "createFirstCorrectPanel", options: {left: left}}, {varName: "panelUCCInfo", fnName: "createUserCreatedContentInfoPanel2", options: {left: left}} ] for panelSpec in panelSpecs this[panelSpec.varName] = Hy.Panels.OptionPanels[panelSpec.fnName](this, Hy.UI.ViewProxy.mergeOptions(panelSpec.options, {top: top})) @container.addChild(this[panelSpec.varName]) top += padding this # ---------------------------------------------------------------------------------------------------------------- addContentOptionsPanel: ()-> options = top: 100 right: 80 @container.addChild(@contentOptionsPanel = new Hy.Panels.ContentOptionsPanel(this, options)) this # ---------------------------------------------------------------------------------------------------------------- updateContentOptionsPanel: ()-> Hy.Trace.debug "StartPage::updateContentOptionsPanel" @contentOptionsPanel?.update() this # ---------------------------------------------------------------------------------------------------------------- obs_userCreatedContentSessionStarted: (label, report = null)-> this.updateStartButtonEnabledState() this.setPageEnabled(false) # @message.startAdHocSession(label) # @message.addAdHoc(if report? then report else "Starting... This will only take a moment...") this # ---------------------------------------------------------------------------------------------------------------- obs_userCreatedContentSessionProgressReport: (report = null)-> # if report? # @message.addAdHoc(report) this # ---------------------------------------------------------------------------------------------------------------- obs_userCreatedContentSessionCompleted: (report = null, changes = false)-> this.updateUCCInfo() this.updateStartButtonEnabledState() this.setPageEnabled(true) # @message.addAdHoc(if report? then report else "Completed") # @message.endAdHocSession() this # ---------------------------------------------------------------------------------------------------------------- createCheckInCritterPanel: ()-> options = left: 0 bottom: 0 @container.addChild(@checkInCritterPanel = new Hy.Panels.CheckInCritterPanel(options)) this # ---------------------------------------------------------------------------------------------------------------- startClicked: ()-> Hy.Utils.Deferral.create 0, ()=>this.getApp().contestStart() # must use deferral to trigger startContest outside of event handler this # ---------------------------------------------------------------------------------------------------------------- updateStartButtonEnabledState: ()-> Hy.Trace.debug "StartPage::updateStartButtonEnabledState" reason = null state = false numTopics = _.size(_.select(Hy.Content.ContentManager.get().getLatestContentPacksOKToDisplay(), (c)=>c.isSelected())) if numTopics <= 0 reason = "No topics selected!" state = false else state = true reason = "#{numTopics} topic#{if numTopics > 1 then "s" else ""} selected" if (r = Hy.Content.ContentManager.isBusy())? reason = "Please wait: #{r}" state = false this.setStartEnabled(state, reason) this # ---------------------------------------------------------------------------------------------------------------- categoriesChanged: (evt)-> this.updateStartButtonEnabledState() # ---------------------------------------------------------------------------------------------------------------- contentPacksChanged: (evt)-> this.updateStartButtonEnabledState() # ---------------------------------------------------------------------------------------------------------------- contentPacksLoadingStart: ()-> @message.startAdHocSession("Preparing Contest") # ---------------------------------------------------------------------------------------------------------------- contentPacksLoadingCompleted: ()-> @message.endAdHocSession() # ---------------------------------------------------------------------------------------------------------------- contentPacksLoading: (report)-> @message.addAdHoc(report) # ================================================================================================================== class NotifierPage extends Page # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app @fnNotify = null this # ---------------------------------------------------------------------------------------------------------------- initialize: (fnNotify)-> super @fnNotify = fnNotify true # ---------------------------------------------------------------------------------------------------------------- start: ()-> super @fnNotify?() this # ---------------------------------------------------------------------------------------------------------------- resumed: ()-> super @fnNotify?() this # ================================================================================================================== class BasePage extends NotifierPage constructor: (state, app)-> super state, app @container.addChild(@questionInfoPanel = new Hy.Panels.QuestionInfoPanel(this.questionInfoPanelOptions())) this # ---------------------------------------------------------------------------------------------------------------- labelColor: ()-> Hy.UI.Colors.white # ---------------------------------------------------------------------------------------------------------------- questionInfoPanelOptions: ()-> {} # ================================================================================================================== # adds support for pause button and countdown class CountdownPage extends BasePage kCountdownStateUndefined = 0 kCountdownStateRunning = 1 kCountdownStatePaused = 2 @kWidth = 164 # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app @fnPause = null @fnCompleted = null @pauseClicked = false @overlayClicked = false @overlayShowing = false @currentCountdownValue = null @countdownSeconds = 0 @startingDelay = 0 @countdownDeferral = null @fnPauseClick = (evt)=> if not @pauseClicked @pauseClicked = true this.click() null @fnClickContinueGame = ()=> this.continue_() @overlayClicked = false @pauseClicked = false null @fnClickNewGame = ()=> @overlayClicked = false @pauseClicked = false this.getApp().contestRestart(false) null @fnClickForceFinish = ()=> @overlayClicked = false @pauseClicked = false this.getApp().contestForceFinish() null @container.addChild(@countdownPanel = new Hy.Panels.CountdownPanel(this.countdownPanelOptions(), @fnPauseClick)) @container.addChild(this.createPauseButton(this.pauseButtonOptions())) @container.addChild(this.createPauseButtonText(this.pauseButtonTextOptions())) this # ---------------------------------------------------------------------------------------------------------------- countdownPanelOptions: ()-> {} # ---------------------------------------------------------------------------------------------------------------- pauseButtonOptions: ()-> {} # ---------------------------------------------------------------------------------------------------------------- pauseButtonTextOptions: ()-> {} # ---------------------------------------------------------------------------------------------------------------- pause: ()-> return if @countdownState is kCountdownStatePaused @countdownState = kCountdownStatePaused this.disablePause() @countdownTicker?.pause() this.showOverlay({opacity:1, duration: 200}) # Hy.Network.NetworkService.get().setImmediate() @fnPause() # ---------------------------------------------------------------------------------------------------------------- resumed: ()-> super this.pause() this # ---------------------------------------------------------------------------------------------------------------- continue_: ()-> return if @countdownState is kCountdownStateRunning # Hy.Network.NetworkService.get().setSuspended() @countdownState = kCountdownStateRunning f = ()=> this.enablePause() @countdownTicker?.continue_() @fnNotify() this.hideOverlay({opacity:0, duration: 200}, f) this # ---------------------------------------------------------------------------------------------------------------- start: ()-> super this.initCountdown() this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> this.haltCountdown() super this # ---------------------------------------------------------------------------------------------------------------- haltCountdown: ()-> @countdownDeferral.clear() if @countdownDeferral?.enqueued() @countdownTicker?.exit() this # ---------------------------------------------------------------------------------------------------------------- initialize: (fnNotify, fnPause, fnCompleted, countdownSeconds, startingDelay)-> super fnNotify @countdownState = kCountdownStateUndefined @fnPause = fnPause @fnCompleted = fnCompleted @currentCountdownValue = null @countdownSeconds = countdownSeconds @startingDelay = startingDelay @pauseClicked = false @overlayClicked = false this.hideOverlayImmediate() this.enablePause() this.getCountdownPanel().initialize().animateCountdown(this.countdownAnimationOptions(@countdownSeconds), @countdownSeconds, null, true) true # ---------------------------------------------------------------------------------------------------------------- obs_networkChanged: (reason)-> Hy.Trace.debug("QuestionPage::obs_networkChanged (isPaused=#{this.isPaused()})") super if this.isPaused() this.updateConnectionInfo(reason) this # ---------------------------------------------------------------------------------------------------------------- createPauseButton: (options)-> defaultOptions = zIndex: 101 backgroundImage: "assets/icons/button-pause-question-page.png" _tag: "Pause" @pauseButton = new Hy.UI.ButtonProxy(Hy.UI.ViewProxy.mergeOptions(defaultOptions, options)) f = ()=> @fnPauseClick() null @pauseButton.addEventListener("click", f) @pauseButton # ---------------------------------------------------------------------------------------------------------------- createPauseButtonText: (options)-> defaultOptions = zIndex: 101 text: 'Pause' font: Hy.UI.Fonts.specTinyMrF color: Hy.UI.Colors.MrF.DarkBlue height: 'auto' textAlign: 'center' _tag: "Pause Text" @pauseButtonText = new Hy.UI.LabelProxy(Hy.UI.ViewProxy.mergeOptions(defaultOptions, options)) @pauseButtonText # ---------------------------------------------------------------------------------------------------------------- getCountdownPanel: ()-> @countdownPanel # ---------------------------------------------------------------------------------------------------------------- animateCountdown: (init, value)-> this.getCountdownPanel().animateCountdown(this.countdownAnimationOptions(value), value, @countdownSeconds, init) this # ---------------------------------------------------------------------------------------------------------------- countdownAnimationOptions: (value)-> _style: "normal" # ---------------------------------------------------------------------------------------------------------------- playCountdownSound: (value)-> if (event = this.countdownSound(value))? Hy.Media.SoundManager.get().playEvent(event) this # ---------------------------------------------------------------------------------------------------------------- initCountdown: ()-> @countdownState = kCountdownStateRunning @countdownDeferral = null if @countdownDeferral?.triggered() fnInitView = (value)=> @currentCountdownValue = value this.animateCountdown(true, value) fnUpdateView = (value)=> @currentCountdownValue = value this.animateCountdown(false, value) fnCompleted = (evt)=>this.countdownCompleted() fnSound = (value)=>this.playCountdownSound(value) @countdownTicker = new CountdownTicker(fnInitView, fnUpdateView, fnCompleted, fnSound) @countdownTicker.init(@countdownSeconds, @startingDelay) this # ---------------------------------------------------------------------------------------------------------------- getCountdownStartValue: ()-> @countdownSeconds # ---------------------------------------------------------------------------------------------------------------- getCountdownValue: ()-> # @countdownTicker?.getValue() # This isn't reliable, if console user answers @currentCountdownValue # ---------------------------------------------------------------------------------------------------------------- countdownSound: (value)-> null # ---------------------------------------------------------------------------------------------------------------- countdownCompleted: ()-> this.disablePause() @fnCompleted() # ---------------------------------------------------------------------------------------------------------------- click: (evt)-> this.pause() if @countdownState is kCountdownStateRunning # ---------------------------------------------------------------------------------------------------------------- disablePause: ()-> for view in [@pauseButton, @pauseButtonText] view?.animate({duration: 100, opacity: 0}) view?.hide() this # ---------------------------------------------------------------------------------------------------------------- enablePause: ()-> for view in [@pauseButton, @pauseButtonText] # view?.animate({duration: 100, opacity: 1}) view?.setUIProperty("opacity", 1) view?.show() this # ---------------------------------------------------------------------------------------------------------------- isPaused: ()-> @countdownState is kCountdownStatePaused # ---------------------------------------------------------------------------------------------------------------- createOverlay: ()-> container = this.overlayContainer() overlayBkgndOptions = top: 0 bottom: 0 left: 0 right: 0 backgroundImage: Hy.UI.Backgrounds.pixelOverlay zIndex: 200 opacity: 0 _tag: "Overlay Background" container.addChild(@overlayBkgnd = new Hy.UI.ViewProxy(overlayBkgndOptions)) overlayFrameOptions = top: 100 bottom: 100 left: 100 right: 100 borderColor: Hy.UI.Colors.white borderRadius: 16 borderWidth: 4 zIndex: 201 # _alignment: "center" opacity: 0 _tag: "Overlay Frame" container.addChild(@overlayFrame = new Hy.UI.ViewProxy(overlayFrameOptions)) elementOptions = width: 400 @overlayFrame.addChild(this.overlayBody(elementOptions)) this # ---------------------------------------------------------------------------------------------------------------- showOverlay: (options, fnDone = null)-> fn = ()=> if fnDone? Hy.Utils.Deferral.create(0, fnDone) null if not @overlayBkgnd? this.createOverlay() this.updateConnectionInfo() @panelSound?.syncCurrentChoiceWithAppOption() for view in [@overlayBkgnd, @overlayFrame] view.setUIProperty("opacity", 0) view.show() @overlayBkgnd.animate(options, ()=>) @overlayFrame.animate(options, fn) this # ---------------------------------------------------------------------------------------------------------------- hideOverlayImmediate: ()-> for view in [@overlayBkgnd, @overlayFrame] view?.hide() this # ---------------------------------------------------------------------------------------------------------------- hideOverlay: (options, fnDone = null)-> fn = ()=> for view in [@overlayBkgnd, @overlayFrame] view?.hide() if fnDone? Hy.Utils.Deferral.create(0, fnDone) null if @overlayBkgnd? @overlayFrame.animate(options, ()=>) @overlayBkgnd.animate(options, fn) else fn() this # ---------------------------------------------------------------------------------------------------------------- overlayContainer: ()-> @container # ---------------------------------------------------------------------------------------------------------------- overlayBody: (elementOptions)-> options = backgroundImage: Hy.UI.Backgrounds.pixelOverlay _tag: "Overlay Body" body = new Hy.UI.ViewProxy(options) body.addChild(this.createGamePausedText()) top = 170 #200 verticalPadding = 90 #elementOptions.height + 15 #25 textOffset = 125 horizontalPadding = 20 choiceOptions = _style: "plainOnDarkBackground" @panelSound = Hy.Panels.OptionPanels.createSoundPanel(this, Hy.UI.ViewProxy.mergeOptions(elementOptions, {top:top}), {font: Hy.UI.Fonts.specBigNormal, color: Hy.UI.Colors.white, _attach: "right"}, choiceOptions) body.addChild(@panelSound) continueGame = this.createOverlayButtonPanel(Hy.UI.ViewProxy.mergeOptions(elementOptions, {top: (top += verticalPadding)}), {backgroundImage: "assets/icons/button-play-small-blue.png", left: horizontalPadding}, {left: textOffset, text: "Continue Game"}, @fnClickContinueGame) body.addChild(continueGame) forceFinishGame = this.createOverlayButtonPanel(Hy.UI.ViewProxy.mergeOptions(elementOptions, {top: (top += verticalPadding)}), {backgroundImage: "assets/icons/button-cancel.png", left: horizontalPadding}, {left: textOffset, text: "Finish Game"}, @fnClickForceFinish) body.addChild(forceFinishGame) newGame = this.createOverlayButtonPanel(Hy.UI.ViewProxy.mergeOptions(elementOptions, {top: (top += verticalPadding)}), {backgroundImage: "assets/icons/button-restart.png", left: horizontalPadding}, {left: textOffset, text: "Restart Game"}, @fnClickNewGame) body.addChild(newGame) @connectionInfo = this.createConnectionInfo(Hy.UI.ViewProxy.mergeOptions(elementOptions, {top: (top += verticalPadding)})) this.updateConnectionInfo() body.addChild(@connectionInfo) body # ---------------------------------------------------------------------------------------------------------------- updateConnectionInfo: (reason = "Wifi")-> text = "" if reason is "Wifi" if Hy.Network.NetworkService.isOnlineWifi() if (encoding = Hy.Network.NetworkService.getAddressEncoding())? text = "Additional players? Visit #{Hy.Config.Rendezvous.URLDisplayName} and enter: #{encoding}" @connectionInfo?.setUIProperty("text", text) this # ---------------------------------------------------------------------------------------------------------------- createConnectionInfo: (commonOptions)-> options = width: 600 font: Hy.UI.Fonts.specSmallNormal color: Hy.UI.Colors.white _tag: "Connection Info" height: 'auto' textAlign: 'center' _tag: "Connection Info" new Hy.UI.LabelProxy(Hy.UI.ViewProxy.mergeOptions(commonOptions, options)) # ---------------------------------------------------------------------------------------------------------------- createGamePausedText: ()-> gamePausedOptions = text: 'Game Paused' font: Hy.UI.Fonts.specGiantMrF color: Hy.UI.Colors.white top: 50 height: 'auto' textAlign: 'center' _tag: "Game Paused" new Hy.UI.LabelProxy(gamePausedOptions) # ---------------------------------------------------------------------------------------------------------------- createOverlayButtonPanel: (containerOptions, buttonOptions, labelOptions, fnClick)-> options = height: 72 _tag: "Overlay Button Panel" container = new Hy.UI.ViewProxy(Hy.UI.ViewProxy.mergeOptions(options, containerOptions)) f = ()=> if not @overlayClicked @overlayClicked = true fnClick() null defaultButtonOptions = height: 72 width: 72 left: 0 _tag: "Overlay Button" button = new Hy.UI.ButtonProxy(Hy.UI.ViewProxy.mergeOptions(defaultButtonOptions, buttonOptions)) button.addEventListener 'click', f container.addChild(button) defaultLabelOptions = font: Hy.UI.Fonts.specBigNormal color: Hy.UI.Colors.white _tag: "Overlay Label" container.addChild(new Hy.UI.LabelProxy(Hy.UI.ViewProxy.mergeOptions(defaultLabelOptions, labelOptions))) container # ================================================================================================================== class QuestionPage extends CountdownPage kQuestionBlockHeight = 215 kQuestionBlockWidth = 944 kQuestionInfoHeight = kQuestionInfoWidth = 86 kQuestionBlockHorizontalMargin = (Hy.UI.iPad.screenWidth - kQuestionBlockWidth)/2 # kQuestionBlockVerticalMargin = 30 kQuestionBlockVerticalMargin = 25 kQuestionTextMargin = 10 kQuestionTextWidth = kQuestionBlockWidth - (kQuestionTextMargin + kQuestionInfoWidth) kQuestionTextHeight = kQuestionBlockHeight - (2*kQuestionTextMargin) kAnswerBlockWidth = 460 kAnswerBlockHeight = 206 kAnswerBlockHorizontalPadding = 24 kAnswerBlockVerticalPadding = 15 # kAnswerContainerVerticalMargin = 20 kAnswerContainerVerticalMargin = 7 kAnswerContainerHorizontalMargin = kQuestionBlockHorizontalMargin kAnswerContainerWidth = (2*kAnswerBlockWidth) + kAnswerBlockHorizontalPadding kAnswerContainerHeight = (2*kAnswerBlockHeight) + kAnswerBlockVerticalPadding kAnswerLabelWidth = 60 kAnswerTextMargin = 10 kAnswerTextHeight = kAnswerBlockHeight - (2*kAnswerTextMargin) kAnswerTextWidth = kAnswerBlockWidth - ((2*kAnswerTextMargin) + kAnswerLabelWidth) kCountdownClockHeight = kCountdownClockWidth = 86 kButtonOffset = 5 kPauseButtonHeight = kPauseButtonWidth = 86 kPauseButtonVerticalMargin = kQuestionBlockVerticalMargin + kQuestionBlockHeight - (kPauseButtonHeight - kButtonOffset) kPauseButtonHorizontalMargin = kQuestionBlockHorizontalMargin - 20 kQuestionInfoVerticalMargin = kQuestionBlockVerticalMargin - kButtonOffset kQuestionInfoHorizontalMargin = kQuestionBlockHorizontalMargin - 20 # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> @zIndexPassive = 110 @zIndexActive = 150 @top = 0 @sound = null super state, app @soundCounter ||= 0 @soundKeys = ["countDown_0", "countDown_1", "countDown_2", "countDown_3", "countDown_4"] @nSounds = @soundKeys.length @pageImage = null this.webViewPanelCreate() @container.addChild(this.createQuestionBlock()) @container.addChild(this.createAnswerBlocks()) this.createAnswerCritterPanel() @questionTestCount = 0 @answerTestCount = 0 # It's important that these all share the same view, due to the overlapping nature of the animations [@animateInLongScenes, @animateInLongSceneDuration] = this.buildAnimationFromScenes(this.initAnimateInLongScenes()) [@animateInShortScenes, @animateInShortSceneDuration] = this.buildAnimationFromScenes(this.initAnimateInShortScenes(), @animateInLongScenes) [@animateOutScenes, @animateOutSceneDuration] = this.buildAnimationFromScenes(this.initAnimateOutScenes(), @animateInShortScenes) this # ---------------------------------------------------------------------------------------------------------------- countdownPanelOptions: ()-> top : kQuestionBlockVerticalMargin + kQuestionBlockHeight + kAnswerContainerVerticalMargin + (kAnswerContainerHeight - kCountdownClockHeight)/2 left : kAnswerContainerHorizontalMargin + (kAnswerContainerWidth - kCountdownClockWidth)/2 height : kCountdownClockHeight width : kCountdownClockWidth zIndex : @zIndexActive + 2 # ---------------------------------------------------------------------------------------------------------------- pauseButtonOptions: ()-> zIndex : @zIndexActive + 2 height : kPauseButtonHeight width : kPauseButtonWidth top : kPauseButtonVerticalMargin right : kPauseButtonHorizontalMargin # ---------------------------------------------------------------------------------------------------------------- pauseButtonTextOptions: ()-> textHeight = 25 buttonOptions = this.pauseButtonOptions() options = top : buttonOptions.top - (textHeight + 5) right : buttonOptions.right width : buttonOptions.width height : textHeight zIndex : buttonOptions.zIndex options # ---------------------------------------------------------------------------------------------------------------- questionInfoPanelOptions: ()-> top : kQuestionInfoVerticalMargin right : kQuestionInfoHorizontalMargin # ---------------------------------------------------------------------------------------------------------------- start: ()-> super this.clearAnimation() @sound?.play() if not @showingAnswers @answerCritterPanel.start() this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> @sound.stop() if @sound?.isPlaying() if @showingAnswers @answerCritterPanel.stop() super this # ---------------------------------------------------------------------------------------------------------------- pause: ()-> @sound.pause() if @sound?.isPlaying() @answerCritterPanel.pause() super this # ---------------------------------------------------------------------------------------------------------------- resumed: ()-> super @sound.play() if @sound? and not @sound.isPlaying() @answerCritterPanel.resumed() this # ---------------------------------------------------------------------------------------------------------------- closeWindow: (options={})-> @webViewPanel?.close() super this # ---------------------------------------------------------------------------------------------------------------- openWindow: (options={})-> super options this # ---------------------------------------------------------------------------------------------------------------- continue_: ()-> super @sound.play() if @sound? and not @sound.isPlaying() this # ---------------------------------------------------------------------------------------------------------------- initializeForQuestion: (fnNotify, fnPause, fnCompleted, countdownSeconds, startingDelay, contestQuestion, iQuestion, nQuestions)-> @showingAnswers = false @consoleAnswered = false @showingAnswersClicked = false this.initialize fnNotify, fnPause, fnCompleted, countdownSeconds, startingDelay, contestQuestion, iQuestion, nQuestions @answerCritterPanel.initialize() # apparently, the window has to be open in order for the webview to work... @window.setUIProperty("opacity", 0) this.animateChildren({duration: 0, opacity: 0}) this.openWindow() @webViewPanel?.initialize(()=>this.webViewPanelContentInitialize()) false # ---------------------------------------------------------------------------------------------------------------- initializeForAnswers: (fnNotify, fnPause, fnCompleted, countdownSeconds, startingDelay)-> @showingAnswers = true this.initialize fnNotify, fnPause, fnCompleted, countdownSeconds, startingDelay, @contestQuestion, @iQuestion, @nQuestions this.revealAnswer() true # ---------------------------------------------------------------------------------------------------------------- initialize: (fnNotify, fnPause, fnCompleted, countdownSeconds, startingDelay, contestQuestion, iQuestion, nQuestions)-> super @contestQuestion = contestQuestion @iQuestion = iQuestion @nQuestions = nQuestions @sound?.reset() @questionInfoPanel.initialize @iQuestion+1, @nQuestions, this.labelColor() true # ---------------------------------------------------------------------------------------------------------------- initAnimateInLongScenes: ()-> [ {image: "splash", imageOptions: {zIndex: 200, top: 0, left: 0, right: 0, bottom: 0}, animationOptions: [{_incrementalDelay: 500, duration: 400, _startOpacity: 1.0, opacity: 0.0, _waitForWindowFn: ((fn)=>this.webViewPanelWait(fn))}]} ] # ---------------------------------------------------------------------------------------------------------------- initAnimateInShortScenes: ()-> [ {image: "black", imageOptions: {zIndex: 200, top: 0, left: 0, right: 0, bottom: 0}, animationOptions: [{_incrementalDelay: 0, duration: 400, _startOpacity: 1.0, opacity: 0.0, _waitForWindowFn: ((fn)=>this.webViewPanelWait(fn))}]} ] # ---------------------------------------------------------------------------------------------------------------- initAnimateOutScenes: ()-> [ {image: "black", imageOptions: {zIndex: 200, top: 0, left: 0, right: 0, bottom: 0, opacity: 0}, animationOptions: [{_incrementalDelay: 0, duration: 400, _startOpacity: 0, opacity: 1.0}]} ] # ---------------------------------------------------------------------------------------------------------------- # Animates all child views EXCEPT the web view, which we animate separately # animateChildren: (options)-> for child in @container.getChildren() if child isnt @webViewPanel if options.opacity? child.setUIProperty("opacity", options.opacity) # child.animate(options) this # ---------------------------------------------------------------------------------------------------------------- animateIn: (useCurtains = false)-> Hy.Trace.debug "QuestionPage::animateIn (ENTER)" @webViewPanel?.fireEvent({kind: "animateIn", data: {useCurtains: useCurtains}}, (event)=>this.animateInFinished()) this.animateWindow({opacity: 1, duration: 0, delay: 150}) # 2.6.0: 50->150 -1 # ---------------------------------------------------------------------------------------------------------------- animateInFinished: ()-> Hy.Trace.debug "QuestionPage::animateInFinished (ENTER)" this.animateChildren({opacity: 1, duration: 100}) Hy.Utils.Deferral.create(100, ()=>PageState.get().resumed()) # ---------------------------------------------------------------------------------------------------------------- animateOut: (useCurtains = false)-> this.animateChildren({opacity: 0, duration: 50}) Hy.Utils.Deferral.create(50, ()=>@webViewPanel?.fireEvent({kind: "animateOut", data: {useCurtains: useCurtains}}, (event)=>this.animateOutFinished())) return -1 this.animateScenes(@animateOutScenes) @animateOutSceneDuration # ---------------------------------------------------------------------------------------------------------------- animateOutFinished: ()-> @window.setUIProperty("opacity", 0) Hy.Utils.Deferral.create(0, ()=>PageState.get().resumed()) # ---------------------------------------------------------------------------------------------------------------- dump: ()-> Hy.Trace.debug "QuestionPage::dump (Question=#{@contestQuestion.getQuestionID()}/#{@contestQuestion.getQuestionText()})" for i in [0..3] Hy.Trace.debug "QuestionPage::dump (#{i} #{@contestQuestion.getAnswerText(i)})" this # ---------------------------------------------------------------------------------------------------------------- labelColor: ()-> if @showingAnswers then Hy.UI.Colors.paleYellow else Hy.UI.Colors.white # ---------------------------------------------------------------------------------------------------------------- animateCountdown: (init, value)-> super color = Hy.UI.Colors.white if not init if not @showingAnswers if value <= Hy.Config.Dynamics.panicAnswerTime color = Hy.UI.Colors.MrF.Red # @questionLabel.setUIProperty("color", color) #TODO this # ---------------------------------------------------------------------------------------------------------------- countdownAnimationOptions: (value)-> _style: if @showingAnswers then "normal" else "frantic" # ---------------------------------------------------------------------------------------------------------------- # Called from ConsoleApp animateCountdownQuestionCompleted: ()-> this.getCountdownPanel().animateCountdown({_style: "completed"}) this # ---------------------------------------------------------------------------------------------------------------- webViewPanelCreate: ()-> options = this.containerOptions() options._tag = "WebViewPanel" # options.borderWidth = 10 # options.borderColor = Hy.UI.Colors.green webViewOptions = top: options.top left: options.left width: options.width height: options.height _tag: "Question Page Web View" scalesPageToFit:false url: "html-question-page.html" zIndex: 50 #@zIndexPassive backgroundColor:'transparent' # http://developer.appcelerator.com/question/45491/can-i-change-the-white-background-that-shows-when-a-web-view-is-loading @container.addChild(@webViewPanel = new Hy.Panels.WebViewPanel(options, webViewOptions)) this # ---------------------------------------------------------------------------------------------------------------- webViewPanelWait: (fn)-> Hy.Trace.debug "QuestionPage::webViewPanelWait (PAGE WAIT: WebViewInitialized=#{@webViewPanel.isInitialized()})" @webViewPanelFinishAnimateInFn = fn if @webViewPanel.isInitialized() this.webViewPanelFinishAnimation() else null null # ---------------------------------------------------------------------------------------------------------------- webViewPanelFinishAnimation: ()-> Hy.Trace.debug "QuestionPage::webViewPanelFinishAnimation (FINISH ANIMATION: WebViewInitialized=#{@webViewPanel.isInitialized()})" if @webViewPanelFinishAnimateInFn? if @webViewPanel.isInitialized() Hy.Trace.debug "QuestionPage::webViewPanelFinishAnimation (FINISHING ANIMATION)" @webViewPanelFinishAnimateInFn() @webViewPanelFinishAnimateInFn = null Hy.Utils.Deferral.create(@animateInSceneDuration, ()=>PageState.get().resumed()) else Hy.Trace.debug "QuestionPage::webViewPanelFinishAnimation (NO ANIMATION TO FINISH)" this # ---------------------------------------------------------------------------------------------------------------- webViewPanelContentInitialize: ()-> data = {} data.question = {} data.question.text = this.formatText(@contestQuestion.getQuestionText()).text code = switch (format = @contestQuestion.getContentPack().getFormatting("question")) when "bold" "b" when "italic" "i" when "none" null else "i" if code? data.question.text = "<#{code}>#{data.question.text}</#{code}>" data.answers = [] for i in [0..3] data.answers[i] = {} data.answers[i].text = this.formatText(@contestQuestion.getAnswerText(i)).text @webViewPanel.fireEvent({kind: "initializePage", data: data}, (event)=>this.webViewPanelContentInitialized()) this # ---------------------------------------------------------------------------------------------------------------- webViewPanelContentInitialized: ()-> Hy.Utils.Deferral.create(0, ()=>PageState.get().resumed()) null # ---------------------------------------------------------------------------------------------------------------- webViewPanelShowConsoleSelection: (indexSelectedAnswer)-> @webViewPanel.fireEvent({kind: "showConsoleSelection", data: {indexSelectedAnswer: indexSelectedAnswer}}) # ---------------------------------------------------------------------------------------------------------------- webViewPanelRevealAnswer: (indexCorrectAnswer)-> @webViewPanel.fireEvent({kind: "revealAnswer", data: {indexCorrectAnswer: indexCorrectAnswer}}) # ---------------------------------------------------------------------------------------------------------------- createQuestionBlock: ()-> #Hack to prevent user "copy" actions, since all other approaches aren't working overlayViewOptions = top: (@top += kQuestionBlockVerticalMargin) width: kQuestionBlockWidth height: kQuestionBlockHeight left: kQuestionBlockHorizontalMargin zIndex: @zIndexPassive + 1 _tag: "Question Block Blocker" @top += overlayViewOptions.height new Hy.UI.ViewProxy(overlayViewOptions) # ---------------------------------------------------------------------------------------------------------------- formatText: (text)-> output = "" chunks = text.split("|") for i in [1..chunks.length] if i > 1 # output += "\n" output += " " output += chunks[i-1] numLines = chunks.length if chunks[chunks.length-1].length is 0 numLines-- {numLines: numLines, text: output} # ---------------------------------------------------------------------------------------------------------------- createAnswerBlocks: ()-> answerItems = [ {index: 0, label: "A", height: kAnswerBlockHeight, width: kAnswerBlockWidth, left: 0, top: 0} {index: 1, label: "B", height: kAnswerBlockHeight, width: kAnswerBlockWidth, left: kAnswerBlockWidth + kAnswerBlockHorizontalPadding, top: 0} {index: 2, label: "C", height: kAnswerBlockHeight, width: kAnswerBlockWidth, left: 0, top: kAnswerBlockHeight + kAnswerBlockVerticalPadding} {index: 3, label: "D", height: kAnswerBlockHeight, width: kAnswerBlockWidth, left: kAnswerBlockWidth + kAnswerBlockHorizontalPadding, top: kAnswerBlockHeight + kAnswerBlockVerticalPadding} ] answerContainerOptions = top: (@top += kAnswerContainerVerticalMargin) left: kAnswerContainerHorizontalMargin height: kAnswerContainerHeight width: kAnswerContainerWidth _tag: "Answer Container" zIndex: @zIndexActive + 1 @answersContainer = new Hy.UI.ViewProxy(answerContainerOptions) @answerBlocks = [] this.createAnswerBlock(answerItem) for answerItem in answerItems @answersContainer # ---------------------------------------------------------------------------------------------------------------- answerBlockOptions: (answerItem)-> height : answerItem.height, width : answerItem.width, top : answerItem.top, left : answerItem.left, _tag : "Answer Container #{answerItem.label}" # ---------------------------------------------------------------------------------------------------------------- createAnswerBlock: (answerItem)-> # For direct play fnClick = (evt)=> this.answerBlockClicked(evt) answerBlockView = new Hy.UI.ViewProxy(this.answerBlockOptions(answerItem)) answerBlockView.addEventListener("click", fnClick) @answerBlocks.push {answerBlockView: answerBlockView, index: answerItem.index, label: answerItem.label} @answersContainer.addChild(answerBlockView) this # ---------------------------------------------------------------------------------------------------------------- answerBlockClicked: (evt)-> answerBlock = _.detect(@answerBlocks, (b)=>b.answerBlockView.getView() is evt.source) Hy.Trace.debug "QuestionPage::answerBlockClicked (label=#{if answerBlock? then answerBlock.label else "?"} allowEvents=#{this.getAllowEvents()} showingAnswers=#{@showingAnswers} consoleAnswered=#{@consoleAnswered} showingAnswersClicked=#{@showingAnswersClicked} PageState.state=#{PageState.get().getState()})" fn = null if this.getAllowEvents() if answerBlock? if @showingAnswers if not @showingAnswersClicked @showingAnswersClicked = true fn = ()=> Hy.Trace.debug "QuestionPage::answerBlockClicked (done showing answers)" this.getApp().questionAnswerCompleted() null else if not @consoleAnswered @consoleAnswered = true this.webViewPanelShowConsoleSelection(answerBlock.index) fn = ()=> Hy.Trace.debug "QuestionPage::answerBlockClicked (console answered)" this.getApp().consolePlayerAnswered(answerBlock.index) null if fn? this.haltCountdown() Hy.Utils.Deferral.create(0, ()=>fn()) null # ---------------------------------------------------------------------------------------------------------------- createAnswerCritterPanel: ()-> options = zIndex: @zIndexActive left: 0 bottom: 0 @container.addChild(@answerCritterPanel = new Hy.Panels.AnswerCritterPanel(options)) this # ---------------------------------------------------------------------------------------------------------------- countdownSound: (value)-> sound = null if not @showingAnswers and value isnt 0 sound = @soundKeys[@soundCounter++ % @nSounds] sound # ---------------------------------------------------------------------------------------------------------------- playerAnswered: (response)-> @answerCritterPanel.playerAnswered(response) # ---------------------------------------------------------------------------------------------------------------- revealAnswer: ()-> this.webViewPanelRevealAnswer(@contestQuestion.indexCorrectAnswer) # We want to display highest scorers first correct = [] incorrect = [] for response in Hy.Contest.ContestResponse.selectByQuestionID(@contestQuestion.getQuestionID()) if response.getCorrect() correct.push response else incorrect.push response sortedCorrect = correct.sort((r1, r2)=> r2.getScore() - r1.getScore()) topScore = null fnResponse = (response)=> # We want to display first place scorers differently t = if topScore? response.getScore() is topScore else topScore = response.getScore() true @answerCritterPanel.playerAnswered(response, true, t) for response in sortedCorrect fnResponse(response) for response in incorrect fnResponse(response) this # ================================================================================================================== class ContestCompletedPage extends NotifierPage # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app @top = 65 @defaultZIndex = 40 this.addBackground(@top) @top += 25 this.addGameOverText() this.addPlayAgainButtonAndText() # this.addAnimation() this # ---------------------------------------------------------------------------------------------------------------- addBackground: (top)-> @backgroundOptions = top: top height: 635 width: 800 image: "assets/icons/scoreboard-background.png" zIndex: @defaultZIndex-1 _tag: "Scoreboard Background" @container.addChild(new Hy.UI.ImageViewProxy(@backgroundOptions)) # ---------------------------------------------------------------------------------------------------------------- addGameOverText: ()-> height = 74 options = image: "assets/icons/label-Game-Over.png" top: @top height: 74 width: 374 zIndex: @defaultZIndex _tag: "Game Over Text" @top += height @container.addChild(@gameOverText = new Hy.UI.ImageViewProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- addPlayAgainButtonAndText: ()-> height = 72 buttonOptions = top: (@top += 20) height: height width: height backgroundImage: "assets/icons/button-play-small-blue.png" zIndex: @defaultZIndex _tag: "Play Again" @container.addChild(@playAgainButton = new Hy.UI.ButtonProxy(buttonOptions)) textOptions = top: @top height: height # width: 120 # borderColor: Hy.UI.Colors.white zIndex: @defaultZIndex padding = 20 this.addButtonText(Hy.UI.ViewProxy.mergeOptions(textOptions, {text: "play", textAlign: "right", right: (Hy.UI.iPad.screenWidth/2) + (height/2) + padding})) this.addButtonText(Hy.UI.ViewProxy.mergeOptions(textOptions, {text: "again", textAlign: "left", left: (Hy.UI.iPad.screenWidth/2) + (height/2) + padding})) @playAgainButtonClicked = false @fnClickPlayAgain = (evt)=> if not @playAgainButtonClicked @playAgainButtonClicked = true this.playAgainClicked() null @playAgainButton.addEventListener("click", @fnClickPlayAgain) @top += height this # ---------------------------------------------------------------------------------------------------------------- addButtonText: (options)-> defaultOptions = font: Hy.UI.Fonts.specBigMrF color: Hy.UI.Colors.white zIndex: @defaultZIndex + 1 _tag: "Button Text" @container.addChild(new Hy.UI.LabelProxy(Hy.UI.ViewProxy.mergeOptions(defaultOptions, options))) this # ---------------------------------------------------------------------------------------------------------------- createScoreboardCritterPanel: ()-> padding = 10 width = @backgroundOptions.width height = @backgroundOptions.height - ((@top - @backgroundOptions.top) + (2*padding)) scoreboardOptions = top: @top height: height width: width left: (Hy.UI.iPad.screenWidth - width)/2 zIndex: @defaultZIndex+2 _orientation: "horizontal" # borderWidth: 1 # borderColor: Hy.UI.Colors.red @container.addChild(@scoreboardCritterPanel = new Hy.Panels.ScoreboardCritterPanel(scoreboardOptions)) @scoreboardCritterPanel # ---------------------------------------------------------------------------------------------------------------- initialize: (fnNotify)-> super @playAgainButtonClicked = false # @nQuestions = nQuestions # @questionInfoPanel?.initialize @nQuestions, @nQuestions, this.labelColor() this.createScoreboardCritterPanel().initialize().displayScores() true # ---------------------------------------------------------------------------------------------------------------- start: ()-> super this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> if @scoreboardCritterPanel? this.container.removeChild(@scoreboardCritterPanel) @scoreboardCritterPanel.stop() @scoreboardCritterPanel = null super this # ---------------------------------------------------------------------------------------------------------------- playAgainClicked: ()-> Hy.Utils.Deferral.create(0, ()=>this.getApp().contestRestart(true)) # ---------------------------------------------------------------------------------------------------------------- getLeaderboard: ()-> @scoreboardCritterPanel?.getLeaderboard() # ---------------------------------------------------------------------------------------------------------------- addAnimation: ()-> # @animateInScenes = null @animateOutScenes = null animationContainerOptions = top: 0 left: 0 right: 0 bottom: 0 zIndex: 50 # [@animateInScenes, sceneTotalDuration] = this.buildAnimationFromScenes(this.initAnimateInScenes()) # [@animateOutScenes, @animateOutSceneDuration] = this.buildAnimationFromScenes(this.initAnimateOutScenes(), @animateoutScenes) this # ---------------------------------------------------------------------------------------------------------------- animateOut: ()-> [@animateOutScenes, @animateOutSceneDuration] = this.buildAnimationFromScenes(this.initAnimateOutScenes(), @animateoutScenes) this.animateScenes(@animateOutScenes) @animateOutSceneDuration # ---------------------------------------------------------------------------------------------------------------- initAnimateOutScenes: ()-> [ {image: "intro-TV", imageOptions: {zIndex: 50}, animationOptions: [{_incrementalDelay: 0, duration: 0, opacity: 1.0}]} # {image: "black", imageOptions: {zIndex: 49, top: 0, left: 0, right: 0, bottom: 0, opacity: 0}, animationOptions: [{_incrementalDelay: 0, duration: 1500, opacity: 1.0}, {_incrementalDelay: 500, duration: 0, opacity: 0}]} {image: "intro-left-front-curtain", imageOptions: {zIndex: 45, top: 0, width:514, height:768, right: Hy.UI.iPad.screenWidth, borderColor: Hy.UI.Colors.white}, animationOptions: [{_incrementalDelay: 0, duration: 1500, right: Hy.UI.iPad.screenWidth/2}, {_incrementalDelay: 0, duration: 100, right: Hy.UI.iPad.screenWidth}]} {image: "intro-right-front-curtain", imageOptions: {zIndex: 45, top: 0, width:514, height:768, left: Hy.UI.iPad.screenWidth, borderColor: Hy.UI.Colors.white}, animationOptions: [{_incrementalDelay: 0, duration: 1500, left: (Hy.UI.iPad.screenWidth/2)-5}, {_incrementalDelay: 0, duration: 100, left: Hy.UI.iPad.screenWidth}]} ] # ================================================================================================================== class PageState gOperationIndex = 0 @Any = -1 @Unknown = 0 @Splash = 1 @Intro = 2 @Start = 3 @Question = 4 @Answer = 5 @Scoreboard = 6 @Completed = 7 @About = 8 @UCCInfo = 9 @JoinCodeInfo = 10 stateToPageClassMap = [ {state: PageState.Splash, pageClass: SplashPage, background: Hy.UI.Backgrounds.splashPage}, {state: PageState.Intro, pageClass: IntroPage, background: null}, {state: PageState.Start, pageClass: StartPage, background: Hy.UI.Backgrounds.startPage} {state: PageState.Question, pageClass: QuestionPage, background: Hy.UI.Backgrounds.stageNoCurtain} {state: PageState.Answer, pageClass: QuestionPage, background: Hy.UI.Backgrounds.stageNoCurtain} {state: PageState.Completed, pageClass: ContestCompletedPage, background: Hy.UI.Backgrounds.stageCurtain} {state: PageState.About, pageClass: AboutPage, background: Hy.UI.Backgrounds.startPage} {state: PageState.UCCInfo, pageClass: UserCreatedContentInfoPage, background: Hy.UI.Backgrounds.startPage} {state: PageState.JoinCodeInfo, pageClass: JoinCodeInfoPage, background: Hy.UI.Backgrounds.startPage} ] @defaultAnimateOut = {duration: 250, _startOpacity: 1, opacity: 0} @defaultAnimateIn = {duration: 250, _startOpacity: 0, opacity: 1} transitionMaps = [ { oldState: [PageState.Any], newState: [PageState.Splash], animateOutBackground: Hy.UI.Backgrounds.splashPage, interstitialBackground: Hy.UI.Backgrounds.splashPage, animateInBackground: Hy.UI.Backgrounds.splashPage }, { oldState: [PageState.Splash], newState: [PageState.Intro], animateOutBackground: Hy.UI.Backgrounds.splashPage, interstitialBackground: Hy.UI.Backgrounds.splashPage, animateInBackground: Hy.UI.Backgrounds.splashPage, animateInFn: ((page)=>page.animateIn()), }, { oldState: [PageState.Intro], newState: [PageState.Start], animateOutFn: ((page)=>page.animateOut()), animateOutBackground: Hy.UI.Backgrounds.splashPage, interstitialBackground: Hy.UI.Backgrounds.splashPage, animateInBackground: Hy.UI.Backgrounds.splashPage, animateIn: {duration: 500, _startOpacity: 0, opacity: 1} }, { # 2.5.0: To handle case where we're backgrounded. See ConsoleApp::resumedPage for details oldState: [PageState.Any], newState: [PageState.Start], interstitialBackground: Hy.UI.Backgrounds.splashPage, animateInBackground: Hy.UI.Backgrounds.splashPage, animateIn: {duration: 500, _startOpacity: 0, opacity: 1} }, { oldState: [PageState.Start], newState: [PageState.Question], animateOut: {duration: 500, opacity: 0}, animateInFn: ((page)=>page.animateIn(true)) }, { oldState: [PageState.Question], newState: [PageState.Answer], animateOut: null, delay: 500, animateIn: null }, { oldState: [PageState.Answer], newState: [PageState.Question], animateOutFn: ((page)=>page.animateOut(false)), animateInFn: ((page)=>page.animateIn(false)), }, { oldState: [PageState.Question, PageState.Answer], newState: [PageState.Completed], animateOutFn: ((page)=>page.animateOut(true)), animateIn: {duration: 500, _startOpacity: 0, opacity: 1} }, { oldState: [PageState.Question, PageState.Answer], newState: [PageState.Start], animateOutFn: ((page)=>page.animateOut(true)), animateIn: @defaultAnimateIn, }, { oldState: [PageState.Completed], newState: [PageState.Start], animateOut: @defaultAnimateOut, animateIn: @defaultAnimateIn, }, { oldState: [PageState.About, PageState.Start], newState: [PageState.Start, PageState.About], animateOut: @defaultAnimateOut, animateIn: @defaultAnimateIn, }, { oldState: [PageState.UCCInfo, PageState.Start], newState: [PageState.Start, PageState.UCCInfo], animateOut: @defaultAnimateOut, animateIn: @defaultAnimateIn, }, { oldState: [PageState.JoinCodeInfo, PageState.Start], newState: [PageState.Start, PageState.JoinCodeInfo], animateOut: @defaultAnimateOut, animateIn: @defaultAnimateIn, } ] gInstance = null # ---------------------------------------------------------------------------------------------------------------- @findTransitionMap: (oldPage, newPageState)-> for map in transitionMaps if (oldPage? and oldPage.state in map.oldState) or (PageState.Any in map.oldState) # 2.5.0 if (newPageState in map.newState) or (PageState.Any in map.newState) # 2.5.0 return map return null # ---------------------------------------------------------------------------------------------------------------- @getPageMap: (pageState)-> for map in stateToPageClassMap if map.state is pageState return map return null # ---------------------------------------------------------------------------------------------------------------- @getPageName: (pageState)-> name = null map = this.getPageMap(pageState) if map? name = map.pageClass.name return name # ---------------------------------------------------------------------------------------------------------------- @findPage: (pageState)-> page = if (map = this.getPageMap(pageState))? Page.findPage(map.pageClass) else null page # ---------------------------------------------------------------------------------------------------------------- @getPage: (pageState)-> page = if (map = this.getPageMap(pageState))? Page.getPage(map) else null page # ---------------------------------------------------------------------------------------------------------------- @get: ()-> gInstance # ---------------------------------------------------------------------------------------------------------------- @doneWithPage: (pageState)-> if (map = this.getPageMap(pageState))? Page.doneWithPage(map) null # ---------------------------------------------------------------------------------------------------------------- @init: (app)-> if not gInstance? gInstance = new PageState(app) gInstance # ---------------------------------------------------------------------------------------------------------------- display: ()-> s = "PageState::display" s += "(" if (state = this.getState())? s += "#{state.oldPageState}->#{state.newPageState}" s += ")" s # ---------------------------------------------------------------------------------------------------------------- constructor: (@app)-> this.initialize() this # ---------------------------------------------------------------------------------------------------------------- initialize: ()-> @state = null timedOperation = new Hy.Utils.TimedOperation("PAGE INITIALIZATION") for map in transitionMaps for v in ["videoOut", "videoIn"] if (videoOptions = map[v])? timedOperation.mark("video: #{videoOptions._url}") map["_#{v}Instance"] = player = Hy.Media.VideoPlayer.create(videoOptions) # player.prepareToPlay().play() timedOperation.mark("DONE") this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> if (page = this.getApp().getpage())? page?.closeWindow() page?.stop() this.getApp().setPage(null) this # ---------------------------------------------------------------------------------------------------------------- getApp: ()-> @app # ---------------------------------------------------------------------------------------------------------------- getState: ()-> @state # ---------------------------------------------------------------------------------------------------------------- setState: (state)-> @state = state # ---------------------------------------------------------------------------------------------------------------- isTransitioning: ()-> if (state = this.getState(false))? state.newPageState else null # ---------------------------------------------------------------------------------------------------------------- getOldPageState: ()-> this.getState()?.oldPageState # ---------------------------------------------------------------------------------------------------------------- stopTransitioning: ()-> this.setState(null) # ---------------------------------------------------------------------------------------------------------------- addPostTransitionAction: (fnPostTransition)-> if (state = this.getState())? @postFunctions.push(fnPostTransition) this # ---------------------------------------------------------------------------------------------------------------- hasPostFunctions: ()-> _.size(@postFunctions) > 0 # ---------------------------------------------------------------------------------------------------------------- # I've re-written this function about 5 times so far. "This time for sure". # I've re-written this function about 6 times so far. "This time for sure". # showPage: (newPageState, fn_newPageInit, postFunctions = [])-> initialState = oldPage: this.getApp().getPage() # newPage: Hy.Pages.PageState.getPage(newPageState) newPage_: null # defer creating the new page oldPageState: (if (oldPage = this.getApp().getPage())? then oldPage.getState() else null) newPageState: newPageState fn_newPageInit: fn_newPageInit if (existingState = this.getState())? s = "OLD STATE: oldPageState=#{if existingState.oldPage? then existingState.oldPage.getState() else "(NONE)"} newPageState=#{existingState.newPageState}" s += " NEW STATE: oldPageState=#{if initialState.oldPage? then initialState.oldPage.getState() else "(NONE)"} newPageState=#{initialState.newPageState}" Hy.Trace.debug "PageState::showPage (RECURSION #{s})", true new Hy.Utils.ErrorMessage("fatal", "PageState::showPage", s) return @postFunctions = [].concat(postFunctions) this.setState(this.showPage_setup(initialState)) this.showPage_execute() this # ---------------------------------------------------------------------------------------------------------------- showPage_setup: (state)-> state.spec = Hy.Pages.PageState.findTransitionMap(state.oldPage, state.newPageState) state.delay = if state.spec? then (if state.spec.delay? then state.spec.delay else 0) else 0 state.exitVideo = if state.spec? then state.spec._videoOutInstance else null state.introVideo = if state.spec? then state.spec._videoInInstance else null state.animateOut = if state.spec? then state.spec.animateOut else Hy.Pages.PageState.defaultAnimateOut state.animateOutFn = if state.spec? then state.spec.animateOutFn state.animateInFn = if state.spec? then state.spec.animateInFn state.animateIn = if state.spec? then state.spec.animateIn else Hy.Pages.PageState.defaultAnimateIn state.previousVideo = null state.networkServiceLevel = null state.operationIndex = ++gOperationIndex # For logging state.fnIndex = 0 # state.fnCompleted = false fnDebug = (fnName, s="")=> p = "" if (state = this.getState())? p += "##{state.operationIndex} fn:#{state.fnIndex} " p += if (oldPageState = this.getState().oldPageState)? then oldPageState else "NONE" p += ">#{this.getState().newPageState}" else p = "(NO STATE!)" Hy.Trace.debug("PageState::showPage (#{p} #{fnName} #{if s? then s else ""})") null fnExecuteNext = (restart = false)=> ok = false if (state = this.getState())? if restart and not state.fnCompleted # Try the last operation again null else ++state.fnIndex if state.fnIndex <= state.fnChain.length state.fnCompleted = false ok = true state.fnChain[state.fnIndex-1]() state.fnCompleted = true ok fnExecutePostFunction = ()=> if (f = @postFunctions.shift())? f(this.getApp().getPage()) null fnExecuteRemaining = ()=> if (state = this.getState())? while fnExecuteNext() null this.showPage_exit(state.operationIndex) while _.size(@postFunctions) > 0 fnExecutePostFunction() null fnIndicateActive = ()=> Hy.Network.NetworkService.setIsActive() fnExecuteNext() null fnSuspendNetwork = ()=> fnDebug("fnSuspendNetwork") if (ns = Hy.Network.NetworkService.get())? l = this.getState().networkServiceLevel = ns.getServiceLevel() fnDebug("fnSuspendNetwork (from \"#{l}\")") ns.setSuspended() fnExecuteNext() null fnResumeNetwork = ()=> fnDebug("fnResumeNetwork") if (serviceLevel = this.getState().networkServiceLevel)? Hy.Network.NetworkService.get().setServiceLevel(serviceLevel) fnExecuteNext() null # Returns existing instance of this kind of page, if it exists. fnCheckNewPage = ()=> Hy.Pages.PageState.findPage(state.newPageState) fnGetNewPage = ()=> this.getState().newPage_ fnCreateNewPage = ()=> s = this.getState() if not s.newPage_? s.newPage_ = Hy.Pages.PageState.getPage(state.newPageState) s.newPage_ fnSetBackground = (backgroundName = null)=> fnDebug("fnSetBackground", backgroundName) bkgnd = if backgroundName? then this.getState().spec?[backgroundName] else null this.getApp().setBackground(bkgnd) fnExecuteNext() fnCleanupVideo = (video)=> fnDebug("fnCleanupVideo") video.setUIProperty("borderColor", Hy.UI.Colors.green) fnExecuteNext() null fnPlayVideo = (video, preBackground, postBackground)=> fnDebug("fnPlayVideo") if this.getState().previousVideo? this.getState().previousVideo.release() video.setVideoProperty("backgroundImage", preBackground) f = ()=>fnCleanupVideo(video) video.prepareToPlay(f) this.getApp().getBackgroundWindow().add(video.getView()) this.getApp().setBackground(postBackground) video.setUIProperty("borderColor", Hy.UI.Colors.white) video.play() video.setUIProperty("borderColor", Hy.UI.Colors.red) this.getState().previousVideo = video null fnStopOldPage = ()=> fnDebug("fnStopOldPage") this.getState().oldPage?.stop() fnExecuteNext() null fnAnimateOut = ()=> fnDebug("fnAnimateOut") duration = 0 if (oldPage = this.getState().oldPage)? animateOut = this.getState().animateOut animateOutFn = this.getState().animateOutFn if animateOut? if animateOut._startOpacity? oldPage.window.setUIProperty("opacity", animateOut._startOpacity) oldPage.animateWindow(animateOut) duration = animateOut.duration else if animateOutFn? duration = animateOutFn(oldPage) if duration is -1 # -1 means we'll get called back to resume page transition fnDebug("fnAnimateOut", "WAITING") else Hy.Utils.Deferral.create(duration, fnExecuteNext) null fnCloseOldPage = ()=> fnDebug("fnCloseOldPage") if (oldPage = this.getState().oldPage)? newPage = fnCheckNewPage() # Might be null if page hasn't been created/used before #this.getState().newPage if oldPage isnt newPage oldPage.closeWindow() this.getApp().setPage(null) fnExecuteNext() null fnPlayExitVideo = ()=> fnDebug("fnPlayExitVideo") if this.getState().exitVideo? fnPlayVideo(this.getState().exitVideo, this.getState().spec.animateOutBackground, this.getState().spec.interstitialBackground) else fnExecuteNext() null fnPlayIntroVideo = ()=> fnDebug("fnPlayIntroVideo") if this.getState().introVideo? fnPlayVideo(this.getState().introVideo, this.getState().spec.interstitialBackground, this.getState().spec.animateInBackground) else fnExecuteNext() null fnInitNewPage = ()=> fnDebug("fnInitNewPage") newPage = fnCreateNewPage() #this.getState().newPage this.getApp().setPage(newPage) newPage.setState(this.getState().newPageState) if (result = this.getState().fn_newPageInit(newPage)) fnExecuteNext() else fnDebug("fnInitNewPage: waiting") fnAnimateInAndOpenNewPage = ()=> fnDebug("fnAnimateInAndOpenNewPage") duration = 0 newPage = fnGetNewPage() #this.getState().newPage animateIn = this.getState().animateIn animateInFn = this.getState().animateInFn if animateIn? duration = animateIn.duration if animateIn._startOpacity? newPage.window.setUIProperty("opacity", animateIn._startOpacity) if newPage is this.getState().oldPage newPage.animateWindow(animateIn) else newPage.openWindow(animateIn) else if animateInFn? # if newPage isnt this.getState().oldPage # newPage.openWindow() duration = animateInFn(newPage) else if newPage isnt this.getState().oldPage newPage.openWindow({opacity:1, duration:0}) else newPage.animateWindow({opacity:1, duration:0}) if duration is -1 # -1 means we'll get called back to resume page transition fnDebug("fnAnimateInAndOpenNewPage", "Waiting for callback") else fnDebug("fnAnimateInAndOpenNewPage", "Waiting #{duration}") Hy.Utils.Deferral.create(duration, fnExecuteNext) null fnStartNewPage = ()=> fnDebug("fnStartNewPage") fnGetNewPage().start() fnExecuteNext() null # We do it this way since it makes it easier to change the order and timing of things, # and ensure the integrity of the transition across pause/resumed state.fnChain = # 2.5.0: removed default fnChain... [ fnSuspendNetwork, fnStopOldPage, fnAnimateOut, ()=>fnSetBackground("animateOutBackground"), fnCloseOldPage, fnPlayExitVideo, ()=>fnSetBackground("interstitialBackground"), ()=>Hy.Utils.Deferral.create(this.getState().delay, fnExecuteNext), fnPlayIntroVideo, ()=>fnSetBackground("animateInBackground"), fnInitNewPage, fnAnimateInAndOpenNewPage, ()=>fnSetBackground(), # ()=>Hy.Utils.Deferral.create(0, fnStartNewPage), # 2.5.0 fnStartNewPage, fnResumeNetwork, fnIndicateActive, fnExecuteRemaining ] state.fnExecuteNext = fnExecuteNext state # ---------------------------------------------------------------------------------------------------------------- showPage_execute: (restart = false)-> @state?.fnExecuteNext(restart) this # ---------------------------------------------------------------------------------------------------------------- showPage_exit: (operationIndex)-> Hy.Trace.debug "PageState::showPage_exit (##{operationIndex})" this.setState(null) # ---------------------------------------------------------------------------------------------------------------- resumed: (restart = false)-> Hy.Trace.debug "PageState::resumed" if this.getState()? this.showPage_execute(restart) else if (page = this.getApp().getPage())? page.resumed() else Hy.Trace.debug "PageState::showPage (RESUMED BUT NO WHERE TO GO)" null # ================================================================================================================== Hyperbotic.Pages = Page: Page NotifierPage: NotifierPage IntroPage: IntroPage SplashPage: SplashPage AboutPage: AboutPage UserCreatedContentInfoPage: UserCreatedContentInfoPage StartPage: StartPage QuestionPage: QuestionPage ContestCompletedPage: ContestCompletedPage PageState: PageState CountdownPage: CountdownPage
96213
# ================================================================================================================== class CountdownTicker # ---------------------------------------------------------------------------------------------------------------- constructor: (@fnInitView, @fnUpdateView, @fnCompleted, @fnSound)-> this # ---------------------------------------------------------------------------------------------------------------- init: (@value, startingDelay)-> @startValue = @value this.clearTimers() this.display true fnTick = ()=> this.tick() f = ()=> this.display false @countdownInterval = setInterval fnTick, 1000 @startingDelay = null if startingDelay > 0 @startingDelay = Hy.Utils.Deferral.create startingDelay, f else f() this # ---------------------------------------------------------------------------------------------------------------- getValue: ()-> @value # ---------------------------------------------------------------------------------------------------------------- clearTimers: ()-> if @countdownInterval? clearInterval(@countdownInterval) @countdownInterval = null if @startingDelay? @startingDelay.clear() @startingDelay = null this # ---------------------------------------------------------------------------------------------------------------- display: (init)-> if init @fnInitView @value else @fnSound @value @fnUpdateView @value this # ---------------------------------------------------------------------------------------------------------------- exit: ()-> this.pause() @value = null null # ---------------------------------------------------------------------------------------------------------------- pause: ()-> this.clearTimers() this # ---------------------------------------------------------------------------------------------------------------- continue_: ()-> this.init(@value||@startValue, 0) # ---------------------------------------------------------------------------------------------------------------- reset: ()-> @value = @startValue || 10 # TODO: should get default value from app # ---------------------------------------------------------------------------------------------------------------- tick: ()-> @value -= 1 if @value >= 0 this.display false if @value <= 0 this.exit() @fnCompleted(source:this) this # ================================================================================================================== # # # zIndex scheme: # windows: 1-10 # page-owned stuff: 50-100 # overlays, buttons, other clickbale stuff: 101+ # # Lifecycle of a Page: # created # initialize # open # start # ... # close # stop # # also: # pause # resumed # class Page gInstanceCount = 0 gPages = [] # ---------------------------------------------------------------------------------------------------------------- @findPage: (pageClass)-> for page in gPages if page.constructor.name is pageClass.name return page null # ---------------------------------------------------------------------------------------------------------------- @getPage: (pageMap)-> p = (Page.findPage(pageMap.pageClass)) || new pageMap.pageClass(pageMap.state, Hy.ConsoleApp.get()) p # ---------------------------------------------------------------------------------------------------------------- # NOT IMPLEMENTED @doneWithPage: (pageMap)-> if (p = Page.findPage(pageMap.pageClass)) gPages = gPages.reject(p) p.doneWithPage() null # ---------------------------------------------------------------------------------------------------------------- constructor: (@state, @app)-> @instance = ++gInstanceCount gPages.push this options = fullscreen: true zIndex: 2 orientationModes: [Ti.UI.LANDSCAPE_LEFT, Ti.UI.LANDSCAPE_RIGHT] opacity: 0 _tag: "Main Window" @window = new Hy.UI.WindowProxy(options) @window.addChild(@container = new Hy.UI.ViewProxy(this.containerOptions())) @container.addChild(this.createAnimationContainer()) # @window.setTrace("opacity") this # ---------------------------------------------------------------------------------------------------------------- initialize: ()-> # We do this here since a page's state can change (since pages can be reused, such as Question) @container.setUIProperty("backgroundImage", if (background = PageState.getPageMap(this.getState()).background)? then background else null) @allowEvents = false true # ---------------------------------------------------------------------------------------------------------------- getAllowEvents: ()-> @allowEvents # ---------------------------------------------------------------------------------------------------------------- getState: ()-> @state # ---------------------------------------------------------------------------------------------------------------- setState: (state)-> @state = state # ---------------------------------------------------------------------------------------------------------------- getWindow: ()->@window # ---------------------------------------------------------------------------------------------------------------- getApp: ()-> @app # ---------------------------------------------------------------------------------------------------------------- obs_networkChanged: (reason)-> this # ---------------------------------------------------------------------------------------------------------------- openWindow: (options={})-> @window.open(options) this # ---------------------------------------------------------------------------------------------------------------- closeWindow: (options={})-> @window.close() this # ---------------------------------------------------------------------------------------------------------------- animateWindow: (options)-> # 2.5.0 @window.animate(options) this # ---------------------------------------------------------------------------------------------------------------- start: ()-> @allowEvents = true this.setStopAnimating(false) this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> @allowEvents = false this.setStopAnimating(true) this # ---------------------------------------------------------------------------------------------------------------- pause: ()-> this # ---------------------------------------------------------------------------------------------------------------- resumed: ()-> this # ---------------------------------------------------------------------------------------------------------------- containerOptions: ()-> top: 0 left: 0 width: Hy.UI.iPad.screenWidth # must set these, else _layout{vertical, horizontal} directives wont work height: Hy.UI.iPad.screenHeight zIndex: 101 _tag: "Main Container" # ---------------------------------------------------------------------------------------------------------------- createAnimationContainer: ()-> animationContainerOptions = top: 0 left: 0 right: 0 bottom: 0 zIndex: 200 opacity: 1 _tag: "Animation Container" @animationContainer = new Hy.UI.ViewProxy(animationContainerOptions) @animationContainer.hide() @animationContainerHidden = true @animationContainer # ---------------------------------------------------------------------------------------------------------------- buildAnimationFromScenes: (scenes, previousScenes = null)-> sceneTotalDuration = 0 currentStart = 0 for scene in scenes sceneDuration = 0 sceneCurrentStart = 0 sceneFirstStart = null for animationOption in scene.animationOptions sceneCurrentStart += animationOption._incrementalDelay if not sceneFirstStart? sceneFirstStart = sceneCurrentStart if not animationOption.duration? animationOption.duration = 0 sceneDuration = Math.max(sceneDuration, sceneCurrentStart + animationOption.duration) aOptions = delay: currentStart + sceneCurrentStart animationOption._animationObjectOptions = Hy.UI.ViewProxy.mergeOptions(animationOption, aOptions) computedOptions = Hy.UI.ViewProxy.mergeOptions(scene.imageOptions, {}) #make a copy createdNewScene = true if previousScenes? if(existingScene = _.detect(previousScenes, (s)=>s.image is scene.image))? createdNewScene = false scene._view = existingScene._view scene._view.setUIProperties(computedOptions) if not scene._view? computedOptions._tag = "Animation" if scene.image? computedOptions.image = "assets/bkgnds/animations/#{scene.image}.png" scene._view = new Hy.UI.ImageViewProxy(computedOptions) else if scene.method? scene._view = scene.method(computedOptions) else Hy.Trace.debug "Page::buildAnimationFromScenes (NO SCENE IMAGE OR METHOD)" # STOP events don't seem to be getting fired. The below callback is never called. if scene._view? and createdNewScene scene._view.addEventListener("stop", (evt, view)=>Hy.Trace.debug("ANIMATION STOP EVENT (#{scene.image} view=#{view?.getTag()}")) sceneTotalDuration = Math.max(sceneTotalDuration, currentStart + sceneDuration) currentStart += sceneFirstStart [scenes, sceneTotalDuration] # ---------------------------------------------------------------------------------------------------------------- setStopAnimating: (flag)-> @stopAnimating = flag # ---------------------------------------------------------------------------------------------------------------- clearAnimation: ()-> Hy.Trace.debug "Page::hideAnimation (CLEARING ANIMATION CONTAINER)" this.hideAnimation() @animationContainer.removeChildren() this # ---------------------------------------------------------------------------------------------------------------- hideAnimation: ()-> Hy.Trace.debug "Page::hideAnimation (HIDING ANIMATION CONTAINER)" @animationContainer?.hide() @animationContainerHidden = true this # ---------------------------------------------------------------------------------------------------------------- animateScenes: (scenes)-> this.setStopAnimating(false) @animationOpenedWindow = false for scene in scenes this.animateScene(scenes, scene, 0) this # ---------------------------------------------------------------------------------------------------------------- animateScene: (scenes, scene, index)-> animationOption = scene.animationOptions[index] animationOption._animationObject = null #TEST imageOptions = {} if animationOption._startOpacity? imageOptions.opacity = animationOption._startOpacity else if animationOption.opacity? imageOptions.opacity = 0 scene._view.setUIProperties(imageOptions) if @animationContainerHidden @animationContainerHidden = false @animationContainer.show() if not @animationContainer.hasChild(scene._view) @animationContainer.addChild(scene._view) Hy.Trace.debug "Page::animateScene (BEGIN ANIMATE #{scene.image} ##{index})" if not @animationOpenedWindow @window.setUIProperty("opacity", 1.0) this.openWindow() @animationOpenedWindow = true animateFn = ()=> Hy.Trace.debug "Page::animateScene (CONTINUING ANIMATION #{scene.image})" animationOption._animationObject = Ti.UI.createAnimation(animationOption._animationObjectOptions) animationOption._animationObject.addEventListener("complete", (evt)=>this.animateCompleteEvent(evt.source, scenes)) scene._view.animate(animationOption._animationObject) null # Note that this is a hack and won't work as intended if there are multiple scenes to be animated if (fn = animationOption._waitForWindowFn)? Hy.Utils.Deferral.create(0, ()=>fn(animateFn)) else animateFn() this # ---------------------------------------------------------------------------------------------------------------- # TODO: it's possible that our version of the properties of an object that's been animated may no longer # reflect reality, at the end of an animation. Should really set UIProperties at the end, here. animateCompleteEvent: (animationObject, scenes)-> for scene in scenes index = -1 for animationOption in scene.animationOptions index++ if animationOption._animationObject is animationObject if index < (_.size(scene.animationOptions)-1) if @stopAnimating Hy.Trace.debug "Page::animateCompleteEvent (ANIMATION STOPPED #{scene.image})" else Hy.Trace.debug "Page::animateCompleteEvent (ANIMATION COMPLETED FOR #{scene.image} ##{index}, continuing)" this.animateScene(scenes, scene, index+1) else # if we're here, we're done with this scene. But we can't necessarily remove the scene's view. Hy.Trace.debug "Page::animateCompleteEvent (ANIMATION COMPLETED #{scene.image})" # @animationContainer.removeChild(scene._view) return this this # ================================================================================================================== class SplashPage extends Page # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app # @container.addChild(this.createJewelContainer()) this # ---------------------------------------------------------------------------------------------------------------- createJewelContainer: ()-> defaultOptions = image: "assets/icons/trivially-01.png" height: 100 width: 100 _tag: "Jewel Container" @jewelView = new Hy.UI.ImageViewProxy(defaultOptions) @jewelView # ---------------------------------------------------------------------------------------------------------------- initialize: (fnReady)-> super true # ---------------------------------------------------------------------------------------------------------------- start: ()-> super this # ================================================================================================================== class IntroPage extends Page # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app this.webViewPanelCreate() this.addClick() this # ---------------------------------------------------------------------------------------------------------------- openWindow: (options={})-> super options @webView?.open() this # ---------------------------------------------------------------------------------------------------------------- closeWindow: (options={})-> @webViewPanel?.close() super this # ---------------------------------------------------------------------------------------------------------------- initialize: (fnReady)-> super @fnReady = fnReady @clicked = false @clickAllowed = true @finishingUp = false @finishedAnimatingIn = false # apparently, the window has to be open in order for the webview to work... # @window.setUIProperty("opacity", 0) this.openWindow() @webViewPanel?.initialize( (event)=>Hy.Utils.Deferral.create(0, ()=>PageState.get().resumed()) ) @introPanel?.initialize() # Not likely false # Wait # ---------------------------------------------------------------------------------------------------------------- start: ()-> super # @clickAllowed = true @webView?.start() this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> @clickAllowed = false @webView?.stop() super this # ---------------------------------------------------------------------------------------------------------------- resumed: ()-> super this # ---------------------------------------------------------------------------------------------------------------- obs_networkChanged: (reason)-> super @introPanel?.obs_networkChanged(reason) this # ---------------------------------------------------------------------------------------------------------------- setStopAnimating: (flag)-> super if not @finishedAnimatingIn @webViewPanel?.fireEvent({kind: "stopAnimating"}, (event)=>this.animateInFinished()) this # ---------------------------------------------------------------------------------------------------------------- addClick: ()-> options = top: 0 bottom: 0 right: 0 left: 0 zIndex: @animationContainer.getUIProperty("zIndex") + 1 _tag: "Click Container" @container.addChild(v = new Hy.UI.ViewProxy(options)) fnClick = (evt)=> if not @clicked and @clickAllowed @clicked = true @finishingUp = true if (pageState = PageState.get()).isTransitioning() Hy.Trace.debug("IntroPage::addClick (WAITING FOR TRANSITION)") pageState.addPostTransitionAction(()=>@fnReady?()) this.setStopAnimating(true) else Hy.Trace.debug("IntroPage::addClick (NOT TRANSITIONING)") this.animateOutIntroPanelAndTitle() @fnReady?() null v.addEventListener("click", fnClick) this # ---------------------------------------------------------------------------------------------------------------- addTitle: ()-> options = top: 140 # 170 # 2.5.0 left: (Hy.UI.iPad.screenWidth-315)/2 image: "assets/bkgnds/animations/label-Trivially.png" width: 315 height: 100 zIndex: 102 opacity: 0 _tag: "Title" @container.addChild(@title = new Hy.UI.ImageViewProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- addIntroPanel: ()-> options = top: 260 # 290 # 2.5.0 zIndex: 102 touchEnabled: false opacity: 0 @container.addChild(@introPanel = new Hy.Panels.IntroPanel(options)) @introPanel.initialize() this # ---------------------------------------------------------------------------------------------------------------- animateInFinished: ()-> if not @finishingUp and not @introPanel? this.addTitle() this.addIntroPanel() this.animateInIntroPanelAndTitle() @finishedAnimatingIn = true Hy.Utils.Deferral.create(0, ()=>PageState.get().resumed()) # ---------------------------------------------------------------------------------------------------------------- animateIn: ()-> @webViewPanel?.fireEvent({kind: "animateIn"}, (event)=>this.animateInFinished()) this.animateWindow({opacity: 1, duration: 0}) return -1 # ---------------------------------------------------------------------------------------------------------------- animateInIntroPanelAndTitle: ()-> @introPanel?.animate({opacity:1, duration: 100}) @title?.animate({opacity:1, duration: 100}) this # ---------------------------------------------------------------------------------------------------------------- animateOutIntroPanelAndTitle: (fnDone = null)-> Hy.Trace.debug("IntroPage::animateOutIntroPanelAndTitle") animateCount = 0 fn = (evt)=> Hy.Trace.debug("IntroPage::animateOutIntroPanelAndTitle (#{animateCount})") if ++animateCount is 2 fnDone?() null if true @introPanel?.animate({opacity:0, duration: 50}, fn) @title?.animate({opacity:0, duration: 50}, fn) else @introPanel?.setUIProperty("opacity", 0) @title?.setUIProperty("opacity", 0) fnDone?() this # ---------------------------------------------------------------------------------------------------------------- animateOut: ()-> Hy.Trace.debug("IntroPage::animateOut") @clickAllowed = false fn = ()=> @webViewPanel?.fireEvent({kind: "animateOut"}, (event)=>this.animateOutFinished()) null this.animateOutIntroPanelAndTitle(fn) return -1 # ---------------------------------------------------------------------------------------------------------------- animateOut2: ()-> @clickAllowed = false @webViewPanel?.fireEvent({kind: "animateOut"}, (event)=>this.animateOutFinished()) @introPanel?.animate({opacity:0, duration: 100}) @title?.animate({opacity:0, duration: 100}) return -1 # ---------------------------------------------------------------------------------------------------------------- animateOutFinished: ()-> duration = 0 this.animateWindow({opacity: 0, duration: duration}) # 2.5.0 Hy.Utils.Deferral.create(duration, ()=>PageState.get().resumed()) this # ---------------------------------------------------------------------------------------------------------------- webViewPanelCreate: ()-> options = this.containerOptions() options._tag = "WebViewPanel" # options.borderWidth = 10 # options.borderColor = Hy.UI.Colors.green webViewOptions = top: options.top left: options.left width: options.width height: options.height _tag: "Intro Page Web View" scalesPageToFit:false url: "html-intro-page.html" zIndex: 50 #@zIndexPassive backgroundColor:'transparent' # http://developer.appcelerator.com/question/45491/can-i-change-the-white-background-that-shows-when-a-web-view-is-loading @container.addChild(@webViewPanel = new Hy.Panels.WebViewPanel(options, webViewOptions)) this # ---------------------------------------------------------------------------------------------------------------- # Bummed. <NAME> just died. 2011 Oct 5. # ---------------------------------------------------------------------------------------------------------------- # ================================================================================================================== class UtilityPage extends Page # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> @subpanels = [] super state, app this.addCrowdGameLogo() .addTitle() this # ---------------------------------------------------------------------------------------------------------------- addSubpanel: (subpanel)-> @container.addChild(subpanel) @subpanels.push subpanel this # ---------------------------------------------------------------------------------------------------------------- containerOptions: ()-> options = super options.zIndex = 90 options # ---------------------------------------------------------------------------------------------------------------- initialize: ()-> super for panel in @subpanels panel.initialize() true # ---------------------------------------------------------------------------------------------------------------- obs_networkChanged: (reason)-> super for panel in @subpanels panel.obs_networkChanged(reason) this # ---------------------------------------------------------------------------------------------------------------- addCrowdGameLogo: ()-> options = top: 20 left: 30 image: "assets/icons/CrowdGame.png" width: 215 height: 50 _tag: "Logo" @container.addChild(new Hy.UI.ImageViewProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- addTitle: ()-> options = top: 20 left: (Hy.UI.iPad.screenWidth-316)/2 image: "assets/icons/label-Trivially.png" width: 316 height: 101 _tag: "Title" @container.addChild(new Hy.UI.ImageViewProxy(options)) this # ================================================================================================================== class AboutPage extends UtilityPage # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app @restored = false this.addSubpanel(this.addAboutPanel()) this # ---------------------------------------------------------------------------------------------------------------- addAboutPanel: ()-> fnClickDone = ()=> # If we did a restore, we need to reinitialize the content list on the Start Page r = @restored @restored = false this.getApp().showStartPage(if r then [((page)=>page.updateContentOptionsPanel())] else []) null fnUpdateClicked = (evt, clickedView)=> if evt.index is 0 Hy.Content.ContentManager.get()?.updateManifests() null fnClickRestore = ()=> # Must be online if Hy.Network.NetworkService.isOnline() # If an update is available, force it first if Hy.Content.ContentManifestUpdate.getUpdate()? options = message: "Trivially requires an update before purchases can be restored.\nTap \"update\" to begin" buttonNames: ["update", "cancel"] cancel: 1 dialog = new Hy.UI.AlertDialog(options) dialog.addEventListener("click", fnUpdateClicked) else @restored = true Hy.Content.ContentManager.get()?.restore() # Let's present the restore UI on the About page # this.getApp().restoreAction() else new Hy.UI.AlertDialog("Please connect to Wifi and try again") null fnClickJoinHelp = ()=> this.getApp().showJoinCodeInfoPage() null new Hy.Panels.AboutPanel({}, fnClickDone, fnClickRestore, fnClickJoinHelp) # ================================================================================================================== class UserCreatedContentInfoPage extends UtilityPage # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app this.addSubpanel(this.addInfoPanel()) this # ---------------------------------------------------------------------------------------------------------------- addInfoPanel: ()-> fnClickDone = ()=> this.getApp().showStartPage() null fnClickBuy = ()=> this.getApp().userCreatedContentAction("buy", null, true) null new Hy.Panels.UserCreatedContentInfoPanel({}, fnClickDone, fnClickBuy) # ================================================================================================================== class JoinCodeInfoPage extends UtilityPage # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app this.addSubpanel(this.addInfoPanel()) this # ---------------------------------------------------------------------------------------------------------------- addInfoPanel: ()-> fnClickDone = ()=> this.getApp().showStartPage() null new Hy.Panels.JoinCodeInfoPanel({}, fnClickDone) # ================================================================================================================== class StartPage extends Page _.extend StartPage, Hy.Utils.Observable # For changes to the state of the Start button # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app @pageEnabled = true @startEnabled = {state: false, reason: null} fnStart = (evt)=>this.startClicked() this.addCrowdGameLogo() .addTitle() .addAboutPageButton() .addGameOptionPanels() .addContentOptionsPanel() .addStartButton(fnStart) .addStartButtonText() .addContentOptionsInfo() .addJoinCodeInfo() .addUpdateAvailableInfo() @message = new Hy.Panels.MessageMarquee(this, @container) this.createCheckInCritterPanel() @fnContentPacksChanged = (evt)=>this.contentPacksChanged(evt) Hy.Pages.StartPage.addObserver this # For tracking changes to Start Button state this # ---------------------------------------------------------------------------------------------------------------- isPageEnabled: ()-> @pageEnabled # ---------------------------------------------------------------------------------------------------------------- setPageEnabled: (enabled)-> @pageEnabled = enabled for panel in [@aboutPanel, @joinCodeInfoPanel, @updateAvailablePanel] if enabled panel?.initialize() else panel?.setEnabled(false) StartPage.notifyObservers (observer)=>observer.obs_startPagePageEnabledStateChange?(@pageEnabled) this.updateUCCInfo() this # ---------------------------------------------------------------------------------------------------------------- containerOptions: ()-> options = super options.zIndex = 90 options # ---------------------------------------------------------------------------------------------------------------- openWindow: (options={})-> super options @contentOptionsPanel.open(options) this # ---------------------------------------------------------------------------------------------------------------- closeWindow: (options={})-> @contentOptionsPanel.close(options) super this # ---------------------------------------------------------------------------------------------------------------- animateWindow: (options)-> # 2.5.0 @contentOptionsPanel.animate(options) super options this # ---------------------------------------------------------------------------------------------------------------- start: ()-> super Hy.Options.contentPacks.addEventListener 'change', @fnContentPacksChanged Hy.Content.ContentManager.addObserver this # Tracking inventory changes Hy.Content.ContentManagerActivity.addObserver this # ContentPack updates Hy.Update.Update.addObserver this # as updates become available: "obs_updateAvailable" @contentOptionsPanel.start() @message.start() @checkInCritterPanel.start() # Check for required or strongly-urged content or app updates, which appear to the user # as a popover, which either allows dismissal, with frequent reminders, or which can't be dismissed, in # the case of required updates. # First, make sure we're online and not otherwise busy if not Hy.Pages.PageState.get().hasPostFunctions() and Hy.Network.NetworkService.isOnline() if not Hy.Content.ContentManager.get().doUpdateChecks() # Do update checks first if not Hy.Update.ConsoleAppUpdate.getUpdate()?.doRequiredUpdateCheck() # Then app updates Hy.Update.RateAppReminder.getUpdate()?.doRateAppReminderCheck() # Then rate app requests this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> Hy.Options.contentPacks.removeEventListener 'change', @fnContentPacksChanged Hy.Content.ContentManager.removeObserver this Hy.Content.ContentManagerActivity.removeObserver this Hy.Update.Update.removeObserver this @contentOptionsPanel.stop() @message.stop() @checkInCritterPanel.stop() super this # ---------------------------------------------------------------------------------------------------------------- pause: ()-> @message.pause() @checkInCritterPanel.pause() super this # ---------------------------------------------------------------------------------------------------------------- resumed: ()-> super @message.resumed() @checkInCritterPanel.resumed() # If our state shows that the Start Button was clicked, and we're being resumed, then # it's likely that we were backgrounded while preparing a contest. So just reset state and let # the user tap the button again if so inclined if this.startButtonIsClicked() this.resetStartButtonClicked() this # ---------------------------------------------------------------------------------------------------------------- initialize: ()-> super this.updateStartButtonEnabledState() this.resetStartButtonClicked() @aboutPanelButtonClicked = false @joinCodeInfoPanelButtonClicked = false @updateAvailablePanelButtonClicked = false @aboutPanel.initialize() @updateAvailablePanel.initialize() @joinCodeInfoPanel.initialize() if @panelSound? @panelSound.syncCurrentChoiceWithAppOption() @checkInCritterPanel.initialize() @contentOptionsPanel.initialize() this.updateUCCInfo() true # ---------------------------------------------------------------------------------------------------------------- obs_networkChanged: (reason)-> super if this.isPageEnabled() @joinCodeInfoPanel.obs_networkChanged(reason) @updateAvailablePanel.obs_networkChanged(reason) this # ---------------------------------------------------------------------------------------------------------------- obs_updateAvailable: (update)-> if this.isPageEnabled() if update.isContentManifestUpdate() or update.isConsoleAppUpdate() @updateAvailablePanel.obs_updateAvailable() this # ---------------------------------------------------------------------------------------------------------------- updateUCCInfo: ()-> buyButton = @panelUCCInfo.findButtonViewByValue(Hy.Config.Content.kThirdPartyContentBuyText) addButton = @panelUCCInfo.findButtonViewByValue(Hy.Config.Content.kThirdPartyContentNewText) infoButton = @panelUCCInfo.findButtonViewByValue(Hy.Config.Content.kThirdPartyContentInfoText) if this.isPageEnabled() isPurchased = Hy.Content.ContentManager.get().getUCCPurchaseItem().isPurchased() buyButton?.setEnabled(not isPurchased) addButton?.setEnabled(isPurchased) infoButton?.setEnabled(true) else buyButton?.setEnabled(false) addButton?.setEnabled(false) infoButton?.setEnabled(false) this # ---------------------------------------------------------------------------------------------------------------- addCrowdGameLogo: ()-> options = top: 20 left: 30 image: "assets/icons/CrowdGame.png" width: 215 height: 50 _tag: "Logo" @container.addChild(@crowdGameLogoView = new Hy.UI.ImageViewProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- addTitle: ()-> options = top: 20 left: (Hy.UI.iPad.screenWidth-316)/2 image: "assets/icons/label-Trivially.png" width: 315 height: 100 _tag: "Title" @container.addChild(@titleView = new Hy.UI.ImageViewProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- # addAboutPageButton: ()-> @aboutPanelButtonClicked = false fnClick = ()=> if @aboutPanel.isEnabled() and not @aboutPanelButtonClicked @aboutPanelButtonClicked = true this.getApp().showAboutPage() null # We take our cues from other screen elements: CrowdGame Logo image, Trivially label options = top: @titleView.getUIProperty("top") right: @crowdGameLogoView.getUIProperty("left") title: "?" font: Hy.UI.Fonts.specBigNormal _tag: "About Button" buttonOptions = title: "?" font: Hy.UI.Fonts.specBigNormal topTextOptions = {} bottomTextOptions = {text: "Help"} @container.addChild(@aboutPanel = new Hy.Panels.LabeledButtonPanel(options, buttonOptions, fnClick, topTextOptions, bottomTextOptions)) this # ---------------------------------------------------------------------------------------------------------------- obs_contentUpdateSessionStarted: (label, report)-> # @message.startAdHocSession(label) this.updateStartButtonEnabledState() this.setPageEnabled(false) # if report? # @message.addAdHoc(report) this # ---------------------------------------------------------------------------------------------------------------- obs_contentUpdateSessionProgressReport: (report, percentDone = -1)-> Hy.Trace.debug "StartPage::contentUpdateSessionProgressReport (#{report} / #{percentDone})" if percentDone isnt -1 report += " (#{percentDone}% done)" # if report? # @message.addAdHoc report this # ---------------------------------------------------------------------------------------------------------------- obs_contentUpdateSessionCompleted: (report, changes)-> Hy.Trace.debug "StartPage::contentUpdateSessionCompleted #{report}" # @message.addAdHoc(report) # @message.endAdHocSession() this.updateStartButtonEnabledState() this.setPageEnabled(true) @updateAvailablePanel.initialize() this # ---------------------------------------------------------------------------------------------------------------- obs_inventoryInitiated: ()-> @message.startAdHocSession("Syncing with Apple App Store") @message.addAdHoc("Contacting Store") this # ---------------------------------------------------------------------------------------------------------------- obs_inventoryUpdate: (status, message)-> if message? @message.addAdHoc(message) this # ---------------------------------------------------------------------------------------------------------------- obs_inventoryCompleted: (status, message)-> if message? @message.addAdHoc(message) @message.endAdHocSession() this # ---------------------------------------------------------------------------------------------------------------- obs_purchaseInitiated: (label, report)-> this.updateStartButtonEnabledState() this.setPageEnabled(false) # @message.startAdHocSession(label) # if report? # @message.addAdHoc(report) this # ---------------------------------------------------------------------------------------------------------------- obs_purchaseProgressReport: (report)-> Hy.Trace.debug "StartPage::purchaseProgressReport #{report}" # if report? # @message.addAdHoc(report) null # ---------------------------------------------------------------------------------------------------------------- obs_purchaseCompleted: (report)-> this.updateStartButtonEnabledState() this.setPageEnabled(true) this.updateUCCInfo() # if report? # @message.addAdHoc(report) # @message.endAdHocSession() null # ---------------------------------------------------------------------------------------------------------------- obs_restoreInitiated: (report)-> this.updateStartButtonEnabledState() this.setPageEnabled(false) # @message.startAdHocSession("Restore of purchases") # if report? # @message.addAdHoc(report) null # ---------------------------------------------------------------------------------------------------------------- obs_restoreProgressReport: (report)-> # if report? # @message.addAdHoc(report) null # ---------------------------------------------------------------------------------------------------------------- obs_restoreCompleted: (report)-> this.updateStartButtonEnabledState() this.setPageEnabled(true) # if report? # @message.addAdHoc(report) # @message.endAdHocSession() null # ---------------------------------------------------------------------------------------------------------------- addStartButton: (fn)-> options = height: 110 width: 110 top: 415 left: 277 zIndex: 101 backgroundImage: "assets/icons/button-play.png" backgroundSelectedImage: "assets/icons/button-play-selected.png" _tag: "Start Button" @container.addChild(@startButton = new Hy.UI.ButtonProxy(options)) this.resetStartButtonClicked() @fnClickStartGame = (evt)=> if @startEnabled.state if not this.startButtonIsClicked() this.setStartButtonClicked() fn() null @startButton.addEventListener 'click', @fnClickStartGame this # ---------------------------------------------------------------------------------------------------------------- startButtonIsClicked: ()-> @startButtonClicked # ---------------------------------------------------------------------------------------------------------------- setStartButtonClicked: ()-> @startButtonClicked = true # ---------------------------------------------------------------------------------------------------------------- resetStartButtonClicked: ()-> @startButtonClicked = false # ---------------------------------------------------------------------------------------------------------------- getStartEnabled: ()-> [@startEnabled.state, @startEnabled.reason] # ---------------------------------------------------------------------------------------------------------------- setStartEnabled: (state, reason)-> @startEnabled.state = state @startEnabled.reason = reason @startButton.setEnabled(state) this.setContentOptionsInfo(state, reason) StartPage.notifyObservers (observer)=>observer.obs_startPageStartButtonStateChanged?(state, reason) this # ---------------------------------------------------------------------------------------------------------------- addStartButtonText: ()-> width = 200 options = top: @startButton.getUIProperty("top") + 120 left: @startButton.getUIProperty("left") - ((width-@startButton.getUIProperty("width"))/2) width: width height: 50 text: "Start Game" font: Hy.UI.Fonts.specMediumMrF zIndex:@startButton.getUIProperty("zIndex") textAlign: 'center' _tag: "Start Game Label" @container.addChild(@startButtonTextView = new Hy.UI.LabelProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- # "1 topic selected", etc # addContentOptionsInfo: ()-> width = 70 options = top: @startButton.getUIProperty("top") left: @startButton.getUIProperty("left") - (width + 20) width: width height: @startButton.getUIProperty("height") font: Hy.UI.Fonts.specMinisculeNormal color: Hy.UI.Colors.black zIndex:@startButton.getUIProperty("zIndex") textAlign: 'center' _tag: "Content Options Info" # borderColor: Hy.UI.Colors.white @container.addChild(@contentOptionsPanelInfoView = new Hy.UI.LabelProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- setContentOptionsInfo: (state, info = null)-> @contentOptionsPanelInfoView.setUIProperty("color", if state then Hy.UI.Colors.black else Hy.UI.Colors.MrF.Red) @contentOptionsPanelInfoView.setUIProperty("text", info) this # ---------------------------------------------------------------------------------------------------------------- # We position this relative to the ? About Page Button... # addJoinCodeInfo: ()-> @joinCodeInfoPanelButtonClicked = false fnClick = ()=> if @joinCodeInfoPanel.isEnabled() and not @joinCodeInfoPanelButtonClicked @joinCodeInfoPanelButtonClicked = true this.getApp().showJoinCodeInfoPage() null options = bottom: @startButtonTextView.getUIProperty("bottom") - 20 left: 50 @container.addChild(@joinCodeInfoPanel = new Hy.Panels.CodePanel(options, fnClick)) this # ---------------------------------------------------------------------------------------------------------------- # We position this relative to the ? About Page Button... # addUpdateAvailableInfo: ()-> @updateAvailablePanelButtonClicked = false fnClick = (e, v)=> if @updateAvailablePanel.isEnabled() and not @updateAvailablePanelButtonClicked @updateAvailablePanelButtonClicked = true if Hy.Network.NetworkService.isOnline() # Check for Content Update, then App Update if Hy.Content.ContentManifestUpdate.getUpdate()? Hy.Content.ContentManager.get()?.updateManifests() else if (update = Hy.Update.ConsoleAppUpdate.getUpdate())? update.doURL() @updateAvailablePanelButtonClicked = false null options = top: @startButton.getUIProperty("top") - 20 left: 50 @container.addChild(@updateAvailablePanel = new Hy.Panels.UpdateAvailablePanel(options, fnClick)) this # ---------------------------------------------------------------------------------------------------------------- addGameOptionPanels: ()-> top = 93 #130 #155 left = 85 #75 padding = 55 panelSpecs = [ {varName: "panelSound", fnName: "createSoundPanel", options: {left: left}}, {varName: "panelNumberOfQuestions", fnName: "createNumberOfQuestionsPanel", options: {left: left}}, {varName: "panelSecondsPerQuestion", fnName: "createSecondsPerQuestionPanel", options: {left: left}}, {varName: "panelFirstCorrect", fnName: "createFirstCorrectPanel", options: {left: left}}, {varName: "panelUCCInfo", fnName: "createUserCreatedContentInfoPanel2", options: {left: left}} ] for panelSpec in panelSpecs this[panelSpec.varName] = Hy.Panels.OptionPanels[panelSpec.fnName](this, Hy.UI.ViewProxy.mergeOptions(panelSpec.options, {top: top})) @container.addChild(this[panelSpec.varName]) top += padding this # ---------------------------------------------------------------------------------------------------------------- addContentOptionsPanel: ()-> options = top: 100 right: 80 @container.addChild(@contentOptionsPanel = new Hy.Panels.ContentOptionsPanel(this, options)) this # ---------------------------------------------------------------------------------------------------------------- updateContentOptionsPanel: ()-> Hy.Trace.debug "StartPage::updateContentOptionsPanel" @contentOptionsPanel?.update() this # ---------------------------------------------------------------------------------------------------------------- obs_userCreatedContentSessionStarted: (label, report = null)-> this.updateStartButtonEnabledState() this.setPageEnabled(false) # @message.startAdHocSession(label) # @message.addAdHoc(if report? then report else "Starting... This will only take a moment...") this # ---------------------------------------------------------------------------------------------------------------- obs_userCreatedContentSessionProgressReport: (report = null)-> # if report? # @message.addAdHoc(report) this # ---------------------------------------------------------------------------------------------------------------- obs_userCreatedContentSessionCompleted: (report = null, changes = false)-> this.updateUCCInfo() this.updateStartButtonEnabledState() this.setPageEnabled(true) # @message.addAdHoc(if report? then report else "Completed") # @message.endAdHocSession() this # ---------------------------------------------------------------------------------------------------------------- createCheckInCritterPanel: ()-> options = left: 0 bottom: 0 @container.addChild(@checkInCritterPanel = new Hy.Panels.CheckInCritterPanel(options)) this # ---------------------------------------------------------------------------------------------------------------- startClicked: ()-> Hy.Utils.Deferral.create 0, ()=>this.getApp().contestStart() # must use deferral to trigger startContest outside of event handler this # ---------------------------------------------------------------------------------------------------------------- updateStartButtonEnabledState: ()-> Hy.Trace.debug "StartPage::updateStartButtonEnabledState" reason = null state = false numTopics = _.size(_.select(Hy.Content.ContentManager.get().getLatestContentPacksOKToDisplay(), (c)=>c.isSelected())) if numTopics <= 0 reason = "No topics selected!" state = false else state = true reason = "#{numTopics} topic#{if numTopics > 1 then "s" else ""} selected" if (r = Hy.Content.ContentManager.isBusy())? reason = "Please wait: #{r}" state = false this.setStartEnabled(state, reason) this # ---------------------------------------------------------------------------------------------------------------- categoriesChanged: (evt)-> this.updateStartButtonEnabledState() # ---------------------------------------------------------------------------------------------------------------- contentPacksChanged: (evt)-> this.updateStartButtonEnabledState() # ---------------------------------------------------------------------------------------------------------------- contentPacksLoadingStart: ()-> @message.startAdHocSession("Preparing Contest") # ---------------------------------------------------------------------------------------------------------------- contentPacksLoadingCompleted: ()-> @message.endAdHocSession() # ---------------------------------------------------------------------------------------------------------------- contentPacksLoading: (report)-> @message.addAdHoc(report) # ================================================================================================================== class NotifierPage extends Page # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app @fnNotify = null this # ---------------------------------------------------------------------------------------------------------------- initialize: (fnNotify)-> super @fnNotify = fnNotify true # ---------------------------------------------------------------------------------------------------------------- start: ()-> super @fnNotify?() this # ---------------------------------------------------------------------------------------------------------------- resumed: ()-> super @fnNotify?() this # ================================================================================================================== class BasePage extends NotifierPage constructor: (state, app)-> super state, app @container.addChild(@questionInfoPanel = new Hy.Panels.QuestionInfoPanel(this.questionInfoPanelOptions())) this # ---------------------------------------------------------------------------------------------------------------- labelColor: ()-> Hy.UI.Colors.white # ---------------------------------------------------------------------------------------------------------------- questionInfoPanelOptions: ()-> {} # ================================================================================================================== # adds support for pause button and countdown class CountdownPage extends BasePage kCountdownStateUndefined = 0 kCountdownStateRunning = 1 kCountdownStatePaused = 2 @kWidth = 164 # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app @fnPause = null @fnCompleted = null @pauseClicked = false @overlayClicked = false @overlayShowing = false @currentCountdownValue = null @countdownSeconds = 0 @startingDelay = 0 @countdownDeferral = null @fnPauseClick = (evt)=> if not @pauseClicked @pauseClicked = true this.click() null @fnClickContinueGame = ()=> this.continue_() @overlayClicked = false @pauseClicked = false null @fnClickNewGame = ()=> @overlayClicked = false @pauseClicked = false this.getApp().contestRestart(false) null @fnClickForceFinish = ()=> @overlayClicked = false @pauseClicked = false this.getApp().contestForceFinish() null @container.addChild(@countdownPanel = new Hy.Panels.CountdownPanel(this.countdownPanelOptions(), @fnPauseClick)) @container.addChild(this.createPauseButton(this.pauseButtonOptions())) @container.addChild(this.createPauseButtonText(this.pauseButtonTextOptions())) this # ---------------------------------------------------------------------------------------------------------------- countdownPanelOptions: ()-> {} # ---------------------------------------------------------------------------------------------------------------- pauseButtonOptions: ()-> {} # ---------------------------------------------------------------------------------------------------------------- pauseButtonTextOptions: ()-> {} # ---------------------------------------------------------------------------------------------------------------- pause: ()-> return if @countdownState is kCountdownStatePaused @countdownState = kCountdownStatePaused this.disablePause() @countdownTicker?.pause() this.showOverlay({opacity:1, duration: 200}) # Hy.Network.NetworkService.get().setImmediate() @fnPause() # ---------------------------------------------------------------------------------------------------------------- resumed: ()-> super this.pause() this # ---------------------------------------------------------------------------------------------------------------- continue_: ()-> return if @countdownState is kCountdownStateRunning # Hy.Network.NetworkService.get().setSuspended() @countdownState = kCountdownStateRunning f = ()=> this.enablePause() @countdownTicker?.continue_() @fnNotify() this.hideOverlay({opacity:0, duration: 200}, f) this # ---------------------------------------------------------------------------------------------------------------- start: ()-> super this.initCountdown() this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> this.haltCountdown() super this # ---------------------------------------------------------------------------------------------------------------- haltCountdown: ()-> @countdownDeferral.clear() if @countdownDeferral?.enqueued() @countdownTicker?.exit() this # ---------------------------------------------------------------------------------------------------------------- initialize: (fnNotify, fnPause, fnCompleted, countdownSeconds, startingDelay)-> super fnNotify @countdownState = kCountdownStateUndefined @fnPause = fnPause @fnCompleted = fnCompleted @currentCountdownValue = null @countdownSeconds = countdownSeconds @startingDelay = startingDelay @pauseClicked = false @overlayClicked = false this.hideOverlayImmediate() this.enablePause() this.getCountdownPanel().initialize().animateCountdown(this.countdownAnimationOptions(@countdownSeconds), @countdownSeconds, null, true) true # ---------------------------------------------------------------------------------------------------------------- obs_networkChanged: (reason)-> Hy.Trace.debug("QuestionPage::obs_networkChanged (isPaused=#{this.isPaused()})") super if this.isPaused() this.updateConnectionInfo(reason) this # ---------------------------------------------------------------------------------------------------------------- createPauseButton: (options)-> defaultOptions = zIndex: 101 backgroundImage: "assets/icons/button-pause-question-page.png" _tag: "Pause" @pauseButton = new Hy.UI.ButtonProxy(Hy.UI.ViewProxy.mergeOptions(defaultOptions, options)) f = ()=> @fnPauseClick() null @pauseButton.addEventListener("click", f) @pauseButton # ---------------------------------------------------------------------------------------------------------------- createPauseButtonText: (options)-> defaultOptions = zIndex: 101 text: 'Pause' font: Hy.UI.Fonts.specTinyMrF color: Hy.UI.Colors.MrF.DarkBlue height: 'auto' textAlign: 'center' _tag: "Pause Text" @pauseButtonText = new Hy.UI.LabelProxy(Hy.UI.ViewProxy.mergeOptions(defaultOptions, options)) @pauseButtonText # ---------------------------------------------------------------------------------------------------------------- getCountdownPanel: ()-> @countdownPanel # ---------------------------------------------------------------------------------------------------------------- animateCountdown: (init, value)-> this.getCountdownPanel().animateCountdown(this.countdownAnimationOptions(value), value, @countdownSeconds, init) this # ---------------------------------------------------------------------------------------------------------------- countdownAnimationOptions: (value)-> _style: "normal" # ---------------------------------------------------------------------------------------------------------------- playCountdownSound: (value)-> if (event = this.countdownSound(value))? Hy.Media.SoundManager.get().playEvent(event) this # ---------------------------------------------------------------------------------------------------------------- initCountdown: ()-> @countdownState = kCountdownStateRunning @countdownDeferral = null if @countdownDeferral?.triggered() fnInitView = (value)=> @currentCountdownValue = value this.animateCountdown(true, value) fnUpdateView = (value)=> @currentCountdownValue = value this.animateCountdown(false, value) fnCompleted = (evt)=>this.countdownCompleted() fnSound = (value)=>this.playCountdownSound(value) @countdownTicker = new CountdownTicker(fnInitView, fnUpdateView, fnCompleted, fnSound) @countdownTicker.init(@countdownSeconds, @startingDelay) this # ---------------------------------------------------------------------------------------------------------------- getCountdownStartValue: ()-> @countdownSeconds # ---------------------------------------------------------------------------------------------------------------- getCountdownValue: ()-> # @countdownTicker?.getValue() # This isn't reliable, if console user answers @currentCountdownValue # ---------------------------------------------------------------------------------------------------------------- countdownSound: (value)-> null # ---------------------------------------------------------------------------------------------------------------- countdownCompleted: ()-> this.disablePause() @fnCompleted() # ---------------------------------------------------------------------------------------------------------------- click: (evt)-> this.pause() if @countdownState is kCountdownStateRunning # ---------------------------------------------------------------------------------------------------------------- disablePause: ()-> for view in [@pauseButton, @pauseButtonText] view?.animate({duration: 100, opacity: 0}) view?.hide() this # ---------------------------------------------------------------------------------------------------------------- enablePause: ()-> for view in [@pauseButton, @pauseButtonText] # view?.animate({duration: 100, opacity: 1}) view?.setUIProperty("opacity", 1) view?.show() this # ---------------------------------------------------------------------------------------------------------------- isPaused: ()-> @countdownState is kCountdownStatePaused # ---------------------------------------------------------------------------------------------------------------- createOverlay: ()-> container = this.overlayContainer() overlayBkgndOptions = top: 0 bottom: 0 left: 0 right: 0 backgroundImage: Hy.UI.Backgrounds.pixelOverlay zIndex: 200 opacity: 0 _tag: "Overlay Background" container.addChild(@overlayBkgnd = new Hy.UI.ViewProxy(overlayBkgndOptions)) overlayFrameOptions = top: 100 bottom: 100 left: 100 right: 100 borderColor: Hy.UI.Colors.white borderRadius: 16 borderWidth: 4 zIndex: 201 # _alignment: "center" opacity: 0 _tag: "Overlay Frame" container.addChild(@overlayFrame = new Hy.UI.ViewProxy(overlayFrameOptions)) elementOptions = width: 400 @overlayFrame.addChild(this.overlayBody(elementOptions)) this # ---------------------------------------------------------------------------------------------------------------- showOverlay: (options, fnDone = null)-> fn = ()=> if fnDone? Hy.Utils.Deferral.create(0, fnDone) null if not @overlayBkgnd? this.createOverlay() this.updateConnectionInfo() @panelSound?.syncCurrentChoiceWithAppOption() for view in [@overlayBkgnd, @overlayFrame] view.setUIProperty("opacity", 0) view.show() @overlayBkgnd.animate(options, ()=>) @overlayFrame.animate(options, fn) this # ---------------------------------------------------------------------------------------------------------------- hideOverlayImmediate: ()-> for view in [@overlayBkgnd, @overlayFrame] view?.hide() this # ---------------------------------------------------------------------------------------------------------------- hideOverlay: (options, fnDone = null)-> fn = ()=> for view in [@overlayBkgnd, @overlayFrame] view?.hide() if fnDone? Hy.Utils.Deferral.create(0, fnDone) null if @overlayBkgnd? @overlayFrame.animate(options, ()=>) @overlayBkgnd.animate(options, fn) else fn() this # ---------------------------------------------------------------------------------------------------------------- overlayContainer: ()-> @container # ---------------------------------------------------------------------------------------------------------------- overlayBody: (elementOptions)-> options = backgroundImage: Hy.UI.Backgrounds.pixelOverlay _tag: "Overlay Body" body = new Hy.UI.ViewProxy(options) body.addChild(this.createGamePausedText()) top = 170 #200 verticalPadding = 90 #elementOptions.height + 15 #25 textOffset = 125 horizontalPadding = 20 choiceOptions = _style: "plainOnDarkBackground" @panelSound = Hy.Panels.OptionPanels.createSoundPanel(this, Hy.UI.ViewProxy.mergeOptions(elementOptions, {top:top}), {font: Hy.UI.Fonts.specBigNormal, color: Hy.UI.Colors.white, _attach: "right"}, choiceOptions) body.addChild(@panelSound) continueGame = this.createOverlayButtonPanel(Hy.UI.ViewProxy.mergeOptions(elementOptions, {top: (top += verticalPadding)}), {backgroundImage: "assets/icons/button-play-small-blue.png", left: horizontalPadding}, {left: textOffset, text: "Continue Game"}, @fnClickContinueGame) body.addChild(continueGame) forceFinishGame = this.createOverlayButtonPanel(Hy.UI.ViewProxy.mergeOptions(elementOptions, {top: (top += verticalPadding)}), {backgroundImage: "assets/icons/button-cancel.png", left: horizontalPadding}, {left: textOffset, text: "Finish Game"}, @fnClickForceFinish) body.addChild(forceFinishGame) newGame = this.createOverlayButtonPanel(Hy.UI.ViewProxy.mergeOptions(elementOptions, {top: (top += verticalPadding)}), {backgroundImage: "assets/icons/button-restart.png", left: horizontalPadding}, {left: textOffset, text: "Restart Game"}, @fnClickNewGame) body.addChild(newGame) @connectionInfo = this.createConnectionInfo(Hy.UI.ViewProxy.mergeOptions(elementOptions, {top: (top += verticalPadding)})) this.updateConnectionInfo() body.addChild(@connectionInfo) body # ---------------------------------------------------------------------------------------------------------------- updateConnectionInfo: (reason = "Wifi")-> text = "" if reason is "Wifi" if Hy.Network.NetworkService.isOnlineWifi() if (encoding = Hy.Network.NetworkService.getAddressEncoding())? text = "Additional players? Visit #{Hy.Config.Rendezvous.URLDisplayName} and enter: #{encoding}" @connectionInfo?.setUIProperty("text", text) this # ---------------------------------------------------------------------------------------------------------------- createConnectionInfo: (commonOptions)-> options = width: 600 font: Hy.UI.Fonts.specSmallNormal color: Hy.UI.Colors.white _tag: "Connection Info" height: 'auto' textAlign: 'center' _tag: "Connection Info" new Hy.UI.LabelProxy(Hy.UI.ViewProxy.mergeOptions(commonOptions, options)) # ---------------------------------------------------------------------------------------------------------------- createGamePausedText: ()-> gamePausedOptions = text: 'Game Paused' font: Hy.UI.Fonts.specGiantMrF color: Hy.UI.Colors.white top: 50 height: 'auto' textAlign: 'center' _tag: "Game Paused" new Hy.UI.LabelProxy(gamePausedOptions) # ---------------------------------------------------------------------------------------------------------------- createOverlayButtonPanel: (containerOptions, buttonOptions, labelOptions, fnClick)-> options = height: 72 _tag: "Overlay Button Panel" container = new Hy.UI.ViewProxy(Hy.UI.ViewProxy.mergeOptions(options, containerOptions)) f = ()=> if not @overlayClicked @overlayClicked = true fnClick() null defaultButtonOptions = height: 72 width: 72 left: 0 _tag: "Overlay Button" button = new Hy.UI.ButtonProxy(Hy.UI.ViewProxy.mergeOptions(defaultButtonOptions, buttonOptions)) button.addEventListener 'click', f container.addChild(button) defaultLabelOptions = font: Hy.UI.Fonts.specBigNormal color: Hy.UI.Colors.white _tag: "Overlay Label" container.addChild(new Hy.UI.LabelProxy(Hy.UI.ViewProxy.mergeOptions(defaultLabelOptions, labelOptions))) container # ================================================================================================================== class QuestionPage extends CountdownPage kQuestionBlockHeight = 215 kQuestionBlockWidth = 944 kQuestionInfoHeight = kQuestionInfoWidth = 86 kQuestionBlockHorizontalMargin = (Hy.UI.iPad.screenWidth - kQuestionBlockWidth)/2 # kQuestionBlockVerticalMargin = 30 kQuestionBlockVerticalMargin = 25 kQuestionTextMargin = 10 kQuestionTextWidth = kQuestionBlockWidth - (kQuestionTextMargin + kQuestionInfoWidth) kQuestionTextHeight = kQuestionBlockHeight - (2*kQuestionTextMargin) kAnswerBlockWidth = 460 kAnswerBlockHeight = 206 kAnswerBlockHorizontalPadding = 24 kAnswerBlockVerticalPadding = 15 # kAnswerContainerVerticalMargin = 20 kAnswerContainerVerticalMargin = 7 kAnswerContainerHorizontalMargin = kQuestionBlockHorizontalMargin kAnswerContainerWidth = (2*kAnswerBlockWidth) + kAnswerBlockHorizontalPadding kAnswerContainerHeight = (2*kAnswerBlockHeight) + kAnswerBlockVerticalPadding kAnswerLabelWidth = 60 kAnswerTextMargin = 10 kAnswerTextHeight = kAnswerBlockHeight - (2*kAnswerTextMargin) kAnswerTextWidth = kAnswerBlockWidth - ((2*kAnswerTextMargin) + kAnswerLabelWidth) kCountdownClockHeight = kCountdownClockWidth = 86 kButtonOffset = 5 kPauseButtonHeight = kPauseButtonWidth = 86 kPauseButtonVerticalMargin = kQuestionBlockVerticalMargin + kQuestionBlockHeight - (kPauseButtonHeight - kButtonOffset) kPauseButtonHorizontalMargin = kQuestionBlockHorizontalMargin - 20 kQuestionInfoVerticalMargin = kQuestionBlockVerticalMargin - kButtonOffset kQuestionInfoHorizontalMargin = kQuestionBlockHorizontalMargin - 20 # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> @zIndexPassive = 110 @zIndexActive = 150 @top = 0 @sound = null super state, app @soundCounter ||= 0 @soundKeys = ["count<KEY>0", "count<KEY>1", "count<KEY>_2", "countDown_3", "countDown_4"] @nSounds = @soundKeys.length @pageImage = null this.webViewPanelCreate() @container.addChild(this.createQuestionBlock()) @container.addChild(this.createAnswerBlocks()) this.createAnswerCritterPanel() @questionTestCount = 0 @answerTestCount = 0 # It's important that these all share the same view, due to the overlapping nature of the animations [@animateInLongScenes, @animateInLongSceneDuration] = this.buildAnimationFromScenes(this.initAnimateInLongScenes()) [@animateInShortScenes, @animateInShortSceneDuration] = this.buildAnimationFromScenes(this.initAnimateInShortScenes(), @animateInLongScenes) [@animateOutScenes, @animateOutSceneDuration] = this.buildAnimationFromScenes(this.initAnimateOutScenes(), @animateInShortScenes) this # ---------------------------------------------------------------------------------------------------------------- countdownPanelOptions: ()-> top : kQuestionBlockVerticalMargin + kQuestionBlockHeight + kAnswerContainerVerticalMargin + (kAnswerContainerHeight - kCountdownClockHeight)/2 left : kAnswerContainerHorizontalMargin + (kAnswerContainerWidth - kCountdownClockWidth)/2 height : kCountdownClockHeight width : kCountdownClockWidth zIndex : @zIndexActive + 2 # ---------------------------------------------------------------------------------------------------------------- pauseButtonOptions: ()-> zIndex : @zIndexActive + 2 height : kPauseButtonHeight width : kPauseButtonWidth top : kPauseButtonVerticalMargin right : kPauseButtonHorizontalMargin # ---------------------------------------------------------------------------------------------------------------- pauseButtonTextOptions: ()-> textHeight = 25 buttonOptions = this.pauseButtonOptions() options = top : buttonOptions.top - (textHeight + 5) right : buttonOptions.right width : buttonOptions.width height : textHeight zIndex : buttonOptions.zIndex options # ---------------------------------------------------------------------------------------------------------------- questionInfoPanelOptions: ()-> top : kQuestionInfoVerticalMargin right : kQuestionInfoHorizontalMargin # ---------------------------------------------------------------------------------------------------------------- start: ()-> super this.clearAnimation() @sound?.play() if not @showingAnswers @answerCritterPanel.start() this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> @sound.stop() if @sound?.isPlaying() if @showingAnswers @answerCritterPanel.stop() super this # ---------------------------------------------------------------------------------------------------------------- pause: ()-> @sound.pause() if @sound?.isPlaying() @answerCritterPanel.pause() super this # ---------------------------------------------------------------------------------------------------------------- resumed: ()-> super @sound.play() if @sound? and not @sound.isPlaying() @answerCritterPanel.resumed() this # ---------------------------------------------------------------------------------------------------------------- closeWindow: (options={})-> @webViewPanel?.close() super this # ---------------------------------------------------------------------------------------------------------------- openWindow: (options={})-> super options this # ---------------------------------------------------------------------------------------------------------------- continue_: ()-> super @sound.play() if @sound? and not @sound.isPlaying() this # ---------------------------------------------------------------------------------------------------------------- initializeForQuestion: (fnNotify, fnPause, fnCompleted, countdownSeconds, startingDelay, contestQuestion, iQuestion, nQuestions)-> @showingAnswers = false @consoleAnswered = false @showingAnswersClicked = false this.initialize fnNotify, fnPause, fnCompleted, countdownSeconds, startingDelay, contestQuestion, iQuestion, nQuestions @answerCritterPanel.initialize() # apparently, the window has to be open in order for the webview to work... @window.setUIProperty("opacity", 0) this.animateChildren({duration: 0, opacity: 0}) this.openWindow() @webViewPanel?.initialize(()=>this.webViewPanelContentInitialize()) false # ---------------------------------------------------------------------------------------------------------------- initializeForAnswers: (fnNotify, fnPause, fnCompleted, countdownSeconds, startingDelay)-> @showingAnswers = true this.initialize fnNotify, fnPause, fnCompleted, countdownSeconds, startingDelay, @contestQuestion, @iQuestion, @nQuestions this.revealAnswer() true # ---------------------------------------------------------------------------------------------------------------- initialize: (fnNotify, fnPause, fnCompleted, countdownSeconds, startingDelay, contestQuestion, iQuestion, nQuestions)-> super @contestQuestion = contestQuestion @iQuestion = iQuestion @nQuestions = nQuestions @sound?.reset() @questionInfoPanel.initialize @iQuestion+1, @nQuestions, this.labelColor() true # ---------------------------------------------------------------------------------------------------------------- initAnimateInLongScenes: ()-> [ {image: "splash", imageOptions: {zIndex: 200, top: 0, left: 0, right: 0, bottom: 0}, animationOptions: [{_incrementalDelay: 500, duration: 400, _startOpacity: 1.0, opacity: 0.0, _waitForWindowFn: ((fn)=>this.webViewPanelWait(fn))}]} ] # ---------------------------------------------------------------------------------------------------------------- initAnimateInShortScenes: ()-> [ {image: "black", imageOptions: {zIndex: 200, top: 0, left: 0, right: 0, bottom: 0}, animationOptions: [{_incrementalDelay: 0, duration: 400, _startOpacity: 1.0, opacity: 0.0, _waitForWindowFn: ((fn)=>this.webViewPanelWait(fn))}]} ] # ---------------------------------------------------------------------------------------------------------------- initAnimateOutScenes: ()-> [ {image: "black", imageOptions: {zIndex: 200, top: 0, left: 0, right: 0, bottom: 0, opacity: 0}, animationOptions: [{_incrementalDelay: 0, duration: 400, _startOpacity: 0, opacity: 1.0}]} ] # ---------------------------------------------------------------------------------------------------------------- # Animates all child views EXCEPT the web view, which we animate separately # animateChildren: (options)-> for child in @container.getChildren() if child isnt @webViewPanel if options.opacity? child.setUIProperty("opacity", options.opacity) # child.animate(options) this # ---------------------------------------------------------------------------------------------------------------- animateIn: (useCurtains = false)-> Hy.Trace.debug "QuestionPage::animateIn (ENTER)" @webViewPanel?.fireEvent({kind: "animateIn", data: {useCurtains: useCurtains}}, (event)=>this.animateInFinished()) this.animateWindow({opacity: 1, duration: 0, delay: 150}) # 2.6.0: 50->150 -1 # ---------------------------------------------------------------------------------------------------------------- animateInFinished: ()-> Hy.Trace.debug "QuestionPage::animateInFinished (ENTER)" this.animateChildren({opacity: 1, duration: 100}) Hy.Utils.Deferral.create(100, ()=>PageState.get().resumed()) # ---------------------------------------------------------------------------------------------------------------- animateOut: (useCurtains = false)-> this.animateChildren({opacity: 0, duration: 50}) Hy.Utils.Deferral.create(50, ()=>@webViewPanel?.fireEvent({kind: "animateOut", data: {useCurtains: useCurtains}}, (event)=>this.animateOutFinished())) return -1 this.animateScenes(@animateOutScenes) @animateOutSceneDuration # ---------------------------------------------------------------------------------------------------------------- animateOutFinished: ()-> @window.setUIProperty("opacity", 0) Hy.Utils.Deferral.create(0, ()=>PageState.get().resumed()) # ---------------------------------------------------------------------------------------------------------------- dump: ()-> Hy.Trace.debug "QuestionPage::dump (Question=#{@contestQuestion.getQuestionID()}/#{@contestQuestion.getQuestionText()})" for i in [0..3] Hy.Trace.debug "QuestionPage::dump (#{i} #{@contestQuestion.getAnswerText(i)})" this # ---------------------------------------------------------------------------------------------------------------- labelColor: ()-> if @showingAnswers then Hy.UI.Colors.paleYellow else Hy.UI.Colors.white # ---------------------------------------------------------------------------------------------------------------- animateCountdown: (init, value)-> super color = Hy.UI.Colors.white if not init if not @showingAnswers if value <= Hy.Config.Dynamics.panicAnswerTime color = Hy.UI.Colors.MrF.Red # @questionLabel.setUIProperty("color", color) #TODO this # ---------------------------------------------------------------------------------------------------------------- countdownAnimationOptions: (value)-> _style: if @showingAnswers then "normal" else "frantic" # ---------------------------------------------------------------------------------------------------------------- # Called from ConsoleApp animateCountdownQuestionCompleted: ()-> this.getCountdownPanel().animateCountdown({_style: "completed"}) this # ---------------------------------------------------------------------------------------------------------------- webViewPanelCreate: ()-> options = this.containerOptions() options._tag = "WebViewPanel" # options.borderWidth = 10 # options.borderColor = Hy.UI.Colors.green webViewOptions = top: options.top left: options.left width: options.width height: options.height _tag: "Question Page Web View" scalesPageToFit:false url: "html-question-page.html" zIndex: 50 #@zIndexPassive backgroundColor:'transparent' # http://developer.appcelerator.com/question/45491/can-i-change-the-white-background-that-shows-when-a-web-view-is-loading @container.addChild(@webViewPanel = new Hy.Panels.WebViewPanel(options, webViewOptions)) this # ---------------------------------------------------------------------------------------------------------------- webViewPanelWait: (fn)-> Hy.Trace.debug "QuestionPage::webViewPanelWait (PAGE WAIT: WebViewInitialized=#{@webViewPanel.isInitialized()})" @webViewPanelFinishAnimateInFn = fn if @webViewPanel.isInitialized() this.webViewPanelFinishAnimation() else null null # ---------------------------------------------------------------------------------------------------------------- webViewPanelFinishAnimation: ()-> Hy.Trace.debug "QuestionPage::webViewPanelFinishAnimation (FINISH ANIMATION: WebViewInitialized=#{@webViewPanel.isInitialized()})" if @webViewPanelFinishAnimateInFn? if @webViewPanel.isInitialized() Hy.Trace.debug "QuestionPage::webViewPanelFinishAnimation (FINISHING ANIMATION)" @webViewPanelFinishAnimateInFn() @webViewPanelFinishAnimateInFn = null Hy.Utils.Deferral.create(@animateInSceneDuration, ()=>PageState.get().resumed()) else Hy.Trace.debug "QuestionPage::webViewPanelFinishAnimation (NO ANIMATION TO FINISH)" this # ---------------------------------------------------------------------------------------------------------------- webViewPanelContentInitialize: ()-> data = {} data.question = {} data.question.text = this.formatText(@contestQuestion.getQuestionText()).text code = switch (format = @contestQuestion.getContentPack().getFormatting("question")) when "bold" "b" when "italic" "i" when "none" null else "i" if code? data.question.text = "<#{code}>#{data.question.text}</#{code}>" data.answers = [] for i in [0..3] data.answers[i] = {} data.answers[i].text = this.formatText(@contestQuestion.getAnswerText(i)).text @webViewPanel.fireEvent({kind: "initializePage", data: data}, (event)=>this.webViewPanelContentInitialized()) this # ---------------------------------------------------------------------------------------------------------------- webViewPanelContentInitialized: ()-> Hy.Utils.Deferral.create(0, ()=>PageState.get().resumed()) null # ---------------------------------------------------------------------------------------------------------------- webViewPanelShowConsoleSelection: (indexSelectedAnswer)-> @webViewPanel.fireEvent({kind: "showConsoleSelection", data: {indexSelectedAnswer: indexSelectedAnswer}}) # ---------------------------------------------------------------------------------------------------------------- webViewPanelRevealAnswer: (indexCorrectAnswer)-> @webViewPanel.fireEvent({kind: "revealAnswer", data: {indexCorrectAnswer: indexCorrectAnswer}}) # ---------------------------------------------------------------------------------------------------------------- createQuestionBlock: ()-> #Hack to prevent user "copy" actions, since all other approaches aren't working overlayViewOptions = top: (@top += kQuestionBlockVerticalMargin) width: kQuestionBlockWidth height: kQuestionBlockHeight left: kQuestionBlockHorizontalMargin zIndex: @zIndexPassive + 1 _tag: "Question Block Blocker" @top += overlayViewOptions.height new Hy.UI.ViewProxy(overlayViewOptions) # ---------------------------------------------------------------------------------------------------------------- formatText: (text)-> output = "" chunks = text.split("|") for i in [1..chunks.length] if i > 1 # output += "\n" output += " " output += chunks[i-1] numLines = chunks.length if chunks[chunks.length-1].length is 0 numLines-- {numLines: numLines, text: output} # ---------------------------------------------------------------------------------------------------------------- createAnswerBlocks: ()-> answerItems = [ {index: 0, label: "A", height: kAnswerBlockHeight, width: kAnswerBlockWidth, left: 0, top: 0} {index: 1, label: "B", height: kAnswerBlockHeight, width: kAnswerBlockWidth, left: kAnswerBlockWidth + kAnswerBlockHorizontalPadding, top: 0} {index: 2, label: "C", height: kAnswerBlockHeight, width: kAnswerBlockWidth, left: 0, top: kAnswerBlockHeight + kAnswerBlockVerticalPadding} {index: 3, label: "D", height: kAnswerBlockHeight, width: kAnswerBlockWidth, left: kAnswerBlockWidth + kAnswerBlockHorizontalPadding, top: kAnswerBlockHeight + kAnswerBlockVerticalPadding} ] answerContainerOptions = top: (@top += kAnswerContainerVerticalMargin) left: kAnswerContainerHorizontalMargin height: kAnswerContainerHeight width: kAnswerContainerWidth _tag: "Answer Container" zIndex: @zIndexActive + 1 @answersContainer = new Hy.UI.ViewProxy(answerContainerOptions) @answerBlocks = [] this.createAnswerBlock(answerItem) for answerItem in answerItems @answersContainer # ---------------------------------------------------------------------------------------------------------------- answerBlockOptions: (answerItem)-> height : answerItem.height, width : answerItem.width, top : answerItem.top, left : answerItem.left, _tag : "Answer Container #{answerItem.label}" # ---------------------------------------------------------------------------------------------------------------- createAnswerBlock: (answerItem)-> # For direct play fnClick = (evt)=> this.answerBlockClicked(evt) answerBlockView = new Hy.UI.ViewProxy(this.answerBlockOptions(answerItem)) answerBlockView.addEventListener("click", fnClick) @answerBlocks.push {answerBlockView: answerBlockView, index: answerItem.index, label: answerItem.label} @answersContainer.addChild(answerBlockView) this # ---------------------------------------------------------------------------------------------------------------- answerBlockClicked: (evt)-> answerBlock = _.detect(@answerBlocks, (b)=>b.answerBlockView.getView() is evt.source) Hy.Trace.debug "QuestionPage::answerBlockClicked (label=#{if answerBlock? then answerBlock.label else "?"} allowEvents=#{this.getAllowEvents()} showingAnswers=#{@showingAnswers} consoleAnswered=#{@consoleAnswered} showingAnswersClicked=#{@showingAnswersClicked} PageState.state=#{PageState.get().getState()})" fn = null if this.getAllowEvents() if answerBlock? if @showingAnswers if not @showingAnswersClicked @showingAnswersClicked = true fn = ()=> Hy.Trace.debug "QuestionPage::answerBlockClicked (done showing answers)" this.getApp().questionAnswerCompleted() null else if not @consoleAnswered @consoleAnswered = true this.webViewPanelShowConsoleSelection(answerBlock.index) fn = ()=> Hy.Trace.debug "QuestionPage::answerBlockClicked (console answered)" this.getApp().consolePlayerAnswered(answerBlock.index) null if fn? this.haltCountdown() Hy.Utils.Deferral.create(0, ()=>fn()) null # ---------------------------------------------------------------------------------------------------------------- createAnswerCritterPanel: ()-> options = zIndex: @zIndexActive left: 0 bottom: 0 @container.addChild(@answerCritterPanel = new Hy.Panels.AnswerCritterPanel(options)) this # ---------------------------------------------------------------------------------------------------------------- countdownSound: (value)-> sound = null if not @showingAnswers and value isnt 0 sound = @soundKeys[@soundCounter++ % @nSounds] sound # ---------------------------------------------------------------------------------------------------------------- playerAnswered: (response)-> @answerCritterPanel.playerAnswered(response) # ---------------------------------------------------------------------------------------------------------------- revealAnswer: ()-> this.webViewPanelRevealAnswer(@contestQuestion.indexCorrectAnswer) # We want to display highest scorers first correct = [] incorrect = [] for response in Hy.Contest.ContestResponse.selectByQuestionID(@contestQuestion.getQuestionID()) if response.getCorrect() correct.push response else incorrect.push response sortedCorrect = correct.sort((r1, r2)=> r2.getScore() - r1.getScore()) topScore = null fnResponse = (response)=> # We want to display first place scorers differently t = if topScore? response.getScore() is topScore else topScore = response.getScore() true @answerCritterPanel.playerAnswered(response, true, t) for response in sortedCorrect fnResponse(response) for response in incorrect fnResponse(response) this # ================================================================================================================== class ContestCompletedPage extends NotifierPage # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app @top = 65 @defaultZIndex = 40 this.addBackground(@top) @top += 25 this.addGameOverText() this.addPlayAgainButtonAndText() # this.addAnimation() this # ---------------------------------------------------------------------------------------------------------------- addBackground: (top)-> @backgroundOptions = top: top height: 635 width: 800 image: "assets/icons/scoreboard-background.png" zIndex: @defaultZIndex-1 _tag: "Scoreboard Background" @container.addChild(new Hy.UI.ImageViewProxy(@backgroundOptions)) # ---------------------------------------------------------------------------------------------------------------- addGameOverText: ()-> height = 74 options = image: "assets/icons/label-Game-Over.png" top: @top height: 74 width: 374 zIndex: @defaultZIndex _tag: "Game Over Text" @top += height @container.addChild(@gameOverText = new Hy.UI.ImageViewProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- addPlayAgainButtonAndText: ()-> height = 72 buttonOptions = top: (@top += 20) height: height width: height backgroundImage: "assets/icons/button-play-small-blue.png" zIndex: @defaultZIndex _tag: "Play Again" @container.addChild(@playAgainButton = new Hy.UI.ButtonProxy(buttonOptions)) textOptions = top: @top height: height # width: 120 # borderColor: Hy.UI.Colors.white zIndex: @defaultZIndex padding = 20 this.addButtonText(Hy.UI.ViewProxy.mergeOptions(textOptions, {text: "play", textAlign: "right", right: (Hy.UI.iPad.screenWidth/2) + (height/2) + padding})) this.addButtonText(Hy.UI.ViewProxy.mergeOptions(textOptions, {text: "again", textAlign: "left", left: (Hy.UI.iPad.screenWidth/2) + (height/2) + padding})) @playAgainButtonClicked = false @fnClickPlayAgain = (evt)=> if not @playAgainButtonClicked @playAgainButtonClicked = true this.playAgainClicked() null @playAgainButton.addEventListener("click", @fnClickPlayAgain) @top += height this # ---------------------------------------------------------------------------------------------------------------- addButtonText: (options)-> defaultOptions = font: Hy.UI.Fonts.specBigMrF color: Hy.UI.Colors.white zIndex: @defaultZIndex + 1 _tag: "Button Text" @container.addChild(new Hy.UI.LabelProxy(Hy.UI.ViewProxy.mergeOptions(defaultOptions, options))) this # ---------------------------------------------------------------------------------------------------------------- createScoreboardCritterPanel: ()-> padding = 10 width = @backgroundOptions.width height = @backgroundOptions.height - ((@top - @backgroundOptions.top) + (2*padding)) scoreboardOptions = top: @top height: height width: width left: (Hy.UI.iPad.screenWidth - width)/2 zIndex: @defaultZIndex+2 _orientation: "horizontal" # borderWidth: 1 # borderColor: Hy.UI.Colors.red @container.addChild(@scoreboardCritterPanel = new Hy.Panels.ScoreboardCritterPanel(scoreboardOptions)) @scoreboardCritterPanel # ---------------------------------------------------------------------------------------------------------------- initialize: (fnNotify)-> super @playAgainButtonClicked = false # @nQuestions = nQuestions # @questionInfoPanel?.initialize @nQuestions, @nQuestions, this.labelColor() this.createScoreboardCritterPanel().initialize().displayScores() true # ---------------------------------------------------------------------------------------------------------------- start: ()-> super this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> if @scoreboardCritterPanel? this.container.removeChild(@scoreboardCritterPanel) @scoreboardCritterPanel.stop() @scoreboardCritterPanel = null super this # ---------------------------------------------------------------------------------------------------------------- playAgainClicked: ()-> Hy.Utils.Deferral.create(0, ()=>this.getApp().contestRestart(true)) # ---------------------------------------------------------------------------------------------------------------- getLeaderboard: ()-> @scoreboardCritterPanel?.getLeaderboard() # ---------------------------------------------------------------------------------------------------------------- addAnimation: ()-> # @animateInScenes = null @animateOutScenes = null animationContainerOptions = top: 0 left: 0 right: 0 bottom: 0 zIndex: 50 # [@animateInScenes, sceneTotalDuration] = this.buildAnimationFromScenes(this.initAnimateInScenes()) # [@animateOutScenes, @animateOutSceneDuration] = this.buildAnimationFromScenes(this.initAnimateOutScenes(), @animateoutScenes) this # ---------------------------------------------------------------------------------------------------------------- animateOut: ()-> [@animateOutScenes, @animateOutSceneDuration] = this.buildAnimationFromScenes(this.initAnimateOutScenes(), @animateoutScenes) this.animateScenes(@animateOutScenes) @animateOutSceneDuration # ---------------------------------------------------------------------------------------------------------------- initAnimateOutScenes: ()-> [ {image: "intro-TV", imageOptions: {zIndex: 50}, animationOptions: [{_incrementalDelay: 0, duration: 0, opacity: 1.0}]} # {image: "black", imageOptions: {zIndex: 49, top: 0, left: 0, right: 0, bottom: 0, opacity: 0}, animationOptions: [{_incrementalDelay: 0, duration: 1500, opacity: 1.0}, {_incrementalDelay: 500, duration: 0, opacity: 0}]} {image: "intro-left-front-curtain", imageOptions: {zIndex: 45, top: 0, width:514, height:768, right: Hy.UI.iPad.screenWidth, borderColor: Hy.UI.Colors.white}, animationOptions: [{_incrementalDelay: 0, duration: 1500, right: Hy.UI.iPad.screenWidth/2}, {_incrementalDelay: 0, duration: 100, right: Hy.UI.iPad.screenWidth}]} {image: "intro-right-front-curtain", imageOptions: {zIndex: 45, top: 0, width:514, height:768, left: Hy.UI.iPad.screenWidth, borderColor: Hy.UI.Colors.white}, animationOptions: [{_incrementalDelay: 0, duration: 1500, left: (Hy.UI.iPad.screenWidth/2)-5}, {_incrementalDelay: 0, duration: 100, left: Hy.UI.iPad.screenWidth}]} ] # ================================================================================================================== class PageState gOperationIndex = 0 @Any = -1 @Unknown = 0 @Splash = 1 @Intro = 2 @Start = 3 @Question = 4 @Answer = 5 @Scoreboard = 6 @Completed = 7 @About = 8 @UCCInfo = 9 @JoinCodeInfo = 10 stateToPageClassMap = [ {state: PageState.Splash, pageClass: SplashPage, background: Hy.UI.Backgrounds.splashPage}, {state: PageState.Intro, pageClass: IntroPage, background: null}, {state: PageState.Start, pageClass: StartPage, background: Hy.UI.Backgrounds.startPage} {state: PageState.Question, pageClass: QuestionPage, background: Hy.UI.Backgrounds.stageNoCurtain} {state: PageState.Answer, pageClass: QuestionPage, background: Hy.UI.Backgrounds.stageNoCurtain} {state: PageState.Completed, pageClass: ContestCompletedPage, background: Hy.UI.Backgrounds.stageCurtain} {state: PageState.About, pageClass: AboutPage, background: Hy.UI.Backgrounds.startPage} {state: PageState.UCCInfo, pageClass: UserCreatedContentInfoPage, background: Hy.UI.Backgrounds.startPage} {state: PageState.JoinCodeInfo, pageClass: JoinCodeInfoPage, background: Hy.UI.Backgrounds.startPage} ] @defaultAnimateOut = {duration: 250, _startOpacity: 1, opacity: 0} @defaultAnimateIn = {duration: 250, _startOpacity: 0, opacity: 1} transitionMaps = [ { oldState: [PageState.Any], newState: [PageState.Splash], animateOutBackground: Hy.UI.Backgrounds.splashPage, interstitialBackground: Hy.UI.Backgrounds.splashPage, animateInBackground: Hy.UI.Backgrounds.splashPage }, { oldState: [PageState.Splash], newState: [PageState.Intro], animateOutBackground: Hy.UI.Backgrounds.splashPage, interstitialBackground: Hy.UI.Backgrounds.splashPage, animateInBackground: Hy.UI.Backgrounds.splashPage, animateInFn: ((page)=>page.animateIn()), }, { oldState: [PageState.Intro], newState: [PageState.Start], animateOutFn: ((page)=>page.animateOut()), animateOutBackground: Hy.UI.Backgrounds.splashPage, interstitialBackground: Hy.UI.Backgrounds.splashPage, animateInBackground: Hy.UI.Backgrounds.splashPage, animateIn: {duration: 500, _startOpacity: 0, opacity: 1} }, { # 2.5.0: To handle case where we're backgrounded. See ConsoleApp::resumedPage for details oldState: [PageState.Any], newState: [PageState.Start], interstitialBackground: Hy.UI.Backgrounds.splashPage, animateInBackground: Hy.UI.Backgrounds.splashPage, animateIn: {duration: 500, _startOpacity: 0, opacity: 1} }, { oldState: [PageState.Start], newState: [PageState.Question], animateOut: {duration: 500, opacity: 0}, animateInFn: ((page)=>page.animateIn(true)) }, { oldState: [PageState.Question], newState: [PageState.Answer], animateOut: null, delay: 500, animateIn: null }, { oldState: [PageState.Answer], newState: [PageState.Question], animateOutFn: ((page)=>page.animateOut(false)), animateInFn: ((page)=>page.animateIn(false)), }, { oldState: [PageState.Question, PageState.Answer], newState: [PageState.Completed], animateOutFn: ((page)=>page.animateOut(true)), animateIn: {duration: 500, _startOpacity: 0, opacity: 1} }, { oldState: [PageState.Question, PageState.Answer], newState: [PageState.Start], animateOutFn: ((page)=>page.animateOut(true)), animateIn: @defaultAnimateIn, }, { oldState: [PageState.Completed], newState: [PageState.Start], animateOut: @defaultAnimateOut, animateIn: @defaultAnimateIn, }, { oldState: [PageState.About, PageState.Start], newState: [PageState.Start, PageState.About], animateOut: @defaultAnimateOut, animateIn: @defaultAnimateIn, }, { oldState: [PageState.UCCInfo, PageState.Start], newState: [PageState.Start, PageState.UCCInfo], animateOut: @defaultAnimateOut, animateIn: @defaultAnimateIn, }, { oldState: [PageState.JoinCodeInfo, PageState.Start], newState: [PageState.Start, PageState.JoinCodeInfo], animateOut: @defaultAnimateOut, animateIn: @defaultAnimateIn, } ] gInstance = null # ---------------------------------------------------------------------------------------------------------------- @findTransitionMap: (oldPage, newPageState)-> for map in transitionMaps if (oldPage? and oldPage.state in map.oldState) or (PageState.Any in map.oldState) # 2.5.0 if (newPageState in map.newState) or (PageState.Any in map.newState) # 2.5.0 return map return null # ---------------------------------------------------------------------------------------------------------------- @getPageMap: (pageState)-> for map in stateToPageClassMap if map.state is pageState return map return null # ---------------------------------------------------------------------------------------------------------------- @getPageName: (pageState)-> name = null map = this.getPageMap(pageState) if map? name = map.pageClass.name return name # ---------------------------------------------------------------------------------------------------------------- @findPage: (pageState)-> page = if (map = this.getPageMap(pageState))? Page.findPage(map.pageClass) else null page # ---------------------------------------------------------------------------------------------------------------- @getPage: (pageState)-> page = if (map = this.getPageMap(pageState))? Page.getPage(map) else null page # ---------------------------------------------------------------------------------------------------------------- @get: ()-> gInstance # ---------------------------------------------------------------------------------------------------------------- @doneWithPage: (pageState)-> if (map = this.getPageMap(pageState))? Page.doneWithPage(map) null # ---------------------------------------------------------------------------------------------------------------- @init: (app)-> if not gInstance? gInstance = new PageState(app) gInstance # ---------------------------------------------------------------------------------------------------------------- display: ()-> s = "PageState::display" s += "(" if (state = this.getState())? s += "#{state.oldPageState}->#{state.newPageState}" s += ")" s # ---------------------------------------------------------------------------------------------------------------- constructor: (@app)-> this.initialize() this # ---------------------------------------------------------------------------------------------------------------- initialize: ()-> @state = null timedOperation = new Hy.Utils.TimedOperation("PAGE INITIALIZATION") for map in transitionMaps for v in ["videoOut", "videoIn"] if (videoOptions = map[v])? timedOperation.mark("video: #{videoOptions._url}") map["_#{v}Instance"] = player = Hy.Media.VideoPlayer.create(videoOptions) # player.prepareToPlay().play() timedOperation.mark("DONE") this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> if (page = this.getApp().getpage())? page?.closeWindow() page?.stop() this.getApp().setPage(null) this # ---------------------------------------------------------------------------------------------------------------- getApp: ()-> @app # ---------------------------------------------------------------------------------------------------------------- getState: ()-> @state # ---------------------------------------------------------------------------------------------------------------- setState: (state)-> @state = state # ---------------------------------------------------------------------------------------------------------------- isTransitioning: ()-> if (state = this.getState(false))? state.newPageState else null # ---------------------------------------------------------------------------------------------------------------- getOldPageState: ()-> this.getState()?.oldPageState # ---------------------------------------------------------------------------------------------------------------- stopTransitioning: ()-> this.setState(null) # ---------------------------------------------------------------------------------------------------------------- addPostTransitionAction: (fnPostTransition)-> if (state = this.getState())? @postFunctions.push(fnPostTransition) this # ---------------------------------------------------------------------------------------------------------------- hasPostFunctions: ()-> _.size(@postFunctions) > 0 # ---------------------------------------------------------------------------------------------------------------- # I've re-written this function about 5 times so far. "This time for sure". # I've re-written this function about 6 times so far. "This time for sure". # showPage: (newPageState, fn_newPageInit, postFunctions = [])-> initialState = oldPage: this.getApp().getPage() # newPage: Hy.Pages.PageState.getPage(newPageState) newPage_: null # defer creating the new page oldPageState: (if (oldPage = this.getApp().getPage())? then oldPage.getState() else null) newPageState: newPageState fn_newPageInit: fn_newPageInit if (existingState = this.getState())? s = "OLD STATE: oldPageState=#{if existingState.oldPage? then existingState.oldPage.getState() else "(NONE)"} newPageState=#{existingState.newPageState}" s += " NEW STATE: oldPageState=#{if initialState.oldPage? then initialState.oldPage.getState() else "(NONE)"} newPageState=#{initialState.newPageState}" Hy.Trace.debug "PageState::showPage (RECURSION #{s})", true new Hy.Utils.ErrorMessage("fatal", "PageState::showPage", s) return @postFunctions = [].concat(postFunctions) this.setState(this.showPage_setup(initialState)) this.showPage_execute() this # ---------------------------------------------------------------------------------------------------------------- showPage_setup: (state)-> state.spec = Hy.Pages.PageState.findTransitionMap(state.oldPage, state.newPageState) state.delay = if state.spec? then (if state.spec.delay? then state.spec.delay else 0) else 0 state.exitVideo = if state.spec? then state.spec._videoOutInstance else null state.introVideo = if state.spec? then state.spec._videoInInstance else null state.animateOut = if state.spec? then state.spec.animateOut else Hy.Pages.PageState.defaultAnimateOut state.animateOutFn = if state.spec? then state.spec.animateOutFn state.animateInFn = if state.spec? then state.spec.animateInFn state.animateIn = if state.spec? then state.spec.animateIn else Hy.Pages.PageState.defaultAnimateIn state.previousVideo = null state.networkServiceLevel = null state.operationIndex = ++gOperationIndex # For logging state.fnIndex = 0 # state.fnCompleted = false fnDebug = (fnName, s="")=> p = "" if (state = this.getState())? p += "##{state.operationIndex} fn:#{state.fnIndex} " p += if (oldPageState = this.getState().oldPageState)? then oldPageState else "NONE" p += ">#{this.getState().newPageState}" else p = "(NO STATE!)" Hy.Trace.debug("PageState::showPage (#{p} #{fnName} #{if s? then s else ""})") null fnExecuteNext = (restart = false)=> ok = false if (state = this.getState())? if restart and not state.fnCompleted # Try the last operation again null else ++state.fnIndex if state.fnIndex <= state.fnChain.length state.fnCompleted = false ok = true state.fnChain[state.fnIndex-1]() state.fnCompleted = true ok fnExecutePostFunction = ()=> if (f = @postFunctions.shift())? f(this.getApp().getPage()) null fnExecuteRemaining = ()=> if (state = this.getState())? while fnExecuteNext() null this.showPage_exit(state.operationIndex) while _.size(@postFunctions) > 0 fnExecutePostFunction() null fnIndicateActive = ()=> Hy.Network.NetworkService.setIsActive() fnExecuteNext() null fnSuspendNetwork = ()=> fnDebug("fnSuspendNetwork") if (ns = Hy.Network.NetworkService.get())? l = this.getState().networkServiceLevel = ns.getServiceLevel() fnDebug("fnSuspendNetwork (from \"#{l}\")") ns.setSuspended() fnExecuteNext() null fnResumeNetwork = ()=> fnDebug("fnResumeNetwork") if (serviceLevel = this.getState().networkServiceLevel)? Hy.Network.NetworkService.get().setServiceLevel(serviceLevel) fnExecuteNext() null # Returns existing instance of this kind of page, if it exists. fnCheckNewPage = ()=> Hy.Pages.PageState.findPage(state.newPageState) fnGetNewPage = ()=> this.getState().newPage_ fnCreateNewPage = ()=> s = this.getState() if not s.newPage_? s.newPage_ = Hy.Pages.PageState.getPage(state.newPageState) s.newPage_ fnSetBackground = (backgroundName = null)=> fnDebug("fnSetBackground", backgroundName) bkgnd = if backgroundName? then this.getState().spec?[backgroundName] else null this.getApp().setBackground(bkgnd) fnExecuteNext() fnCleanupVideo = (video)=> fnDebug("fnCleanupVideo") video.setUIProperty("borderColor", Hy.UI.Colors.green) fnExecuteNext() null fnPlayVideo = (video, preBackground, postBackground)=> fnDebug("fnPlayVideo") if this.getState().previousVideo? this.getState().previousVideo.release() video.setVideoProperty("backgroundImage", preBackground) f = ()=>fnCleanupVideo(video) video.prepareToPlay(f) this.getApp().getBackgroundWindow().add(video.getView()) this.getApp().setBackground(postBackground) video.setUIProperty("borderColor", Hy.UI.Colors.white) video.play() video.setUIProperty("borderColor", Hy.UI.Colors.red) this.getState().previousVideo = video null fnStopOldPage = ()=> fnDebug("fnStopOldPage") this.getState().oldPage?.stop() fnExecuteNext() null fnAnimateOut = ()=> fnDebug("fnAnimateOut") duration = 0 if (oldPage = this.getState().oldPage)? animateOut = this.getState().animateOut animateOutFn = this.getState().animateOutFn if animateOut? if animateOut._startOpacity? oldPage.window.setUIProperty("opacity", animateOut._startOpacity) oldPage.animateWindow(animateOut) duration = animateOut.duration else if animateOutFn? duration = animateOutFn(oldPage) if duration is -1 # -1 means we'll get called back to resume page transition fnDebug("fnAnimateOut", "WAITING") else Hy.Utils.Deferral.create(duration, fnExecuteNext) null fnCloseOldPage = ()=> fnDebug("fnCloseOldPage") if (oldPage = this.getState().oldPage)? newPage = fnCheckNewPage() # Might be null if page hasn't been created/used before #this.getState().newPage if oldPage isnt newPage oldPage.closeWindow() this.getApp().setPage(null) fnExecuteNext() null fnPlayExitVideo = ()=> fnDebug("fnPlayExitVideo") if this.getState().exitVideo? fnPlayVideo(this.getState().exitVideo, this.getState().spec.animateOutBackground, this.getState().spec.interstitialBackground) else fnExecuteNext() null fnPlayIntroVideo = ()=> fnDebug("fnPlayIntroVideo") if this.getState().introVideo? fnPlayVideo(this.getState().introVideo, this.getState().spec.interstitialBackground, this.getState().spec.animateInBackground) else fnExecuteNext() null fnInitNewPage = ()=> fnDebug("fnInitNewPage") newPage = fnCreateNewPage() #this.getState().newPage this.getApp().setPage(newPage) newPage.setState(this.getState().newPageState) if (result = this.getState().fn_newPageInit(newPage)) fnExecuteNext() else fnDebug("fnInitNewPage: waiting") fnAnimateInAndOpenNewPage = ()=> fnDebug("fnAnimateInAndOpenNewPage") duration = 0 newPage = fnGetNewPage() #this.getState().newPage animateIn = this.getState().animateIn animateInFn = this.getState().animateInFn if animateIn? duration = animateIn.duration if animateIn._startOpacity? newPage.window.setUIProperty("opacity", animateIn._startOpacity) if newPage is this.getState().oldPage newPage.animateWindow(animateIn) else newPage.openWindow(animateIn) else if animateInFn? # if newPage isnt this.getState().oldPage # newPage.openWindow() duration = animateInFn(newPage) else if newPage isnt this.getState().oldPage newPage.openWindow({opacity:1, duration:0}) else newPage.animateWindow({opacity:1, duration:0}) if duration is -1 # -1 means we'll get called back to resume page transition fnDebug("fnAnimateInAndOpenNewPage", "Waiting for callback") else fnDebug("fnAnimateInAndOpenNewPage", "Waiting #{duration}") Hy.Utils.Deferral.create(duration, fnExecuteNext) null fnStartNewPage = ()=> fnDebug("fnStartNewPage") fnGetNewPage().start() fnExecuteNext() null # We do it this way since it makes it easier to change the order and timing of things, # and ensure the integrity of the transition across pause/resumed state.fnChain = # 2.5.0: removed default fnChain... [ fnSuspendNetwork, fnStopOldPage, fnAnimateOut, ()=>fnSetBackground("animateOutBackground"), fnCloseOldPage, fnPlayExitVideo, ()=>fnSetBackground("interstitialBackground"), ()=>Hy.Utils.Deferral.create(this.getState().delay, fnExecuteNext), fnPlayIntroVideo, ()=>fnSetBackground("animateInBackground"), fnInitNewPage, fnAnimateInAndOpenNewPage, ()=>fnSetBackground(), # ()=>Hy.Utils.Deferral.create(0, fnStartNewPage), # 2.5.0 fnStartNewPage, fnResumeNetwork, fnIndicateActive, fnExecuteRemaining ] state.fnExecuteNext = fnExecuteNext state # ---------------------------------------------------------------------------------------------------------------- showPage_execute: (restart = false)-> @state?.fnExecuteNext(restart) this # ---------------------------------------------------------------------------------------------------------------- showPage_exit: (operationIndex)-> Hy.Trace.debug "PageState::showPage_exit (##{operationIndex})" this.setState(null) # ---------------------------------------------------------------------------------------------------------------- resumed: (restart = false)-> Hy.Trace.debug "PageState::resumed" if this.getState()? this.showPage_execute(restart) else if (page = this.getApp().getPage())? page.resumed() else Hy.Trace.debug "PageState::showPage (RESUMED BUT NO WHERE TO GO)" null # ================================================================================================================== Hyperbotic.Pages = Page: Page NotifierPage: NotifierPage IntroPage: IntroPage SplashPage: SplashPage AboutPage: AboutPage UserCreatedContentInfoPage: UserCreatedContentInfoPage StartPage: StartPage QuestionPage: QuestionPage ContestCompletedPage: ContestCompletedPage PageState: PageState CountdownPage: CountdownPage
true
# ================================================================================================================== class CountdownTicker # ---------------------------------------------------------------------------------------------------------------- constructor: (@fnInitView, @fnUpdateView, @fnCompleted, @fnSound)-> this # ---------------------------------------------------------------------------------------------------------------- init: (@value, startingDelay)-> @startValue = @value this.clearTimers() this.display true fnTick = ()=> this.tick() f = ()=> this.display false @countdownInterval = setInterval fnTick, 1000 @startingDelay = null if startingDelay > 0 @startingDelay = Hy.Utils.Deferral.create startingDelay, f else f() this # ---------------------------------------------------------------------------------------------------------------- getValue: ()-> @value # ---------------------------------------------------------------------------------------------------------------- clearTimers: ()-> if @countdownInterval? clearInterval(@countdownInterval) @countdownInterval = null if @startingDelay? @startingDelay.clear() @startingDelay = null this # ---------------------------------------------------------------------------------------------------------------- display: (init)-> if init @fnInitView @value else @fnSound @value @fnUpdateView @value this # ---------------------------------------------------------------------------------------------------------------- exit: ()-> this.pause() @value = null null # ---------------------------------------------------------------------------------------------------------------- pause: ()-> this.clearTimers() this # ---------------------------------------------------------------------------------------------------------------- continue_: ()-> this.init(@value||@startValue, 0) # ---------------------------------------------------------------------------------------------------------------- reset: ()-> @value = @startValue || 10 # TODO: should get default value from app # ---------------------------------------------------------------------------------------------------------------- tick: ()-> @value -= 1 if @value >= 0 this.display false if @value <= 0 this.exit() @fnCompleted(source:this) this # ================================================================================================================== # # # zIndex scheme: # windows: 1-10 # page-owned stuff: 50-100 # overlays, buttons, other clickbale stuff: 101+ # # Lifecycle of a Page: # created # initialize # open # start # ... # close # stop # # also: # pause # resumed # class Page gInstanceCount = 0 gPages = [] # ---------------------------------------------------------------------------------------------------------------- @findPage: (pageClass)-> for page in gPages if page.constructor.name is pageClass.name return page null # ---------------------------------------------------------------------------------------------------------------- @getPage: (pageMap)-> p = (Page.findPage(pageMap.pageClass)) || new pageMap.pageClass(pageMap.state, Hy.ConsoleApp.get()) p # ---------------------------------------------------------------------------------------------------------------- # NOT IMPLEMENTED @doneWithPage: (pageMap)-> if (p = Page.findPage(pageMap.pageClass)) gPages = gPages.reject(p) p.doneWithPage() null # ---------------------------------------------------------------------------------------------------------------- constructor: (@state, @app)-> @instance = ++gInstanceCount gPages.push this options = fullscreen: true zIndex: 2 orientationModes: [Ti.UI.LANDSCAPE_LEFT, Ti.UI.LANDSCAPE_RIGHT] opacity: 0 _tag: "Main Window" @window = new Hy.UI.WindowProxy(options) @window.addChild(@container = new Hy.UI.ViewProxy(this.containerOptions())) @container.addChild(this.createAnimationContainer()) # @window.setTrace("opacity") this # ---------------------------------------------------------------------------------------------------------------- initialize: ()-> # We do this here since a page's state can change (since pages can be reused, such as Question) @container.setUIProperty("backgroundImage", if (background = PageState.getPageMap(this.getState()).background)? then background else null) @allowEvents = false true # ---------------------------------------------------------------------------------------------------------------- getAllowEvents: ()-> @allowEvents # ---------------------------------------------------------------------------------------------------------------- getState: ()-> @state # ---------------------------------------------------------------------------------------------------------------- setState: (state)-> @state = state # ---------------------------------------------------------------------------------------------------------------- getWindow: ()->@window # ---------------------------------------------------------------------------------------------------------------- getApp: ()-> @app # ---------------------------------------------------------------------------------------------------------------- obs_networkChanged: (reason)-> this # ---------------------------------------------------------------------------------------------------------------- openWindow: (options={})-> @window.open(options) this # ---------------------------------------------------------------------------------------------------------------- closeWindow: (options={})-> @window.close() this # ---------------------------------------------------------------------------------------------------------------- animateWindow: (options)-> # 2.5.0 @window.animate(options) this # ---------------------------------------------------------------------------------------------------------------- start: ()-> @allowEvents = true this.setStopAnimating(false) this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> @allowEvents = false this.setStopAnimating(true) this # ---------------------------------------------------------------------------------------------------------------- pause: ()-> this # ---------------------------------------------------------------------------------------------------------------- resumed: ()-> this # ---------------------------------------------------------------------------------------------------------------- containerOptions: ()-> top: 0 left: 0 width: Hy.UI.iPad.screenWidth # must set these, else _layout{vertical, horizontal} directives wont work height: Hy.UI.iPad.screenHeight zIndex: 101 _tag: "Main Container" # ---------------------------------------------------------------------------------------------------------------- createAnimationContainer: ()-> animationContainerOptions = top: 0 left: 0 right: 0 bottom: 0 zIndex: 200 opacity: 1 _tag: "Animation Container" @animationContainer = new Hy.UI.ViewProxy(animationContainerOptions) @animationContainer.hide() @animationContainerHidden = true @animationContainer # ---------------------------------------------------------------------------------------------------------------- buildAnimationFromScenes: (scenes, previousScenes = null)-> sceneTotalDuration = 0 currentStart = 0 for scene in scenes sceneDuration = 0 sceneCurrentStart = 0 sceneFirstStart = null for animationOption in scene.animationOptions sceneCurrentStart += animationOption._incrementalDelay if not sceneFirstStart? sceneFirstStart = sceneCurrentStart if not animationOption.duration? animationOption.duration = 0 sceneDuration = Math.max(sceneDuration, sceneCurrentStart + animationOption.duration) aOptions = delay: currentStart + sceneCurrentStart animationOption._animationObjectOptions = Hy.UI.ViewProxy.mergeOptions(animationOption, aOptions) computedOptions = Hy.UI.ViewProxy.mergeOptions(scene.imageOptions, {}) #make a copy createdNewScene = true if previousScenes? if(existingScene = _.detect(previousScenes, (s)=>s.image is scene.image))? createdNewScene = false scene._view = existingScene._view scene._view.setUIProperties(computedOptions) if not scene._view? computedOptions._tag = "Animation" if scene.image? computedOptions.image = "assets/bkgnds/animations/#{scene.image}.png" scene._view = new Hy.UI.ImageViewProxy(computedOptions) else if scene.method? scene._view = scene.method(computedOptions) else Hy.Trace.debug "Page::buildAnimationFromScenes (NO SCENE IMAGE OR METHOD)" # STOP events don't seem to be getting fired. The below callback is never called. if scene._view? and createdNewScene scene._view.addEventListener("stop", (evt, view)=>Hy.Trace.debug("ANIMATION STOP EVENT (#{scene.image} view=#{view?.getTag()}")) sceneTotalDuration = Math.max(sceneTotalDuration, currentStart + sceneDuration) currentStart += sceneFirstStart [scenes, sceneTotalDuration] # ---------------------------------------------------------------------------------------------------------------- setStopAnimating: (flag)-> @stopAnimating = flag # ---------------------------------------------------------------------------------------------------------------- clearAnimation: ()-> Hy.Trace.debug "Page::hideAnimation (CLEARING ANIMATION CONTAINER)" this.hideAnimation() @animationContainer.removeChildren() this # ---------------------------------------------------------------------------------------------------------------- hideAnimation: ()-> Hy.Trace.debug "Page::hideAnimation (HIDING ANIMATION CONTAINER)" @animationContainer?.hide() @animationContainerHidden = true this # ---------------------------------------------------------------------------------------------------------------- animateScenes: (scenes)-> this.setStopAnimating(false) @animationOpenedWindow = false for scene in scenes this.animateScene(scenes, scene, 0) this # ---------------------------------------------------------------------------------------------------------------- animateScene: (scenes, scene, index)-> animationOption = scene.animationOptions[index] animationOption._animationObject = null #TEST imageOptions = {} if animationOption._startOpacity? imageOptions.opacity = animationOption._startOpacity else if animationOption.opacity? imageOptions.opacity = 0 scene._view.setUIProperties(imageOptions) if @animationContainerHidden @animationContainerHidden = false @animationContainer.show() if not @animationContainer.hasChild(scene._view) @animationContainer.addChild(scene._view) Hy.Trace.debug "Page::animateScene (BEGIN ANIMATE #{scene.image} ##{index})" if not @animationOpenedWindow @window.setUIProperty("opacity", 1.0) this.openWindow() @animationOpenedWindow = true animateFn = ()=> Hy.Trace.debug "Page::animateScene (CONTINUING ANIMATION #{scene.image})" animationOption._animationObject = Ti.UI.createAnimation(animationOption._animationObjectOptions) animationOption._animationObject.addEventListener("complete", (evt)=>this.animateCompleteEvent(evt.source, scenes)) scene._view.animate(animationOption._animationObject) null # Note that this is a hack and won't work as intended if there are multiple scenes to be animated if (fn = animationOption._waitForWindowFn)? Hy.Utils.Deferral.create(0, ()=>fn(animateFn)) else animateFn() this # ---------------------------------------------------------------------------------------------------------------- # TODO: it's possible that our version of the properties of an object that's been animated may no longer # reflect reality, at the end of an animation. Should really set UIProperties at the end, here. animateCompleteEvent: (animationObject, scenes)-> for scene in scenes index = -1 for animationOption in scene.animationOptions index++ if animationOption._animationObject is animationObject if index < (_.size(scene.animationOptions)-1) if @stopAnimating Hy.Trace.debug "Page::animateCompleteEvent (ANIMATION STOPPED #{scene.image})" else Hy.Trace.debug "Page::animateCompleteEvent (ANIMATION COMPLETED FOR #{scene.image} ##{index}, continuing)" this.animateScene(scenes, scene, index+1) else # if we're here, we're done with this scene. But we can't necessarily remove the scene's view. Hy.Trace.debug "Page::animateCompleteEvent (ANIMATION COMPLETED #{scene.image})" # @animationContainer.removeChild(scene._view) return this this # ================================================================================================================== class SplashPage extends Page # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app # @container.addChild(this.createJewelContainer()) this # ---------------------------------------------------------------------------------------------------------------- createJewelContainer: ()-> defaultOptions = image: "assets/icons/trivially-01.png" height: 100 width: 100 _tag: "Jewel Container" @jewelView = new Hy.UI.ImageViewProxy(defaultOptions) @jewelView # ---------------------------------------------------------------------------------------------------------------- initialize: (fnReady)-> super true # ---------------------------------------------------------------------------------------------------------------- start: ()-> super this # ================================================================================================================== class IntroPage extends Page # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app this.webViewPanelCreate() this.addClick() this # ---------------------------------------------------------------------------------------------------------------- openWindow: (options={})-> super options @webView?.open() this # ---------------------------------------------------------------------------------------------------------------- closeWindow: (options={})-> @webViewPanel?.close() super this # ---------------------------------------------------------------------------------------------------------------- initialize: (fnReady)-> super @fnReady = fnReady @clicked = false @clickAllowed = true @finishingUp = false @finishedAnimatingIn = false # apparently, the window has to be open in order for the webview to work... # @window.setUIProperty("opacity", 0) this.openWindow() @webViewPanel?.initialize( (event)=>Hy.Utils.Deferral.create(0, ()=>PageState.get().resumed()) ) @introPanel?.initialize() # Not likely false # Wait # ---------------------------------------------------------------------------------------------------------------- start: ()-> super # @clickAllowed = true @webView?.start() this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> @clickAllowed = false @webView?.stop() super this # ---------------------------------------------------------------------------------------------------------------- resumed: ()-> super this # ---------------------------------------------------------------------------------------------------------------- obs_networkChanged: (reason)-> super @introPanel?.obs_networkChanged(reason) this # ---------------------------------------------------------------------------------------------------------------- setStopAnimating: (flag)-> super if not @finishedAnimatingIn @webViewPanel?.fireEvent({kind: "stopAnimating"}, (event)=>this.animateInFinished()) this # ---------------------------------------------------------------------------------------------------------------- addClick: ()-> options = top: 0 bottom: 0 right: 0 left: 0 zIndex: @animationContainer.getUIProperty("zIndex") + 1 _tag: "Click Container" @container.addChild(v = new Hy.UI.ViewProxy(options)) fnClick = (evt)=> if not @clicked and @clickAllowed @clicked = true @finishingUp = true if (pageState = PageState.get()).isTransitioning() Hy.Trace.debug("IntroPage::addClick (WAITING FOR TRANSITION)") pageState.addPostTransitionAction(()=>@fnReady?()) this.setStopAnimating(true) else Hy.Trace.debug("IntroPage::addClick (NOT TRANSITIONING)") this.animateOutIntroPanelAndTitle() @fnReady?() null v.addEventListener("click", fnClick) this # ---------------------------------------------------------------------------------------------------------------- addTitle: ()-> options = top: 140 # 170 # 2.5.0 left: (Hy.UI.iPad.screenWidth-315)/2 image: "assets/bkgnds/animations/label-Trivially.png" width: 315 height: 100 zIndex: 102 opacity: 0 _tag: "Title" @container.addChild(@title = new Hy.UI.ImageViewProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- addIntroPanel: ()-> options = top: 260 # 290 # 2.5.0 zIndex: 102 touchEnabled: false opacity: 0 @container.addChild(@introPanel = new Hy.Panels.IntroPanel(options)) @introPanel.initialize() this # ---------------------------------------------------------------------------------------------------------------- animateInFinished: ()-> if not @finishingUp and not @introPanel? this.addTitle() this.addIntroPanel() this.animateInIntroPanelAndTitle() @finishedAnimatingIn = true Hy.Utils.Deferral.create(0, ()=>PageState.get().resumed()) # ---------------------------------------------------------------------------------------------------------------- animateIn: ()-> @webViewPanel?.fireEvent({kind: "animateIn"}, (event)=>this.animateInFinished()) this.animateWindow({opacity: 1, duration: 0}) return -1 # ---------------------------------------------------------------------------------------------------------------- animateInIntroPanelAndTitle: ()-> @introPanel?.animate({opacity:1, duration: 100}) @title?.animate({opacity:1, duration: 100}) this # ---------------------------------------------------------------------------------------------------------------- animateOutIntroPanelAndTitle: (fnDone = null)-> Hy.Trace.debug("IntroPage::animateOutIntroPanelAndTitle") animateCount = 0 fn = (evt)=> Hy.Trace.debug("IntroPage::animateOutIntroPanelAndTitle (#{animateCount})") if ++animateCount is 2 fnDone?() null if true @introPanel?.animate({opacity:0, duration: 50}, fn) @title?.animate({opacity:0, duration: 50}, fn) else @introPanel?.setUIProperty("opacity", 0) @title?.setUIProperty("opacity", 0) fnDone?() this # ---------------------------------------------------------------------------------------------------------------- animateOut: ()-> Hy.Trace.debug("IntroPage::animateOut") @clickAllowed = false fn = ()=> @webViewPanel?.fireEvent({kind: "animateOut"}, (event)=>this.animateOutFinished()) null this.animateOutIntroPanelAndTitle(fn) return -1 # ---------------------------------------------------------------------------------------------------------------- animateOut2: ()-> @clickAllowed = false @webViewPanel?.fireEvent({kind: "animateOut"}, (event)=>this.animateOutFinished()) @introPanel?.animate({opacity:0, duration: 100}) @title?.animate({opacity:0, duration: 100}) return -1 # ---------------------------------------------------------------------------------------------------------------- animateOutFinished: ()-> duration = 0 this.animateWindow({opacity: 0, duration: duration}) # 2.5.0 Hy.Utils.Deferral.create(duration, ()=>PageState.get().resumed()) this # ---------------------------------------------------------------------------------------------------------------- webViewPanelCreate: ()-> options = this.containerOptions() options._tag = "WebViewPanel" # options.borderWidth = 10 # options.borderColor = Hy.UI.Colors.green webViewOptions = top: options.top left: options.left width: options.width height: options.height _tag: "Intro Page Web View" scalesPageToFit:false url: "html-intro-page.html" zIndex: 50 #@zIndexPassive backgroundColor:'transparent' # http://developer.appcelerator.com/question/45491/can-i-change-the-white-background-that-shows-when-a-web-view-is-loading @container.addChild(@webViewPanel = new Hy.Panels.WebViewPanel(options, webViewOptions)) this # ---------------------------------------------------------------------------------------------------------------- # Bummed. PI:NAME:<NAME>END_PI just died. 2011 Oct 5. # ---------------------------------------------------------------------------------------------------------------- # ================================================================================================================== class UtilityPage extends Page # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> @subpanels = [] super state, app this.addCrowdGameLogo() .addTitle() this # ---------------------------------------------------------------------------------------------------------------- addSubpanel: (subpanel)-> @container.addChild(subpanel) @subpanels.push subpanel this # ---------------------------------------------------------------------------------------------------------------- containerOptions: ()-> options = super options.zIndex = 90 options # ---------------------------------------------------------------------------------------------------------------- initialize: ()-> super for panel in @subpanels panel.initialize() true # ---------------------------------------------------------------------------------------------------------------- obs_networkChanged: (reason)-> super for panel in @subpanels panel.obs_networkChanged(reason) this # ---------------------------------------------------------------------------------------------------------------- addCrowdGameLogo: ()-> options = top: 20 left: 30 image: "assets/icons/CrowdGame.png" width: 215 height: 50 _tag: "Logo" @container.addChild(new Hy.UI.ImageViewProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- addTitle: ()-> options = top: 20 left: (Hy.UI.iPad.screenWidth-316)/2 image: "assets/icons/label-Trivially.png" width: 316 height: 101 _tag: "Title" @container.addChild(new Hy.UI.ImageViewProxy(options)) this # ================================================================================================================== class AboutPage extends UtilityPage # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app @restored = false this.addSubpanel(this.addAboutPanel()) this # ---------------------------------------------------------------------------------------------------------------- addAboutPanel: ()-> fnClickDone = ()=> # If we did a restore, we need to reinitialize the content list on the Start Page r = @restored @restored = false this.getApp().showStartPage(if r then [((page)=>page.updateContentOptionsPanel())] else []) null fnUpdateClicked = (evt, clickedView)=> if evt.index is 0 Hy.Content.ContentManager.get()?.updateManifests() null fnClickRestore = ()=> # Must be online if Hy.Network.NetworkService.isOnline() # If an update is available, force it first if Hy.Content.ContentManifestUpdate.getUpdate()? options = message: "Trivially requires an update before purchases can be restored.\nTap \"update\" to begin" buttonNames: ["update", "cancel"] cancel: 1 dialog = new Hy.UI.AlertDialog(options) dialog.addEventListener("click", fnUpdateClicked) else @restored = true Hy.Content.ContentManager.get()?.restore() # Let's present the restore UI on the About page # this.getApp().restoreAction() else new Hy.UI.AlertDialog("Please connect to Wifi and try again") null fnClickJoinHelp = ()=> this.getApp().showJoinCodeInfoPage() null new Hy.Panels.AboutPanel({}, fnClickDone, fnClickRestore, fnClickJoinHelp) # ================================================================================================================== class UserCreatedContentInfoPage extends UtilityPage # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app this.addSubpanel(this.addInfoPanel()) this # ---------------------------------------------------------------------------------------------------------------- addInfoPanel: ()-> fnClickDone = ()=> this.getApp().showStartPage() null fnClickBuy = ()=> this.getApp().userCreatedContentAction("buy", null, true) null new Hy.Panels.UserCreatedContentInfoPanel({}, fnClickDone, fnClickBuy) # ================================================================================================================== class JoinCodeInfoPage extends UtilityPage # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app this.addSubpanel(this.addInfoPanel()) this # ---------------------------------------------------------------------------------------------------------------- addInfoPanel: ()-> fnClickDone = ()=> this.getApp().showStartPage() null new Hy.Panels.JoinCodeInfoPanel({}, fnClickDone) # ================================================================================================================== class StartPage extends Page _.extend StartPage, Hy.Utils.Observable # For changes to the state of the Start button # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app @pageEnabled = true @startEnabled = {state: false, reason: null} fnStart = (evt)=>this.startClicked() this.addCrowdGameLogo() .addTitle() .addAboutPageButton() .addGameOptionPanels() .addContentOptionsPanel() .addStartButton(fnStart) .addStartButtonText() .addContentOptionsInfo() .addJoinCodeInfo() .addUpdateAvailableInfo() @message = new Hy.Panels.MessageMarquee(this, @container) this.createCheckInCritterPanel() @fnContentPacksChanged = (evt)=>this.contentPacksChanged(evt) Hy.Pages.StartPage.addObserver this # For tracking changes to Start Button state this # ---------------------------------------------------------------------------------------------------------------- isPageEnabled: ()-> @pageEnabled # ---------------------------------------------------------------------------------------------------------------- setPageEnabled: (enabled)-> @pageEnabled = enabled for panel in [@aboutPanel, @joinCodeInfoPanel, @updateAvailablePanel] if enabled panel?.initialize() else panel?.setEnabled(false) StartPage.notifyObservers (observer)=>observer.obs_startPagePageEnabledStateChange?(@pageEnabled) this.updateUCCInfo() this # ---------------------------------------------------------------------------------------------------------------- containerOptions: ()-> options = super options.zIndex = 90 options # ---------------------------------------------------------------------------------------------------------------- openWindow: (options={})-> super options @contentOptionsPanel.open(options) this # ---------------------------------------------------------------------------------------------------------------- closeWindow: (options={})-> @contentOptionsPanel.close(options) super this # ---------------------------------------------------------------------------------------------------------------- animateWindow: (options)-> # 2.5.0 @contentOptionsPanel.animate(options) super options this # ---------------------------------------------------------------------------------------------------------------- start: ()-> super Hy.Options.contentPacks.addEventListener 'change', @fnContentPacksChanged Hy.Content.ContentManager.addObserver this # Tracking inventory changes Hy.Content.ContentManagerActivity.addObserver this # ContentPack updates Hy.Update.Update.addObserver this # as updates become available: "obs_updateAvailable" @contentOptionsPanel.start() @message.start() @checkInCritterPanel.start() # Check for required or strongly-urged content or app updates, which appear to the user # as a popover, which either allows dismissal, with frequent reminders, or which can't be dismissed, in # the case of required updates. # First, make sure we're online and not otherwise busy if not Hy.Pages.PageState.get().hasPostFunctions() and Hy.Network.NetworkService.isOnline() if not Hy.Content.ContentManager.get().doUpdateChecks() # Do update checks first if not Hy.Update.ConsoleAppUpdate.getUpdate()?.doRequiredUpdateCheck() # Then app updates Hy.Update.RateAppReminder.getUpdate()?.doRateAppReminderCheck() # Then rate app requests this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> Hy.Options.contentPacks.removeEventListener 'change', @fnContentPacksChanged Hy.Content.ContentManager.removeObserver this Hy.Content.ContentManagerActivity.removeObserver this Hy.Update.Update.removeObserver this @contentOptionsPanel.stop() @message.stop() @checkInCritterPanel.stop() super this # ---------------------------------------------------------------------------------------------------------------- pause: ()-> @message.pause() @checkInCritterPanel.pause() super this # ---------------------------------------------------------------------------------------------------------------- resumed: ()-> super @message.resumed() @checkInCritterPanel.resumed() # If our state shows that the Start Button was clicked, and we're being resumed, then # it's likely that we were backgrounded while preparing a contest. So just reset state and let # the user tap the button again if so inclined if this.startButtonIsClicked() this.resetStartButtonClicked() this # ---------------------------------------------------------------------------------------------------------------- initialize: ()-> super this.updateStartButtonEnabledState() this.resetStartButtonClicked() @aboutPanelButtonClicked = false @joinCodeInfoPanelButtonClicked = false @updateAvailablePanelButtonClicked = false @aboutPanel.initialize() @updateAvailablePanel.initialize() @joinCodeInfoPanel.initialize() if @panelSound? @panelSound.syncCurrentChoiceWithAppOption() @checkInCritterPanel.initialize() @contentOptionsPanel.initialize() this.updateUCCInfo() true # ---------------------------------------------------------------------------------------------------------------- obs_networkChanged: (reason)-> super if this.isPageEnabled() @joinCodeInfoPanel.obs_networkChanged(reason) @updateAvailablePanel.obs_networkChanged(reason) this # ---------------------------------------------------------------------------------------------------------------- obs_updateAvailable: (update)-> if this.isPageEnabled() if update.isContentManifestUpdate() or update.isConsoleAppUpdate() @updateAvailablePanel.obs_updateAvailable() this # ---------------------------------------------------------------------------------------------------------------- updateUCCInfo: ()-> buyButton = @panelUCCInfo.findButtonViewByValue(Hy.Config.Content.kThirdPartyContentBuyText) addButton = @panelUCCInfo.findButtonViewByValue(Hy.Config.Content.kThirdPartyContentNewText) infoButton = @panelUCCInfo.findButtonViewByValue(Hy.Config.Content.kThirdPartyContentInfoText) if this.isPageEnabled() isPurchased = Hy.Content.ContentManager.get().getUCCPurchaseItem().isPurchased() buyButton?.setEnabled(not isPurchased) addButton?.setEnabled(isPurchased) infoButton?.setEnabled(true) else buyButton?.setEnabled(false) addButton?.setEnabled(false) infoButton?.setEnabled(false) this # ---------------------------------------------------------------------------------------------------------------- addCrowdGameLogo: ()-> options = top: 20 left: 30 image: "assets/icons/CrowdGame.png" width: 215 height: 50 _tag: "Logo" @container.addChild(@crowdGameLogoView = new Hy.UI.ImageViewProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- addTitle: ()-> options = top: 20 left: (Hy.UI.iPad.screenWidth-316)/2 image: "assets/icons/label-Trivially.png" width: 315 height: 100 _tag: "Title" @container.addChild(@titleView = new Hy.UI.ImageViewProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- # addAboutPageButton: ()-> @aboutPanelButtonClicked = false fnClick = ()=> if @aboutPanel.isEnabled() and not @aboutPanelButtonClicked @aboutPanelButtonClicked = true this.getApp().showAboutPage() null # We take our cues from other screen elements: CrowdGame Logo image, Trivially label options = top: @titleView.getUIProperty("top") right: @crowdGameLogoView.getUIProperty("left") title: "?" font: Hy.UI.Fonts.specBigNormal _tag: "About Button" buttonOptions = title: "?" font: Hy.UI.Fonts.specBigNormal topTextOptions = {} bottomTextOptions = {text: "Help"} @container.addChild(@aboutPanel = new Hy.Panels.LabeledButtonPanel(options, buttonOptions, fnClick, topTextOptions, bottomTextOptions)) this # ---------------------------------------------------------------------------------------------------------------- obs_contentUpdateSessionStarted: (label, report)-> # @message.startAdHocSession(label) this.updateStartButtonEnabledState() this.setPageEnabled(false) # if report? # @message.addAdHoc(report) this # ---------------------------------------------------------------------------------------------------------------- obs_contentUpdateSessionProgressReport: (report, percentDone = -1)-> Hy.Trace.debug "StartPage::contentUpdateSessionProgressReport (#{report} / #{percentDone})" if percentDone isnt -1 report += " (#{percentDone}% done)" # if report? # @message.addAdHoc report this # ---------------------------------------------------------------------------------------------------------------- obs_contentUpdateSessionCompleted: (report, changes)-> Hy.Trace.debug "StartPage::contentUpdateSessionCompleted #{report}" # @message.addAdHoc(report) # @message.endAdHocSession() this.updateStartButtonEnabledState() this.setPageEnabled(true) @updateAvailablePanel.initialize() this # ---------------------------------------------------------------------------------------------------------------- obs_inventoryInitiated: ()-> @message.startAdHocSession("Syncing with Apple App Store") @message.addAdHoc("Contacting Store") this # ---------------------------------------------------------------------------------------------------------------- obs_inventoryUpdate: (status, message)-> if message? @message.addAdHoc(message) this # ---------------------------------------------------------------------------------------------------------------- obs_inventoryCompleted: (status, message)-> if message? @message.addAdHoc(message) @message.endAdHocSession() this # ---------------------------------------------------------------------------------------------------------------- obs_purchaseInitiated: (label, report)-> this.updateStartButtonEnabledState() this.setPageEnabled(false) # @message.startAdHocSession(label) # if report? # @message.addAdHoc(report) this # ---------------------------------------------------------------------------------------------------------------- obs_purchaseProgressReport: (report)-> Hy.Trace.debug "StartPage::purchaseProgressReport #{report}" # if report? # @message.addAdHoc(report) null # ---------------------------------------------------------------------------------------------------------------- obs_purchaseCompleted: (report)-> this.updateStartButtonEnabledState() this.setPageEnabled(true) this.updateUCCInfo() # if report? # @message.addAdHoc(report) # @message.endAdHocSession() null # ---------------------------------------------------------------------------------------------------------------- obs_restoreInitiated: (report)-> this.updateStartButtonEnabledState() this.setPageEnabled(false) # @message.startAdHocSession("Restore of purchases") # if report? # @message.addAdHoc(report) null # ---------------------------------------------------------------------------------------------------------------- obs_restoreProgressReport: (report)-> # if report? # @message.addAdHoc(report) null # ---------------------------------------------------------------------------------------------------------------- obs_restoreCompleted: (report)-> this.updateStartButtonEnabledState() this.setPageEnabled(true) # if report? # @message.addAdHoc(report) # @message.endAdHocSession() null # ---------------------------------------------------------------------------------------------------------------- addStartButton: (fn)-> options = height: 110 width: 110 top: 415 left: 277 zIndex: 101 backgroundImage: "assets/icons/button-play.png" backgroundSelectedImage: "assets/icons/button-play-selected.png" _tag: "Start Button" @container.addChild(@startButton = new Hy.UI.ButtonProxy(options)) this.resetStartButtonClicked() @fnClickStartGame = (evt)=> if @startEnabled.state if not this.startButtonIsClicked() this.setStartButtonClicked() fn() null @startButton.addEventListener 'click', @fnClickStartGame this # ---------------------------------------------------------------------------------------------------------------- startButtonIsClicked: ()-> @startButtonClicked # ---------------------------------------------------------------------------------------------------------------- setStartButtonClicked: ()-> @startButtonClicked = true # ---------------------------------------------------------------------------------------------------------------- resetStartButtonClicked: ()-> @startButtonClicked = false # ---------------------------------------------------------------------------------------------------------------- getStartEnabled: ()-> [@startEnabled.state, @startEnabled.reason] # ---------------------------------------------------------------------------------------------------------------- setStartEnabled: (state, reason)-> @startEnabled.state = state @startEnabled.reason = reason @startButton.setEnabled(state) this.setContentOptionsInfo(state, reason) StartPage.notifyObservers (observer)=>observer.obs_startPageStartButtonStateChanged?(state, reason) this # ---------------------------------------------------------------------------------------------------------------- addStartButtonText: ()-> width = 200 options = top: @startButton.getUIProperty("top") + 120 left: @startButton.getUIProperty("left") - ((width-@startButton.getUIProperty("width"))/2) width: width height: 50 text: "Start Game" font: Hy.UI.Fonts.specMediumMrF zIndex:@startButton.getUIProperty("zIndex") textAlign: 'center' _tag: "Start Game Label" @container.addChild(@startButtonTextView = new Hy.UI.LabelProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- # "1 topic selected", etc # addContentOptionsInfo: ()-> width = 70 options = top: @startButton.getUIProperty("top") left: @startButton.getUIProperty("left") - (width + 20) width: width height: @startButton.getUIProperty("height") font: Hy.UI.Fonts.specMinisculeNormal color: Hy.UI.Colors.black zIndex:@startButton.getUIProperty("zIndex") textAlign: 'center' _tag: "Content Options Info" # borderColor: Hy.UI.Colors.white @container.addChild(@contentOptionsPanelInfoView = new Hy.UI.LabelProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- setContentOptionsInfo: (state, info = null)-> @contentOptionsPanelInfoView.setUIProperty("color", if state then Hy.UI.Colors.black else Hy.UI.Colors.MrF.Red) @contentOptionsPanelInfoView.setUIProperty("text", info) this # ---------------------------------------------------------------------------------------------------------------- # We position this relative to the ? About Page Button... # addJoinCodeInfo: ()-> @joinCodeInfoPanelButtonClicked = false fnClick = ()=> if @joinCodeInfoPanel.isEnabled() and not @joinCodeInfoPanelButtonClicked @joinCodeInfoPanelButtonClicked = true this.getApp().showJoinCodeInfoPage() null options = bottom: @startButtonTextView.getUIProperty("bottom") - 20 left: 50 @container.addChild(@joinCodeInfoPanel = new Hy.Panels.CodePanel(options, fnClick)) this # ---------------------------------------------------------------------------------------------------------------- # We position this relative to the ? About Page Button... # addUpdateAvailableInfo: ()-> @updateAvailablePanelButtonClicked = false fnClick = (e, v)=> if @updateAvailablePanel.isEnabled() and not @updateAvailablePanelButtonClicked @updateAvailablePanelButtonClicked = true if Hy.Network.NetworkService.isOnline() # Check for Content Update, then App Update if Hy.Content.ContentManifestUpdate.getUpdate()? Hy.Content.ContentManager.get()?.updateManifests() else if (update = Hy.Update.ConsoleAppUpdate.getUpdate())? update.doURL() @updateAvailablePanelButtonClicked = false null options = top: @startButton.getUIProperty("top") - 20 left: 50 @container.addChild(@updateAvailablePanel = new Hy.Panels.UpdateAvailablePanel(options, fnClick)) this # ---------------------------------------------------------------------------------------------------------------- addGameOptionPanels: ()-> top = 93 #130 #155 left = 85 #75 padding = 55 panelSpecs = [ {varName: "panelSound", fnName: "createSoundPanel", options: {left: left}}, {varName: "panelNumberOfQuestions", fnName: "createNumberOfQuestionsPanel", options: {left: left}}, {varName: "panelSecondsPerQuestion", fnName: "createSecondsPerQuestionPanel", options: {left: left}}, {varName: "panelFirstCorrect", fnName: "createFirstCorrectPanel", options: {left: left}}, {varName: "panelUCCInfo", fnName: "createUserCreatedContentInfoPanel2", options: {left: left}} ] for panelSpec in panelSpecs this[panelSpec.varName] = Hy.Panels.OptionPanels[panelSpec.fnName](this, Hy.UI.ViewProxy.mergeOptions(panelSpec.options, {top: top})) @container.addChild(this[panelSpec.varName]) top += padding this # ---------------------------------------------------------------------------------------------------------------- addContentOptionsPanel: ()-> options = top: 100 right: 80 @container.addChild(@contentOptionsPanel = new Hy.Panels.ContentOptionsPanel(this, options)) this # ---------------------------------------------------------------------------------------------------------------- updateContentOptionsPanel: ()-> Hy.Trace.debug "StartPage::updateContentOptionsPanel" @contentOptionsPanel?.update() this # ---------------------------------------------------------------------------------------------------------------- obs_userCreatedContentSessionStarted: (label, report = null)-> this.updateStartButtonEnabledState() this.setPageEnabled(false) # @message.startAdHocSession(label) # @message.addAdHoc(if report? then report else "Starting... This will only take a moment...") this # ---------------------------------------------------------------------------------------------------------------- obs_userCreatedContentSessionProgressReport: (report = null)-> # if report? # @message.addAdHoc(report) this # ---------------------------------------------------------------------------------------------------------------- obs_userCreatedContentSessionCompleted: (report = null, changes = false)-> this.updateUCCInfo() this.updateStartButtonEnabledState() this.setPageEnabled(true) # @message.addAdHoc(if report? then report else "Completed") # @message.endAdHocSession() this # ---------------------------------------------------------------------------------------------------------------- createCheckInCritterPanel: ()-> options = left: 0 bottom: 0 @container.addChild(@checkInCritterPanel = new Hy.Panels.CheckInCritterPanel(options)) this # ---------------------------------------------------------------------------------------------------------------- startClicked: ()-> Hy.Utils.Deferral.create 0, ()=>this.getApp().contestStart() # must use deferral to trigger startContest outside of event handler this # ---------------------------------------------------------------------------------------------------------------- updateStartButtonEnabledState: ()-> Hy.Trace.debug "StartPage::updateStartButtonEnabledState" reason = null state = false numTopics = _.size(_.select(Hy.Content.ContentManager.get().getLatestContentPacksOKToDisplay(), (c)=>c.isSelected())) if numTopics <= 0 reason = "No topics selected!" state = false else state = true reason = "#{numTopics} topic#{if numTopics > 1 then "s" else ""} selected" if (r = Hy.Content.ContentManager.isBusy())? reason = "Please wait: #{r}" state = false this.setStartEnabled(state, reason) this # ---------------------------------------------------------------------------------------------------------------- categoriesChanged: (evt)-> this.updateStartButtonEnabledState() # ---------------------------------------------------------------------------------------------------------------- contentPacksChanged: (evt)-> this.updateStartButtonEnabledState() # ---------------------------------------------------------------------------------------------------------------- contentPacksLoadingStart: ()-> @message.startAdHocSession("Preparing Contest") # ---------------------------------------------------------------------------------------------------------------- contentPacksLoadingCompleted: ()-> @message.endAdHocSession() # ---------------------------------------------------------------------------------------------------------------- contentPacksLoading: (report)-> @message.addAdHoc(report) # ================================================================================================================== class NotifierPage extends Page # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app @fnNotify = null this # ---------------------------------------------------------------------------------------------------------------- initialize: (fnNotify)-> super @fnNotify = fnNotify true # ---------------------------------------------------------------------------------------------------------------- start: ()-> super @fnNotify?() this # ---------------------------------------------------------------------------------------------------------------- resumed: ()-> super @fnNotify?() this # ================================================================================================================== class BasePage extends NotifierPage constructor: (state, app)-> super state, app @container.addChild(@questionInfoPanel = new Hy.Panels.QuestionInfoPanel(this.questionInfoPanelOptions())) this # ---------------------------------------------------------------------------------------------------------------- labelColor: ()-> Hy.UI.Colors.white # ---------------------------------------------------------------------------------------------------------------- questionInfoPanelOptions: ()-> {} # ================================================================================================================== # adds support for pause button and countdown class CountdownPage extends BasePage kCountdownStateUndefined = 0 kCountdownStateRunning = 1 kCountdownStatePaused = 2 @kWidth = 164 # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app @fnPause = null @fnCompleted = null @pauseClicked = false @overlayClicked = false @overlayShowing = false @currentCountdownValue = null @countdownSeconds = 0 @startingDelay = 0 @countdownDeferral = null @fnPauseClick = (evt)=> if not @pauseClicked @pauseClicked = true this.click() null @fnClickContinueGame = ()=> this.continue_() @overlayClicked = false @pauseClicked = false null @fnClickNewGame = ()=> @overlayClicked = false @pauseClicked = false this.getApp().contestRestart(false) null @fnClickForceFinish = ()=> @overlayClicked = false @pauseClicked = false this.getApp().contestForceFinish() null @container.addChild(@countdownPanel = new Hy.Panels.CountdownPanel(this.countdownPanelOptions(), @fnPauseClick)) @container.addChild(this.createPauseButton(this.pauseButtonOptions())) @container.addChild(this.createPauseButtonText(this.pauseButtonTextOptions())) this # ---------------------------------------------------------------------------------------------------------------- countdownPanelOptions: ()-> {} # ---------------------------------------------------------------------------------------------------------------- pauseButtonOptions: ()-> {} # ---------------------------------------------------------------------------------------------------------------- pauseButtonTextOptions: ()-> {} # ---------------------------------------------------------------------------------------------------------------- pause: ()-> return if @countdownState is kCountdownStatePaused @countdownState = kCountdownStatePaused this.disablePause() @countdownTicker?.pause() this.showOverlay({opacity:1, duration: 200}) # Hy.Network.NetworkService.get().setImmediate() @fnPause() # ---------------------------------------------------------------------------------------------------------------- resumed: ()-> super this.pause() this # ---------------------------------------------------------------------------------------------------------------- continue_: ()-> return if @countdownState is kCountdownStateRunning # Hy.Network.NetworkService.get().setSuspended() @countdownState = kCountdownStateRunning f = ()=> this.enablePause() @countdownTicker?.continue_() @fnNotify() this.hideOverlay({opacity:0, duration: 200}, f) this # ---------------------------------------------------------------------------------------------------------------- start: ()-> super this.initCountdown() this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> this.haltCountdown() super this # ---------------------------------------------------------------------------------------------------------------- haltCountdown: ()-> @countdownDeferral.clear() if @countdownDeferral?.enqueued() @countdownTicker?.exit() this # ---------------------------------------------------------------------------------------------------------------- initialize: (fnNotify, fnPause, fnCompleted, countdownSeconds, startingDelay)-> super fnNotify @countdownState = kCountdownStateUndefined @fnPause = fnPause @fnCompleted = fnCompleted @currentCountdownValue = null @countdownSeconds = countdownSeconds @startingDelay = startingDelay @pauseClicked = false @overlayClicked = false this.hideOverlayImmediate() this.enablePause() this.getCountdownPanel().initialize().animateCountdown(this.countdownAnimationOptions(@countdownSeconds), @countdownSeconds, null, true) true # ---------------------------------------------------------------------------------------------------------------- obs_networkChanged: (reason)-> Hy.Trace.debug("QuestionPage::obs_networkChanged (isPaused=#{this.isPaused()})") super if this.isPaused() this.updateConnectionInfo(reason) this # ---------------------------------------------------------------------------------------------------------------- createPauseButton: (options)-> defaultOptions = zIndex: 101 backgroundImage: "assets/icons/button-pause-question-page.png" _tag: "Pause" @pauseButton = new Hy.UI.ButtonProxy(Hy.UI.ViewProxy.mergeOptions(defaultOptions, options)) f = ()=> @fnPauseClick() null @pauseButton.addEventListener("click", f) @pauseButton # ---------------------------------------------------------------------------------------------------------------- createPauseButtonText: (options)-> defaultOptions = zIndex: 101 text: 'Pause' font: Hy.UI.Fonts.specTinyMrF color: Hy.UI.Colors.MrF.DarkBlue height: 'auto' textAlign: 'center' _tag: "Pause Text" @pauseButtonText = new Hy.UI.LabelProxy(Hy.UI.ViewProxy.mergeOptions(defaultOptions, options)) @pauseButtonText # ---------------------------------------------------------------------------------------------------------------- getCountdownPanel: ()-> @countdownPanel # ---------------------------------------------------------------------------------------------------------------- animateCountdown: (init, value)-> this.getCountdownPanel().animateCountdown(this.countdownAnimationOptions(value), value, @countdownSeconds, init) this # ---------------------------------------------------------------------------------------------------------------- countdownAnimationOptions: (value)-> _style: "normal" # ---------------------------------------------------------------------------------------------------------------- playCountdownSound: (value)-> if (event = this.countdownSound(value))? Hy.Media.SoundManager.get().playEvent(event) this # ---------------------------------------------------------------------------------------------------------------- initCountdown: ()-> @countdownState = kCountdownStateRunning @countdownDeferral = null if @countdownDeferral?.triggered() fnInitView = (value)=> @currentCountdownValue = value this.animateCountdown(true, value) fnUpdateView = (value)=> @currentCountdownValue = value this.animateCountdown(false, value) fnCompleted = (evt)=>this.countdownCompleted() fnSound = (value)=>this.playCountdownSound(value) @countdownTicker = new CountdownTicker(fnInitView, fnUpdateView, fnCompleted, fnSound) @countdownTicker.init(@countdownSeconds, @startingDelay) this # ---------------------------------------------------------------------------------------------------------------- getCountdownStartValue: ()-> @countdownSeconds # ---------------------------------------------------------------------------------------------------------------- getCountdownValue: ()-> # @countdownTicker?.getValue() # This isn't reliable, if console user answers @currentCountdownValue # ---------------------------------------------------------------------------------------------------------------- countdownSound: (value)-> null # ---------------------------------------------------------------------------------------------------------------- countdownCompleted: ()-> this.disablePause() @fnCompleted() # ---------------------------------------------------------------------------------------------------------------- click: (evt)-> this.pause() if @countdownState is kCountdownStateRunning # ---------------------------------------------------------------------------------------------------------------- disablePause: ()-> for view in [@pauseButton, @pauseButtonText] view?.animate({duration: 100, opacity: 0}) view?.hide() this # ---------------------------------------------------------------------------------------------------------------- enablePause: ()-> for view in [@pauseButton, @pauseButtonText] # view?.animate({duration: 100, opacity: 1}) view?.setUIProperty("opacity", 1) view?.show() this # ---------------------------------------------------------------------------------------------------------------- isPaused: ()-> @countdownState is kCountdownStatePaused # ---------------------------------------------------------------------------------------------------------------- createOverlay: ()-> container = this.overlayContainer() overlayBkgndOptions = top: 0 bottom: 0 left: 0 right: 0 backgroundImage: Hy.UI.Backgrounds.pixelOverlay zIndex: 200 opacity: 0 _tag: "Overlay Background" container.addChild(@overlayBkgnd = new Hy.UI.ViewProxy(overlayBkgndOptions)) overlayFrameOptions = top: 100 bottom: 100 left: 100 right: 100 borderColor: Hy.UI.Colors.white borderRadius: 16 borderWidth: 4 zIndex: 201 # _alignment: "center" opacity: 0 _tag: "Overlay Frame" container.addChild(@overlayFrame = new Hy.UI.ViewProxy(overlayFrameOptions)) elementOptions = width: 400 @overlayFrame.addChild(this.overlayBody(elementOptions)) this # ---------------------------------------------------------------------------------------------------------------- showOverlay: (options, fnDone = null)-> fn = ()=> if fnDone? Hy.Utils.Deferral.create(0, fnDone) null if not @overlayBkgnd? this.createOverlay() this.updateConnectionInfo() @panelSound?.syncCurrentChoiceWithAppOption() for view in [@overlayBkgnd, @overlayFrame] view.setUIProperty("opacity", 0) view.show() @overlayBkgnd.animate(options, ()=>) @overlayFrame.animate(options, fn) this # ---------------------------------------------------------------------------------------------------------------- hideOverlayImmediate: ()-> for view in [@overlayBkgnd, @overlayFrame] view?.hide() this # ---------------------------------------------------------------------------------------------------------------- hideOverlay: (options, fnDone = null)-> fn = ()=> for view in [@overlayBkgnd, @overlayFrame] view?.hide() if fnDone? Hy.Utils.Deferral.create(0, fnDone) null if @overlayBkgnd? @overlayFrame.animate(options, ()=>) @overlayBkgnd.animate(options, fn) else fn() this # ---------------------------------------------------------------------------------------------------------------- overlayContainer: ()-> @container # ---------------------------------------------------------------------------------------------------------------- overlayBody: (elementOptions)-> options = backgroundImage: Hy.UI.Backgrounds.pixelOverlay _tag: "Overlay Body" body = new Hy.UI.ViewProxy(options) body.addChild(this.createGamePausedText()) top = 170 #200 verticalPadding = 90 #elementOptions.height + 15 #25 textOffset = 125 horizontalPadding = 20 choiceOptions = _style: "plainOnDarkBackground" @panelSound = Hy.Panels.OptionPanels.createSoundPanel(this, Hy.UI.ViewProxy.mergeOptions(elementOptions, {top:top}), {font: Hy.UI.Fonts.specBigNormal, color: Hy.UI.Colors.white, _attach: "right"}, choiceOptions) body.addChild(@panelSound) continueGame = this.createOverlayButtonPanel(Hy.UI.ViewProxy.mergeOptions(elementOptions, {top: (top += verticalPadding)}), {backgroundImage: "assets/icons/button-play-small-blue.png", left: horizontalPadding}, {left: textOffset, text: "Continue Game"}, @fnClickContinueGame) body.addChild(continueGame) forceFinishGame = this.createOverlayButtonPanel(Hy.UI.ViewProxy.mergeOptions(elementOptions, {top: (top += verticalPadding)}), {backgroundImage: "assets/icons/button-cancel.png", left: horizontalPadding}, {left: textOffset, text: "Finish Game"}, @fnClickForceFinish) body.addChild(forceFinishGame) newGame = this.createOverlayButtonPanel(Hy.UI.ViewProxy.mergeOptions(elementOptions, {top: (top += verticalPadding)}), {backgroundImage: "assets/icons/button-restart.png", left: horizontalPadding}, {left: textOffset, text: "Restart Game"}, @fnClickNewGame) body.addChild(newGame) @connectionInfo = this.createConnectionInfo(Hy.UI.ViewProxy.mergeOptions(elementOptions, {top: (top += verticalPadding)})) this.updateConnectionInfo() body.addChild(@connectionInfo) body # ---------------------------------------------------------------------------------------------------------------- updateConnectionInfo: (reason = "Wifi")-> text = "" if reason is "Wifi" if Hy.Network.NetworkService.isOnlineWifi() if (encoding = Hy.Network.NetworkService.getAddressEncoding())? text = "Additional players? Visit #{Hy.Config.Rendezvous.URLDisplayName} and enter: #{encoding}" @connectionInfo?.setUIProperty("text", text) this # ---------------------------------------------------------------------------------------------------------------- createConnectionInfo: (commonOptions)-> options = width: 600 font: Hy.UI.Fonts.specSmallNormal color: Hy.UI.Colors.white _tag: "Connection Info" height: 'auto' textAlign: 'center' _tag: "Connection Info" new Hy.UI.LabelProxy(Hy.UI.ViewProxy.mergeOptions(commonOptions, options)) # ---------------------------------------------------------------------------------------------------------------- createGamePausedText: ()-> gamePausedOptions = text: 'Game Paused' font: Hy.UI.Fonts.specGiantMrF color: Hy.UI.Colors.white top: 50 height: 'auto' textAlign: 'center' _tag: "Game Paused" new Hy.UI.LabelProxy(gamePausedOptions) # ---------------------------------------------------------------------------------------------------------------- createOverlayButtonPanel: (containerOptions, buttonOptions, labelOptions, fnClick)-> options = height: 72 _tag: "Overlay Button Panel" container = new Hy.UI.ViewProxy(Hy.UI.ViewProxy.mergeOptions(options, containerOptions)) f = ()=> if not @overlayClicked @overlayClicked = true fnClick() null defaultButtonOptions = height: 72 width: 72 left: 0 _tag: "Overlay Button" button = new Hy.UI.ButtonProxy(Hy.UI.ViewProxy.mergeOptions(defaultButtonOptions, buttonOptions)) button.addEventListener 'click', f container.addChild(button) defaultLabelOptions = font: Hy.UI.Fonts.specBigNormal color: Hy.UI.Colors.white _tag: "Overlay Label" container.addChild(new Hy.UI.LabelProxy(Hy.UI.ViewProxy.mergeOptions(defaultLabelOptions, labelOptions))) container # ================================================================================================================== class QuestionPage extends CountdownPage kQuestionBlockHeight = 215 kQuestionBlockWidth = 944 kQuestionInfoHeight = kQuestionInfoWidth = 86 kQuestionBlockHorizontalMargin = (Hy.UI.iPad.screenWidth - kQuestionBlockWidth)/2 # kQuestionBlockVerticalMargin = 30 kQuestionBlockVerticalMargin = 25 kQuestionTextMargin = 10 kQuestionTextWidth = kQuestionBlockWidth - (kQuestionTextMargin + kQuestionInfoWidth) kQuestionTextHeight = kQuestionBlockHeight - (2*kQuestionTextMargin) kAnswerBlockWidth = 460 kAnswerBlockHeight = 206 kAnswerBlockHorizontalPadding = 24 kAnswerBlockVerticalPadding = 15 # kAnswerContainerVerticalMargin = 20 kAnswerContainerVerticalMargin = 7 kAnswerContainerHorizontalMargin = kQuestionBlockHorizontalMargin kAnswerContainerWidth = (2*kAnswerBlockWidth) + kAnswerBlockHorizontalPadding kAnswerContainerHeight = (2*kAnswerBlockHeight) + kAnswerBlockVerticalPadding kAnswerLabelWidth = 60 kAnswerTextMargin = 10 kAnswerTextHeight = kAnswerBlockHeight - (2*kAnswerTextMargin) kAnswerTextWidth = kAnswerBlockWidth - ((2*kAnswerTextMargin) + kAnswerLabelWidth) kCountdownClockHeight = kCountdownClockWidth = 86 kButtonOffset = 5 kPauseButtonHeight = kPauseButtonWidth = 86 kPauseButtonVerticalMargin = kQuestionBlockVerticalMargin + kQuestionBlockHeight - (kPauseButtonHeight - kButtonOffset) kPauseButtonHorizontalMargin = kQuestionBlockHorizontalMargin - 20 kQuestionInfoVerticalMargin = kQuestionBlockVerticalMargin - kButtonOffset kQuestionInfoHorizontalMargin = kQuestionBlockHorizontalMargin - 20 # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> @zIndexPassive = 110 @zIndexActive = 150 @top = 0 @sound = null super state, app @soundCounter ||= 0 @soundKeys = ["countPI:KEY:<KEY>END_PI0", "countPI:KEY:<KEY>END_PI1", "countPI:KEY:<KEY>END_PI_2", "countDown_3", "countDown_4"] @nSounds = @soundKeys.length @pageImage = null this.webViewPanelCreate() @container.addChild(this.createQuestionBlock()) @container.addChild(this.createAnswerBlocks()) this.createAnswerCritterPanel() @questionTestCount = 0 @answerTestCount = 0 # It's important that these all share the same view, due to the overlapping nature of the animations [@animateInLongScenes, @animateInLongSceneDuration] = this.buildAnimationFromScenes(this.initAnimateInLongScenes()) [@animateInShortScenes, @animateInShortSceneDuration] = this.buildAnimationFromScenes(this.initAnimateInShortScenes(), @animateInLongScenes) [@animateOutScenes, @animateOutSceneDuration] = this.buildAnimationFromScenes(this.initAnimateOutScenes(), @animateInShortScenes) this # ---------------------------------------------------------------------------------------------------------------- countdownPanelOptions: ()-> top : kQuestionBlockVerticalMargin + kQuestionBlockHeight + kAnswerContainerVerticalMargin + (kAnswerContainerHeight - kCountdownClockHeight)/2 left : kAnswerContainerHorizontalMargin + (kAnswerContainerWidth - kCountdownClockWidth)/2 height : kCountdownClockHeight width : kCountdownClockWidth zIndex : @zIndexActive + 2 # ---------------------------------------------------------------------------------------------------------------- pauseButtonOptions: ()-> zIndex : @zIndexActive + 2 height : kPauseButtonHeight width : kPauseButtonWidth top : kPauseButtonVerticalMargin right : kPauseButtonHorizontalMargin # ---------------------------------------------------------------------------------------------------------------- pauseButtonTextOptions: ()-> textHeight = 25 buttonOptions = this.pauseButtonOptions() options = top : buttonOptions.top - (textHeight + 5) right : buttonOptions.right width : buttonOptions.width height : textHeight zIndex : buttonOptions.zIndex options # ---------------------------------------------------------------------------------------------------------------- questionInfoPanelOptions: ()-> top : kQuestionInfoVerticalMargin right : kQuestionInfoHorizontalMargin # ---------------------------------------------------------------------------------------------------------------- start: ()-> super this.clearAnimation() @sound?.play() if not @showingAnswers @answerCritterPanel.start() this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> @sound.stop() if @sound?.isPlaying() if @showingAnswers @answerCritterPanel.stop() super this # ---------------------------------------------------------------------------------------------------------------- pause: ()-> @sound.pause() if @sound?.isPlaying() @answerCritterPanel.pause() super this # ---------------------------------------------------------------------------------------------------------------- resumed: ()-> super @sound.play() if @sound? and not @sound.isPlaying() @answerCritterPanel.resumed() this # ---------------------------------------------------------------------------------------------------------------- closeWindow: (options={})-> @webViewPanel?.close() super this # ---------------------------------------------------------------------------------------------------------------- openWindow: (options={})-> super options this # ---------------------------------------------------------------------------------------------------------------- continue_: ()-> super @sound.play() if @sound? and not @sound.isPlaying() this # ---------------------------------------------------------------------------------------------------------------- initializeForQuestion: (fnNotify, fnPause, fnCompleted, countdownSeconds, startingDelay, contestQuestion, iQuestion, nQuestions)-> @showingAnswers = false @consoleAnswered = false @showingAnswersClicked = false this.initialize fnNotify, fnPause, fnCompleted, countdownSeconds, startingDelay, contestQuestion, iQuestion, nQuestions @answerCritterPanel.initialize() # apparently, the window has to be open in order for the webview to work... @window.setUIProperty("opacity", 0) this.animateChildren({duration: 0, opacity: 0}) this.openWindow() @webViewPanel?.initialize(()=>this.webViewPanelContentInitialize()) false # ---------------------------------------------------------------------------------------------------------------- initializeForAnswers: (fnNotify, fnPause, fnCompleted, countdownSeconds, startingDelay)-> @showingAnswers = true this.initialize fnNotify, fnPause, fnCompleted, countdownSeconds, startingDelay, @contestQuestion, @iQuestion, @nQuestions this.revealAnswer() true # ---------------------------------------------------------------------------------------------------------------- initialize: (fnNotify, fnPause, fnCompleted, countdownSeconds, startingDelay, contestQuestion, iQuestion, nQuestions)-> super @contestQuestion = contestQuestion @iQuestion = iQuestion @nQuestions = nQuestions @sound?.reset() @questionInfoPanel.initialize @iQuestion+1, @nQuestions, this.labelColor() true # ---------------------------------------------------------------------------------------------------------------- initAnimateInLongScenes: ()-> [ {image: "splash", imageOptions: {zIndex: 200, top: 0, left: 0, right: 0, bottom: 0}, animationOptions: [{_incrementalDelay: 500, duration: 400, _startOpacity: 1.0, opacity: 0.0, _waitForWindowFn: ((fn)=>this.webViewPanelWait(fn))}]} ] # ---------------------------------------------------------------------------------------------------------------- initAnimateInShortScenes: ()-> [ {image: "black", imageOptions: {zIndex: 200, top: 0, left: 0, right: 0, bottom: 0}, animationOptions: [{_incrementalDelay: 0, duration: 400, _startOpacity: 1.0, opacity: 0.0, _waitForWindowFn: ((fn)=>this.webViewPanelWait(fn))}]} ] # ---------------------------------------------------------------------------------------------------------------- initAnimateOutScenes: ()-> [ {image: "black", imageOptions: {zIndex: 200, top: 0, left: 0, right: 0, bottom: 0, opacity: 0}, animationOptions: [{_incrementalDelay: 0, duration: 400, _startOpacity: 0, opacity: 1.0}]} ] # ---------------------------------------------------------------------------------------------------------------- # Animates all child views EXCEPT the web view, which we animate separately # animateChildren: (options)-> for child in @container.getChildren() if child isnt @webViewPanel if options.opacity? child.setUIProperty("opacity", options.opacity) # child.animate(options) this # ---------------------------------------------------------------------------------------------------------------- animateIn: (useCurtains = false)-> Hy.Trace.debug "QuestionPage::animateIn (ENTER)" @webViewPanel?.fireEvent({kind: "animateIn", data: {useCurtains: useCurtains}}, (event)=>this.animateInFinished()) this.animateWindow({opacity: 1, duration: 0, delay: 150}) # 2.6.0: 50->150 -1 # ---------------------------------------------------------------------------------------------------------------- animateInFinished: ()-> Hy.Trace.debug "QuestionPage::animateInFinished (ENTER)" this.animateChildren({opacity: 1, duration: 100}) Hy.Utils.Deferral.create(100, ()=>PageState.get().resumed()) # ---------------------------------------------------------------------------------------------------------------- animateOut: (useCurtains = false)-> this.animateChildren({opacity: 0, duration: 50}) Hy.Utils.Deferral.create(50, ()=>@webViewPanel?.fireEvent({kind: "animateOut", data: {useCurtains: useCurtains}}, (event)=>this.animateOutFinished())) return -1 this.animateScenes(@animateOutScenes) @animateOutSceneDuration # ---------------------------------------------------------------------------------------------------------------- animateOutFinished: ()-> @window.setUIProperty("opacity", 0) Hy.Utils.Deferral.create(0, ()=>PageState.get().resumed()) # ---------------------------------------------------------------------------------------------------------------- dump: ()-> Hy.Trace.debug "QuestionPage::dump (Question=#{@contestQuestion.getQuestionID()}/#{@contestQuestion.getQuestionText()})" for i in [0..3] Hy.Trace.debug "QuestionPage::dump (#{i} #{@contestQuestion.getAnswerText(i)})" this # ---------------------------------------------------------------------------------------------------------------- labelColor: ()-> if @showingAnswers then Hy.UI.Colors.paleYellow else Hy.UI.Colors.white # ---------------------------------------------------------------------------------------------------------------- animateCountdown: (init, value)-> super color = Hy.UI.Colors.white if not init if not @showingAnswers if value <= Hy.Config.Dynamics.panicAnswerTime color = Hy.UI.Colors.MrF.Red # @questionLabel.setUIProperty("color", color) #TODO this # ---------------------------------------------------------------------------------------------------------------- countdownAnimationOptions: (value)-> _style: if @showingAnswers then "normal" else "frantic" # ---------------------------------------------------------------------------------------------------------------- # Called from ConsoleApp animateCountdownQuestionCompleted: ()-> this.getCountdownPanel().animateCountdown({_style: "completed"}) this # ---------------------------------------------------------------------------------------------------------------- webViewPanelCreate: ()-> options = this.containerOptions() options._tag = "WebViewPanel" # options.borderWidth = 10 # options.borderColor = Hy.UI.Colors.green webViewOptions = top: options.top left: options.left width: options.width height: options.height _tag: "Question Page Web View" scalesPageToFit:false url: "html-question-page.html" zIndex: 50 #@zIndexPassive backgroundColor:'transparent' # http://developer.appcelerator.com/question/45491/can-i-change-the-white-background-that-shows-when-a-web-view-is-loading @container.addChild(@webViewPanel = new Hy.Panels.WebViewPanel(options, webViewOptions)) this # ---------------------------------------------------------------------------------------------------------------- webViewPanelWait: (fn)-> Hy.Trace.debug "QuestionPage::webViewPanelWait (PAGE WAIT: WebViewInitialized=#{@webViewPanel.isInitialized()})" @webViewPanelFinishAnimateInFn = fn if @webViewPanel.isInitialized() this.webViewPanelFinishAnimation() else null null # ---------------------------------------------------------------------------------------------------------------- webViewPanelFinishAnimation: ()-> Hy.Trace.debug "QuestionPage::webViewPanelFinishAnimation (FINISH ANIMATION: WebViewInitialized=#{@webViewPanel.isInitialized()})" if @webViewPanelFinishAnimateInFn? if @webViewPanel.isInitialized() Hy.Trace.debug "QuestionPage::webViewPanelFinishAnimation (FINISHING ANIMATION)" @webViewPanelFinishAnimateInFn() @webViewPanelFinishAnimateInFn = null Hy.Utils.Deferral.create(@animateInSceneDuration, ()=>PageState.get().resumed()) else Hy.Trace.debug "QuestionPage::webViewPanelFinishAnimation (NO ANIMATION TO FINISH)" this # ---------------------------------------------------------------------------------------------------------------- webViewPanelContentInitialize: ()-> data = {} data.question = {} data.question.text = this.formatText(@contestQuestion.getQuestionText()).text code = switch (format = @contestQuestion.getContentPack().getFormatting("question")) when "bold" "b" when "italic" "i" when "none" null else "i" if code? data.question.text = "<#{code}>#{data.question.text}</#{code}>" data.answers = [] for i in [0..3] data.answers[i] = {} data.answers[i].text = this.formatText(@contestQuestion.getAnswerText(i)).text @webViewPanel.fireEvent({kind: "initializePage", data: data}, (event)=>this.webViewPanelContentInitialized()) this # ---------------------------------------------------------------------------------------------------------------- webViewPanelContentInitialized: ()-> Hy.Utils.Deferral.create(0, ()=>PageState.get().resumed()) null # ---------------------------------------------------------------------------------------------------------------- webViewPanelShowConsoleSelection: (indexSelectedAnswer)-> @webViewPanel.fireEvent({kind: "showConsoleSelection", data: {indexSelectedAnswer: indexSelectedAnswer}}) # ---------------------------------------------------------------------------------------------------------------- webViewPanelRevealAnswer: (indexCorrectAnswer)-> @webViewPanel.fireEvent({kind: "revealAnswer", data: {indexCorrectAnswer: indexCorrectAnswer}}) # ---------------------------------------------------------------------------------------------------------------- createQuestionBlock: ()-> #Hack to prevent user "copy" actions, since all other approaches aren't working overlayViewOptions = top: (@top += kQuestionBlockVerticalMargin) width: kQuestionBlockWidth height: kQuestionBlockHeight left: kQuestionBlockHorizontalMargin zIndex: @zIndexPassive + 1 _tag: "Question Block Blocker" @top += overlayViewOptions.height new Hy.UI.ViewProxy(overlayViewOptions) # ---------------------------------------------------------------------------------------------------------------- formatText: (text)-> output = "" chunks = text.split("|") for i in [1..chunks.length] if i > 1 # output += "\n" output += " " output += chunks[i-1] numLines = chunks.length if chunks[chunks.length-1].length is 0 numLines-- {numLines: numLines, text: output} # ---------------------------------------------------------------------------------------------------------------- createAnswerBlocks: ()-> answerItems = [ {index: 0, label: "A", height: kAnswerBlockHeight, width: kAnswerBlockWidth, left: 0, top: 0} {index: 1, label: "B", height: kAnswerBlockHeight, width: kAnswerBlockWidth, left: kAnswerBlockWidth + kAnswerBlockHorizontalPadding, top: 0} {index: 2, label: "C", height: kAnswerBlockHeight, width: kAnswerBlockWidth, left: 0, top: kAnswerBlockHeight + kAnswerBlockVerticalPadding} {index: 3, label: "D", height: kAnswerBlockHeight, width: kAnswerBlockWidth, left: kAnswerBlockWidth + kAnswerBlockHorizontalPadding, top: kAnswerBlockHeight + kAnswerBlockVerticalPadding} ] answerContainerOptions = top: (@top += kAnswerContainerVerticalMargin) left: kAnswerContainerHorizontalMargin height: kAnswerContainerHeight width: kAnswerContainerWidth _tag: "Answer Container" zIndex: @zIndexActive + 1 @answersContainer = new Hy.UI.ViewProxy(answerContainerOptions) @answerBlocks = [] this.createAnswerBlock(answerItem) for answerItem in answerItems @answersContainer # ---------------------------------------------------------------------------------------------------------------- answerBlockOptions: (answerItem)-> height : answerItem.height, width : answerItem.width, top : answerItem.top, left : answerItem.left, _tag : "Answer Container #{answerItem.label}" # ---------------------------------------------------------------------------------------------------------------- createAnswerBlock: (answerItem)-> # For direct play fnClick = (evt)=> this.answerBlockClicked(evt) answerBlockView = new Hy.UI.ViewProxy(this.answerBlockOptions(answerItem)) answerBlockView.addEventListener("click", fnClick) @answerBlocks.push {answerBlockView: answerBlockView, index: answerItem.index, label: answerItem.label} @answersContainer.addChild(answerBlockView) this # ---------------------------------------------------------------------------------------------------------------- answerBlockClicked: (evt)-> answerBlock = _.detect(@answerBlocks, (b)=>b.answerBlockView.getView() is evt.source) Hy.Trace.debug "QuestionPage::answerBlockClicked (label=#{if answerBlock? then answerBlock.label else "?"} allowEvents=#{this.getAllowEvents()} showingAnswers=#{@showingAnswers} consoleAnswered=#{@consoleAnswered} showingAnswersClicked=#{@showingAnswersClicked} PageState.state=#{PageState.get().getState()})" fn = null if this.getAllowEvents() if answerBlock? if @showingAnswers if not @showingAnswersClicked @showingAnswersClicked = true fn = ()=> Hy.Trace.debug "QuestionPage::answerBlockClicked (done showing answers)" this.getApp().questionAnswerCompleted() null else if not @consoleAnswered @consoleAnswered = true this.webViewPanelShowConsoleSelection(answerBlock.index) fn = ()=> Hy.Trace.debug "QuestionPage::answerBlockClicked (console answered)" this.getApp().consolePlayerAnswered(answerBlock.index) null if fn? this.haltCountdown() Hy.Utils.Deferral.create(0, ()=>fn()) null # ---------------------------------------------------------------------------------------------------------------- createAnswerCritterPanel: ()-> options = zIndex: @zIndexActive left: 0 bottom: 0 @container.addChild(@answerCritterPanel = new Hy.Panels.AnswerCritterPanel(options)) this # ---------------------------------------------------------------------------------------------------------------- countdownSound: (value)-> sound = null if not @showingAnswers and value isnt 0 sound = @soundKeys[@soundCounter++ % @nSounds] sound # ---------------------------------------------------------------------------------------------------------------- playerAnswered: (response)-> @answerCritterPanel.playerAnswered(response) # ---------------------------------------------------------------------------------------------------------------- revealAnswer: ()-> this.webViewPanelRevealAnswer(@contestQuestion.indexCorrectAnswer) # We want to display highest scorers first correct = [] incorrect = [] for response in Hy.Contest.ContestResponse.selectByQuestionID(@contestQuestion.getQuestionID()) if response.getCorrect() correct.push response else incorrect.push response sortedCorrect = correct.sort((r1, r2)=> r2.getScore() - r1.getScore()) topScore = null fnResponse = (response)=> # We want to display first place scorers differently t = if topScore? response.getScore() is topScore else topScore = response.getScore() true @answerCritterPanel.playerAnswered(response, true, t) for response in sortedCorrect fnResponse(response) for response in incorrect fnResponse(response) this # ================================================================================================================== class ContestCompletedPage extends NotifierPage # ---------------------------------------------------------------------------------------------------------------- constructor: (state, app)-> super state, app @top = 65 @defaultZIndex = 40 this.addBackground(@top) @top += 25 this.addGameOverText() this.addPlayAgainButtonAndText() # this.addAnimation() this # ---------------------------------------------------------------------------------------------------------------- addBackground: (top)-> @backgroundOptions = top: top height: 635 width: 800 image: "assets/icons/scoreboard-background.png" zIndex: @defaultZIndex-1 _tag: "Scoreboard Background" @container.addChild(new Hy.UI.ImageViewProxy(@backgroundOptions)) # ---------------------------------------------------------------------------------------------------------------- addGameOverText: ()-> height = 74 options = image: "assets/icons/label-Game-Over.png" top: @top height: 74 width: 374 zIndex: @defaultZIndex _tag: "Game Over Text" @top += height @container.addChild(@gameOverText = new Hy.UI.ImageViewProxy(options)) this # ---------------------------------------------------------------------------------------------------------------- addPlayAgainButtonAndText: ()-> height = 72 buttonOptions = top: (@top += 20) height: height width: height backgroundImage: "assets/icons/button-play-small-blue.png" zIndex: @defaultZIndex _tag: "Play Again" @container.addChild(@playAgainButton = new Hy.UI.ButtonProxy(buttonOptions)) textOptions = top: @top height: height # width: 120 # borderColor: Hy.UI.Colors.white zIndex: @defaultZIndex padding = 20 this.addButtonText(Hy.UI.ViewProxy.mergeOptions(textOptions, {text: "play", textAlign: "right", right: (Hy.UI.iPad.screenWidth/2) + (height/2) + padding})) this.addButtonText(Hy.UI.ViewProxy.mergeOptions(textOptions, {text: "again", textAlign: "left", left: (Hy.UI.iPad.screenWidth/2) + (height/2) + padding})) @playAgainButtonClicked = false @fnClickPlayAgain = (evt)=> if not @playAgainButtonClicked @playAgainButtonClicked = true this.playAgainClicked() null @playAgainButton.addEventListener("click", @fnClickPlayAgain) @top += height this # ---------------------------------------------------------------------------------------------------------------- addButtonText: (options)-> defaultOptions = font: Hy.UI.Fonts.specBigMrF color: Hy.UI.Colors.white zIndex: @defaultZIndex + 1 _tag: "Button Text" @container.addChild(new Hy.UI.LabelProxy(Hy.UI.ViewProxy.mergeOptions(defaultOptions, options))) this # ---------------------------------------------------------------------------------------------------------------- createScoreboardCritterPanel: ()-> padding = 10 width = @backgroundOptions.width height = @backgroundOptions.height - ((@top - @backgroundOptions.top) + (2*padding)) scoreboardOptions = top: @top height: height width: width left: (Hy.UI.iPad.screenWidth - width)/2 zIndex: @defaultZIndex+2 _orientation: "horizontal" # borderWidth: 1 # borderColor: Hy.UI.Colors.red @container.addChild(@scoreboardCritterPanel = new Hy.Panels.ScoreboardCritterPanel(scoreboardOptions)) @scoreboardCritterPanel # ---------------------------------------------------------------------------------------------------------------- initialize: (fnNotify)-> super @playAgainButtonClicked = false # @nQuestions = nQuestions # @questionInfoPanel?.initialize @nQuestions, @nQuestions, this.labelColor() this.createScoreboardCritterPanel().initialize().displayScores() true # ---------------------------------------------------------------------------------------------------------------- start: ()-> super this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> if @scoreboardCritterPanel? this.container.removeChild(@scoreboardCritterPanel) @scoreboardCritterPanel.stop() @scoreboardCritterPanel = null super this # ---------------------------------------------------------------------------------------------------------------- playAgainClicked: ()-> Hy.Utils.Deferral.create(0, ()=>this.getApp().contestRestart(true)) # ---------------------------------------------------------------------------------------------------------------- getLeaderboard: ()-> @scoreboardCritterPanel?.getLeaderboard() # ---------------------------------------------------------------------------------------------------------------- addAnimation: ()-> # @animateInScenes = null @animateOutScenes = null animationContainerOptions = top: 0 left: 0 right: 0 bottom: 0 zIndex: 50 # [@animateInScenes, sceneTotalDuration] = this.buildAnimationFromScenes(this.initAnimateInScenes()) # [@animateOutScenes, @animateOutSceneDuration] = this.buildAnimationFromScenes(this.initAnimateOutScenes(), @animateoutScenes) this # ---------------------------------------------------------------------------------------------------------------- animateOut: ()-> [@animateOutScenes, @animateOutSceneDuration] = this.buildAnimationFromScenes(this.initAnimateOutScenes(), @animateoutScenes) this.animateScenes(@animateOutScenes) @animateOutSceneDuration # ---------------------------------------------------------------------------------------------------------------- initAnimateOutScenes: ()-> [ {image: "intro-TV", imageOptions: {zIndex: 50}, animationOptions: [{_incrementalDelay: 0, duration: 0, opacity: 1.0}]} # {image: "black", imageOptions: {zIndex: 49, top: 0, left: 0, right: 0, bottom: 0, opacity: 0}, animationOptions: [{_incrementalDelay: 0, duration: 1500, opacity: 1.0}, {_incrementalDelay: 500, duration: 0, opacity: 0}]} {image: "intro-left-front-curtain", imageOptions: {zIndex: 45, top: 0, width:514, height:768, right: Hy.UI.iPad.screenWidth, borderColor: Hy.UI.Colors.white}, animationOptions: [{_incrementalDelay: 0, duration: 1500, right: Hy.UI.iPad.screenWidth/2}, {_incrementalDelay: 0, duration: 100, right: Hy.UI.iPad.screenWidth}]} {image: "intro-right-front-curtain", imageOptions: {zIndex: 45, top: 0, width:514, height:768, left: Hy.UI.iPad.screenWidth, borderColor: Hy.UI.Colors.white}, animationOptions: [{_incrementalDelay: 0, duration: 1500, left: (Hy.UI.iPad.screenWidth/2)-5}, {_incrementalDelay: 0, duration: 100, left: Hy.UI.iPad.screenWidth}]} ] # ================================================================================================================== class PageState gOperationIndex = 0 @Any = -1 @Unknown = 0 @Splash = 1 @Intro = 2 @Start = 3 @Question = 4 @Answer = 5 @Scoreboard = 6 @Completed = 7 @About = 8 @UCCInfo = 9 @JoinCodeInfo = 10 stateToPageClassMap = [ {state: PageState.Splash, pageClass: SplashPage, background: Hy.UI.Backgrounds.splashPage}, {state: PageState.Intro, pageClass: IntroPage, background: null}, {state: PageState.Start, pageClass: StartPage, background: Hy.UI.Backgrounds.startPage} {state: PageState.Question, pageClass: QuestionPage, background: Hy.UI.Backgrounds.stageNoCurtain} {state: PageState.Answer, pageClass: QuestionPage, background: Hy.UI.Backgrounds.stageNoCurtain} {state: PageState.Completed, pageClass: ContestCompletedPage, background: Hy.UI.Backgrounds.stageCurtain} {state: PageState.About, pageClass: AboutPage, background: Hy.UI.Backgrounds.startPage} {state: PageState.UCCInfo, pageClass: UserCreatedContentInfoPage, background: Hy.UI.Backgrounds.startPage} {state: PageState.JoinCodeInfo, pageClass: JoinCodeInfoPage, background: Hy.UI.Backgrounds.startPage} ] @defaultAnimateOut = {duration: 250, _startOpacity: 1, opacity: 0} @defaultAnimateIn = {duration: 250, _startOpacity: 0, opacity: 1} transitionMaps = [ { oldState: [PageState.Any], newState: [PageState.Splash], animateOutBackground: Hy.UI.Backgrounds.splashPage, interstitialBackground: Hy.UI.Backgrounds.splashPage, animateInBackground: Hy.UI.Backgrounds.splashPage }, { oldState: [PageState.Splash], newState: [PageState.Intro], animateOutBackground: Hy.UI.Backgrounds.splashPage, interstitialBackground: Hy.UI.Backgrounds.splashPage, animateInBackground: Hy.UI.Backgrounds.splashPage, animateInFn: ((page)=>page.animateIn()), }, { oldState: [PageState.Intro], newState: [PageState.Start], animateOutFn: ((page)=>page.animateOut()), animateOutBackground: Hy.UI.Backgrounds.splashPage, interstitialBackground: Hy.UI.Backgrounds.splashPage, animateInBackground: Hy.UI.Backgrounds.splashPage, animateIn: {duration: 500, _startOpacity: 0, opacity: 1} }, { # 2.5.0: To handle case where we're backgrounded. See ConsoleApp::resumedPage for details oldState: [PageState.Any], newState: [PageState.Start], interstitialBackground: Hy.UI.Backgrounds.splashPage, animateInBackground: Hy.UI.Backgrounds.splashPage, animateIn: {duration: 500, _startOpacity: 0, opacity: 1} }, { oldState: [PageState.Start], newState: [PageState.Question], animateOut: {duration: 500, opacity: 0}, animateInFn: ((page)=>page.animateIn(true)) }, { oldState: [PageState.Question], newState: [PageState.Answer], animateOut: null, delay: 500, animateIn: null }, { oldState: [PageState.Answer], newState: [PageState.Question], animateOutFn: ((page)=>page.animateOut(false)), animateInFn: ((page)=>page.animateIn(false)), }, { oldState: [PageState.Question, PageState.Answer], newState: [PageState.Completed], animateOutFn: ((page)=>page.animateOut(true)), animateIn: {duration: 500, _startOpacity: 0, opacity: 1} }, { oldState: [PageState.Question, PageState.Answer], newState: [PageState.Start], animateOutFn: ((page)=>page.animateOut(true)), animateIn: @defaultAnimateIn, }, { oldState: [PageState.Completed], newState: [PageState.Start], animateOut: @defaultAnimateOut, animateIn: @defaultAnimateIn, }, { oldState: [PageState.About, PageState.Start], newState: [PageState.Start, PageState.About], animateOut: @defaultAnimateOut, animateIn: @defaultAnimateIn, }, { oldState: [PageState.UCCInfo, PageState.Start], newState: [PageState.Start, PageState.UCCInfo], animateOut: @defaultAnimateOut, animateIn: @defaultAnimateIn, }, { oldState: [PageState.JoinCodeInfo, PageState.Start], newState: [PageState.Start, PageState.JoinCodeInfo], animateOut: @defaultAnimateOut, animateIn: @defaultAnimateIn, } ] gInstance = null # ---------------------------------------------------------------------------------------------------------------- @findTransitionMap: (oldPage, newPageState)-> for map in transitionMaps if (oldPage? and oldPage.state in map.oldState) or (PageState.Any in map.oldState) # 2.5.0 if (newPageState in map.newState) or (PageState.Any in map.newState) # 2.5.0 return map return null # ---------------------------------------------------------------------------------------------------------------- @getPageMap: (pageState)-> for map in stateToPageClassMap if map.state is pageState return map return null # ---------------------------------------------------------------------------------------------------------------- @getPageName: (pageState)-> name = null map = this.getPageMap(pageState) if map? name = map.pageClass.name return name # ---------------------------------------------------------------------------------------------------------------- @findPage: (pageState)-> page = if (map = this.getPageMap(pageState))? Page.findPage(map.pageClass) else null page # ---------------------------------------------------------------------------------------------------------------- @getPage: (pageState)-> page = if (map = this.getPageMap(pageState))? Page.getPage(map) else null page # ---------------------------------------------------------------------------------------------------------------- @get: ()-> gInstance # ---------------------------------------------------------------------------------------------------------------- @doneWithPage: (pageState)-> if (map = this.getPageMap(pageState))? Page.doneWithPage(map) null # ---------------------------------------------------------------------------------------------------------------- @init: (app)-> if not gInstance? gInstance = new PageState(app) gInstance # ---------------------------------------------------------------------------------------------------------------- display: ()-> s = "PageState::display" s += "(" if (state = this.getState())? s += "#{state.oldPageState}->#{state.newPageState}" s += ")" s # ---------------------------------------------------------------------------------------------------------------- constructor: (@app)-> this.initialize() this # ---------------------------------------------------------------------------------------------------------------- initialize: ()-> @state = null timedOperation = new Hy.Utils.TimedOperation("PAGE INITIALIZATION") for map in transitionMaps for v in ["videoOut", "videoIn"] if (videoOptions = map[v])? timedOperation.mark("video: #{videoOptions._url}") map["_#{v}Instance"] = player = Hy.Media.VideoPlayer.create(videoOptions) # player.prepareToPlay().play() timedOperation.mark("DONE") this # ---------------------------------------------------------------------------------------------------------------- stop: ()-> if (page = this.getApp().getpage())? page?.closeWindow() page?.stop() this.getApp().setPage(null) this # ---------------------------------------------------------------------------------------------------------------- getApp: ()-> @app # ---------------------------------------------------------------------------------------------------------------- getState: ()-> @state # ---------------------------------------------------------------------------------------------------------------- setState: (state)-> @state = state # ---------------------------------------------------------------------------------------------------------------- isTransitioning: ()-> if (state = this.getState(false))? state.newPageState else null # ---------------------------------------------------------------------------------------------------------------- getOldPageState: ()-> this.getState()?.oldPageState # ---------------------------------------------------------------------------------------------------------------- stopTransitioning: ()-> this.setState(null) # ---------------------------------------------------------------------------------------------------------------- addPostTransitionAction: (fnPostTransition)-> if (state = this.getState())? @postFunctions.push(fnPostTransition) this # ---------------------------------------------------------------------------------------------------------------- hasPostFunctions: ()-> _.size(@postFunctions) > 0 # ---------------------------------------------------------------------------------------------------------------- # I've re-written this function about 5 times so far. "This time for sure". # I've re-written this function about 6 times so far. "This time for sure". # showPage: (newPageState, fn_newPageInit, postFunctions = [])-> initialState = oldPage: this.getApp().getPage() # newPage: Hy.Pages.PageState.getPage(newPageState) newPage_: null # defer creating the new page oldPageState: (if (oldPage = this.getApp().getPage())? then oldPage.getState() else null) newPageState: newPageState fn_newPageInit: fn_newPageInit if (existingState = this.getState())? s = "OLD STATE: oldPageState=#{if existingState.oldPage? then existingState.oldPage.getState() else "(NONE)"} newPageState=#{existingState.newPageState}" s += " NEW STATE: oldPageState=#{if initialState.oldPage? then initialState.oldPage.getState() else "(NONE)"} newPageState=#{initialState.newPageState}" Hy.Trace.debug "PageState::showPage (RECURSION #{s})", true new Hy.Utils.ErrorMessage("fatal", "PageState::showPage", s) return @postFunctions = [].concat(postFunctions) this.setState(this.showPage_setup(initialState)) this.showPage_execute() this # ---------------------------------------------------------------------------------------------------------------- showPage_setup: (state)-> state.spec = Hy.Pages.PageState.findTransitionMap(state.oldPage, state.newPageState) state.delay = if state.spec? then (if state.spec.delay? then state.spec.delay else 0) else 0 state.exitVideo = if state.spec? then state.spec._videoOutInstance else null state.introVideo = if state.spec? then state.spec._videoInInstance else null state.animateOut = if state.spec? then state.spec.animateOut else Hy.Pages.PageState.defaultAnimateOut state.animateOutFn = if state.spec? then state.spec.animateOutFn state.animateInFn = if state.spec? then state.spec.animateInFn state.animateIn = if state.spec? then state.spec.animateIn else Hy.Pages.PageState.defaultAnimateIn state.previousVideo = null state.networkServiceLevel = null state.operationIndex = ++gOperationIndex # For logging state.fnIndex = 0 # state.fnCompleted = false fnDebug = (fnName, s="")=> p = "" if (state = this.getState())? p += "##{state.operationIndex} fn:#{state.fnIndex} " p += if (oldPageState = this.getState().oldPageState)? then oldPageState else "NONE" p += ">#{this.getState().newPageState}" else p = "(NO STATE!)" Hy.Trace.debug("PageState::showPage (#{p} #{fnName} #{if s? then s else ""})") null fnExecuteNext = (restart = false)=> ok = false if (state = this.getState())? if restart and not state.fnCompleted # Try the last operation again null else ++state.fnIndex if state.fnIndex <= state.fnChain.length state.fnCompleted = false ok = true state.fnChain[state.fnIndex-1]() state.fnCompleted = true ok fnExecutePostFunction = ()=> if (f = @postFunctions.shift())? f(this.getApp().getPage()) null fnExecuteRemaining = ()=> if (state = this.getState())? while fnExecuteNext() null this.showPage_exit(state.operationIndex) while _.size(@postFunctions) > 0 fnExecutePostFunction() null fnIndicateActive = ()=> Hy.Network.NetworkService.setIsActive() fnExecuteNext() null fnSuspendNetwork = ()=> fnDebug("fnSuspendNetwork") if (ns = Hy.Network.NetworkService.get())? l = this.getState().networkServiceLevel = ns.getServiceLevel() fnDebug("fnSuspendNetwork (from \"#{l}\")") ns.setSuspended() fnExecuteNext() null fnResumeNetwork = ()=> fnDebug("fnResumeNetwork") if (serviceLevel = this.getState().networkServiceLevel)? Hy.Network.NetworkService.get().setServiceLevel(serviceLevel) fnExecuteNext() null # Returns existing instance of this kind of page, if it exists. fnCheckNewPage = ()=> Hy.Pages.PageState.findPage(state.newPageState) fnGetNewPage = ()=> this.getState().newPage_ fnCreateNewPage = ()=> s = this.getState() if not s.newPage_? s.newPage_ = Hy.Pages.PageState.getPage(state.newPageState) s.newPage_ fnSetBackground = (backgroundName = null)=> fnDebug("fnSetBackground", backgroundName) bkgnd = if backgroundName? then this.getState().spec?[backgroundName] else null this.getApp().setBackground(bkgnd) fnExecuteNext() fnCleanupVideo = (video)=> fnDebug("fnCleanupVideo") video.setUIProperty("borderColor", Hy.UI.Colors.green) fnExecuteNext() null fnPlayVideo = (video, preBackground, postBackground)=> fnDebug("fnPlayVideo") if this.getState().previousVideo? this.getState().previousVideo.release() video.setVideoProperty("backgroundImage", preBackground) f = ()=>fnCleanupVideo(video) video.prepareToPlay(f) this.getApp().getBackgroundWindow().add(video.getView()) this.getApp().setBackground(postBackground) video.setUIProperty("borderColor", Hy.UI.Colors.white) video.play() video.setUIProperty("borderColor", Hy.UI.Colors.red) this.getState().previousVideo = video null fnStopOldPage = ()=> fnDebug("fnStopOldPage") this.getState().oldPage?.stop() fnExecuteNext() null fnAnimateOut = ()=> fnDebug("fnAnimateOut") duration = 0 if (oldPage = this.getState().oldPage)? animateOut = this.getState().animateOut animateOutFn = this.getState().animateOutFn if animateOut? if animateOut._startOpacity? oldPage.window.setUIProperty("opacity", animateOut._startOpacity) oldPage.animateWindow(animateOut) duration = animateOut.duration else if animateOutFn? duration = animateOutFn(oldPage) if duration is -1 # -1 means we'll get called back to resume page transition fnDebug("fnAnimateOut", "WAITING") else Hy.Utils.Deferral.create(duration, fnExecuteNext) null fnCloseOldPage = ()=> fnDebug("fnCloseOldPage") if (oldPage = this.getState().oldPage)? newPage = fnCheckNewPage() # Might be null if page hasn't been created/used before #this.getState().newPage if oldPage isnt newPage oldPage.closeWindow() this.getApp().setPage(null) fnExecuteNext() null fnPlayExitVideo = ()=> fnDebug("fnPlayExitVideo") if this.getState().exitVideo? fnPlayVideo(this.getState().exitVideo, this.getState().spec.animateOutBackground, this.getState().spec.interstitialBackground) else fnExecuteNext() null fnPlayIntroVideo = ()=> fnDebug("fnPlayIntroVideo") if this.getState().introVideo? fnPlayVideo(this.getState().introVideo, this.getState().spec.interstitialBackground, this.getState().spec.animateInBackground) else fnExecuteNext() null fnInitNewPage = ()=> fnDebug("fnInitNewPage") newPage = fnCreateNewPage() #this.getState().newPage this.getApp().setPage(newPage) newPage.setState(this.getState().newPageState) if (result = this.getState().fn_newPageInit(newPage)) fnExecuteNext() else fnDebug("fnInitNewPage: waiting") fnAnimateInAndOpenNewPage = ()=> fnDebug("fnAnimateInAndOpenNewPage") duration = 0 newPage = fnGetNewPage() #this.getState().newPage animateIn = this.getState().animateIn animateInFn = this.getState().animateInFn if animateIn? duration = animateIn.duration if animateIn._startOpacity? newPage.window.setUIProperty("opacity", animateIn._startOpacity) if newPage is this.getState().oldPage newPage.animateWindow(animateIn) else newPage.openWindow(animateIn) else if animateInFn? # if newPage isnt this.getState().oldPage # newPage.openWindow() duration = animateInFn(newPage) else if newPage isnt this.getState().oldPage newPage.openWindow({opacity:1, duration:0}) else newPage.animateWindow({opacity:1, duration:0}) if duration is -1 # -1 means we'll get called back to resume page transition fnDebug("fnAnimateInAndOpenNewPage", "Waiting for callback") else fnDebug("fnAnimateInAndOpenNewPage", "Waiting #{duration}") Hy.Utils.Deferral.create(duration, fnExecuteNext) null fnStartNewPage = ()=> fnDebug("fnStartNewPage") fnGetNewPage().start() fnExecuteNext() null # We do it this way since it makes it easier to change the order and timing of things, # and ensure the integrity of the transition across pause/resumed state.fnChain = # 2.5.0: removed default fnChain... [ fnSuspendNetwork, fnStopOldPage, fnAnimateOut, ()=>fnSetBackground("animateOutBackground"), fnCloseOldPage, fnPlayExitVideo, ()=>fnSetBackground("interstitialBackground"), ()=>Hy.Utils.Deferral.create(this.getState().delay, fnExecuteNext), fnPlayIntroVideo, ()=>fnSetBackground("animateInBackground"), fnInitNewPage, fnAnimateInAndOpenNewPage, ()=>fnSetBackground(), # ()=>Hy.Utils.Deferral.create(0, fnStartNewPage), # 2.5.0 fnStartNewPage, fnResumeNetwork, fnIndicateActive, fnExecuteRemaining ] state.fnExecuteNext = fnExecuteNext state # ---------------------------------------------------------------------------------------------------------------- showPage_execute: (restart = false)-> @state?.fnExecuteNext(restart) this # ---------------------------------------------------------------------------------------------------------------- showPage_exit: (operationIndex)-> Hy.Trace.debug "PageState::showPage_exit (##{operationIndex})" this.setState(null) # ---------------------------------------------------------------------------------------------------------------- resumed: (restart = false)-> Hy.Trace.debug "PageState::resumed" if this.getState()? this.showPage_execute(restart) else if (page = this.getApp().getPage())? page.resumed() else Hy.Trace.debug "PageState::showPage (RESUMED BUT NO WHERE TO GO)" null # ================================================================================================================== Hyperbotic.Pages = Page: Page NotifierPage: NotifierPage IntroPage: IntroPage SplashPage: SplashPage AboutPage: AboutPage UserCreatedContentInfoPage: UserCreatedContentInfoPage StartPage: StartPage QuestionPage: QuestionPage ContestCompletedPage: ContestCompletedPage PageState: PageState CountdownPage: CountdownPage
[ { "context": "cription: \"\"\n keywords: \"\"\n author: \"feilaoda\"\n year: \"2012\"\n copyright: \"&copy; u", "end": 104, "score": 0.9804194569587708, "start": 96, "tag": "USERNAME", "value": "feilaoda" }, { "context": " \"noodp,noydir,index,follow\"\n github: \"User\"\n email: \"azhenglive@gmail.com\"\n\n titles", "end": 260, "score": 0.973259687423706, "start": 256, "tag": "USERNAME", "value": "User" }, { "context": "x,follow\"\n github: \"User\"\n email: \"azhenglive@gmail.com\"\n\n titles:\n index: \"%{name}\"\n show: \"%{nam", "end": 299, "score": 0.9999293684959412, "start": 279, "tag": "EMAIL", "value": "azhenglive@gmail.com" } ]
app/config/shared/locales/en.coffee
MagicPower2/Power
0
module.exports = title: "Power" description: "" keywords: "" author: "feilaoda" year: "2012" copyright: "&copy; undefined feilaoda. All rights reserved." robots: "noodp,noydir,index,follow" github: "User" email: "azhenglive@gmail.com" titles: index: "%{name}" show: "%{name} overview" new: "Create a new %{name}" edit: "Editing %{name}" links: sessions: "Sessions" tasklists: "Tasklists" tasks: "Tasks" users: "Users" projects: "Projects" default: "%{name}" home: "Home" docs: "Docs" openGraph: siteName: "Power" title: "Power" description: "" type: "website" url: "" image: ""
224387
module.exports = title: "Power" description: "" keywords: "" author: "feilaoda" year: "2012" copyright: "&copy; undefined feilaoda. All rights reserved." robots: "noodp,noydir,index,follow" github: "User" email: "<EMAIL>" titles: index: "%{name}" show: "%{name} overview" new: "Create a new %{name}" edit: "Editing %{name}" links: sessions: "Sessions" tasklists: "Tasklists" tasks: "Tasks" users: "Users" projects: "Projects" default: "%{name}" home: "Home" docs: "Docs" openGraph: siteName: "Power" title: "Power" description: "" type: "website" url: "" image: ""
true
module.exports = title: "Power" description: "" keywords: "" author: "feilaoda" year: "2012" copyright: "&copy; undefined feilaoda. All rights reserved." robots: "noodp,noydir,index,follow" github: "User" email: "PI:EMAIL:<EMAIL>END_PI" titles: index: "%{name}" show: "%{name} overview" new: "Create a new %{name}" edit: "Editing %{name}" links: sessions: "Sessions" tasklists: "Tasklists" tasks: "Tasks" users: "Users" projects: "Projects" default: "%{name}" home: "Home" docs: "Docs" openGraph: siteName: "Power" title: "Power" description: "" type: "website" url: "" image: ""
[ { "context": "# Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>\n#\n# Redistribution and u", "end": 35, "score": 0.9998366236686707, "start": 22, "tag": "NAME", "value": "Yusuke Suzuki" }, { "context": "# Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>\n#\n# Redistribution and use in source and binary", "end": 58, "score": 0.9999339580535889, "start": 37, "tag": "EMAIL", "value": "utatane.tea@gmail.com" } ]
src/hook.coffee
HBOCodeLabs/ibrik
0
# Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. fs = require 'fs' Module = require 'module' istanbul = require 'istanbul' coffee = require 'coffee-script' originalLoader = require.extensions['.coffee'] originalJSLoader = null hook = Object.create istanbul.hook transformFn = (matcher, transformer, verbose) -> (code, filename) -> shouldHook = matcher filename changed = no if shouldHook console.error "Module load hook: transform [#{filename}]" if verbose try transformed = transformer code, filename changed = yes catch ex console.error 'Transformation error; return original code' console.error ex console.error ex.stack transformed = code else transformed = code {code: transformed, changed} hook.hookRequire = (matcher, transformer, options = {}) -> fn = transformFn matcher, transformer, options.verbose postLoadHook = null if options.postLoadHook and typeof options.postLoadHook is 'function' postLoadHook = options.postLoadHook require.extensions['.coffee'] = (module, filename) -> ret = fn (fs.readFileSync filename, 'utf8'), filename if ret.changed module._compile ret.code, filename else originalLoader module, filename postLoadHook filename if postLoadHook istanbul.hook.hookRequire matcher, transformer, options originalJSLoader = require.extensions['.js'] require.extensions['.js'] = (module, filename) -> # When we're testing code that calls require('coffee-script'), # our loader for .coffee is trounced. I'm not happy about this, but # suppress re-loading coffee-script here if not endsWith(filename, 'coffee-script.js') originalJSLoader module, filename return hook.unhookRequire = -> if originalJSLoader require.extensions['.js'] = originalJSLoader originalJSLoader = null do istanbul.hook.unhookRequire require.extensions['.coffee'] = originalLoader endsWith = (string, endString) -> return false if string.length < endString.length return string.substr(string.length - endString.length) is endString module.exports = hook # vim: set sw=4 ts=4 et tw=80 :
202958
# Copyright (C) 2012 <NAME> <<EMAIL>> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. fs = require 'fs' Module = require 'module' istanbul = require 'istanbul' coffee = require 'coffee-script' originalLoader = require.extensions['.coffee'] originalJSLoader = null hook = Object.create istanbul.hook transformFn = (matcher, transformer, verbose) -> (code, filename) -> shouldHook = matcher filename changed = no if shouldHook console.error "Module load hook: transform [#{filename}]" if verbose try transformed = transformer code, filename changed = yes catch ex console.error 'Transformation error; return original code' console.error ex console.error ex.stack transformed = code else transformed = code {code: transformed, changed} hook.hookRequire = (matcher, transformer, options = {}) -> fn = transformFn matcher, transformer, options.verbose postLoadHook = null if options.postLoadHook and typeof options.postLoadHook is 'function' postLoadHook = options.postLoadHook require.extensions['.coffee'] = (module, filename) -> ret = fn (fs.readFileSync filename, 'utf8'), filename if ret.changed module._compile ret.code, filename else originalLoader module, filename postLoadHook filename if postLoadHook istanbul.hook.hookRequire matcher, transformer, options originalJSLoader = require.extensions['.js'] require.extensions['.js'] = (module, filename) -> # When we're testing code that calls require('coffee-script'), # our loader for .coffee is trounced. I'm not happy about this, but # suppress re-loading coffee-script here if not endsWith(filename, 'coffee-script.js') originalJSLoader module, filename return hook.unhookRequire = -> if originalJSLoader require.extensions['.js'] = originalJSLoader originalJSLoader = null do istanbul.hook.unhookRequire require.extensions['.coffee'] = originalLoader endsWith = (string, endString) -> return false if string.length < endString.length return string.substr(string.length - endString.length) is endString module.exports = hook # vim: set sw=4 ts=4 et tw=80 :
true
# Copyright (C) 2012 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. fs = require 'fs' Module = require 'module' istanbul = require 'istanbul' coffee = require 'coffee-script' originalLoader = require.extensions['.coffee'] originalJSLoader = null hook = Object.create istanbul.hook transformFn = (matcher, transformer, verbose) -> (code, filename) -> shouldHook = matcher filename changed = no if shouldHook console.error "Module load hook: transform [#{filename}]" if verbose try transformed = transformer code, filename changed = yes catch ex console.error 'Transformation error; return original code' console.error ex console.error ex.stack transformed = code else transformed = code {code: transformed, changed} hook.hookRequire = (matcher, transformer, options = {}) -> fn = transformFn matcher, transformer, options.verbose postLoadHook = null if options.postLoadHook and typeof options.postLoadHook is 'function' postLoadHook = options.postLoadHook require.extensions['.coffee'] = (module, filename) -> ret = fn (fs.readFileSync filename, 'utf8'), filename if ret.changed module._compile ret.code, filename else originalLoader module, filename postLoadHook filename if postLoadHook istanbul.hook.hookRequire matcher, transformer, options originalJSLoader = require.extensions['.js'] require.extensions['.js'] = (module, filename) -> # When we're testing code that calls require('coffee-script'), # our loader for .coffee is trounced. I'm not happy about this, but # suppress re-loading coffee-script here if not endsWith(filename, 'coffee-script.js') originalJSLoader module, filename return hook.unhookRequire = -> if originalJSLoader require.extensions['.js'] = originalJSLoader originalJSLoader = null do istanbul.hook.unhookRequire require.extensions['.coffee'] = originalLoader endsWith = (string, endString) -> return false if string.length < endString.length return string.substr(string.length - endString.length) is endString module.exports = hook # vim: set sw=4 ts=4 et tw=80 :
[ { "context": "lizer = DS.RESTSerializer.extend\n\n primaryKey: '_id'\n\n normalize: (type, hash, prop) ->\n @normali", "end": 169, "score": 0.5948894023895264, "start": 167, "tag": "KEY", "value": "id" }, { "context": "ments = []\n for k, v of attachments\n key = \"#{hash._id}/#{k}\"\n attachment =\n id: key\n conten", "end": 981, "score": 0.9934120178222656, "start": 963, "tag": "KEY", "value": "\"#{hash._id}/#{k}\"" }, { "context": " findManyWithRev: (store, type, ids) ->\n key = Ember.String.pluralize(type.typeKey)\n self = @\n d", "end": 6017, "score": 0.5867030620574951, "start": 6012, "tag": "KEY", "value": "Ember" }, { "context": "anyWithRev: (store, type, ids) ->\n key = Ember.String.pluralize(type.typeKey)\n self = @\n docs = {}\n docs", "end": 6034, "score": 0.7544629573822021, "start": 6018, "tag": "KEY", "value": "String.pluralize" } ]
src/document-adapter.coffee
ekrabismi/CRUD-Ember-couchdb
0
### @namespace EmberCouchDBKit @class DocumentSerializer @extends DS.RESTSerializer ### EmberCouchDBKit.DocumentSerializer = DS.RESTSerializer.extend primaryKey: '_id' normalize: (type, hash, prop) -> @normalizeId(hash) @normalizeAttachments(hash["_attachments"], type.typeKey, hash) @addHistoryId(hash) @normalizeUsingDeclaredMapping(type, hash) @normalizeAttributes(type, hash) @normalizeRelationships(type, hash) return @normalizeHash[prop](hash) if @normalizeHash and @normalizeHash[prop] return hash if !hash @applyTransforms(type, hash) hash extractSingle: (store, type, payload, id, requestType) -> @_super(store, type, payload, id, requestType) serialize: (record, options) -> @_super(record, options) addHistoryId: (hash) -> hash.history = "%@/history".fmt(hash.id) normalizeAttachments: (attachments, type, hash) -> _attachments = [] for k, v of attachments key = "#{hash._id}/#{k}" attachment = id: key content_type: v.content_type digest: v.digest length: v.length stub: v.stub doc_id: hash._id rev: hash.rev file_name: k model_name: type revpos: v.revpos db: v.db EmberCouchDBKit.sharedStore.add('attachment', key, attachment) _attachments.push(key) hash.attachments = _attachments normalizeId: (hash) -> hash.id = (hash["_id"] || hash["id"]) normalizeRelationships: (type, hash) -> payloadKey = undefined key = undefined if @keyForRelationship type.eachRelationship ((key, relationship) -> payloadKey = @keyForRelationship(key, relationship.kind) return if key is payloadKey hash[key] = hash[payloadKey] delete hash[payloadKey] ), this serializeBelongsTo: (record, json, relationship) -> attribute = (relationship.options.attribute || "id") key = relationship.key belongsTo = record.belongsTo(key) return if Ember.isNone(belongsTo) json[key] = if (attribute == "id") then belongsTo.id else belongsTo.attr(attribute) json[key + "_type"] = belongsTo.typeKey if relationship.options.polymorphic serializeHasMany: (record, json, relationship) -> attribute = (relationship.options.attribute || "id") key = relationship.key relationshipType = record.type.determineRelationshipType(relationship) switch relationshipType when "manyToNone", "manyToMany", "manyToOne" json[key] = record.hasMany(key).mapBy(attribute) ### A `DocumentAdapter` should be used as a main adapter for working with models as a CouchDB documents. Let's consider: ```coffee EmberApp.DocumentAdapter = EmberCouchDBKit.DocumentAdapter.extend({db: db, host: host}) EmberApp.DocumentSerializer = EmberCouchDBKit.DocumentSerializer.extend() EmberApp.Document = DS.Model.extend title: DS.attr('title') type: DS.attr('string', {defaultValue: 'document'}) ``` The following available operations: ```coffee # GET /my_couchdb/:id @get('store').find('document', id) # POST /my_couchdb @get('store').createRecord('document', {title: "title"}).save() # update PUT /my_couchdb/:id @get('store').find('document', id).then((document) -> document.set('title', title) document.save() ) # DELETE /my_couchdb/:id @get('store').find('document', id).deleteRecord().save() ``` For more advanced tips and tricks, you should check available specs @namespace EmberCouchDBKit @class DocumentAdapter @extends DS.Adapter ### EmberCouchDBKit.DocumentAdapter = DS.Adapter.extend defaultSerializer: '_default' customTypeLookup: false typeViewName: "all" buildURL: -> host = Ember.get(this, "host") namespace = Ember.get(this, "namespace") url = [] url.push host if host url.push namespace if namespace url.push @get('db') url = url.join("/") url = "/" + url unless host url ajax: (url, type, normalizeResponce, hash) -> @_ajax('%@/%@'.fmt(@buildURL(), url || ''), type, normalizeResponce, hash) _ajax: (url, type, normalizeResponce, hash={}) -> adapter = this return new Ember.RSVP.Promise((resolve, reject) -> if url.split("/").pop() == "" then url = url.substr(0, url.length - 1) hash.url = url hash.type = type hash.dataType = 'json' hash.contentType = 'application/json; charset=utf-8' hash.context = adapter if hash.data && type != 'GET' hash.data = JSON.stringify(hash.data) if adapter.headers headers = adapter.headers hash.beforeSend = (xhr) -> Ember.keys(headers).forEach (key) -> xhr.setRequestHeader key, headers[key] unless hash.success hash.success = (json) -> _modelJson = normalizeResponce.call(adapter, json) Ember.run(null, resolve, _modelJson) hash.error = (jqXHR, textStatus, errorThrown) -> if (jqXHR) jqXHR.then = null Ember.run(null, reject, jqXHR) Ember.$.ajax(hash) ) _normalizeRevision: (json) -> if json && json._rev json.rev = json._rev delete json._rev json shouldCommit: (record, relationships) -> @_super.apply(arguments) find: (store, type, id) -> if @_checkForRevision(id) @findWithRev(store, type, id) else normalizeResponce = (data) -> @_normalizeRevision(data) _modelJson = {} _modelJson[type.typeKey] = data _modelJson @ajax(id, 'GET', normalizeResponce) findWithRev: (store, type, id, hash) -> [_id, _rev] = id.split("/")[0..1] url = "%@?rev=%@".fmt(_id, _rev) normalizeResponce = (data) -> @_normalizeRevision(data) _modelJson = {} data._id = id _modelJson[type.typeKey] = data _modelJson @ajax(url, 'GET', normalizeResponce, hash) findManyWithRev: (store, type, ids) -> key = Ember.String.pluralize(type.typeKey) self = @ docs = {} docs[key] = [] hash = {async: false} ids.forEach (id) => [_id, _rev] = id.split("/")[0..1] url = "%@?rev=%@".fmt(_id, _rev) url = '%@/%@'.fmt(@buildURL(), url) hash.url = url hash.type = 'GET' hash.dataType = 'json' hash.contentType = 'application/json; charset=utf-8' hash.success = (json) -> json._id = id self._normalizeRevision(json) docs[key].push(json) Ember.$.ajax(hash) docs findMany: (store, type, ids) -> if @_checkForRevision(ids[0]) @findManyWithRev(store, type, ids) else data = include_docs: true keys: ids normalizeResponce = (data) -> json = {} json[Ember.String.pluralize(type.typeKey)] = data.rows.getEach('doc').map((doc) => @_normalizeRevision(doc)) json @ajax('_all_docs?include_docs=true', 'POST', normalizeResponce, { data: data }) findQuery: (store, type, query, modelArray) -> designDoc = (query.designDoc || @get('designDoc')) query.options = {} unless query.options query.options.include_docs = true normalizeResponce = (data) -> json = {} json[designDoc] = data.rows.getEach('doc').map((doc) => @_normalizeRevision(doc)) json @ajax('_design/%@/_view/%@'.fmt(designDoc, query.viewName), 'GET', normalizeResponce, { context: this data: query.options }) findAll: (store, type) -> typeString = Ember.String.singularize(type.typeKey) designDoc = @get('designDoc') || typeString typeViewName = @get('typeViewName') normalizeResponce = (data) -> json = {} json[[Ember.String.pluralize(type.typeKey)]] = data.rows.getEach('doc').map((doc) => @_normalizeRevision(doc)) json data = include_docs: true key: '"' + typeString + '"' @ajax('_design/%@/_view/%@'.fmt(designDoc, typeViewName), 'GET', normalizeResponce, { data: data }) createRecord: (store, type, record) -> json = store.serializerFor(type.typeKey).serialize(record._createSnapshot()) @_push(store, type, record, json) updateRecord: (store, type, record) -> json = @serialize(record, {associations: true, includeId: true }) @_updateAttachmnets(record, json) if record.get('attachments') @_push(store, type, record, json) deleteRecord: (store, type, record) -> @ajax("%@?rev=%@".fmt(record.get('id'), record.get('_data.rev')), 'DELETE', (->), { }) _updateAttachmnets: (record, json) -> _attachments = {} record.get('attachments').forEach (item) -> attachment = EmberCouchDBKit.sharedStore.get('attachment', item.get('id')) _attachments[item.get('file_name')] = content_type: attachment.content_type digest: attachment.digest length: attachment.length stub: attachment.stub revpos: attachment.revpos json._attachments = _attachments delete json.attachments delete json.history _checkForRevision: (id) -> id.split("/").length > 1 _push: (store, type, record, json) -> id = record.get('id') || '' method = if record.get('id') then 'PUT' else 'POST' if record.get('_data.rev') json._rev = record.get('_data.rev') normalizeResponce = (data) -> _data = json || {} @_normalizeRevision(data) _modelJson = {} _modelJson[type.typeKey] = $.extend(_data, data) _modelJson @ajax(id, method, normalizeResponce, { data: json })
195609
### @namespace EmberCouchDBKit @class DocumentSerializer @extends DS.RESTSerializer ### EmberCouchDBKit.DocumentSerializer = DS.RESTSerializer.extend primaryKey: '_<KEY>' normalize: (type, hash, prop) -> @normalizeId(hash) @normalizeAttachments(hash["_attachments"], type.typeKey, hash) @addHistoryId(hash) @normalizeUsingDeclaredMapping(type, hash) @normalizeAttributes(type, hash) @normalizeRelationships(type, hash) return @normalizeHash[prop](hash) if @normalizeHash and @normalizeHash[prop] return hash if !hash @applyTransforms(type, hash) hash extractSingle: (store, type, payload, id, requestType) -> @_super(store, type, payload, id, requestType) serialize: (record, options) -> @_super(record, options) addHistoryId: (hash) -> hash.history = "%@/history".fmt(hash.id) normalizeAttachments: (attachments, type, hash) -> _attachments = [] for k, v of attachments key = <KEY> attachment = id: key content_type: v.content_type digest: v.digest length: v.length stub: v.stub doc_id: hash._id rev: hash.rev file_name: k model_name: type revpos: v.revpos db: v.db EmberCouchDBKit.sharedStore.add('attachment', key, attachment) _attachments.push(key) hash.attachments = _attachments normalizeId: (hash) -> hash.id = (hash["_id"] || hash["id"]) normalizeRelationships: (type, hash) -> payloadKey = undefined key = undefined if @keyForRelationship type.eachRelationship ((key, relationship) -> payloadKey = @keyForRelationship(key, relationship.kind) return if key is payloadKey hash[key] = hash[payloadKey] delete hash[payloadKey] ), this serializeBelongsTo: (record, json, relationship) -> attribute = (relationship.options.attribute || "id") key = relationship.key belongsTo = record.belongsTo(key) return if Ember.isNone(belongsTo) json[key] = if (attribute == "id") then belongsTo.id else belongsTo.attr(attribute) json[key + "_type"] = belongsTo.typeKey if relationship.options.polymorphic serializeHasMany: (record, json, relationship) -> attribute = (relationship.options.attribute || "id") key = relationship.key relationshipType = record.type.determineRelationshipType(relationship) switch relationshipType when "manyToNone", "manyToMany", "manyToOne" json[key] = record.hasMany(key).mapBy(attribute) ### A `DocumentAdapter` should be used as a main adapter for working with models as a CouchDB documents. Let's consider: ```coffee EmberApp.DocumentAdapter = EmberCouchDBKit.DocumentAdapter.extend({db: db, host: host}) EmberApp.DocumentSerializer = EmberCouchDBKit.DocumentSerializer.extend() EmberApp.Document = DS.Model.extend title: DS.attr('title') type: DS.attr('string', {defaultValue: 'document'}) ``` The following available operations: ```coffee # GET /my_couchdb/:id @get('store').find('document', id) # POST /my_couchdb @get('store').createRecord('document', {title: "title"}).save() # update PUT /my_couchdb/:id @get('store').find('document', id).then((document) -> document.set('title', title) document.save() ) # DELETE /my_couchdb/:id @get('store').find('document', id).deleteRecord().save() ``` For more advanced tips and tricks, you should check available specs @namespace EmberCouchDBKit @class DocumentAdapter @extends DS.Adapter ### EmberCouchDBKit.DocumentAdapter = DS.Adapter.extend defaultSerializer: '_default' customTypeLookup: false typeViewName: "all" buildURL: -> host = Ember.get(this, "host") namespace = Ember.get(this, "namespace") url = [] url.push host if host url.push namespace if namespace url.push @get('db') url = url.join("/") url = "/" + url unless host url ajax: (url, type, normalizeResponce, hash) -> @_ajax('%@/%@'.fmt(@buildURL(), url || ''), type, normalizeResponce, hash) _ajax: (url, type, normalizeResponce, hash={}) -> adapter = this return new Ember.RSVP.Promise((resolve, reject) -> if url.split("/").pop() == "" then url = url.substr(0, url.length - 1) hash.url = url hash.type = type hash.dataType = 'json' hash.contentType = 'application/json; charset=utf-8' hash.context = adapter if hash.data && type != 'GET' hash.data = JSON.stringify(hash.data) if adapter.headers headers = adapter.headers hash.beforeSend = (xhr) -> Ember.keys(headers).forEach (key) -> xhr.setRequestHeader key, headers[key] unless hash.success hash.success = (json) -> _modelJson = normalizeResponce.call(adapter, json) Ember.run(null, resolve, _modelJson) hash.error = (jqXHR, textStatus, errorThrown) -> if (jqXHR) jqXHR.then = null Ember.run(null, reject, jqXHR) Ember.$.ajax(hash) ) _normalizeRevision: (json) -> if json && json._rev json.rev = json._rev delete json._rev json shouldCommit: (record, relationships) -> @_super.apply(arguments) find: (store, type, id) -> if @_checkForRevision(id) @findWithRev(store, type, id) else normalizeResponce = (data) -> @_normalizeRevision(data) _modelJson = {} _modelJson[type.typeKey] = data _modelJson @ajax(id, 'GET', normalizeResponce) findWithRev: (store, type, id, hash) -> [_id, _rev] = id.split("/")[0..1] url = "%@?rev=%@".fmt(_id, _rev) normalizeResponce = (data) -> @_normalizeRevision(data) _modelJson = {} data._id = id _modelJson[type.typeKey] = data _modelJson @ajax(url, 'GET', normalizeResponce, hash) findManyWithRev: (store, type, ids) -> key = <KEY>.<KEY>(type.typeKey) self = @ docs = {} docs[key] = [] hash = {async: false} ids.forEach (id) => [_id, _rev] = id.split("/")[0..1] url = "%@?rev=%@".fmt(_id, _rev) url = '%@/%@'.fmt(@buildURL(), url) hash.url = url hash.type = 'GET' hash.dataType = 'json' hash.contentType = 'application/json; charset=utf-8' hash.success = (json) -> json._id = id self._normalizeRevision(json) docs[key].push(json) Ember.$.ajax(hash) docs findMany: (store, type, ids) -> if @_checkForRevision(ids[0]) @findManyWithRev(store, type, ids) else data = include_docs: true keys: ids normalizeResponce = (data) -> json = {} json[Ember.String.pluralize(type.typeKey)] = data.rows.getEach('doc').map((doc) => @_normalizeRevision(doc)) json @ajax('_all_docs?include_docs=true', 'POST', normalizeResponce, { data: data }) findQuery: (store, type, query, modelArray) -> designDoc = (query.designDoc || @get('designDoc')) query.options = {} unless query.options query.options.include_docs = true normalizeResponce = (data) -> json = {} json[designDoc] = data.rows.getEach('doc').map((doc) => @_normalizeRevision(doc)) json @ajax('_design/%@/_view/%@'.fmt(designDoc, query.viewName), 'GET', normalizeResponce, { context: this data: query.options }) findAll: (store, type) -> typeString = Ember.String.singularize(type.typeKey) designDoc = @get('designDoc') || typeString typeViewName = @get('typeViewName') normalizeResponce = (data) -> json = {} json[[Ember.String.pluralize(type.typeKey)]] = data.rows.getEach('doc').map((doc) => @_normalizeRevision(doc)) json data = include_docs: true key: '"' + typeString + '"' @ajax('_design/%@/_view/%@'.fmt(designDoc, typeViewName), 'GET', normalizeResponce, { data: data }) createRecord: (store, type, record) -> json = store.serializerFor(type.typeKey).serialize(record._createSnapshot()) @_push(store, type, record, json) updateRecord: (store, type, record) -> json = @serialize(record, {associations: true, includeId: true }) @_updateAttachmnets(record, json) if record.get('attachments') @_push(store, type, record, json) deleteRecord: (store, type, record) -> @ajax("%@?rev=%@".fmt(record.get('id'), record.get('_data.rev')), 'DELETE', (->), { }) _updateAttachmnets: (record, json) -> _attachments = {} record.get('attachments').forEach (item) -> attachment = EmberCouchDBKit.sharedStore.get('attachment', item.get('id')) _attachments[item.get('file_name')] = content_type: attachment.content_type digest: attachment.digest length: attachment.length stub: attachment.stub revpos: attachment.revpos json._attachments = _attachments delete json.attachments delete json.history _checkForRevision: (id) -> id.split("/").length > 1 _push: (store, type, record, json) -> id = record.get('id') || '' method = if record.get('id') then 'PUT' else 'POST' if record.get('_data.rev') json._rev = record.get('_data.rev') normalizeResponce = (data) -> _data = json || {} @_normalizeRevision(data) _modelJson = {} _modelJson[type.typeKey] = $.extend(_data, data) _modelJson @ajax(id, method, normalizeResponce, { data: json })
true
### @namespace EmberCouchDBKit @class DocumentSerializer @extends DS.RESTSerializer ### EmberCouchDBKit.DocumentSerializer = DS.RESTSerializer.extend primaryKey: '_PI:KEY:<KEY>END_PI' normalize: (type, hash, prop) -> @normalizeId(hash) @normalizeAttachments(hash["_attachments"], type.typeKey, hash) @addHistoryId(hash) @normalizeUsingDeclaredMapping(type, hash) @normalizeAttributes(type, hash) @normalizeRelationships(type, hash) return @normalizeHash[prop](hash) if @normalizeHash and @normalizeHash[prop] return hash if !hash @applyTransforms(type, hash) hash extractSingle: (store, type, payload, id, requestType) -> @_super(store, type, payload, id, requestType) serialize: (record, options) -> @_super(record, options) addHistoryId: (hash) -> hash.history = "%@/history".fmt(hash.id) normalizeAttachments: (attachments, type, hash) -> _attachments = [] for k, v of attachments key = PI:KEY:<KEY>END_PI attachment = id: key content_type: v.content_type digest: v.digest length: v.length stub: v.stub doc_id: hash._id rev: hash.rev file_name: k model_name: type revpos: v.revpos db: v.db EmberCouchDBKit.sharedStore.add('attachment', key, attachment) _attachments.push(key) hash.attachments = _attachments normalizeId: (hash) -> hash.id = (hash["_id"] || hash["id"]) normalizeRelationships: (type, hash) -> payloadKey = undefined key = undefined if @keyForRelationship type.eachRelationship ((key, relationship) -> payloadKey = @keyForRelationship(key, relationship.kind) return if key is payloadKey hash[key] = hash[payloadKey] delete hash[payloadKey] ), this serializeBelongsTo: (record, json, relationship) -> attribute = (relationship.options.attribute || "id") key = relationship.key belongsTo = record.belongsTo(key) return if Ember.isNone(belongsTo) json[key] = if (attribute == "id") then belongsTo.id else belongsTo.attr(attribute) json[key + "_type"] = belongsTo.typeKey if relationship.options.polymorphic serializeHasMany: (record, json, relationship) -> attribute = (relationship.options.attribute || "id") key = relationship.key relationshipType = record.type.determineRelationshipType(relationship) switch relationshipType when "manyToNone", "manyToMany", "manyToOne" json[key] = record.hasMany(key).mapBy(attribute) ### A `DocumentAdapter` should be used as a main adapter for working with models as a CouchDB documents. Let's consider: ```coffee EmberApp.DocumentAdapter = EmberCouchDBKit.DocumentAdapter.extend({db: db, host: host}) EmberApp.DocumentSerializer = EmberCouchDBKit.DocumentSerializer.extend() EmberApp.Document = DS.Model.extend title: DS.attr('title') type: DS.attr('string', {defaultValue: 'document'}) ``` The following available operations: ```coffee # GET /my_couchdb/:id @get('store').find('document', id) # POST /my_couchdb @get('store').createRecord('document', {title: "title"}).save() # update PUT /my_couchdb/:id @get('store').find('document', id).then((document) -> document.set('title', title) document.save() ) # DELETE /my_couchdb/:id @get('store').find('document', id).deleteRecord().save() ``` For more advanced tips and tricks, you should check available specs @namespace EmberCouchDBKit @class DocumentAdapter @extends DS.Adapter ### EmberCouchDBKit.DocumentAdapter = DS.Adapter.extend defaultSerializer: '_default' customTypeLookup: false typeViewName: "all" buildURL: -> host = Ember.get(this, "host") namespace = Ember.get(this, "namespace") url = [] url.push host if host url.push namespace if namespace url.push @get('db') url = url.join("/") url = "/" + url unless host url ajax: (url, type, normalizeResponce, hash) -> @_ajax('%@/%@'.fmt(@buildURL(), url || ''), type, normalizeResponce, hash) _ajax: (url, type, normalizeResponce, hash={}) -> adapter = this return new Ember.RSVP.Promise((resolve, reject) -> if url.split("/").pop() == "" then url = url.substr(0, url.length - 1) hash.url = url hash.type = type hash.dataType = 'json' hash.contentType = 'application/json; charset=utf-8' hash.context = adapter if hash.data && type != 'GET' hash.data = JSON.stringify(hash.data) if adapter.headers headers = adapter.headers hash.beforeSend = (xhr) -> Ember.keys(headers).forEach (key) -> xhr.setRequestHeader key, headers[key] unless hash.success hash.success = (json) -> _modelJson = normalizeResponce.call(adapter, json) Ember.run(null, resolve, _modelJson) hash.error = (jqXHR, textStatus, errorThrown) -> if (jqXHR) jqXHR.then = null Ember.run(null, reject, jqXHR) Ember.$.ajax(hash) ) _normalizeRevision: (json) -> if json && json._rev json.rev = json._rev delete json._rev json shouldCommit: (record, relationships) -> @_super.apply(arguments) find: (store, type, id) -> if @_checkForRevision(id) @findWithRev(store, type, id) else normalizeResponce = (data) -> @_normalizeRevision(data) _modelJson = {} _modelJson[type.typeKey] = data _modelJson @ajax(id, 'GET', normalizeResponce) findWithRev: (store, type, id, hash) -> [_id, _rev] = id.split("/")[0..1] url = "%@?rev=%@".fmt(_id, _rev) normalizeResponce = (data) -> @_normalizeRevision(data) _modelJson = {} data._id = id _modelJson[type.typeKey] = data _modelJson @ajax(url, 'GET', normalizeResponce, hash) findManyWithRev: (store, type, ids) -> key = PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI(type.typeKey) self = @ docs = {} docs[key] = [] hash = {async: false} ids.forEach (id) => [_id, _rev] = id.split("/")[0..1] url = "%@?rev=%@".fmt(_id, _rev) url = '%@/%@'.fmt(@buildURL(), url) hash.url = url hash.type = 'GET' hash.dataType = 'json' hash.contentType = 'application/json; charset=utf-8' hash.success = (json) -> json._id = id self._normalizeRevision(json) docs[key].push(json) Ember.$.ajax(hash) docs findMany: (store, type, ids) -> if @_checkForRevision(ids[0]) @findManyWithRev(store, type, ids) else data = include_docs: true keys: ids normalizeResponce = (data) -> json = {} json[Ember.String.pluralize(type.typeKey)] = data.rows.getEach('doc').map((doc) => @_normalizeRevision(doc)) json @ajax('_all_docs?include_docs=true', 'POST', normalizeResponce, { data: data }) findQuery: (store, type, query, modelArray) -> designDoc = (query.designDoc || @get('designDoc')) query.options = {} unless query.options query.options.include_docs = true normalizeResponce = (data) -> json = {} json[designDoc] = data.rows.getEach('doc').map((doc) => @_normalizeRevision(doc)) json @ajax('_design/%@/_view/%@'.fmt(designDoc, query.viewName), 'GET', normalizeResponce, { context: this data: query.options }) findAll: (store, type) -> typeString = Ember.String.singularize(type.typeKey) designDoc = @get('designDoc') || typeString typeViewName = @get('typeViewName') normalizeResponce = (data) -> json = {} json[[Ember.String.pluralize(type.typeKey)]] = data.rows.getEach('doc').map((doc) => @_normalizeRevision(doc)) json data = include_docs: true key: '"' + typeString + '"' @ajax('_design/%@/_view/%@'.fmt(designDoc, typeViewName), 'GET', normalizeResponce, { data: data }) createRecord: (store, type, record) -> json = store.serializerFor(type.typeKey).serialize(record._createSnapshot()) @_push(store, type, record, json) updateRecord: (store, type, record) -> json = @serialize(record, {associations: true, includeId: true }) @_updateAttachmnets(record, json) if record.get('attachments') @_push(store, type, record, json) deleteRecord: (store, type, record) -> @ajax("%@?rev=%@".fmt(record.get('id'), record.get('_data.rev')), 'DELETE', (->), { }) _updateAttachmnets: (record, json) -> _attachments = {} record.get('attachments').forEach (item) -> attachment = EmberCouchDBKit.sharedStore.get('attachment', item.get('id')) _attachments[item.get('file_name')] = content_type: attachment.content_type digest: attachment.digest length: attachment.length stub: attachment.stub revpos: attachment.revpos json._attachments = _attachments delete json.attachments delete json.history _checkForRevision: (id) -> id.split("/").length > 1 _push: (store, type, record, json) -> id = record.get('id') || '' method = if record.get('id') then 'PUT' else 'POST' if record.get('_data.rev') json._rev = record.get('_data.rev') normalizeResponce = (data) -> _data = json || {} @_normalizeRevision(data) _modelJson = {} _modelJson[type.typeKey] = $.extend(_data, data) _modelJson @ajax(id, method, normalizeResponce, { data: json })
[ { "context": "# @author mr.doob / http://mrdoob.com/\n# @author aladjev.andre", "end": 12, "score": 0.6706682443618774, "start": 10, "tag": "USERNAME", "value": "mr" }, { "context": "# @author mr.doob / http://mrdoob.com/\n# @author aladjev.andrew@gma", "end": 17, "score": 0.7920354008674622, "start": 13, "tag": "NAME", "value": "doob" }, { "context": "# @author mr.doob / http://mrdoob.com/\n# @author aladjev.andrew@gmail.com\n\nclass Vertex\n constructor: ->\n console.warn ", "end": 73, "score": 0.9999186992645264, "start": 49, "tag": "EMAIL", "value": "aladjev.andrew@gmail.com" } ]
source/javascripts/new_src/core/vertex.coffee
andrew-aladev/three.js
0
# @author mr.doob / http://mrdoob.com/ # @author aladjev.andrew@gmail.com class Vertex constructor: -> console.warn "THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead." namespace "THREE", (exports) -> exports.Vertex = Vertex
56637
# @author mr.<NAME> / http://mrdoob.com/ # @author <EMAIL> class Vertex constructor: -> console.warn "THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead." namespace "THREE", (exports) -> exports.Vertex = Vertex
true
# @author mr.PI:NAME:<NAME>END_PI / http://mrdoob.com/ # @author PI:EMAIL:<EMAIL>END_PI class Vertex constructor: -> console.warn "THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead." namespace "THREE", (exports) -> exports.Vertex = Vertex
[ { "context": "d.equal 10\n results[0].title.should.equal 'Vennice Biennalez'\n done()\n\n describe '#find', ->\n\n it '", "end": 604, "score": 0.9993260502815247, "start": 587, "tag": "NAME", "value": "Vennice Biennalez" } ]
src/api/apps/sections/test/model.test.coffee
craigspaeth/positron
76
_ = require 'underscore' moment = require 'moment' { db, fabricate, empty, fixtures } = require '../../../test/helpers/db' Section = require '../model' { ObjectId } = require 'mongojs' describe 'Section', -> beforeEach (done) -> empty -> fabricate 'sections', _.times(10, -> {}), -> done() describe '#where', -> it 'can return all sections along with total and counts', (done) -> Section.where {}, (err, res) -> { total, count, results } = res total.should.equal 10 count.should.equal 10 results[0].title.should.equal 'Vennice Biennalez' done() describe '#find', -> it 'finds an section by an id string', (done) -> fabricate 'sections', { _id: ObjectId('5086df098523e60002000018') }, -> Section.find '5086df098523e60002000018', (err, section) -> section._id.toString().should.equal '5086df098523e60002000018' done() describe '#save', -> it 'saves valid section input data', (done) -> Section.save { title: 'Top Ten Shows' description: 'Hello World' }, (err, section) -> section.title.should.equal 'Top Ten Shows' section.description.should.equal 'Hello World' db.sections.count (err, count) -> count.should.equal 11 done() describe '#present', -> it 'converts _id to id', (done) -> db.sections.findOne (err, section) -> data = Section.present section (typeof data.id).should.equal 'string' done()
199137
_ = require 'underscore' moment = require 'moment' { db, fabricate, empty, fixtures } = require '../../../test/helpers/db' Section = require '../model' { ObjectId } = require 'mongojs' describe 'Section', -> beforeEach (done) -> empty -> fabricate 'sections', _.times(10, -> {}), -> done() describe '#where', -> it 'can return all sections along with total and counts', (done) -> Section.where {}, (err, res) -> { total, count, results } = res total.should.equal 10 count.should.equal 10 results[0].title.should.equal '<NAME>' done() describe '#find', -> it 'finds an section by an id string', (done) -> fabricate 'sections', { _id: ObjectId('5086df098523e60002000018') }, -> Section.find '5086df098523e60002000018', (err, section) -> section._id.toString().should.equal '5086df098523e60002000018' done() describe '#save', -> it 'saves valid section input data', (done) -> Section.save { title: 'Top Ten Shows' description: 'Hello World' }, (err, section) -> section.title.should.equal 'Top Ten Shows' section.description.should.equal 'Hello World' db.sections.count (err, count) -> count.should.equal 11 done() describe '#present', -> it 'converts _id to id', (done) -> db.sections.findOne (err, section) -> data = Section.present section (typeof data.id).should.equal 'string' done()
true
_ = require 'underscore' moment = require 'moment' { db, fabricate, empty, fixtures } = require '../../../test/helpers/db' Section = require '../model' { ObjectId } = require 'mongojs' describe 'Section', -> beforeEach (done) -> empty -> fabricate 'sections', _.times(10, -> {}), -> done() describe '#where', -> it 'can return all sections along with total and counts', (done) -> Section.where {}, (err, res) -> { total, count, results } = res total.should.equal 10 count.should.equal 10 results[0].title.should.equal 'PI:NAME:<NAME>END_PI' done() describe '#find', -> it 'finds an section by an id string', (done) -> fabricate 'sections', { _id: ObjectId('5086df098523e60002000018') }, -> Section.find '5086df098523e60002000018', (err, section) -> section._id.toString().should.equal '5086df098523e60002000018' done() describe '#save', -> it 'saves valid section input data', (done) -> Section.save { title: 'Top Ten Shows' description: 'Hello World' }, (err, section) -> section.title.should.equal 'Top Ten Shows' section.description.should.equal 'Hello World' db.sections.count (err, count) -> count.should.equal 11 done() describe '#present', -> it 'converts _id to id', (done) -> db.sections.findOne (err, section) -> data = Section.present section (typeof data.id).should.equal 'string' done()
[ { "context": "nts'\n id: 1\n attributes:\n name: 'Demo'\n\n expect(event.name).to.equal 'Demo'\n\n it 's", "end": 332, "score": 0.9157630205154419, "start": 328, "tag": "NAME", "value": "Demo" }, { "context": "nts'\n id: 1\n attributes:\n name: 'Demo'\n\n event = @store.find 'events', 1\n expect(", "end": 499, "score": 0.9497962594032288, "start": 495, "tag": "NAME", "value": "Demo" }, { "context": " id: 1\n attributes:\n name: 'Demo'\n relationships:\n images:\n ", "end": 808, "score": 0.9686005711555481, "start": 804, "tag": "NAME", "value": "Demo" }, { "context": " id: 2\n attributes:\n name: 'Header'\n }]\n\n event = @store.find 'events', 1\n ", "end": 1128, "score": 0.5988432765007019, "start": 1122, "tag": "NAME", "value": "Header" }, { "context": "find 'events', 1\n expect(event.name).to.equal 'Demo'\n expect(event.images.length).to.equal 1\n\n ", "end": 1213, "score": 0.8656022548675537, "start": 1209, "tag": "NAME", "value": "Demo" }, { "context": " 1\n attributes:\n name: 'Demo'\n relationships:\n image", "end": 1530, "score": 0.9667619466781616, "start": 1526, "tag": "NAME", "value": "Demo" }, { "context": " 'events', 1\n\n expect(event.name).to.equal 'Demo'\n expect(event.image).to.be.null\n\n it 'sho", "end": 1782, "score": 0.7812207937240601, "start": 1778, "tag": "NAME", "value": "Demo" }, { "context": " id: 1\n attributes:\n name: 'Demo'\n relationships:\n images:\n ", "end": 1973, "score": 0.9553405046463013, "start": 1969, "tag": "NAME", "value": "Demo" }, { "context": " id: 1\n attributes:\n name: \"Nordic.js\"\n slug: \"nordicjs\"\n relationships", "end": 2681, "score": 0.9996955990791321, "start": 2672, "tag": "NAME", "value": "Nordic.js" }, { "context": " id: 1\n attributes:\n firstName: 'Jonny'\n relationships:\n event:\n ", "end": 3146, "score": 0.9997296929359436, "start": 3141, "tag": "NAME", "value": "Jonny" }, { "context": " id: 2\n attributes:\n firstName: 'Martina'\n relationships:\n event:\n ", "end": 3389, "score": 0.9997268915176392, "start": 3382, "tag": "NAME", "value": "Martina" }, { "context": " id: 2\n attributes:\n name: 'Organiser Johannes'\n relationships:\n ev", "end": 3795, "score": 0.9915497303009033, "start": 3790, "tag": "NAME", "value": "Organ" }, { "context": " id: 2\n attributes:\n name: 'Organiser Johannes'\n relationships:\n event:", "end": 3799, "score": 0.8106139302253723, "start": 3795, "tag": "NAME", "value": "iser" }, { "context": ": 2\n attributes:\n name: 'Organiser Johannes'\n relationships:\n event:\n ", "end": 3808, "score": 0.9863133430480957, "start": 3800, "tag": "NAME", "value": "Johannes" }, { "context": " id: 3\n attributes:\n name: 'Organiser Martina'\n relationships:\n eve", "end": 3981, "score": 0.9901055693626404, "start": 3976, "tag": "NAME", "value": "Organ" }, { "context": " id: 3\n attributes:\n name: 'Organiser Martina'\n relationships:\n event:\n", "end": 3985, "score": 0.6697067618370056, "start": 3981, "tag": "NAME", "value": "iser" }, { "context": ": 3\n attributes:\n name: 'Organiser Martina'\n relationships:\n event:\n ", "end": 3993, "score": 0.9884634017944336, "start": 3986, "tag": "NAME", "value": "Martina" }, { "context": " id: 2\n attributes:\n name: 'Demo 2'\n }]\n included: [\n type: 'im", "end": 5160, "score": 0.5449749827384949, "start": 5156, "tag": "NAME", "value": "Demo" }, { "context": "le body'\n meta:\n author: 'John Doe'\n date: '2017-06-26'\n meta:", "end": 6748, "score": 0.9993180632591248, "start": 6740, "tag": "NAME", "value": "John Doe" }, { "context": ": 'Comment'\n details:\n user: 'micha3ldavid'\n body: 'this is a comment...'\n ", "end": 7285, "score": 0.9997268319129944, "start": 7273, "tag": "USERNAME", "value": "micha3ldavid" }, { "context": "e.com/comment/2'\n meta:\n author: 'John Doe'\n date: '2017-06-26'\n ]\n\n expect", "end": 7431, "score": 0.9994508028030396, "start": 7423, "tag": "NAME", "value": "John Doe" }, { "context": "t(result[0].article.meta).to.deep.equal {author: 'John Doe', date: '2017-06-26'}\n expect(result[0].commen", "end": 7616, "score": 0.9994518756866455, "start": 7608, "tag": "NAME", "value": "John Doe" }, { "context": "t(result[0].comment.meta).to.deep.equal {author: 'John Doe', date: '2017-06-26'}\n expect(result[0].commen", "end": 7706, "score": 0.9992518424987793, "start": 7698, "tag": "NAME", "value": "John Doe" } ]
test/yayson/store.coffee
nie7321/yayson
0
expect = require('chai').expect Store = require('../../src/yayson.coffee')().Store describe 'Store', -> beforeEach -> @store = new Store() @store.records = [] @store.relations = {} it 'should sync an event', -> event = @store.sync data: type: 'events' id: 1 attributes: name: 'Demo' expect(event.name).to.equal 'Demo' it 'should find an event', -> @store.sync data: type: 'events' id: 1 attributes: name: 'Demo' event = @store.find 'events', 1 expect(event.id).to.equal 1 expect(event.type).to.equal 'events' expect(event.name).to.equal 'Demo' it 'should handle relations with duplicates', -> @store.sync data: type: 'events' id: 1 attributes: name: 'Demo' relationships: images: data: [{ type: 'images' id: 2 }] included: [{ type: 'images' id: 2 attributes: name: 'Header' }, { type: 'images' id: 2 attributes: name: 'Header' }] event = @store.find 'events', 1 expect(event.name).to.equal 'Demo' expect(event.images.length).to.equal 1 images = @store.findAll 'images' expect(images.length).to.eq 1 it 'should handle relationship elements without links attribute', -> @store.sync data: type: 'events' id: 1 attributes: name: 'Demo' relationships: image: data: { type: 'images', id: 2 } event = @store.find 'events', 1 expect(event.name).to.equal 'Demo' expect(event.image).to.be.null it 'should handle circular relations', -> @store.sync data: type: 'events' id: 1 attributes: name: 'Demo' relationships: images: data: [ type: 'images' id: 2 ] included: [ type: 'images' id: 2 attributes: name: 'Header' relationships: event: data: type: 'events' id: 1 ] event = @store.find 'events', 1 expect(event.name).to.equal 'Demo' expect(event.images[0].name).to.equal 'Header' expect(event.images[0].event.id).to.equal 1 it 'should return a event with all associated objects', -> @store.sync data: type: 'events' id: 1 attributes: name: "Nordic.js" slug: "nordicjs" relationships: images: data: [ {type: 'images', id: 1} {type: 'images', id: 2} {type: 'images', id: 3} ] organisers: data: [ {type: 'organisers', id: 1} {type: 'organisers', id: 2} ] included: [{ type: 'organisers' id: 1 attributes: firstName: 'Jonny' relationships: event: data: {type: 'events', id: 1} image: data: {type: 'images', id: 2} },{ type: 'organisers' id: 2 attributes: firstName: 'Martina' relationships: event: data: {type: 'events', id: 1} image: data: {type: 'images', id: 3} },{ type: 'images' id: 1 attributes: name: 'Header' relationships: event: data: {type: 'events', id: 1} },{ type: 'images' id: 2 attributes: name: 'Organiser Johannes' relationships: event: data: {type: 'events', id: 1} },{ type: 'images' id: 3 attributes: name: 'Organiser Martina' relationships: event: data: {type: 'events', id: 1} }] event = @store.find 'events', 1 expect(event.organisers.length).to.equal 2 expect(event.images.length).to.equal 3 expect(event.organisers[0].image.id).to.equal 2 it 'should remove an event', -> @store.sync data: [ {id: 1, type: 'events'} {id: 2, type: 'events'} ] event = @store.find 'events', 1 expect(event.id).to.eq 1 @store.remove 'events', 1 event = @store.find 'events', 1 expect(event).to.eq null it 'should remove all events', -> @store.sync data: [ {id: 1, type: 'events'} {id: 2, type: 'events'} ] events = @store.findAll 'events' expect(events.length).to.eq 2 @store.remove 'events' events = @store.findAll 'events' expect(events).to.deep.eq [] it 'should reset', -> @store.sync data: [{ type: 'events' id: 1 attributes: name: 'Demo' relationships: images: data: [ type: 'images', id: 2 ] },{ type: 'events' id: 2 attributes: name: 'Demo 2' }] included: [ type: 'images' id: 2 attributes: name: 'Header' relationships: event: data: {type: 'events', id: 1} ] events = @store.findAll 'events' images = @store.findAll 'images' expect(events.length).to.eq 2 expect(images.length).to.eq 1 @store.reset() events = @store.findAll 'event' images = @store.findAll 'image' expect(events).to.deep.eq [] expect(images).to.deep.eq [] it 'should handle circular relations', -> @store.sync data: type: 'events' id: 1 attributes: name: 'Demo' relationships: images: links: self: 'http://example.com/events/1/relationships/images' event = @store.find 'events', 1 expect(event.name).to.equal 'Demo' expect(event.images._links).to.deep.equal self: 'http://example.com/events/1/relationships/images' it 'should retain links and meta', -> result = @store.sync links: self: 'http://example.com/events' next: 'http://example.com/events?page[offset]=2' meta: name: 'top level meta data' value: 1 data: [ type: 'events' id: 1 meta: name: 'second level meta' value: 2 attributes: name: 'Demo' article: name: 'An Article test' teaser: 'this is a teaser...' body: 'this is an article body' meta: author: 'John Doe' date: '2017-06-26' meta: name: 'attribute nested meta' value: 3 relationships: comment: links: self: 'http://example.com/events/1/relationships/comment' related: 'http://example.com/events/1/comment' data: type: 'comment', id: 2 ] included: [ type: 'comment' id: 2 attributes: name: 'Comment' details: user: 'micha3ldavid' body: 'this is a comment...' links: self: 'http://example.com/comment/2' meta: author: 'John Doe' date: '2017-06-26' ] expect(result.meta).to.deep.equal {name: 'top level meta data', value: 1} expect(result[0].article.meta).to.deep.equal {author: 'John Doe', date: '2017-06-26'} expect(result[0].comment.meta).to.deep.equal {author: 'John Doe', date: '2017-06-26'} expect(result[0].comment._links).to.deep.equal {self: 'http://example.com/events/1/relationships/comment', related: 'http://example.com/events/1/comment'}
134637
expect = require('chai').expect Store = require('../../src/yayson.coffee')().Store describe 'Store', -> beforeEach -> @store = new Store() @store.records = [] @store.relations = {} it 'should sync an event', -> event = @store.sync data: type: 'events' id: 1 attributes: name: '<NAME>' expect(event.name).to.equal 'Demo' it 'should find an event', -> @store.sync data: type: 'events' id: 1 attributes: name: '<NAME>' event = @store.find 'events', 1 expect(event.id).to.equal 1 expect(event.type).to.equal 'events' expect(event.name).to.equal 'Demo' it 'should handle relations with duplicates', -> @store.sync data: type: 'events' id: 1 attributes: name: '<NAME>' relationships: images: data: [{ type: 'images' id: 2 }] included: [{ type: 'images' id: 2 attributes: name: 'Header' }, { type: 'images' id: 2 attributes: name: '<NAME>' }] event = @store.find 'events', 1 expect(event.name).to.equal '<NAME>' expect(event.images.length).to.equal 1 images = @store.findAll 'images' expect(images.length).to.eq 1 it 'should handle relationship elements without links attribute', -> @store.sync data: type: 'events' id: 1 attributes: name: '<NAME>' relationships: image: data: { type: 'images', id: 2 } event = @store.find 'events', 1 expect(event.name).to.equal '<NAME>' expect(event.image).to.be.null it 'should handle circular relations', -> @store.sync data: type: 'events' id: 1 attributes: name: '<NAME>' relationships: images: data: [ type: 'images' id: 2 ] included: [ type: 'images' id: 2 attributes: name: 'Header' relationships: event: data: type: 'events' id: 1 ] event = @store.find 'events', 1 expect(event.name).to.equal 'Demo' expect(event.images[0].name).to.equal 'Header' expect(event.images[0].event.id).to.equal 1 it 'should return a event with all associated objects', -> @store.sync data: type: 'events' id: 1 attributes: name: "<NAME>" slug: "nordicjs" relationships: images: data: [ {type: 'images', id: 1} {type: 'images', id: 2} {type: 'images', id: 3} ] organisers: data: [ {type: 'organisers', id: 1} {type: 'organisers', id: 2} ] included: [{ type: 'organisers' id: 1 attributes: firstName: '<NAME>' relationships: event: data: {type: 'events', id: 1} image: data: {type: 'images', id: 2} },{ type: 'organisers' id: 2 attributes: firstName: '<NAME>' relationships: event: data: {type: 'events', id: 1} image: data: {type: 'images', id: 3} },{ type: 'images' id: 1 attributes: name: 'Header' relationships: event: data: {type: 'events', id: 1} },{ type: 'images' id: 2 attributes: name: '<NAME> <NAME> <NAME>' relationships: event: data: {type: 'events', id: 1} },{ type: 'images' id: 3 attributes: name: '<NAME> <NAME> <NAME>' relationships: event: data: {type: 'events', id: 1} }] event = @store.find 'events', 1 expect(event.organisers.length).to.equal 2 expect(event.images.length).to.equal 3 expect(event.organisers[0].image.id).to.equal 2 it 'should remove an event', -> @store.sync data: [ {id: 1, type: 'events'} {id: 2, type: 'events'} ] event = @store.find 'events', 1 expect(event.id).to.eq 1 @store.remove 'events', 1 event = @store.find 'events', 1 expect(event).to.eq null it 'should remove all events', -> @store.sync data: [ {id: 1, type: 'events'} {id: 2, type: 'events'} ] events = @store.findAll 'events' expect(events.length).to.eq 2 @store.remove 'events' events = @store.findAll 'events' expect(events).to.deep.eq [] it 'should reset', -> @store.sync data: [{ type: 'events' id: 1 attributes: name: 'Demo' relationships: images: data: [ type: 'images', id: 2 ] },{ type: 'events' id: 2 attributes: name: '<NAME> 2' }] included: [ type: 'images' id: 2 attributes: name: 'Header' relationships: event: data: {type: 'events', id: 1} ] events = @store.findAll 'events' images = @store.findAll 'images' expect(events.length).to.eq 2 expect(images.length).to.eq 1 @store.reset() events = @store.findAll 'event' images = @store.findAll 'image' expect(events).to.deep.eq [] expect(images).to.deep.eq [] it 'should handle circular relations', -> @store.sync data: type: 'events' id: 1 attributes: name: 'Demo' relationships: images: links: self: 'http://example.com/events/1/relationships/images' event = @store.find 'events', 1 expect(event.name).to.equal 'Demo' expect(event.images._links).to.deep.equal self: 'http://example.com/events/1/relationships/images' it 'should retain links and meta', -> result = @store.sync links: self: 'http://example.com/events' next: 'http://example.com/events?page[offset]=2' meta: name: 'top level meta data' value: 1 data: [ type: 'events' id: 1 meta: name: 'second level meta' value: 2 attributes: name: 'Demo' article: name: 'An Article test' teaser: 'this is a teaser...' body: 'this is an article body' meta: author: '<NAME>' date: '2017-06-26' meta: name: 'attribute nested meta' value: 3 relationships: comment: links: self: 'http://example.com/events/1/relationships/comment' related: 'http://example.com/events/1/comment' data: type: 'comment', id: 2 ] included: [ type: 'comment' id: 2 attributes: name: 'Comment' details: user: 'micha3ldavid' body: 'this is a comment...' links: self: 'http://example.com/comment/2' meta: author: '<NAME>' date: '2017-06-26' ] expect(result.meta).to.deep.equal {name: 'top level meta data', value: 1} expect(result[0].article.meta).to.deep.equal {author: '<NAME>', date: '2017-06-26'} expect(result[0].comment.meta).to.deep.equal {author: '<NAME>', date: '2017-06-26'} expect(result[0].comment._links).to.deep.equal {self: 'http://example.com/events/1/relationships/comment', related: 'http://example.com/events/1/comment'}
true
expect = require('chai').expect Store = require('../../src/yayson.coffee')().Store describe 'Store', -> beforeEach -> @store = new Store() @store.records = [] @store.relations = {} it 'should sync an event', -> event = @store.sync data: type: 'events' id: 1 attributes: name: 'PI:NAME:<NAME>END_PI' expect(event.name).to.equal 'Demo' it 'should find an event', -> @store.sync data: type: 'events' id: 1 attributes: name: 'PI:NAME:<NAME>END_PI' event = @store.find 'events', 1 expect(event.id).to.equal 1 expect(event.type).to.equal 'events' expect(event.name).to.equal 'Demo' it 'should handle relations with duplicates', -> @store.sync data: type: 'events' id: 1 attributes: name: 'PI:NAME:<NAME>END_PI' relationships: images: data: [{ type: 'images' id: 2 }] included: [{ type: 'images' id: 2 attributes: name: 'Header' }, { type: 'images' id: 2 attributes: name: 'PI:NAME:<NAME>END_PI' }] event = @store.find 'events', 1 expect(event.name).to.equal 'PI:NAME:<NAME>END_PI' expect(event.images.length).to.equal 1 images = @store.findAll 'images' expect(images.length).to.eq 1 it 'should handle relationship elements without links attribute', -> @store.sync data: type: 'events' id: 1 attributes: name: 'PI:NAME:<NAME>END_PI' relationships: image: data: { type: 'images', id: 2 } event = @store.find 'events', 1 expect(event.name).to.equal 'PI:NAME:<NAME>END_PI' expect(event.image).to.be.null it 'should handle circular relations', -> @store.sync data: type: 'events' id: 1 attributes: name: 'PI:NAME:<NAME>END_PI' relationships: images: data: [ type: 'images' id: 2 ] included: [ type: 'images' id: 2 attributes: name: 'Header' relationships: event: data: type: 'events' id: 1 ] event = @store.find 'events', 1 expect(event.name).to.equal 'Demo' expect(event.images[0].name).to.equal 'Header' expect(event.images[0].event.id).to.equal 1 it 'should return a event with all associated objects', -> @store.sync data: type: 'events' id: 1 attributes: name: "PI:NAME:<NAME>END_PI" slug: "nordicjs" relationships: images: data: [ {type: 'images', id: 1} {type: 'images', id: 2} {type: 'images', id: 3} ] organisers: data: [ {type: 'organisers', id: 1} {type: 'organisers', id: 2} ] included: [{ type: 'organisers' id: 1 attributes: firstName: 'PI:NAME:<NAME>END_PI' relationships: event: data: {type: 'events', id: 1} image: data: {type: 'images', id: 2} },{ type: 'organisers' id: 2 attributes: firstName: 'PI:NAME:<NAME>END_PI' relationships: event: data: {type: 'events', id: 1} image: data: {type: 'images', id: 3} },{ type: 'images' id: 1 attributes: name: 'Header' relationships: event: data: {type: 'events', id: 1} },{ type: 'images' id: 2 attributes: name: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI' relationships: event: data: {type: 'events', id: 1} },{ type: 'images' id: 3 attributes: name: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI' relationships: event: data: {type: 'events', id: 1} }] event = @store.find 'events', 1 expect(event.organisers.length).to.equal 2 expect(event.images.length).to.equal 3 expect(event.organisers[0].image.id).to.equal 2 it 'should remove an event', -> @store.sync data: [ {id: 1, type: 'events'} {id: 2, type: 'events'} ] event = @store.find 'events', 1 expect(event.id).to.eq 1 @store.remove 'events', 1 event = @store.find 'events', 1 expect(event).to.eq null it 'should remove all events', -> @store.sync data: [ {id: 1, type: 'events'} {id: 2, type: 'events'} ] events = @store.findAll 'events' expect(events.length).to.eq 2 @store.remove 'events' events = @store.findAll 'events' expect(events).to.deep.eq [] it 'should reset', -> @store.sync data: [{ type: 'events' id: 1 attributes: name: 'Demo' relationships: images: data: [ type: 'images', id: 2 ] },{ type: 'events' id: 2 attributes: name: 'PI:NAME:<NAME>END_PI 2' }] included: [ type: 'images' id: 2 attributes: name: 'Header' relationships: event: data: {type: 'events', id: 1} ] events = @store.findAll 'events' images = @store.findAll 'images' expect(events.length).to.eq 2 expect(images.length).to.eq 1 @store.reset() events = @store.findAll 'event' images = @store.findAll 'image' expect(events).to.deep.eq [] expect(images).to.deep.eq [] it 'should handle circular relations', -> @store.sync data: type: 'events' id: 1 attributes: name: 'Demo' relationships: images: links: self: 'http://example.com/events/1/relationships/images' event = @store.find 'events', 1 expect(event.name).to.equal 'Demo' expect(event.images._links).to.deep.equal self: 'http://example.com/events/1/relationships/images' it 'should retain links and meta', -> result = @store.sync links: self: 'http://example.com/events' next: 'http://example.com/events?page[offset]=2' meta: name: 'top level meta data' value: 1 data: [ type: 'events' id: 1 meta: name: 'second level meta' value: 2 attributes: name: 'Demo' article: name: 'An Article test' teaser: 'this is a teaser...' body: 'this is an article body' meta: author: 'PI:NAME:<NAME>END_PI' date: '2017-06-26' meta: name: 'attribute nested meta' value: 3 relationships: comment: links: self: 'http://example.com/events/1/relationships/comment' related: 'http://example.com/events/1/comment' data: type: 'comment', id: 2 ] included: [ type: 'comment' id: 2 attributes: name: 'Comment' details: user: 'micha3ldavid' body: 'this is a comment...' links: self: 'http://example.com/comment/2' meta: author: 'PI:NAME:<NAME>END_PI' date: '2017-06-26' ] expect(result.meta).to.deep.equal {name: 'top level meta data', value: 1} expect(result[0].article.meta).to.deep.equal {author: 'PI:NAME:<NAME>END_PI', date: '2017-06-26'} expect(result[0].comment.meta).to.deep.equal {author: 'PI:NAME:<NAME>END_PI', date: '2017-06-26'} expect(result[0].comment._links).to.deep.equal {self: 'http://example.com/events/1/relationships/comment', related: 'http://example.com/events/1/comment'}
[ { "context": " newUser = new User()\n newUser.username = username\n newUser.oauthAccessToken = token\n newU", "end": 3203, "score": 0.9994101524353027, "start": 3195, "tag": "USERNAME", "value": "username" }, { "context": " newUser.salt = salt\n newUser.password = md5(pwd + salt)\n\n c = new Evernote.Client({token", "end": 3557, "score": 0.7617728114128113, "start": 3554, "tag": "PASSWORD", "value": "md5" }, { "context": "wUser.salt = salt\n newUser.password = md5(pwd + salt)\n\n c = new Evernote.Client({token: token})\n ", "end": 3568, "score": 0.8162703514099121, "start": 3562, "tag": "PASSWORD", "value": "+ salt" }, { "context": "'/user/', (req, res) ->\n User.findOne {username:'youqingkui'}, (err, row) ->\n return console.log err if er", "end": 4834, "score": 0.9996979832649231, "start": 4824, "tag": "USERNAME", "value": "youqingkui" }, { "context": "t_login', (req, res) ->\n req.session.username = 'youqingkui'\n return res.send \"ok login\"\n\n\n\nmodule.exports =", "end": 5002, "score": 0.9996773600578308, "start": 4992, "tag": "USERNAME", "value": "youqingkui" } ]
routes/index.coffee
youqingkui/zhihu2evernote
0
express = require('express') router = express.Router() Evernote = require('evernote').Evernote config = require('../config.json') callbackUrl = "http://localhost:3000/oauth_callback" User = require('../models/user') async = require('async') createNote = require('../server/createAccount') crypto = require('crypto') md5 = (str) -> md5sum = crypto.createHash('md5') md5sum.update(str) str = md5sum.digest('hex') return str ### GET home page. ### router.get '/', (req, res, next) -> res.render 'index', title: 'Express' return router.get '/oauth', (req, res) -> client = new Evernote.Client consumerKey: config.API_CONSUMER_KEY consumerSecret: config.API_CONSUMER_SECRET sandbox: config.SANDBOX client.getRequestToken callbackUrl, (err, oauthToken, oauthTokenSecret, result) -> return console.log err if err console.log "result =>",result console.log "oauthToken =>", oauthToken console.log "oauthTokenSecret =>", oauthTokenSecret req.session.oauthTokenSecret = oauthTokenSecret return res.redirect(client.getAuthorizeUrl(oauthToken)) router.get '/oauth_callback', (req, res) -> client = new Evernote.Client consumerKey: config.API_CONSUMER_KEY, consumerSecret: config.API_CONSUMER_SECRET, sandbox: config.SANDBOX oauthToken = req.query.oauth_token oauthTokenSecret = req.session.oauthTokenSecret oauth_verifier = req.query.oauth_verifier token = '' resInfo = null username = '' async.auto # 验证信息 checkOauth:(cb) -> client.getAccessToken oauthToken, oauthTokenSecret, oauth_verifier, (err, oauthAccessToken, oauthAccessTokenSecret, results) -> if err return res.send "oauth err" if err console.log "oauthAccessToken =>", oauthAccessToken console.log "oauthAccessTokenSecret =>", oauthAccessTokenSecret console.log "results =>", results token = oauthAccessToken resInfo = results cb() # 获取用户信息 getUserInfo:['checkOauth', (cb, result) -> c = new Evernote.Client token:token userStore = c.getUserStore() userStore.getUser (err, user) -> return console.log err if err cb(null, user) ] # 检查用户是否存在 checkUser:['getUserInfo', (cb, result) -> username = result.getUserInfo.username User.findOne {username:username}, (err, row) -> return console.log err if err cb(null, row) ] # 修改用户信息 comUser:['checkUser', (cb, result) -> user = result.checkUser if user user.oauthAccessToken = token user.edamShard = resInfo.edamShard user.edamUserId = resInfo.edamUserId user.edamExpires = resInfo.edamExpires user.edamNoteStoreUrl = resInfo.edamNoteStoreUrl user.edamWebApiUrlPrefix = resInfo.edamWebApiUrlPrefix user.save (err, row) -> return console.log err if err return res.send "up ok" else cb() ] # 创建用户 createUser:['comUser', (cb) -> pwd = Math.random().toString(36).substr(2) salt = Math.random().toString(36).substr(2) newUser = new User() newUser.username = username newUser.oauthAccessToken = token newUser.edamShard = resInfo.edamShard newUser.edamUserId = resInfo.edamUserId newUser.edamExpires = resInfo.edamExpires newUser.edamNoteStoreUrl = resInfo.edamNoteStoreUrl newUser.edamWebApiUrlPrefix = resInfo.edamWebApiUrlPrefix newUser.salt = salt newUser.password = md5(pwd + salt) c = new Evernote.Client({token: token}) noteStore = c.getNoteStore() createNote noteStore, 'zhihu2evernote', pwd, (err, note) -> return console.log err if err newUser.save (err2, row) -> return console.log err2 if err2 return res.send "create ok" ] router.get '/login', (req, res) -> console.log req.session.username return res.render 'login', {title:'登录'} router.post '/login', (req, res) -> username = (req.body.username || '').trim() password = (req.body.password || '').trim() async.auto findUser:(cb) -> User.findOne {username:username}, (err, row) -> return console.log err if err if not row error = "没有此用户或者密码错误" return res.render 'login', {title:'登入', error:error, username:username} cb(null, row) checkPWD:['findUser', (cb, result) -> user = result.findUser md5Pwd = md5(password + user.salt) if md5Pwd != user.password error = "密码错误" return res.render 'login', {title:'登入', error:error, username:username} req.session.username = user.username return res.redirect('/') ] router.get '/user/', (req, res) -> User.findOne {username:'youqingkui'}, (err, row) -> return console.log err if err console.log row res.send row router.get '/test_login', (req, res) -> req.session.username = 'youqingkui' return res.send "ok login" module.exports = router
55836
express = require('express') router = express.Router() Evernote = require('evernote').Evernote config = require('../config.json') callbackUrl = "http://localhost:3000/oauth_callback" User = require('../models/user') async = require('async') createNote = require('../server/createAccount') crypto = require('crypto') md5 = (str) -> md5sum = crypto.createHash('md5') md5sum.update(str) str = md5sum.digest('hex') return str ### GET home page. ### router.get '/', (req, res, next) -> res.render 'index', title: 'Express' return router.get '/oauth', (req, res) -> client = new Evernote.Client consumerKey: config.API_CONSUMER_KEY consumerSecret: config.API_CONSUMER_SECRET sandbox: config.SANDBOX client.getRequestToken callbackUrl, (err, oauthToken, oauthTokenSecret, result) -> return console.log err if err console.log "result =>",result console.log "oauthToken =>", oauthToken console.log "oauthTokenSecret =>", oauthTokenSecret req.session.oauthTokenSecret = oauthTokenSecret return res.redirect(client.getAuthorizeUrl(oauthToken)) router.get '/oauth_callback', (req, res) -> client = new Evernote.Client consumerKey: config.API_CONSUMER_KEY, consumerSecret: config.API_CONSUMER_SECRET, sandbox: config.SANDBOX oauthToken = req.query.oauth_token oauthTokenSecret = req.session.oauthTokenSecret oauth_verifier = req.query.oauth_verifier token = '' resInfo = null username = '' async.auto # 验证信息 checkOauth:(cb) -> client.getAccessToken oauthToken, oauthTokenSecret, oauth_verifier, (err, oauthAccessToken, oauthAccessTokenSecret, results) -> if err return res.send "oauth err" if err console.log "oauthAccessToken =>", oauthAccessToken console.log "oauthAccessTokenSecret =>", oauthAccessTokenSecret console.log "results =>", results token = oauthAccessToken resInfo = results cb() # 获取用户信息 getUserInfo:['checkOauth', (cb, result) -> c = new Evernote.Client token:token userStore = c.getUserStore() userStore.getUser (err, user) -> return console.log err if err cb(null, user) ] # 检查用户是否存在 checkUser:['getUserInfo', (cb, result) -> username = result.getUserInfo.username User.findOne {username:username}, (err, row) -> return console.log err if err cb(null, row) ] # 修改用户信息 comUser:['checkUser', (cb, result) -> user = result.checkUser if user user.oauthAccessToken = token user.edamShard = resInfo.edamShard user.edamUserId = resInfo.edamUserId user.edamExpires = resInfo.edamExpires user.edamNoteStoreUrl = resInfo.edamNoteStoreUrl user.edamWebApiUrlPrefix = resInfo.edamWebApiUrlPrefix user.save (err, row) -> return console.log err if err return res.send "up ok" else cb() ] # 创建用户 createUser:['comUser', (cb) -> pwd = Math.random().toString(36).substr(2) salt = Math.random().toString(36).substr(2) newUser = new User() newUser.username = username newUser.oauthAccessToken = token newUser.edamShard = resInfo.edamShard newUser.edamUserId = resInfo.edamUserId newUser.edamExpires = resInfo.edamExpires newUser.edamNoteStoreUrl = resInfo.edamNoteStoreUrl newUser.edamWebApiUrlPrefix = resInfo.edamWebApiUrlPrefix newUser.salt = salt newUser.password = <PASSWORD>(pwd <PASSWORD>) c = new Evernote.Client({token: token}) noteStore = c.getNoteStore() createNote noteStore, 'zhihu2evernote', pwd, (err, note) -> return console.log err if err newUser.save (err2, row) -> return console.log err2 if err2 return res.send "create ok" ] router.get '/login', (req, res) -> console.log req.session.username return res.render 'login', {title:'登录'} router.post '/login', (req, res) -> username = (req.body.username || '').trim() password = (req.body.password || '').trim() async.auto findUser:(cb) -> User.findOne {username:username}, (err, row) -> return console.log err if err if not row error = "没有此用户或者密码错误" return res.render 'login', {title:'登入', error:error, username:username} cb(null, row) checkPWD:['findUser', (cb, result) -> user = result.findUser md5Pwd = md5(password + user.salt) if md5Pwd != user.password error = "密码错误" return res.render 'login', {title:'登入', error:error, username:username} req.session.username = user.username return res.redirect('/') ] router.get '/user/', (req, res) -> User.findOne {username:'youqingkui'}, (err, row) -> return console.log err if err console.log row res.send row router.get '/test_login', (req, res) -> req.session.username = 'youqingkui' return res.send "ok login" module.exports = router
true
express = require('express') router = express.Router() Evernote = require('evernote').Evernote config = require('../config.json') callbackUrl = "http://localhost:3000/oauth_callback" User = require('../models/user') async = require('async') createNote = require('../server/createAccount') crypto = require('crypto') md5 = (str) -> md5sum = crypto.createHash('md5') md5sum.update(str) str = md5sum.digest('hex') return str ### GET home page. ### router.get '/', (req, res, next) -> res.render 'index', title: 'Express' return router.get '/oauth', (req, res) -> client = new Evernote.Client consumerKey: config.API_CONSUMER_KEY consumerSecret: config.API_CONSUMER_SECRET sandbox: config.SANDBOX client.getRequestToken callbackUrl, (err, oauthToken, oauthTokenSecret, result) -> return console.log err if err console.log "result =>",result console.log "oauthToken =>", oauthToken console.log "oauthTokenSecret =>", oauthTokenSecret req.session.oauthTokenSecret = oauthTokenSecret return res.redirect(client.getAuthorizeUrl(oauthToken)) router.get '/oauth_callback', (req, res) -> client = new Evernote.Client consumerKey: config.API_CONSUMER_KEY, consumerSecret: config.API_CONSUMER_SECRET, sandbox: config.SANDBOX oauthToken = req.query.oauth_token oauthTokenSecret = req.session.oauthTokenSecret oauth_verifier = req.query.oauth_verifier token = '' resInfo = null username = '' async.auto # 验证信息 checkOauth:(cb) -> client.getAccessToken oauthToken, oauthTokenSecret, oauth_verifier, (err, oauthAccessToken, oauthAccessTokenSecret, results) -> if err return res.send "oauth err" if err console.log "oauthAccessToken =>", oauthAccessToken console.log "oauthAccessTokenSecret =>", oauthAccessTokenSecret console.log "results =>", results token = oauthAccessToken resInfo = results cb() # 获取用户信息 getUserInfo:['checkOauth', (cb, result) -> c = new Evernote.Client token:token userStore = c.getUserStore() userStore.getUser (err, user) -> return console.log err if err cb(null, user) ] # 检查用户是否存在 checkUser:['getUserInfo', (cb, result) -> username = result.getUserInfo.username User.findOne {username:username}, (err, row) -> return console.log err if err cb(null, row) ] # 修改用户信息 comUser:['checkUser', (cb, result) -> user = result.checkUser if user user.oauthAccessToken = token user.edamShard = resInfo.edamShard user.edamUserId = resInfo.edamUserId user.edamExpires = resInfo.edamExpires user.edamNoteStoreUrl = resInfo.edamNoteStoreUrl user.edamWebApiUrlPrefix = resInfo.edamWebApiUrlPrefix user.save (err, row) -> return console.log err if err return res.send "up ok" else cb() ] # 创建用户 createUser:['comUser', (cb) -> pwd = Math.random().toString(36).substr(2) salt = Math.random().toString(36).substr(2) newUser = new User() newUser.username = username newUser.oauthAccessToken = token newUser.edamShard = resInfo.edamShard newUser.edamUserId = resInfo.edamUserId newUser.edamExpires = resInfo.edamExpires newUser.edamNoteStoreUrl = resInfo.edamNoteStoreUrl newUser.edamWebApiUrlPrefix = resInfo.edamWebApiUrlPrefix newUser.salt = salt newUser.password = PI:PASSWORD:<PASSWORD>END_PI(pwd PI:PASSWORD:<PASSWORD>END_PI) c = new Evernote.Client({token: token}) noteStore = c.getNoteStore() createNote noteStore, 'zhihu2evernote', pwd, (err, note) -> return console.log err if err newUser.save (err2, row) -> return console.log err2 if err2 return res.send "create ok" ] router.get '/login', (req, res) -> console.log req.session.username return res.render 'login', {title:'登录'} router.post '/login', (req, res) -> username = (req.body.username || '').trim() password = (req.body.password || '').trim() async.auto findUser:(cb) -> User.findOne {username:username}, (err, row) -> return console.log err if err if not row error = "没有此用户或者密码错误" return res.render 'login', {title:'登入', error:error, username:username} cb(null, row) checkPWD:['findUser', (cb, result) -> user = result.findUser md5Pwd = md5(password + user.salt) if md5Pwd != user.password error = "密码错误" return res.render 'login', {title:'登入', error:error, username:username} req.session.username = user.username return res.redirect('/') ] router.get '/user/', (req, res) -> User.findOne {username:'youqingkui'}, (err, row) -> return console.log err if err console.log row res.send row router.get '/test_login', (req, res) -> req.session.username = 'youqingkui' return res.send "ok login" module.exports = router
[ { "context": "', 'link')\n selected: new Batman.Object(name: 'crono')\n helpers.render '<select data-bind=\"selected.n", "end": 375, "score": 0.8770135641098022, "start": 370, "tag": "NAME", "value": "crono" }, { "context": "context = Batman\n heros: new Batman.SimpleSet('mario', 'crono', 'link')\n selected: 'crono'\n help", "end": 916, "score": 0.5535367131233215, "start": 913, "tag": "NAME", "value": "mar" }, { "context": "ve the rendered event\n equal node[0].value, 'crono'\n equal context.get('crono.selected'), true\n", "end": 1944, "score": 0.8743686079978943, "start": 1939, "tag": "NAME", "value": "crono" }, { "context": "('mario.selected'), false\n\n node[0].value = 'mario'\n helpers.triggerChange node[0]\n delay ", "end": 2072, "score": 0.9641764163970947, "start": 2067, "tag": "NAME", "value": "mario" }, { "context": "xt = new Batman.Object\n heros: new Batman.Set('mario', 'crono', 'link', 'kirby')\n selected: new B", "end": 2397, "score": 0.9088427424430847, "start": 2394, "tag": "NAME", "value": "mar" }, { "context": "Batman.Object\n heros: new Batman.Set('mario', 'crono', 'link', 'kirby')\n selected: new Batman.Objec", "end": 2408, "score": 0.9012632369995117, "start": 2403, "tag": "NAME", "value": "crono" }, { "context": " 'kirby')\n selected: new Batman.Object(name: ['crono', 'link'])\n helpers.render '<select multiple=\"mu", "end": 2473, "score": 0.9590238332748413, "start": 2468, "tag": "NAME", "value": "crono" }, { "context": "\n selected: new Batman.Object(name: ['crono', 'link'])\n helpers.render '<select multiple=\"multiple\" ", "end": 2481, "score": 0.7153189778327942, "start": 2477, "tag": "NAME", "value": "link" }, { "context": "es, yes, no]\n context.set 'selected.name', ['mario', 'kirby']\n delay =>\n selections = (c", "end": 2913, "score": 0.9820455312728882, "start": 2908, "tag": "NAME", "value": "mario" }, { "context": "no]\n context.set 'selected.name', ['mario', 'kirby']\n delay =>\n selections = (c.selected", "end": 2922, "score": 0.9846409559249878, "start": 2917, "tag": "NAME", "value": "kirby" }, { "context": "le=\"multiple\" data-bind=\"selected\"><option value=\"mario\" data-bind-selected=\"mario.selected\"></option><op", "end": 3412, "score": 0.6963342428207397, "start": 3407, "tag": "NAME", "value": "mario" }, { "context": "selected=\"mario.selected\"></option><option value=\"crono\" data-bind-selected=\"crono.selected\"></option></s", "end": 3479, "score": 0.7373007535934448, "start": 3474, "tag": "NAME", "value": "crono" } ]
tests/batman/view/select_rendering_test.coffee
airhorns/batman
1
helpers = if typeof require is 'undefined' then window.viewHelpers else require './view_helper' QUnit.module 'Batman.View &lt;select&gt; rendering' asyncTest 'it should bind the value of a select box and update when the javascript land value changes', 2, -> context = Batman heros: new Batman.Set('mario', 'crono', 'link') selected: new Batman.Object(name: 'crono') helpers.render '<select data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) -> delay => # wait for select's data-bind listener to receive the rendered event equals node[0].value, 'crono' context.set 'selected.name', 'link' delay => equal node[0].value, 'link' asyncTest 'it should bind the value of a select box and update the javascript land value with the selected option', 3, -> context = Batman heros: new Batman.SimpleSet('mario', 'crono', 'link') selected: 'crono' helpers.render '<select data-bind="selected"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) -> delay => # wait for select's data-bind listener to receive the rendered event equals node[0].value, 'crono' context.set 'selected', 'link' delay => equal node[0].value, 'link' context.set 'selected', 'mario' delay => equal node[0].value, 'mario' asyncTest 'it binds the options of a select box and updates when the select\'s value changes', -> context = Batman something: 'crono' mario: Batman(selected: null) crono: Batman(selected: null) helpers.render '<select data-bind="something"><option value="mario" data-bind-selected="mario.selected"></option><option value="crono" data-bind-selected="crono.selected"></option></select>', context, (node) -> delay => # wait for select's data-bind listener to receive the rendered event equal node[0].value, 'crono' equal context.get('crono.selected'), true equal context.get('mario.selected'), false node[0].value = 'mario' helpers.triggerChange node[0] delay => equal context.get('mario.selected'), true equal context.get('crono.selected'), false asyncTest 'it binds the value of a multi-select box and updates the options when the bound value changes', -> context = new Batman.Object heros: new Batman.Set('mario', 'crono', 'link', 'kirby') selected: new Batman.Object(name: ['crono', 'link']) helpers.render '<select multiple="multiple" size="2" data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) -> delay => # wait for select's data-bind listener to receive the rendered event selections = (c.selected for c in node[0].children when c.nodeType is 1) deepEqual selections, [no, yes, yes, no] context.set 'selected.name', ['mario', 'kirby'] delay => selections = (c.selected for c in node[0].children when c.nodeType is 1) deepEqual selections, [yes, no, no, yes] asyncTest 'it binds the value of a multi-select box and updates the value when the selected options change', -> context = new Batman.Object selected: 'crono' mario: new Batman.Object(selected: null) crono: new Batman.Object(selected: null) helpers.render '<select multiple="multiple" data-bind="selected"><option value="mario" data-bind-selected="mario.selected"></option><option value="crono" data-bind-selected="crono.selected"></option></select>', context, (node) -> delay => # wait for select's data-bind listener to receive the rendered event equal node[0].value, 'crono', 'node value is crono' equal context.get('selected'), 'crono', 'selected is crono' equal context.get('crono.selected'), true, 'crono is selected' equal context.get('mario.selected'), false, 'mario is not selected' context.set 'mario.selected', true delay => equal context.get('mario.selected'), true, 'mario is selected' equal context.get('crono.selected'), true, 'crono is still selected' deepEqual context.get('selected'), ['mario', 'crono'], 'mario and crono are selected in binding' for opt in node[0].children ok opt.selected, "#{opt.value} option is selected" asyncTest 'should be able to remove bound select nodes', 2, -> context = new Batman.Object selected: "foo" helpers.render '<select data-bind="selected"><option value="foo">foo</option></select>', context, (node) -> Batman.DOM.removeNode(node[0]) deepEqual Batman.data(node[0]), {} deepEqual Batman._data(node[0]), {} QUnit.start()
80500
helpers = if typeof require is 'undefined' then window.viewHelpers else require './view_helper' QUnit.module 'Batman.View &lt;select&gt; rendering' asyncTest 'it should bind the value of a select box and update when the javascript land value changes', 2, -> context = Batman heros: new Batman.Set('mario', 'crono', 'link') selected: new Batman.Object(name: '<NAME>') helpers.render '<select data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) -> delay => # wait for select's data-bind listener to receive the rendered event equals node[0].value, 'crono' context.set 'selected.name', 'link' delay => equal node[0].value, 'link' asyncTest 'it should bind the value of a select box and update the javascript land value with the selected option', 3, -> context = Batman heros: new Batman.SimpleSet('<NAME>io', 'crono', 'link') selected: 'crono' helpers.render '<select data-bind="selected"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) -> delay => # wait for select's data-bind listener to receive the rendered event equals node[0].value, 'crono' context.set 'selected', 'link' delay => equal node[0].value, 'link' context.set 'selected', 'mario' delay => equal node[0].value, 'mario' asyncTest 'it binds the options of a select box and updates when the select\'s value changes', -> context = Batman something: 'crono' mario: Batman(selected: null) crono: Batman(selected: null) helpers.render '<select data-bind="something"><option value="mario" data-bind-selected="mario.selected"></option><option value="crono" data-bind-selected="crono.selected"></option></select>', context, (node) -> delay => # wait for select's data-bind listener to receive the rendered event equal node[0].value, '<NAME>' equal context.get('crono.selected'), true equal context.get('mario.selected'), false node[0].value = '<NAME>' helpers.triggerChange node[0] delay => equal context.get('mario.selected'), true equal context.get('crono.selected'), false asyncTest 'it binds the value of a multi-select box and updates the options when the bound value changes', -> context = new Batman.Object heros: new Batman.Set('<NAME>io', '<NAME>', 'link', 'kirby') selected: new Batman.Object(name: ['<NAME>', '<NAME>']) helpers.render '<select multiple="multiple" size="2" data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) -> delay => # wait for select's data-bind listener to receive the rendered event selections = (c.selected for c in node[0].children when c.nodeType is 1) deepEqual selections, [no, yes, yes, no] context.set 'selected.name', ['<NAME>', '<NAME>'] delay => selections = (c.selected for c in node[0].children when c.nodeType is 1) deepEqual selections, [yes, no, no, yes] asyncTest 'it binds the value of a multi-select box and updates the value when the selected options change', -> context = new Batman.Object selected: 'crono' mario: new Batman.Object(selected: null) crono: new Batman.Object(selected: null) helpers.render '<select multiple="multiple" data-bind="selected"><option value="<NAME>" data-bind-selected="mario.selected"></option><option value="<NAME>" data-bind-selected="crono.selected"></option></select>', context, (node) -> delay => # wait for select's data-bind listener to receive the rendered event equal node[0].value, 'crono', 'node value is crono' equal context.get('selected'), 'crono', 'selected is crono' equal context.get('crono.selected'), true, 'crono is selected' equal context.get('mario.selected'), false, 'mario is not selected' context.set 'mario.selected', true delay => equal context.get('mario.selected'), true, 'mario is selected' equal context.get('crono.selected'), true, 'crono is still selected' deepEqual context.get('selected'), ['mario', 'crono'], 'mario and crono are selected in binding' for opt in node[0].children ok opt.selected, "#{opt.value} option is selected" asyncTest 'should be able to remove bound select nodes', 2, -> context = new Batman.Object selected: "foo" helpers.render '<select data-bind="selected"><option value="foo">foo</option></select>', context, (node) -> Batman.DOM.removeNode(node[0]) deepEqual Batman.data(node[0]), {} deepEqual Batman._data(node[0]), {} QUnit.start()
true
helpers = if typeof require is 'undefined' then window.viewHelpers else require './view_helper' QUnit.module 'Batman.View &lt;select&gt; rendering' asyncTest 'it should bind the value of a select box and update when the javascript land value changes', 2, -> context = Batman heros: new Batman.Set('mario', 'crono', 'link') selected: new Batman.Object(name: 'PI:NAME:<NAME>END_PI') helpers.render '<select data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) -> delay => # wait for select's data-bind listener to receive the rendered event equals node[0].value, 'crono' context.set 'selected.name', 'link' delay => equal node[0].value, 'link' asyncTest 'it should bind the value of a select box and update the javascript land value with the selected option', 3, -> context = Batman heros: new Batman.SimpleSet('PI:NAME:<NAME>END_PIio', 'crono', 'link') selected: 'crono' helpers.render '<select data-bind="selected"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) -> delay => # wait for select's data-bind listener to receive the rendered event equals node[0].value, 'crono' context.set 'selected', 'link' delay => equal node[0].value, 'link' context.set 'selected', 'mario' delay => equal node[0].value, 'mario' asyncTest 'it binds the options of a select box and updates when the select\'s value changes', -> context = Batman something: 'crono' mario: Batman(selected: null) crono: Batman(selected: null) helpers.render '<select data-bind="something"><option value="mario" data-bind-selected="mario.selected"></option><option value="crono" data-bind-selected="crono.selected"></option></select>', context, (node) -> delay => # wait for select's data-bind listener to receive the rendered event equal node[0].value, 'PI:NAME:<NAME>END_PI' equal context.get('crono.selected'), true equal context.get('mario.selected'), false node[0].value = 'PI:NAME:<NAME>END_PI' helpers.triggerChange node[0] delay => equal context.get('mario.selected'), true equal context.get('crono.selected'), false asyncTest 'it binds the value of a multi-select box and updates the options when the bound value changes', -> context = new Batman.Object heros: new Batman.Set('PI:NAME:<NAME>END_PIio', 'PI:NAME:<NAME>END_PI', 'link', 'kirby') selected: new Batman.Object(name: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']) helpers.render '<select multiple="multiple" size="2" data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) -> delay => # wait for select's data-bind listener to receive the rendered event selections = (c.selected for c in node[0].children when c.nodeType is 1) deepEqual selections, [no, yes, yes, no] context.set 'selected.name', ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] delay => selections = (c.selected for c in node[0].children when c.nodeType is 1) deepEqual selections, [yes, no, no, yes] asyncTest 'it binds the value of a multi-select box and updates the value when the selected options change', -> context = new Batman.Object selected: 'crono' mario: new Batman.Object(selected: null) crono: new Batman.Object(selected: null) helpers.render '<select multiple="multiple" data-bind="selected"><option value="PI:NAME:<NAME>END_PI" data-bind-selected="mario.selected"></option><option value="PI:NAME:<NAME>END_PI" data-bind-selected="crono.selected"></option></select>', context, (node) -> delay => # wait for select's data-bind listener to receive the rendered event equal node[0].value, 'crono', 'node value is crono' equal context.get('selected'), 'crono', 'selected is crono' equal context.get('crono.selected'), true, 'crono is selected' equal context.get('mario.selected'), false, 'mario is not selected' context.set 'mario.selected', true delay => equal context.get('mario.selected'), true, 'mario is selected' equal context.get('crono.selected'), true, 'crono is still selected' deepEqual context.get('selected'), ['mario', 'crono'], 'mario and crono are selected in binding' for opt in node[0].children ok opt.selected, "#{opt.value} option is selected" asyncTest 'should be able to remove bound select nodes', 2, -> context = new Batman.Object selected: "foo" helpers.render '<select data-bind="selected"><option value="foo">foo</option></select>', context, (node) -> Batman.DOM.removeNode(node[0]) deepEqual Batman.data(node[0]), {} deepEqual Batman._data(node[0]), {} QUnit.start()
[ { "context": "ew Artwork fabricate 'artwork', { partner: name: 'House of Bitty' }]\n @template = render('index')(\n sd", "end": 521, "score": 0.9867294430732727, "start": 507, "tag": "NAME", "value": "House of Bitty" }, { "context": "tner name', ->\n @template.should.containEql 'Gagosian'\n", "end": 1027, "score": 0.8732485175132751, "start": 1019, "tag": "NAME", "value": "Gagosian" } ]
src/desktop/components/fillwidth_row/test/template.coffee
kanaabe/force
1
cheerio = require 'cheerio' jade = require 'jade' path = require 'path' fs = require 'fs' Backbone = require 'backbone' { fabricate } = require 'antigravity' Artwork = require '../../../models/artwork' render = -> filename = path.resolve __dirname, "../template.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'Fillwidth row', -> describe 'artwork with a partner', -> beforeEach -> @artworks = [new Artwork fabricate 'artwork', { partner: name: 'House of Bitty' }] @template = render('index')( sd: {} artworks: @artworks ) it 'correctly renders and displays the partner name', -> @template.should.containEql 'House of Bitty' describe 'artwork with a partner', -> beforeEach -> @artworks = [new Artwork fabricate 'artwork'] @template = render('index')( sd: {} artworks: @artworks ) it 'correctly renders and displays the partner name', -> @template.should.containEql 'Gagosian'
158557
cheerio = require 'cheerio' jade = require 'jade' path = require 'path' fs = require 'fs' Backbone = require 'backbone' { fabricate } = require 'antigravity' Artwork = require '../../../models/artwork' render = -> filename = path.resolve __dirname, "../template.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'Fillwidth row', -> describe 'artwork with a partner', -> beforeEach -> @artworks = [new Artwork fabricate 'artwork', { partner: name: '<NAME>' }] @template = render('index')( sd: {} artworks: @artworks ) it 'correctly renders and displays the partner name', -> @template.should.containEql 'House of Bitty' describe 'artwork with a partner', -> beforeEach -> @artworks = [new Artwork fabricate 'artwork'] @template = render('index')( sd: {} artworks: @artworks ) it 'correctly renders and displays the partner name', -> @template.should.containEql '<NAME>'
true
cheerio = require 'cheerio' jade = require 'jade' path = require 'path' fs = require 'fs' Backbone = require 'backbone' { fabricate } = require 'antigravity' Artwork = require '../../../models/artwork' render = -> filename = path.resolve __dirname, "../template.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'Fillwidth row', -> describe 'artwork with a partner', -> beforeEach -> @artworks = [new Artwork fabricate 'artwork', { partner: name: 'PI:NAME:<NAME>END_PI' }] @template = render('index')( sd: {} artworks: @artworks ) it 'correctly renders and displays the partner name', -> @template.should.containEql 'House of Bitty' describe 'artwork with a partner', -> beforeEach -> @artworks = [new Artwork fabricate 'artwork'] @template = render('index')( sd: {} artworks: @artworks ) it 'correctly renders and displays the partner name', -> @template.should.containEql 'PI:NAME:<NAME>END_PI'
[ { "context": "->\n $scope.entities = [\n name: \"Players\"\n members: []\n ,\n na", "end": 5811, "score": 0.506792426109314, "start": 5804, "tag": "NAME", "value": "Players" }, { "context": " members: []\n ,\n name: \"NPCs\"\n members: []\n ]\n entity", "end": 5932, "score": 0.8431153297424316, "start": 5928, "tag": "NAME", "value": "NPCs" } ]
public/core.coffee
tim-dev/rpg_calc
0
String.prototype.toTitleCase = () -> return this.replace /\w\S*/g, (txt) -> return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase() uuid = () -> 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace /[xy]/g, (c) -> r = Math.random()*16|0 v = if c == 'x' then r else r&0x3 or 0x8 return v.toString(16) remove_spaces = (txt) -> return '' unless txt txt.replace(/\s/g, '') window.roll_dice = (roll_string) -> ### Example roll strings: 1d6 1d8 + 8 1d4 - 1 1d8 + 2d4 + 3 ### # TODO more operations! dice_parts = roll_string.match(/.+?(?=[+-]|$)/g) #dice_parts = roll_string.split(/\ *\+\ */g) roll = 0 roll_parts = [] for dice in dice_parts roll_part = _roll_die(dice) roll_parts.push("#{ dice } => #{ roll_part }", ) roll += roll_part console.log "Rolled a #{ roll_string }, parts were #{ roll_parts }" return roll _roll_die = (dice) -> return dice if typeof dice == "int" return parseInt(dice) unless /d/i.test(dice) # TODO Bonus dice! [num, die] = dice.split(/d/i) num = parseInt(num) die = parseInt(die) total = 0 for i in [0...num] roll = Math.ceil(Math.random() * die) total += roll return if num < 0 then total * -1 else total class Entity @defaults = name : "New entity" cur_hit_points : 10 max_hit_points : 10 armor_class : 10 armor_reduction : 0 weapons : [] checks : {} constructor: (options={}) -> for k, v of angular.extend({}, Entity.defaults, options) this[k] = v @weapons = @weapons.map (w) -> if w.constructor.name == "Weapon" then w else new Weapon(w) @uuid = uuid() damage: (damage=0) -> @cur_hit_points -= if damage < 0 then 0 else damage heal: (healing=0) -> @cur_hit_points += if healing < 0 then 0 else healing class Weapon @defaults = hit_dice: "1d20" critical: "x2" attack_bonus: "0" #damage: "1d6" constructor: (options={}) -> angular.extend(this, Weapon.defaults, options) # Temp fix for old style if @hit_dice dice = remove_spaces(@hit_dice).match(/1d20(?:\s*[+-]\s*)(\d+)?/i) if dice @hit_dice = "1d20" @attack_bonus = dice[1] attack: (defender, options={}) -> # Sanitize options options.roll options.hit_modifier # Roll dice roll = if options.roll then parseInt(options.roll) else roll_dice(@hit_dice) return alert("Invalid roll: #{ options.roll }") if isNaN(roll) # Criticals! crit = false crit_multi = 1 if @critical [full, crit_roll, crit_multi] = (@critical or '').match(/(\d+)?(?:\-20)?x(\d)/i) crit_roll = if crit_roll then parseInt(crit_roll) else 20 crit = @hit_dice is "1d20" and roll >= crit_roll crit_multi = if crit then parseInt(crit_multi) else 1 # Parse the bonus from the hit dice roll += parseInt(@attack_bonus or 0) roll += parseInt(options.hit_modifier or 0) hit = crit or roll > defender.armor_class return { hit: hit, roll: roll } unless hit # EXTRA STUFF FOR GAME OF THRONES degree = 1 if options.use_degree degree = Math.ceil((roll - defender.armor_class) / 5) # Calculate damage base_damage = roll_dice(@damage) given_damage = (degree * base_damage * crit_multi) - defender.armor_reduction # Apply damage defender.damage(given_damage) return { hit: hit crit: crit crit_multi: crit_multi roll: roll degree: degree base_damage: base_damage given_damage: given_damage } app = angular.module('app', ['ui.sortable']) .factory('debounce', ['$timeout', ($timeout) -> timer = null return (callback, ms) -> $timeout.cancel(timer) if timer timer = $timeout(callback, ms) ]) .directive 'entity', () -> return { restrict: "E" replace: true scope: false templateUrl: "entity.html" controller: ($scope, $element, $attrs) -> $element.on "click", (e) -> return if $(e.toElement).is("a.dropdown-toggle, a > i, a > b, ul.dropdown-menu li, ul.dropdown-menu li > a") $scope.$apply (scope) -> scope.$root.set_combatant(scope.entity) $scope.hit_point_color = () -> hp = $scope.entity.cur_hit_points if hp < 1 return "red" else if hp < 0.5 * $scope.entity.max_hit_points return "yellow" return "" } .directive 'entitybasics', () -> return { restrict: "E" replace: true scope: {entity: "="} templateUrl: "entity_basics.html" } .directive 'ddentity', () -> return { restrict: "E" replace: true scope: {entity: "="} templateUrl: "ddentity.html" controller: ($scope, $element, $attrs) -> $scope.add_weapon = () -> $scope.entity.weapons.push(new Weapon()) $scope.fix_hit_dice = (weapon) -> weapon.hit_dice = "1d20" #+ weapon.attack_bonus } .controller 'MainController', ['$rootScope', '$timeout', ($scope, $timeout) -> $scope.entities = [ name: "Players" members: [] , name: "Enemies" members: [] , name: "NPCs" members: [] ] entity_counter = 0 $scope.angular = angular $scope.ruleset = "d&d" $scope.check_types = ['listen', 'spot', 'fortitude', 'reflex', 'will'] $scope.results = [] $scope.attack_options = {} $scope.sortableOptions = connectWith: ".entities" revert: true delay: 100 distance: 10 start: (event, ui) -> # Kill the click that happens on mouseup $(event.toElement).one 'click', (e) -> e.stopImmediatePropagation() $scope.roll_check = (check) -> console.log check check_results = [] for e in check.entities res = roll_dice("1d20+" + (e.checks[check.type] or 0)) console.log "Rolled ", "1d20+" + (e.checks[check.type] or 0), " and got a ", res check_results.push(roll: res, name: e.name) check_results.sort (a, b) -> a.roll < b.roll $scope.results.unshift(type: "check", name: check.name || check.type.toTitleCase(), checks: check_results) $scope.make_entity = (options={}) -> e = new Entity(options) # To get animations working e.adding = true $timeout () -> e.adding = false , 1000 return e $scope.get_group = (group_name) -> for group in $scope.entities return group if group.name == group_name return null $scope.extend_entities = (ent_groups) -> for _group in ent_groups group = $scope.get_group(_group.name) if group group.members = group.members.concat(_group.members) else $scope.entities.push _group return $scope.heal_all = (members) -> m.cur_hit_points = m.max_hit_points for m in members $scope.clear_members = (group) -> return unless confirm "Are you sure you want to delete all the #{ group.name.toLowerCase() }?" group.members = [] $scope.add_entity = (group_name="Players") -> ent = $scope.make_entity({name: "entity#{ entity_counter++ }"}) $scope.get_group(group_name).members.push(ent) $scope.edit_entity(ent) $scope.edit_entity = ($event, entity) -> if entity $event.stopPropagation() else entity = $event $event = null $scope.editee = entity $scope.clear_attack() $("#entity_modal").modal("show") return $scope.copy_entity = ($event, i, ent) -> e = angular.copy(ent) e.uuid = null $scope.entities[i].members.push($scope.make_entity(e)) $scope.remove_entity = ($event, gi, i, entity) -> $event.stopPropagation() # Cute animation entity.removing = true $timeout () -> delete $scope.entities[gi].members.splice(i, 1) , 500 $scope.get_attack_options = () -> options = {ruleset: $scope.ruleset} switch $scope.ruleset #when 'd&d' when 'got' options.use_degree = true return options $scope.set_combatant = (entity) -> # If attacker unless $scope.attacker if entity.weapons.length and entity.weapons.indexOf(entity.chosen_weapon) == -1 entity.chosen_weapon = entity.weapons[0] $scope.attacker = entity else $scope.defender = entity if $scope.attacker.uuid == $scope.defender.uuid $scope.clear_attack() return null # Show the modal to get more information $("#attack_modal").modal("show") return $scope.clear_attack = () -> # Clear out the attack data $scope.attacker = null $scope.defender = null $scope.attack_options = {} $scope.do_attack = () -> # Basic options, related to the current ruleset angular.extend($scope.attack_options, $scope.get_attack_options()) result = $scope.attacker.chosen_weapon.attack($scope.defender, $scope.attack_options) result.attacker = $scope.attacker result.defender = $scope.defender result.type = 'attack' console.log result $scope.results.unshift(result) $("#attack_modal").modal("hide") $scope.clear_attack() $scope.remove_attack = (result) -> result.defender.heal(result.given_damage) delete $scope.results.splice($scope.results.indexOf(result), 1) $scope.save = () -> blob = new Blob([angular.toJson($scope.entities)], {type: "application/json;charset=utf-8"}) saveAs(blob, "rpg.json") $scope.load = () -> $("#load_file").trigger("click") return $("#load_file").on "change", () -> file = @files[0] return unless file reader = new FileReader() reader.readAsText(file, "UTF-8") reader.onload = (evt) -> results = JSON.parse(evt.target.result) # The new style for group in results group.members = group.members.map (e) -> return new Entity(e) $scope.$apply (scope) -> scope.extend_entities(results) reader.onerror = (evt) -> console.error "error loading file" # Focus on the proper thing when the modal is shown $("#attack_modal").on "shown", () -> setTimeout () -> $("#attack_modal input[name='custom_roll']").focus() , 1 ]
167957
String.prototype.toTitleCase = () -> return this.replace /\w\S*/g, (txt) -> return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase() uuid = () -> 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace /[xy]/g, (c) -> r = Math.random()*16|0 v = if c == 'x' then r else r&0x3 or 0x8 return v.toString(16) remove_spaces = (txt) -> return '' unless txt txt.replace(/\s/g, '') window.roll_dice = (roll_string) -> ### Example roll strings: 1d6 1d8 + 8 1d4 - 1 1d8 + 2d4 + 3 ### # TODO more operations! dice_parts = roll_string.match(/.+?(?=[+-]|$)/g) #dice_parts = roll_string.split(/\ *\+\ */g) roll = 0 roll_parts = [] for dice in dice_parts roll_part = _roll_die(dice) roll_parts.push("#{ dice } => #{ roll_part }", ) roll += roll_part console.log "Rolled a #{ roll_string }, parts were #{ roll_parts }" return roll _roll_die = (dice) -> return dice if typeof dice == "int" return parseInt(dice) unless /d/i.test(dice) # TODO Bonus dice! [num, die] = dice.split(/d/i) num = parseInt(num) die = parseInt(die) total = 0 for i in [0...num] roll = Math.ceil(Math.random() * die) total += roll return if num < 0 then total * -1 else total class Entity @defaults = name : "New entity" cur_hit_points : 10 max_hit_points : 10 armor_class : 10 armor_reduction : 0 weapons : [] checks : {} constructor: (options={}) -> for k, v of angular.extend({}, Entity.defaults, options) this[k] = v @weapons = @weapons.map (w) -> if w.constructor.name == "Weapon" then w else new Weapon(w) @uuid = uuid() damage: (damage=0) -> @cur_hit_points -= if damage < 0 then 0 else damage heal: (healing=0) -> @cur_hit_points += if healing < 0 then 0 else healing class Weapon @defaults = hit_dice: "1d20" critical: "x2" attack_bonus: "0" #damage: "1d6" constructor: (options={}) -> angular.extend(this, Weapon.defaults, options) # Temp fix for old style if @hit_dice dice = remove_spaces(@hit_dice).match(/1d20(?:\s*[+-]\s*)(\d+)?/i) if dice @hit_dice = "1d20" @attack_bonus = dice[1] attack: (defender, options={}) -> # Sanitize options options.roll options.hit_modifier # Roll dice roll = if options.roll then parseInt(options.roll) else roll_dice(@hit_dice) return alert("Invalid roll: #{ options.roll }") if isNaN(roll) # Criticals! crit = false crit_multi = 1 if @critical [full, crit_roll, crit_multi] = (@critical or '').match(/(\d+)?(?:\-20)?x(\d)/i) crit_roll = if crit_roll then parseInt(crit_roll) else 20 crit = @hit_dice is "1d20" and roll >= crit_roll crit_multi = if crit then parseInt(crit_multi) else 1 # Parse the bonus from the hit dice roll += parseInt(@attack_bonus or 0) roll += parseInt(options.hit_modifier or 0) hit = crit or roll > defender.armor_class return { hit: hit, roll: roll } unless hit # EXTRA STUFF FOR GAME OF THRONES degree = 1 if options.use_degree degree = Math.ceil((roll - defender.armor_class) / 5) # Calculate damage base_damage = roll_dice(@damage) given_damage = (degree * base_damage * crit_multi) - defender.armor_reduction # Apply damage defender.damage(given_damage) return { hit: hit crit: crit crit_multi: crit_multi roll: roll degree: degree base_damage: base_damage given_damage: given_damage } app = angular.module('app', ['ui.sortable']) .factory('debounce', ['$timeout', ($timeout) -> timer = null return (callback, ms) -> $timeout.cancel(timer) if timer timer = $timeout(callback, ms) ]) .directive 'entity', () -> return { restrict: "E" replace: true scope: false templateUrl: "entity.html" controller: ($scope, $element, $attrs) -> $element.on "click", (e) -> return if $(e.toElement).is("a.dropdown-toggle, a > i, a > b, ul.dropdown-menu li, ul.dropdown-menu li > a") $scope.$apply (scope) -> scope.$root.set_combatant(scope.entity) $scope.hit_point_color = () -> hp = $scope.entity.cur_hit_points if hp < 1 return "red" else if hp < 0.5 * $scope.entity.max_hit_points return "yellow" return "" } .directive 'entitybasics', () -> return { restrict: "E" replace: true scope: {entity: "="} templateUrl: "entity_basics.html" } .directive 'ddentity', () -> return { restrict: "E" replace: true scope: {entity: "="} templateUrl: "ddentity.html" controller: ($scope, $element, $attrs) -> $scope.add_weapon = () -> $scope.entity.weapons.push(new Weapon()) $scope.fix_hit_dice = (weapon) -> weapon.hit_dice = "1d20" #+ weapon.attack_bonus } .controller 'MainController', ['$rootScope', '$timeout', ($scope, $timeout) -> $scope.entities = [ name: "<NAME>" members: [] , name: "Enemies" members: [] , name: "<NAME>" members: [] ] entity_counter = 0 $scope.angular = angular $scope.ruleset = "d&d" $scope.check_types = ['listen', 'spot', 'fortitude', 'reflex', 'will'] $scope.results = [] $scope.attack_options = {} $scope.sortableOptions = connectWith: ".entities" revert: true delay: 100 distance: 10 start: (event, ui) -> # Kill the click that happens on mouseup $(event.toElement).one 'click', (e) -> e.stopImmediatePropagation() $scope.roll_check = (check) -> console.log check check_results = [] for e in check.entities res = roll_dice("1d20+" + (e.checks[check.type] or 0)) console.log "Rolled ", "1d20+" + (e.checks[check.type] or 0), " and got a ", res check_results.push(roll: res, name: e.name) check_results.sort (a, b) -> a.roll < b.roll $scope.results.unshift(type: "check", name: check.name || check.type.toTitleCase(), checks: check_results) $scope.make_entity = (options={}) -> e = new Entity(options) # To get animations working e.adding = true $timeout () -> e.adding = false , 1000 return e $scope.get_group = (group_name) -> for group in $scope.entities return group if group.name == group_name return null $scope.extend_entities = (ent_groups) -> for _group in ent_groups group = $scope.get_group(_group.name) if group group.members = group.members.concat(_group.members) else $scope.entities.push _group return $scope.heal_all = (members) -> m.cur_hit_points = m.max_hit_points for m in members $scope.clear_members = (group) -> return unless confirm "Are you sure you want to delete all the #{ group.name.toLowerCase() }?" group.members = [] $scope.add_entity = (group_name="Players") -> ent = $scope.make_entity({name: "entity#{ entity_counter++ }"}) $scope.get_group(group_name).members.push(ent) $scope.edit_entity(ent) $scope.edit_entity = ($event, entity) -> if entity $event.stopPropagation() else entity = $event $event = null $scope.editee = entity $scope.clear_attack() $("#entity_modal").modal("show") return $scope.copy_entity = ($event, i, ent) -> e = angular.copy(ent) e.uuid = null $scope.entities[i].members.push($scope.make_entity(e)) $scope.remove_entity = ($event, gi, i, entity) -> $event.stopPropagation() # Cute animation entity.removing = true $timeout () -> delete $scope.entities[gi].members.splice(i, 1) , 500 $scope.get_attack_options = () -> options = {ruleset: $scope.ruleset} switch $scope.ruleset #when 'd&d' when 'got' options.use_degree = true return options $scope.set_combatant = (entity) -> # If attacker unless $scope.attacker if entity.weapons.length and entity.weapons.indexOf(entity.chosen_weapon) == -1 entity.chosen_weapon = entity.weapons[0] $scope.attacker = entity else $scope.defender = entity if $scope.attacker.uuid == $scope.defender.uuid $scope.clear_attack() return null # Show the modal to get more information $("#attack_modal").modal("show") return $scope.clear_attack = () -> # Clear out the attack data $scope.attacker = null $scope.defender = null $scope.attack_options = {} $scope.do_attack = () -> # Basic options, related to the current ruleset angular.extend($scope.attack_options, $scope.get_attack_options()) result = $scope.attacker.chosen_weapon.attack($scope.defender, $scope.attack_options) result.attacker = $scope.attacker result.defender = $scope.defender result.type = 'attack' console.log result $scope.results.unshift(result) $("#attack_modal").modal("hide") $scope.clear_attack() $scope.remove_attack = (result) -> result.defender.heal(result.given_damage) delete $scope.results.splice($scope.results.indexOf(result), 1) $scope.save = () -> blob = new Blob([angular.toJson($scope.entities)], {type: "application/json;charset=utf-8"}) saveAs(blob, "rpg.json") $scope.load = () -> $("#load_file").trigger("click") return $("#load_file").on "change", () -> file = @files[0] return unless file reader = new FileReader() reader.readAsText(file, "UTF-8") reader.onload = (evt) -> results = JSON.parse(evt.target.result) # The new style for group in results group.members = group.members.map (e) -> return new Entity(e) $scope.$apply (scope) -> scope.extend_entities(results) reader.onerror = (evt) -> console.error "error loading file" # Focus on the proper thing when the modal is shown $("#attack_modal").on "shown", () -> setTimeout () -> $("#attack_modal input[name='custom_roll']").focus() , 1 ]
true
String.prototype.toTitleCase = () -> return this.replace /\w\S*/g, (txt) -> return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase() uuid = () -> 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace /[xy]/g, (c) -> r = Math.random()*16|0 v = if c == 'x' then r else r&0x3 or 0x8 return v.toString(16) remove_spaces = (txt) -> return '' unless txt txt.replace(/\s/g, '') window.roll_dice = (roll_string) -> ### Example roll strings: 1d6 1d8 + 8 1d4 - 1 1d8 + 2d4 + 3 ### # TODO more operations! dice_parts = roll_string.match(/.+?(?=[+-]|$)/g) #dice_parts = roll_string.split(/\ *\+\ */g) roll = 0 roll_parts = [] for dice in dice_parts roll_part = _roll_die(dice) roll_parts.push("#{ dice } => #{ roll_part }", ) roll += roll_part console.log "Rolled a #{ roll_string }, parts were #{ roll_parts }" return roll _roll_die = (dice) -> return dice if typeof dice == "int" return parseInt(dice) unless /d/i.test(dice) # TODO Bonus dice! [num, die] = dice.split(/d/i) num = parseInt(num) die = parseInt(die) total = 0 for i in [0...num] roll = Math.ceil(Math.random() * die) total += roll return if num < 0 then total * -1 else total class Entity @defaults = name : "New entity" cur_hit_points : 10 max_hit_points : 10 armor_class : 10 armor_reduction : 0 weapons : [] checks : {} constructor: (options={}) -> for k, v of angular.extend({}, Entity.defaults, options) this[k] = v @weapons = @weapons.map (w) -> if w.constructor.name == "Weapon" then w else new Weapon(w) @uuid = uuid() damage: (damage=0) -> @cur_hit_points -= if damage < 0 then 0 else damage heal: (healing=0) -> @cur_hit_points += if healing < 0 then 0 else healing class Weapon @defaults = hit_dice: "1d20" critical: "x2" attack_bonus: "0" #damage: "1d6" constructor: (options={}) -> angular.extend(this, Weapon.defaults, options) # Temp fix for old style if @hit_dice dice = remove_spaces(@hit_dice).match(/1d20(?:\s*[+-]\s*)(\d+)?/i) if dice @hit_dice = "1d20" @attack_bonus = dice[1] attack: (defender, options={}) -> # Sanitize options options.roll options.hit_modifier # Roll dice roll = if options.roll then parseInt(options.roll) else roll_dice(@hit_dice) return alert("Invalid roll: #{ options.roll }") if isNaN(roll) # Criticals! crit = false crit_multi = 1 if @critical [full, crit_roll, crit_multi] = (@critical or '').match(/(\d+)?(?:\-20)?x(\d)/i) crit_roll = if crit_roll then parseInt(crit_roll) else 20 crit = @hit_dice is "1d20" and roll >= crit_roll crit_multi = if crit then parseInt(crit_multi) else 1 # Parse the bonus from the hit dice roll += parseInt(@attack_bonus or 0) roll += parseInt(options.hit_modifier or 0) hit = crit or roll > defender.armor_class return { hit: hit, roll: roll } unless hit # EXTRA STUFF FOR GAME OF THRONES degree = 1 if options.use_degree degree = Math.ceil((roll - defender.armor_class) / 5) # Calculate damage base_damage = roll_dice(@damage) given_damage = (degree * base_damage * crit_multi) - defender.armor_reduction # Apply damage defender.damage(given_damage) return { hit: hit crit: crit crit_multi: crit_multi roll: roll degree: degree base_damage: base_damage given_damage: given_damage } app = angular.module('app', ['ui.sortable']) .factory('debounce', ['$timeout', ($timeout) -> timer = null return (callback, ms) -> $timeout.cancel(timer) if timer timer = $timeout(callback, ms) ]) .directive 'entity', () -> return { restrict: "E" replace: true scope: false templateUrl: "entity.html" controller: ($scope, $element, $attrs) -> $element.on "click", (e) -> return if $(e.toElement).is("a.dropdown-toggle, a > i, a > b, ul.dropdown-menu li, ul.dropdown-menu li > a") $scope.$apply (scope) -> scope.$root.set_combatant(scope.entity) $scope.hit_point_color = () -> hp = $scope.entity.cur_hit_points if hp < 1 return "red" else if hp < 0.5 * $scope.entity.max_hit_points return "yellow" return "" } .directive 'entitybasics', () -> return { restrict: "E" replace: true scope: {entity: "="} templateUrl: "entity_basics.html" } .directive 'ddentity', () -> return { restrict: "E" replace: true scope: {entity: "="} templateUrl: "ddentity.html" controller: ($scope, $element, $attrs) -> $scope.add_weapon = () -> $scope.entity.weapons.push(new Weapon()) $scope.fix_hit_dice = (weapon) -> weapon.hit_dice = "1d20" #+ weapon.attack_bonus } .controller 'MainController', ['$rootScope', '$timeout', ($scope, $timeout) -> $scope.entities = [ name: "PI:NAME:<NAME>END_PI" members: [] , name: "Enemies" members: [] , name: "PI:NAME:<NAME>END_PI" members: [] ] entity_counter = 0 $scope.angular = angular $scope.ruleset = "d&d" $scope.check_types = ['listen', 'spot', 'fortitude', 'reflex', 'will'] $scope.results = [] $scope.attack_options = {} $scope.sortableOptions = connectWith: ".entities" revert: true delay: 100 distance: 10 start: (event, ui) -> # Kill the click that happens on mouseup $(event.toElement).one 'click', (e) -> e.stopImmediatePropagation() $scope.roll_check = (check) -> console.log check check_results = [] for e in check.entities res = roll_dice("1d20+" + (e.checks[check.type] or 0)) console.log "Rolled ", "1d20+" + (e.checks[check.type] or 0), " and got a ", res check_results.push(roll: res, name: e.name) check_results.sort (a, b) -> a.roll < b.roll $scope.results.unshift(type: "check", name: check.name || check.type.toTitleCase(), checks: check_results) $scope.make_entity = (options={}) -> e = new Entity(options) # To get animations working e.adding = true $timeout () -> e.adding = false , 1000 return e $scope.get_group = (group_name) -> for group in $scope.entities return group if group.name == group_name return null $scope.extend_entities = (ent_groups) -> for _group in ent_groups group = $scope.get_group(_group.name) if group group.members = group.members.concat(_group.members) else $scope.entities.push _group return $scope.heal_all = (members) -> m.cur_hit_points = m.max_hit_points for m in members $scope.clear_members = (group) -> return unless confirm "Are you sure you want to delete all the #{ group.name.toLowerCase() }?" group.members = [] $scope.add_entity = (group_name="Players") -> ent = $scope.make_entity({name: "entity#{ entity_counter++ }"}) $scope.get_group(group_name).members.push(ent) $scope.edit_entity(ent) $scope.edit_entity = ($event, entity) -> if entity $event.stopPropagation() else entity = $event $event = null $scope.editee = entity $scope.clear_attack() $("#entity_modal").modal("show") return $scope.copy_entity = ($event, i, ent) -> e = angular.copy(ent) e.uuid = null $scope.entities[i].members.push($scope.make_entity(e)) $scope.remove_entity = ($event, gi, i, entity) -> $event.stopPropagation() # Cute animation entity.removing = true $timeout () -> delete $scope.entities[gi].members.splice(i, 1) , 500 $scope.get_attack_options = () -> options = {ruleset: $scope.ruleset} switch $scope.ruleset #when 'd&d' when 'got' options.use_degree = true return options $scope.set_combatant = (entity) -> # If attacker unless $scope.attacker if entity.weapons.length and entity.weapons.indexOf(entity.chosen_weapon) == -1 entity.chosen_weapon = entity.weapons[0] $scope.attacker = entity else $scope.defender = entity if $scope.attacker.uuid == $scope.defender.uuid $scope.clear_attack() return null # Show the modal to get more information $("#attack_modal").modal("show") return $scope.clear_attack = () -> # Clear out the attack data $scope.attacker = null $scope.defender = null $scope.attack_options = {} $scope.do_attack = () -> # Basic options, related to the current ruleset angular.extend($scope.attack_options, $scope.get_attack_options()) result = $scope.attacker.chosen_weapon.attack($scope.defender, $scope.attack_options) result.attacker = $scope.attacker result.defender = $scope.defender result.type = 'attack' console.log result $scope.results.unshift(result) $("#attack_modal").modal("hide") $scope.clear_attack() $scope.remove_attack = (result) -> result.defender.heal(result.given_damage) delete $scope.results.splice($scope.results.indexOf(result), 1) $scope.save = () -> blob = new Blob([angular.toJson($scope.entities)], {type: "application/json;charset=utf-8"}) saveAs(blob, "rpg.json") $scope.load = () -> $("#load_file").trigger("click") return $("#load_file").on "change", () -> file = @files[0] return unless file reader = new FileReader() reader.readAsText(file, "UTF-8") reader.onload = (evt) -> results = JSON.parse(evt.target.result) # The new style for group in results group.members = group.members.map (e) -> return new Entity(e) $scope.$apply (scope) -> scope.extend_entities(results) reader.onerror = (evt) -> console.error "error loading file" # Focus on the proper thing when the modal is shown $("#attack_modal").on "shown", () -> setTimeout () -> $("#attack_modal input[name='custom_roll']").focus() , 1 ]
[ { "context": "console.log db\n await db.users.insert\n name: 'jeff'\n users = await db.users.select()\n console.log ", "end": 173, "score": 0.7722405195236206, "start": 169, "tag": "NAME", "value": "jeff" } ]
src/test/test.coffee
ndxbxrme/rsdb
0
'use strict' db = require('../index') database: 'test' localStorage: 'data' tables: ['users'] .on 'ready', -> console.log db await db.users.insert name: 'jeff' users = await db.users.select() console.log users
74812
'use strict' db = require('../index') database: 'test' localStorage: 'data' tables: ['users'] .on 'ready', -> console.log db await db.users.insert name: '<NAME>' users = await db.users.select() console.log users
true
'use strict' db = require('../index') database: 'test' localStorage: 'data' tables: ['users'] .on 'ready', -> console.log db await db.users.insert name: 'PI:NAME:<NAME>END_PI' users = await db.users.select() console.log users
[ { "context": " ->\n\n shinout:\n firstName : 'Shin'\n age : 29\n regist", "end": 132, "score": 0.9997575283050537, "start": 128, "tag": "NAME", "value": "Shin" }, { "context": " ]\n\n satake:\n firstName : 'Kohta'\n age : 32\n regist", "end": 446, "score": 0.9997830390930176, "start": 441, "tag": "NAME", "value": "Kohta" } ]
spec/fixtures/sample/data/member.coffee
CureApp/base-domain
37
module.exports = dependencies: [ 'hobby' ] data: (pool) -> shinout: firstName : 'Shin' age : 29 registeredAt : '2013-03-10' hobbies : [ pool.hobby.keyboard pool.hobby.ingress ] newHobbies : [ pool.hobby.jogging ] satake: firstName : 'Kohta' age : 32 registeredAt : '2012-02-20' hobbies : [ pool.hobby.sailing ]
130766
module.exports = dependencies: [ 'hobby' ] data: (pool) -> shinout: firstName : '<NAME>' age : 29 registeredAt : '2013-03-10' hobbies : [ pool.hobby.keyboard pool.hobby.ingress ] newHobbies : [ pool.hobby.jogging ] satake: firstName : '<NAME>' age : 32 registeredAt : '2012-02-20' hobbies : [ pool.hobby.sailing ]
true
module.exports = dependencies: [ 'hobby' ] data: (pool) -> shinout: firstName : 'PI:NAME:<NAME>END_PI' age : 29 registeredAt : '2013-03-10' hobbies : [ pool.hobby.keyboard pool.hobby.ingress ] newHobbies : [ pool.hobby.jogging ] satake: firstName : 'PI:NAME:<NAME>END_PI' age : 32 registeredAt : '2012-02-20' hobbies : [ pool.hobby.sailing ]
[ { "context": "276766fd4f50996aeca2b8'\n author_id: ObjectId('4d8cd73191a5c50ce210002a')\n layout: 'standard'\n thumbnail_title: 'To", "end": 275, "score": 0.6580862998962402, "start": 252, "tag": "PASSWORD", "value": "d8cd73191a5c50ce210002a" }, { "context": " body: '<p><h1>10. Lisson Gallery</h1></p><p>Mia Bergeron merges the <em>personal</em> and <em>universal</e", "end": 1545, "score": 0.9998771548271179, "start": 1533, "tag": "NAME", "value": "Mia Bergeron" }, { "context": "rtsy.net/artwork.jpg'\n partner: name: 'Guggenheim'\n date: '1956'\n artists: [ ", "end": 1920, "score": 0.9998470544815063, "start": 1910, "tag": "NAME", "value": "Guggenheim" }, { "context": " date: '1956'\n artists: [ { name: 'Van Gogh' }, { name: 'Van Dogh' } ]\n }\n ", "end": 1987, "score": 0.9998201131820679, "start": 1979, "tag": "NAME", "value": "Van Gogh" }, { "context": " artists: [ { name: 'Van Gogh' }, { name: 'Van Dogh' } ]\n }\n {\n type: 'a", "end": 2009, "score": 0.9998418688774109, "start": 2001, "tag": "NAME", "value": "Van Dogh" }, { "context": "tsy.net/artwork2.jpg'\n partner: name: 'Guggenheim'\n date: '1956'\n artists: [ ", "end": 2242, "score": 0.9998009204864502, "start": 2232, "tag": "NAME", "value": "Guggenheim" }, { "context": " date: '1956'\n artists: [ { name: 'Van Gogh' }]\n }\n ]\n }\n {\n ", "end": 2309, "score": 0.9998352527618408, "start": 2301, "tag": "NAME", "value": "Van Gogh" }, { "context": "tsy.net/artwork2.jpg'\n partner: name: 'Guggenheim'\n date: '1956'\n artists: [ ", "end": 2839, "score": 0.9998571872711182, "start": 2829, "tag": "NAME", "value": "Guggenheim" }, { "context": " date: '1956'\n artists: [ { name: 'Van Gogh' }]\n }\n {\n type: 'im", "end": 2906, "score": 0.9997961521148682, "start": 2898, "tag": "NAME", "value": "Van Gogh" }, { "context": "p://img.png'\n headline: 'Foo'\n author: 'Craig Spaeth'\n slug: 'artsy-editorial-top-ten-booths-at-mia", "end": 3503, "score": 0.9998975992202759, "start": 3491, "tag": "NAME", "value": "Craig Spaeth" }, { "context": "h Description Here.'\n\n fixtures.users =\n id: '4d8cd73191a5c50ce200002a'\n name: 'Craig Spaeth'\n type: 'Admin'\n p", "end": 4406, "score": 0.6248620748519897, "start": 4382, "tag": "KEY", "value": "4d8cd73191a5c50ce200002a" }, { "context": "s =\n id: '4d8cd73191a5c50ce200002a'\n name: 'Craig Spaeth'\n type: 'Admin'\n profile_icon_url: 'https:/", "end": 4431, "score": 0.9998967051506042, "start": 4419, "tag": "NAME", "value": "Craig Spaeth" }, { "context": "n8lwVAubiMIIYYA/square140.png'\n access_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsInBhcnRuZXJfaWRzIjpbXX0.-A-T4cwj1PFzuMhiHn9FYk8IBA0lIukzXKUNa43jjlQ'\n current_channel:\n name: 'Editorial'\n ", "end": 4741, "score": 0.9997414350509644, "start": 4569, "tag": "KEY", "value": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsInBhcnRuZXJfaWRzIjpbXX0.-A-T4cwj1PFzuMhiHn9FYk8IBA0lIukzXKUNa43jjlQ" }, { "context": " name: 'Culture'\n\n fixtures.authors =\n id: '55356a9deca560a0137bb4a7'\n name: 'Halley Johnson'\n bio: 'Writer base", "end": 6047, "score": 0.983649730682373, "start": 6023, "tag": "PASSWORD", "value": "55356a9deca560a0137bb4a7" }, { "context": "s =\n id: '55356a9deca560a0137bb4a7'\n name: 'Halley Johnson'\n bio: 'Writer based in NYC'\n twitter_handl", "end": 6074, "score": 0.9996769428253174, "start": 6060, "tag": "NAME", "value": "Halley Johnson" }, { "context": " bio: 'Writer based in NYC'\n twitter_handle: 'kanaabe'\n image_url: 'https://artsy-media.net/halley.j", "end": 6135, "score": 0.983732283115387, "start": 6128, "tag": "USERNAME", "value": "kanaabe" }, { "context": "3, 'minutes').format()\n user: {\n id: '123'\n name: 'John Doe'\n }\n article: ", "end": 7777, "score": 0.9983773231506348, "start": 7774, "tag": "USERNAME", "value": "123" }, { "context": "()\n user: {\n id: '123'\n name: 'John Doe'\n }\n article: '123456'\n channel: {", "end": 7802, "score": 0.9994208812713623, "start": 7794, "tag": "NAME", "value": "John Doe" }, { "context": "5, 'minutes').format()\n user: {\n id: '124'\n name: 'Ellen Poe'\n }\n article:", "end": 8064, "score": 0.9983965754508972, "start": 8061, "tag": "USERNAME", "value": "124" }, { "context": "()\n user: {\n id: '124'\n name: 'Ellen Poe'\n }\n article: '246810'\n channel: {", "end": 8090, "score": 0.9997830986976624, "start": 8081, "tag": "NAME", "value": "Ellen Poe" }, { "context": "4, 'minutes').format()\n user: {\n id: '126'\n name: 'Steve Publisher'\n }\n ch", "end": 8350, "score": 0.9984986782073975, "start": 8347, "tag": "USERNAME", "value": "126" }, { "context": "()\n user: {\n id: '126'\n name: 'Steve Publisher'\n }\n channel: {\n id: '1'\n ", "end": 8382, "score": 0.9996041655540466, "start": 8367, "tag": "NAME", "value": "Steve Publisher" }, { "context": "t(1, 'hours').format()\n user: {\n id: '210'\n name: 'Richard Lafosse'\n }\n ch", "end": 8618, "score": 0.9976571202278137, "start": 8615, "tag": "USERNAME", "value": "210" }, { "context": "()\n user: {\n id: '210'\n name: 'Richard Lafosse'\n }\n channel: {\n id: '2'\n ", "end": 8650, "score": 0.9998343586921692, "start": 8635, "tag": "NAME", "value": "Richard Lafosse" } ]
src/test/helpers/fixtures.coffee
joeyAghion/positron
76
User = require '../../client/models/user' { ObjectId } = require 'mongojs' moment = require 'moment' timeCount = 0 module.exports = -> timeCount++ fixtures = {} fixtures.articles = id: '54276766fd4f50996aeca2b8' author_id: ObjectId('4d8cd73191a5c50ce210002a') layout: 'standard' thumbnail_title: 'Top Ten Booths at miart 2014', thumbnail_teaser: 'Look here! Before the lines start forming...', thumbnail_image: 'http://kitten.com', tier: 1, vertical: {name: 'Culture', id: '55356a9deca560a0137bb4a7'} channel_id: '5aa99c11da4c00d6bc33a816' tags: ['Fair Coverage', 'Magazine'] tracking_tags: ['Newsfeed', 'Video'] title: 'Top Ten Booths', lead_paragraph: '<p>Just before the lines start forming...</p>', description: 'Just before the lines start forming, we predict where they will go.', published: true, published_at: moment().add(timeCount, 'seconds').format(), updated_at: moment().add(timeCount, 'seconds').format(), sections: [ { type: 'slideshow', items: [ { type: 'artwork', id: '54276766fd4f50996aeca2b8' } { type: 'image', url: '', caption: '' } { type: 'video', url: '' } ] } { type: 'image_collection', images: [ type: 'image' url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg' caption: 'This is a terrible caption' ] } { type: 'text', body: '<p><h1>10. Lisson Gallery</h1></p><p>Mia Bergeron merges the <em>personal</em> and <em>universal</em>...', } { type: 'image_collection', layout: 'overflow_fillwidth' images: [ { type: 'artwork' title: 'The Four Hedgehogs' id: '5321b73dc9dc2458c4000196' image: 'https://artsy.net/artwork.jpg' partner: name: 'Guggenheim' date: '1956' artists: [ { name: 'Van Gogh' }, { name: 'Van Dogh' } ] } { type: 'artwork' title: 'The Four Hedgehogs 2' id: '5321b71c275b24bcaa0001a5' image: 'https://artsy.net/artwork2.jpg' partner: name: 'Guggenheim' date: '1956' artists: [ { name: 'Van Gogh' }] } ] } { type: 'text', body: '<p>Check out this video art:</p>', } { type: 'video', url: 'http://youtu.be/yYjLrJRuMnY' } { type: 'image_set' title: 'The Best Artworks' layout: 'mini' images: [ { type: 'artwork' title: 'The Four Hedgehogs 2' id: '5321b71c275b24bcaa0001a5' image: 'https://artsy.net/artwork2.jpg' partner: name: 'Guggenheim' date: '1956' artists: [ { name: 'Van Gogh' }] } { type: 'image', url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg' caption: 'This is a terrible caption' } ] } ] primary_featured_artist_ids: ['5086df098523e60002000012'] featured_artist_ids: ['5086df098523e60002000012'] featured_artwork_ids: ['5321b71c275b24bcaa0001a5'] gravity_id: '502a6debe8b6470002000004' featured: false indexable: true contributing_authors: [] email_metadata: image_url: 'http://img.png' headline: 'Foo' author: 'Craig Spaeth' slug: 'artsy-editorial-top-ten-booths-at-miart-2014' super_article: partner_link: 'http://partnerlink.com' partner_logo: 'http://partnerlink.com/logo.jpg' partner_link_title: 'Download The App' partner_logo_link: 'http://itunes' partner_fullscreen_header_logo: 'http://partnerlink.com/blacklogo.jpg' secondary_partner_logo: 'http://secondarypartner.com/logo.png' secondary_logo_text: 'In Partnership With' secondary_logo_link: 'http://secondary' footer_blurb: 'This is a Footer Blurb' related_articles: [ '5530e72f7261696238050000' ] footer_title: 'Footer Title' social_description: 'Social Description Here.' social_title: 'Social Title' social_image: 'http://socialimage.jpg' search_title: 'Search Title' search_description: 'Search Description Here.' fixtures.users = id: '4d8cd73191a5c50ce200002a' name: 'Craig Spaeth' type: 'Admin' profile_icon_url: 'https://d32dm0rphc51dk.cloudfront.net/CJOHhrln8lwVAubiMIIYYA/square140.png' access_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsInBhcnRuZXJfaWRzIjpbXX0.-A-T4cwj1PFzuMhiHn9FYk8IBA0lIukzXKUNa43jjlQ' current_channel: name: 'Editorial' type: 'editorial' id: '4d8cd73191a5c50ce200002b' channel_ids: ['4d8cd73191a5c50ce200002b'] partner_ids: [] fixtures.sections = id: '55356a9deca560a0137aa4b7' title: 'Vennice Biennalez' description: 'The coolest biennale' slug: 'vennice-biennale' partner_logo_url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg' thumbnail_url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg' featured_article_ids: [ '5522d03ae8e369060053d953' ] fixtures.curations = id: '55356a9deca560a0137aa4b7' name: 'Featured Articles' fixtures.channels = id: '5086df098523e60002000018' name: 'Editorial' user_ids: [ '5522d03ae8e369060053d953', "4d8cd73191a5c50ce200002a" ] type: 'editorial' tagline: 'A bunch of cool stuff at Artsy' image_url: 'artsy.net/image.jpg' slug: 'editorial' pinned_articles: [ { id: '5086df098523e60002000015' index: 0 }, { id: '5086df098523e60002000011' index: 1 } ] fixtures.tags = id: '55356a9deca560a0137aa4b7' name: 'Show Reviews' public: true fixtures.verticals = id: '55356a9deca560a0137bb4a7' name: 'Culture' fixtures.authors = id: '55356a9deca560a0137bb4a7' name: 'Halley Johnson' bio: 'Writer based in NYC' twitter_handle: 'kanaabe' image_url: 'https://artsy-media.net/halley.jpg' fixtures.display = canvas: layout: 'slideshow' headline: 'Sample copy sed posuere consectetur est at lobortis. Nullam id dolor ultricies vehicula.' body: '' link: text: 'Link Example' url: 'http://artsy.net' assets: [ { url: 'https://artsy-media-uploads.s3.amazonaws.com/YqTtwB7AWqKD95NGItwjJg%2FRachel_Rossin_portrait_2.jpg' caption: 'Nullam id dolor ultricies vehicula.' }, { url: 'https://d32dm0rphc51dk.cloudfront.net/0aRUvnVgQKbQk5dj8xcCAg/larger.jpg'} ] logo: 'http://files.artsy.net/images/artsy-logo-wide-black.png' disclaimer: 'Donec id elit non mi porta gravida at eget metus. Cras justo odio, dapibus ac facilisis in, egestas eget quam.' name: 'Sample Campaign' panel: headline: 'Euismod Inceptos Quam' body: '<p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. <a href="http://artsy.net/articles">Example Link</a></p>' assets: [ { url: 'https://artsy-media-uploads.s3.amazonaws.com/YqTtwB7AWqKD95NGItwjJg%2FRachel_Rossin_portrait_2.jpg' } ] logo: 'https://artsy-vanity-files-production.s3.amazonaws.com/images/artsy_logo_square_white_transparent.png', link: { text: '', url: 'http://artsy.net' } sov: .25 start_date: moment(new Date()).subtract(1, 'days').toDate() end_date: moment(new Date()).add(1, 'days').toDate() fixtures.sessions = [ { _id: 123456 timestamp: moment(new Date()).subtract(3, 'minutes').format() user: { id: '123' name: 'John Doe' } article: '123456' channel: { id: '1' name: 'Artsy Editorial' type: 'editorial' } }, { _id: 246810 timestamp: moment(new Date()).subtract(5, 'minutes').format() user: { id: '124' name: 'Ellen Poe' } article: '246810' channel: { id: '2' name: 'Other Editors' type: 'editorial' } }, { _id: 246814 timestamp: moment(new Date()).subtract(4, 'minutes').format() user: { id: '126' name: 'Steve Publisher' } channel: { id: '1' name: 'Artsy Editorial' type: 'editorial' } }, { _id: 246920 timestamp: moment(new Date()).subtract(1, 'hours').format() user: { id: '210' name: 'Richard Lafosse' } channel: { id: '2' name: 'Other Editors' type: 'editorial' } } ] fixtures.locals = asset: -> user: new User fixtures.users sd: PATH: '/' URL: '/' USER: roles: '' moment: require 'moment' sharify: script: -> '<script>var sharify = {}</script>' crop: (url) -> url resize: (url) -> url fill: (url) -> url fixtures
66761
User = require '../../client/models/user' { ObjectId } = require 'mongojs' moment = require 'moment' timeCount = 0 module.exports = -> timeCount++ fixtures = {} fixtures.articles = id: '54276766fd4f50996aeca2b8' author_id: ObjectId('4<PASSWORD>') layout: 'standard' thumbnail_title: 'Top Ten Booths at miart 2014', thumbnail_teaser: 'Look here! Before the lines start forming...', thumbnail_image: 'http://kitten.com', tier: 1, vertical: {name: 'Culture', id: '55356a9deca560a0137bb4a7'} channel_id: '5aa99c11da4c00d6bc33a816' tags: ['Fair Coverage', 'Magazine'] tracking_tags: ['Newsfeed', 'Video'] title: 'Top Ten Booths', lead_paragraph: '<p>Just before the lines start forming...</p>', description: 'Just before the lines start forming, we predict where they will go.', published: true, published_at: moment().add(timeCount, 'seconds').format(), updated_at: moment().add(timeCount, 'seconds').format(), sections: [ { type: 'slideshow', items: [ { type: 'artwork', id: '54276766fd4f50996aeca2b8' } { type: 'image', url: '', caption: '' } { type: 'video', url: '' } ] } { type: 'image_collection', images: [ type: 'image' url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg' caption: 'This is a terrible caption' ] } { type: 'text', body: '<p><h1>10. Lisson Gallery</h1></p><p><NAME> merges the <em>personal</em> and <em>universal</em>...', } { type: 'image_collection', layout: 'overflow_fillwidth' images: [ { type: 'artwork' title: 'The Four Hedgehogs' id: '5321b73dc9dc2458c4000196' image: 'https://artsy.net/artwork.jpg' partner: name: '<NAME>' date: '1956' artists: [ { name: '<NAME>' }, { name: '<NAME>' } ] } { type: 'artwork' title: 'The Four Hedgehogs 2' id: '5321b71c275b24bcaa0001a5' image: 'https://artsy.net/artwork2.jpg' partner: name: '<NAME>' date: '1956' artists: [ { name: '<NAME>' }] } ] } { type: 'text', body: '<p>Check out this video art:</p>', } { type: 'video', url: 'http://youtu.be/yYjLrJRuMnY' } { type: 'image_set' title: 'The Best Artworks' layout: 'mini' images: [ { type: 'artwork' title: 'The Four Hedgehogs 2' id: '5321b71c275b24bcaa0001a5' image: 'https://artsy.net/artwork2.jpg' partner: name: '<NAME>' date: '1956' artists: [ { name: '<NAME>' }] } { type: 'image', url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg' caption: 'This is a terrible caption' } ] } ] primary_featured_artist_ids: ['5086df098523e60002000012'] featured_artist_ids: ['5086df098523e60002000012'] featured_artwork_ids: ['5321b71c275b24bcaa0001a5'] gravity_id: '502a6debe8b6470002000004' featured: false indexable: true contributing_authors: [] email_metadata: image_url: 'http://img.png' headline: 'Foo' author: '<NAME>' slug: 'artsy-editorial-top-ten-booths-at-miart-2014' super_article: partner_link: 'http://partnerlink.com' partner_logo: 'http://partnerlink.com/logo.jpg' partner_link_title: 'Download The App' partner_logo_link: 'http://itunes' partner_fullscreen_header_logo: 'http://partnerlink.com/blacklogo.jpg' secondary_partner_logo: 'http://secondarypartner.com/logo.png' secondary_logo_text: 'In Partnership With' secondary_logo_link: 'http://secondary' footer_blurb: 'This is a Footer Blurb' related_articles: [ '5530e72f7261696238050000' ] footer_title: 'Footer Title' social_description: 'Social Description Here.' social_title: 'Social Title' social_image: 'http://socialimage.jpg' search_title: 'Search Title' search_description: 'Search Description Here.' fixtures.users = id: '<KEY>' name: '<NAME>' type: 'Admin' profile_icon_url: 'https://d32dm0rphc51dk.cloudfront.net/CJOHhrln8lwVAubiMIIYYA/square140.png' access_token: '<KEY>' current_channel: name: 'Editorial' type: 'editorial' id: '4d8cd73191a5c50ce200002b' channel_ids: ['4d8cd73191a5c50ce200002b'] partner_ids: [] fixtures.sections = id: '55356a9deca560a0137aa4b7' title: 'Vennice Biennalez' description: 'The coolest biennale' slug: 'vennice-biennale' partner_logo_url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg' thumbnail_url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg' featured_article_ids: [ '5522d03ae8e369060053d953' ] fixtures.curations = id: '55356a9deca560a0137aa4b7' name: 'Featured Articles' fixtures.channels = id: '5086df098523e60002000018' name: 'Editorial' user_ids: [ '5522d03ae8e369060053d953', "4d8cd73191a5c50ce200002a" ] type: 'editorial' tagline: 'A bunch of cool stuff at Artsy' image_url: 'artsy.net/image.jpg' slug: 'editorial' pinned_articles: [ { id: '5086df098523e60002000015' index: 0 }, { id: '5086df098523e60002000011' index: 1 } ] fixtures.tags = id: '55356a9deca560a0137aa4b7' name: 'Show Reviews' public: true fixtures.verticals = id: '55356a9deca560a0137bb4a7' name: 'Culture' fixtures.authors = id: '<PASSWORD>' name: '<NAME>' bio: 'Writer based in NYC' twitter_handle: 'kanaabe' image_url: 'https://artsy-media.net/halley.jpg' fixtures.display = canvas: layout: 'slideshow' headline: 'Sample copy sed posuere consectetur est at lobortis. Nullam id dolor ultricies vehicula.' body: '' link: text: 'Link Example' url: 'http://artsy.net' assets: [ { url: 'https://artsy-media-uploads.s3.amazonaws.com/YqTtwB7AWqKD95NGItwjJg%2FRachel_Rossin_portrait_2.jpg' caption: 'Nullam id dolor ultricies vehicula.' }, { url: 'https://d32dm0rphc51dk.cloudfront.net/0aRUvnVgQKbQk5dj8xcCAg/larger.jpg'} ] logo: 'http://files.artsy.net/images/artsy-logo-wide-black.png' disclaimer: 'Donec id elit non mi porta gravida at eget metus. Cras justo odio, dapibus ac facilisis in, egestas eget quam.' name: 'Sample Campaign' panel: headline: 'Euismod Inceptos Quam' body: '<p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. <a href="http://artsy.net/articles">Example Link</a></p>' assets: [ { url: 'https://artsy-media-uploads.s3.amazonaws.com/YqTtwB7AWqKD95NGItwjJg%2FRachel_Rossin_portrait_2.jpg' } ] logo: 'https://artsy-vanity-files-production.s3.amazonaws.com/images/artsy_logo_square_white_transparent.png', link: { text: '', url: 'http://artsy.net' } sov: .25 start_date: moment(new Date()).subtract(1, 'days').toDate() end_date: moment(new Date()).add(1, 'days').toDate() fixtures.sessions = [ { _id: 123456 timestamp: moment(new Date()).subtract(3, 'minutes').format() user: { id: '123' name: '<NAME>' } article: '123456' channel: { id: '1' name: 'Artsy Editorial' type: 'editorial' } }, { _id: 246810 timestamp: moment(new Date()).subtract(5, 'minutes').format() user: { id: '124' name: '<NAME>' } article: '246810' channel: { id: '2' name: 'Other Editors' type: 'editorial' } }, { _id: 246814 timestamp: moment(new Date()).subtract(4, 'minutes').format() user: { id: '126' name: '<NAME>' } channel: { id: '1' name: 'Artsy Editorial' type: 'editorial' } }, { _id: 246920 timestamp: moment(new Date()).subtract(1, 'hours').format() user: { id: '210' name: '<NAME>' } channel: { id: '2' name: 'Other Editors' type: 'editorial' } } ] fixtures.locals = asset: -> user: new User fixtures.users sd: PATH: '/' URL: '/' USER: roles: '' moment: require 'moment' sharify: script: -> '<script>var sharify = {}</script>' crop: (url) -> url resize: (url) -> url fill: (url) -> url fixtures
true
User = require '../../client/models/user' { ObjectId } = require 'mongojs' moment = require 'moment' timeCount = 0 module.exports = -> timeCount++ fixtures = {} fixtures.articles = id: '54276766fd4f50996aeca2b8' author_id: ObjectId('4PI:PASSWORD:<PASSWORD>END_PI') layout: 'standard' thumbnail_title: 'Top Ten Booths at miart 2014', thumbnail_teaser: 'Look here! Before the lines start forming...', thumbnail_image: 'http://kitten.com', tier: 1, vertical: {name: 'Culture', id: '55356a9deca560a0137bb4a7'} channel_id: '5aa99c11da4c00d6bc33a816' tags: ['Fair Coverage', 'Magazine'] tracking_tags: ['Newsfeed', 'Video'] title: 'Top Ten Booths', lead_paragraph: '<p>Just before the lines start forming...</p>', description: 'Just before the lines start forming, we predict where they will go.', published: true, published_at: moment().add(timeCount, 'seconds').format(), updated_at: moment().add(timeCount, 'seconds').format(), sections: [ { type: 'slideshow', items: [ { type: 'artwork', id: '54276766fd4f50996aeca2b8' } { type: 'image', url: '', caption: '' } { type: 'video', url: '' } ] } { type: 'image_collection', images: [ type: 'image' url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg' caption: 'This is a terrible caption' ] } { type: 'text', body: '<p><h1>10. Lisson Gallery</h1></p><p>PI:NAME:<NAME>END_PI merges the <em>personal</em> and <em>universal</em>...', } { type: 'image_collection', layout: 'overflow_fillwidth' images: [ { type: 'artwork' title: 'The Four Hedgehogs' id: '5321b73dc9dc2458c4000196' image: 'https://artsy.net/artwork.jpg' partner: name: 'PI:NAME:<NAME>END_PI' date: '1956' artists: [ { name: 'PI:NAME:<NAME>END_PI' }, { name: 'PI:NAME:<NAME>END_PI' } ] } { type: 'artwork' title: 'The Four Hedgehogs 2' id: '5321b71c275b24bcaa0001a5' image: 'https://artsy.net/artwork2.jpg' partner: name: 'PI:NAME:<NAME>END_PI' date: '1956' artists: [ { name: 'PI:NAME:<NAME>END_PI' }] } ] } { type: 'text', body: '<p>Check out this video art:</p>', } { type: 'video', url: 'http://youtu.be/yYjLrJRuMnY' } { type: 'image_set' title: 'The Best Artworks' layout: 'mini' images: [ { type: 'artwork' title: 'The Four Hedgehogs 2' id: '5321b71c275b24bcaa0001a5' image: 'https://artsy.net/artwork2.jpg' partner: name: 'PI:NAME:<NAME>END_PI' date: '1956' artists: [ { name: 'PI:NAME:<NAME>END_PI' }] } { type: 'image', url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg' caption: 'This is a terrible caption' } ] } ] primary_featured_artist_ids: ['5086df098523e60002000012'] featured_artist_ids: ['5086df098523e60002000012'] featured_artwork_ids: ['5321b71c275b24bcaa0001a5'] gravity_id: '502a6debe8b6470002000004' featured: false indexable: true contributing_authors: [] email_metadata: image_url: 'http://img.png' headline: 'Foo' author: 'PI:NAME:<NAME>END_PI' slug: 'artsy-editorial-top-ten-booths-at-miart-2014' super_article: partner_link: 'http://partnerlink.com' partner_logo: 'http://partnerlink.com/logo.jpg' partner_link_title: 'Download The App' partner_logo_link: 'http://itunes' partner_fullscreen_header_logo: 'http://partnerlink.com/blacklogo.jpg' secondary_partner_logo: 'http://secondarypartner.com/logo.png' secondary_logo_text: 'In Partnership With' secondary_logo_link: 'http://secondary' footer_blurb: 'This is a Footer Blurb' related_articles: [ '5530e72f7261696238050000' ] footer_title: 'Footer Title' social_description: 'Social Description Here.' social_title: 'Social Title' social_image: 'http://socialimage.jpg' search_title: 'Search Title' search_description: 'Search Description Here.' fixtures.users = id: 'PI:KEY:<KEY>END_PI' name: 'PI:NAME:<NAME>END_PI' type: 'Admin' profile_icon_url: 'https://d32dm0rphc51dk.cloudfront.net/CJOHhrln8lwVAubiMIIYYA/square140.png' access_token: 'PI:KEY:<KEY>END_PI' current_channel: name: 'Editorial' type: 'editorial' id: '4d8cd73191a5c50ce200002b' channel_ids: ['4d8cd73191a5c50ce200002b'] partner_ids: [] fixtures.sections = id: '55356a9deca560a0137aa4b7' title: 'Vennice Biennalez' description: 'The coolest biennale' slug: 'vennice-biennale' partner_logo_url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg' thumbnail_url: 'http://gemini.herokuapp.com/123/miaart-banner.jpg' featured_article_ids: [ '5522d03ae8e369060053d953' ] fixtures.curations = id: '55356a9deca560a0137aa4b7' name: 'Featured Articles' fixtures.channels = id: '5086df098523e60002000018' name: 'Editorial' user_ids: [ '5522d03ae8e369060053d953', "4d8cd73191a5c50ce200002a" ] type: 'editorial' tagline: 'A bunch of cool stuff at Artsy' image_url: 'artsy.net/image.jpg' slug: 'editorial' pinned_articles: [ { id: '5086df098523e60002000015' index: 0 }, { id: '5086df098523e60002000011' index: 1 } ] fixtures.tags = id: '55356a9deca560a0137aa4b7' name: 'Show Reviews' public: true fixtures.verticals = id: '55356a9deca560a0137bb4a7' name: 'Culture' fixtures.authors = id: 'PI:PASSWORD:<PASSWORD>END_PI' name: 'PI:NAME:<NAME>END_PI' bio: 'Writer based in NYC' twitter_handle: 'kanaabe' image_url: 'https://artsy-media.net/halley.jpg' fixtures.display = canvas: layout: 'slideshow' headline: 'Sample copy sed posuere consectetur est at lobortis. Nullam id dolor ultricies vehicula.' body: '' link: text: 'Link Example' url: 'http://artsy.net' assets: [ { url: 'https://artsy-media-uploads.s3.amazonaws.com/YqTtwB7AWqKD95NGItwjJg%2FRachel_Rossin_portrait_2.jpg' caption: 'Nullam id dolor ultricies vehicula.' }, { url: 'https://d32dm0rphc51dk.cloudfront.net/0aRUvnVgQKbQk5dj8xcCAg/larger.jpg'} ] logo: 'http://files.artsy.net/images/artsy-logo-wide-black.png' disclaimer: 'Donec id elit non mi porta gravida at eget metus. Cras justo odio, dapibus ac facilisis in, egestas eget quam.' name: 'Sample Campaign' panel: headline: 'Euismod Inceptos Quam' body: '<p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. <a href="http://artsy.net/articles">Example Link</a></p>' assets: [ { url: 'https://artsy-media-uploads.s3.amazonaws.com/YqTtwB7AWqKD95NGItwjJg%2FRachel_Rossin_portrait_2.jpg' } ] logo: 'https://artsy-vanity-files-production.s3.amazonaws.com/images/artsy_logo_square_white_transparent.png', link: { text: '', url: 'http://artsy.net' } sov: .25 start_date: moment(new Date()).subtract(1, 'days').toDate() end_date: moment(new Date()).add(1, 'days').toDate() fixtures.sessions = [ { _id: 123456 timestamp: moment(new Date()).subtract(3, 'minutes').format() user: { id: '123' name: 'PI:NAME:<NAME>END_PI' } article: '123456' channel: { id: '1' name: 'Artsy Editorial' type: 'editorial' } }, { _id: 246810 timestamp: moment(new Date()).subtract(5, 'minutes').format() user: { id: '124' name: 'PI:NAME:<NAME>END_PI' } article: '246810' channel: { id: '2' name: 'Other Editors' type: 'editorial' } }, { _id: 246814 timestamp: moment(new Date()).subtract(4, 'minutes').format() user: { id: '126' name: 'PI:NAME:<NAME>END_PI' } channel: { id: '1' name: 'Artsy Editorial' type: 'editorial' } }, { _id: 246920 timestamp: moment(new Date()).subtract(1, 'hours').format() user: { id: '210' name: 'PI:NAME:<NAME>END_PI' } channel: { id: '2' name: 'Other Editors' type: 'editorial' } } ] fixtures.locals = asset: -> user: new User fixtures.users sd: PATH: '/' URL: '/' USER: roles: '' moment: require 'moment' sharify: script: -> '<script>var sharify = {}</script>' crop: (url) -> url resize: (url) -> url fill: (url) -> url fixtures
[ { "context": "tterBibTeX.formatter.format(item)\n citekey = \"zotero-#{if item.libraryID in [undefined, null] then 'nul", "end": 4620, "score": 0.7644116282463074, "start": 4614, "tag": "KEY", "value": "otero-" }, { "context": "y, value of entry\n switch\n when key in ['$loki', 'meta'] t", "end": 10017, "score": 0.9984023571014404, "start": 10010, "tag": "KEY", "value": "['$loki" }, { "context": "entry\n switch\n when key in ['$loki', 'meta'] then # i", "end": 10025, "score": 0.9458844661712646, "start": 10021, "tag": "KEY", "value": "meta" } ]
chrome/content/zotero-better-bibtex/keymanager.coffee
edwinksl/zotero-better-bibtex
0
Components.utils.import('resource://gre/modules/Services.jsm') Zotero.BetterBibTeX.keymanager = new class constructor: -> @db = Zotero.BetterBibTeX.DB @log = Zotero.BetterBibTeX.log @resetJournalAbbrevs() ### three-letter month abbreviations. I assume these are the same ones that the docs say are defined in some appendix of the LaTeX book. (I don't have the LaTeX book.) ### months: [ 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec' ] embeddedKeyRE: /\bbibtex: *([^\s\r\n]+)/ andersJohanssonKeyRE: /\bbiblatexcitekey\[([^\]]+)\]/ findKeysSQL: "select i.itemID as itemID, i.libraryID as libraryID, idv.value as extra from items i join itemData id on i.itemID = id.itemID join itemDataValues idv on idv.valueID = id.valueID join fields f on id.fieldID = f.fieldID where f.fieldName = 'extra' and not i.itemID in (select itemID from deletedItems) and (idv.value like '%bibtex:%' or idv.value like '%biblatexcitekey[%' or idv.value like '%biblatexcitekey{%')" integer: (v) -> return v if typeof v == 'number' || v == null _v = parseInt(v) throw new Error("#{typeof v} '#{v}' is not an integer-string") if isNaN(_v) return _v cache: -> return (@clone(key) for key in @db.keys.find()) prime: -> sql = "select i.itemID as itemID from items i where itemTypeID not in (1, 14) and not i.itemID in (select itemID from deletedItems)" assigned = (key.itemID for key in @db.keys.find()) sql += " and not i.itemID in #{Zotero.BetterBibTeX.DB.SQLite.Set(assigned)}" if assigned.length > 0 items = Zotero.DB.columnQuery(sql) if items.length > 100 return unless Services.prompt.confirm(null, 'Filling citation key cache', """ You have requested a scan over all citation keys, but have #{items.length} references for which the citation key must still be calculated. This might take a long time, and Zotero will freeze while it's calculating them. If you click 'Cancel' now, the scan will only occur over the citation keys you happen to have in place. Do you wish to proceed calculating all citation keys now? """) for itemID in items @get({itemID}, 'on-export') return reset: -> @resetJournalAbbrevs() @db.keys.removeWhere((obj) -> true) # causes cache drop @scan() resetJournalAbbrevs: -> @journalAbbrevs = { default: { "container-title": { }, "collection-title": { }, "institution-entire": { }, "institution-part": { }, "nickname": { }, "number": { }, "title": { }, "place": { }, "hereinafter": { }, "classic": { }, "container-phrase": { }, "title-phrase": { } } } clearDynamic: -> @db.keys.removeWhere((obj) -> obj.citekeyFormat) journalAbbrev: (item) -> return item.journalAbbreviation if item.journalAbbreviation return null unless item.itemType in ['journalArticle', 'bill', 'case', 'statute'] key = item.publicationTitle || item.reporter || item.code return unless key return unless Zotero.BetterBibTeX.pref.get('autoAbbrev') style = Zotero.BetterBibTeX.pref.get('autoAbbrevStyle') || (style for style in Zotero.Styles.getVisible() when style.usesAbbreviation)[0].styleID @journalAbbrevs['default']?['container-title']?[key] || Zotero.Cite.getAbbreviation(style, @journalAbbrevs, 'default', 'container-title', key) return @journalAbbrevs['default']?['container-title']?[key] || key extract: (item, insitu) -> switch when item.getField throw("#{insitu}: cannot extract in-situ for real items") if insitu item = {itemID: item.id, extra: item.getField('extra')} when !insitu item = {itemID: item.itemID, extra: item.extra.slice(0)} return item unless item.extra m = @embeddedKeyRE.exec(item.extra) or @andersJohanssonKeyRE.exec(item.extra) return item unless m item.extra = item.extra.replace(m[0], '').trim() item.__citekey__ = m[1].trim() delete item.__citekey__ if item.__citekey__ == '' return item alphabet: (String.fromCharCode('a'.charCodeAt() + n) for n in [0...26]) postfix: (n) -> return '' if n == 0 n -= 1 postfix = '' while n >= 0 postfix = @alphabet[n % 26] + postfix n = parseInt(n / 26) - 1 return postfix assign: (item, pin) -> {citekey, postfix: postfixStyle} = Zotero.BetterBibTeX.formatter.format(item) citekey = "zotero-#{if item.libraryID in [undefined, null] then 'null' else item.libraryID}-#{item.itemID}" if citekey in [undefined, null, ''] return null unless citekey libraryID = @integer(if item.libraryID == undefined then Zotero.DB.valueQuery('select libraryID from items where itemID = ?', [item.itemID]) else item.libraryID) itemID = @integer(item.itemID) in_use = (key.citekey for key in @db.keys.where((o) -> o.libraryID == libraryID && o.itemID != itemID && o.citekey.indexOf(citekey) == 0)) postfix = { n: 0, c: '' } while (citekey + postfix.c) in in_use postfix.n++ if postfixStyle == '0' postfix.c = "-#{postfix.n}" else postfix.c = @postfix(postfix.n) res = @set(item, citekey + postfix.c, pin) return res selected: (action) -> throw new Error("Unexpected action #{action}") unless action in ['set', 'reset'] zoteroPane = Zotero.getActiveZoteroPane() items = (item for item in zoteroPane.getSelectedItems() when !item.isAttachment() && !item.isNote()) items.sort((a, b) -> a.dateAdded.localeCompare(b.dateAdded)) warn = Zotero.BetterBibTeX.pref.get('warnBulkModify') if warn > 0 && items.length > warn ids = (parseInt(item.itemID) for item in items) if action == 'set' affected = items.length else affected = @db.keys.where((key) -> key.itemID in ids && !key.citekeyFormat).length if affected > warn params = { treshold: warn, response: null } window.openDialog('chrome://zotero-better-bibtex/content/bulk-clear-confirm.xul', '', 'chrome,dialog,centerscreen,modal', params) switch params.response when 'ok' then when 'whatever' then Zotero.BetterBibTeX.pref.set('warnBulkModify', 0) else return for item in items @remove(item, action == 'set') if action == 'set' for item in items @assign(item, true) save: (item, citekey) -> ### only save if no change ### item = Zotero.Items.get(item.itemID) unless item.getField extra = @extract(item) if (extra.__citekey__ == citekey) || (!citekey && !extra.__citekey__) return extra = extra.extra extra += " \nbibtex: #{citekey}" if citekey extra = extra.trim() item.setField('extra', extra) item.save({skipDateModifiedUpdate: true}) set: (item, citekey, pin) -> throw new Error('Cannot set empty cite key') if !citekey || citekey.trim() == '' ### no keys for notes and attachments ### return unless @eligible(item) item = Zotero.Items.get(item.itemID) unless item.getField itemID = @integer(item.itemID) libraryID = @integer(item.libraryID) citekeyFormat = if pin then null else Zotero.BetterBibTeX.citekeyFormat key = @db.keys.findOne({itemID}) return @verify(key) if key && key.citekey == citekey && key.citekeyFormat == citekeyFormat if key key.citekey = citekey key.citekeyFormat = citekeyFormat key.libraryID = libraryID @db.keys.update(key) else key = {itemID, libraryID, citekey, citekeyFormat} @db.keys.insert(key) @save(item, citekey) if pin Zotero.BetterBibTeX.auto.markIDs([itemID], 'citekey changed') return @verify(key) scan: (ids, reason) -> if reason in ['delete', 'trash'] ids = (@integer(id) for id in ids || []) @db.keys.removeWhere((o) -> o.itemID in ids) return switch when !ids items = Zotero.DB.query(@findKeysSQL) when ids.length == 0 items = [] when ids.length == 1 items = Zotero.Items.get(ids[0]) items = if items then [items] else [] else items = Zotero.Items.get(ids) || [] pinned = {} for item in items itemID = @integer(item.itemID) citekey = @extract(item).__citekey__ cached = @db.keys.findOne({itemID}) continue unless citekey && citekey != '' if !cached || cached.citekey != citekey || cached.citekeyFormat != null libraryID = @integer(item.libraryID) if cached cached.citekey = citekey cached.citekeyFormat = null cached.libraryID = libraryID @db.keys.update(cached) else cached = {itemID, libraryID, citekey: citekey, citekeyFormat: null} @db.keys.insert(cached) pinned['' + item.itemID] = cached.citekey for itemID in ids || [] continue if pinned['' + itemID] @remove({itemID}, true) @get({itemID}, 'on-change') remove: (item, soft) -> @db.keys.removeWhere({itemID: @integer(item.itemID)}) @save(item) unless soft # only use soft remove if you know a hard set follows! eligible: (item) -> type = item.itemType if !type item = Zotero.Items.get(item.itemID) unless item.itemTypeID type = switch item.itemTypeID when 1 then 'note' when 14 then 'attachment' else 'reference' return false if type in ['note', 'attachment'] #item = Zotero.Items.get(item.itemID) unless item.getField #return false unless item #return !item.deleted return true verify: (entry) -> return entry unless Zotero.BetterBibTeX.pref.get('debug') || Zotero.BetterBibTeX.testing verify = {citekey: true, citekeyFormat: null, itemID: true, libraryID: null} for own key, value of entry switch when key in ['$loki', 'meta'] then # ignore when verify[key] == undefined then throw new Error("Unexpected field #{key} in #{typeof entry} #{JSON.stringify(entry)}") when verify[key] && typeof value == 'number' then delete verify[key] when verify[key] && typeof value == 'string' && value.trim() != '' then delete verify[key] when verify[key] && !value then throw new Error("field #{key} of #{typeof entry} #{JSON.stringify(entry)} may not be empty") else delete verify[key] verify = Object.keys(verify) return entry if verify.length == 0 throw new Error("missing fields #{verify} in #{typeof entry} #{JSON.stringify(entry)}") clone: (key) -> return key if key in [undefined, null] clone = JSON.parse(JSON.stringify(key)) delete clone.meta delete clone['$loki'] @verify(clone) return clone get: (item, pinmode) -> if (typeof item.itemID == 'undefined') && (typeof item.key != 'undefined') && (typeof item.libraryID != 'undefined') item = Zotero.Items.getByLibraryAndKey(item.libraryID, item.key) ### no keys for notes and attachments ### return unless @eligible(item) ### pinmode can be: * on-change: generate and pin if pinCitekeys is on-change, 'null' behavior if not * on-export: generate and pin if pinCitekeys is on-export, 'null' behavior if not * null: fetch -> generate -> return ### pin = (pinmode == Zotero.BetterBibTeX.pref.get('pinCitekeys')) cached = @db.keys.findOne({itemID: @integer(item.itemID)}) ### store new cache item if we have a miss or if a re-pin is requested ### cached = @assign(item, pin) if !cached || (pin && cached.citekeyFormat) return @clone(cached) resolve: (citekeys, options = {}) -> options.libraryID = null if options.libraryID == undefined libraryID = @integer(options.libraryID) citekeys = [citekeys] unless Array.isArray(citekeys) resolved = {} for citekey in citekeys resolved[citekey] = @db.keys.findObject({citekey, libraryID}) return resolved alternates: (item) -> return Zotero.BetterBibTeX.formatter.alternates(item)
163430
Components.utils.import('resource://gre/modules/Services.jsm') Zotero.BetterBibTeX.keymanager = new class constructor: -> @db = Zotero.BetterBibTeX.DB @log = Zotero.BetterBibTeX.log @resetJournalAbbrevs() ### three-letter month abbreviations. I assume these are the same ones that the docs say are defined in some appendix of the LaTeX book. (I don't have the LaTeX book.) ### months: [ 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec' ] embeddedKeyRE: /\bbibtex: *([^\s\r\n]+)/ andersJohanssonKeyRE: /\bbiblatexcitekey\[([^\]]+)\]/ findKeysSQL: "select i.itemID as itemID, i.libraryID as libraryID, idv.value as extra from items i join itemData id on i.itemID = id.itemID join itemDataValues idv on idv.valueID = id.valueID join fields f on id.fieldID = f.fieldID where f.fieldName = 'extra' and not i.itemID in (select itemID from deletedItems) and (idv.value like '%bibtex:%' or idv.value like '%biblatexcitekey[%' or idv.value like '%biblatexcitekey{%')" integer: (v) -> return v if typeof v == 'number' || v == null _v = parseInt(v) throw new Error("#{typeof v} '#{v}' is not an integer-string") if isNaN(_v) return _v cache: -> return (@clone(key) for key in @db.keys.find()) prime: -> sql = "select i.itemID as itemID from items i where itemTypeID not in (1, 14) and not i.itemID in (select itemID from deletedItems)" assigned = (key.itemID for key in @db.keys.find()) sql += " and not i.itemID in #{Zotero.BetterBibTeX.DB.SQLite.Set(assigned)}" if assigned.length > 0 items = Zotero.DB.columnQuery(sql) if items.length > 100 return unless Services.prompt.confirm(null, 'Filling citation key cache', """ You have requested a scan over all citation keys, but have #{items.length} references for which the citation key must still be calculated. This might take a long time, and Zotero will freeze while it's calculating them. If you click 'Cancel' now, the scan will only occur over the citation keys you happen to have in place. Do you wish to proceed calculating all citation keys now? """) for itemID in items @get({itemID}, 'on-export') return reset: -> @resetJournalAbbrevs() @db.keys.removeWhere((obj) -> true) # causes cache drop @scan() resetJournalAbbrevs: -> @journalAbbrevs = { default: { "container-title": { }, "collection-title": { }, "institution-entire": { }, "institution-part": { }, "nickname": { }, "number": { }, "title": { }, "place": { }, "hereinafter": { }, "classic": { }, "container-phrase": { }, "title-phrase": { } } } clearDynamic: -> @db.keys.removeWhere((obj) -> obj.citekeyFormat) journalAbbrev: (item) -> return item.journalAbbreviation if item.journalAbbreviation return null unless item.itemType in ['journalArticle', 'bill', 'case', 'statute'] key = item.publicationTitle || item.reporter || item.code return unless key return unless Zotero.BetterBibTeX.pref.get('autoAbbrev') style = Zotero.BetterBibTeX.pref.get('autoAbbrevStyle') || (style for style in Zotero.Styles.getVisible() when style.usesAbbreviation)[0].styleID @journalAbbrevs['default']?['container-title']?[key] || Zotero.Cite.getAbbreviation(style, @journalAbbrevs, 'default', 'container-title', key) return @journalAbbrevs['default']?['container-title']?[key] || key extract: (item, insitu) -> switch when item.getField throw("#{insitu}: cannot extract in-situ for real items") if insitu item = {itemID: item.id, extra: item.getField('extra')} when !insitu item = {itemID: item.itemID, extra: item.extra.slice(0)} return item unless item.extra m = @embeddedKeyRE.exec(item.extra) or @andersJohanssonKeyRE.exec(item.extra) return item unless m item.extra = item.extra.replace(m[0], '').trim() item.__citekey__ = m[1].trim() delete item.__citekey__ if item.__citekey__ == '' return item alphabet: (String.fromCharCode('a'.charCodeAt() + n) for n in [0...26]) postfix: (n) -> return '' if n == 0 n -= 1 postfix = '' while n >= 0 postfix = @alphabet[n % 26] + postfix n = parseInt(n / 26) - 1 return postfix assign: (item, pin) -> {citekey, postfix: postfixStyle} = Zotero.BetterBibTeX.formatter.format(item) citekey = "z<KEY>#{if item.libraryID in [undefined, null] then 'null' else item.libraryID}-#{item.itemID}" if citekey in [undefined, null, ''] return null unless citekey libraryID = @integer(if item.libraryID == undefined then Zotero.DB.valueQuery('select libraryID from items where itemID = ?', [item.itemID]) else item.libraryID) itemID = @integer(item.itemID) in_use = (key.citekey for key in @db.keys.where((o) -> o.libraryID == libraryID && o.itemID != itemID && o.citekey.indexOf(citekey) == 0)) postfix = { n: 0, c: '' } while (citekey + postfix.c) in in_use postfix.n++ if postfixStyle == '0' postfix.c = "-#{postfix.n}" else postfix.c = @postfix(postfix.n) res = @set(item, citekey + postfix.c, pin) return res selected: (action) -> throw new Error("Unexpected action #{action}") unless action in ['set', 'reset'] zoteroPane = Zotero.getActiveZoteroPane() items = (item for item in zoteroPane.getSelectedItems() when !item.isAttachment() && !item.isNote()) items.sort((a, b) -> a.dateAdded.localeCompare(b.dateAdded)) warn = Zotero.BetterBibTeX.pref.get('warnBulkModify') if warn > 0 && items.length > warn ids = (parseInt(item.itemID) for item in items) if action == 'set' affected = items.length else affected = @db.keys.where((key) -> key.itemID in ids && !key.citekeyFormat).length if affected > warn params = { treshold: warn, response: null } window.openDialog('chrome://zotero-better-bibtex/content/bulk-clear-confirm.xul', '', 'chrome,dialog,centerscreen,modal', params) switch params.response when 'ok' then when 'whatever' then Zotero.BetterBibTeX.pref.set('warnBulkModify', 0) else return for item in items @remove(item, action == 'set') if action == 'set' for item in items @assign(item, true) save: (item, citekey) -> ### only save if no change ### item = Zotero.Items.get(item.itemID) unless item.getField extra = @extract(item) if (extra.__citekey__ == citekey) || (!citekey && !extra.__citekey__) return extra = extra.extra extra += " \nbibtex: #{citekey}" if citekey extra = extra.trim() item.setField('extra', extra) item.save({skipDateModifiedUpdate: true}) set: (item, citekey, pin) -> throw new Error('Cannot set empty cite key') if !citekey || citekey.trim() == '' ### no keys for notes and attachments ### return unless @eligible(item) item = Zotero.Items.get(item.itemID) unless item.getField itemID = @integer(item.itemID) libraryID = @integer(item.libraryID) citekeyFormat = if pin then null else Zotero.BetterBibTeX.citekeyFormat key = @db.keys.findOne({itemID}) return @verify(key) if key && key.citekey == citekey && key.citekeyFormat == citekeyFormat if key key.citekey = citekey key.citekeyFormat = citekeyFormat key.libraryID = libraryID @db.keys.update(key) else key = {itemID, libraryID, citekey, citekeyFormat} @db.keys.insert(key) @save(item, citekey) if pin Zotero.BetterBibTeX.auto.markIDs([itemID], 'citekey changed') return @verify(key) scan: (ids, reason) -> if reason in ['delete', 'trash'] ids = (@integer(id) for id in ids || []) @db.keys.removeWhere((o) -> o.itemID in ids) return switch when !ids items = Zotero.DB.query(@findKeysSQL) when ids.length == 0 items = [] when ids.length == 1 items = Zotero.Items.get(ids[0]) items = if items then [items] else [] else items = Zotero.Items.get(ids) || [] pinned = {} for item in items itemID = @integer(item.itemID) citekey = @extract(item).__citekey__ cached = @db.keys.findOne({itemID}) continue unless citekey && citekey != '' if !cached || cached.citekey != citekey || cached.citekeyFormat != null libraryID = @integer(item.libraryID) if cached cached.citekey = citekey cached.citekeyFormat = null cached.libraryID = libraryID @db.keys.update(cached) else cached = {itemID, libraryID, citekey: citekey, citekeyFormat: null} @db.keys.insert(cached) pinned['' + item.itemID] = cached.citekey for itemID in ids || [] continue if pinned['' + itemID] @remove({itemID}, true) @get({itemID}, 'on-change') remove: (item, soft) -> @db.keys.removeWhere({itemID: @integer(item.itemID)}) @save(item) unless soft # only use soft remove if you know a hard set follows! eligible: (item) -> type = item.itemType if !type item = Zotero.Items.get(item.itemID) unless item.itemTypeID type = switch item.itemTypeID when 1 then 'note' when 14 then 'attachment' else 'reference' return false if type in ['note', 'attachment'] #item = Zotero.Items.get(item.itemID) unless item.getField #return false unless item #return !item.deleted return true verify: (entry) -> return entry unless Zotero.BetterBibTeX.pref.get('debug') || Zotero.BetterBibTeX.testing verify = {citekey: true, citekeyFormat: null, itemID: true, libraryID: null} for own key, value of entry switch when key in <KEY>', '<KEY>'] then # ignore when verify[key] == undefined then throw new Error("Unexpected field #{key} in #{typeof entry} #{JSON.stringify(entry)}") when verify[key] && typeof value == 'number' then delete verify[key] when verify[key] && typeof value == 'string' && value.trim() != '' then delete verify[key] when verify[key] && !value then throw new Error("field #{key} of #{typeof entry} #{JSON.stringify(entry)} may not be empty") else delete verify[key] verify = Object.keys(verify) return entry if verify.length == 0 throw new Error("missing fields #{verify} in #{typeof entry} #{JSON.stringify(entry)}") clone: (key) -> return key if key in [undefined, null] clone = JSON.parse(JSON.stringify(key)) delete clone.meta delete clone['$loki'] @verify(clone) return clone get: (item, pinmode) -> if (typeof item.itemID == 'undefined') && (typeof item.key != 'undefined') && (typeof item.libraryID != 'undefined') item = Zotero.Items.getByLibraryAndKey(item.libraryID, item.key) ### no keys for notes and attachments ### return unless @eligible(item) ### pinmode can be: * on-change: generate and pin if pinCitekeys is on-change, 'null' behavior if not * on-export: generate and pin if pinCitekeys is on-export, 'null' behavior if not * null: fetch -> generate -> return ### pin = (pinmode == Zotero.BetterBibTeX.pref.get('pinCitekeys')) cached = @db.keys.findOne({itemID: @integer(item.itemID)}) ### store new cache item if we have a miss or if a re-pin is requested ### cached = @assign(item, pin) if !cached || (pin && cached.citekeyFormat) return @clone(cached) resolve: (citekeys, options = {}) -> options.libraryID = null if options.libraryID == undefined libraryID = @integer(options.libraryID) citekeys = [citekeys] unless Array.isArray(citekeys) resolved = {} for citekey in citekeys resolved[citekey] = @db.keys.findObject({citekey, libraryID}) return resolved alternates: (item) -> return Zotero.BetterBibTeX.formatter.alternates(item)
true
Components.utils.import('resource://gre/modules/Services.jsm') Zotero.BetterBibTeX.keymanager = new class constructor: -> @db = Zotero.BetterBibTeX.DB @log = Zotero.BetterBibTeX.log @resetJournalAbbrevs() ### three-letter month abbreviations. I assume these are the same ones that the docs say are defined in some appendix of the LaTeX book. (I don't have the LaTeX book.) ### months: [ 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec' ] embeddedKeyRE: /\bbibtex: *([^\s\r\n]+)/ andersJohanssonKeyRE: /\bbiblatexcitekey\[([^\]]+)\]/ findKeysSQL: "select i.itemID as itemID, i.libraryID as libraryID, idv.value as extra from items i join itemData id on i.itemID = id.itemID join itemDataValues idv on idv.valueID = id.valueID join fields f on id.fieldID = f.fieldID where f.fieldName = 'extra' and not i.itemID in (select itemID from deletedItems) and (idv.value like '%bibtex:%' or idv.value like '%biblatexcitekey[%' or idv.value like '%biblatexcitekey{%')" integer: (v) -> return v if typeof v == 'number' || v == null _v = parseInt(v) throw new Error("#{typeof v} '#{v}' is not an integer-string") if isNaN(_v) return _v cache: -> return (@clone(key) for key in @db.keys.find()) prime: -> sql = "select i.itemID as itemID from items i where itemTypeID not in (1, 14) and not i.itemID in (select itemID from deletedItems)" assigned = (key.itemID for key in @db.keys.find()) sql += " and not i.itemID in #{Zotero.BetterBibTeX.DB.SQLite.Set(assigned)}" if assigned.length > 0 items = Zotero.DB.columnQuery(sql) if items.length > 100 return unless Services.prompt.confirm(null, 'Filling citation key cache', """ You have requested a scan over all citation keys, but have #{items.length} references for which the citation key must still be calculated. This might take a long time, and Zotero will freeze while it's calculating them. If you click 'Cancel' now, the scan will only occur over the citation keys you happen to have in place. Do you wish to proceed calculating all citation keys now? """) for itemID in items @get({itemID}, 'on-export') return reset: -> @resetJournalAbbrevs() @db.keys.removeWhere((obj) -> true) # causes cache drop @scan() resetJournalAbbrevs: -> @journalAbbrevs = { default: { "container-title": { }, "collection-title": { }, "institution-entire": { }, "institution-part": { }, "nickname": { }, "number": { }, "title": { }, "place": { }, "hereinafter": { }, "classic": { }, "container-phrase": { }, "title-phrase": { } } } clearDynamic: -> @db.keys.removeWhere((obj) -> obj.citekeyFormat) journalAbbrev: (item) -> return item.journalAbbreviation if item.journalAbbreviation return null unless item.itemType in ['journalArticle', 'bill', 'case', 'statute'] key = item.publicationTitle || item.reporter || item.code return unless key return unless Zotero.BetterBibTeX.pref.get('autoAbbrev') style = Zotero.BetterBibTeX.pref.get('autoAbbrevStyle') || (style for style in Zotero.Styles.getVisible() when style.usesAbbreviation)[0].styleID @journalAbbrevs['default']?['container-title']?[key] || Zotero.Cite.getAbbreviation(style, @journalAbbrevs, 'default', 'container-title', key) return @journalAbbrevs['default']?['container-title']?[key] || key extract: (item, insitu) -> switch when item.getField throw("#{insitu}: cannot extract in-situ for real items") if insitu item = {itemID: item.id, extra: item.getField('extra')} when !insitu item = {itemID: item.itemID, extra: item.extra.slice(0)} return item unless item.extra m = @embeddedKeyRE.exec(item.extra) or @andersJohanssonKeyRE.exec(item.extra) return item unless m item.extra = item.extra.replace(m[0], '').trim() item.__citekey__ = m[1].trim() delete item.__citekey__ if item.__citekey__ == '' return item alphabet: (String.fromCharCode('a'.charCodeAt() + n) for n in [0...26]) postfix: (n) -> return '' if n == 0 n -= 1 postfix = '' while n >= 0 postfix = @alphabet[n % 26] + postfix n = parseInt(n / 26) - 1 return postfix assign: (item, pin) -> {citekey, postfix: postfixStyle} = Zotero.BetterBibTeX.formatter.format(item) citekey = "zPI:KEY:<KEY>END_PI#{if item.libraryID in [undefined, null] then 'null' else item.libraryID}-#{item.itemID}" if citekey in [undefined, null, ''] return null unless citekey libraryID = @integer(if item.libraryID == undefined then Zotero.DB.valueQuery('select libraryID from items where itemID = ?', [item.itemID]) else item.libraryID) itemID = @integer(item.itemID) in_use = (key.citekey for key in @db.keys.where((o) -> o.libraryID == libraryID && o.itemID != itemID && o.citekey.indexOf(citekey) == 0)) postfix = { n: 0, c: '' } while (citekey + postfix.c) in in_use postfix.n++ if postfixStyle == '0' postfix.c = "-#{postfix.n}" else postfix.c = @postfix(postfix.n) res = @set(item, citekey + postfix.c, pin) return res selected: (action) -> throw new Error("Unexpected action #{action}") unless action in ['set', 'reset'] zoteroPane = Zotero.getActiveZoteroPane() items = (item for item in zoteroPane.getSelectedItems() when !item.isAttachment() && !item.isNote()) items.sort((a, b) -> a.dateAdded.localeCompare(b.dateAdded)) warn = Zotero.BetterBibTeX.pref.get('warnBulkModify') if warn > 0 && items.length > warn ids = (parseInt(item.itemID) for item in items) if action == 'set' affected = items.length else affected = @db.keys.where((key) -> key.itemID in ids && !key.citekeyFormat).length if affected > warn params = { treshold: warn, response: null } window.openDialog('chrome://zotero-better-bibtex/content/bulk-clear-confirm.xul', '', 'chrome,dialog,centerscreen,modal', params) switch params.response when 'ok' then when 'whatever' then Zotero.BetterBibTeX.pref.set('warnBulkModify', 0) else return for item in items @remove(item, action == 'set') if action == 'set' for item in items @assign(item, true) save: (item, citekey) -> ### only save if no change ### item = Zotero.Items.get(item.itemID) unless item.getField extra = @extract(item) if (extra.__citekey__ == citekey) || (!citekey && !extra.__citekey__) return extra = extra.extra extra += " \nbibtex: #{citekey}" if citekey extra = extra.trim() item.setField('extra', extra) item.save({skipDateModifiedUpdate: true}) set: (item, citekey, pin) -> throw new Error('Cannot set empty cite key') if !citekey || citekey.trim() == '' ### no keys for notes and attachments ### return unless @eligible(item) item = Zotero.Items.get(item.itemID) unless item.getField itemID = @integer(item.itemID) libraryID = @integer(item.libraryID) citekeyFormat = if pin then null else Zotero.BetterBibTeX.citekeyFormat key = @db.keys.findOne({itemID}) return @verify(key) if key && key.citekey == citekey && key.citekeyFormat == citekeyFormat if key key.citekey = citekey key.citekeyFormat = citekeyFormat key.libraryID = libraryID @db.keys.update(key) else key = {itemID, libraryID, citekey, citekeyFormat} @db.keys.insert(key) @save(item, citekey) if pin Zotero.BetterBibTeX.auto.markIDs([itemID], 'citekey changed') return @verify(key) scan: (ids, reason) -> if reason in ['delete', 'trash'] ids = (@integer(id) for id in ids || []) @db.keys.removeWhere((o) -> o.itemID in ids) return switch when !ids items = Zotero.DB.query(@findKeysSQL) when ids.length == 0 items = [] when ids.length == 1 items = Zotero.Items.get(ids[0]) items = if items then [items] else [] else items = Zotero.Items.get(ids) || [] pinned = {} for item in items itemID = @integer(item.itemID) citekey = @extract(item).__citekey__ cached = @db.keys.findOne({itemID}) continue unless citekey && citekey != '' if !cached || cached.citekey != citekey || cached.citekeyFormat != null libraryID = @integer(item.libraryID) if cached cached.citekey = citekey cached.citekeyFormat = null cached.libraryID = libraryID @db.keys.update(cached) else cached = {itemID, libraryID, citekey: citekey, citekeyFormat: null} @db.keys.insert(cached) pinned['' + item.itemID] = cached.citekey for itemID in ids || [] continue if pinned['' + itemID] @remove({itemID}, true) @get({itemID}, 'on-change') remove: (item, soft) -> @db.keys.removeWhere({itemID: @integer(item.itemID)}) @save(item) unless soft # only use soft remove if you know a hard set follows! eligible: (item) -> type = item.itemType if !type item = Zotero.Items.get(item.itemID) unless item.itemTypeID type = switch item.itemTypeID when 1 then 'note' when 14 then 'attachment' else 'reference' return false if type in ['note', 'attachment'] #item = Zotero.Items.get(item.itemID) unless item.getField #return false unless item #return !item.deleted return true verify: (entry) -> return entry unless Zotero.BetterBibTeX.pref.get('debug') || Zotero.BetterBibTeX.testing verify = {citekey: true, citekeyFormat: null, itemID: true, libraryID: null} for own key, value of entry switch when key in PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI'] then # ignore when verify[key] == undefined then throw new Error("Unexpected field #{key} in #{typeof entry} #{JSON.stringify(entry)}") when verify[key] && typeof value == 'number' then delete verify[key] when verify[key] && typeof value == 'string' && value.trim() != '' then delete verify[key] when verify[key] && !value then throw new Error("field #{key} of #{typeof entry} #{JSON.stringify(entry)} may not be empty") else delete verify[key] verify = Object.keys(verify) return entry if verify.length == 0 throw new Error("missing fields #{verify} in #{typeof entry} #{JSON.stringify(entry)}") clone: (key) -> return key if key in [undefined, null] clone = JSON.parse(JSON.stringify(key)) delete clone.meta delete clone['$loki'] @verify(clone) return clone get: (item, pinmode) -> if (typeof item.itemID == 'undefined') && (typeof item.key != 'undefined') && (typeof item.libraryID != 'undefined') item = Zotero.Items.getByLibraryAndKey(item.libraryID, item.key) ### no keys for notes and attachments ### return unless @eligible(item) ### pinmode can be: * on-change: generate and pin if pinCitekeys is on-change, 'null' behavior if not * on-export: generate and pin if pinCitekeys is on-export, 'null' behavior if not * null: fetch -> generate -> return ### pin = (pinmode == Zotero.BetterBibTeX.pref.get('pinCitekeys')) cached = @db.keys.findOne({itemID: @integer(item.itemID)}) ### store new cache item if we have a miss or if a re-pin is requested ### cached = @assign(item, pin) if !cached || (pin && cached.citekeyFormat) return @clone(cached) resolve: (citekeys, options = {}) -> options.libraryID = null if options.libraryID == undefined libraryID = @integer(options.libraryID) citekeys = [citekeys] unless Array.isArray(citekeys) resolved = {} for citekey in citekeys resolved[citekey] = @db.keys.findObject({citekey, libraryID}) return resolved alternates: (item) -> return Zotero.BetterBibTeX.formatter.alternates(item)
[ { "context": "#!/usr/bin/coffee\n\n###\n#@author rankun203@gmail.com\n#Call the module node6filteredLsModule, to list f", "end": 51, "score": 0.9999114274978638, "start": 32, "tag": "EMAIL", "value": "rankun203@gmail.com" } ]
node2/node6filteredLsRunner.coffee
rankun203/ModernWebStudy
0
#!/usr/bin/coffee ### #@author rankun203@gmail.com #Call the module node6filteredLsModule, to list filtered files. ### fil = require './node6filteredLsModule.js' fil process.argv[2] ? './', process.argv[3] ? 'js', (err, data) -> console.log "Something went wrong, #{err}." if err for item in data console.log item
122517
#!/usr/bin/coffee ### #@author <EMAIL> #Call the module node6filteredLsModule, to list filtered files. ### fil = require './node6filteredLsModule.js' fil process.argv[2] ? './', process.argv[3] ? 'js', (err, data) -> console.log "Something went wrong, #{err}." if err for item in data console.log item
true
#!/usr/bin/coffee ### #@author PI:EMAIL:<EMAIL>END_PI #Call the module node6filteredLsModule, to list filtered files. ### fil = require './node6filteredLsModule.js' fil process.argv[2] ? './', process.argv[3] ? 'js', (err, data) -> console.log "Something went wrong, #{err}." if err for item in data console.log item
[ { "context": "d to parentWidget\n setting = {}\n setting.key = \"organizations\"\n setting.isInitialized = false\n\n # initializat", "end": 604, "score": 0.993464469909668, "start": 591, "tag": "KEY", "value": "organizations" } ]
src/components/widgets-settings/organizations/organizations.directive.coffee
agranado2k/impac-angular
0
module = angular.module('impac.components.widgets-settings.organizations',[]) module.controller('SettingOrganizationsCtrl', ($scope, $log, ImpacDashboardsSvc) -> w = $scope.parentWidget w.selectedOrganizations = {} $scope.isOrganizationSelected = (orgUid) -> !!w.selectedOrganizations[orgUid] $scope.toggleSelectOrganization = (orgUid) -> w.selectedOrganizations[orgUid] = !w.selectedOrganizations[orgUid] $scope.onSelect({orgs: w.selectedOrganizations}) if angular.isDefined( $scope.onSelect ) # What will be passed to parentWidget setting = {} setting.key = "organizations" setting.isInitialized = false # initialization of selected organizations setting.initialize = -> ImpacDashboardsSvc.load().then( (config) -> $scope.dashboardOrganizations = config.currentDashboard.data_sources if w.metadata? && w.metadata.organization_ids? for org in $scope.dashboardOrganizations w.selectedOrganizations[org.uid] = _.contains(w.metadata.organization_ids, org.uid) setting.isInitialized = true ) setting.toMetadata = -> newOrganizations = _.compact(_.map(w.selectedOrganizations, (checked,uid) -> uid if checked )) newOrganizations = [_.first($scope.dashboardOrganizations).uid] if _.isEmpty(newOrganizations) return { organization_ids: newOrganizations } w.settings.push(setting) # Setting is ready: trigger load content # ------------------------------------ $scope.deferred.resolve($scope.parentWidget) ) module.directive('settingOrganizations', ($templateCache) -> return { restrict: 'A', scope: { parentWidget: '=' deferred: '=' onSelect: '&?' }, template: $templateCache.get('widgets-settings/organizations.tmpl.html'), controller: 'SettingOrganizationsCtrl' } )
24245
module = angular.module('impac.components.widgets-settings.organizations',[]) module.controller('SettingOrganizationsCtrl', ($scope, $log, ImpacDashboardsSvc) -> w = $scope.parentWidget w.selectedOrganizations = {} $scope.isOrganizationSelected = (orgUid) -> !!w.selectedOrganizations[orgUid] $scope.toggleSelectOrganization = (orgUid) -> w.selectedOrganizations[orgUid] = !w.selectedOrganizations[orgUid] $scope.onSelect({orgs: w.selectedOrganizations}) if angular.isDefined( $scope.onSelect ) # What will be passed to parentWidget setting = {} setting.key = "<KEY>" setting.isInitialized = false # initialization of selected organizations setting.initialize = -> ImpacDashboardsSvc.load().then( (config) -> $scope.dashboardOrganizations = config.currentDashboard.data_sources if w.metadata? && w.metadata.organization_ids? for org in $scope.dashboardOrganizations w.selectedOrganizations[org.uid] = _.contains(w.metadata.organization_ids, org.uid) setting.isInitialized = true ) setting.toMetadata = -> newOrganizations = _.compact(_.map(w.selectedOrganizations, (checked,uid) -> uid if checked )) newOrganizations = [_.first($scope.dashboardOrganizations).uid] if _.isEmpty(newOrganizations) return { organization_ids: newOrganizations } w.settings.push(setting) # Setting is ready: trigger load content # ------------------------------------ $scope.deferred.resolve($scope.parentWidget) ) module.directive('settingOrganizations', ($templateCache) -> return { restrict: 'A', scope: { parentWidget: '=' deferred: '=' onSelect: '&?' }, template: $templateCache.get('widgets-settings/organizations.tmpl.html'), controller: 'SettingOrganizationsCtrl' } )
true
module = angular.module('impac.components.widgets-settings.organizations',[]) module.controller('SettingOrganizationsCtrl', ($scope, $log, ImpacDashboardsSvc) -> w = $scope.parentWidget w.selectedOrganizations = {} $scope.isOrganizationSelected = (orgUid) -> !!w.selectedOrganizations[orgUid] $scope.toggleSelectOrganization = (orgUid) -> w.selectedOrganizations[orgUid] = !w.selectedOrganizations[orgUid] $scope.onSelect({orgs: w.selectedOrganizations}) if angular.isDefined( $scope.onSelect ) # What will be passed to parentWidget setting = {} setting.key = "PI:KEY:<KEY>END_PI" setting.isInitialized = false # initialization of selected organizations setting.initialize = -> ImpacDashboardsSvc.load().then( (config) -> $scope.dashboardOrganizations = config.currentDashboard.data_sources if w.metadata? && w.metadata.organization_ids? for org in $scope.dashboardOrganizations w.selectedOrganizations[org.uid] = _.contains(w.metadata.organization_ids, org.uid) setting.isInitialized = true ) setting.toMetadata = -> newOrganizations = _.compact(_.map(w.selectedOrganizations, (checked,uid) -> uid if checked )) newOrganizations = [_.first($scope.dashboardOrganizations).uid] if _.isEmpty(newOrganizations) return { organization_ids: newOrganizations } w.settings.push(setting) # Setting is ready: trigger load content # ------------------------------------ $scope.deferred.resolve($scope.parentWidget) ) module.directive('settingOrganizations', ($templateCache) -> return { restrict: 'A', scope: { parentWidget: '=' deferred: '=' onSelect: '&?' }, template: $templateCache.get('widgets-settings/organizations.tmpl.html'), controller: 'SettingOrganizationsCtrl' } )
[ { "context": "tion.currentCohort\n eventData['projectToken'] = \"galaxy_zoo\"\n eventData['userID'] = \"(anonymous)\"\n # set fi", "end": 515, "score": 0.9683782458305359, "start": 505, "tag": "PASSWORD", "value": "galaxy_zoo" } ]
app/lib/analytics.coffee
murraycu/Galaxy-Zoo
0
$ = require 'jqueryify' Subject = require 'models/subject' UserGetter = require 'lib/userID' Intervention = require 'lib/intervention' buildEventData = (params) -> eventData = {} # defaults eventData['subjectID'] = Subject.current?.zooniverse_id eventData['relatedID'] = Intervention.currentRelatedId eventData['experiment'] = Intervention.currentExperimentName eventData['projectToken'] = Subject.projectName eventData['cohort'] = Intervention.currentCohort eventData['projectToken'] = "galaxy_zoo" eventData['userID'] = "(anonymous)" # set fields from params eventData['time'] = Date.now() eventData['projectToken'] = params.projectToken if params.projectToken? eventData['userID'] = params.userID if params.userID? eventData['subjectID'] = params.subjectID if params.subjectID? eventData['type'] = params.type eventData['relatedID'] = params.relatedID if params.relatedID? eventData['experiment'] = params.experiment if params.experiment? eventData['errorCode'] = "" eventData['errorDescription'] = "" eventData['cohort'] = params.cohort if params.cohort? eventData addUserDetailsToEventData = (eventData) -> eventualUserIdentifier = new $.Deferred UserGetter.getUserIDorIPAddress() .then (data) => if data? UserGetter.currentUserID = data .fail => UserGetter.currentUserID = "(anonymous)" .always => eventData['userID'] = UserGetter.currentUserID eventualUserIdentifier.resolve eventData eventualUserIdentifier.promise() ### log event with Geordi v2 ### logToGeordi = (eventData) => $.ajax { url: 'https://geordi.zooniverse.org/api/events/', type: 'POST', contentType: 'application/json; charset=utf-8', data: JSON.stringify(eventData), dataType: 'json' } ### log event with Google Analytics ### logToGoogle = (eventData) => dataLayer.push { event: "gaTriggerEvent" project_token: eventData['projectToken'] user_id: eventData['userID'] subject_id: eventData['subjectID'] geordi_event_type: eventData['type'] classification_id: eventData['relatedID'] } ### This will log a user interaction both in the Geordi analytics API and in Google Analytics. ### logEvent = (params) => eventData = buildEventData(params) addUserDetailsToEventData(eventData) .always (eventData) => logToGeordi eventData logToGoogle eventData ### This will log an error in Geordi only. ### logError = (params) -> eventData = buildEventData(params) eventData['errorCode'] = params.errorCode eventData['type'] = "error" eventData['errorDescription'] = params.errorDescription logToGeordi eventData exports.logEvent = logEvent exports.logError = logError
30412
$ = require 'jqueryify' Subject = require 'models/subject' UserGetter = require 'lib/userID' Intervention = require 'lib/intervention' buildEventData = (params) -> eventData = {} # defaults eventData['subjectID'] = Subject.current?.zooniverse_id eventData['relatedID'] = Intervention.currentRelatedId eventData['experiment'] = Intervention.currentExperimentName eventData['projectToken'] = Subject.projectName eventData['cohort'] = Intervention.currentCohort eventData['projectToken'] = "<PASSWORD>" eventData['userID'] = "(anonymous)" # set fields from params eventData['time'] = Date.now() eventData['projectToken'] = params.projectToken if params.projectToken? eventData['userID'] = params.userID if params.userID? eventData['subjectID'] = params.subjectID if params.subjectID? eventData['type'] = params.type eventData['relatedID'] = params.relatedID if params.relatedID? eventData['experiment'] = params.experiment if params.experiment? eventData['errorCode'] = "" eventData['errorDescription'] = "" eventData['cohort'] = params.cohort if params.cohort? eventData addUserDetailsToEventData = (eventData) -> eventualUserIdentifier = new $.Deferred UserGetter.getUserIDorIPAddress() .then (data) => if data? UserGetter.currentUserID = data .fail => UserGetter.currentUserID = "(anonymous)" .always => eventData['userID'] = UserGetter.currentUserID eventualUserIdentifier.resolve eventData eventualUserIdentifier.promise() ### log event with Geordi v2 ### logToGeordi = (eventData) => $.ajax { url: 'https://geordi.zooniverse.org/api/events/', type: 'POST', contentType: 'application/json; charset=utf-8', data: JSON.stringify(eventData), dataType: 'json' } ### log event with Google Analytics ### logToGoogle = (eventData) => dataLayer.push { event: "gaTriggerEvent" project_token: eventData['projectToken'] user_id: eventData['userID'] subject_id: eventData['subjectID'] geordi_event_type: eventData['type'] classification_id: eventData['relatedID'] } ### This will log a user interaction both in the Geordi analytics API and in Google Analytics. ### logEvent = (params) => eventData = buildEventData(params) addUserDetailsToEventData(eventData) .always (eventData) => logToGeordi eventData logToGoogle eventData ### This will log an error in Geordi only. ### logError = (params) -> eventData = buildEventData(params) eventData['errorCode'] = params.errorCode eventData['type'] = "error" eventData['errorDescription'] = params.errorDescription logToGeordi eventData exports.logEvent = logEvent exports.logError = logError
true
$ = require 'jqueryify' Subject = require 'models/subject' UserGetter = require 'lib/userID' Intervention = require 'lib/intervention' buildEventData = (params) -> eventData = {} # defaults eventData['subjectID'] = Subject.current?.zooniverse_id eventData['relatedID'] = Intervention.currentRelatedId eventData['experiment'] = Intervention.currentExperimentName eventData['projectToken'] = Subject.projectName eventData['cohort'] = Intervention.currentCohort eventData['projectToken'] = "PI:PASSWORD:<PASSWORD>END_PI" eventData['userID'] = "(anonymous)" # set fields from params eventData['time'] = Date.now() eventData['projectToken'] = params.projectToken if params.projectToken? eventData['userID'] = params.userID if params.userID? eventData['subjectID'] = params.subjectID if params.subjectID? eventData['type'] = params.type eventData['relatedID'] = params.relatedID if params.relatedID? eventData['experiment'] = params.experiment if params.experiment? eventData['errorCode'] = "" eventData['errorDescription'] = "" eventData['cohort'] = params.cohort if params.cohort? eventData addUserDetailsToEventData = (eventData) -> eventualUserIdentifier = new $.Deferred UserGetter.getUserIDorIPAddress() .then (data) => if data? UserGetter.currentUserID = data .fail => UserGetter.currentUserID = "(anonymous)" .always => eventData['userID'] = UserGetter.currentUserID eventualUserIdentifier.resolve eventData eventualUserIdentifier.promise() ### log event with Geordi v2 ### logToGeordi = (eventData) => $.ajax { url: 'https://geordi.zooniverse.org/api/events/', type: 'POST', contentType: 'application/json; charset=utf-8', data: JSON.stringify(eventData), dataType: 'json' } ### log event with Google Analytics ### logToGoogle = (eventData) => dataLayer.push { event: "gaTriggerEvent" project_token: eventData['projectToken'] user_id: eventData['userID'] subject_id: eventData['subjectID'] geordi_event_type: eventData['type'] classification_id: eventData['relatedID'] } ### This will log a user interaction both in the Geordi analytics API and in Google Analytics. ### logEvent = (params) => eventData = buildEventData(params) addUserDetailsToEventData(eventData) .always (eventData) => logToGeordi eventData logToGoogle eventData ### This will log an error in Geordi only. ### logError = (params) -> eventData = buildEventData(params) eventData['errorCode'] = params.errorCode eventData['type'] = "error" eventData['errorDescription'] = params.errorDescription logToGeordi eventData exports.logEvent = logEvent exports.logError = logError
[ { "context": "} = require '../lib/user'\nalice = users().lookup 'test_alice'\nbob = users().lookup 'test_bob'\ncharlie = users(", "end": 66, "score": 0.9980328679084778, "start": 56, "tag": "USERNAME", "value": "test_alice" }, { "context": "users().lookup 'test_alice'\nbob = users().lookup 'test_bob'\ncharlie = users().lookup 'test_charlie'\n\nexports", "end": 98, "score": 0.9981662631034851, "start": 90, "tag": "USERNAME", "value": "test_bob" }, { "context": "okup 'test_alice'\nbob = users().lookup 'test_bob'\ncharlie = users().lookup 'test_charlie'\n\nexports.clean", "end": 104, "score": 0.7661427855491638, "start": 100, "tag": "NAME", "value": "char" }, { "context": " 'test_alice'\nbob = users().lookup 'test_bob'\ncharlie = users().lookup 'test_charlie'\n\nexports.cleanup ", "end": 107, "score": 0.6448540687561035, "start": 104, "tag": "USERNAME", "value": "lie" }, { "context": "ers().lookup 'test_bob'\ncharlie = users().lookup 'test_charlie'\n\nexports.cleanup = (T,cb) ->\n cb()\n\n", "end": 138, "score": 0.9966932535171509, "start": 126, "tag": "USERNAME", "value": "test_charlie" } ]
test/files/99_cleanup.iced
AngelKey/Angelkey.nodeclient
151
{users} = require '../lib/user' alice = users().lookup 'test_alice' bob = users().lookup 'test_bob' charlie = users().lookup 'test_charlie' exports.cleanup = (T,cb) -> cb()
136502
{users} = require '../lib/user' alice = users().lookup 'test_alice' bob = users().lookup 'test_bob' <NAME>lie = users().lookup 'test_charlie' exports.cleanup = (T,cb) -> cb()
true
{users} = require '../lib/user' alice = users().lookup 'test_alice' bob = users().lookup 'test_bob' PI:NAME:<NAME>END_PIlie = users().lookup 'test_charlie' exports.cleanup = (T,cb) -> cb()
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9992423057556152, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-http-malformed-request.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") net = require("net") http = require("http") url = require("url") # Make sure no exceptions are thrown when receiving malformed HTTP # requests. nrequests_completed = 0 nrequests_expected = 1 server = http.createServer((req, res) -> console.log "req: " + JSON.stringify(url.parse(req.url)) res.writeHead 200, "Content-Type": "text/plain" res.write "Hello World" res.end() server.close() if ++nrequests_completed is nrequests_expected return ) server.listen common.PORT server.on "listening", -> c = net.createConnection(common.PORT) c.on "connect", -> c.write "GET /hello?foo=%99bar HTTP/1.1\r\n\r\n" c.end() return return # TODO add more! process.on "exit", -> assert.equal nrequests_expected, nrequests_completed return
66174
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") net = require("net") http = require("http") url = require("url") # Make sure no exceptions are thrown when receiving malformed HTTP # requests. nrequests_completed = 0 nrequests_expected = 1 server = http.createServer((req, res) -> console.log "req: " + JSON.stringify(url.parse(req.url)) res.writeHead 200, "Content-Type": "text/plain" res.write "Hello World" res.end() server.close() if ++nrequests_completed is nrequests_expected return ) server.listen common.PORT server.on "listening", -> c = net.createConnection(common.PORT) c.on "connect", -> c.write "GET /hello?foo=%99bar HTTP/1.1\r\n\r\n" c.end() return return # TODO add more! process.on "exit", -> assert.equal nrequests_expected, nrequests_completed return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") net = require("net") http = require("http") url = require("url") # Make sure no exceptions are thrown when receiving malformed HTTP # requests. nrequests_completed = 0 nrequests_expected = 1 server = http.createServer((req, res) -> console.log "req: " + JSON.stringify(url.parse(req.url)) res.writeHead 200, "Content-Type": "text/plain" res.write "Hello World" res.end() server.close() if ++nrequests_completed is nrequests_expected return ) server.listen common.PORT server.on "listening", -> c = net.createConnection(common.PORT) c.on "connect", -> c.write "GET /hello?foo=%99bar HTTP/1.1\r\n\r\n" c.end() return return # TODO add more! process.on "exit", -> assert.equal nrequests_expected, nrequests_completed return
[ { "context": "##\n backbone-mongo.js 0.6.10\n Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-mongo\n Li", "end": 60, "score": 0.9994237422943115, "start": 52, "tag": "NAME", "value": "Vidigami" }, { "context": " Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-mongo\n License: MIT (http://www.opensou", "end": 90, "score": 0.9997034668922424, "start": 82, "tag": "USERNAME", "value": "vidigami" } ]
src/sync.coffee
vidigami/backbone-mongo
1
### backbone-mongo.js 0.6.10 Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-mongo License: MIT (http://www.opensource.org/licenses/mit-license.php) ### {ObjectID} = require 'mongodb' {_, Backbone, Queue, Schema, Utils, JSONUtils} = BackboneORM = require 'backbone-orm' MONGO_GENERATION = +(require 'mongodb/package.json').version.split('.').shift() throw new Error("mongodb driver version #{(require 'mongodb/package.json').version} not yet supported. Open an issue: https://github.com/vidigami/backbone-mongo/issues") unless MONGO_GENERATION in [1, 2] MongoCursor = require './cursor' Connection = require './lib/connection' DatabaseTools = require './database_tools' DESTROY_BATCH_LIMIT = 1000 CAPABILITIES = {embed: true, json: true, unique: true, manual_ids: true, dynamic: true, self_reference: true} class MongoSync constructor: (@model_type, @sync_options={}) -> @model_type.model_name = Utils.findOrGenerateModelName(@model_type) @schema = new Schema(@model_type, {id: {type: ObjectID}}) @backbone_adapter = @model_type.backbone_adapter = @_selectAdapter() # @nodoc initialize: (model) -> return if @is_initialized; @is_initialized = true @schema.initialize() throw new Error "Missing url for model" unless url = _.result(new @model_type, 'url') @connect(url) ################################### # Classic Backbone Sync ################################### # @nodoc read: (model, options) -> # a collection if model.models @cursor().toJSON (err, json) -> return options.error(err) if err options.success(json) # a model else @cursor(model.id).toJSON (err, json) -> return options.error(err) if err return options.error(new Error "Model not found. Id #{model.id}") unless json options.success(json) # @nodoc create: (model, options, force) -> return options.error(new Error("Create should not be called for manual option. Set an id before calling save. Model: #{JSONUtils.stringify(model.toJSON())}")) if @manual_id and not force @connection.collection (err, collection) => return options.error(err) if err return options.error(new Error 'New document has a non-empty revision') if model.get('_rev') doc = @backbone_adapter.attributesToNative(model.toJSON()); doc._rev = 1 # start revisions collection.insert doc, (err, results) => return options.error(err) if err docs = if MONGO_GENERATION is 1 then results else results.ops # 1.x and 2.x return callback(new Error "Failed to create model. Error: document not found") if not docs or docs.length isnt 1 options.success(@backbone_adapter.nativeToAttributes(docs[0])) # @nodoc update: (model, options) -> return @create(model, options, true) unless model.get('_rev') # no revision, create - in the case we manually set an id and are saving for the first time @connection.collection (err, collection) => return options.error(err) if err json = @backbone_adapter.attributesToNative(model.toJSON()) delete json._id if @backbone_adapter.id_attribute is '_id' find_query = @backbone_adapter.modelFindQuery(model) find_query._rev = json._rev json._rev++ # increment revisions modifications = {$set: json} if unsets = Utils.get(model, 'unsets') Utils.unset(model, 'unsets') # clear now that we are dealing with them if unsets.length modifications.$unset = {} modifications.$unset[key] = '' for key in unsets when not model.attributes.hasOwnProperty(key) # unset if they haven't been re-set # update the record collection.findAndModify find_query, [[@backbone_adapter.id_attribute, 'asc']], modifications, {new: true}, (err, result) => return options.error(new Error "Failed to update model (#{@model_type.model_name}). Error: #{err}") if err doc = if MONGO_GENERATION is 1 then result else result.value # 1.x and 2.x return options.error(new Error "Failed to update model (#{@model_type.model_name}). Either the document has been deleted or the revision (_rev) was stale.") unless doc return options.error(new Error "Failed to update revision (#{@model_type.model_name}). Is: #{doc._rev} expecting: #{json._rev}") if doc._rev isnt json._rev options.success(@backbone_adapter.nativeToAttributes(doc)) # @nodoc delete: (model, options) -> @deleteCB(model, (err) => if err then options.error(err) else options.success()) # @nodoc deleteCB: (model, callback) => @connection.collection (err, collection) => return options.error(err) if err collection.remove @backbone_adapter.attributesToNative({id: model.id}), (err) => if err then callback(err) else Utils.patchRemove(@model_type, model, callback) ################################### # Backbone ORM - Class Extensions ################################### # @no_doc resetSchema: (options, callback) -> @db().resetSchema(options, callback) # @no_doc cursor: (query={}) -> return new MongoCursor(query, _.pick(@, ['model_type', 'connection', 'backbone_adapter'])) # @no_doc destroy: (query, callback) -> [query, callback] = [{}, query] if arguments.length is 1 @connection.collection (err, collection) => if err then callback(err) else @model_type.each _.extend({$each: {limit: DESTROY_BATCH_LIMIT, json: true}}, query), @deleteCB, callback ################################### # Backbone Mongo - Extensions ################################### connect: (url) -> return if @connection and @connection.url is url @connection.destroy() if @connection @connection = new Connection(url, @schema, @sync_options) collection: (callback) -> @connection.collection(callback) db: => @db_tools or= new DatabaseTools(@) ################################### # Internal ################################### _selectAdapter: -> for field_name, field_info of @schema.raw continue if (field_name isnt 'id') or not _.isArray(field_info) for info in field_info if info.manual or info.manual_id # TODO: remove legacy support for manual_id @manual_id = true return require './lib/document_adapter_no_mongo_id' return require './lib/document_adapter_mongo_id' # default is using the mongodb's ids module.exports = (type, sync_options={}) -> if Utils.isCollection(new type()) # collection model_type = Utils.configureCollectionModelType(type, module.exports) return type::sync = model_type::sync sync = new MongoSync(type, sync_options) type::sync = sync_fn = (method, model, options={}) -> # save for access by model extensions sync.initialize() return module.exports.apply(null, Array::slice.call(arguments, 1)) if method is 'createSync' # create a new sync return sync if method is 'sync' return sync.schema if method is 'schema' return false if method is 'isRemote' return if sync[method] then sync[method].apply(sync, Array::slice.call(arguments, 1)) else undefined Utils.configureModelType(type) # mixin extensions return BackboneORM.model_cache.configureSync(type, sync_fn) module.exports.capabilities = (url) -> CAPABILITIES
120204
### backbone-mongo.js 0.6.10 Copyright (c) 2013 <NAME> - https://github.com/vidigami/backbone-mongo License: MIT (http://www.opensource.org/licenses/mit-license.php) ### {ObjectID} = require 'mongodb' {_, Backbone, Queue, Schema, Utils, JSONUtils} = BackboneORM = require 'backbone-orm' MONGO_GENERATION = +(require 'mongodb/package.json').version.split('.').shift() throw new Error("mongodb driver version #{(require 'mongodb/package.json').version} not yet supported. Open an issue: https://github.com/vidigami/backbone-mongo/issues") unless MONGO_GENERATION in [1, 2] MongoCursor = require './cursor' Connection = require './lib/connection' DatabaseTools = require './database_tools' DESTROY_BATCH_LIMIT = 1000 CAPABILITIES = {embed: true, json: true, unique: true, manual_ids: true, dynamic: true, self_reference: true} class MongoSync constructor: (@model_type, @sync_options={}) -> @model_type.model_name = Utils.findOrGenerateModelName(@model_type) @schema = new Schema(@model_type, {id: {type: ObjectID}}) @backbone_adapter = @model_type.backbone_adapter = @_selectAdapter() # @nodoc initialize: (model) -> return if @is_initialized; @is_initialized = true @schema.initialize() throw new Error "Missing url for model" unless url = _.result(new @model_type, 'url') @connect(url) ################################### # Classic Backbone Sync ################################### # @nodoc read: (model, options) -> # a collection if model.models @cursor().toJSON (err, json) -> return options.error(err) if err options.success(json) # a model else @cursor(model.id).toJSON (err, json) -> return options.error(err) if err return options.error(new Error "Model not found. Id #{model.id}") unless json options.success(json) # @nodoc create: (model, options, force) -> return options.error(new Error("Create should not be called for manual option. Set an id before calling save. Model: #{JSONUtils.stringify(model.toJSON())}")) if @manual_id and not force @connection.collection (err, collection) => return options.error(err) if err return options.error(new Error 'New document has a non-empty revision') if model.get('_rev') doc = @backbone_adapter.attributesToNative(model.toJSON()); doc._rev = 1 # start revisions collection.insert doc, (err, results) => return options.error(err) if err docs = if MONGO_GENERATION is 1 then results else results.ops # 1.x and 2.x return callback(new Error "Failed to create model. Error: document not found") if not docs or docs.length isnt 1 options.success(@backbone_adapter.nativeToAttributes(docs[0])) # @nodoc update: (model, options) -> return @create(model, options, true) unless model.get('_rev') # no revision, create - in the case we manually set an id and are saving for the first time @connection.collection (err, collection) => return options.error(err) if err json = @backbone_adapter.attributesToNative(model.toJSON()) delete json._id if @backbone_adapter.id_attribute is '_id' find_query = @backbone_adapter.modelFindQuery(model) find_query._rev = json._rev json._rev++ # increment revisions modifications = {$set: json} if unsets = Utils.get(model, 'unsets') Utils.unset(model, 'unsets') # clear now that we are dealing with them if unsets.length modifications.$unset = {} modifications.$unset[key] = '' for key in unsets when not model.attributes.hasOwnProperty(key) # unset if they haven't been re-set # update the record collection.findAndModify find_query, [[@backbone_adapter.id_attribute, 'asc']], modifications, {new: true}, (err, result) => return options.error(new Error "Failed to update model (#{@model_type.model_name}). Error: #{err}") if err doc = if MONGO_GENERATION is 1 then result else result.value # 1.x and 2.x return options.error(new Error "Failed to update model (#{@model_type.model_name}). Either the document has been deleted or the revision (_rev) was stale.") unless doc return options.error(new Error "Failed to update revision (#{@model_type.model_name}). Is: #{doc._rev} expecting: #{json._rev}") if doc._rev isnt json._rev options.success(@backbone_adapter.nativeToAttributes(doc)) # @nodoc delete: (model, options) -> @deleteCB(model, (err) => if err then options.error(err) else options.success()) # @nodoc deleteCB: (model, callback) => @connection.collection (err, collection) => return options.error(err) if err collection.remove @backbone_adapter.attributesToNative({id: model.id}), (err) => if err then callback(err) else Utils.patchRemove(@model_type, model, callback) ################################### # Backbone ORM - Class Extensions ################################### # @no_doc resetSchema: (options, callback) -> @db().resetSchema(options, callback) # @no_doc cursor: (query={}) -> return new MongoCursor(query, _.pick(@, ['model_type', 'connection', 'backbone_adapter'])) # @no_doc destroy: (query, callback) -> [query, callback] = [{}, query] if arguments.length is 1 @connection.collection (err, collection) => if err then callback(err) else @model_type.each _.extend({$each: {limit: DESTROY_BATCH_LIMIT, json: true}}, query), @deleteCB, callback ################################### # Backbone Mongo - Extensions ################################### connect: (url) -> return if @connection and @connection.url is url @connection.destroy() if @connection @connection = new Connection(url, @schema, @sync_options) collection: (callback) -> @connection.collection(callback) db: => @db_tools or= new DatabaseTools(@) ################################### # Internal ################################### _selectAdapter: -> for field_name, field_info of @schema.raw continue if (field_name isnt 'id') or not _.isArray(field_info) for info in field_info if info.manual or info.manual_id # TODO: remove legacy support for manual_id @manual_id = true return require './lib/document_adapter_no_mongo_id' return require './lib/document_adapter_mongo_id' # default is using the mongodb's ids module.exports = (type, sync_options={}) -> if Utils.isCollection(new type()) # collection model_type = Utils.configureCollectionModelType(type, module.exports) return type::sync = model_type::sync sync = new MongoSync(type, sync_options) type::sync = sync_fn = (method, model, options={}) -> # save for access by model extensions sync.initialize() return module.exports.apply(null, Array::slice.call(arguments, 1)) if method is 'createSync' # create a new sync return sync if method is 'sync' return sync.schema if method is 'schema' return false if method is 'isRemote' return if sync[method] then sync[method].apply(sync, Array::slice.call(arguments, 1)) else undefined Utils.configureModelType(type) # mixin extensions return BackboneORM.model_cache.configureSync(type, sync_fn) module.exports.capabilities = (url) -> CAPABILITIES
true
### backbone-mongo.js 0.6.10 Copyright (c) 2013 PI:NAME:<NAME>END_PI - https://github.com/vidigami/backbone-mongo License: MIT (http://www.opensource.org/licenses/mit-license.php) ### {ObjectID} = require 'mongodb' {_, Backbone, Queue, Schema, Utils, JSONUtils} = BackboneORM = require 'backbone-orm' MONGO_GENERATION = +(require 'mongodb/package.json').version.split('.').shift() throw new Error("mongodb driver version #{(require 'mongodb/package.json').version} not yet supported. Open an issue: https://github.com/vidigami/backbone-mongo/issues") unless MONGO_GENERATION in [1, 2] MongoCursor = require './cursor' Connection = require './lib/connection' DatabaseTools = require './database_tools' DESTROY_BATCH_LIMIT = 1000 CAPABILITIES = {embed: true, json: true, unique: true, manual_ids: true, dynamic: true, self_reference: true} class MongoSync constructor: (@model_type, @sync_options={}) -> @model_type.model_name = Utils.findOrGenerateModelName(@model_type) @schema = new Schema(@model_type, {id: {type: ObjectID}}) @backbone_adapter = @model_type.backbone_adapter = @_selectAdapter() # @nodoc initialize: (model) -> return if @is_initialized; @is_initialized = true @schema.initialize() throw new Error "Missing url for model" unless url = _.result(new @model_type, 'url') @connect(url) ################################### # Classic Backbone Sync ################################### # @nodoc read: (model, options) -> # a collection if model.models @cursor().toJSON (err, json) -> return options.error(err) if err options.success(json) # a model else @cursor(model.id).toJSON (err, json) -> return options.error(err) if err return options.error(new Error "Model not found. Id #{model.id}") unless json options.success(json) # @nodoc create: (model, options, force) -> return options.error(new Error("Create should not be called for manual option. Set an id before calling save. Model: #{JSONUtils.stringify(model.toJSON())}")) if @manual_id and not force @connection.collection (err, collection) => return options.error(err) if err return options.error(new Error 'New document has a non-empty revision') if model.get('_rev') doc = @backbone_adapter.attributesToNative(model.toJSON()); doc._rev = 1 # start revisions collection.insert doc, (err, results) => return options.error(err) if err docs = if MONGO_GENERATION is 1 then results else results.ops # 1.x and 2.x return callback(new Error "Failed to create model. Error: document not found") if not docs or docs.length isnt 1 options.success(@backbone_adapter.nativeToAttributes(docs[0])) # @nodoc update: (model, options) -> return @create(model, options, true) unless model.get('_rev') # no revision, create - in the case we manually set an id and are saving for the first time @connection.collection (err, collection) => return options.error(err) if err json = @backbone_adapter.attributesToNative(model.toJSON()) delete json._id if @backbone_adapter.id_attribute is '_id' find_query = @backbone_adapter.modelFindQuery(model) find_query._rev = json._rev json._rev++ # increment revisions modifications = {$set: json} if unsets = Utils.get(model, 'unsets') Utils.unset(model, 'unsets') # clear now that we are dealing with them if unsets.length modifications.$unset = {} modifications.$unset[key] = '' for key in unsets when not model.attributes.hasOwnProperty(key) # unset if they haven't been re-set # update the record collection.findAndModify find_query, [[@backbone_adapter.id_attribute, 'asc']], modifications, {new: true}, (err, result) => return options.error(new Error "Failed to update model (#{@model_type.model_name}). Error: #{err}") if err doc = if MONGO_GENERATION is 1 then result else result.value # 1.x and 2.x return options.error(new Error "Failed to update model (#{@model_type.model_name}). Either the document has been deleted or the revision (_rev) was stale.") unless doc return options.error(new Error "Failed to update revision (#{@model_type.model_name}). Is: #{doc._rev} expecting: #{json._rev}") if doc._rev isnt json._rev options.success(@backbone_adapter.nativeToAttributes(doc)) # @nodoc delete: (model, options) -> @deleteCB(model, (err) => if err then options.error(err) else options.success()) # @nodoc deleteCB: (model, callback) => @connection.collection (err, collection) => return options.error(err) if err collection.remove @backbone_adapter.attributesToNative({id: model.id}), (err) => if err then callback(err) else Utils.patchRemove(@model_type, model, callback) ################################### # Backbone ORM - Class Extensions ################################### # @no_doc resetSchema: (options, callback) -> @db().resetSchema(options, callback) # @no_doc cursor: (query={}) -> return new MongoCursor(query, _.pick(@, ['model_type', 'connection', 'backbone_adapter'])) # @no_doc destroy: (query, callback) -> [query, callback] = [{}, query] if arguments.length is 1 @connection.collection (err, collection) => if err then callback(err) else @model_type.each _.extend({$each: {limit: DESTROY_BATCH_LIMIT, json: true}}, query), @deleteCB, callback ################################### # Backbone Mongo - Extensions ################################### connect: (url) -> return if @connection and @connection.url is url @connection.destroy() if @connection @connection = new Connection(url, @schema, @sync_options) collection: (callback) -> @connection.collection(callback) db: => @db_tools or= new DatabaseTools(@) ################################### # Internal ################################### _selectAdapter: -> for field_name, field_info of @schema.raw continue if (field_name isnt 'id') or not _.isArray(field_info) for info in field_info if info.manual or info.manual_id # TODO: remove legacy support for manual_id @manual_id = true return require './lib/document_adapter_no_mongo_id' return require './lib/document_adapter_mongo_id' # default is using the mongodb's ids module.exports = (type, sync_options={}) -> if Utils.isCollection(new type()) # collection model_type = Utils.configureCollectionModelType(type, module.exports) return type::sync = model_type::sync sync = new MongoSync(type, sync_options) type::sync = sync_fn = (method, model, options={}) -> # save for access by model extensions sync.initialize() return module.exports.apply(null, Array::slice.call(arguments, 1)) if method is 'createSync' # create a new sync return sync if method is 'sync' return sync.schema if method is 'schema' return false if method is 'isRemote' return if sync[method] then sync[method].apply(sync, Array::slice.call(arguments, 1)) else undefined Utils.configureModelType(type) # mixin extensions return BackboneORM.model_cache.configureSync(type, sync_fn) module.exports.capabilities = (url) -> CAPABILITIES
[ { "context": " @$scope.original_project = { id: 1, name: 'original_name'}\n\n it 'should not call update when project ", "end": 2790, "score": 0.7026975750923157, "start": 2777, "tag": "NAME", "value": "original_name" } ]
spec/javascripts/unit/controllers/project_ctrl_spec.js.coffee
FanAnToXa/todo-app
2
#= require spec_helper describe 'ProjectCtrl', -> beforeEach -> @success_action = true @ProjectResource = jasmine.createSpyObj 'ProjectResource', [ 'query', 'save', 'update', 'remove' ] @project_list = [ { id: 1, name: 'name 1'}, { id: 3, name: 'name 3'}] @project = { id: 3, name: 'name 3'} @ProjectResource.query.and.returnValue(@project_list) action_with_promise = $promise: then: (resolve, reject) => if @success_action then resolve(@project) else reject(@project) @ProjectResource.save.and.returnValue action_with_promise @ProjectResource.update.and.returnValue action_with_promise @ProjectResource.remove.and.returnValue action_with_promise console.log = jasmine.createSpy 'log' @initProjectCtrl = -> @$controller 'ProjectCtrl', $scope: @$scope $location: @$location Auth: @Auth ProjectResource: @ProjectResource describe 'when authenticated', -> beforeEach -> @controller = @initProjectCtrl() it 'should not redirect to /', -> expect(@$location.path).not.toHaveBeenCalledWith '/' describe 'should initialize vairables', -> it 'should get projects list', -> expect(@$scope.projects_list).toEqual @project_list it 'should set defult vairables', -> expect(@$scope.edited_project).toEqual null it 'should assign functions to scope', -> expect(@$scope.addProject).toEqual @controller.addProject expect(@$scope.editProject).toEqual @controller.editProject expect(@$scope.cancelEditing).toEqual @controller.cancelEditing expect(@$scope.updateProject).toEqual @controller.updateProject expect(@$scope.destroyProject).toEqual @controller.destroyProject describe '#addProject', -> it 'should save project', -> @$scope.addProject @project expect(@$scope.projects_list.pop()).toEqual @project expect(@$scope.new_project).toEqual {} it 'should handle errors', -> @success_action = false @$scope.addProject @project expect(@ProjectResource.save).toHaveBeenCalledWith @project expect(console.log).toHaveBeenCalledWith 'error' describe '#editProject', -> it 'should initialize editing', -> @$scope.editProject @project expect(@$scope.edited_project).toEqual @project expect(@$scope.original_project).toEqual @project describe '#cancelEditing', -> it 'should cancel editing', -> @$scope.cancelEditing @project expect(@$scope.edited_project).toEqual null expect(@$scope.original_project).toEqual null describe '#updateProject', -> beforeEach -> @$scope.original_project = { id: 1, name: 'original_name'} it 'should not call update when project not modified', -> @$scope.original_project = @project @$scope.updateProject @project expect(@ProjectResource.update).not.toHaveBeenCalled() it 'should update project', -> @$scope.updateProject @project expect(@$scope.edited_project).toEqual null it 'should handle errors', -> @success_action = false @$scope.updateProject @project expect(@project.name).toEqual 'original_name' describe '#destroyProject', -> it 'should destroy project', -> @$scope.destroyProject @project expect(@$scope.projects_list.indexOf(@project)).toEqual -1 describe 'when not authenticated', -> beforeEach -> @Auth.isAuthenticated.and.returnValue(false) @initProjectCtrl() it 'should not redirect to /', -> expect(@$location.path).toHaveBeenCalledWith('/')
209573
#= require spec_helper describe 'ProjectCtrl', -> beforeEach -> @success_action = true @ProjectResource = jasmine.createSpyObj 'ProjectResource', [ 'query', 'save', 'update', 'remove' ] @project_list = [ { id: 1, name: 'name 1'}, { id: 3, name: 'name 3'}] @project = { id: 3, name: 'name 3'} @ProjectResource.query.and.returnValue(@project_list) action_with_promise = $promise: then: (resolve, reject) => if @success_action then resolve(@project) else reject(@project) @ProjectResource.save.and.returnValue action_with_promise @ProjectResource.update.and.returnValue action_with_promise @ProjectResource.remove.and.returnValue action_with_promise console.log = jasmine.createSpy 'log' @initProjectCtrl = -> @$controller 'ProjectCtrl', $scope: @$scope $location: @$location Auth: @Auth ProjectResource: @ProjectResource describe 'when authenticated', -> beforeEach -> @controller = @initProjectCtrl() it 'should not redirect to /', -> expect(@$location.path).not.toHaveBeenCalledWith '/' describe 'should initialize vairables', -> it 'should get projects list', -> expect(@$scope.projects_list).toEqual @project_list it 'should set defult vairables', -> expect(@$scope.edited_project).toEqual null it 'should assign functions to scope', -> expect(@$scope.addProject).toEqual @controller.addProject expect(@$scope.editProject).toEqual @controller.editProject expect(@$scope.cancelEditing).toEqual @controller.cancelEditing expect(@$scope.updateProject).toEqual @controller.updateProject expect(@$scope.destroyProject).toEqual @controller.destroyProject describe '#addProject', -> it 'should save project', -> @$scope.addProject @project expect(@$scope.projects_list.pop()).toEqual @project expect(@$scope.new_project).toEqual {} it 'should handle errors', -> @success_action = false @$scope.addProject @project expect(@ProjectResource.save).toHaveBeenCalledWith @project expect(console.log).toHaveBeenCalledWith 'error' describe '#editProject', -> it 'should initialize editing', -> @$scope.editProject @project expect(@$scope.edited_project).toEqual @project expect(@$scope.original_project).toEqual @project describe '#cancelEditing', -> it 'should cancel editing', -> @$scope.cancelEditing @project expect(@$scope.edited_project).toEqual null expect(@$scope.original_project).toEqual null describe '#updateProject', -> beforeEach -> @$scope.original_project = { id: 1, name: '<NAME>'} it 'should not call update when project not modified', -> @$scope.original_project = @project @$scope.updateProject @project expect(@ProjectResource.update).not.toHaveBeenCalled() it 'should update project', -> @$scope.updateProject @project expect(@$scope.edited_project).toEqual null it 'should handle errors', -> @success_action = false @$scope.updateProject @project expect(@project.name).toEqual 'original_name' describe '#destroyProject', -> it 'should destroy project', -> @$scope.destroyProject @project expect(@$scope.projects_list.indexOf(@project)).toEqual -1 describe 'when not authenticated', -> beforeEach -> @Auth.isAuthenticated.and.returnValue(false) @initProjectCtrl() it 'should not redirect to /', -> expect(@$location.path).toHaveBeenCalledWith('/')
true
#= require spec_helper describe 'ProjectCtrl', -> beforeEach -> @success_action = true @ProjectResource = jasmine.createSpyObj 'ProjectResource', [ 'query', 'save', 'update', 'remove' ] @project_list = [ { id: 1, name: 'name 1'}, { id: 3, name: 'name 3'}] @project = { id: 3, name: 'name 3'} @ProjectResource.query.and.returnValue(@project_list) action_with_promise = $promise: then: (resolve, reject) => if @success_action then resolve(@project) else reject(@project) @ProjectResource.save.and.returnValue action_with_promise @ProjectResource.update.and.returnValue action_with_promise @ProjectResource.remove.and.returnValue action_with_promise console.log = jasmine.createSpy 'log' @initProjectCtrl = -> @$controller 'ProjectCtrl', $scope: @$scope $location: @$location Auth: @Auth ProjectResource: @ProjectResource describe 'when authenticated', -> beforeEach -> @controller = @initProjectCtrl() it 'should not redirect to /', -> expect(@$location.path).not.toHaveBeenCalledWith '/' describe 'should initialize vairables', -> it 'should get projects list', -> expect(@$scope.projects_list).toEqual @project_list it 'should set defult vairables', -> expect(@$scope.edited_project).toEqual null it 'should assign functions to scope', -> expect(@$scope.addProject).toEqual @controller.addProject expect(@$scope.editProject).toEqual @controller.editProject expect(@$scope.cancelEditing).toEqual @controller.cancelEditing expect(@$scope.updateProject).toEqual @controller.updateProject expect(@$scope.destroyProject).toEqual @controller.destroyProject describe '#addProject', -> it 'should save project', -> @$scope.addProject @project expect(@$scope.projects_list.pop()).toEqual @project expect(@$scope.new_project).toEqual {} it 'should handle errors', -> @success_action = false @$scope.addProject @project expect(@ProjectResource.save).toHaveBeenCalledWith @project expect(console.log).toHaveBeenCalledWith 'error' describe '#editProject', -> it 'should initialize editing', -> @$scope.editProject @project expect(@$scope.edited_project).toEqual @project expect(@$scope.original_project).toEqual @project describe '#cancelEditing', -> it 'should cancel editing', -> @$scope.cancelEditing @project expect(@$scope.edited_project).toEqual null expect(@$scope.original_project).toEqual null describe '#updateProject', -> beforeEach -> @$scope.original_project = { id: 1, name: 'PI:NAME:<NAME>END_PI'} it 'should not call update when project not modified', -> @$scope.original_project = @project @$scope.updateProject @project expect(@ProjectResource.update).not.toHaveBeenCalled() it 'should update project', -> @$scope.updateProject @project expect(@$scope.edited_project).toEqual null it 'should handle errors', -> @success_action = false @$scope.updateProject @project expect(@project.name).toEqual 'original_name' describe '#destroyProject', -> it 'should destroy project', -> @$scope.destroyProject @project expect(@$scope.projects_list.indexOf(@project)).toEqual -1 describe 'when not authenticated', -> beforeEach -> @Auth.isAuthenticated.and.returnValue(false) @initProjectCtrl() it 'should not redirect to /', -> expect(@$location.path).toHaveBeenCalledWith('/')
[ { "context": "grids.state.selected_ids)\r\n\r\n id: id\r\n name: name\r\n role: @state.role\r\n post_action_ids: post", "end": 3838, "score": 0.9935438632965088, "start": 3834, "tag": "NAME", "value": "name" } ]
app/assets/javascripts/operation_flow_editor/course_wares/oe_action_list.coffee.cjsx
kc-train/operation-flow-editor
2
OEActionSelectGrid = React.createClass displayName: 'OEActionSelectGrid' getInitialState: -> selected_ids: [] render: -> <div className='actions-select-grid'> { for id, action of @props.optional_actions klass = ['action'] klass.push 'selected' if @state.selected_ids.indexOf(id) > -1 <div key={action.id} className={klass.join(' ')} data-id={action.id}> <div className='inner' onClick={@select}> <div className='name'>{action.name}</div> </div> </div> } </div> select: (evt)-> $action = jQuery(evt.target).closest('.action') id = $action.data('id') selected_ids = @state.selected_ids if selected_ids.indexOf(id) > -1 selected_ids = selected_ids.filter (x)-> x != id else selected_ids.push id @setState selected_ids: selected_ids OEActionModal = React.createClass getInitialState: -> show: false id: null name: '' role: '柜员' optional_actions: {} saving: false render: -> if @state.id? title = '修改操作节点' else title = '新增操作节点' <BSModal show={@state.show} bs_size='default'> <BSModal.Header> <BSModal.Title>{title}</BSModal.Title> </BSModal.Header> <BSModal.Body> <div className='row'> <div className='col-sm-8'> <div className='form-group'> <label>操作名称</label> <input ref='name_inputer' name='name' className='form-control' type='text' placeholder='名称' value={@state.name} onChange={@on_name_change} /> </div> </div> <div className='col-sm-4'> <div className='form-group'> <label>操作角色</label> <select ref='role_inputer' className='form-control' onChange={@on_role_change} value={@state.role}> <option value='柜员'>柜员</option> <option value='客户'>客户</option> </select> </div> </div> </div> { if Object.keys(@state.optional_actions).length klass = 'row' else klass = 'row hide' <div className={klass}> <div className='col-sm-12'> <div className='form-group'> <label>后续操作(点击选中)</label> <OEActionSelectGrid ref='grids' optional_actions={@state.optional_actions} /> </div> </div> </div> } </BSModal.Body> <BSModal.Footer> { if @state.saving <div className='saving'> <i className='fa fa-spinner fa-pulse' /> <span>正在保存</span> </div> else <BSButton onClick={@props.submit} bsstyle='primary'> <i className='fa fa-ok'></i> <span>确定保存</span> </BSButton> } <BSButton onClick={@hide}> <span>关闭</span> </BSButton> </BSModal.Footer> </BSModal> show: -> @setState show: true saving: false hide: -> @setState show: false set_action: (action)-> @setState id: action.id name: action.name role: action.role return @ set_optional_actions: (optional_actions, selected_ids)-> @setState optional_actions: optional_actions @refs.grids.setState selected_ids: selected_ids.map (x)-> x return @ get_action_data: -> id = @state.id || "id#{new Date().getTime()}" name = @state.name name = '未命名操作' if jQuery.trim(name).length is 0 role = @state.role post_action_ids = (_id for _id in @refs.grids.state.selected_ids) id: id name: name role: @state.role post_action_ids: post_action_ids on_name_change: (evt)-> @setState name: evt.target.value on_role_change: (evt)-> @setState role: evt.target.value OEScreenModal = React.createClass getInitialState: -> action: null render: -> <BSModal.FormModal ref='modal' title="流程节点设置 - #{@state.action?.name}" bs_size='lg' submit={@submit}> <div className='action-node-edit'> <ul className="nav nav-tabs" role="tablist"> <li role="presentation" className="active"><a href="#modal-screen" aria-controls="home" role="tab" data-toggle="tab">屏幕关联</a></li> <li role="presentation"><a href="#modal-desc" aria-controls="profile" role="tab" data-toggle="tab">描述文本</a></li> <li role="presentation"><a href="#modal-attach" aria-controls="messages" role="tab" data-toggle="tab">上传附件</a></li> <li role="presentation"><a href="#modal-knet" aria-controls="settings" role="tab" data-toggle="tab">知识关联</a></li> </ul> <div className="tab-content"> <div role="tabpanel" className="tab-pane active screen-table" id="modal-screen"> <ScreensTable ref='table' data={@props.screen_data} xmdm={@props.flow.number} /> </div> <div role="tabpanel" className="tab-pane" id="modal-desc"> <textarea className='desc-area form-control' placeholder='填写介绍说明内容' rows='10'></textarea> </div> <div role="tabpanel" className="tab-pane upload" id="modal-attach"> <label>上传说明附件</label> <input type='file' /> </div> <div role="tabpanel" className="tab-pane klink" id="modal-knet"> 从知识网络关联教材知识点(制作中) </div> </div> </div> </BSModal.FormModal> show: -> @refs.modal.show() hide: -> @refs.modal.hide() submit: -> hmdms = @refs.table.state.linked_hmdms @state.action.linked_screen_ids = hmdms @refs.modal.setState saving: true @props.handle.save_actions @props.handle.state.actions ScreensTable = React.createClass displayName: 'ScreensTable' getInitialState: -> linked_hmdms: [] render: -> <table className='table table-striped table-bordered'> <thead><tr> <th>联动交易</th><th>输入屏幕</th><th>响应屏幕</th><th>复核屏幕</th> </tr></thead> <tbody> { idx = 0 for ldjy in @props.data <tr key={idx++}> <td>{ldjy.jymc}-{ldjy.jydm}</td> <td> { for screen in ldjy.input_screens || [] checked = @state.linked_hmdms.indexOf(screen.hmdm) > -1 <ScreensTable.Screen checked={checked} key={screen.hmdm} data={screen} xmdm={@props.xmdm} on_click={@on_click} /> } </td> <td> { if ldjy.response_screen? checked = @state.linked_hmdms.indexOf(ldjy.response_screen.hmdm) > -1 <ScreensTable.Screen checked={checked} data={ldjy.response_screen} xmdm={@props.xmdm} on_click={@on_click} /> } </td> <td> { if ldjy.compound_screen checked = @state.linked_hmdms.indexOf(ldjy.compound_screen.hmdm) > -1 <ScreensTable.Screen checked={checked} data={ldjy.compound_screen} xmdm={@props.xmdm} on_click={@on_click} /> } </td> </tr> } </tbody> </table> on_click: (evt)-> $screen = jQuery(evt.target).closest('.screen') hmdm = $screen.data('hmdm') + "" linked_hmdms = @state.linked_hmdms if $screen.hasClass('checked') linked_hmdms = linked_hmdms.filter (x)-> x != hmdm else linked_hmdms.push hmdm @setState linked_hmdms: linked_hmdms statics: Screen: React.createClass getInitialState: -> show: false render: -> klass = if @props.checked then 'screen checked' else 'screen' <div className={klass} data-hmdm={@props.data.hmdm}> <a href="/editor/screen/#{@props.xmdm}/#{@props.data.hmdm}" target='_blank'>{@props.data.hmdm}</a> <div className='cb' onClick={@props.on_click}> <i className='fa fa-check' /> </div> </div> @OEActionList = React.createClass displayName: 'OEActionList' getInitialState: -> actions: @props.flow.actions || {} render: -> <div className='OEActionList'> <div className='toolbar'> <a className='add-action' href='javascript:;' onClick={@show_create_action_modal}> <i className='fa fa-plus'></i> </a> <div className='baseinfo'> <div className='number'>{@props.flow.number}</div> <div className='name'>{@props.flow.name}</div> </div> </div> <div className='actions-list'> { for id, action of @state.actions <div data-role={action.role} data-id={action.id} key={action.id} className='action'> <div className='name'>{action.name}</div> <div className='role'>{action.role}</div> <a className='link' href='javascript:;' onClick={@show_update_action_modal}> <i className='fa fa-pencil'></i> </a> <a className='screen' href='javascript:;' onClick={@show_screen_modal}> <i className='fa fa-desktop'></i> </a> <a className='remove' href='javascript:;' onClick={@remove_action}> <i className='fa fa-times'></i> </a> </div> } </div> <OEActionModal ref='action_modal' submit={@submit} actions={@state.actions} /> <OEScreenModal ref='screen_modal' flow={@props.flow} screen_data={@props.screen_data} handle={@} /> </div> show_screen_modal: (evt)-> action_id = jQuery(evt.target).closest('.action').data('id') action = @state.actions[action_id] @refs.screen_modal.setState action: action @refs.screen_modal.refs.table.setState linked_hmdms: action.linked_screen_ids || [] @refs.screen_modal.refs.modal.setState saving: false @refs.screen_modal.show() show_create_action_modal: -> action = id: null name: '' role: '柜员' post_action_ids: [] @refs.action_modal .set_action action .set_optional_actions {}, [] .show() show_update_action_modal: (evt)-> $a = jQuery evt.target $action = $a.closest('.action') id = $action.data('id') action = @state.actions[id] optional_actions = {} all_pres_action_ids = Object.keys @get_all_pres_actions action for a_id, _action of @state.actions if all_pres_action_ids.indexOf(_action.id) < 0 optional_actions[_action.id] = _action console.log action @refs.action_modal .set_action action .set_optional_actions optional_actions, action.post_action_ids || [] .show() # 获取所有直接前置节点 get_pre_actions: (action)-> pre_actions = {} for _id, _action of @state.actions if (_action.post_action_ids || []).indexOf(action.id) > -1 pre_actions[_action.id] = _action pre_actions get_all_pres_actions: (action)-> all_pres_actions = {} @_r_ga action, all_pres_actions all_pres_actions _r_ga: (action, all_pres_actions)-> all_pres_actions[action.id] = action for _id, _action of @get_pre_actions(action) @_r_ga _action, all_pres_actions hide_action_modal: -> @refs.action_modal.hide() hide_screen_modal: -> @refs.screen_modal.hide() submit: -> action = @refs.action_modal.get_action_data() actions = @state.actions actions[action.id] = action @save_actions actions remove_action: (evt, react_id)-> $btn = jQuery("[data-reactid='#{react_id}']") $action = $btn.closest('.action') id = $action.data('id') if confirm '确定要删除吗?' actions = @state.actions delete actions[id] # 从其他节点的后续节点中去掉 for _id, action of actions if action.post_action_ids? action.post_action_ids = action.post_action_ids.filter (x)-> x != id $action.fadeOut => @save_actions actions save_actions: (actions)-> @refs.action_modal.setState saving: true jQuery.ajax url: @props.update_url type: 'PUT' data: actions: actions .done (res)=> @hide_action_modal() @hide_screen_modal() @setState actions: actions jQuery(document).trigger 'editor:action-changed', actions .fail -> console.log 2
41016
OEActionSelectGrid = React.createClass displayName: 'OEActionSelectGrid' getInitialState: -> selected_ids: [] render: -> <div className='actions-select-grid'> { for id, action of @props.optional_actions klass = ['action'] klass.push 'selected' if @state.selected_ids.indexOf(id) > -1 <div key={action.id} className={klass.join(' ')} data-id={action.id}> <div className='inner' onClick={@select}> <div className='name'>{action.name}</div> </div> </div> } </div> select: (evt)-> $action = jQuery(evt.target).closest('.action') id = $action.data('id') selected_ids = @state.selected_ids if selected_ids.indexOf(id) > -1 selected_ids = selected_ids.filter (x)-> x != id else selected_ids.push id @setState selected_ids: selected_ids OEActionModal = React.createClass getInitialState: -> show: false id: null name: '' role: '柜员' optional_actions: {} saving: false render: -> if @state.id? title = '修改操作节点' else title = '新增操作节点' <BSModal show={@state.show} bs_size='default'> <BSModal.Header> <BSModal.Title>{title}</BSModal.Title> </BSModal.Header> <BSModal.Body> <div className='row'> <div className='col-sm-8'> <div className='form-group'> <label>操作名称</label> <input ref='name_inputer' name='name' className='form-control' type='text' placeholder='名称' value={@state.name} onChange={@on_name_change} /> </div> </div> <div className='col-sm-4'> <div className='form-group'> <label>操作角色</label> <select ref='role_inputer' className='form-control' onChange={@on_role_change} value={@state.role}> <option value='柜员'>柜员</option> <option value='客户'>客户</option> </select> </div> </div> </div> { if Object.keys(@state.optional_actions).length klass = 'row' else klass = 'row hide' <div className={klass}> <div className='col-sm-12'> <div className='form-group'> <label>后续操作(点击选中)</label> <OEActionSelectGrid ref='grids' optional_actions={@state.optional_actions} /> </div> </div> </div> } </BSModal.Body> <BSModal.Footer> { if @state.saving <div className='saving'> <i className='fa fa-spinner fa-pulse' /> <span>正在保存</span> </div> else <BSButton onClick={@props.submit} bsstyle='primary'> <i className='fa fa-ok'></i> <span>确定保存</span> </BSButton> } <BSButton onClick={@hide}> <span>关闭</span> </BSButton> </BSModal.Footer> </BSModal> show: -> @setState show: true saving: false hide: -> @setState show: false set_action: (action)-> @setState id: action.id name: action.name role: action.role return @ set_optional_actions: (optional_actions, selected_ids)-> @setState optional_actions: optional_actions @refs.grids.setState selected_ids: selected_ids.map (x)-> x return @ get_action_data: -> id = @state.id || "id#{new Date().getTime()}" name = @state.name name = '未命名操作' if jQuery.trim(name).length is 0 role = @state.role post_action_ids = (_id for _id in @refs.grids.state.selected_ids) id: id name: <NAME> role: @state.role post_action_ids: post_action_ids on_name_change: (evt)-> @setState name: evt.target.value on_role_change: (evt)-> @setState role: evt.target.value OEScreenModal = React.createClass getInitialState: -> action: null render: -> <BSModal.FormModal ref='modal' title="流程节点设置 - #{@state.action?.name}" bs_size='lg' submit={@submit}> <div className='action-node-edit'> <ul className="nav nav-tabs" role="tablist"> <li role="presentation" className="active"><a href="#modal-screen" aria-controls="home" role="tab" data-toggle="tab">屏幕关联</a></li> <li role="presentation"><a href="#modal-desc" aria-controls="profile" role="tab" data-toggle="tab">描述文本</a></li> <li role="presentation"><a href="#modal-attach" aria-controls="messages" role="tab" data-toggle="tab">上传附件</a></li> <li role="presentation"><a href="#modal-knet" aria-controls="settings" role="tab" data-toggle="tab">知识关联</a></li> </ul> <div className="tab-content"> <div role="tabpanel" className="tab-pane active screen-table" id="modal-screen"> <ScreensTable ref='table' data={@props.screen_data} xmdm={@props.flow.number} /> </div> <div role="tabpanel" className="tab-pane" id="modal-desc"> <textarea className='desc-area form-control' placeholder='填写介绍说明内容' rows='10'></textarea> </div> <div role="tabpanel" className="tab-pane upload" id="modal-attach"> <label>上传说明附件</label> <input type='file' /> </div> <div role="tabpanel" className="tab-pane klink" id="modal-knet"> 从知识网络关联教材知识点(制作中) </div> </div> </div> </BSModal.FormModal> show: -> @refs.modal.show() hide: -> @refs.modal.hide() submit: -> hmdms = @refs.table.state.linked_hmdms @state.action.linked_screen_ids = hmdms @refs.modal.setState saving: true @props.handle.save_actions @props.handle.state.actions ScreensTable = React.createClass displayName: 'ScreensTable' getInitialState: -> linked_hmdms: [] render: -> <table className='table table-striped table-bordered'> <thead><tr> <th>联动交易</th><th>输入屏幕</th><th>响应屏幕</th><th>复核屏幕</th> </tr></thead> <tbody> { idx = 0 for ldjy in @props.data <tr key={idx++}> <td>{ldjy.jymc}-{ldjy.jydm}</td> <td> { for screen in ldjy.input_screens || [] checked = @state.linked_hmdms.indexOf(screen.hmdm) > -1 <ScreensTable.Screen checked={checked} key={screen.hmdm} data={screen} xmdm={@props.xmdm} on_click={@on_click} /> } </td> <td> { if ldjy.response_screen? checked = @state.linked_hmdms.indexOf(ldjy.response_screen.hmdm) > -1 <ScreensTable.Screen checked={checked} data={ldjy.response_screen} xmdm={@props.xmdm} on_click={@on_click} /> } </td> <td> { if ldjy.compound_screen checked = @state.linked_hmdms.indexOf(ldjy.compound_screen.hmdm) > -1 <ScreensTable.Screen checked={checked} data={ldjy.compound_screen} xmdm={@props.xmdm} on_click={@on_click} /> } </td> </tr> } </tbody> </table> on_click: (evt)-> $screen = jQuery(evt.target).closest('.screen') hmdm = $screen.data('hmdm') + "" linked_hmdms = @state.linked_hmdms if $screen.hasClass('checked') linked_hmdms = linked_hmdms.filter (x)-> x != hmdm else linked_hmdms.push hmdm @setState linked_hmdms: linked_hmdms statics: Screen: React.createClass getInitialState: -> show: false render: -> klass = if @props.checked then 'screen checked' else 'screen' <div className={klass} data-hmdm={@props.data.hmdm}> <a href="/editor/screen/#{@props.xmdm}/#{@props.data.hmdm}" target='_blank'>{@props.data.hmdm}</a> <div className='cb' onClick={@props.on_click}> <i className='fa fa-check' /> </div> </div> @OEActionList = React.createClass displayName: 'OEActionList' getInitialState: -> actions: @props.flow.actions || {} render: -> <div className='OEActionList'> <div className='toolbar'> <a className='add-action' href='javascript:;' onClick={@show_create_action_modal}> <i className='fa fa-plus'></i> </a> <div className='baseinfo'> <div className='number'>{@props.flow.number}</div> <div className='name'>{@props.flow.name}</div> </div> </div> <div className='actions-list'> { for id, action of @state.actions <div data-role={action.role} data-id={action.id} key={action.id} className='action'> <div className='name'>{action.name}</div> <div className='role'>{action.role}</div> <a className='link' href='javascript:;' onClick={@show_update_action_modal}> <i className='fa fa-pencil'></i> </a> <a className='screen' href='javascript:;' onClick={@show_screen_modal}> <i className='fa fa-desktop'></i> </a> <a className='remove' href='javascript:;' onClick={@remove_action}> <i className='fa fa-times'></i> </a> </div> } </div> <OEActionModal ref='action_modal' submit={@submit} actions={@state.actions} /> <OEScreenModal ref='screen_modal' flow={@props.flow} screen_data={@props.screen_data} handle={@} /> </div> show_screen_modal: (evt)-> action_id = jQuery(evt.target).closest('.action').data('id') action = @state.actions[action_id] @refs.screen_modal.setState action: action @refs.screen_modal.refs.table.setState linked_hmdms: action.linked_screen_ids || [] @refs.screen_modal.refs.modal.setState saving: false @refs.screen_modal.show() show_create_action_modal: -> action = id: null name: '' role: '柜员' post_action_ids: [] @refs.action_modal .set_action action .set_optional_actions {}, [] .show() show_update_action_modal: (evt)-> $a = jQuery evt.target $action = $a.closest('.action') id = $action.data('id') action = @state.actions[id] optional_actions = {} all_pres_action_ids = Object.keys @get_all_pres_actions action for a_id, _action of @state.actions if all_pres_action_ids.indexOf(_action.id) < 0 optional_actions[_action.id] = _action console.log action @refs.action_modal .set_action action .set_optional_actions optional_actions, action.post_action_ids || [] .show() # 获取所有直接前置节点 get_pre_actions: (action)-> pre_actions = {} for _id, _action of @state.actions if (_action.post_action_ids || []).indexOf(action.id) > -1 pre_actions[_action.id] = _action pre_actions get_all_pres_actions: (action)-> all_pres_actions = {} @_r_ga action, all_pres_actions all_pres_actions _r_ga: (action, all_pres_actions)-> all_pres_actions[action.id] = action for _id, _action of @get_pre_actions(action) @_r_ga _action, all_pres_actions hide_action_modal: -> @refs.action_modal.hide() hide_screen_modal: -> @refs.screen_modal.hide() submit: -> action = @refs.action_modal.get_action_data() actions = @state.actions actions[action.id] = action @save_actions actions remove_action: (evt, react_id)-> $btn = jQuery("[data-reactid='#{react_id}']") $action = $btn.closest('.action') id = $action.data('id') if confirm '确定要删除吗?' actions = @state.actions delete actions[id] # 从其他节点的后续节点中去掉 for _id, action of actions if action.post_action_ids? action.post_action_ids = action.post_action_ids.filter (x)-> x != id $action.fadeOut => @save_actions actions save_actions: (actions)-> @refs.action_modal.setState saving: true jQuery.ajax url: @props.update_url type: 'PUT' data: actions: actions .done (res)=> @hide_action_modal() @hide_screen_modal() @setState actions: actions jQuery(document).trigger 'editor:action-changed', actions .fail -> console.log 2
true
OEActionSelectGrid = React.createClass displayName: 'OEActionSelectGrid' getInitialState: -> selected_ids: [] render: -> <div className='actions-select-grid'> { for id, action of @props.optional_actions klass = ['action'] klass.push 'selected' if @state.selected_ids.indexOf(id) > -1 <div key={action.id} className={klass.join(' ')} data-id={action.id}> <div className='inner' onClick={@select}> <div className='name'>{action.name}</div> </div> </div> } </div> select: (evt)-> $action = jQuery(evt.target).closest('.action') id = $action.data('id') selected_ids = @state.selected_ids if selected_ids.indexOf(id) > -1 selected_ids = selected_ids.filter (x)-> x != id else selected_ids.push id @setState selected_ids: selected_ids OEActionModal = React.createClass getInitialState: -> show: false id: null name: '' role: '柜员' optional_actions: {} saving: false render: -> if @state.id? title = '修改操作节点' else title = '新增操作节点' <BSModal show={@state.show} bs_size='default'> <BSModal.Header> <BSModal.Title>{title}</BSModal.Title> </BSModal.Header> <BSModal.Body> <div className='row'> <div className='col-sm-8'> <div className='form-group'> <label>操作名称</label> <input ref='name_inputer' name='name' className='form-control' type='text' placeholder='名称' value={@state.name} onChange={@on_name_change} /> </div> </div> <div className='col-sm-4'> <div className='form-group'> <label>操作角色</label> <select ref='role_inputer' className='form-control' onChange={@on_role_change} value={@state.role}> <option value='柜员'>柜员</option> <option value='客户'>客户</option> </select> </div> </div> </div> { if Object.keys(@state.optional_actions).length klass = 'row' else klass = 'row hide' <div className={klass}> <div className='col-sm-12'> <div className='form-group'> <label>后续操作(点击选中)</label> <OEActionSelectGrid ref='grids' optional_actions={@state.optional_actions} /> </div> </div> </div> } </BSModal.Body> <BSModal.Footer> { if @state.saving <div className='saving'> <i className='fa fa-spinner fa-pulse' /> <span>正在保存</span> </div> else <BSButton onClick={@props.submit} bsstyle='primary'> <i className='fa fa-ok'></i> <span>确定保存</span> </BSButton> } <BSButton onClick={@hide}> <span>关闭</span> </BSButton> </BSModal.Footer> </BSModal> show: -> @setState show: true saving: false hide: -> @setState show: false set_action: (action)-> @setState id: action.id name: action.name role: action.role return @ set_optional_actions: (optional_actions, selected_ids)-> @setState optional_actions: optional_actions @refs.grids.setState selected_ids: selected_ids.map (x)-> x return @ get_action_data: -> id = @state.id || "id#{new Date().getTime()}" name = @state.name name = '未命名操作' if jQuery.trim(name).length is 0 role = @state.role post_action_ids = (_id for _id in @refs.grids.state.selected_ids) id: id name: PI:NAME:<NAME>END_PI role: @state.role post_action_ids: post_action_ids on_name_change: (evt)-> @setState name: evt.target.value on_role_change: (evt)-> @setState role: evt.target.value OEScreenModal = React.createClass getInitialState: -> action: null render: -> <BSModal.FormModal ref='modal' title="流程节点设置 - #{@state.action?.name}" bs_size='lg' submit={@submit}> <div className='action-node-edit'> <ul className="nav nav-tabs" role="tablist"> <li role="presentation" className="active"><a href="#modal-screen" aria-controls="home" role="tab" data-toggle="tab">屏幕关联</a></li> <li role="presentation"><a href="#modal-desc" aria-controls="profile" role="tab" data-toggle="tab">描述文本</a></li> <li role="presentation"><a href="#modal-attach" aria-controls="messages" role="tab" data-toggle="tab">上传附件</a></li> <li role="presentation"><a href="#modal-knet" aria-controls="settings" role="tab" data-toggle="tab">知识关联</a></li> </ul> <div className="tab-content"> <div role="tabpanel" className="tab-pane active screen-table" id="modal-screen"> <ScreensTable ref='table' data={@props.screen_data} xmdm={@props.flow.number} /> </div> <div role="tabpanel" className="tab-pane" id="modal-desc"> <textarea className='desc-area form-control' placeholder='填写介绍说明内容' rows='10'></textarea> </div> <div role="tabpanel" className="tab-pane upload" id="modal-attach"> <label>上传说明附件</label> <input type='file' /> </div> <div role="tabpanel" className="tab-pane klink" id="modal-knet"> 从知识网络关联教材知识点(制作中) </div> </div> </div> </BSModal.FormModal> show: -> @refs.modal.show() hide: -> @refs.modal.hide() submit: -> hmdms = @refs.table.state.linked_hmdms @state.action.linked_screen_ids = hmdms @refs.modal.setState saving: true @props.handle.save_actions @props.handle.state.actions ScreensTable = React.createClass displayName: 'ScreensTable' getInitialState: -> linked_hmdms: [] render: -> <table className='table table-striped table-bordered'> <thead><tr> <th>联动交易</th><th>输入屏幕</th><th>响应屏幕</th><th>复核屏幕</th> </tr></thead> <tbody> { idx = 0 for ldjy in @props.data <tr key={idx++}> <td>{ldjy.jymc}-{ldjy.jydm}</td> <td> { for screen in ldjy.input_screens || [] checked = @state.linked_hmdms.indexOf(screen.hmdm) > -1 <ScreensTable.Screen checked={checked} key={screen.hmdm} data={screen} xmdm={@props.xmdm} on_click={@on_click} /> } </td> <td> { if ldjy.response_screen? checked = @state.linked_hmdms.indexOf(ldjy.response_screen.hmdm) > -1 <ScreensTable.Screen checked={checked} data={ldjy.response_screen} xmdm={@props.xmdm} on_click={@on_click} /> } </td> <td> { if ldjy.compound_screen checked = @state.linked_hmdms.indexOf(ldjy.compound_screen.hmdm) > -1 <ScreensTable.Screen checked={checked} data={ldjy.compound_screen} xmdm={@props.xmdm} on_click={@on_click} /> } </td> </tr> } </tbody> </table> on_click: (evt)-> $screen = jQuery(evt.target).closest('.screen') hmdm = $screen.data('hmdm') + "" linked_hmdms = @state.linked_hmdms if $screen.hasClass('checked') linked_hmdms = linked_hmdms.filter (x)-> x != hmdm else linked_hmdms.push hmdm @setState linked_hmdms: linked_hmdms statics: Screen: React.createClass getInitialState: -> show: false render: -> klass = if @props.checked then 'screen checked' else 'screen' <div className={klass} data-hmdm={@props.data.hmdm}> <a href="/editor/screen/#{@props.xmdm}/#{@props.data.hmdm}" target='_blank'>{@props.data.hmdm}</a> <div className='cb' onClick={@props.on_click}> <i className='fa fa-check' /> </div> </div> @OEActionList = React.createClass displayName: 'OEActionList' getInitialState: -> actions: @props.flow.actions || {} render: -> <div className='OEActionList'> <div className='toolbar'> <a className='add-action' href='javascript:;' onClick={@show_create_action_modal}> <i className='fa fa-plus'></i> </a> <div className='baseinfo'> <div className='number'>{@props.flow.number}</div> <div className='name'>{@props.flow.name}</div> </div> </div> <div className='actions-list'> { for id, action of @state.actions <div data-role={action.role} data-id={action.id} key={action.id} className='action'> <div className='name'>{action.name}</div> <div className='role'>{action.role}</div> <a className='link' href='javascript:;' onClick={@show_update_action_modal}> <i className='fa fa-pencil'></i> </a> <a className='screen' href='javascript:;' onClick={@show_screen_modal}> <i className='fa fa-desktop'></i> </a> <a className='remove' href='javascript:;' onClick={@remove_action}> <i className='fa fa-times'></i> </a> </div> } </div> <OEActionModal ref='action_modal' submit={@submit} actions={@state.actions} /> <OEScreenModal ref='screen_modal' flow={@props.flow} screen_data={@props.screen_data} handle={@} /> </div> show_screen_modal: (evt)-> action_id = jQuery(evt.target).closest('.action').data('id') action = @state.actions[action_id] @refs.screen_modal.setState action: action @refs.screen_modal.refs.table.setState linked_hmdms: action.linked_screen_ids || [] @refs.screen_modal.refs.modal.setState saving: false @refs.screen_modal.show() show_create_action_modal: -> action = id: null name: '' role: '柜员' post_action_ids: [] @refs.action_modal .set_action action .set_optional_actions {}, [] .show() show_update_action_modal: (evt)-> $a = jQuery evt.target $action = $a.closest('.action') id = $action.data('id') action = @state.actions[id] optional_actions = {} all_pres_action_ids = Object.keys @get_all_pres_actions action for a_id, _action of @state.actions if all_pres_action_ids.indexOf(_action.id) < 0 optional_actions[_action.id] = _action console.log action @refs.action_modal .set_action action .set_optional_actions optional_actions, action.post_action_ids || [] .show() # 获取所有直接前置节点 get_pre_actions: (action)-> pre_actions = {} for _id, _action of @state.actions if (_action.post_action_ids || []).indexOf(action.id) > -1 pre_actions[_action.id] = _action pre_actions get_all_pres_actions: (action)-> all_pres_actions = {} @_r_ga action, all_pres_actions all_pres_actions _r_ga: (action, all_pres_actions)-> all_pres_actions[action.id] = action for _id, _action of @get_pre_actions(action) @_r_ga _action, all_pres_actions hide_action_modal: -> @refs.action_modal.hide() hide_screen_modal: -> @refs.screen_modal.hide() submit: -> action = @refs.action_modal.get_action_data() actions = @state.actions actions[action.id] = action @save_actions actions remove_action: (evt, react_id)-> $btn = jQuery("[data-reactid='#{react_id}']") $action = $btn.closest('.action') id = $action.data('id') if confirm '确定要删除吗?' actions = @state.actions delete actions[id] # 从其他节点的后续节点中去掉 for _id, action of actions if action.post_action_ids? action.post_action_ids = action.post_action_ids.filter (x)-> x != id $action.fadeOut => @save_actions actions save_actions: (actions)-> @refs.action_modal.setState saving: true jQuery.ajax url: @props.update_url type: 'PUT' data: actions: actions .done (res)=> @hide_action_modal() @hide_screen_modal() @setState actions: actions jQuery(document).trigger 'editor:action-changed', actions .fail -> console.log 2
[ { "context": "###*\n chroma.js\n\n Copyright (c) 2011-2013, Gregor Aisch\n All rights reserved.\n\n Redistribution and ", "end": 61, "score": 0.9998905062675476, "start": 49, "tag": "NAME", "value": "Gregor Aisch" }, { "context": " OF SUCH DAMAGE.\n\n @source: https://github.com/gka/chroma.js\n###\n\n\nclass Color\n\n constructor: () ", "end": 1576, "score": 0.9947803020477295, "start": 1573, "tag": "USERNAME", "value": "gka" } ]
node_modules/chroma-js/src/color.coffee
balamurugan01/foundation6
49
###* chroma.js Copyright (c) 2011-2013, Gregor Aisch All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The name Gregor Aisch may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GREGOR AISCH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @source: https://github.com/gka/chroma.js ### class Color constructor: () -> me = @ args = [] for arg in arguments args.push arg if arg? if args.length == 0 # Color() [x,y,z,a,m] = [255,0,255,1,'rgb'] else if type(args[0]) == "array" # Color([255,0,0], 'rgb') # unpack array args if args[0].length == 3 [x,y,z] = args[0] a = 1 else if args[0].length == 4 [x,y,z,a] = args[0] else throw 'unknown input argument' m = args[1] ? 'rgb' else if type(args[0]) == "string" # Color('#ff0000') # named color, hex color, css color x = args[0] m = 'hex' else if type(args[0]) == "object" # Color(Color) [x,y,z,a] = args[0]._rgb m = 'rgb' else if args.length >= 3 x = args[0] y = args[1] z = args[2] if args.length == 3 m = 'rgb' a = 1 else if args.length == 4 if type(args[3]) == "string" m = args[3] a = 1 else if type(args[3]) == "number" m = 'rgb' a = args[3] else if args.length == 5 a = args[3] m = args[4] a ?= 1 # create color if m == 'rgb' me._rgb = [x,y,z,a] else if m == 'gl' me._rgb = [x*255,y*255,z*255,a] else if m == 'hsl' me._rgb = hsl2rgb x,y,z me._rgb[3] = a else if m == 'hsv' me._rgb = hsv2rgb x,y,z me._rgb[3] = a else if m == 'hex' me._rgb = hex2rgb x else if m == 'lab' me._rgb = lab2rgb x,y,z me._rgb[3] = a else if m == 'lch' me._rgb = lch2rgb x,y,z me._rgb[3] = a else if m == 'hsi' me._rgb = hsi2rgb x,y,z me._rgb[3] = a me_rgb = clip_rgb me._rgb rgb: -> @_rgb.slice 0,3 rgba: -> @_rgb hex: -> rgb2hex @_rgb toString: -> @name() hsl: -> rgb2hsl @_rgb hsv: -> rgb2hsv @_rgb lab: -> rgb2lab @_rgb lch: -> rgb2lch @_rgb hsi: -> rgb2hsi @_rgb gl: -> [@_rgb[0]/255, @_rgb[1]/255, @_rgb[2]/255, @_rgb[3]] luminance: (lum, mode='rgb') -> return luminance @_rgb if !arguments.length # set luminance if lum == 0 then @_rgb = [0,0,0,@_rgb[3]] if lum == 1 then @_rgb = [255,255,255,@_rgb[3]] cur_lum = luminance @_rgb eps = 1e-7 max_iter = 20 test = (l,h) -> m = l.interpolate(0.5, h, mode) lm = m.luminance() if Math.abs(lum - lm) < eps or not max_iter-- return m if lm > lum return test(l, m) return test(m, h) @_rgb = (if cur_lum > lum then test(new Color('black'), @) else test(@, new Color('white'))).rgba() @ name: -> h = @hex() for k of chroma.colors if h == chroma.colors[k] return k h alpha: (alpha) -> if arguments.length @_rgb[3] = alpha return @ @_rgb[3] css: (mode='rgb') -> me = @ rgb = me._rgb if mode.length == 3 and rgb[3] < 1 mode += 'a' if mode == 'rgb' mode+'('+rgb.slice(0,3).map(Math.round).join(',')+')' else if mode == 'rgba' mode+'('+rgb.slice(0,3).map(Math.round).join(',')+','+rgb[3]+')' else if mode == 'hsl' or mode == 'hsla' hsl = me.hsl() rnd = (a) -> Math.round(a*100)/100 hsl[0] = rnd(hsl[0]) hsl[1] = rnd(hsl[1]*100) + '%' hsl[2] = rnd(hsl[2]*100) + '%' if mode.length == 4 hsl[3] = rgb[3] mode + '(' + hsl.join(',') + ')' interpolate: (f, col, m) -> ### interpolates between colors f = 0 --> me f = 1 --> col ### me = @ m ?= 'rgb' col = new Color(col) if type(col) == "string" if m == 'hsl' or m == 'hsv' or m == 'lch' or m == 'hsi' if m == 'hsl' xyz0 = me.hsl() xyz1 = col.hsl() else if m == 'hsv' xyz0 = me.hsv() xyz1 = col.hsv() else if m == 'hsi' xyz0 = me.hsi() xyz1 = col.hsi() else if m == 'lch' xyz0 = me.lch() xyz1 = col.lch() if m.substr(0, 1) == 'h' [hue0, sat0, lbv0] = xyz0 [hue1, sat1, lbv1] = xyz1 else [lbv0, sat0, hue0] = xyz0 [lbv1, sat1, hue1] = xyz1 if not isNaN(hue0) and not isNaN(hue1) if hue1 > hue0 and hue1 - hue0 > 180 dh = hue1-(hue0+360) else if hue1 < hue0 and hue0 - hue1 > 180 dh = hue1+360-hue0 else dh = hue1 - hue0 hue = hue0+f*dh else if not isNaN(hue0) hue = hue0 sat = sat0 if (lbv1 == 1 or lbv1 == 0) and m != 'hsv' else if not isNaN(hue1) hue = hue1 sat = sat1 if (lbv0 == 1 or lbv0 == 0) and m != 'hsv' else hue = Number.NaN sat ?= sat0 + f*(sat1 - sat0) lbv = lbv0 + f*(lbv1-lbv0) if m.substr(0, 1) == 'h' res = new Color hue, sat, lbv, m else res = new Color lbv, sat, hue, m else if m == 'rgb' xyz0 = me._rgb xyz1 = col._rgb res = new Color( xyz0[0]+f*(xyz1[0]-xyz0[0]), xyz0[1] + f*(xyz1[1]-xyz0[1]), xyz0[2] + f*(xyz1[2]-xyz0[2]), m ) else if m == 'lab' xyz0 = me.lab() xyz1 = col.lab() res = new Color( xyz0[0]+f*(xyz1[0]-xyz0[0]), xyz0[1] + f*(xyz1[1]-xyz0[1]), xyz0[2] + f*(xyz1[2]-xyz0[2]), m ) else throw "color mode "+m+" is not supported" # interpolate alpha at last res.alpha me.alpha() + f * (col.alpha() - me.alpha()) res premultiply: -> rgb = @rgb() a = @alpha() chroma(rgb[0]*a, rgb[1]*a, rgb[2]*a, a) darken: (amount=20) -> me = @ lch = me.lch() lch[0] -= amount chroma.lch(lch).alpha(me.alpha()) darker: (amount) -> @darken amount brighten: (amount=20) -> @darken -amount brighter: (amount) -> @brighten amount saturate: (amount=20) -> me = @ lch = me.lch() lch[1] += amount chroma.lch(lch).alpha(me.alpha()) desaturate: (amount=20) -> @saturate -amount
68944
###* chroma.js Copyright (c) 2011-2013, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The name Gregor Aisch may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GREGOR AISCH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @source: https://github.com/gka/chroma.js ### class Color constructor: () -> me = @ args = [] for arg in arguments args.push arg if arg? if args.length == 0 # Color() [x,y,z,a,m] = [255,0,255,1,'rgb'] else if type(args[0]) == "array" # Color([255,0,0], 'rgb') # unpack array args if args[0].length == 3 [x,y,z] = args[0] a = 1 else if args[0].length == 4 [x,y,z,a] = args[0] else throw 'unknown input argument' m = args[1] ? 'rgb' else if type(args[0]) == "string" # Color('#ff0000') # named color, hex color, css color x = args[0] m = 'hex' else if type(args[0]) == "object" # Color(Color) [x,y,z,a] = args[0]._rgb m = 'rgb' else if args.length >= 3 x = args[0] y = args[1] z = args[2] if args.length == 3 m = 'rgb' a = 1 else if args.length == 4 if type(args[3]) == "string" m = args[3] a = 1 else if type(args[3]) == "number" m = 'rgb' a = args[3] else if args.length == 5 a = args[3] m = args[4] a ?= 1 # create color if m == 'rgb' me._rgb = [x,y,z,a] else if m == 'gl' me._rgb = [x*255,y*255,z*255,a] else if m == 'hsl' me._rgb = hsl2rgb x,y,z me._rgb[3] = a else if m == 'hsv' me._rgb = hsv2rgb x,y,z me._rgb[3] = a else if m == 'hex' me._rgb = hex2rgb x else if m == 'lab' me._rgb = lab2rgb x,y,z me._rgb[3] = a else if m == 'lch' me._rgb = lch2rgb x,y,z me._rgb[3] = a else if m == 'hsi' me._rgb = hsi2rgb x,y,z me._rgb[3] = a me_rgb = clip_rgb me._rgb rgb: -> @_rgb.slice 0,3 rgba: -> @_rgb hex: -> rgb2hex @_rgb toString: -> @name() hsl: -> rgb2hsl @_rgb hsv: -> rgb2hsv @_rgb lab: -> rgb2lab @_rgb lch: -> rgb2lch @_rgb hsi: -> rgb2hsi @_rgb gl: -> [@_rgb[0]/255, @_rgb[1]/255, @_rgb[2]/255, @_rgb[3]] luminance: (lum, mode='rgb') -> return luminance @_rgb if !arguments.length # set luminance if lum == 0 then @_rgb = [0,0,0,@_rgb[3]] if lum == 1 then @_rgb = [255,255,255,@_rgb[3]] cur_lum = luminance @_rgb eps = 1e-7 max_iter = 20 test = (l,h) -> m = l.interpolate(0.5, h, mode) lm = m.luminance() if Math.abs(lum - lm) < eps or not max_iter-- return m if lm > lum return test(l, m) return test(m, h) @_rgb = (if cur_lum > lum then test(new Color('black'), @) else test(@, new Color('white'))).rgba() @ name: -> h = @hex() for k of chroma.colors if h == chroma.colors[k] return k h alpha: (alpha) -> if arguments.length @_rgb[3] = alpha return @ @_rgb[3] css: (mode='rgb') -> me = @ rgb = me._rgb if mode.length == 3 and rgb[3] < 1 mode += 'a' if mode == 'rgb' mode+'('+rgb.slice(0,3).map(Math.round).join(',')+')' else if mode == 'rgba' mode+'('+rgb.slice(0,3).map(Math.round).join(',')+','+rgb[3]+')' else if mode == 'hsl' or mode == 'hsla' hsl = me.hsl() rnd = (a) -> Math.round(a*100)/100 hsl[0] = rnd(hsl[0]) hsl[1] = rnd(hsl[1]*100) + '%' hsl[2] = rnd(hsl[2]*100) + '%' if mode.length == 4 hsl[3] = rgb[3] mode + '(' + hsl.join(',') + ')' interpolate: (f, col, m) -> ### interpolates between colors f = 0 --> me f = 1 --> col ### me = @ m ?= 'rgb' col = new Color(col) if type(col) == "string" if m == 'hsl' or m == 'hsv' or m == 'lch' or m == 'hsi' if m == 'hsl' xyz0 = me.hsl() xyz1 = col.hsl() else if m == 'hsv' xyz0 = me.hsv() xyz1 = col.hsv() else if m == 'hsi' xyz0 = me.hsi() xyz1 = col.hsi() else if m == 'lch' xyz0 = me.lch() xyz1 = col.lch() if m.substr(0, 1) == 'h' [hue0, sat0, lbv0] = xyz0 [hue1, sat1, lbv1] = xyz1 else [lbv0, sat0, hue0] = xyz0 [lbv1, sat1, hue1] = xyz1 if not isNaN(hue0) and not isNaN(hue1) if hue1 > hue0 and hue1 - hue0 > 180 dh = hue1-(hue0+360) else if hue1 < hue0 and hue0 - hue1 > 180 dh = hue1+360-hue0 else dh = hue1 - hue0 hue = hue0+f*dh else if not isNaN(hue0) hue = hue0 sat = sat0 if (lbv1 == 1 or lbv1 == 0) and m != 'hsv' else if not isNaN(hue1) hue = hue1 sat = sat1 if (lbv0 == 1 or lbv0 == 0) and m != 'hsv' else hue = Number.NaN sat ?= sat0 + f*(sat1 - sat0) lbv = lbv0 + f*(lbv1-lbv0) if m.substr(0, 1) == 'h' res = new Color hue, sat, lbv, m else res = new Color lbv, sat, hue, m else if m == 'rgb' xyz0 = me._rgb xyz1 = col._rgb res = new Color( xyz0[0]+f*(xyz1[0]-xyz0[0]), xyz0[1] + f*(xyz1[1]-xyz0[1]), xyz0[2] + f*(xyz1[2]-xyz0[2]), m ) else if m == 'lab' xyz0 = me.lab() xyz1 = col.lab() res = new Color( xyz0[0]+f*(xyz1[0]-xyz0[0]), xyz0[1] + f*(xyz1[1]-xyz0[1]), xyz0[2] + f*(xyz1[2]-xyz0[2]), m ) else throw "color mode "+m+" is not supported" # interpolate alpha at last res.alpha me.alpha() + f * (col.alpha() - me.alpha()) res premultiply: -> rgb = @rgb() a = @alpha() chroma(rgb[0]*a, rgb[1]*a, rgb[2]*a, a) darken: (amount=20) -> me = @ lch = me.lch() lch[0] -= amount chroma.lch(lch).alpha(me.alpha()) darker: (amount) -> @darken amount brighten: (amount=20) -> @darken -amount brighter: (amount) -> @brighten amount saturate: (amount=20) -> me = @ lch = me.lch() lch[1] += amount chroma.lch(lch).alpha(me.alpha()) desaturate: (amount=20) -> @saturate -amount
true
###* chroma.js Copyright (c) 2011-2013, PI:NAME:<NAME>END_PI All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The name Gregor Aisch may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GREGOR AISCH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @source: https://github.com/gka/chroma.js ### class Color constructor: () -> me = @ args = [] for arg in arguments args.push arg if arg? if args.length == 0 # Color() [x,y,z,a,m] = [255,0,255,1,'rgb'] else if type(args[0]) == "array" # Color([255,0,0], 'rgb') # unpack array args if args[0].length == 3 [x,y,z] = args[0] a = 1 else if args[0].length == 4 [x,y,z,a] = args[0] else throw 'unknown input argument' m = args[1] ? 'rgb' else if type(args[0]) == "string" # Color('#ff0000') # named color, hex color, css color x = args[0] m = 'hex' else if type(args[0]) == "object" # Color(Color) [x,y,z,a] = args[0]._rgb m = 'rgb' else if args.length >= 3 x = args[0] y = args[1] z = args[2] if args.length == 3 m = 'rgb' a = 1 else if args.length == 4 if type(args[3]) == "string" m = args[3] a = 1 else if type(args[3]) == "number" m = 'rgb' a = args[3] else if args.length == 5 a = args[3] m = args[4] a ?= 1 # create color if m == 'rgb' me._rgb = [x,y,z,a] else if m == 'gl' me._rgb = [x*255,y*255,z*255,a] else if m == 'hsl' me._rgb = hsl2rgb x,y,z me._rgb[3] = a else if m == 'hsv' me._rgb = hsv2rgb x,y,z me._rgb[3] = a else if m == 'hex' me._rgb = hex2rgb x else if m == 'lab' me._rgb = lab2rgb x,y,z me._rgb[3] = a else if m == 'lch' me._rgb = lch2rgb x,y,z me._rgb[3] = a else if m == 'hsi' me._rgb = hsi2rgb x,y,z me._rgb[3] = a me_rgb = clip_rgb me._rgb rgb: -> @_rgb.slice 0,3 rgba: -> @_rgb hex: -> rgb2hex @_rgb toString: -> @name() hsl: -> rgb2hsl @_rgb hsv: -> rgb2hsv @_rgb lab: -> rgb2lab @_rgb lch: -> rgb2lch @_rgb hsi: -> rgb2hsi @_rgb gl: -> [@_rgb[0]/255, @_rgb[1]/255, @_rgb[2]/255, @_rgb[3]] luminance: (lum, mode='rgb') -> return luminance @_rgb if !arguments.length # set luminance if lum == 0 then @_rgb = [0,0,0,@_rgb[3]] if lum == 1 then @_rgb = [255,255,255,@_rgb[3]] cur_lum = luminance @_rgb eps = 1e-7 max_iter = 20 test = (l,h) -> m = l.interpolate(0.5, h, mode) lm = m.luminance() if Math.abs(lum - lm) < eps or not max_iter-- return m if lm > lum return test(l, m) return test(m, h) @_rgb = (if cur_lum > lum then test(new Color('black'), @) else test(@, new Color('white'))).rgba() @ name: -> h = @hex() for k of chroma.colors if h == chroma.colors[k] return k h alpha: (alpha) -> if arguments.length @_rgb[3] = alpha return @ @_rgb[3] css: (mode='rgb') -> me = @ rgb = me._rgb if mode.length == 3 and rgb[3] < 1 mode += 'a' if mode == 'rgb' mode+'('+rgb.slice(0,3).map(Math.round).join(',')+')' else if mode == 'rgba' mode+'('+rgb.slice(0,3).map(Math.round).join(',')+','+rgb[3]+')' else if mode == 'hsl' or mode == 'hsla' hsl = me.hsl() rnd = (a) -> Math.round(a*100)/100 hsl[0] = rnd(hsl[0]) hsl[1] = rnd(hsl[1]*100) + '%' hsl[2] = rnd(hsl[2]*100) + '%' if mode.length == 4 hsl[3] = rgb[3] mode + '(' + hsl.join(',') + ')' interpolate: (f, col, m) -> ### interpolates between colors f = 0 --> me f = 1 --> col ### me = @ m ?= 'rgb' col = new Color(col) if type(col) == "string" if m == 'hsl' or m == 'hsv' or m == 'lch' or m == 'hsi' if m == 'hsl' xyz0 = me.hsl() xyz1 = col.hsl() else if m == 'hsv' xyz0 = me.hsv() xyz1 = col.hsv() else if m == 'hsi' xyz0 = me.hsi() xyz1 = col.hsi() else if m == 'lch' xyz0 = me.lch() xyz1 = col.lch() if m.substr(0, 1) == 'h' [hue0, sat0, lbv0] = xyz0 [hue1, sat1, lbv1] = xyz1 else [lbv0, sat0, hue0] = xyz0 [lbv1, sat1, hue1] = xyz1 if not isNaN(hue0) and not isNaN(hue1) if hue1 > hue0 and hue1 - hue0 > 180 dh = hue1-(hue0+360) else if hue1 < hue0 and hue0 - hue1 > 180 dh = hue1+360-hue0 else dh = hue1 - hue0 hue = hue0+f*dh else if not isNaN(hue0) hue = hue0 sat = sat0 if (lbv1 == 1 or lbv1 == 0) and m != 'hsv' else if not isNaN(hue1) hue = hue1 sat = sat1 if (lbv0 == 1 or lbv0 == 0) and m != 'hsv' else hue = Number.NaN sat ?= sat0 + f*(sat1 - sat0) lbv = lbv0 + f*(lbv1-lbv0) if m.substr(0, 1) == 'h' res = new Color hue, sat, lbv, m else res = new Color lbv, sat, hue, m else if m == 'rgb' xyz0 = me._rgb xyz1 = col._rgb res = new Color( xyz0[0]+f*(xyz1[0]-xyz0[0]), xyz0[1] + f*(xyz1[1]-xyz0[1]), xyz0[2] + f*(xyz1[2]-xyz0[2]), m ) else if m == 'lab' xyz0 = me.lab() xyz1 = col.lab() res = new Color( xyz0[0]+f*(xyz1[0]-xyz0[0]), xyz0[1] + f*(xyz1[1]-xyz0[1]), xyz0[2] + f*(xyz1[2]-xyz0[2]), m ) else throw "color mode "+m+" is not supported" # interpolate alpha at last res.alpha me.alpha() + f * (col.alpha() - me.alpha()) res premultiply: -> rgb = @rgb() a = @alpha() chroma(rgb[0]*a, rgb[1]*a, rgb[2]*a, a) darken: (amount=20) -> me = @ lch = me.lch() lch[0] -= amount chroma.lch(lch).alpha(me.alpha()) darker: (amount) -> @darken amount brighten: (amount=20) -> @darken -amount brighter: (amount) -> @brighten amount saturate: (amount=20) -> me = @ lch = me.lch() lch[1] += amount chroma.lch(lch).alpha(me.alpha()) desaturate: (amount=20) -> @saturate -amount
[ { "context": "= (person) ->\n alert \"Hello #{person}\"\n\nhello \"Esteban\"\n", "end": 63, "score": 0.9997143745422363, "start": 56, "tag": "NAME", "value": "Esteban" } ]
test/example/script.coffee
debrouwere/draughtsman
3
hello = (person) -> alert "Hello #{person}" hello "Esteban"
62436
hello = (person) -> alert "Hello #{person}" hello "<NAME>"
true
hello = (person) -> alert "Hello #{person}" hello "PI:NAME:<NAME>END_PI"
[ { "context": "that attribute\n\nBased on Spine-Attribute-Events by Mitch Lloyd\nhttps://github.com/mitchlloyd/Spine-Attribute-Eve", "end": 163, "score": 0.999906063079834, "start": 152, "tag": "NAME", "value": "Mitch Lloyd" }, { "context": "ttribute-Events by Mitch Lloyd\nhttps://github.com/mitchlloyd/Spine-Attribute-Events\n###\n\n_ = require \"undersco", "end": 193, "score": 0.9995899200439453, "start": 183, "tag": "USERNAME", "value": "mitchlloyd" } ]
app/lib/updateAttr.coffee
gzferrar/Nitro
1
### Trigger updateAttr on model with the attribute that was modified and the new and old versions of that attribute Based on Spine-Attribute-Events by Mitch Lloyd https://github.com/mitchlloyd/Spine-Attribute-Events ### _ = require "underscore" ClassMethods = # Clone model setAttributesSnapshot: (model) -> data = model.toJSON() # Clone arrays for k, v of data if v instanceof Array data[k] = v.slice(0) @_attributesSnapshots[model.cid] = data # Return clone getAttributesSnapshot: (model) -> @_attributesSnapshots[model.cid] AttributeTracking = extended: -> @_attributesSnapshots = {} @bind 'refresh create', (models) => # Spine is a little quirky with refresh({clear: true}) and passes false. # So we need this fix for now. models or= @all() # models could be an array of models or one model. if models.length? @setAttributesSnapshot(model) for model in models else @setAttributesSnapshot(models) @bind 'update', (model, options) => for key, value of model.attributes() old = @getAttributesSnapshot(model)[key] unless _.isEqual(old, value) model.trigger "updateAttr", key, value, old, options model.trigger "update:#{key}", value, old, options @setAttributesSnapshot(model) @extend ClassMethods Spine?.AttributeTracking = AttributeTracking module?.exports = AttributeTracking
102904
### Trigger updateAttr on model with the attribute that was modified and the new and old versions of that attribute Based on Spine-Attribute-Events by <NAME> https://github.com/mitchlloyd/Spine-Attribute-Events ### _ = require "underscore" ClassMethods = # Clone model setAttributesSnapshot: (model) -> data = model.toJSON() # Clone arrays for k, v of data if v instanceof Array data[k] = v.slice(0) @_attributesSnapshots[model.cid] = data # Return clone getAttributesSnapshot: (model) -> @_attributesSnapshots[model.cid] AttributeTracking = extended: -> @_attributesSnapshots = {} @bind 'refresh create', (models) => # Spine is a little quirky with refresh({clear: true}) and passes false. # So we need this fix for now. models or= @all() # models could be an array of models or one model. if models.length? @setAttributesSnapshot(model) for model in models else @setAttributesSnapshot(models) @bind 'update', (model, options) => for key, value of model.attributes() old = @getAttributesSnapshot(model)[key] unless _.isEqual(old, value) model.trigger "updateAttr", key, value, old, options model.trigger "update:#{key}", value, old, options @setAttributesSnapshot(model) @extend ClassMethods Spine?.AttributeTracking = AttributeTracking module?.exports = AttributeTracking
true
### Trigger updateAttr on model with the attribute that was modified and the new and old versions of that attribute Based on Spine-Attribute-Events by PI:NAME:<NAME>END_PI https://github.com/mitchlloyd/Spine-Attribute-Events ### _ = require "underscore" ClassMethods = # Clone model setAttributesSnapshot: (model) -> data = model.toJSON() # Clone arrays for k, v of data if v instanceof Array data[k] = v.slice(0) @_attributesSnapshots[model.cid] = data # Return clone getAttributesSnapshot: (model) -> @_attributesSnapshots[model.cid] AttributeTracking = extended: -> @_attributesSnapshots = {} @bind 'refresh create', (models) => # Spine is a little quirky with refresh({clear: true}) and passes false. # So we need this fix for now. models or= @all() # models could be an array of models or one model. if models.length? @setAttributesSnapshot(model) for model in models else @setAttributesSnapshot(models) @bind 'update', (model, options) => for key, value of model.attributes() old = @getAttributesSnapshot(model)[key] unless _.isEqual(old, value) model.trigger "updateAttr", key, value, old, options model.trigger "update:#{key}", value, old, options @setAttributesSnapshot(model) @extend ClassMethods Spine?.AttributeTracking = AttributeTracking module?.exports = AttributeTracking
[ { "context": "m) ->\n chances = [1, 5, 10, 20, 100]\n keys = [@t4, @t3, @t2, @t1, @t0]\n validKeysToChoose = _.compact _.map keys, (ke", "end": 3848, "score": 0.990965723991394, "start": 3823, "tag": "KEY", "value": "[@t4, @t3, @t2, @t1, @t0]" } ]
src/event/Event.coffee
sadbear-/IdleLands
0
chance = new (require "chance")() MessageCreator = require "../system/MessageCreator" Constants = require "../system/Constants" _ = require "lodash" class Event constructor: (@game, @event, @player) -> calcXpEventGain: (eventType, player) -> if (chance.bool {likelihood: player.calculateYesPercent()}) percent = Constants.eventEffects[eventType].fail if player.level.getValue() < 100 then Math.floor player.xp.maximum * (percent/100) else 1 else min = Constants.eventEffects[eventType].minPercent max = Constants.eventEffects[eventType].maxPercent flux = Constants.eventEffects[eventType].flux step = player.level.maximum / (max - min) steps = Math.floor ((player.level.maximum - player.level.getValue()) / step) fluxed = chance.floating {min: -flux, max: flux, fixed: 3} percent = min + steps + fluxed if player.level.getValue() < 100 then Math.floor player.xp.maximum * (percent/100) else player.level.getValue() grantRapportForAllPlayers: (party, bonus) -> _.each party.players, (player) -> _.each party.players, (playerTwo) -> return if player is playerTwo return if playerTwo.isMonster player.modifyRelationshipWith playerTwo.name, bonus calcGoldEventGain: (eventType, player) -> goldTiers = Constants.eventEffects[eventType].amount curGold = player.gold.getValue() boost = 0 for i in [0...goldTiers.length] if curGold < Math.abs goldTiers[i] highVal = if not goldTiers[i-1] then 100 else goldTiers[i-1] lowVal = if not goldTiers[i] then 1 else goldTiers[i] min = Math.min highVal, lowVal max = Math.max highVal, lowVal boost = chance.integer {min: min, max: max} break if not boost val = _.last goldTiers min = Math.min val, 0 max = Math.max val, 1 boost = chance.integer min: min, max: max boost ignoreKeys: ['_calcScore', 'enchantLevel'] specialStats: [ 'absolute' 'aegis' 'crit' 'dance' 'deadeye' 'defense' 'glowing' 'haste' 'lethal' 'poison' 'power' 'prone' 'offense' 'royal' 'shatter' 'silver' 'sturdy' 'vampire' 'venom' 'vorpal' 'startle' 'fear' 'parry' 'punish' 'darkside' 'forsaken' 'limitless' 'sacred' 'sentimentality' ] t0: ['int', 'str', 'dex', 'con', 'wis', 'agi'] t1: ['intPercent', 'strPercent', 'conPercent', 'wisPercent', 'agiPercent'] t2: ['gold', 'xp', 'hp', 'mp'] t3: ['goldPercent', 'xpPercent', 'hpPercent', 'mpPercent', 'luck'] t4: ['luckPercent'] allValidStats: -> @t0.concat @t1.concat @t2.concat @t3.concat @t4 pickStatPresentOnItem: (item, base = @allValidStats()) -> nonZeroStats = _.reject (_.keys item), (stat) -> item[stat] is 0 or _.isNaN item[stat] statsInBoth = _.intersection base, nonZeroStats _.sample statsInBoth pickStatNotPresentOnItem: (item, base = @allValidStats()) -> zeroStats = _.filter (_.keys item), (stat) -> item[stat] is 0 statsMissing = _.intersection base, zeroStats _.sample statsMissing pickSpecialNotPresentOnItem: (item, base = @specialStats) -> statsMissing = _.reject @specialStats, (stat) -> item[stat]? _.sample statsMissing pickValidItem: (player, isEnchant = no) -> items = player.equipment forsaken = _.findWhere items, {forsaken: 1} return forsaken if forsaken nonSacred = _.reject items, (item) -> item.sacred badSlots = _.reject nonSacred, (item) -> item.type in ["providence"] if isEnchant then badSlots = _.reject badSlots, (item) -> item.enchantLevel >= Constants.defaults.game.maxEnchantLevel and not item.limitless _.sample badSlots pickBlessStat: (item) -> chances = [1, 5, 10, 20, 100] keys = [@t4, @t3, @t2, @t1, @t0] validKeysToChoose = _.compact _.map keys, (keyList) => @pickStatPresentOnItem item, keyList return '' if validKeysToChoose.length is 0 chances = chances[-validKeysToChoose.length..] retStat = '' for i in [0..validKeysToChoose.length] if chance.bool {likelihood: chances[i]} retStat = validKeysToChoose[i] break retStat module.exports = exports = Event
6182
chance = new (require "chance")() MessageCreator = require "../system/MessageCreator" Constants = require "../system/Constants" _ = require "lodash" class Event constructor: (@game, @event, @player) -> calcXpEventGain: (eventType, player) -> if (chance.bool {likelihood: player.calculateYesPercent()}) percent = Constants.eventEffects[eventType].fail if player.level.getValue() < 100 then Math.floor player.xp.maximum * (percent/100) else 1 else min = Constants.eventEffects[eventType].minPercent max = Constants.eventEffects[eventType].maxPercent flux = Constants.eventEffects[eventType].flux step = player.level.maximum / (max - min) steps = Math.floor ((player.level.maximum - player.level.getValue()) / step) fluxed = chance.floating {min: -flux, max: flux, fixed: 3} percent = min + steps + fluxed if player.level.getValue() < 100 then Math.floor player.xp.maximum * (percent/100) else player.level.getValue() grantRapportForAllPlayers: (party, bonus) -> _.each party.players, (player) -> _.each party.players, (playerTwo) -> return if player is playerTwo return if playerTwo.isMonster player.modifyRelationshipWith playerTwo.name, bonus calcGoldEventGain: (eventType, player) -> goldTiers = Constants.eventEffects[eventType].amount curGold = player.gold.getValue() boost = 0 for i in [0...goldTiers.length] if curGold < Math.abs goldTiers[i] highVal = if not goldTiers[i-1] then 100 else goldTiers[i-1] lowVal = if not goldTiers[i] then 1 else goldTiers[i] min = Math.min highVal, lowVal max = Math.max highVal, lowVal boost = chance.integer {min: min, max: max} break if not boost val = _.last goldTiers min = Math.min val, 0 max = Math.max val, 1 boost = chance.integer min: min, max: max boost ignoreKeys: ['_calcScore', 'enchantLevel'] specialStats: [ 'absolute' 'aegis' 'crit' 'dance' 'deadeye' 'defense' 'glowing' 'haste' 'lethal' 'poison' 'power' 'prone' 'offense' 'royal' 'shatter' 'silver' 'sturdy' 'vampire' 'venom' 'vorpal' 'startle' 'fear' 'parry' 'punish' 'darkside' 'forsaken' 'limitless' 'sacred' 'sentimentality' ] t0: ['int', 'str', 'dex', 'con', 'wis', 'agi'] t1: ['intPercent', 'strPercent', 'conPercent', 'wisPercent', 'agiPercent'] t2: ['gold', 'xp', 'hp', 'mp'] t3: ['goldPercent', 'xpPercent', 'hpPercent', 'mpPercent', 'luck'] t4: ['luckPercent'] allValidStats: -> @t0.concat @t1.concat @t2.concat @t3.concat @t4 pickStatPresentOnItem: (item, base = @allValidStats()) -> nonZeroStats = _.reject (_.keys item), (stat) -> item[stat] is 0 or _.isNaN item[stat] statsInBoth = _.intersection base, nonZeroStats _.sample statsInBoth pickStatNotPresentOnItem: (item, base = @allValidStats()) -> zeroStats = _.filter (_.keys item), (stat) -> item[stat] is 0 statsMissing = _.intersection base, zeroStats _.sample statsMissing pickSpecialNotPresentOnItem: (item, base = @specialStats) -> statsMissing = _.reject @specialStats, (stat) -> item[stat]? _.sample statsMissing pickValidItem: (player, isEnchant = no) -> items = player.equipment forsaken = _.findWhere items, {forsaken: 1} return forsaken if forsaken nonSacred = _.reject items, (item) -> item.sacred badSlots = _.reject nonSacred, (item) -> item.type in ["providence"] if isEnchant then badSlots = _.reject badSlots, (item) -> item.enchantLevel >= Constants.defaults.game.maxEnchantLevel and not item.limitless _.sample badSlots pickBlessStat: (item) -> chances = [1, 5, 10, 20, 100] keys = <KEY> validKeysToChoose = _.compact _.map keys, (keyList) => @pickStatPresentOnItem item, keyList return '' if validKeysToChoose.length is 0 chances = chances[-validKeysToChoose.length..] retStat = '' for i in [0..validKeysToChoose.length] if chance.bool {likelihood: chances[i]} retStat = validKeysToChoose[i] break retStat module.exports = exports = Event
true
chance = new (require "chance")() MessageCreator = require "../system/MessageCreator" Constants = require "../system/Constants" _ = require "lodash" class Event constructor: (@game, @event, @player) -> calcXpEventGain: (eventType, player) -> if (chance.bool {likelihood: player.calculateYesPercent()}) percent = Constants.eventEffects[eventType].fail if player.level.getValue() < 100 then Math.floor player.xp.maximum * (percent/100) else 1 else min = Constants.eventEffects[eventType].minPercent max = Constants.eventEffects[eventType].maxPercent flux = Constants.eventEffects[eventType].flux step = player.level.maximum / (max - min) steps = Math.floor ((player.level.maximum - player.level.getValue()) / step) fluxed = chance.floating {min: -flux, max: flux, fixed: 3} percent = min + steps + fluxed if player.level.getValue() < 100 then Math.floor player.xp.maximum * (percent/100) else player.level.getValue() grantRapportForAllPlayers: (party, bonus) -> _.each party.players, (player) -> _.each party.players, (playerTwo) -> return if player is playerTwo return if playerTwo.isMonster player.modifyRelationshipWith playerTwo.name, bonus calcGoldEventGain: (eventType, player) -> goldTiers = Constants.eventEffects[eventType].amount curGold = player.gold.getValue() boost = 0 for i in [0...goldTiers.length] if curGold < Math.abs goldTiers[i] highVal = if not goldTiers[i-1] then 100 else goldTiers[i-1] lowVal = if not goldTiers[i] then 1 else goldTiers[i] min = Math.min highVal, lowVal max = Math.max highVal, lowVal boost = chance.integer {min: min, max: max} break if not boost val = _.last goldTiers min = Math.min val, 0 max = Math.max val, 1 boost = chance.integer min: min, max: max boost ignoreKeys: ['_calcScore', 'enchantLevel'] specialStats: [ 'absolute' 'aegis' 'crit' 'dance' 'deadeye' 'defense' 'glowing' 'haste' 'lethal' 'poison' 'power' 'prone' 'offense' 'royal' 'shatter' 'silver' 'sturdy' 'vampire' 'venom' 'vorpal' 'startle' 'fear' 'parry' 'punish' 'darkside' 'forsaken' 'limitless' 'sacred' 'sentimentality' ] t0: ['int', 'str', 'dex', 'con', 'wis', 'agi'] t1: ['intPercent', 'strPercent', 'conPercent', 'wisPercent', 'agiPercent'] t2: ['gold', 'xp', 'hp', 'mp'] t3: ['goldPercent', 'xpPercent', 'hpPercent', 'mpPercent', 'luck'] t4: ['luckPercent'] allValidStats: -> @t0.concat @t1.concat @t2.concat @t3.concat @t4 pickStatPresentOnItem: (item, base = @allValidStats()) -> nonZeroStats = _.reject (_.keys item), (stat) -> item[stat] is 0 or _.isNaN item[stat] statsInBoth = _.intersection base, nonZeroStats _.sample statsInBoth pickStatNotPresentOnItem: (item, base = @allValidStats()) -> zeroStats = _.filter (_.keys item), (stat) -> item[stat] is 0 statsMissing = _.intersection base, zeroStats _.sample statsMissing pickSpecialNotPresentOnItem: (item, base = @specialStats) -> statsMissing = _.reject @specialStats, (stat) -> item[stat]? _.sample statsMissing pickValidItem: (player, isEnchant = no) -> items = player.equipment forsaken = _.findWhere items, {forsaken: 1} return forsaken if forsaken nonSacred = _.reject items, (item) -> item.sacred badSlots = _.reject nonSacred, (item) -> item.type in ["providence"] if isEnchant then badSlots = _.reject badSlots, (item) -> item.enchantLevel >= Constants.defaults.game.maxEnchantLevel and not item.limitless _.sample badSlots pickBlessStat: (item) -> chances = [1, 5, 10, 20, 100] keys = PI:KEY:<KEY>END_PI validKeysToChoose = _.compact _.map keys, (keyList) => @pickStatPresentOnItem item, keyList return '' if validKeysToChoose.length is 0 chances = chances[-validKeysToChoose.length..] retStat = '' for i in [0..validKeysToChoose.length] if chance.bool {likelihood: chances[i]} retStat = validKeysToChoose[i] break retStat module.exports = exports = Event
[ { "context": "leoverview Tests for concise-object rule\n# @author Jamund Ferguson <http://www.jamund.com>\n###\n\n'use strict'\n\n#-----", "end": 76, "score": 0.9998776316642761, "start": 61, "tag": "NAME", "value": "Jamund Ferguson" } ]
src/tests/rules/object-shorthand.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for concise-object rule # @author Jamund Ferguson <http://www.jamund.com> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/object-shorthand' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ PROPERTY_ERROR = message: 'Expected property shorthand.', type: 'Property' LONGFORM_PROPERTY_ERROR = message: 'Expected longform property syntax.', type: 'Property' ALL_SHORTHAND_ERROR = message: 'Expected shorthand for all properties.', type: 'ObjectExpression' MIXED_SHORTHAND_ERROR = message: 'Unexpected mix of shorthand and non-shorthand properties.' type: 'ObjectExpression' ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'object-shorthand', rule, valid: [ 'x = y: ->' 'x = {y}' 'x = {a: b}' "x = {a: 'a'}" "x = {'a': 'a'}" "x = {'a': b}" 'x = {y: (x) ->}' '{x,y,z} = x' '{x: {y}} = z' 'x = {x: y}' 'x = {x: y, y: z}' "x = {x: y, y: z, z: 'z'}" 'x = {x: ->, y: z, l: ->}' 'x = {x: y, y: z, a: b}' "x = {x: y, y: z, 'a': b}" 'x = {x: y, y: ->, z: a}' 'x = {[y]: y}' 'doSomething({x: y})' "doSomething({'x': y})" "doSomething({x: 'x'})" "doSomething({'x': 'x'})" 'doSomething({y: ->})' 'doSomething({x: y, y: ->})' 'doSomething({y: ->, z: a})' '!{ a: -> }' # # getters and setters are ok # 'var x = {get y() {}}' # 'var x = {set y(z) {}}' # 'var x = {get y() {}, set y(z) {}}' # 'doSomething({get y() {}})' # 'doSomething({set y(z) {}})' # 'doSomething({get y() {}, set y(z) {}})' # object literal computed properties 'x = {[y]: y}' "x = {['y']: 'y'}" "x = {['y']: y}" 'x = {y}' 'x = {y: {b}}' , code: 'x = {a: n, c: d, f: g}' options: ['never'] , code: 'x = {a: ->, b: {c: d}}' options: ['never'] , # avoidQuotes code: "x = 'a': ->" options: ['always', {avoidQuotes: yes}] , code: "x = ['a']: ->" options: ['always', {avoidQuotes: yes}] , code: "'y': y" options: ['always', {avoidQuotes: yes}] , # ignore object shorthand code: '{a, b} = o' options: ['never'] , code: 'x = {foo: foo, bar: bar, ...baz}' options: ['never'] , # consistent code: 'x = {a: a, b: b}' options: ['consistent'] , code: 'x = {a: b, c: d, f: g}' options: ['consistent'] , code: 'x = {a, b}' options: ['consistent'] , # , # code: 'x = {a, b, get test() { return 1; }}' # options: ['consistent'] code: 'x = {...bar}' options: ['consistent-as-needed'] , code: 'x = {foo, bar, ...baz}' options: ['consistent'] , code: 'x = {bar: baz, ...qux}' options: ['consistent'] , code: 'x = {...foo, bar: bar, baz: baz}' options: ['consistent'] , # consistent-as-needed code: 'x = {a, b}' options: ['consistent-as-needed'] , # , # code: 'x = {a, b, get test(){return 1;}}' # options: ['consistent-as-needed'] code: "x = {0: 'foo'}" options: ['consistent-as-needed'] , code: "x = {'key': 'baz'}" options: ['consistent-as-needed'] , code: "x = {foo: 'foo'}" options: ['consistent-as-needed'] , code: 'x = {[foo]: foo}' options: ['consistent-as-needed'] , code: 'x = {foo: ->}' options: ['consistent-as-needed'] , code: "x = {[foo]: 'foo'}" options: ['consistent-as-needed'] , code: 'x = {bar, ...baz}' options: ['consistent-as-needed'] , code: 'x = {bar: baz, ...qux}' options: ['consistent-as-needed'] , code: 'x = {...foo, bar, baz}' options: ['consistent-as-needed'] ] invalid: [ code: 'x = {x: x}' errors: [PROPERTY_ERROR] , code: "x = {'x': x}" errors: [PROPERTY_ERROR] , code: 'x = {y: y, x: x}' errors: [PROPERTY_ERROR, PROPERTY_ERROR] , code: 'x = {y: z, x: x, a: b}' errors: [PROPERTY_ERROR] , code: ''' x = { y: z x: x a: b # comment } ''' errors: [PROPERTY_ERROR] , code: ''' x = { a: b ### comment ### y: y } ''' errors: [PROPERTY_ERROR] , code: 'x = {x: y, y: z, a: a}' errors: [PROPERTY_ERROR] , code: 'doSomething({x: x})' errors: [PROPERTY_ERROR] , code: "doSomething({'x': x})" errors: [PROPERTY_ERROR] , code: "doSomething({a: 'a', 'x': x})" errors: [PROPERTY_ERROR] , code: 'x = {y}' options: ['never'] errors: [LONGFORM_PROPERTY_ERROR] , code: 'x = {y: {x}}' options: ['never'] errors: [LONGFORM_PROPERTY_ERROR] , code: 'x = {foo: foo, bar: baz, ...qux}' options: ['always'] errors: [PROPERTY_ERROR] , code: 'x = {foo, bar: baz, ...qux}' options: ['never'] errors: [LONGFORM_PROPERTY_ERROR] , # avoidQuotes code: 'x = {a: a}' options: ['always', {avoidQuotes: yes}] errors: [PROPERTY_ERROR] , # consistent code: 'x = {a: a, b}' options: ['consistent'] errors: [MIXED_SHORTHAND_ERROR] , code: 'x = {b, c: d, f: g}' options: ['consistent'] errors: [MIXED_SHORTHAND_ERROR] , code: 'x = {foo, bar: baz, ...qux}' options: ['consistent'] errors: [MIXED_SHORTHAND_ERROR] , # consistent-as-needed code: 'x = {a: a, b: b}' options: ['consistent-as-needed'] errors: [ALL_SHORTHAND_ERROR] , code: 'x = {a: a, b: b, ...baz}' options: ['consistent-as-needed'] errors: [ALL_SHORTHAND_ERROR] , code: 'x = {foo, bar: bar, ...qux}' options: ['consistent-as-needed'] errors: [MIXED_SHORTHAND_ERROR] , code: 'x = {a, z: ->}' options: ['consistent-as-needed'] errors: [MIXED_SHORTHAND_ERROR] ]
224595
###* # @fileoverview Tests for concise-object rule # @author <NAME> <http://www.jamund.com> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/object-shorthand' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ PROPERTY_ERROR = message: 'Expected property shorthand.', type: 'Property' LONGFORM_PROPERTY_ERROR = message: 'Expected longform property syntax.', type: 'Property' ALL_SHORTHAND_ERROR = message: 'Expected shorthand for all properties.', type: 'ObjectExpression' MIXED_SHORTHAND_ERROR = message: 'Unexpected mix of shorthand and non-shorthand properties.' type: 'ObjectExpression' ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'object-shorthand', rule, valid: [ 'x = y: ->' 'x = {y}' 'x = {a: b}' "x = {a: 'a'}" "x = {'a': 'a'}" "x = {'a': b}" 'x = {y: (x) ->}' '{x,y,z} = x' '{x: {y}} = z' 'x = {x: y}' 'x = {x: y, y: z}' "x = {x: y, y: z, z: 'z'}" 'x = {x: ->, y: z, l: ->}' 'x = {x: y, y: z, a: b}' "x = {x: y, y: z, 'a': b}" 'x = {x: y, y: ->, z: a}' 'x = {[y]: y}' 'doSomething({x: y})' "doSomething({'x': y})" "doSomething({x: 'x'})" "doSomething({'x': 'x'})" 'doSomething({y: ->})' 'doSomething({x: y, y: ->})' 'doSomething({y: ->, z: a})' '!{ a: -> }' # # getters and setters are ok # 'var x = {get y() {}}' # 'var x = {set y(z) {}}' # 'var x = {get y() {}, set y(z) {}}' # 'doSomething({get y() {}})' # 'doSomething({set y(z) {}})' # 'doSomething({get y() {}, set y(z) {}})' # object literal computed properties 'x = {[y]: y}' "x = {['y']: 'y'}" "x = {['y']: y}" 'x = {y}' 'x = {y: {b}}' , code: 'x = {a: n, c: d, f: g}' options: ['never'] , code: 'x = {a: ->, b: {c: d}}' options: ['never'] , # avoidQuotes code: "x = 'a': ->" options: ['always', {avoidQuotes: yes}] , code: "x = ['a']: ->" options: ['always', {avoidQuotes: yes}] , code: "'y': y" options: ['always', {avoidQuotes: yes}] , # ignore object shorthand code: '{a, b} = o' options: ['never'] , code: 'x = {foo: foo, bar: bar, ...baz}' options: ['never'] , # consistent code: 'x = {a: a, b: b}' options: ['consistent'] , code: 'x = {a: b, c: d, f: g}' options: ['consistent'] , code: 'x = {a, b}' options: ['consistent'] , # , # code: 'x = {a, b, get test() { return 1; }}' # options: ['consistent'] code: 'x = {...bar}' options: ['consistent-as-needed'] , code: 'x = {foo, bar, ...baz}' options: ['consistent'] , code: 'x = {bar: baz, ...qux}' options: ['consistent'] , code: 'x = {...foo, bar: bar, baz: baz}' options: ['consistent'] , # consistent-as-needed code: 'x = {a, b}' options: ['consistent-as-needed'] , # , # code: 'x = {a, b, get test(){return 1;}}' # options: ['consistent-as-needed'] code: "x = {0: 'foo'}" options: ['consistent-as-needed'] , code: "x = {'key': 'baz'}" options: ['consistent-as-needed'] , code: "x = {foo: 'foo'}" options: ['consistent-as-needed'] , code: 'x = {[foo]: foo}' options: ['consistent-as-needed'] , code: 'x = {foo: ->}' options: ['consistent-as-needed'] , code: "x = {[foo]: 'foo'}" options: ['consistent-as-needed'] , code: 'x = {bar, ...baz}' options: ['consistent-as-needed'] , code: 'x = {bar: baz, ...qux}' options: ['consistent-as-needed'] , code: 'x = {...foo, bar, baz}' options: ['consistent-as-needed'] ] invalid: [ code: 'x = {x: x}' errors: [PROPERTY_ERROR] , code: "x = {'x': x}" errors: [PROPERTY_ERROR] , code: 'x = {y: y, x: x}' errors: [PROPERTY_ERROR, PROPERTY_ERROR] , code: 'x = {y: z, x: x, a: b}' errors: [PROPERTY_ERROR] , code: ''' x = { y: z x: x a: b # comment } ''' errors: [PROPERTY_ERROR] , code: ''' x = { a: b ### comment ### y: y } ''' errors: [PROPERTY_ERROR] , code: 'x = {x: y, y: z, a: a}' errors: [PROPERTY_ERROR] , code: 'doSomething({x: x})' errors: [PROPERTY_ERROR] , code: "doSomething({'x': x})" errors: [PROPERTY_ERROR] , code: "doSomething({a: 'a', 'x': x})" errors: [PROPERTY_ERROR] , code: 'x = {y}' options: ['never'] errors: [LONGFORM_PROPERTY_ERROR] , code: 'x = {y: {x}}' options: ['never'] errors: [LONGFORM_PROPERTY_ERROR] , code: 'x = {foo: foo, bar: baz, ...qux}' options: ['always'] errors: [PROPERTY_ERROR] , code: 'x = {foo, bar: baz, ...qux}' options: ['never'] errors: [LONGFORM_PROPERTY_ERROR] , # avoidQuotes code: 'x = {a: a}' options: ['always', {avoidQuotes: yes}] errors: [PROPERTY_ERROR] , # consistent code: 'x = {a: a, b}' options: ['consistent'] errors: [MIXED_SHORTHAND_ERROR] , code: 'x = {b, c: d, f: g}' options: ['consistent'] errors: [MIXED_SHORTHAND_ERROR] , code: 'x = {foo, bar: baz, ...qux}' options: ['consistent'] errors: [MIXED_SHORTHAND_ERROR] , # consistent-as-needed code: 'x = {a: a, b: b}' options: ['consistent-as-needed'] errors: [ALL_SHORTHAND_ERROR] , code: 'x = {a: a, b: b, ...baz}' options: ['consistent-as-needed'] errors: [ALL_SHORTHAND_ERROR] , code: 'x = {foo, bar: bar, ...qux}' options: ['consistent-as-needed'] errors: [MIXED_SHORTHAND_ERROR] , code: 'x = {a, z: ->}' options: ['consistent-as-needed'] errors: [MIXED_SHORTHAND_ERROR] ]
true
###* # @fileoverview Tests for concise-object rule # @author PI:NAME:<NAME>END_PI <http://www.jamund.com> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/object-shorthand' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ PROPERTY_ERROR = message: 'Expected property shorthand.', type: 'Property' LONGFORM_PROPERTY_ERROR = message: 'Expected longform property syntax.', type: 'Property' ALL_SHORTHAND_ERROR = message: 'Expected shorthand for all properties.', type: 'ObjectExpression' MIXED_SHORTHAND_ERROR = message: 'Unexpected mix of shorthand and non-shorthand properties.' type: 'ObjectExpression' ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'object-shorthand', rule, valid: [ 'x = y: ->' 'x = {y}' 'x = {a: b}' "x = {a: 'a'}" "x = {'a': 'a'}" "x = {'a': b}" 'x = {y: (x) ->}' '{x,y,z} = x' '{x: {y}} = z' 'x = {x: y}' 'x = {x: y, y: z}' "x = {x: y, y: z, z: 'z'}" 'x = {x: ->, y: z, l: ->}' 'x = {x: y, y: z, a: b}' "x = {x: y, y: z, 'a': b}" 'x = {x: y, y: ->, z: a}' 'x = {[y]: y}' 'doSomething({x: y})' "doSomething({'x': y})" "doSomething({x: 'x'})" "doSomething({'x': 'x'})" 'doSomething({y: ->})' 'doSomething({x: y, y: ->})' 'doSomething({y: ->, z: a})' '!{ a: -> }' # # getters and setters are ok # 'var x = {get y() {}}' # 'var x = {set y(z) {}}' # 'var x = {get y() {}, set y(z) {}}' # 'doSomething({get y() {}})' # 'doSomething({set y(z) {}})' # 'doSomething({get y() {}, set y(z) {}})' # object literal computed properties 'x = {[y]: y}' "x = {['y']: 'y'}" "x = {['y']: y}" 'x = {y}' 'x = {y: {b}}' , code: 'x = {a: n, c: d, f: g}' options: ['never'] , code: 'x = {a: ->, b: {c: d}}' options: ['never'] , # avoidQuotes code: "x = 'a': ->" options: ['always', {avoidQuotes: yes}] , code: "x = ['a']: ->" options: ['always', {avoidQuotes: yes}] , code: "'y': y" options: ['always', {avoidQuotes: yes}] , # ignore object shorthand code: '{a, b} = o' options: ['never'] , code: 'x = {foo: foo, bar: bar, ...baz}' options: ['never'] , # consistent code: 'x = {a: a, b: b}' options: ['consistent'] , code: 'x = {a: b, c: d, f: g}' options: ['consistent'] , code: 'x = {a, b}' options: ['consistent'] , # , # code: 'x = {a, b, get test() { return 1; }}' # options: ['consistent'] code: 'x = {...bar}' options: ['consistent-as-needed'] , code: 'x = {foo, bar, ...baz}' options: ['consistent'] , code: 'x = {bar: baz, ...qux}' options: ['consistent'] , code: 'x = {...foo, bar: bar, baz: baz}' options: ['consistent'] , # consistent-as-needed code: 'x = {a, b}' options: ['consistent-as-needed'] , # , # code: 'x = {a, b, get test(){return 1;}}' # options: ['consistent-as-needed'] code: "x = {0: 'foo'}" options: ['consistent-as-needed'] , code: "x = {'key': 'baz'}" options: ['consistent-as-needed'] , code: "x = {foo: 'foo'}" options: ['consistent-as-needed'] , code: 'x = {[foo]: foo}' options: ['consistent-as-needed'] , code: 'x = {foo: ->}' options: ['consistent-as-needed'] , code: "x = {[foo]: 'foo'}" options: ['consistent-as-needed'] , code: 'x = {bar, ...baz}' options: ['consistent-as-needed'] , code: 'x = {bar: baz, ...qux}' options: ['consistent-as-needed'] , code: 'x = {...foo, bar, baz}' options: ['consistent-as-needed'] ] invalid: [ code: 'x = {x: x}' errors: [PROPERTY_ERROR] , code: "x = {'x': x}" errors: [PROPERTY_ERROR] , code: 'x = {y: y, x: x}' errors: [PROPERTY_ERROR, PROPERTY_ERROR] , code: 'x = {y: z, x: x, a: b}' errors: [PROPERTY_ERROR] , code: ''' x = { y: z x: x a: b # comment } ''' errors: [PROPERTY_ERROR] , code: ''' x = { a: b ### comment ### y: y } ''' errors: [PROPERTY_ERROR] , code: 'x = {x: y, y: z, a: a}' errors: [PROPERTY_ERROR] , code: 'doSomething({x: x})' errors: [PROPERTY_ERROR] , code: "doSomething({'x': x})" errors: [PROPERTY_ERROR] , code: "doSomething({a: 'a', 'x': x})" errors: [PROPERTY_ERROR] , code: 'x = {y}' options: ['never'] errors: [LONGFORM_PROPERTY_ERROR] , code: 'x = {y: {x}}' options: ['never'] errors: [LONGFORM_PROPERTY_ERROR] , code: 'x = {foo: foo, bar: baz, ...qux}' options: ['always'] errors: [PROPERTY_ERROR] , code: 'x = {foo, bar: baz, ...qux}' options: ['never'] errors: [LONGFORM_PROPERTY_ERROR] , # avoidQuotes code: 'x = {a: a}' options: ['always', {avoidQuotes: yes}] errors: [PROPERTY_ERROR] , # consistent code: 'x = {a: a, b}' options: ['consistent'] errors: [MIXED_SHORTHAND_ERROR] , code: 'x = {b, c: d, f: g}' options: ['consistent'] errors: [MIXED_SHORTHAND_ERROR] , code: 'x = {foo, bar: baz, ...qux}' options: ['consistent'] errors: [MIXED_SHORTHAND_ERROR] , # consistent-as-needed code: 'x = {a: a, b: b}' options: ['consistent-as-needed'] errors: [ALL_SHORTHAND_ERROR] , code: 'x = {a: a, b: b, ...baz}' options: ['consistent-as-needed'] errors: [ALL_SHORTHAND_ERROR] , code: 'x = {foo, bar: bar, ...qux}' options: ['consistent-as-needed'] errors: [MIXED_SHORTHAND_ERROR] , code: 'x = {a, z: ->}' options: ['consistent-as-needed'] errors: [MIXED_SHORTHAND_ERROR] ]
[ { "context": "#\n# Configuration:\n# HUBOT_TEAMCITY_USERNAME = <user name>\n# HUBOT_TEAMCITY_PASSWORD = <password>\n# HUB", "end": 152, "score": 0.956489086151123, "start": 143, "tag": "USERNAME", "value": "user name" }, { "context": "NAME = <user name>\n# HUBOT_TEAMCITY_PASSWORD = <password>\n# HUBOT_TEAMCITY_HOSTNAME = <host : port>\n#\n# ", "end": 193, "score": 0.8892824649810791, "start": 185, "tag": "PASSWORD", "value": "password" }, { "context": "queue for the specified build type\n#\n# Author:\n# Micah Martin\n\nutil = require 'util'\n_ = require 'undersco", "end": 638, "score": 0.9998116493225098, "start": 626, "tag": "NAME", "value": "Micah Martin" } ]
src/scripts/teamcity.coffee
neilprosser/hubot-scripts
1
# Description: # wrapper for TeamCity REST API # # Dependencies: # "underscore": "1.3.3" # # Configuration: # HUBOT_TEAMCITY_USERNAME = <user name> # HUBOT_TEAMCITY_PASSWORD = <password> # HUBOT_TEAMCITY_HOSTNAME = <host : port> # # Commands: # hubot show me builds - Show status of currently running builds # hubot tc list projects - Show all available projects # hubot tc list buildTypes - Show all available build types # hubot tc list builds <buildType> - Show the status of the last 5 builds # hubot tc build start <buildType> - Adds a build to the queue for the specified build type # # Author: # Micah Martin util = require 'util' _ = require 'underscore' module.exports = (robot) -> username = process.env.HUBOT_TEAMCITY_USERNAME password = process.env.HUBOT_TEAMCITY_PASSWORD hostname = process.env.HUBOT_TEAMCITY_HOSTNAME buildTypes = [] getAuthHeader = -> return Authorization: "Basic #{new Buffer("#{username}:#{password}").toString("base64")}", Accept: "application/json" getBuildType = (msg, type, callback) -> url = "http://#{hostname}/httpAuth/app/rest/buildTypes/#{type}" console.log "sending request to #{url}" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 callback err, body, msg getCurrentBuild = (msg, type, callback) -> url = "http://#{hostname}/httpAuth/app/rest/builds/?locator=buildType:#{type},running:true" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 callback err, body, msg getProjects = (msg, callback) -> url = "http://#{hostname}/httpAuth/app/rest/projects" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 projects = JSON.parse(body).project unless err callback err, msg, projects getBuildTypes = (msg, callback) -> url = "http://#{hostname}/httpAuth/app/rest/buildTypes" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 buildTypes = JSON.parse(body).buildType unless err callback err, msg, buildTypes getBuilds = (msg, id, type, callback) -> url = "http://#{hostname}/httpAuth/app/rest/buildTypes/#{type}:#{escape(id)}/builds" msg.http(url) .headers(getAuthHeader()) .query(locator: ["lookupLimit:5","running:any"].join(",")) .get() (err, res, body) -> err = body unless res.statusCode == 200 builds = JSON.parse(body).build unless err callback err, msg, builds mapNameToIdForBuildType = (msg, name, callback) -> execute = (buildTypes) -> buildType = _.find buildTypes, (bt) -> return bt.name == name if buildType return buildType.id result = execute(buildTypes) if result callback(msg, result) return getBuildTypes msg, (err, msg, buildTypes) -> callback msg, execute(buildTypes) robot.respond /tc build start (.*)/i, (msg) -> buildName = msg.match[1] mapNameToIdForBuildType msg, buildName, (msg, buildType) -> if not buildType msg.send "Build type #{buildName} was not found" return url = "http://#{hostname}/httpAuth/action.html?add2Queue=#{buildType}" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 if err msg.send "Fail! Something went wrong. Couldn't start the build for some reason" else msg.send "Dropped a build in the queue for #{buildName}. Run `tc list builds #{buildName}` to check the status" robot.respond /tc list (projects|buildTypes|builds) ?(.*)?/i, (msg) -> type = msg.match[1] option = msg.match[2] switch type when "projects" getProjects msg, (err, msg, projects) -> message = "" for project in projects message += project.name + "\n" msg.send message when "buildTypes" getBuildTypes msg, (err, msg, buildTypes) -> message = "" for buildType in buildTypes message += buildType.name + "\n" msg.send message when "builds" getBuilds msg, option, "name", (err, msg, builds) -> if not builds msg.send "Could not find builds for #{option}" return for build in builds baseMessage = "##{build.number} of #{build.branchName} #{build.webUrl}" if build.running status = if build.status == "SUCCESS" then "**Winning**" else "__FAILING__" message = "#{status} #{build.percentageComplete}% Complete :: #{baseMessage}" else status = if build.status == "SUCCESS" then "OK!" else "__FAILED__" message = "#{status} :: #{baseMessage}" msg.send message
90
# Description: # wrapper for TeamCity REST API # # Dependencies: # "underscore": "1.3.3" # # Configuration: # HUBOT_TEAMCITY_USERNAME = <user name> # HUBOT_TEAMCITY_PASSWORD = <<PASSWORD>> # HUBOT_TEAMCITY_HOSTNAME = <host : port> # # Commands: # hubot show me builds - Show status of currently running builds # hubot tc list projects - Show all available projects # hubot tc list buildTypes - Show all available build types # hubot tc list builds <buildType> - Show the status of the last 5 builds # hubot tc build start <buildType> - Adds a build to the queue for the specified build type # # Author: # <NAME> util = require 'util' _ = require 'underscore' module.exports = (robot) -> username = process.env.HUBOT_TEAMCITY_USERNAME password = process.env.HUBOT_TEAMCITY_PASSWORD hostname = process.env.HUBOT_TEAMCITY_HOSTNAME buildTypes = [] getAuthHeader = -> return Authorization: "Basic #{new Buffer("#{username}:#{password}").toString("base64")}", Accept: "application/json" getBuildType = (msg, type, callback) -> url = "http://#{hostname}/httpAuth/app/rest/buildTypes/#{type}" console.log "sending request to #{url}" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 callback err, body, msg getCurrentBuild = (msg, type, callback) -> url = "http://#{hostname}/httpAuth/app/rest/builds/?locator=buildType:#{type},running:true" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 callback err, body, msg getProjects = (msg, callback) -> url = "http://#{hostname}/httpAuth/app/rest/projects" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 projects = JSON.parse(body).project unless err callback err, msg, projects getBuildTypes = (msg, callback) -> url = "http://#{hostname}/httpAuth/app/rest/buildTypes" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 buildTypes = JSON.parse(body).buildType unless err callback err, msg, buildTypes getBuilds = (msg, id, type, callback) -> url = "http://#{hostname}/httpAuth/app/rest/buildTypes/#{type}:#{escape(id)}/builds" msg.http(url) .headers(getAuthHeader()) .query(locator: ["lookupLimit:5","running:any"].join(",")) .get() (err, res, body) -> err = body unless res.statusCode == 200 builds = JSON.parse(body).build unless err callback err, msg, builds mapNameToIdForBuildType = (msg, name, callback) -> execute = (buildTypes) -> buildType = _.find buildTypes, (bt) -> return bt.name == name if buildType return buildType.id result = execute(buildTypes) if result callback(msg, result) return getBuildTypes msg, (err, msg, buildTypes) -> callback msg, execute(buildTypes) robot.respond /tc build start (.*)/i, (msg) -> buildName = msg.match[1] mapNameToIdForBuildType msg, buildName, (msg, buildType) -> if not buildType msg.send "Build type #{buildName} was not found" return url = "http://#{hostname}/httpAuth/action.html?add2Queue=#{buildType}" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 if err msg.send "Fail! Something went wrong. Couldn't start the build for some reason" else msg.send "Dropped a build in the queue for #{buildName}. Run `tc list builds #{buildName}` to check the status" robot.respond /tc list (projects|buildTypes|builds) ?(.*)?/i, (msg) -> type = msg.match[1] option = msg.match[2] switch type when "projects" getProjects msg, (err, msg, projects) -> message = "" for project in projects message += project.name + "\n" msg.send message when "buildTypes" getBuildTypes msg, (err, msg, buildTypes) -> message = "" for buildType in buildTypes message += buildType.name + "\n" msg.send message when "builds" getBuilds msg, option, "name", (err, msg, builds) -> if not builds msg.send "Could not find builds for #{option}" return for build in builds baseMessage = "##{build.number} of #{build.branchName} #{build.webUrl}" if build.running status = if build.status == "SUCCESS" then "**Winning**" else "__FAILING__" message = "#{status} #{build.percentageComplete}% Complete :: #{baseMessage}" else status = if build.status == "SUCCESS" then "OK!" else "__FAILED__" message = "#{status} :: #{baseMessage}" msg.send message
true
# Description: # wrapper for TeamCity REST API # # Dependencies: # "underscore": "1.3.3" # # Configuration: # HUBOT_TEAMCITY_USERNAME = <user name> # HUBOT_TEAMCITY_PASSWORD = <PI:PASSWORD:<PASSWORD>END_PI> # HUBOT_TEAMCITY_HOSTNAME = <host : port> # # Commands: # hubot show me builds - Show status of currently running builds # hubot tc list projects - Show all available projects # hubot tc list buildTypes - Show all available build types # hubot tc list builds <buildType> - Show the status of the last 5 builds # hubot tc build start <buildType> - Adds a build to the queue for the specified build type # # Author: # PI:NAME:<NAME>END_PI util = require 'util' _ = require 'underscore' module.exports = (robot) -> username = process.env.HUBOT_TEAMCITY_USERNAME password = process.env.HUBOT_TEAMCITY_PASSWORD hostname = process.env.HUBOT_TEAMCITY_HOSTNAME buildTypes = [] getAuthHeader = -> return Authorization: "Basic #{new Buffer("#{username}:#{password}").toString("base64")}", Accept: "application/json" getBuildType = (msg, type, callback) -> url = "http://#{hostname}/httpAuth/app/rest/buildTypes/#{type}" console.log "sending request to #{url}" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 callback err, body, msg getCurrentBuild = (msg, type, callback) -> url = "http://#{hostname}/httpAuth/app/rest/builds/?locator=buildType:#{type},running:true" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 callback err, body, msg getProjects = (msg, callback) -> url = "http://#{hostname}/httpAuth/app/rest/projects" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 projects = JSON.parse(body).project unless err callback err, msg, projects getBuildTypes = (msg, callback) -> url = "http://#{hostname}/httpAuth/app/rest/buildTypes" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 buildTypes = JSON.parse(body).buildType unless err callback err, msg, buildTypes getBuilds = (msg, id, type, callback) -> url = "http://#{hostname}/httpAuth/app/rest/buildTypes/#{type}:#{escape(id)}/builds" msg.http(url) .headers(getAuthHeader()) .query(locator: ["lookupLimit:5","running:any"].join(",")) .get() (err, res, body) -> err = body unless res.statusCode == 200 builds = JSON.parse(body).build unless err callback err, msg, builds mapNameToIdForBuildType = (msg, name, callback) -> execute = (buildTypes) -> buildType = _.find buildTypes, (bt) -> return bt.name == name if buildType return buildType.id result = execute(buildTypes) if result callback(msg, result) return getBuildTypes msg, (err, msg, buildTypes) -> callback msg, execute(buildTypes) robot.respond /tc build start (.*)/i, (msg) -> buildName = msg.match[1] mapNameToIdForBuildType msg, buildName, (msg, buildType) -> if not buildType msg.send "Build type #{buildName} was not found" return url = "http://#{hostname}/httpAuth/action.html?add2Queue=#{buildType}" msg.http(url) .headers(getAuthHeader()) .get() (err, res, body) -> err = body unless res.statusCode == 200 if err msg.send "Fail! Something went wrong. Couldn't start the build for some reason" else msg.send "Dropped a build in the queue for #{buildName}. Run `tc list builds #{buildName}` to check the status" robot.respond /tc list (projects|buildTypes|builds) ?(.*)?/i, (msg) -> type = msg.match[1] option = msg.match[2] switch type when "projects" getProjects msg, (err, msg, projects) -> message = "" for project in projects message += project.name + "\n" msg.send message when "buildTypes" getBuildTypes msg, (err, msg, buildTypes) -> message = "" for buildType in buildTypes message += buildType.name + "\n" msg.send message when "builds" getBuilds msg, option, "name", (err, msg, builds) -> if not builds msg.send "Could not find builds for #{option}" return for build in builds baseMessage = "##{build.number} of #{build.branchName} #{build.webUrl}" if build.running status = if build.status == "SUCCESS" then "**Winning**" else "__FAILING__" message = "#{status} #{build.percentageComplete}% Complete :: #{baseMessage}" else status = if build.status == "SUCCESS" then "OK!" else "__FAILED__" message = "#{status} :: #{baseMessage}" msg.send message
[ { "context": " result, true\n # App.Post.exists authorName: \"David\", (error, result) -> assert.equal result, true\n ", "end": 535, "score": 0.9997520446777344, "start": 530, "tag": "NAME", "value": "David" }, { "context": " result, true\n # App.Post.exists authorName: \"Mary\", approved: true, (error, result) -> assert.equal", "end": 623, "score": 0.999793291091919, "start": 619, "tag": "NAME", "value": "Mary" } ]
test/cases/model/findersTest.coffee
ludicast/tower
1
require '../../config' moment = require('moment') describeWith = (store) -> describe "Tower.Model.Finders (Tower.Store.#{store.name})", -> beforeEach (done) -> App.Post.store(new store(name: "posts", type: "App.Post")) App.Post.destroy(done) afterEach (done) -> App.Post.destroy(done) #test 'exists', -> # App.Post.exists 1, (error, result) -> assert.equal result, true # App.Post.exists "1", (error, result) -> assert.equal result, true # App.Post.exists authorName: "David", (error, result) -> assert.equal result, true # App.Post.exists authorName: "Mary", approved: true, (error, result) -> assert.equal result, true # App.Post.exists 45, (error, result) -> assert.equal result, false # App.Post.exists (error, result) -> assert.equal result, true # App.Post.exists null, (error, result) -> assert.equal result, false describe '$gt', -> describe 'integer > value (8, 10)', -> beforeEach (done) -> App.Post.create [{rating: 8}, {rating: 10}], => done() test 'where(rating: ">": 10)', (done) -> App.Post.where(rating: ">": 10).count (error, count) => assert.equal count, 0 done() test 'where(rating: ">": 8)', (done) -> App.Post.where(rating: ">": 8).count (error, count) => assert.equal count, 1 done() test 'where(rating: ">": 7)', (done) -> App.Post.where(rating: ">": 7).count (error, count) => assert.equal count, 2 done() describe 'date > value (' + moment().format('MMM D, YYYY') + ')', -> beforeEach (done) -> App.Post.create rating: 1, someDate: moment()._d, done test 'where(someDate: ">": Dec 25, 1995)', (done) -> App.Post.where(someDate: ">": moment("Dec 25, 1995")._d).count (error, count) => assert.equal count, 1 done() test 'where(createdAt: ">": Dec 25, 1995)', (done) -> App.Post.where(createdAt: ">": moment("Dec 25, 1995")._d).count (error, count) => assert.equal count, 1 done() test 'where(createdAt: ">": Dec 25, 2050)', (done) -> App.Post.where(createdAt: ">": moment("Dec 25, 2050")._d).count (error, count) => assert.equal count, 0 done() describe '$gte', -> describe 'integer >= value (8, 10)', -> beforeEach (done) -> App.Post.create [{rating: 8}, {rating: 10}], done test 'where(rating: ">=": 11)', (done) -> App.Post.where(rating: ">=": 11).count (error, count) => assert.equal count, 0 done() test 'where(rating: ">=": 10)', (done) -> App.Post.where(rating: ">=": 10).count (error, count) => assert.equal count, 1 done() test 'where(rating: ">=": 8)', (done) -> App.Post.where(rating: ">=": 8).count (error, count) => assert.equal count, 2 done() test 'where(rating: ">=": 7)', (done) -> App.Post.where(rating: ">=": 7).count (error, count) => assert.equal count, 2 done() describe '$lt', -> describe "integer < value", -> beforeEach (done) -> App.Post.create [{rating: 8}, {rating: 10}], => done() test 'where(rating: "<": 11)', (done) -> App.Post.where(rating: "<": 11).count (error, count) => assert.equal count, 2 done() test 'where(rating: "<": 10)', (done) -> App.Post.where(rating: "<": 10).count (error, count) => assert.equal count, 1 done() test 'where(rating: "<": 8)', (done) -> App.Post.where(rating: "<": 8).count (error, count) => assert.equal count, 0 done() describe 'date < value (' + moment().format('MMM D, YYYY') + ')', -> beforeEach (done) -> App.Post.create rating: 1, someDate: moment()._d, done test 'where(someDate: "<": Dec 25, 2050)', (done) -> App.Post.where(someDate: "<": moment("Dec 25, 2050")._d).count (error, count) => assert.equal count, 1 done() test 'where(createdAt: "<": Dec 25, 2050)', (done) -> App.Post.where(createdAt: "<": moment("Dec 25, 2050")._d).count (error, count) => assert.equal count, 1 done() test 'where(createdAt: "<": Dec 25, 1995)', (done) -> App.Post.where(createdAt: "<": moment("Dec 25, 1995")._d).count (error, count) => assert.equal count, 0 done() describe '$lte', -> describe 'integer <= value', -> beforeEach (done) -> attributes = [] attributes.push rating: 8 attributes.push rating: 10 App.Post.create(attributes, done) test 'where(rating: "<=": 11)', (done) -> App.Post.where(rating: "<=": 11).count (error, count) => assert.equal count, 2 done() test 'where(rating: "<=": 10)', (done) -> App.Post.where(rating: "<=": 10).count (error, count) => assert.equal count, 2 done() test 'where(rating: "<=": 8)', (done) -> App.Post.where(rating: "<=": 8).count (error, count) => assert.equal count, 1 done() test 'where(rating: "<=": 7)', (done) -> App.Post.where(rating: "<=": 7).count (error, count) => assert.equal count, 0 done() test 'date <= value', -> beforeEach (done) -> App.Post.create(rating: 1, someDate: moment()._d, done) test 'where(someDate: "<=": Dec 25, 2050)', (done) -> App.Post.where(someDate: "<=": moment("Dec 25, 2050")._d).count (error, count) => assert.equal count, 1 done() test 'where(createdAt: "<=": Dec 25, 2050)', (done) -> App.Post.where(createdAt: "<=": moment("Dec 25, 2050")._d).count (error, count) => assert.equal count, 1 done() test 'where(createdAt: "<=": Dec 25, 1995)', (done) -> App.Post.where(createdAt: "<=": moment("Dec 25, 1995")._d).count (error, count) => assert.equal count, 0 done() describe '$match', -> describe '$notMatch', -> describe '$in', -> describe 'string in array', -> beforeEach (done) -> attributes = [] attributes.push rating: 8, tags: ["ruby", "javascript"] attributes.push rating: 9, tags: ["nodejs", "javascript"] App.Post.create(attributes, done) test 'where(tags: "$in": ["javascript"])', (done) -> App.Post.where(tags: "$in": ["javascript"]).count (error, count) => assert.equal count, 2 done() test 'where(tags: "$in": ["asp"])', (done) -> App.Post.where(tags: "$in": ["asp"]).count (error, count) => assert.equal count, 0 done() test 'where(tags: "$in": ["nodejs"])', (done) -> App.Post.where(tags: "$in": ["nodejs"]).count (error, count) => assert.equal count, 1 done() describe '$any', -> describe 'string in array', -> beforeEach (done) -> attributes = [] attributes.push rating: 8, tags: ["ruby", "javascript"] attributes.push rating: 9, tags: ["nodejs", "javascript"] App.Post.create(attributes, done) test 'anyIn(tags: ["javascript"])', (done) -> App.Post.anyIn(tags: ["javascript"]).count (error, count) => assert.equal count, 2 done() test 'anyIn(tags: ["asp"])', (done) -> App.Post.anyIn(tags: ["asp"]).count (error, count) => assert.equal count, 0 done() test 'anyIn(tags: ["nodejs"])', (done) -> App.Post.anyIn(tags: ["nodejs"]).count (error, count) => assert.equal count, 1 done() test 'anyIn(tags: ["nodejs", "ruby"])', (done) -> App.Post.anyIn(tags: ["nodejs", "ruby"]).count (error, count) => assert.equal count, 2 done() test 'anyIn(tags: ["nodejs", "asp"])', (done) -> App.Post.anyIn(tags: ["nodejs", "asp"]).count (error, count) => assert.equal count, 1 done() describe '$nin', -> beforeEach (done) -> attributes = [] attributes.push rating: 8, tags: ["ruby", "javascript"] attributes.push rating: 9, tags: ["nodejs", "javascript"] App.Post.create(attributes, done) test 'notIn(tags: ["javascript"])', (done) -> App.Post.notIn(tags: ["javascript"]).count (error, count) => assert.equal count, 0 done() test 'notIn(tags: ["asp"])', (done) -> App.Post.notIn(tags: ["asp"]).count (error, count) => assert.equal count, 2 done() test 'notIn(tags: ["nodejs"])', (done) -> App.Post.notIn(tags: ["nodejs"]).count (error, count) => assert.equal count, 1 done() describe '$all', -> beforeEach (done) -> attributes = [] attributes.push rating: 8, tags: ["ruby", "javascript"] attributes.push rating: 9, tags: ["nodejs", "javascript"] App.Post.create(attributes, done) describe 'string in array', -> test 'allIn(tags: ["javascript"])', (done) -> App.Post.allIn(tags: ["javascript"]).count (error, count) => assert.equal count, 2 done() test 'allIn(tags: ["asp"])', (done) -> App.Post.allIn(tags: ["asp"]).count (error, count) => assert.equal count, 0 done() test 'allIn(tags: ["nodejs"])', (done) -> App.Post.allIn(tags: ["nodejs"]).count (error, count) => assert.equal count, 1 done() test 'allIn(tags: ["nodejs", "javascript"])', (done) -> App.Post.allIn(tags: ["nodejs", "javascript"]).count (error, count) => assert.equal count, 1 done() test 'allIn(tags: ["nodejs", "ruby"])', (done) -> App.Post.allIn(tags: ["nodejs", "ruby"]).count (error, count) => assert.equal count, 0 done() describe '$null', -> describe '$notNull', -> describe '$eq', -> describe 'string', -> beforeEach (done) -> attributes = [] attributes.push title: "Ruby", rating: 8 attributes.push title: "JavaScript", rating: 10 App.Post.create(attributes, done) test 'where(title: $eq: "Ruby")', (done) -> App.Post.where(title: $eq: "Ruby").count (error, count) => assert.equal count, 1 done() test 'where(title: /R/)', (done) -> App.Post.where(title: /R/).count (error, count) => assert.equal count, 1 done() test 'where(title: /[Rr]/)', (done) -> App.Post.where(title: /[Rr]/).count (error, count) => assert.equal count, 2 done() describe '$neq', -> describeWith(Tower.Store.Memory) describeWith(Tower.Store.MongoDB)
176614
require '../../config' moment = require('moment') describeWith = (store) -> describe "Tower.Model.Finders (Tower.Store.#{store.name})", -> beforeEach (done) -> App.Post.store(new store(name: "posts", type: "App.Post")) App.Post.destroy(done) afterEach (done) -> App.Post.destroy(done) #test 'exists', -> # App.Post.exists 1, (error, result) -> assert.equal result, true # App.Post.exists "1", (error, result) -> assert.equal result, true # App.Post.exists authorName: "<NAME>", (error, result) -> assert.equal result, true # App.Post.exists authorName: "<NAME>", approved: true, (error, result) -> assert.equal result, true # App.Post.exists 45, (error, result) -> assert.equal result, false # App.Post.exists (error, result) -> assert.equal result, true # App.Post.exists null, (error, result) -> assert.equal result, false describe '$gt', -> describe 'integer > value (8, 10)', -> beforeEach (done) -> App.Post.create [{rating: 8}, {rating: 10}], => done() test 'where(rating: ">": 10)', (done) -> App.Post.where(rating: ">": 10).count (error, count) => assert.equal count, 0 done() test 'where(rating: ">": 8)', (done) -> App.Post.where(rating: ">": 8).count (error, count) => assert.equal count, 1 done() test 'where(rating: ">": 7)', (done) -> App.Post.where(rating: ">": 7).count (error, count) => assert.equal count, 2 done() describe 'date > value (' + moment().format('MMM D, YYYY') + ')', -> beforeEach (done) -> App.Post.create rating: 1, someDate: moment()._d, done test 'where(someDate: ">": Dec 25, 1995)', (done) -> App.Post.where(someDate: ">": moment("Dec 25, 1995")._d).count (error, count) => assert.equal count, 1 done() test 'where(createdAt: ">": Dec 25, 1995)', (done) -> App.Post.where(createdAt: ">": moment("Dec 25, 1995")._d).count (error, count) => assert.equal count, 1 done() test 'where(createdAt: ">": Dec 25, 2050)', (done) -> App.Post.where(createdAt: ">": moment("Dec 25, 2050")._d).count (error, count) => assert.equal count, 0 done() describe '$gte', -> describe 'integer >= value (8, 10)', -> beforeEach (done) -> App.Post.create [{rating: 8}, {rating: 10}], done test 'where(rating: ">=": 11)', (done) -> App.Post.where(rating: ">=": 11).count (error, count) => assert.equal count, 0 done() test 'where(rating: ">=": 10)', (done) -> App.Post.where(rating: ">=": 10).count (error, count) => assert.equal count, 1 done() test 'where(rating: ">=": 8)', (done) -> App.Post.where(rating: ">=": 8).count (error, count) => assert.equal count, 2 done() test 'where(rating: ">=": 7)', (done) -> App.Post.where(rating: ">=": 7).count (error, count) => assert.equal count, 2 done() describe '$lt', -> describe "integer < value", -> beforeEach (done) -> App.Post.create [{rating: 8}, {rating: 10}], => done() test 'where(rating: "<": 11)', (done) -> App.Post.where(rating: "<": 11).count (error, count) => assert.equal count, 2 done() test 'where(rating: "<": 10)', (done) -> App.Post.where(rating: "<": 10).count (error, count) => assert.equal count, 1 done() test 'where(rating: "<": 8)', (done) -> App.Post.where(rating: "<": 8).count (error, count) => assert.equal count, 0 done() describe 'date < value (' + moment().format('MMM D, YYYY') + ')', -> beforeEach (done) -> App.Post.create rating: 1, someDate: moment()._d, done test 'where(someDate: "<": Dec 25, 2050)', (done) -> App.Post.where(someDate: "<": moment("Dec 25, 2050")._d).count (error, count) => assert.equal count, 1 done() test 'where(createdAt: "<": Dec 25, 2050)', (done) -> App.Post.where(createdAt: "<": moment("Dec 25, 2050")._d).count (error, count) => assert.equal count, 1 done() test 'where(createdAt: "<": Dec 25, 1995)', (done) -> App.Post.where(createdAt: "<": moment("Dec 25, 1995")._d).count (error, count) => assert.equal count, 0 done() describe '$lte', -> describe 'integer <= value', -> beforeEach (done) -> attributes = [] attributes.push rating: 8 attributes.push rating: 10 App.Post.create(attributes, done) test 'where(rating: "<=": 11)', (done) -> App.Post.where(rating: "<=": 11).count (error, count) => assert.equal count, 2 done() test 'where(rating: "<=": 10)', (done) -> App.Post.where(rating: "<=": 10).count (error, count) => assert.equal count, 2 done() test 'where(rating: "<=": 8)', (done) -> App.Post.where(rating: "<=": 8).count (error, count) => assert.equal count, 1 done() test 'where(rating: "<=": 7)', (done) -> App.Post.where(rating: "<=": 7).count (error, count) => assert.equal count, 0 done() test 'date <= value', -> beforeEach (done) -> App.Post.create(rating: 1, someDate: moment()._d, done) test 'where(someDate: "<=": Dec 25, 2050)', (done) -> App.Post.where(someDate: "<=": moment("Dec 25, 2050")._d).count (error, count) => assert.equal count, 1 done() test 'where(createdAt: "<=": Dec 25, 2050)', (done) -> App.Post.where(createdAt: "<=": moment("Dec 25, 2050")._d).count (error, count) => assert.equal count, 1 done() test 'where(createdAt: "<=": Dec 25, 1995)', (done) -> App.Post.where(createdAt: "<=": moment("Dec 25, 1995")._d).count (error, count) => assert.equal count, 0 done() describe '$match', -> describe '$notMatch', -> describe '$in', -> describe 'string in array', -> beforeEach (done) -> attributes = [] attributes.push rating: 8, tags: ["ruby", "javascript"] attributes.push rating: 9, tags: ["nodejs", "javascript"] App.Post.create(attributes, done) test 'where(tags: "$in": ["javascript"])', (done) -> App.Post.where(tags: "$in": ["javascript"]).count (error, count) => assert.equal count, 2 done() test 'where(tags: "$in": ["asp"])', (done) -> App.Post.where(tags: "$in": ["asp"]).count (error, count) => assert.equal count, 0 done() test 'where(tags: "$in": ["nodejs"])', (done) -> App.Post.where(tags: "$in": ["nodejs"]).count (error, count) => assert.equal count, 1 done() describe '$any', -> describe 'string in array', -> beforeEach (done) -> attributes = [] attributes.push rating: 8, tags: ["ruby", "javascript"] attributes.push rating: 9, tags: ["nodejs", "javascript"] App.Post.create(attributes, done) test 'anyIn(tags: ["javascript"])', (done) -> App.Post.anyIn(tags: ["javascript"]).count (error, count) => assert.equal count, 2 done() test 'anyIn(tags: ["asp"])', (done) -> App.Post.anyIn(tags: ["asp"]).count (error, count) => assert.equal count, 0 done() test 'anyIn(tags: ["nodejs"])', (done) -> App.Post.anyIn(tags: ["nodejs"]).count (error, count) => assert.equal count, 1 done() test 'anyIn(tags: ["nodejs", "ruby"])', (done) -> App.Post.anyIn(tags: ["nodejs", "ruby"]).count (error, count) => assert.equal count, 2 done() test 'anyIn(tags: ["nodejs", "asp"])', (done) -> App.Post.anyIn(tags: ["nodejs", "asp"]).count (error, count) => assert.equal count, 1 done() describe '$nin', -> beforeEach (done) -> attributes = [] attributes.push rating: 8, tags: ["ruby", "javascript"] attributes.push rating: 9, tags: ["nodejs", "javascript"] App.Post.create(attributes, done) test 'notIn(tags: ["javascript"])', (done) -> App.Post.notIn(tags: ["javascript"]).count (error, count) => assert.equal count, 0 done() test 'notIn(tags: ["asp"])', (done) -> App.Post.notIn(tags: ["asp"]).count (error, count) => assert.equal count, 2 done() test 'notIn(tags: ["nodejs"])', (done) -> App.Post.notIn(tags: ["nodejs"]).count (error, count) => assert.equal count, 1 done() describe '$all', -> beforeEach (done) -> attributes = [] attributes.push rating: 8, tags: ["ruby", "javascript"] attributes.push rating: 9, tags: ["nodejs", "javascript"] App.Post.create(attributes, done) describe 'string in array', -> test 'allIn(tags: ["javascript"])', (done) -> App.Post.allIn(tags: ["javascript"]).count (error, count) => assert.equal count, 2 done() test 'allIn(tags: ["asp"])', (done) -> App.Post.allIn(tags: ["asp"]).count (error, count) => assert.equal count, 0 done() test 'allIn(tags: ["nodejs"])', (done) -> App.Post.allIn(tags: ["nodejs"]).count (error, count) => assert.equal count, 1 done() test 'allIn(tags: ["nodejs", "javascript"])', (done) -> App.Post.allIn(tags: ["nodejs", "javascript"]).count (error, count) => assert.equal count, 1 done() test 'allIn(tags: ["nodejs", "ruby"])', (done) -> App.Post.allIn(tags: ["nodejs", "ruby"]).count (error, count) => assert.equal count, 0 done() describe '$null', -> describe '$notNull', -> describe '$eq', -> describe 'string', -> beforeEach (done) -> attributes = [] attributes.push title: "Ruby", rating: 8 attributes.push title: "JavaScript", rating: 10 App.Post.create(attributes, done) test 'where(title: $eq: "Ruby")', (done) -> App.Post.where(title: $eq: "Ruby").count (error, count) => assert.equal count, 1 done() test 'where(title: /R/)', (done) -> App.Post.where(title: /R/).count (error, count) => assert.equal count, 1 done() test 'where(title: /[Rr]/)', (done) -> App.Post.where(title: /[Rr]/).count (error, count) => assert.equal count, 2 done() describe '$neq', -> describeWith(Tower.Store.Memory) describeWith(Tower.Store.MongoDB)
true
require '../../config' moment = require('moment') describeWith = (store) -> describe "Tower.Model.Finders (Tower.Store.#{store.name})", -> beforeEach (done) -> App.Post.store(new store(name: "posts", type: "App.Post")) App.Post.destroy(done) afterEach (done) -> App.Post.destroy(done) #test 'exists', -> # App.Post.exists 1, (error, result) -> assert.equal result, true # App.Post.exists "1", (error, result) -> assert.equal result, true # App.Post.exists authorName: "PI:NAME:<NAME>END_PI", (error, result) -> assert.equal result, true # App.Post.exists authorName: "PI:NAME:<NAME>END_PI", approved: true, (error, result) -> assert.equal result, true # App.Post.exists 45, (error, result) -> assert.equal result, false # App.Post.exists (error, result) -> assert.equal result, true # App.Post.exists null, (error, result) -> assert.equal result, false describe '$gt', -> describe 'integer > value (8, 10)', -> beforeEach (done) -> App.Post.create [{rating: 8}, {rating: 10}], => done() test 'where(rating: ">": 10)', (done) -> App.Post.where(rating: ">": 10).count (error, count) => assert.equal count, 0 done() test 'where(rating: ">": 8)', (done) -> App.Post.where(rating: ">": 8).count (error, count) => assert.equal count, 1 done() test 'where(rating: ">": 7)', (done) -> App.Post.where(rating: ">": 7).count (error, count) => assert.equal count, 2 done() describe 'date > value (' + moment().format('MMM D, YYYY') + ')', -> beforeEach (done) -> App.Post.create rating: 1, someDate: moment()._d, done test 'where(someDate: ">": Dec 25, 1995)', (done) -> App.Post.where(someDate: ">": moment("Dec 25, 1995")._d).count (error, count) => assert.equal count, 1 done() test 'where(createdAt: ">": Dec 25, 1995)', (done) -> App.Post.where(createdAt: ">": moment("Dec 25, 1995")._d).count (error, count) => assert.equal count, 1 done() test 'where(createdAt: ">": Dec 25, 2050)', (done) -> App.Post.where(createdAt: ">": moment("Dec 25, 2050")._d).count (error, count) => assert.equal count, 0 done() describe '$gte', -> describe 'integer >= value (8, 10)', -> beforeEach (done) -> App.Post.create [{rating: 8}, {rating: 10}], done test 'where(rating: ">=": 11)', (done) -> App.Post.where(rating: ">=": 11).count (error, count) => assert.equal count, 0 done() test 'where(rating: ">=": 10)', (done) -> App.Post.where(rating: ">=": 10).count (error, count) => assert.equal count, 1 done() test 'where(rating: ">=": 8)', (done) -> App.Post.where(rating: ">=": 8).count (error, count) => assert.equal count, 2 done() test 'where(rating: ">=": 7)', (done) -> App.Post.where(rating: ">=": 7).count (error, count) => assert.equal count, 2 done() describe '$lt', -> describe "integer < value", -> beforeEach (done) -> App.Post.create [{rating: 8}, {rating: 10}], => done() test 'where(rating: "<": 11)', (done) -> App.Post.where(rating: "<": 11).count (error, count) => assert.equal count, 2 done() test 'where(rating: "<": 10)', (done) -> App.Post.where(rating: "<": 10).count (error, count) => assert.equal count, 1 done() test 'where(rating: "<": 8)', (done) -> App.Post.where(rating: "<": 8).count (error, count) => assert.equal count, 0 done() describe 'date < value (' + moment().format('MMM D, YYYY') + ')', -> beforeEach (done) -> App.Post.create rating: 1, someDate: moment()._d, done test 'where(someDate: "<": Dec 25, 2050)', (done) -> App.Post.where(someDate: "<": moment("Dec 25, 2050")._d).count (error, count) => assert.equal count, 1 done() test 'where(createdAt: "<": Dec 25, 2050)', (done) -> App.Post.where(createdAt: "<": moment("Dec 25, 2050")._d).count (error, count) => assert.equal count, 1 done() test 'where(createdAt: "<": Dec 25, 1995)', (done) -> App.Post.where(createdAt: "<": moment("Dec 25, 1995")._d).count (error, count) => assert.equal count, 0 done() describe '$lte', -> describe 'integer <= value', -> beforeEach (done) -> attributes = [] attributes.push rating: 8 attributes.push rating: 10 App.Post.create(attributes, done) test 'where(rating: "<=": 11)', (done) -> App.Post.where(rating: "<=": 11).count (error, count) => assert.equal count, 2 done() test 'where(rating: "<=": 10)', (done) -> App.Post.where(rating: "<=": 10).count (error, count) => assert.equal count, 2 done() test 'where(rating: "<=": 8)', (done) -> App.Post.where(rating: "<=": 8).count (error, count) => assert.equal count, 1 done() test 'where(rating: "<=": 7)', (done) -> App.Post.where(rating: "<=": 7).count (error, count) => assert.equal count, 0 done() test 'date <= value', -> beforeEach (done) -> App.Post.create(rating: 1, someDate: moment()._d, done) test 'where(someDate: "<=": Dec 25, 2050)', (done) -> App.Post.where(someDate: "<=": moment("Dec 25, 2050")._d).count (error, count) => assert.equal count, 1 done() test 'where(createdAt: "<=": Dec 25, 2050)', (done) -> App.Post.where(createdAt: "<=": moment("Dec 25, 2050")._d).count (error, count) => assert.equal count, 1 done() test 'where(createdAt: "<=": Dec 25, 1995)', (done) -> App.Post.where(createdAt: "<=": moment("Dec 25, 1995")._d).count (error, count) => assert.equal count, 0 done() describe '$match', -> describe '$notMatch', -> describe '$in', -> describe 'string in array', -> beforeEach (done) -> attributes = [] attributes.push rating: 8, tags: ["ruby", "javascript"] attributes.push rating: 9, tags: ["nodejs", "javascript"] App.Post.create(attributes, done) test 'where(tags: "$in": ["javascript"])', (done) -> App.Post.where(tags: "$in": ["javascript"]).count (error, count) => assert.equal count, 2 done() test 'where(tags: "$in": ["asp"])', (done) -> App.Post.where(tags: "$in": ["asp"]).count (error, count) => assert.equal count, 0 done() test 'where(tags: "$in": ["nodejs"])', (done) -> App.Post.where(tags: "$in": ["nodejs"]).count (error, count) => assert.equal count, 1 done() describe '$any', -> describe 'string in array', -> beforeEach (done) -> attributes = [] attributes.push rating: 8, tags: ["ruby", "javascript"] attributes.push rating: 9, tags: ["nodejs", "javascript"] App.Post.create(attributes, done) test 'anyIn(tags: ["javascript"])', (done) -> App.Post.anyIn(tags: ["javascript"]).count (error, count) => assert.equal count, 2 done() test 'anyIn(tags: ["asp"])', (done) -> App.Post.anyIn(tags: ["asp"]).count (error, count) => assert.equal count, 0 done() test 'anyIn(tags: ["nodejs"])', (done) -> App.Post.anyIn(tags: ["nodejs"]).count (error, count) => assert.equal count, 1 done() test 'anyIn(tags: ["nodejs", "ruby"])', (done) -> App.Post.anyIn(tags: ["nodejs", "ruby"]).count (error, count) => assert.equal count, 2 done() test 'anyIn(tags: ["nodejs", "asp"])', (done) -> App.Post.anyIn(tags: ["nodejs", "asp"]).count (error, count) => assert.equal count, 1 done() describe '$nin', -> beforeEach (done) -> attributes = [] attributes.push rating: 8, tags: ["ruby", "javascript"] attributes.push rating: 9, tags: ["nodejs", "javascript"] App.Post.create(attributes, done) test 'notIn(tags: ["javascript"])', (done) -> App.Post.notIn(tags: ["javascript"]).count (error, count) => assert.equal count, 0 done() test 'notIn(tags: ["asp"])', (done) -> App.Post.notIn(tags: ["asp"]).count (error, count) => assert.equal count, 2 done() test 'notIn(tags: ["nodejs"])', (done) -> App.Post.notIn(tags: ["nodejs"]).count (error, count) => assert.equal count, 1 done() describe '$all', -> beforeEach (done) -> attributes = [] attributes.push rating: 8, tags: ["ruby", "javascript"] attributes.push rating: 9, tags: ["nodejs", "javascript"] App.Post.create(attributes, done) describe 'string in array', -> test 'allIn(tags: ["javascript"])', (done) -> App.Post.allIn(tags: ["javascript"]).count (error, count) => assert.equal count, 2 done() test 'allIn(tags: ["asp"])', (done) -> App.Post.allIn(tags: ["asp"]).count (error, count) => assert.equal count, 0 done() test 'allIn(tags: ["nodejs"])', (done) -> App.Post.allIn(tags: ["nodejs"]).count (error, count) => assert.equal count, 1 done() test 'allIn(tags: ["nodejs", "javascript"])', (done) -> App.Post.allIn(tags: ["nodejs", "javascript"]).count (error, count) => assert.equal count, 1 done() test 'allIn(tags: ["nodejs", "ruby"])', (done) -> App.Post.allIn(tags: ["nodejs", "ruby"]).count (error, count) => assert.equal count, 0 done() describe '$null', -> describe '$notNull', -> describe '$eq', -> describe 'string', -> beforeEach (done) -> attributes = [] attributes.push title: "Ruby", rating: 8 attributes.push title: "JavaScript", rating: 10 App.Post.create(attributes, done) test 'where(title: $eq: "Ruby")', (done) -> App.Post.where(title: $eq: "Ruby").count (error, count) => assert.equal count, 1 done() test 'where(title: /R/)', (done) -> App.Post.where(title: /R/).count (error, count) => assert.equal count, 1 done() test 'where(title: /[Rr]/)', (done) -> App.Post.where(title: /[Rr]/).count (error, count) => assert.equal count, 2 done() describe '$neq', -> describeWith(Tower.Store.Memory) describeWith(Tower.Store.MongoDB)
[ { "context": "earchResult\n model: 'artist',\n id: 'andy-warhol',\n display: 'Andy Warhol',\n label: ", "end": 6976, "score": 0.999534010887146, "start": 6965, "tag": "USERNAME", "value": "andy-warhol" }, { "context": "st',\n id: 'andy-warhol',\n display: 'Andy Warhol',\n label: 'Artist',\n score: 'excell", "end": 7008, "score": 0.9997249841690063, "start": 6997, "tag": "NAME", "value": "Andy Warhol" }, { "context": "Result\n model: 'partnershow',\n id: 'oriol-galeria-dart-oriol-galeria-dart-at-the-armory-s", "end": 7414, "score": 0.9311395287513733, "start": 7411, "tag": "USERNAME", "value": "ori" } ]
apps/fair/test/templates.coffee
kanaabe/microgravity
0
_ = require 'underscore' jade = require 'jade' path = require 'path' fs = require 'fs' cheerio = require 'cheerio' Backbone = require 'backbone' Shows = require '../../../collections/shows_feed' Fair = require '../../../models/fair' Profile = require '../../../models/profile' PartnerLocation = require '../../../models/partner_location' Artist = require '../../../models/artist' { fabricate } = require 'antigravity' SearchResult = require '../../../models/search_result' Artworks = require '../../../collections/artworks' describe 'Artworks template', -> describe 'with no params', -> beforeEach -> filename = path.resolve __dirname, "../templates/artworks.jade" @page = jade.compile(fs.readFileSync(filename), filename: filename) { sd: {} fair: new Fair fabricate 'fair', filter_genes: [] filters: new Backbone.Model medium: {}, related_genes: {} } it 'renders correctly', -> @page.should.containEql '<a href="/the-armory-show/browse/artworks?filter=true">All Works</a>' @page.should.containEql 'fairs-artworks-categories' @page.should.not.containEql 'fair-artworks-list' describe 'with params', -> beforeEach -> filename = path.resolve __dirname, "../templates/artworks.jade" @page = jade.compile(fs.readFileSync(filename), filename: filename) { sd: PARAMS: filter: 'true' fair: new Fair fabricate 'fair', filter_genes: [] filters: new Backbone.Model medium: {}, related_genes: {} } it 'renders correctly', -> @page.should.not.containEql '<a href="/the-armory-show/browse/artworks?filter=true">All Works</a>' @page.should.containEql 'artwork-filter-content' describe 'Exhibitors template', -> describe 'A-Z link', -> render = (options) -> defaults = fair: new Fair(fabricate 'fair') shows: new Shows(fabricate 'show', fair_location: {}) displayToggle: true artworkColumnsTemplate: -> sd: {} params = _.extend defaults, options filename = path.resolve __dirname, "../templates/exhibitors_page.jade" jade.compile(fs.readFileSync(filename), filename: filename) params it 'hides the A-Z link unless its all exhibitors', -> render(displayToggle: false).should.not.containEql 'a-z-feed-toggle-container' render().should.containEql 'a-z-feed-toggle-container' describe 'less than 6 artworks', -> before -> render = (templateName) -> filename = path.resolve __dirname, "../templates/exhibitors_page.jade" jade.compile(fs.readFileSync(filename), filename: filename) @shows = new Shows [fabricate('show', fair: fabricate('fair'), artwork: fabricate('artwork'))] @template = render('exhibitors')( shows: @shows fair: new Fair fabricate 'fair', name: 'Armory Show 2013' sd: {} ) it 'should not display artwork slider', -> $ = cheerio.load @template $.html().should.not.containEql 'fair-exhibit-artworks-slider' describe 'more than 6 artworks', -> before -> render = (templateName) -> filename = path.resolve __dirname, "../templates/exhibitors_page.jade" jade.compile(fs.readFileSync(filename), filename: filename) artworks = [ fabricate('artwork', id: 1), fabricate('artwork', id: 2), fabricate('artwork', id: 3), fabricate('artwork', id: 4), fabricate('artwork', id: 5), fabricate('artwork', id: 6), fabricate('artwork', id: 7) ] @shows = new Shows [fabricate('show', fair: fabricate('fair'), artworks: artworks)] @template = render('exhibitors')( shows: @shows fair: new Fair fabricate 'fair', name: 'Armory Show 2013' sd: {} ) xit 'should display artwork slider', -> $ = cheerio.load @template $.html().should.containEql 'fair-exhibit-artworks-slider' describe 'Sections template', -> render = (options) -> defaults = fair: new Fair(fabricate 'fair') shows: new Shows(fabricate 'show', fair_location: {}) displayToggle: true artworkColumnsTemplate: -> sd: {} sections: new Backbone.Collection([ { section: '', partner_shows_count: 10 } { section: 'Pier 1', partner_shows_count: 2 } ]).models params = _.extend defaults, options filename = path.resolve __dirname, "../templates/sections.jade" jade.compile(fs.readFileSync(filename), filename: filename) params it 'working links', -> render().should.not.containEql 'null' describe 'Main page template ', -> beforeEach -> render = (profile, fair) -> filename = path.resolve __dirname, "../templates/main_page.jade" jade.compile(fs.readFileSync(filename), filename: filename) fair: fair profile: profile sd: {} sections: new Backbone.Collection([ { section: '', partner_shows_count: 10 } { section: 'Pier 1', partner_shows_count: 2 } ]).models it 'renders a profile icon', -> profile = new Profile(fabricate('profile')) fair = new Fair(fabricate('fair')) render(profile, fair).should.containEql profile.iconUrl() render(profile, fair).should.containEql 'fair-page-profile-icon' profile.unset 'icon' render(profile, fair).should.not.containEql 'fair-page-profile-icon' it 'renders a banner when one is present', -> profile = new Profile(fabricate('profile')) fair = new Fair(fabricate('fair')) fair.set 'banner_image_urls', {'mobile-fair-cover': 'http://placehold.it/350x150'} render(profile, fair).should.containEql 'mobile-fair-cover' render(profile, fair).should.not.containEql 'fair-page-profile-icon' fair.unset 'banner_image_urls' render(profile, fair).should.not.containEql 'mobile-fair-cover' render(profile, fair).should.containEql 'fair-page-profile-icon' describe 'Info page template ', -> render = (fair, location) -> filename = path.resolve __dirname, "../templates/info.jade" jade.compile(fs.readFileSync(filename), filename: filename) fair: fair location: location sd: {} it 'does not render a map without coordinates', -> fair = new Fair fabricate('fair') @html = render fair, new PartnerLocation(fair.get('location')) @html.should.not.containEql 'fair-page-info-map' it 'render a map with coordinates', -> fair = new Fair fabricate('fair') @html = render fair, new PartnerLocation(fair.get('location'), coordinates: { lat: 1, lng: 2 } ) @html.should.not.containEql 'fair-page-info-map' it 'renders markdown converted content', -> fair = new Fair fabricate('fair') @html = render fair, new PartnerLocation(fair.get('location')) @html.should.containEql fair.mdToHtml('about') @html.should.containEql 'fair-page-info-content' describe 'Search', -> beforeEach -> @results = [ new SearchResult model: 'artist', id: 'andy-warhol', display: 'Andy Warhol', label: 'Artist', score: 'excellent', search_detail: 'American, 1928-1987', published: true, highlights: [], image_url: 'http://artsy.net/api/v1/artist/andy-warh' display_model: 'Artist', location: '/artist/andy-warhol', is_human: true ] @fairResults = [ new SearchResult model: 'partnershow', id: 'oriol-galeria-dart-oriol-galeria-dart-at-the-armory-show-2013', display: 'Oriol Galeria d\'Art at The Armory Show 2013', label: 'Partnershow', score: 'excellent', search_detail: null, published: false, highlights: [], image_url: 'http://artsy.net/api/v1/' display_model: 'Booth', location: '/show/oriol-galeria-dart-oriol-galeria-dart-at-the-armory-show-2013', is_human: false ] @term = 'bitty' @fair = new Fair (fabricate 'fair', about: 'about the fair', id: 'cat') @fairResults[0].updateForFair @fair @profile = new Profile(fabricate('profile', id: 'dog')) render = (locals) -> filename = path.resolve __dirname, "../templates/search_results.jade" jade.compile(fs.readFileSync(filename), filename: filename)(locals) it 'renders without errors', -> html = render( fair: @fair term: @term fairResults: @fairResults results: @results sd: {} profile: @profile ) $ = cheerio.load html $('.artsy-search-results .search-result').length.should.equal 1 $('.fair-search-results .search-result').html().should.containEql 'Booth' $('.fair-search-results .search-result').length.should.equal 1 it 'submits the form to the correct route', -> html = render( fair: @fair term: @term fairResults: @fairResults results: @results sd: {} profile: @profile ) $ = cheerio.load html $('form').attr('action').should.equal 'dog/search' # note this is the profile id xdescribe 'For You template ', -> describe 'Artist template ', -> it 'protects against those crazy fair booths that exist in the aether', -> # TODO: Consolidate these various render helpers render = (params) -> filename = path.resolve __dirname, "../templates/artist.jade" jade.compile(fs.readFileSync(filename), filename: filename) _.extend( profile: @profile artist: new Artist fabricate 'artist' fairResults: @fairResults results: @results fair: new Backbone.Model fabricate 'fair' sd: {} , params) render { shows: new Shows [fabricate 'show', fair_location: null] }, 'artist'
34473
_ = require 'underscore' jade = require 'jade' path = require 'path' fs = require 'fs' cheerio = require 'cheerio' Backbone = require 'backbone' Shows = require '../../../collections/shows_feed' Fair = require '../../../models/fair' Profile = require '../../../models/profile' PartnerLocation = require '../../../models/partner_location' Artist = require '../../../models/artist' { fabricate } = require 'antigravity' SearchResult = require '../../../models/search_result' Artworks = require '../../../collections/artworks' describe 'Artworks template', -> describe 'with no params', -> beforeEach -> filename = path.resolve __dirname, "../templates/artworks.jade" @page = jade.compile(fs.readFileSync(filename), filename: filename) { sd: {} fair: new Fair fabricate 'fair', filter_genes: [] filters: new Backbone.Model medium: {}, related_genes: {} } it 'renders correctly', -> @page.should.containEql '<a href="/the-armory-show/browse/artworks?filter=true">All Works</a>' @page.should.containEql 'fairs-artworks-categories' @page.should.not.containEql 'fair-artworks-list' describe 'with params', -> beforeEach -> filename = path.resolve __dirname, "../templates/artworks.jade" @page = jade.compile(fs.readFileSync(filename), filename: filename) { sd: PARAMS: filter: 'true' fair: new Fair fabricate 'fair', filter_genes: [] filters: new Backbone.Model medium: {}, related_genes: {} } it 'renders correctly', -> @page.should.not.containEql '<a href="/the-armory-show/browse/artworks?filter=true">All Works</a>' @page.should.containEql 'artwork-filter-content' describe 'Exhibitors template', -> describe 'A-Z link', -> render = (options) -> defaults = fair: new Fair(fabricate 'fair') shows: new Shows(fabricate 'show', fair_location: {}) displayToggle: true artworkColumnsTemplate: -> sd: {} params = _.extend defaults, options filename = path.resolve __dirname, "../templates/exhibitors_page.jade" jade.compile(fs.readFileSync(filename), filename: filename) params it 'hides the A-Z link unless its all exhibitors', -> render(displayToggle: false).should.not.containEql 'a-z-feed-toggle-container' render().should.containEql 'a-z-feed-toggle-container' describe 'less than 6 artworks', -> before -> render = (templateName) -> filename = path.resolve __dirname, "../templates/exhibitors_page.jade" jade.compile(fs.readFileSync(filename), filename: filename) @shows = new Shows [fabricate('show', fair: fabricate('fair'), artwork: fabricate('artwork'))] @template = render('exhibitors')( shows: @shows fair: new Fair fabricate 'fair', name: 'Armory Show 2013' sd: {} ) it 'should not display artwork slider', -> $ = cheerio.load @template $.html().should.not.containEql 'fair-exhibit-artworks-slider' describe 'more than 6 artworks', -> before -> render = (templateName) -> filename = path.resolve __dirname, "../templates/exhibitors_page.jade" jade.compile(fs.readFileSync(filename), filename: filename) artworks = [ fabricate('artwork', id: 1), fabricate('artwork', id: 2), fabricate('artwork', id: 3), fabricate('artwork', id: 4), fabricate('artwork', id: 5), fabricate('artwork', id: 6), fabricate('artwork', id: 7) ] @shows = new Shows [fabricate('show', fair: fabricate('fair'), artworks: artworks)] @template = render('exhibitors')( shows: @shows fair: new Fair fabricate 'fair', name: 'Armory Show 2013' sd: {} ) xit 'should display artwork slider', -> $ = cheerio.load @template $.html().should.containEql 'fair-exhibit-artworks-slider' describe 'Sections template', -> render = (options) -> defaults = fair: new Fair(fabricate 'fair') shows: new Shows(fabricate 'show', fair_location: {}) displayToggle: true artworkColumnsTemplate: -> sd: {} sections: new Backbone.Collection([ { section: '', partner_shows_count: 10 } { section: 'Pier 1', partner_shows_count: 2 } ]).models params = _.extend defaults, options filename = path.resolve __dirname, "../templates/sections.jade" jade.compile(fs.readFileSync(filename), filename: filename) params it 'working links', -> render().should.not.containEql 'null' describe 'Main page template ', -> beforeEach -> render = (profile, fair) -> filename = path.resolve __dirname, "../templates/main_page.jade" jade.compile(fs.readFileSync(filename), filename: filename) fair: fair profile: profile sd: {} sections: new Backbone.Collection([ { section: '', partner_shows_count: 10 } { section: 'Pier 1', partner_shows_count: 2 } ]).models it 'renders a profile icon', -> profile = new Profile(fabricate('profile')) fair = new Fair(fabricate('fair')) render(profile, fair).should.containEql profile.iconUrl() render(profile, fair).should.containEql 'fair-page-profile-icon' profile.unset 'icon' render(profile, fair).should.not.containEql 'fair-page-profile-icon' it 'renders a banner when one is present', -> profile = new Profile(fabricate('profile')) fair = new Fair(fabricate('fair')) fair.set 'banner_image_urls', {'mobile-fair-cover': 'http://placehold.it/350x150'} render(profile, fair).should.containEql 'mobile-fair-cover' render(profile, fair).should.not.containEql 'fair-page-profile-icon' fair.unset 'banner_image_urls' render(profile, fair).should.not.containEql 'mobile-fair-cover' render(profile, fair).should.containEql 'fair-page-profile-icon' describe 'Info page template ', -> render = (fair, location) -> filename = path.resolve __dirname, "../templates/info.jade" jade.compile(fs.readFileSync(filename), filename: filename) fair: fair location: location sd: {} it 'does not render a map without coordinates', -> fair = new Fair fabricate('fair') @html = render fair, new PartnerLocation(fair.get('location')) @html.should.not.containEql 'fair-page-info-map' it 'render a map with coordinates', -> fair = new Fair fabricate('fair') @html = render fair, new PartnerLocation(fair.get('location'), coordinates: { lat: 1, lng: 2 } ) @html.should.not.containEql 'fair-page-info-map' it 'renders markdown converted content', -> fair = new Fair fabricate('fair') @html = render fair, new PartnerLocation(fair.get('location')) @html.should.containEql fair.mdToHtml('about') @html.should.containEql 'fair-page-info-content' describe 'Search', -> beforeEach -> @results = [ new SearchResult model: 'artist', id: 'andy-warhol', display: '<NAME>', label: 'Artist', score: 'excellent', search_detail: 'American, 1928-1987', published: true, highlights: [], image_url: 'http://artsy.net/api/v1/artist/andy-warh' display_model: 'Artist', location: '/artist/andy-warhol', is_human: true ] @fairResults = [ new SearchResult model: 'partnershow', id: 'oriol-galeria-dart-oriol-galeria-dart-at-the-armory-show-2013', display: 'Oriol Galeria d\'Art at The Armory Show 2013', label: 'Partnershow', score: 'excellent', search_detail: null, published: false, highlights: [], image_url: 'http://artsy.net/api/v1/' display_model: 'Booth', location: '/show/oriol-galeria-dart-oriol-galeria-dart-at-the-armory-show-2013', is_human: false ] @term = 'bitty' @fair = new Fair (fabricate 'fair', about: 'about the fair', id: 'cat') @fairResults[0].updateForFair @fair @profile = new Profile(fabricate('profile', id: 'dog')) render = (locals) -> filename = path.resolve __dirname, "../templates/search_results.jade" jade.compile(fs.readFileSync(filename), filename: filename)(locals) it 'renders without errors', -> html = render( fair: @fair term: @term fairResults: @fairResults results: @results sd: {} profile: @profile ) $ = cheerio.load html $('.artsy-search-results .search-result').length.should.equal 1 $('.fair-search-results .search-result').html().should.containEql 'Booth' $('.fair-search-results .search-result').length.should.equal 1 it 'submits the form to the correct route', -> html = render( fair: @fair term: @term fairResults: @fairResults results: @results sd: {} profile: @profile ) $ = cheerio.load html $('form').attr('action').should.equal 'dog/search' # note this is the profile id xdescribe 'For You template ', -> describe 'Artist template ', -> it 'protects against those crazy fair booths that exist in the aether', -> # TODO: Consolidate these various render helpers render = (params) -> filename = path.resolve __dirname, "../templates/artist.jade" jade.compile(fs.readFileSync(filename), filename: filename) _.extend( profile: @profile artist: new Artist fabricate 'artist' fairResults: @fairResults results: @results fair: new Backbone.Model fabricate 'fair' sd: {} , params) render { shows: new Shows [fabricate 'show', fair_location: null] }, 'artist'
true
_ = require 'underscore' jade = require 'jade' path = require 'path' fs = require 'fs' cheerio = require 'cheerio' Backbone = require 'backbone' Shows = require '../../../collections/shows_feed' Fair = require '../../../models/fair' Profile = require '../../../models/profile' PartnerLocation = require '../../../models/partner_location' Artist = require '../../../models/artist' { fabricate } = require 'antigravity' SearchResult = require '../../../models/search_result' Artworks = require '../../../collections/artworks' describe 'Artworks template', -> describe 'with no params', -> beforeEach -> filename = path.resolve __dirname, "../templates/artworks.jade" @page = jade.compile(fs.readFileSync(filename), filename: filename) { sd: {} fair: new Fair fabricate 'fair', filter_genes: [] filters: new Backbone.Model medium: {}, related_genes: {} } it 'renders correctly', -> @page.should.containEql '<a href="/the-armory-show/browse/artworks?filter=true">All Works</a>' @page.should.containEql 'fairs-artworks-categories' @page.should.not.containEql 'fair-artworks-list' describe 'with params', -> beforeEach -> filename = path.resolve __dirname, "../templates/artworks.jade" @page = jade.compile(fs.readFileSync(filename), filename: filename) { sd: PARAMS: filter: 'true' fair: new Fair fabricate 'fair', filter_genes: [] filters: new Backbone.Model medium: {}, related_genes: {} } it 'renders correctly', -> @page.should.not.containEql '<a href="/the-armory-show/browse/artworks?filter=true">All Works</a>' @page.should.containEql 'artwork-filter-content' describe 'Exhibitors template', -> describe 'A-Z link', -> render = (options) -> defaults = fair: new Fair(fabricate 'fair') shows: new Shows(fabricate 'show', fair_location: {}) displayToggle: true artworkColumnsTemplate: -> sd: {} params = _.extend defaults, options filename = path.resolve __dirname, "../templates/exhibitors_page.jade" jade.compile(fs.readFileSync(filename), filename: filename) params it 'hides the A-Z link unless its all exhibitors', -> render(displayToggle: false).should.not.containEql 'a-z-feed-toggle-container' render().should.containEql 'a-z-feed-toggle-container' describe 'less than 6 artworks', -> before -> render = (templateName) -> filename = path.resolve __dirname, "../templates/exhibitors_page.jade" jade.compile(fs.readFileSync(filename), filename: filename) @shows = new Shows [fabricate('show', fair: fabricate('fair'), artwork: fabricate('artwork'))] @template = render('exhibitors')( shows: @shows fair: new Fair fabricate 'fair', name: 'Armory Show 2013' sd: {} ) it 'should not display artwork slider', -> $ = cheerio.load @template $.html().should.not.containEql 'fair-exhibit-artworks-slider' describe 'more than 6 artworks', -> before -> render = (templateName) -> filename = path.resolve __dirname, "../templates/exhibitors_page.jade" jade.compile(fs.readFileSync(filename), filename: filename) artworks = [ fabricate('artwork', id: 1), fabricate('artwork', id: 2), fabricate('artwork', id: 3), fabricate('artwork', id: 4), fabricate('artwork', id: 5), fabricate('artwork', id: 6), fabricate('artwork', id: 7) ] @shows = new Shows [fabricate('show', fair: fabricate('fair'), artworks: artworks)] @template = render('exhibitors')( shows: @shows fair: new Fair fabricate 'fair', name: 'Armory Show 2013' sd: {} ) xit 'should display artwork slider', -> $ = cheerio.load @template $.html().should.containEql 'fair-exhibit-artworks-slider' describe 'Sections template', -> render = (options) -> defaults = fair: new Fair(fabricate 'fair') shows: new Shows(fabricate 'show', fair_location: {}) displayToggle: true artworkColumnsTemplate: -> sd: {} sections: new Backbone.Collection([ { section: '', partner_shows_count: 10 } { section: 'Pier 1', partner_shows_count: 2 } ]).models params = _.extend defaults, options filename = path.resolve __dirname, "../templates/sections.jade" jade.compile(fs.readFileSync(filename), filename: filename) params it 'working links', -> render().should.not.containEql 'null' describe 'Main page template ', -> beforeEach -> render = (profile, fair) -> filename = path.resolve __dirname, "../templates/main_page.jade" jade.compile(fs.readFileSync(filename), filename: filename) fair: fair profile: profile sd: {} sections: new Backbone.Collection([ { section: '', partner_shows_count: 10 } { section: 'Pier 1', partner_shows_count: 2 } ]).models it 'renders a profile icon', -> profile = new Profile(fabricate('profile')) fair = new Fair(fabricate('fair')) render(profile, fair).should.containEql profile.iconUrl() render(profile, fair).should.containEql 'fair-page-profile-icon' profile.unset 'icon' render(profile, fair).should.not.containEql 'fair-page-profile-icon' it 'renders a banner when one is present', -> profile = new Profile(fabricate('profile')) fair = new Fair(fabricate('fair')) fair.set 'banner_image_urls', {'mobile-fair-cover': 'http://placehold.it/350x150'} render(profile, fair).should.containEql 'mobile-fair-cover' render(profile, fair).should.not.containEql 'fair-page-profile-icon' fair.unset 'banner_image_urls' render(profile, fair).should.not.containEql 'mobile-fair-cover' render(profile, fair).should.containEql 'fair-page-profile-icon' describe 'Info page template ', -> render = (fair, location) -> filename = path.resolve __dirname, "../templates/info.jade" jade.compile(fs.readFileSync(filename), filename: filename) fair: fair location: location sd: {} it 'does not render a map without coordinates', -> fair = new Fair fabricate('fair') @html = render fair, new PartnerLocation(fair.get('location')) @html.should.not.containEql 'fair-page-info-map' it 'render a map with coordinates', -> fair = new Fair fabricate('fair') @html = render fair, new PartnerLocation(fair.get('location'), coordinates: { lat: 1, lng: 2 } ) @html.should.not.containEql 'fair-page-info-map' it 'renders markdown converted content', -> fair = new Fair fabricate('fair') @html = render fair, new PartnerLocation(fair.get('location')) @html.should.containEql fair.mdToHtml('about') @html.should.containEql 'fair-page-info-content' describe 'Search', -> beforeEach -> @results = [ new SearchResult model: 'artist', id: 'andy-warhol', display: 'PI:NAME:<NAME>END_PI', label: 'Artist', score: 'excellent', search_detail: 'American, 1928-1987', published: true, highlights: [], image_url: 'http://artsy.net/api/v1/artist/andy-warh' display_model: 'Artist', location: '/artist/andy-warhol', is_human: true ] @fairResults = [ new SearchResult model: 'partnershow', id: 'oriol-galeria-dart-oriol-galeria-dart-at-the-armory-show-2013', display: 'Oriol Galeria d\'Art at The Armory Show 2013', label: 'Partnershow', score: 'excellent', search_detail: null, published: false, highlights: [], image_url: 'http://artsy.net/api/v1/' display_model: 'Booth', location: '/show/oriol-galeria-dart-oriol-galeria-dart-at-the-armory-show-2013', is_human: false ] @term = 'bitty' @fair = new Fair (fabricate 'fair', about: 'about the fair', id: 'cat') @fairResults[0].updateForFair @fair @profile = new Profile(fabricate('profile', id: 'dog')) render = (locals) -> filename = path.resolve __dirname, "../templates/search_results.jade" jade.compile(fs.readFileSync(filename), filename: filename)(locals) it 'renders without errors', -> html = render( fair: @fair term: @term fairResults: @fairResults results: @results sd: {} profile: @profile ) $ = cheerio.load html $('.artsy-search-results .search-result').length.should.equal 1 $('.fair-search-results .search-result').html().should.containEql 'Booth' $('.fair-search-results .search-result').length.should.equal 1 it 'submits the form to the correct route', -> html = render( fair: @fair term: @term fairResults: @fairResults results: @results sd: {} profile: @profile ) $ = cheerio.load html $('form').attr('action').should.equal 'dog/search' # note this is the profile id xdescribe 'For You template ', -> describe 'Artist template ', -> it 'protects against those crazy fair booths that exist in the aether', -> # TODO: Consolidate these various render helpers render = (params) -> filename = path.resolve __dirname, "../templates/artist.jade" jade.compile(fs.readFileSync(filename), filename: filename) _.extend( profile: @profile artist: new Artist fabricate 'artist' fairResults: @fairResults results: @results fair: new Backbone.Model fabricate 'fair' sd: {} , params) render { shows: new Shows [fabricate 'show', fair_location: null] }, 'artist'
[ { "context": "ateTeam = ->\n [ Factory(\"Magikarp\")\n Factory(\"Gyarados\")\n Factory('Hitmonchan')\n Factory(\"Cele", "end": 322, "score": 0.5182156562805176, "start": 318, "tag": "NAME", "value": "Gyar" }, { "context": "layers.push server.findOrCreateUser(id: 1, name: 'abc', @stubSpark())\n players.push server.findOrCre", "end": 794, "score": 0.9956479072570801, "start": 791, "tag": "NAME", "value": "abc" }, { "context": "layers.push server.findOrCreateUser(id: 2, name: 'def', @stubSpark())\n\n spies = []\n for player in", "end": 869, "score": 0.9816229343414307, "start": 866, "tag": "NAME", "value": "def" }, { "context": " derp = server.findOrCreateUser(id: 1, name: 'derp', @stubSpark())\n server.queuePlayer(derp.nam", "end": 1452, "score": 0.8285276889801025, "start": 1448, "tag": "USERNAME", "value": "derp" }, { "context": " derp = server.findOrCreateUser(id: 1, name: 'derp', @stubSpark())\n server.queuePlayer(derp.nam", "end": 1737, "score": 0.7320435047149658, "start": 1733, "tag": "USERNAME", "value": "derp" }, { "context": " user = server.findOrCreateUser(id: 1, name: \"Batman\", @stubSpark())\n other = server.findOrCreate", "end": 2772, "score": 0.9997088313102722, "start": 2766, "tag": "NAME", "value": "Batman" }, { "context": " other = server.findOrCreateUser(id: 2, name: \"Robin\", @stubSpark())\n team = generateTeam()\n ", "end": 2846, "score": 0.9997216463088989, "start": 2841, "tag": "NAME", "value": "Robin" }, { "context": " user = server.findOrCreateUser(id: 1, name: \"Batman\", @stubSpark())\n other = server.findOrCreate", "end": 3614, "score": 0.9996447563171387, "start": 3608, "tag": "NAME", "value": "Batman" }, { "context": " other = server.findOrCreateUser(id: 2, name: \"Robin\", @stubSpark())\n team = generateTeam()\n ", "end": 3688, "score": 0.9997356534004211, "start": 3683, "tag": "NAME", "value": "Robin" }, { "context": " user = server.findOrCreateUser(id: 1, name: \"Batman\", @stubSpark())\n other = server.findOrCreate", "end": 4278, "score": 0.9996209144592285, "start": 4272, "tag": "NAME", "value": "Batman" }, { "context": " other = server.findOrCreateUser(id: 2, name: \"Robin\", @stubSpark())\n format = 'xy1000'\n\n mo", "end": 4352, "score": 0.9997053742408752, "start": 4347, "tag": "NAME", "value": "Robin" }, { "context": " user = server.findOrCreateUser(id: 1, name: \"Batman\", @stubSpark())\n other = server.findOrCreate", "end": 4722, "score": 0.9996243119239807, "start": 4716, "tag": "NAME", "value": "Batman" }, { "context": " other = server.findOrCreateUser(id: 2, name: \"Robin\", @stubSpark())\n format = 'xy1000'\n tea", "end": 4796, "score": 0.9996857643127441, "start": 4791, "tag": "NAME", "value": "Robin" }, { "context": " user = server.findOrCreateUser(id: 1, name: \"Batman\", @stubSpark())\n other = server.findOrCreate", "end": 5260, "score": 0.9995753765106201, "start": 5254, "tag": "NAME", "value": "Batman" }, { "context": " other = server.findOrCreateUser(id: 2, name: \"Robin\", @stubSpark())\n format = 'xy1000'\n tea", "end": 5334, "score": 0.9997239112854004, "start": 5329, "tag": "NAME", "value": "Robin" }, { "context": " user = server.findOrCreateUser(id: 1, name: \"Batman\", @stubSpark())\n other = server.findOrCreate", "end": 5750, "score": 0.9997156262397766, "start": 5744, "tag": "NAME", "value": "Batman" }, { "context": " other = server.findOrCreateUser(id: 2, name: \"Robin\", @stubSpark())\n team = generateTeam()\n ", "end": 5824, "score": 0.9997879266738892, "start": 5819, "tag": "NAME", "value": "Robin" }, { "context": " user = server.findOrCreateUser(id: 1, name: \"Batman\", @stubSpark())\n team = generateTeam()\n ", "end": 6261, "score": 0.9997334480285645, "start": 6255, "tag": "NAME", "value": "Batman" }, { "context": " user = server.findOrCreateUser(id: 1, name: \"Batman\", @stubSpark())\n other = server.findOrCreate", "end": 6649, "score": 0.9996920228004456, "start": 6643, "tag": "NAME", "value": "Batman" }, { "context": " other = server.findOrCreateUser(id: 2, name: \"Robin\", @stubSpark())\n team = generateTeam()\n ", "end": 6723, "score": 0.9997428059577942, "start": 6718, "tag": "NAME", "value": "Robin" }, { "context": " user = server.findOrCreateUser(id: 1, name: \"Batman\", @stubSpark())\n other = server.findOrCreate", "end": 7130, "score": 0.9996790289878845, "start": 7124, "tag": "NAME", "value": "Batman" }, { "context": " other = server.findOrCreateUser(id: 2, name: \"Robin\", @stubSpark())\n team = generateTeam()\n ", "end": 7204, "score": 0.9997870326042175, "start": 7199, "tag": "NAME", "value": "Robin" }, { "context": " user = server.findOrCreateUser(id: 1, name: \"Batman\", @stubSpark())\n other = server.findOrCreate", "end": 7674, "score": 0.9996339678764343, "start": 7668, "tag": "NAME", "value": "Batman" }, { "context": " other = server.findOrCreateUser(id: 2, name: \"Robin\", @stubSpark())\n team = generateTeam()\n ", "end": 7748, "score": 0.999744176864624, "start": 7743, "tag": "NAME", "value": "Robin" }, { "context": " user = server.findOrCreateUser(id: 1, name: \"Batman\", @stubSpark())\n other = server.findOrCreate", "end": 8284, "score": 0.9996280074119568, "start": 8278, "tag": "NAME", "value": "Batman" }, { "context": " other = server.findOrCreateUser(id: 2, name: \"Robin\", @stubSpark())\n format = 'xy1000'\n tea", "end": 8358, "score": 0.9997288584709167, "start": 8353, "tag": "NAME", "value": "Robin" }, { "context": " user = server.findOrCreateUser(id: 1, name: \"Batman\", @stubSpark())\n other = server.findOrCreate", "end": 8850, "score": 0.999640703201294, "start": 8844, "tag": "NAME", "value": "Batman" }, { "context": " other = server.findOrCreateUser(id: 2, name: \"Robin\", @stubSpark())\n team = generateTeam()\n ", "end": 8924, "score": 0.9997503757476807, "start": 8919, "tag": "NAME", "value": "Robin" }, { "context": " user = server.findOrCreateUser(id: 1, name: \"Batman\", @stubSpark())\n other = server.findOrCreate", "end": 9646, "score": 0.9996428489685059, "start": 9640, "tag": "NAME", "value": "Batman" }, { "context": " other = server.findOrCreateUser(id: 2, name: \"Robin\", @stubSpark())\n team = generateTeam()\n ", "end": 9720, "score": 0.9997228384017944, "start": 9715, "tag": "NAME", "value": "Robin" }, { "context": " user = server.findOrCreateUser(id: 1, name: \"Batman\", @stubSpark())\n other = server.findOrCreate", "end": 10256, "score": 0.999603807926178, "start": 10250, "tag": "NAME", "value": "Batman" }, { "context": " other = server.findOrCreateUser(id: 2, name: \"Robin\", @stubSpark())\n team = generateTeam()\n ", "end": 10330, "score": 0.9996840953826904, "start": 10325, "tag": "NAME", "value": "Robin" }, { "context": " user = server.findOrCreateUser(id: 1, name: \"Batman\", @stubSpark())\n other = server.findOrCreate", "end": 11053, "score": 0.999671459197998, "start": 11047, "tag": "NAME", "value": "Batman" }, { "context": " other = server.findOrCreateUser(id: 2, name: \"Robin\", @stubSpark())\n team = generateTeam()\n ", "end": 11127, "score": 0.9997609853744507, "start": 11122, "tag": "NAME", "value": "Robin" }, { "context": " user = server.findOrCreateUser(id: 1, name: \"Batman\", @stubSpark())\n other = server.findOrCreate", "end": 11615, "score": 0.9997382164001465, "start": 11609, "tag": "NAME", "value": "Batman" }, { "context": " other = server.findOrCreateUser(id: 2, name: \"Robin\", @stubSpark())\n team = generateTeam()\n ", "end": 11689, "score": 0.9997654557228088, "start": 11684, "tag": "NAME", "value": "Robin" }, { "context": " @user = @server.findOrCreateUser(id: 1, name: \"Batman\", @stubSpark())\n @other = @server.findOrCrea", "end": 12133, "score": 0.9997178912162781, "start": 12127, "tag": "NAME", "value": "Batman" }, { "context": " @other = @server.findOrCreateUser(id: 2, name: \"Robin\", @stubSpark())\n\n it \"creates a battle with th", "end": 12209, "score": 0.9997420907020569, "start": 12204, "tag": "NAME", "value": "Robin" }, { "context": " conditions = []\n\n @server.registerChallenge(@user, @other.name, format, team, conditions)\n sho", "end": 13712, "score": 0.8084270358085632, "start": 13707, "tag": "USERNAME", "value": "@user" }, { "context": "name][@other.name]\n @server.acceptChallenge(@other, @user.name, team)\n should.not.exist @server", "end": 13852, "score": 0.5764878988265991, "start": 13847, "tag": "USERNAME", "value": "other" }, { "context": " conditions = []\n\n userSpy = @sandbox.spy(@user, 'send')\n userSpy.withArgs('challengeSuccess", "end": 14139, "score": 0.9806962013244629, "start": 14134, "tag": "USERNAME", "value": "@user" }, { "context": "ccess', @other.name)\n otherSpy = @sandbox.spy(@other, 'send')\n otherSpy.withArgs('challengeSucces", "end": 14241, "score": 0.6650246977806091, "start": 14235, "tag": "USERNAME", "value": "@other" }, { "context": " conditions = []\n\n @server.registerChallenge(@user, @other.name, format, team, conditions)\n moc", "end": 14806, "score": 0.7860331535339355, "start": 14801, "tag": "USERNAME", "value": "@user" }, { "context": "ge(@user, @other.name, format, team, conditions, \"Bruce Wayne\")\n battleId = @server.acceptChallenge(@other", "end": 15245, "score": 0.9873560070991516, "start": 15234, "tag": "NAME", "value": "Bruce Wayne" }, { "context": "server.acceptChallenge(@other, @user.name, team, \"Jason Todd\")\n battle = @server.findBattle(battleId)\n ", "end": 15326, "score": 0.999832272529602, "start": 15316, "tag": "NAME", "value": "Jason Todd" }, { "context": "eId)\n battle.battle.playerNames.should.eql [\"Bruce Wayne\", \"Jason Todd\"]\n\n it \"sets the rating key to b", "end": 15429, "score": 0.9998455047607422, "start": 15418, "tag": "NAME", "value": "Bruce Wayne" }, { "context": "le.battle.playerNames.should.eql [\"Bruce Wayne\", \"Jason Todd\"]\n\n it \"sets the rating key to be the unique a", "end": 15443, "score": 0.9998377561569214, "start": 15433, "tag": "NAME", "value": "Jason Todd" }, { "context": "ge(@user, @other.name, format, team, conditions, \"Bruce Wayne\")\n battleId = @server.acceptChallenge(@other", "end": 15716, "score": 0.9819933772087097, "start": 15705, "tag": "NAME", "value": "Bruce Wayne" }, { "context": "server.acceptChallenge(@other, @user.name, team, \"Jason Todd\")\n battle = @server.findBattle(battleId)\n\n ", "end": 15797, "score": 0.999824583530426, "start": 15787, "tag": "NAME", "value": "Jason Todd" }, { "context": "dBattle(battleId)\n\n battle.battle.getPlayer(\"Batman\").ratingKey.should.equal alts.uniqueId(@user.name", "end": 15882, "score": 0.9998450875282288, "start": 15876, "tag": "NAME", "value": "Batman" }, { "context": "ratingKey.should.equal alts.uniqueId(@user.name, \"Bruce Wayne\")\n battle.battle.getPlayer(\"Robin\").ratingKe", "end": 15946, "score": 0.9998420476913452, "start": 15935, "tag": "NAME", "value": "Bruce Wayne" }, { "context": "me, \"Bruce Wayne\")\n battle.battle.getPlayer(\"Robin\").ratingKey.should.equal alts.uniqueId(@other.nam", "end": 15985, "score": 0.999860942363739, "start": 15980, "tag": "NAME", "value": "Robin" }, { "context": "atingKey.should.equal alts.uniqueId(@other.name, \"Jason Todd\")\n\n describe \"#leave\", ->\n it \"removes challe", "end": 16049, "score": 0.9998357892036438, "start": 16039, "tag": "NAME", "value": "Jason Todd" }, { "context": " user = server.findOrCreateUser(id: 1, name: \"Batman\", spark = @stubSpark())\n other = server.find", "end": 16215, "score": 0.9998562932014465, "start": 16209, "tag": "NAME", "value": "Batman" }, { "context": " other = server.findOrCreateUser(id: 2, name: \"Robin\", @stubSpark())\n team = generateTeam()\n ", "end": 16297, "score": 0.999872088432312, "start": 16292, "tag": "NAME", "value": "Robin" }, { "context": " user = server.findOrCreateUser(id: 1, name: \"Batman\", spark = @stubSpark())\n other = server.find", "end": 16789, "score": 0.9995010495185852, "start": 16783, "tag": "NAME", "value": "Batman" }, { "context": " other = server.findOrCreateUser(id: 2, name: \"Robin\", @stubSpark())\n team = generateTeam()\n ", "end": 16871, "score": 0.9996315240859985, "start": 16866, "tag": "NAME", "value": "Robin" }, { "context": " user = server.findOrCreateUser(id: 1, name: \"Batman\", @stubSpark())\n other = server.findOrCreate", "end": 17441, "score": 0.9996488690376282, "start": 17435, "tag": "NAME", "value": "Batman" }, { "context": " other = server.findOrCreateUser(id: 2, name: \"Robin\", @stubSpark())\n team = generateTeam()\n ", "end": 17515, "score": 0.9996696710586548, "start": 17510, "tag": "NAME", "value": "Robin" }, { "context": " team = generateTeam()\n team[0] = Factory(\"Magikarp\", moves: [ \"Splash\", \"Armageddon\" ])\n server", "end": 20707, "score": 0.5955815315246582, "start": 20699, "tag": "NAME", "value": "Magikarp" }, { "context": " team = generateTeam()\n team[0] = Factory(\"Magikarp\", ability: \"Wonder Guard\")\n server.vali", "end": 20961, "score": 0.5146622657775879, "start": 20958, "tag": "NAME", "value": "Mag" }, { "context": "team = generateTeam()\n team[0] = Factory(\"Cloyster\", ability: \"Overcoat\")\n server.validateTeam(", "end": 21443, "score": 0.5402826070785522, "start": 21438, "tag": "NAME", "value": "yster" }, { "context": " team = generateTeam()\n team[0] = Factory(\"Magikarp\", level: 0)\n server.validateTeam(team).shoul", "end": 21675, "score": 0.6872992515563965, "start": 21667, "tag": "NAME", "value": "Magikarp" }, { "context": " team = generateTeam()\n team[0] = Factory(\"Magikarp\", level: \"hi\")\n server.validateTeam(tea", "end": 21893, "score": 0.5535030961036682, "start": 21890, "tag": "NAME", "value": "Mag" }, { "context": "am = generateTeam()\n team[0] = Factory(\"Magikarp\", level: \"hi\")\n server.validateTeam(team).sh", "end": 21898, "score": 0.5825591087341309, "start": 21895, "tag": "NAME", "value": "arp" }, { "context": " team = generateTeam()\n team[0] = Factory(\"Magikarp\", level: 101)\n server.validateTeam(team).sho", "end": 22163, "score": 0.5971630215644836, "start": 22155, "tag": "NAME", "value": "Magikarp" }, { "context": "am = generateTeam()\n team[0] = Factory(\"Magikarp\", ivs: { hp: -1 })\n server.validateTeam(team", "end": 22388, "score": 0.5056656002998352, "start": 22385, "tag": "NAME", "value": "arp" }, { "context": " team = generateTeam()\n team[0].name = \"Latios\"\n server.validateTeam(team).should.not.be.em", "end": 25495, "score": 0.9855591654777527, "start": 25489, "tag": "NAME", "value": "Latios" }, { "context": "ver()\n server.findOrCreateUser(id: 1, name: \"hey\", spark1 = @stubSpark())\n server.join(spark1", "end": 28212, "score": 0.8039785027503967, "start": 28209, "tag": "NAME", "value": "hey" }, { "context": "(=>\n server.findOrCreateUser(id: 1, name: \"hey\", spark2 = @stubSpark())\n server.join(spar", "end": 28323, "score": 0.6901149749755859, "start": 28320, "tag": "NAME", "value": "hey" }, { "context": ", \"b\" ]\n server.findOrCreateUser(id: 1, name: user1, spark1 = @stubSpark())\n server.findOrCreat", "end": 30174, "score": 0.664617657661438, "start": 30170, "tag": "USERNAME", "value": "user" }, { "context": "e) ->\n @server = new BattleServer()\n [ @user1, @user2, @user3 ] = [ \"a\", \"b\", \"c\" ]\n for n", "end": 31556, "score": 0.7481426000595093, "start": 31551, "tag": "USERNAME", "value": "user1" }, { "context": " @server = new BattleServer()\n [ @user1, @user2, @user3 ] = [ \"a\", \"b\", \"c\" ]\n for name, i ", "end": 31563, "score": 0.842803955078125, "start": 31559, "tag": "USERNAME", "value": "user" }, { "context": "er3 ] = [ \"a\", \"b\", \"c\" ]\n for name, i in [ @user1, @user2, @user3 ]\n @server.findOrCreateUs", "end": 31623, "score": 0.8162186741828918, "start": 31619, "tag": "USERNAME", "value": "user" }, { "context": "[ \"a\", \"b\", \"c\" ]\n for name, i in [ @user1, @user2, @user3 ]\n @server.findOrCreateUser(id: i", "end": 31631, "score": 0.838421106338501, "start": 31627, "tag": "USERNAME", "value": "user" }, { "context": "b\", \"c\" ]\n for name, i in [ @user1, @user2, @user3 ]\n @server.findOrCreateUser(id: i, name: ", "end": 31639, "score": 0.6212201714515686, "start": 31635, "tag": "USERNAME", "value": "user" }, { "context": "ame: name, @stubSpark())\n @server.queuePlayer(@user1, generateTeam()).should.be.empty\n @server.qu", "end": 31741, "score": 0.9956464767456055, "start": 31735, "tag": "USERNAME", "value": "@user1" }, { "context": "eTeam()).should.be.empty\n @server.queuePlayer(@user2, generateTeam()).should.be.empty\n @server.qu", "end": 31807, "score": 0.9961977601051331, "start": 31801, "tag": "USERNAME", "value": "@user2" }, { "context": "eTeam()).should.be.empty\n @server.queuePlayer(@user3, generateTeam()).should.be.empty\n @server.qu", "end": 31873, "score": 0.9965130686759949, "start": 31867, "tag": "USERNAME", "value": "@user3" }, { "context": "battles if ended\", ->\n @server.getUserBattles(@relevantUser).should.not.be.empty\n battle = @server.findB", "end": 32221, "score": 0.8954368233680725, "start": 32208, "tag": "USERNAME", "value": "@relevantUser" }, { "context": " battle.endBattle()\n @server.getUserBattles(@user1).should.be.empty\n @server.getUserBattles(@us", "end": 32352, "score": 0.9816017150878906, "start": 32346, "tag": "USERNAME", "value": "@user1" }, { "context": "ser1).should.be.empty\n @server.getUserBattles(@user2).should.be.empty\n @server.getUserBattles(@us", "end": 32405, "score": 0.9906209111213684, "start": 32399, "tag": "USERNAME", "value": "@user2" }, { "context": "ser2).should.be.empty\n @server.getUserBattles(@user3).should.be.empty\n\n it \"removes from user battl", "end": 32458, "score": 0.9896801114082336, "start": 32452, "tag": "USERNAME", "value": "@user3" }, { "context": "les if forfeited\", ->\n @server.getUserBattles(@relevantUser).should.not.be.empty\n battle = @server.f", "end": 32567, "score": 0.5903410911560059, "start": 32558, "tag": "USERNAME", "value": "@relevant" }, { "context": "ver.findBattle(@battleIds[0])\n battle.forfeit(@relevantUser)\n @server.getUserBattles(@user1).should.be.e", "end": 32676, "score": 0.688930094242096, "start": 32663, "tag": "USERNAME", "value": "@relevantUser" }, { "context": "orfeit(@relevantUser)\n @server.getUserBattles(@user1).should.be.empty\n @server.getUserBattles(@us", "end": 32713, "score": 0.9945010542869568, "start": 32707, "tag": "USERNAME", "value": "@user1" }, { "context": "ser1).should.be.empty\n @server.getUserBattles(@user2).should.be.empty\n @server.getUserBattles(@us", "end": 32766, "score": 0.9885034561157227, "start": 32760, "tag": "USERNAME", "value": "@user2" }, { "context": "ser2).should.be.empty\n @server.getUserBattles(@user3).should.be.empty\n", "end": 32819, "score": 0.9208100438117981, "start": 32813, "tag": "USERNAME", "value": "@user3" } ]
test/server_spec.coffee
sarenji/pokebattle-sim
5
require './helpers' {BattleServer} = require('../server/server') {Conditions, DEFAULT_FORMAT} = require '../shared/conditions' {Protocol} = require '../shared/protocol' {Factory} = require './factory' alts = require('../server/alts') should = require('should') generateTeam = -> [ Factory("Magikarp") Factory("Gyarados") Factory('Hitmonchan') Factory("Celebi") Factory("Blissey") Factory("Alakazam") ] describe 'BattleServer', -> it 'can create a new battle', -> server = new BattleServer() battleId = server.createBattle() server.battles.should.have.ownProperty battleId it "sends the 'spectateBattle' event for each matched player", (done) -> server = new BattleServer() players = [] players.push server.findOrCreateUser(id: 1, name: 'abc', @stubSpark()) players.push server.findOrCreateUser(id: 2, name: 'def', @stubSpark()) spies = [] for player in players spy = @sandbox.spy(player.sparks[0], 'send') spies.push(spy) for player in players server.queuePlayer(player.name, generateTeam()).should.be.empty server.beginBattles (err, ids) -> throw new Error(err.message) if err return if ids.length == 0 for spy in spies spy.calledWith('spectateBattle').should.be.true done() describe "#queuePlayer", -> it "queues players", -> server = new BattleServer() derp = server.findOrCreateUser(id: 1, name: 'derp', @stubSpark()) server.queuePlayer(derp.name, generateTeam()).should.be.empty server.queues[DEFAULT_FORMAT].size().should.equal(1) it "does not queue players already queued", -> server = new BattleServer() derp = server.findOrCreateUser(id: 1, name: 'derp', @stubSpark()) server.queuePlayer(derp.name, generateTeam()).should.be.empty server.queuePlayer(derp.name, generateTeam()).should.be.empty server.queues[DEFAULT_FORMAT].size().should.equal(1) describe "#getOngoingBattles", -> it "returns one object for each queued battle", (done) -> server = new BattleServer() nBattles = 3 for i in [1..nBattles] first = 2 * i second = (2 * i) + 1 server.findOrCreateUser(id: first, name: String(first), @stubSpark()) server.findOrCreateUser(id: second, name: String(second), @stubSpark()) server.queuePlayer(String(first), generateTeam()).should.be.empty server.queuePlayer(String(second), generateTeam()).should.be.empty server.beginBattles -> server.getOngoingBattles().should.have.length(nBattles) done() describe "#registerChallenge", -> it "registers a challenge to a player", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "Batman", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "Robin", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) server.challenges.should.have.property(user.name) server.challenges[user.name].should.have.property(other.name) challenge = server.challenges[user.name][other.name] challenge.should.have.property("team") challenge.should.have.property("format") challenge.should.have.property("conditions") challenge.team.should.equal(team) challenge.format.should.equal(format) challenge.conditions.should.equal(conditions) it "does not override old challenges", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "Batman", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "Robin", @stubSpark()) team = generateTeam() format = 'xy1000' diffFormat = 'xy500' diffTeam = generateTeam() diffTeam[0] = Factory("Celebi") server.registerChallenge(user, other.name, format, team) server.registerChallenge(user, other.name, diffFormat, diffTeam) challenge = server.challenges[user.name][other.name] challenge.format.should.equal(format) challenge.team.should.equal(team) it "returns an error if the team is invalid", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "Batman", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "Robin", @stubSpark()) format = 'xy1000' mock = @sandbox.mock(user).expects('error').once() team = [] server.registerChallenge(user, other.name, format, team) mock.verify() it "returns an error if the team is over 1000 PBV with 1000 PBV clause", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "Batman", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "Robin", @stubSpark()) format = 'xy1000' team = generateTeam() team[0] = Factory("Arceus", moves: [ "Recover" ]) conditions = [ Conditions.PBV_1000 ] mock = @sandbox.mock(user).expects('error').once() server.registerChallenge(user, other.name, format, team, conditions) mock.verify() it "returns an error on a rated challenge", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "Batman", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "Robin", @stubSpark()) format = 'xy1000' team = generateTeam() conditions = [ Conditions.RATED_BATTLE ] mock = @sandbox.mock(user).expects('error').once() server.registerChallenge(user, other.name, format, team, conditions) mock.verify() it "returns an error if the format is invalid", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "Batman", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "Robin", @stubSpark()) team = generateTeam() format = "UNRELEASED INFERNO RED AND WEIRD YELLOWISH GREEN" conditions = [] mock = @sandbox.mock(user).expects('error').once() server.registerChallenge(user, other.name, format, team, conditions) mock.verify() it "returns an error if the challengee is offline", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "Batman", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] mock = @sandbox.mock(user).expects('error').once() server.registerChallenge(user, "husk", format, team, conditions) mock.verify() it "returns an error if you challenge yourself", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "Batman", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "Robin", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] mock = @sandbox.mock(user).expects('error').once() server.registerChallenge(user, user.name, format, team, conditions) mock.verify() it "sends an error if a challenge already exists for that pair", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "Batman", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "Robin", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) mock = @sandbox.mock(other).expects('error').once() server.registerChallenge(other, user.name, format, team, conditions) mock.verify() it "sends a 'challenge' event to the challengee", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "Batman", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "Robin", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] otherSpy = @sandbox.spy(other, 'send') otherSpy.withArgs('challenge', user.name, format, conditions) server.registerChallenge(user, other.name, format, team, conditions) otherSpy.withArgs('challenge', user.name, format, conditions) .calledOnce.should.be.true it "returns an error if the server is locked down", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "Batman", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "Robin", @stubSpark()) format = 'xy1000' team = generateTeam() conditions = [ Conditions.PBV_1000 ] mock = @sandbox.mock(user).expects('error').once() server.lockdown() server.registerChallenge(user, other.name, format, team, conditions) mock.verify() describe "#cancelChallenge", -> it "sends a 'cancelChallenge' to both the challengee and challenger", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "Batman", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "Robin", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] userSpy = @sandbox.spy(user, 'send') userSpy.withArgs('cancelChallenge', other.name) otherSpy = @sandbox.spy(other, 'send') otherSpy.withArgs('cancelChallenge', user.name) server.registerChallenge(user, other.name, format, team, conditions) server.cancelChallenge(user, other.name) userSpy.withArgs('cancelChallenge', other.name).calledOnce.should.be.true otherSpy.withArgs('cancelChallenge', user.name).calledOnce.should.be.true it "removes the challenge from the internal hash", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "Batman", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "Robin", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) should.exist server.challenges[user.name][other.name] server.cancelChallenge(user, other.name) should.not.exist server.challenges[user.name][other.name] describe "#rejectChallenge", -> it "sends a 'rejectChallenge' to the challengee and challenger", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "Batman", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "Robin", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) userSpy = @sandbox.spy(user, 'send') userSpy.withArgs('rejectChallenge', other.name) otherSpy = @sandbox.spy(other, 'send') otherSpy.withArgs('rejectChallenge', user.name) server.rejectChallenge(other, user.name) userSpy.withArgs('rejectChallenge', other.name).calledOnce.should.be.true otherSpy.withArgs('rejectChallenge', user.name).calledOnce.should.be.true it "removes the challenge from the internal hash", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "Batman", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "Robin", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) should.exist server.challenges[user.name][other.name] server.rejectChallenge(other, user.name) should.not.exist server.challenges[user.name][other.name] it "returns an error if no such challenge exists", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "Batman", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "Robin", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) mock = @sandbox.mock(other).expects('error').once() server.rejectChallenge(other, "bogus dude") mock.verify() describe "#acceptChallenge", -> initServer = -> @server = new BattleServer() @user = @server.findOrCreateUser(id: 1, name: "Batman", @stubSpark()) @other = @server.findOrCreateUser(id: 2, name: "Robin", @stubSpark()) it "creates a battle with the teams given by both players", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] @server.registerChallenge(@user, @other.name, format, team, conditions) mock = @sandbox.mock(@server).expects('createBattle').once() @server.acceptChallenge(@other, @user.name, team) mock.verify() it "returns an error to a player if their team is invalid", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] @server.registerChallenge(@user, @other.name, format, team, conditions) mock = @sandbox.mock(@other).expects('error').once() @server.acceptChallenge(@other, @user.name, []) mock.verify() it "returns an error to a player if their team violates clauses", -> initServer.call(this) team = generateTeam() acceptTeam = generateTeam() acceptTeam[0] = Factory("Mewtwo", moves: [ "Psychic" ]) format = 'xy1000' conditions = [ Conditions.PBV_1000 ] @server.registerChallenge(@user, @other.name, format, team, conditions) mock = @sandbox.mock(@other).expects('error').once() @server.acceptChallenge(@other, @user.name, acceptTeam) mock.verify() it "removes the challenge from the internal hash", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] @server.registerChallenge(@user, @other.name, format, team, conditions) should.exist @server.challenges[@user.name][@other.name] @server.acceptChallenge(@other, @user.name, team) should.not.exist @server.challenges[@user.name][@other.name] it "sends a 'challengeSuccess' event to both players", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] userSpy = @sandbox.spy(@user, 'send') userSpy.withArgs('challengeSuccess', @other.name) otherSpy = @sandbox.spy(@other, 'send') otherSpy.withArgs('challengeSuccess', @user.name) @server.registerChallenge(@user, @other.name, format, team, conditions) @server.acceptChallenge(@other, @user.name, team) userSpy.withArgs('challengeSuccess', @other.name).calledOnce.should.be.true otherSpy.withArgs('challengeSuccess', @user.name).calledOnce.should.be.true it "returns an error if no such challenge exists", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] @server.registerChallenge(@user, @other.name, format, team, conditions) mock = @sandbox.mock(@other).expects('error').once() @server.acceptChallenge(@other, "bogus dude", team) mock.verify() it "overrides the user's name with the alt name in battle", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] @server.registerChallenge(@user, @other.name, format, team, conditions, "Bruce Wayne") battleId = @server.acceptChallenge(@other, @user.name, team, "Jason Todd") battle = @server.findBattle(battleId) battle.battle.playerNames.should.eql ["Bruce Wayne", "Jason Todd"] it "sets the rating key to be the unique alt id if there is an alt", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] @server.registerChallenge(@user, @other.name, format, team, conditions, "Bruce Wayne") battleId = @server.acceptChallenge(@other, @user.name, team, "Jason Todd") battle = @server.findBattle(battleId) battle.battle.getPlayer("Batman").ratingKey.should.equal alts.uniqueId(@user.name, "Bruce Wayne") battle.battle.getPlayer("Robin").ratingKey.should.equal alts.uniqueId(@other.name, "Jason Todd") describe "#leave", -> it "removes challenges by that player", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "Batman", spark = @stubSpark()) other = server.findOrCreateUser(id: 2, name: "Robin", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) should.exist server.challenges[user.name] should.exist server.challenges[user.name][other.name] server.leave(spark) should.not.exist server.challenges[user.name] it "removes challenges to that player", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "Batman", spark = @stubSpark()) other = server.findOrCreateUser(id: 2, name: "Robin", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(other, user.name, format, team, conditions) should.exist server.challenges[other.name] should.exist server.challenges[other.name][user.name] server.leave(spark) should.exist server.challenges[other.name] should.not.exist server.challenges[other.name][user.name] describe "#lockdown", -> it "cancels all challenges", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "Batman", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "Robin", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(other, user.name, format, team, conditions) should.exist server.challenges[other.name] should.exist server.challenges[other.name][user.name] server.lockdown() should.not.exist server.challenges[other.name] describe "#validateTeam", -> it "returns non-empty if given anything that's not an array", -> server = new BattleServer() server.validateTeam().should.not.be.empty it "returns empty if given a non-empty array containing Pokemon", -> server = new BattleServer() server.validateTeam(generateTeam()).should.be.empty it "returns non-empty if given an empty array", -> server = new BattleServer() server.validateTeam([]).should.not.be.empty it "returns non-empty if a team member is not a valid Pokemon", -> server = new BattleServer() invalidPokemon = {} server.validateTeam([ invalidPokemon ]).should.not.be.empty it "returns non-empty if a team member has a fake species name", -> server = new BattleServer() team = generateTeam() team[0] = {species: "NOTREALMON"} server.validateTeam(team).should.not.be.empty it "returns non-empty if a team member has no moveset", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Hitmonchan", moves: null) server.validateTeam(team).should.not.be.empty it "returns non-empty if a team member has an empty moveset", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Hitmonchan", moves: []) server.validateTeam(team).should.not.be.empty it "returns non-empty if a team member has a bogus moveset", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Hitmonchan", moves: true) server.validateTeam(team).should.not.be.empty team[0] = Factory("Hitmonchan", moves: ["Super Powerful Punch"]) server.validateTeam(team).should.not.be.empty it "returns non-empty if a team member has an illegal moveset", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Raichu", moves: [ "Volt Tackle", "Encore" ]) server.validateTeam(team, 'bw').should.not.be.empty # TODO: 4 is a magic constant it "returns non-empty if a pokemon has more than 4 moves", -> server = new BattleServer() team = generateTeam() team[0] = Factory "Hitmonchan", moves: [ "Ice Punch" "Fire Punch" "Close Combat" "Mach Punch" "Rapid Spin" ] server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a move it can't learn", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", moves: [ "Fissure" ]) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a fake move", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", moves: [ "Splash", "Armageddon" ]) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an ability it can't have", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", ability: "Wonder Guard") server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a bogus ability", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", ability: "Being Batman") server.validateTeam(team).should.not.be.empty it "returns empty if a pokemon has a hidden ability", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Cloyster", ability: "Overcoat") server.validateTeam(team).should.be.empty it "returns non-empty if a pokemon has a level below 1", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", level: 0) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a bogus level", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", level: "hi") server.validateTeam(team).should.not.be.empty # TODO: 100 is a magic constant it "returns non-empty if a pokemon has a level over 100", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", level: 101) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an iv below 0", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", ivs: { hp: -1 }) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an iv above 31", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", ivs: { hp: 32 }) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has bogus ivs", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", ivs: true) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an ev below 0", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", evs: { hp: -1 }) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an ev above 255", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", evs: { hp: 256 }) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an ev total above 510", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", evs: { hp: 255, defense: 255, speed: 255 }) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has bogus evs", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", evs: true) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an invalid gender", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Metagross", gender: "Alien") server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a gender it can't have", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Metagross", gender: "F") server.validateTeam(team).should.not.be.empty team = generateTeam() team[0] = Factory("Blissey", gender: "M") server.validateTeam(team).should.not.be.empty team = generateTeam() team[0] = Factory("Gallade", gender: "F") server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a bogus forme", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Blissey", forme: "Super Ultra Mega Blissey") server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a battle-only forme", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Meloetta", forme: "pirouette", moves: ["Relic Song"]) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon cannot have its forme" it "returns non-empty if the format is fake", -> server = new BattleServer() server.validateTeam(generateTeam(), 'bogusformat').should.not.be.empty it "returns non-empty if a pokemon's nickname matches another species", -> server = new BattleServer() team = generateTeam() team[0].name = "Latios" server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon's nickname is blank", -> server = new BattleServer() team = generateTeam() team[0].name = "" server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon's nickname contains illegal chars", -> server = new BattleServer() team = generateTeam() team[0].name = "some chars \uFE20 are illegal" server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon's nickname is past a certain length", -> server = new BattleServer() team = generateTeam() team[0].name = ("A" for x in [0...50]).join('') server.validateTeam(team).should.not.be.empty describe "#beginBattles", -> it "creates a battle per pair", (done) -> server = new BattleServer() for i in [1..4] server.findOrCreateUser(id: i, name: "user#{i}", @stubSpark()) server.queuePlayer("user#{i}", generateTeam()) server.beginBattles (err, battleIds) -> battleIds.length.should.equal(2) done() describe "users", -> it "are recorded to be playing in which battles", (done) -> server = new BattleServer() [ user1, user2, user3 ] = [ "a", "b", "c" ] for name, i in [ user1, user2, user3 ] server.findOrCreateUser(id: i, name: name, @stubSpark()) server.queuePlayer(user1, generateTeam()).should.be.empty server.queuePlayer(user2, generateTeam()).should.be.empty server.queuePlayer(user3, generateTeam()).should.be.empty server.beginBattles (err, battleIds) -> server.getUserBattles(user1).should.eql(battleIds) server.getUserBattles(user2).should.eql(battleIds) server.getUserBattles(user3).should.be.empty done() it "no longer records battles once they end", (done) -> server = new BattleServer() [ user1, user2, user3 ] = [ "a", "b", "c" ] for name, i in [ user1, user2, user3 ] server.findOrCreateUser(id: i, name: name, @stubSpark()) server.queuePlayer(user1, generateTeam()).should.be.empty server.queuePlayer(user2, generateTeam()).should.be.empty server.queuePlayer(user3, generateTeam()).should.be.empty server.beginBattles (err, battleIds) -> for battleId in battleIds battle = server.findBattle(battleId) battle.endBattle() server.getUserBattles(user1).should.be.empty server.getUserBattles(user2).should.be.empty server.getUserBattles(user3).should.be.empty done() it "can join multiple times", -> server = new BattleServer() server.findOrCreateUser(id: 1, name: "hey", spark1 = @stubSpark()) server.join(spark1) (=> server.findOrCreateUser(id: 1, name: "hey", spark2 = @stubSpark()) server.join(spark2) ).should.not.throw() it "records battles they're under an alt in", (done) -> server = new BattleServer() [ user1, user2 ] = [ "a", "b" ] for name, i in [ user1, user2 ] server.findOrCreateUser(id: i, name: name, @stubSpark()) server.queuePlayer(user1, generateTeam(), null, 'alt1').should.be.empty server.queuePlayer(user2, generateTeam(), null, 'alt2').should.be.empty server.beginBattles (err, battleIds) -> server.getUserBattles(user1).should.not.be.empty server.getUserBattles(user2).should.not.be.empty done() it "auto-rejoin battles they're under an alt in", (done) -> server = new BattleServer() [ user1, user2 ] = [ "a", "b" ] server.findOrCreateUser(id: 1, name: user1, spark1 = @stubSpark()) server.findOrCreateUser(id: 2, name: user2, spark2 = @stubSpark()) server.queuePlayer(user1, generateTeam(), null, 'alt1').should.be.empty server.queuePlayer(user2, generateTeam(), null, 'alt2').should.be.empty server.beginBattles (err, battleIds) => [battleId] = battleIds battle = server.findBattle(battleId).battle # test spark1 spy = @sandbox.spy(battle, 'tellPlayer').withArgs(user1, Protocol.RECEIVE_TEAM) server.join(spark1) spy.calledOnce.should.be.true battle.tellPlayer.restore() # test spark2 spy = @sandbox.spy(battle, 'tellPlayer').withArgs(user2, Protocol.RECEIVE_TEAM) server.join(spark2) spy.calledOnce.should.be.true battle.tellPlayer.restore() done() it "automatically leaves a battle when leaving the server", (done) -> server = new BattleServer() [ user1, user2 ] = [ "a", "b" ] server.findOrCreateUser(id: 1, name: user1, spark1 = @stubSpark()) server.findOrCreateUser(id: 2, name: user2, spark2 = @stubSpark()) server.join(spark1) server.join(spark2) server.queuePlayer(user1, generateTeam(), null, 'alt1').should.be.empty server.queuePlayer(user2, generateTeam(), null, 'alt2').should.be.empty server.beginBattles (err, battleIds) => [battleId] = battleIds battle = server.findBattle(battleId).battle # test spark1 spy = @sandbox.spy(battle, 'remove').withArgs(spark1) broadcastSpy = @sandbox.spy(battle, 'send') broadcastSpy = broadcastSpy.withArgs('leaveChatroom', battle.id, 'alt1') server.leave(spark1) spark1.end() spy.calledOnce.should.be.true broadcastSpy.calledOnce.should.be.true battle.remove.restore() battle.send.restore() # test spark2 spy = @sandbox.spy(battle, 'remove').withArgs(spark2) broadcastSpy = @sandbox.spy(battle, 'send') broadcastSpy = broadcastSpy.withArgs('leaveChatroom', battle.id, 'alt2') server.leave(spark2) spark2.end() spy.calledOnce.should.be.true broadcastSpy.calledOnce.should.be.true battle.remove.restore() battle.send.restore() done() describe "a battle", -> beforeEach (done) -> @server = new BattleServer() [ @user1, @user2, @user3 ] = [ "a", "b", "c" ] for name, i in [ @user1, @user2, @user3 ] @server.findOrCreateUser(id: i, name: name, @stubSpark()) @server.queuePlayer(@user1, generateTeam()).should.be.empty @server.queuePlayer(@user2, generateTeam()).should.be.empty @server.queuePlayer(@user3, generateTeam()).should.be.empty @server.queuedPlayers().should.have.length(3) @server.beginBattles (err, battleIds) => @battleIds = battleIds @relevantUser = @server.findBattle(@battleIds[0]).battle.playerIds[0] done() it "removes from user battles if ended", -> @server.getUserBattles(@relevantUser).should.not.be.empty battle = @server.findBattle(@battleIds[0]) battle.endBattle() @server.getUserBattles(@user1).should.be.empty @server.getUserBattles(@user2).should.be.empty @server.getUserBattles(@user3).should.be.empty it "removes from user battles if forfeited", -> @server.getUserBattles(@relevantUser).should.not.be.empty battle = @server.findBattle(@battleIds[0]) battle.forfeit(@relevantUser) @server.getUserBattles(@user1).should.be.empty @server.getUserBattles(@user2).should.be.empty @server.getUserBattles(@user3).should.be.empty
57185
require './helpers' {BattleServer} = require('../server/server') {Conditions, DEFAULT_FORMAT} = require '../shared/conditions' {Protocol} = require '../shared/protocol' {Factory} = require './factory' alts = require('../server/alts') should = require('should') generateTeam = -> [ Factory("Magikarp") Factory("<NAME>ados") Factory('Hitmonchan') Factory("Celebi") Factory("Blissey") Factory("Alakazam") ] describe 'BattleServer', -> it 'can create a new battle', -> server = new BattleServer() battleId = server.createBattle() server.battles.should.have.ownProperty battleId it "sends the 'spectateBattle' event for each matched player", (done) -> server = new BattleServer() players = [] players.push server.findOrCreateUser(id: 1, name: '<NAME>', @stubSpark()) players.push server.findOrCreateUser(id: 2, name: '<NAME>', @stubSpark()) spies = [] for player in players spy = @sandbox.spy(player.sparks[0], 'send') spies.push(spy) for player in players server.queuePlayer(player.name, generateTeam()).should.be.empty server.beginBattles (err, ids) -> throw new Error(err.message) if err return if ids.length == 0 for spy in spies spy.calledWith('spectateBattle').should.be.true done() describe "#queuePlayer", -> it "queues players", -> server = new BattleServer() derp = server.findOrCreateUser(id: 1, name: 'derp', @stubSpark()) server.queuePlayer(derp.name, generateTeam()).should.be.empty server.queues[DEFAULT_FORMAT].size().should.equal(1) it "does not queue players already queued", -> server = new BattleServer() derp = server.findOrCreateUser(id: 1, name: 'derp', @stubSpark()) server.queuePlayer(derp.name, generateTeam()).should.be.empty server.queuePlayer(derp.name, generateTeam()).should.be.empty server.queues[DEFAULT_FORMAT].size().should.equal(1) describe "#getOngoingBattles", -> it "returns one object for each queued battle", (done) -> server = new BattleServer() nBattles = 3 for i in [1..nBattles] first = 2 * i second = (2 * i) + 1 server.findOrCreateUser(id: first, name: String(first), @stubSpark()) server.findOrCreateUser(id: second, name: String(second), @stubSpark()) server.queuePlayer(String(first), generateTeam()).should.be.empty server.queuePlayer(String(second), generateTeam()).should.be.empty server.beginBattles -> server.getOngoingBattles().should.have.length(nBattles) done() describe "#registerChallenge", -> it "registers a challenge to a player", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "<NAME>", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "<NAME>", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) server.challenges.should.have.property(user.name) server.challenges[user.name].should.have.property(other.name) challenge = server.challenges[user.name][other.name] challenge.should.have.property("team") challenge.should.have.property("format") challenge.should.have.property("conditions") challenge.team.should.equal(team) challenge.format.should.equal(format) challenge.conditions.should.equal(conditions) it "does not override old challenges", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "<NAME>", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "<NAME>", @stubSpark()) team = generateTeam() format = 'xy1000' diffFormat = 'xy500' diffTeam = generateTeam() diffTeam[0] = Factory("Celebi") server.registerChallenge(user, other.name, format, team) server.registerChallenge(user, other.name, diffFormat, diffTeam) challenge = server.challenges[user.name][other.name] challenge.format.should.equal(format) challenge.team.should.equal(team) it "returns an error if the team is invalid", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "<NAME>", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "<NAME>", @stubSpark()) format = 'xy1000' mock = @sandbox.mock(user).expects('error').once() team = [] server.registerChallenge(user, other.name, format, team) mock.verify() it "returns an error if the team is over 1000 PBV with 1000 PBV clause", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "<NAME>", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "<NAME>", @stubSpark()) format = 'xy1000' team = generateTeam() team[0] = Factory("Arceus", moves: [ "Recover" ]) conditions = [ Conditions.PBV_1000 ] mock = @sandbox.mock(user).expects('error').once() server.registerChallenge(user, other.name, format, team, conditions) mock.verify() it "returns an error on a rated challenge", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "<NAME>", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "<NAME>", @stubSpark()) format = 'xy1000' team = generateTeam() conditions = [ Conditions.RATED_BATTLE ] mock = @sandbox.mock(user).expects('error').once() server.registerChallenge(user, other.name, format, team, conditions) mock.verify() it "returns an error if the format is invalid", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "<NAME>", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "<NAME>", @stubSpark()) team = generateTeam() format = "UNRELEASED INFERNO RED AND WEIRD YELLOWISH GREEN" conditions = [] mock = @sandbox.mock(user).expects('error').once() server.registerChallenge(user, other.name, format, team, conditions) mock.verify() it "returns an error if the challengee is offline", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "<NAME>", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] mock = @sandbox.mock(user).expects('error').once() server.registerChallenge(user, "husk", format, team, conditions) mock.verify() it "returns an error if you challenge yourself", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "<NAME>", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "<NAME>", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] mock = @sandbox.mock(user).expects('error').once() server.registerChallenge(user, user.name, format, team, conditions) mock.verify() it "sends an error if a challenge already exists for that pair", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "<NAME>", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "<NAME>", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) mock = @sandbox.mock(other).expects('error').once() server.registerChallenge(other, user.name, format, team, conditions) mock.verify() it "sends a 'challenge' event to the challengee", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "<NAME>", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "<NAME>", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] otherSpy = @sandbox.spy(other, 'send') otherSpy.withArgs('challenge', user.name, format, conditions) server.registerChallenge(user, other.name, format, team, conditions) otherSpy.withArgs('challenge', user.name, format, conditions) .calledOnce.should.be.true it "returns an error if the server is locked down", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "<NAME>", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "<NAME>", @stubSpark()) format = 'xy1000' team = generateTeam() conditions = [ Conditions.PBV_1000 ] mock = @sandbox.mock(user).expects('error').once() server.lockdown() server.registerChallenge(user, other.name, format, team, conditions) mock.verify() describe "#cancelChallenge", -> it "sends a 'cancelChallenge' to both the challengee and challenger", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "<NAME>", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "<NAME>", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] userSpy = @sandbox.spy(user, 'send') userSpy.withArgs('cancelChallenge', other.name) otherSpy = @sandbox.spy(other, 'send') otherSpy.withArgs('cancelChallenge', user.name) server.registerChallenge(user, other.name, format, team, conditions) server.cancelChallenge(user, other.name) userSpy.withArgs('cancelChallenge', other.name).calledOnce.should.be.true otherSpy.withArgs('cancelChallenge', user.name).calledOnce.should.be.true it "removes the challenge from the internal hash", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "<NAME>", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "<NAME>", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) should.exist server.challenges[user.name][other.name] server.cancelChallenge(user, other.name) should.not.exist server.challenges[user.name][other.name] describe "#rejectChallenge", -> it "sends a 'rejectChallenge' to the challengee and challenger", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "<NAME>", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "<NAME>", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) userSpy = @sandbox.spy(user, 'send') userSpy.withArgs('rejectChallenge', other.name) otherSpy = @sandbox.spy(other, 'send') otherSpy.withArgs('rejectChallenge', user.name) server.rejectChallenge(other, user.name) userSpy.withArgs('rejectChallenge', other.name).calledOnce.should.be.true otherSpy.withArgs('rejectChallenge', user.name).calledOnce.should.be.true it "removes the challenge from the internal hash", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "<NAME>", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "<NAME>", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) should.exist server.challenges[user.name][other.name] server.rejectChallenge(other, user.name) should.not.exist server.challenges[user.name][other.name] it "returns an error if no such challenge exists", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "<NAME>", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "<NAME>", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) mock = @sandbox.mock(other).expects('error').once() server.rejectChallenge(other, "bogus dude") mock.verify() describe "#acceptChallenge", -> initServer = -> @server = new BattleServer() @user = @server.findOrCreateUser(id: 1, name: "<NAME>", @stubSpark()) @other = @server.findOrCreateUser(id: 2, name: "<NAME>", @stubSpark()) it "creates a battle with the teams given by both players", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] @server.registerChallenge(@user, @other.name, format, team, conditions) mock = @sandbox.mock(@server).expects('createBattle').once() @server.acceptChallenge(@other, @user.name, team) mock.verify() it "returns an error to a player if their team is invalid", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] @server.registerChallenge(@user, @other.name, format, team, conditions) mock = @sandbox.mock(@other).expects('error').once() @server.acceptChallenge(@other, @user.name, []) mock.verify() it "returns an error to a player if their team violates clauses", -> initServer.call(this) team = generateTeam() acceptTeam = generateTeam() acceptTeam[0] = Factory("Mewtwo", moves: [ "Psychic" ]) format = 'xy1000' conditions = [ Conditions.PBV_1000 ] @server.registerChallenge(@user, @other.name, format, team, conditions) mock = @sandbox.mock(@other).expects('error').once() @server.acceptChallenge(@other, @user.name, acceptTeam) mock.verify() it "removes the challenge from the internal hash", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] @server.registerChallenge(@user, @other.name, format, team, conditions) should.exist @server.challenges[@user.name][@other.name] @server.acceptChallenge(@other, @user.name, team) should.not.exist @server.challenges[@user.name][@other.name] it "sends a 'challengeSuccess' event to both players", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] userSpy = @sandbox.spy(@user, 'send') userSpy.withArgs('challengeSuccess', @other.name) otherSpy = @sandbox.spy(@other, 'send') otherSpy.withArgs('challengeSuccess', @user.name) @server.registerChallenge(@user, @other.name, format, team, conditions) @server.acceptChallenge(@other, @user.name, team) userSpy.withArgs('challengeSuccess', @other.name).calledOnce.should.be.true otherSpy.withArgs('challengeSuccess', @user.name).calledOnce.should.be.true it "returns an error if no such challenge exists", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] @server.registerChallenge(@user, @other.name, format, team, conditions) mock = @sandbox.mock(@other).expects('error').once() @server.acceptChallenge(@other, "bogus dude", team) mock.verify() it "overrides the user's name with the alt name in battle", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] @server.registerChallenge(@user, @other.name, format, team, conditions, "<NAME>") battleId = @server.acceptChallenge(@other, @user.name, team, "<NAME>") battle = @server.findBattle(battleId) battle.battle.playerNames.should.eql ["<NAME>", "<NAME>"] it "sets the rating key to be the unique alt id if there is an alt", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] @server.registerChallenge(@user, @other.name, format, team, conditions, "<NAME>") battleId = @server.acceptChallenge(@other, @user.name, team, "<NAME>") battle = @server.findBattle(battleId) battle.battle.getPlayer("<NAME>").ratingKey.should.equal alts.uniqueId(@user.name, "<NAME>") battle.battle.getPlayer("<NAME>").ratingKey.should.equal alts.uniqueId(@other.name, "<NAME>") describe "#leave", -> it "removes challenges by that player", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "<NAME>", spark = @stubSpark()) other = server.findOrCreateUser(id: 2, name: "<NAME>", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) should.exist server.challenges[user.name] should.exist server.challenges[user.name][other.name] server.leave(spark) should.not.exist server.challenges[user.name] it "removes challenges to that player", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "<NAME>", spark = @stubSpark()) other = server.findOrCreateUser(id: 2, name: "<NAME>", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(other, user.name, format, team, conditions) should.exist server.challenges[other.name] should.exist server.challenges[other.name][user.name] server.leave(spark) should.exist server.challenges[other.name] should.not.exist server.challenges[other.name][user.name] describe "#lockdown", -> it "cancels all challenges", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "<NAME>", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "<NAME>", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(other, user.name, format, team, conditions) should.exist server.challenges[other.name] should.exist server.challenges[other.name][user.name] server.lockdown() should.not.exist server.challenges[other.name] describe "#validateTeam", -> it "returns non-empty if given anything that's not an array", -> server = new BattleServer() server.validateTeam().should.not.be.empty it "returns empty if given a non-empty array containing Pokemon", -> server = new BattleServer() server.validateTeam(generateTeam()).should.be.empty it "returns non-empty if given an empty array", -> server = new BattleServer() server.validateTeam([]).should.not.be.empty it "returns non-empty if a team member is not a valid Pokemon", -> server = new BattleServer() invalidPokemon = {} server.validateTeam([ invalidPokemon ]).should.not.be.empty it "returns non-empty if a team member has a fake species name", -> server = new BattleServer() team = generateTeam() team[0] = {species: "NOTREALMON"} server.validateTeam(team).should.not.be.empty it "returns non-empty if a team member has no moveset", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Hitmonchan", moves: null) server.validateTeam(team).should.not.be.empty it "returns non-empty if a team member has an empty moveset", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Hitmonchan", moves: []) server.validateTeam(team).should.not.be.empty it "returns non-empty if a team member has a bogus moveset", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Hitmonchan", moves: true) server.validateTeam(team).should.not.be.empty team[0] = Factory("Hitmonchan", moves: ["Super Powerful Punch"]) server.validateTeam(team).should.not.be.empty it "returns non-empty if a team member has an illegal moveset", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Raichu", moves: [ "Volt Tackle", "Encore" ]) server.validateTeam(team, 'bw').should.not.be.empty # TODO: 4 is a magic constant it "returns non-empty if a pokemon has more than 4 moves", -> server = new BattleServer() team = generateTeam() team[0] = Factory "Hitmonchan", moves: [ "Ice Punch" "Fire Punch" "Close Combat" "Mach Punch" "Rapid Spin" ] server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a move it can't learn", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", moves: [ "Fissure" ]) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a fake move", -> server = new BattleServer() team = generateTeam() team[0] = Factory("<NAME>", moves: [ "Splash", "Armageddon" ]) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an ability it can't have", -> server = new BattleServer() team = generateTeam() team[0] = Factory("<NAME>ikarp", ability: "Wonder Guard") server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a bogus ability", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", ability: "Being Batman") server.validateTeam(team).should.not.be.empty it "returns empty if a pokemon has a hidden ability", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Clo<NAME>", ability: "Overcoat") server.validateTeam(team).should.be.empty it "returns non-empty if a pokemon has a level below 1", -> server = new BattleServer() team = generateTeam() team[0] = Factory("<NAME>", level: 0) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a bogus level", -> server = new BattleServer() team = generateTeam() team[0] = Factory("<NAME>ik<NAME>", level: "hi") server.validateTeam(team).should.not.be.empty # TODO: 100 is a magic constant it "returns non-empty if a pokemon has a level over 100", -> server = new BattleServer() team = generateTeam() team[0] = Factory("<NAME>", level: 101) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an iv below 0", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magik<NAME>", ivs: { hp: -1 }) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an iv above 31", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", ivs: { hp: 32 }) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has bogus ivs", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", ivs: true) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an ev below 0", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", evs: { hp: -1 }) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an ev above 255", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", evs: { hp: 256 }) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an ev total above 510", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", evs: { hp: 255, defense: 255, speed: 255 }) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has bogus evs", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", evs: true) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an invalid gender", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Metagross", gender: "Alien") server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a gender it can't have", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Metagross", gender: "F") server.validateTeam(team).should.not.be.empty team = generateTeam() team[0] = Factory("Blissey", gender: "M") server.validateTeam(team).should.not.be.empty team = generateTeam() team[0] = Factory("Gallade", gender: "F") server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a bogus forme", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Blissey", forme: "Super Ultra Mega Blissey") server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a battle-only forme", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Meloetta", forme: "pirouette", moves: ["Relic Song"]) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon cannot have its forme" it "returns non-empty if the format is fake", -> server = new BattleServer() server.validateTeam(generateTeam(), 'bogusformat').should.not.be.empty it "returns non-empty if a pokemon's nickname matches another species", -> server = new BattleServer() team = generateTeam() team[0].name = "<NAME>" server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon's nickname is blank", -> server = new BattleServer() team = generateTeam() team[0].name = "" server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon's nickname contains illegal chars", -> server = new BattleServer() team = generateTeam() team[0].name = "some chars \uFE20 are illegal" server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon's nickname is past a certain length", -> server = new BattleServer() team = generateTeam() team[0].name = ("A" for x in [0...50]).join('') server.validateTeam(team).should.not.be.empty describe "#beginBattles", -> it "creates a battle per pair", (done) -> server = new BattleServer() for i in [1..4] server.findOrCreateUser(id: i, name: "user#{i}", @stubSpark()) server.queuePlayer("user#{i}", generateTeam()) server.beginBattles (err, battleIds) -> battleIds.length.should.equal(2) done() describe "users", -> it "are recorded to be playing in which battles", (done) -> server = new BattleServer() [ user1, user2, user3 ] = [ "a", "b", "c" ] for name, i in [ user1, user2, user3 ] server.findOrCreateUser(id: i, name: name, @stubSpark()) server.queuePlayer(user1, generateTeam()).should.be.empty server.queuePlayer(user2, generateTeam()).should.be.empty server.queuePlayer(user3, generateTeam()).should.be.empty server.beginBattles (err, battleIds) -> server.getUserBattles(user1).should.eql(battleIds) server.getUserBattles(user2).should.eql(battleIds) server.getUserBattles(user3).should.be.empty done() it "no longer records battles once they end", (done) -> server = new BattleServer() [ user1, user2, user3 ] = [ "a", "b", "c" ] for name, i in [ user1, user2, user3 ] server.findOrCreateUser(id: i, name: name, @stubSpark()) server.queuePlayer(user1, generateTeam()).should.be.empty server.queuePlayer(user2, generateTeam()).should.be.empty server.queuePlayer(user3, generateTeam()).should.be.empty server.beginBattles (err, battleIds) -> for battleId in battleIds battle = server.findBattle(battleId) battle.endBattle() server.getUserBattles(user1).should.be.empty server.getUserBattles(user2).should.be.empty server.getUserBattles(user3).should.be.empty done() it "can join multiple times", -> server = new BattleServer() server.findOrCreateUser(id: 1, name: "<NAME>", spark1 = @stubSpark()) server.join(spark1) (=> server.findOrCreateUser(id: 1, name: "<NAME>", spark2 = @stubSpark()) server.join(spark2) ).should.not.throw() it "records battles they're under an alt in", (done) -> server = new BattleServer() [ user1, user2 ] = [ "a", "b" ] for name, i in [ user1, user2 ] server.findOrCreateUser(id: i, name: name, @stubSpark()) server.queuePlayer(user1, generateTeam(), null, 'alt1').should.be.empty server.queuePlayer(user2, generateTeam(), null, 'alt2').should.be.empty server.beginBattles (err, battleIds) -> server.getUserBattles(user1).should.not.be.empty server.getUserBattles(user2).should.not.be.empty done() it "auto-rejoin battles they're under an alt in", (done) -> server = new BattleServer() [ user1, user2 ] = [ "a", "b" ] server.findOrCreateUser(id: 1, name: user1, spark1 = @stubSpark()) server.findOrCreateUser(id: 2, name: user2, spark2 = @stubSpark()) server.queuePlayer(user1, generateTeam(), null, 'alt1').should.be.empty server.queuePlayer(user2, generateTeam(), null, 'alt2').should.be.empty server.beginBattles (err, battleIds) => [battleId] = battleIds battle = server.findBattle(battleId).battle # test spark1 spy = @sandbox.spy(battle, 'tellPlayer').withArgs(user1, Protocol.RECEIVE_TEAM) server.join(spark1) spy.calledOnce.should.be.true battle.tellPlayer.restore() # test spark2 spy = @sandbox.spy(battle, 'tellPlayer').withArgs(user2, Protocol.RECEIVE_TEAM) server.join(spark2) spy.calledOnce.should.be.true battle.tellPlayer.restore() done() it "automatically leaves a battle when leaving the server", (done) -> server = new BattleServer() [ user1, user2 ] = [ "a", "b" ] server.findOrCreateUser(id: 1, name: user1, spark1 = @stubSpark()) server.findOrCreateUser(id: 2, name: user2, spark2 = @stubSpark()) server.join(spark1) server.join(spark2) server.queuePlayer(user1, generateTeam(), null, 'alt1').should.be.empty server.queuePlayer(user2, generateTeam(), null, 'alt2').should.be.empty server.beginBattles (err, battleIds) => [battleId] = battleIds battle = server.findBattle(battleId).battle # test spark1 spy = @sandbox.spy(battle, 'remove').withArgs(spark1) broadcastSpy = @sandbox.spy(battle, 'send') broadcastSpy = broadcastSpy.withArgs('leaveChatroom', battle.id, 'alt1') server.leave(spark1) spark1.end() spy.calledOnce.should.be.true broadcastSpy.calledOnce.should.be.true battle.remove.restore() battle.send.restore() # test spark2 spy = @sandbox.spy(battle, 'remove').withArgs(spark2) broadcastSpy = @sandbox.spy(battle, 'send') broadcastSpy = broadcastSpy.withArgs('leaveChatroom', battle.id, 'alt2') server.leave(spark2) spark2.end() spy.calledOnce.should.be.true broadcastSpy.calledOnce.should.be.true battle.remove.restore() battle.send.restore() done() describe "a battle", -> beforeEach (done) -> @server = new BattleServer() [ @user1, @user2, @user3 ] = [ "a", "b", "c" ] for name, i in [ @user1, @user2, @user3 ] @server.findOrCreateUser(id: i, name: name, @stubSpark()) @server.queuePlayer(@user1, generateTeam()).should.be.empty @server.queuePlayer(@user2, generateTeam()).should.be.empty @server.queuePlayer(@user3, generateTeam()).should.be.empty @server.queuedPlayers().should.have.length(3) @server.beginBattles (err, battleIds) => @battleIds = battleIds @relevantUser = @server.findBattle(@battleIds[0]).battle.playerIds[0] done() it "removes from user battles if ended", -> @server.getUserBattles(@relevantUser).should.not.be.empty battle = @server.findBattle(@battleIds[0]) battle.endBattle() @server.getUserBattles(@user1).should.be.empty @server.getUserBattles(@user2).should.be.empty @server.getUserBattles(@user3).should.be.empty it "removes from user battles if forfeited", -> @server.getUserBattles(@relevantUser).should.not.be.empty battle = @server.findBattle(@battleIds[0]) battle.forfeit(@relevantUser) @server.getUserBattles(@user1).should.be.empty @server.getUserBattles(@user2).should.be.empty @server.getUserBattles(@user3).should.be.empty
true
require './helpers' {BattleServer} = require('../server/server') {Conditions, DEFAULT_FORMAT} = require '../shared/conditions' {Protocol} = require '../shared/protocol' {Factory} = require './factory' alts = require('../server/alts') should = require('should') generateTeam = -> [ Factory("Magikarp") Factory("PI:NAME:<NAME>END_PIados") Factory('Hitmonchan') Factory("Celebi") Factory("Blissey") Factory("Alakazam") ] describe 'BattleServer', -> it 'can create a new battle', -> server = new BattleServer() battleId = server.createBattle() server.battles.should.have.ownProperty battleId it "sends the 'spectateBattle' event for each matched player", (done) -> server = new BattleServer() players = [] players.push server.findOrCreateUser(id: 1, name: 'PI:NAME:<NAME>END_PI', @stubSpark()) players.push server.findOrCreateUser(id: 2, name: 'PI:NAME:<NAME>END_PI', @stubSpark()) spies = [] for player in players spy = @sandbox.spy(player.sparks[0], 'send') spies.push(spy) for player in players server.queuePlayer(player.name, generateTeam()).should.be.empty server.beginBattles (err, ids) -> throw new Error(err.message) if err return if ids.length == 0 for spy in spies spy.calledWith('spectateBattle').should.be.true done() describe "#queuePlayer", -> it "queues players", -> server = new BattleServer() derp = server.findOrCreateUser(id: 1, name: 'derp', @stubSpark()) server.queuePlayer(derp.name, generateTeam()).should.be.empty server.queues[DEFAULT_FORMAT].size().should.equal(1) it "does not queue players already queued", -> server = new BattleServer() derp = server.findOrCreateUser(id: 1, name: 'derp', @stubSpark()) server.queuePlayer(derp.name, generateTeam()).should.be.empty server.queuePlayer(derp.name, generateTeam()).should.be.empty server.queues[DEFAULT_FORMAT].size().should.equal(1) describe "#getOngoingBattles", -> it "returns one object for each queued battle", (done) -> server = new BattleServer() nBattles = 3 for i in [1..nBattles] first = 2 * i second = (2 * i) + 1 server.findOrCreateUser(id: first, name: String(first), @stubSpark()) server.findOrCreateUser(id: second, name: String(second), @stubSpark()) server.queuePlayer(String(first), generateTeam()).should.be.empty server.queuePlayer(String(second), generateTeam()).should.be.empty server.beginBattles -> server.getOngoingBattles().should.have.length(nBattles) done() describe "#registerChallenge", -> it "registers a challenge to a player", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) server.challenges.should.have.property(user.name) server.challenges[user.name].should.have.property(other.name) challenge = server.challenges[user.name][other.name] challenge.should.have.property("team") challenge.should.have.property("format") challenge.should.have.property("conditions") challenge.team.should.equal(team) challenge.format.should.equal(format) challenge.conditions.should.equal(conditions) it "does not override old challenges", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @stubSpark()) team = generateTeam() format = 'xy1000' diffFormat = 'xy500' diffTeam = generateTeam() diffTeam[0] = Factory("Celebi") server.registerChallenge(user, other.name, format, team) server.registerChallenge(user, other.name, diffFormat, diffTeam) challenge = server.challenges[user.name][other.name] challenge.format.should.equal(format) challenge.team.should.equal(team) it "returns an error if the team is invalid", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @stubSpark()) format = 'xy1000' mock = @sandbox.mock(user).expects('error').once() team = [] server.registerChallenge(user, other.name, format, team) mock.verify() it "returns an error if the team is over 1000 PBV with 1000 PBV clause", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @stubSpark()) format = 'xy1000' team = generateTeam() team[0] = Factory("Arceus", moves: [ "Recover" ]) conditions = [ Conditions.PBV_1000 ] mock = @sandbox.mock(user).expects('error').once() server.registerChallenge(user, other.name, format, team, conditions) mock.verify() it "returns an error on a rated challenge", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @stubSpark()) format = 'xy1000' team = generateTeam() conditions = [ Conditions.RATED_BATTLE ] mock = @sandbox.mock(user).expects('error').once() server.registerChallenge(user, other.name, format, team, conditions) mock.verify() it "returns an error if the format is invalid", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @stubSpark()) team = generateTeam() format = "UNRELEASED INFERNO RED AND WEIRD YELLOWISH GREEN" conditions = [] mock = @sandbox.mock(user).expects('error').once() server.registerChallenge(user, other.name, format, team, conditions) mock.verify() it "returns an error if the challengee is offline", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] mock = @sandbox.mock(user).expects('error').once() server.registerChallenge(user, "husk", format, team, conditions) mock.verify() it "returns an error if you challenge yourself", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] mock = @sandbox.mock(user).expects('error').once() server.registerChallenge(user, user.name, format, team, conditions) mock.verify() it "sends an error if a challenge already exists for that pair", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) mock = @sandbox.mock(other).expects('error').once() server.registerChallenge(other, user.name, format, team, conditions) mock.verify() it "sends a 'challenge' event to the challengee", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] otherSpy = @sandbox.spy(other, 'send') otherSpy.withArgs('challenge', user.name, format, conditions) server.registerChallenge(user, other.name, format, team, conditions) otherSpy.withArgs('challenge', user.name, format, conditions) .calledOnce.should.be.true it "returns an error if the server is locked down", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @stubSpark()) format = 'xy1000' team = generateTeam() conditions = [ Conditions.PBV_1000 ] mock = @sandbox.mock(user).expects('error').once() server.lockdown() server.registerChallenge(user, other.name, format, team, conditions) mock.verify() describe "#cancelChallenge", -> it "sends a 'cancelChallenge' to both the challengee and challenger", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] userSpy = @sandbox.spy(user, 'send') userSpy.withArgs('cancelChallenge', other.name) otherSpy = @sandbox.spy(other, 'send') otherSpy.withArgs('cancelChallenge', user.name) server.registerChallenge(user, other.name, format, team, conditions) server.cancelChallenge(user, other.name) userSpy.withArgs('cancelChallenge', other.name).calledOnce.should.be.true otherSpy.withArgs('cancelChallenge', user.name).calledOnce.should.be.true it "removes the challenge from the internal hash", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) should.exist server.challenges[user.name][other.name] server.cancelChallenge(user, other.name) should.not.exist server.challenges[user.name][other.name] describe "#rejectChallenge", -> it "sends a 'rejectChallenge' to the challengee and challenger", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) userSpy = @sandbox.spy(user, 'send') userSpy.withArgs('rejectChallenge', other.name) otherSpy = @sandbox.spy(other, 'send') otherSpy.withArgs('rejectChallenge', user.name) server.rejectChallenge(other, user.name) userSpy.withArgs('rejectChallenge', other.name).calledOnce.should.be.true otherSpy.withArgs('rejectChallenge', user.name).calledOnce.should.be.true it "removes the challenge from the internal hash", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) should.exist server.challenges[user.name][other.name] server.rejectChallenge(other, user.name) should.not.exist server.challenges[user.name][other.name] it "returns an error if no such challenge exists", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) mock = @sandbox.mock(other).expects('error').once() server.rejectChallenge(other, "bogus dude") mock.verify() describe "#acceptChallenge", -> initServer = -> @server = new BattleServer() @user = @server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", @stubSpark()) @other = @server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @stubSpark()) it "creates a battle with the teams given by both players", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] @server.registerChallenge(@user, @other.name, format, team, conditions) mock = @sandbox.mock(@server).expects('createBattle').once() @server.acceptChallenge(@other, @user.name, team) mock.verify() it "returns an error to a player if their team is invalid", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] @server.registerChallenge(@user, @other.name, format, team, conditions) mock = @sandbox.mock(@other).expects('error').once() @server.acceptChallenge(@other, @user.name, []) mock.verify() it "returns an error to a player if their team violates clauses", -> initServer.call(this) team = generateTeam() acceptTeam = generateTeam() acceptTeam[0] = Factory("Mewtwo", moves: [ "Psychic" ]) format = 'xy1000' conditions = [ Conditions.PBV_1000 ] @server.registerChallenge(@user, @other.name, format, team, conditions) mock = @sandbox.mock(@other).expects('error').once() @server.acceptChallenge(@other, @user.name, acceptTeam) mock.verify() it "removes the challenge from the internal hash", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] @server.registerChallenge(@user, @other.name, format, team, conditions) should.exist @server.challenges[@user.name][@other.name] @server.acceptChallenge(@other, @user.name, team) should.not.exist @server.challenges[@user.name][@other.name] it "sends a 'challengeSuccess' event to both players", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] userSpy = @sandbox.spy(@user, 'send') userSpy.withArgs('challengeSuccess', @other.name) otherSpy = @sandbox.spy(@other, 'send') otherSpy.withArgs('challengeSuccess', @user.name) @server.registerChallenge(@user, @other.name, format, team, conditions) @server.acceptChallenge(@other, @user.name, team) userSpy.withArgs('challengeSuccess', @other.name).calledOnce.should.be.true otherSpy.withArgs('challengeSuccess', @user.name).calledOnce.should.be.true it "returns an error if no such challenge exists", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] @server.registerChallenge(@user, @other.name, format, team, conditions) mock = @sandbox.mock(@other).expects('error').once() @server.acceptChallenge(@other, "bogus dude", team) mock.verify() it "overrides the user's name with the alt name in battle", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] @server.registerChallenge(@user, @other.name, format, team, conditions, "PI:NAME:<NAME>END_PI") battleId = @server.acceptChallenge(@other, @user.name, team, "PI:NAME:<NAME>END_PI") battle = @server.findBattle(battleId) battle.battle.playerNames.should.eql ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"] it "sets the rating key to be the unique alt id if there is an alt", -> initServer.call(this) team = generateTeam() format = 'xy1000' conditions = [] @server.registerChallenge(@user, @other.name, format, team, conditions, "PI:NAME:<NAME>END_PI") battleId = @server.acceptChallenge(@other, @user.name, team, "PI:NAME:<NAME>END_PI") battle = @server.findBattle(battleId) battle.battle.getPlayer("PI:NAME:<NAME>END_PI").ratingKey.should.equal alts.uniqueId(@user.name, "PI:NAME:<NAME>END_PI") battle.battle.getPlayer("PI:NAME:<NAME>END_PI").ratingKey.should.equal alts.uniqueId(@other.name, "PI:NAME:<NAME>END_PI") describe "#leave", -> it "removes challenges by that player", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", spark = @stubSpark()) other = server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(user, other.name, format, team, conditions) should.exist server.challenges[user.name] should.exist server.challenges[user.name][other.name] server.leave(spark) should.not.exist server.challenges[user.name] it "removes challenges to that player", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", spark = @stubSpark()) other = server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(other, user.name, format, team, conditions) should.exist server.challenges[other.name] should.exist server.challenges[other.name][user.name] server.leave(spark) should.exist server.challenges[other.name] should.not.exist server.challenges[other.name][user.name] describe "#lockdown", -> it "cancels all challenges", -> server = new BattleServer() user = server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", @stubSpark()) other = server.findOrCreateUser(id: 2, name: "PI:NAME:<NAME>END_PI", @stubSpark()) team = generateTeam() format = 'xy1000' conditions = [] server.registerChallenge(other, user.name, format, team, conditions) should.exist server.challenges[other.name] should.exist server.challenges[other.name][user.name] server.lockdown() should.not.exist server.challenges[other.name] describe "#validateTeam", -> it "returns non-empty if given anything that's not an array", -> server = new BattleServer() server.validateTeam().should.not.be.empty it "returns empty if given a non-empty array containing Pokemon", -> server = new BattleServer() server.validateTeam(generateTeam()).should.be.empty it "returns non-empty if given an empty array", -> server = new BattleServer() server.validateTeam([]).should.not.be.empty it "returns non-empty if a team member is not a valid Pokemon", -> server = new BattleServer() invalidPokemon = {} server.validateTeam([ invalidPokemon ]).should.not.be.empty it "returns non-empty if a team member has a fake species name", -> server = new BattleServer() team = generateTeam() team[0] = {species: "NOTREALMON"} server.validateTeam(team).should.not.be.empty it "returns non-empty if a team member has no moveset", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Hitmonchan", moves: null) server.validateTeam(team).should.not.be.empty it "returns non-empty if a team member has an empty moveset", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Hitmonchan", moves: []) server.validateTeam(team).should.not.be.empty it "returns non-empty if a team member has a bogus moveset", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Hitmonchan", moves: true) server.validateTeam(team).should.not.be.empty team[0] = Factory("Hitmonchan", moves: ["Super Powerful Punch"]) server.validateTeam(team).should.not.be.empty it "returns non-empty if a team member has an illegal moveset", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Raichu", moves: [ "Volt Tackle", "Encore" ]) server.validateTeam(team, 'bw').should.not.be.empty # TODO: 4 is a magic constant it "returns non-empty if a pokemon has more than 4 moves", -> server = new BattleServer() team = generateTeam() team[0] = Factory "Hitmonchan", moves: [ "Ice Punch" "Fire Punch" "Close Combat" "Mach Punch" "Rapid Spin" ] server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a move it can't learn", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", moves: [ "Fissure" ]) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a fake move", -> server = new BattleServer() team = generateTeam() team[0] = Factory("PI:NAME:<NAME>END_PI", moves: [ "Splash", "Armageddon" ]) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an ability it can't have", -> server = new BattleServer() team = generateTeam() team[0] = Factory("PI:NAME:<NAME>END_PIikarp", ability: "Wonder Guard") server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a bogus ability", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", ability: "Being Batman") server.validateTeam(team).should.not.be.empty it "returns empty if a pokemon has a hidden ability", -> server = new BattleServer() team = generateTeam() team[0] = Factory("CloPI:NAME:<NAME>END_PI", ability: "Overcoat") server.validateTeam(team).should.be.empty it "returns non-empty if a pokemon has a level below 1", -> server = new BattleServer() team = generateTeam() team[0] = Factory("PI:NAME:<NAME>END_PI", level: 0) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a bogus level", -> server = new BattleServer() team = generateTeam() team[0] = Factory("PI:NAME:<NAME>END_PIikPI:NAME:<NAME>END_PI", level: "hi") server.validateTeam(team).should.not.be.empty # TODO: 100 is a magic constant it "returns non-empty if a pokemon has a level over 100", -> server = new BattleServer() team = generateTeam() team[0] = Factory("PI:NAME:<NAME>END_PI", level: 101) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an iv below 0", -> server = new BattleServer() team = generateTeam() team[0] = Factory("MagikPI:NAME:<NAME>END_PI", ivs: { hp: -1 }) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an iv above 31", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", ivs: { hp: 32 }) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has bogus ivs", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", ivs: true) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an ev below 0", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", evs: { hp: -1 }) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an ev above 255", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", evs: { hp: 256 }) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an ev total above 510", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", evs: { hp: 255, defense: 255, speed: 255 }) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has bogus evs", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Magikarp", evs: true) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has an invalid gender", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Metagross", gender: "Alien") server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a gender it can't have", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Metagross", gender: "F") server.validateTeam(team).should.not.be.empty team = generateTeam() team[0] = Factory("Blissey", gender: "M") server.validateTeam(team).should.not.be.empty team = generateTeam() team[0] = Factory("Gallade", gender: "F") server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a bogus forme", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Blissey", forme: "Super Ultra Mega Blissey") server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon has a battle-only forme", -> server = new BattleServer() team = generateTeam() team[0] = Factory("Meloetta", forme: "pirouette", moves: ["Relic Song"]) server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon cannot have its forme" it "returns non-empty if the format is fake", -> server = new BattleServer() server.validateTeam(generateTeam(), 'bogusformat').should.not.be.empty it "returns non-empty if a pokemon's nickname matches another species", -> server = new BattleServer() team = generateTeam() team[0].name = "PI:NAME:<NAME>END_PI" server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon's nickname is blank", -> server = new BattleServer() team = generateTeam() team[0].name = "" server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon's nickname contains illegal chars", -> server = new BattleServer() team = generateTeam() team[0].name = "some chars \uFE20 are illegal" server.validateTeam(team).should.not.be.empty it "returns non-empty if a pokemon's nickname is past a certain length", -> server = new BattleServer() team = generateTeam() team[0].name = ("A" for x in [0...50]).join('') server.validateTeam(team).should.not.be.empty describe "#beginBattles", -> it "creates a battle per pair", (done) -> server = new BattleServer() for i in [1..4] server.findOrCreateUser(id: i, name: "user#{i}", @stubSpark()) server.queuePlayer("user#{i}", generateTeam()) server.beginBattles (err, battleIds) -> battleIds.length.should.equal(2) done() describe "users", -> it "are recorded to be playing in which battles", (done) -> server = new BattleServer() [ user1, user2, user3 ] = [ "a", "b", "c" ] for name, i in [ user1, user2, user3 ] server.findOrCreateUser(id: i, name: name, @stubSpark()) server.queuePlayer(user1, generateTeam()).should.be.empty server.queuePlayer(user2, generateTeam()).should.be.empty server.queuePlayer(user3, generateTeam()).should.be.empty server.beginBattles (err, battleIds) -> server.getUserBattles(user1).should.eql(battleIds) server.getUserBattles(user2).should.eql(battleIds) server.getUserBattles(user3).should.be.empty done() it "no longer records battles once they end", (done) -> server = new BattleServer() [ user1, user2, user3 ] = [ "a", "b", "c" ] for name, i in [ user1, user2, user3 ] server.findOrCreateUser(id: i, name: name, @stubSpark()) server.queuePlayer(user1, generateTeam()).should.be.empty server.queuePlayer(user2, generateTeam()).should.be.empty server.queuePlayer(user3, generateTeam()).should.be.empty server.beginBattles (err, battleIds) -> for battleId in battleIds battle = server.findBattle(battleId) battle.endBattle() server.getUserBattles(user1).should.be.empty server.getUserBattles(user2).should.be.empty server.getUserBattles(user3).should.be.empty done() it "can join multiple times", -> server = new BattleServer() server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", spark1 = @stubSpark()) server.join(spark1) (=> server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", spark2 = @stubSpark()) server.join(spark2) ).should.not.throw() it "records battles they're under an alt in", (done) -> server = new BattleServer() [ user1, user2 ] = [ "a", "b" ] for name, i in [ user1, user2 ] server.findOrCreateUser(id: i, name: name, @stubSpark()) server.queuePlayer(user1, generateTeam(), null, 'alt1').should.be.empty server.queuePlayer(user2, generateTeam(), null, 'alt2').should.be.empty server.beginBattles (err, battleIds) -> server.getUserBattles(user1).should.not.be.empty server.getUserBattles(user2).should.not.be.empty done() it "auto-rejoin battles they're under an alt in", (done) -> server = new BattleServer() [ user1, user2 ] = [ "a", "b" ] server.findOrCreateUser(id: 1, name: user1, spark1 = @stubSpark()) server.findOrCreateUser(id: 2, name: user2, spark2 = @stubSpark()) server.queuePlayer(user1, generateTeam(), null, 'alt1').should.be.empty server.queuePlayer(user2, generateTeam(), null, 'alt2').should.be.empty server.beginBattles (err, battleIds) => [battleId] = battleIds battle = server.findBattle(battleId).battle # test spark1 spy = @sandbox.spy(battle, 'tellPlayer').withArgs(user1, Protocol.RECEIVE_TEAM) server.join(spark1) spy.calledOnce.should.be.true battle.tellPlayer.restore() # test spark2 spy = @sandbox.spy(battle, 'tellPlayer').withArgs(user2, Protocol.RECEIVE_TEAM) server.join(spark2) spy.calledOnce.should.be.true battle.tellPlayer.restore() done() it "automatically leaves a battle when leaving the server", (done) -> server = new BattleServer() [ user1, user2 ] = [ "a", "b" ] server.findOrCreateUser(id: 1, name: user1, spark1 = @stubSpark()) server.findOrCreateUser(id: 2, name: user2, spark2 = @stubSpark()) server.join(spark1) server.join(spark2) server.queuePlayer(user1, generateTeam(), null, 'alt1').should.be.empty server.queuePlayer(user2, generateTeam(), null, 'alt2').should.be.empty server.beginBattles (err, battleIds) => [battleId] = battleIds battle = server.findBattle(battleId).battle # test spark1 spy = @sandbox.spy(battle, 'remove').withArgs(spark1) broadcastSpy = @sandbox.spy(battle, 'send') broadcastSpy = broadcastSpy.withArgs('leaveChatroom', battle.id, 'alt1') server.leave(spark1) spark1.end() spy.calledOnce.should.be.true broadcastSpy.calledOnce.should.be.true battle.remove.restore() battle.send.restore() # test spark2 spy = @sandbox.spy(battle, 'remove').withArgs(spark2) broadcastSpy = @sandbox.spy(battle, 'send') broadcastSpy = broadcastSpy.withArgs('leaveChatroom', battle.id, 'alt2') server.leave(spark2) spark2.end() spy.calledOnce.should.be.true broadcastSpy.calledOnce.should.be.true battle.remove.restore() battle.send.restore() done() describe "a battle", -> beforeEach (done) -> @server = new BattleServer() [ @user1, @user2, @user3 ] = [ "a", "b", "c" ] for name, i in [ @user1, @user2, @user3 ] @server.findOrCreateUser(id: i, name: name, @stubSpark()) @server.queuePlayer(@user1, generateTeam()).should.be.empty @server.queuePlayer(@user2, generateTeam()).should.be.empty @server.queuePlayer(@user3, generateTeam()).should.be.empty @server.queuedPlayers().should.have.length(3) @server.beginBattles (err, battleIds) => @battleIds = battleIds @relevantUser = @server.findBattle(@battleIds[0]).battle.playerIds[0] done() it "removes from user battles if ended", -> @server.getUserBattles(@relevantUser).should.not.be.empty battle = @server.findBattle(@battleIds[0]) battle.endBattle() @server.getUserBattles(@user1).should.be.empty @server.getUserBattles(@user2).should.be.empty @server.getUserBattles(@user3).should.be.empty it "removes from user battles if forfeited", -> @server.getUserBattles(@relevantUser).should.not.be.empty battle = @server.findBattle(@battleIds[0]) battle.forfeit(@relevantUser) @server.getUserBattles(@user1).should.be.empty @server.getUserBattles(@user2).should.be.empty @server.getUserBattles(@user3).should.be.empty
[ { "context": "e based on a Left Leaning Red-Black Tree\n @author Mads Hartmann Jensen (mads379@gmail.com)\n###\n\nmugs.provide(\"mugs.LLRBS", "end": 144, "score": 0.9998687505722046, "start": 124, "tag": "NAME", "value": "Mads Hartmann Jensen" }, { "context": "ng Red-Black Tree\n @author Mads Hartmann Jensen (mads379@gmail.com)\n###\n\nmugs.provide(\"mugs.LLRBSet\")\n\nmugs.require(", "end": 163, "score": 0.9999280571937561, "start": 146, "tag": "EMAIL", "value": "mads379@gmail.com" } ]
src/LLRBSet.coffee
mads-hartmann/mugs
1
###* @fileoverview Contains the implementation of the Set data structure based on a Left Leaning Red-Black Tree @author Mads Hartmann Jensen (mads379@gmail.com) ### mugs.provide("mugs.LLRBSet") mugs.require("mugs.LLRBNode") mugs.require("mugs.LLRBLeaf") mugs.require("mugs.Indexed") ###* mugs.LLRBSet provides the implementation of the abstract data type 'Set' based on a Left-Leaning Red Black Tree. The LLRBSet contains the following operations <pre> insert(key,value) O(log n) get(index) O(n) (TODO: can be greatly improved) remove(index) O(log n) keys() O(n) values() O(n) isEmpty() O(1) forEach(f) O(n*O(f)) update O(n) removeAt O(n) first O(1) last O(n) head O(1) tail O(log n) foldLeft(seed)(f) O(n*O(f)) foldRight(seed)(f) O(n*O(f)) </pre> @public @augments mugs.Indexed @class mugs.LLRBSet Contains the implementation of the Set data structure based on a Left Leaning Red-Black Tree @param items An array of items to construct the LLRBSet from @param comparator A comparator function that can compare the keys (optional). Will use a default comparator if no comparator is given. The default one uses the < and > operators. ### mugs.LLRBSet = (items,comparator) -> treeUnderConstruction = new mugs.LLRBLeaf(comparator) if items instanceof Array and items.length > 0 for item in items treeUnderConstruction = treeUnderConstruction.insert(item, item) this.tree = treeUnderConstruction this.tree.comparator = comparator if comparator? this mugs.LLRBSet.prototype = new mugs.Indexed() ###* The elements of the set @return {List} A list containing all the element of the set ### mugs.LLRBSet.prototype.values = () -> this.tree.values() ###* Used to construct a TreeMap from mugs.RedBlackTree. This is intended for internal use only. Would've marked it private if I could. @private ### mugs.LLRBSet.prototype.buildFromTree = (tree) -> set = new mugs.LLRBSet(this.comparator) set.tree = tree set ### --------------------------------------------------------------------------------------------- Methods related to Collection prototype --------------------------------------------------------------------------------------------- ### ###* Tests if the set contains the element @param element The element to check for ### mugs.LLRBSet.prototype.contains = ( element ) -> this.tree.containsKey( element ) ###* Checks if the collection is empty @return true if the collection is empty, otherwise false ### mugs.LLRBSet.prototype.isEmpty = () -> this.tree.isEmpty() ### --------------------------------------------------------------------------------------------- Methods related to Collection prototype --------------------------------------------------------------------------------------------- ### ###* @private ### mugs.LLRBSet.prototype.buildFromArray = (arr) -> new mugs.LLRBSet(arr, this.comparator) ###* Applies function 'f' on each value in the collection. This return nothing and is only invoked for the side-effects of f. @param f The unary function to apply on each element in the collection. @see mugs.Collection ### mugs.LLRBSet.prototype.forEach = ( f ) -> # the tree that the set is based on stores key-value pair on each node so we only # have to apply the function on the key and then just return that value. q = (kv) -> newValue = f(kv.key) { key: newValue, value: newValue } this.tree.inorderTraversal( q ) ### --------------------------------------------------------------------------------------------- Extensible interface --------------------------------------------------------------------------------------------- ### ###* Creates a new Set with the item inserted @param item The Item to insert into the Set @return A new LLRBSet with the item inserted ### mugs.LLRBSet.prototype.insert = ( item ) -> this.buildFromTree(this.tree.insert(item,item)) ###* Creates a new Set without the given item @param item The item to remove from the set @return A new Set without the given item ### mugs.LLRBSet.prototype.remove = ( item ) -> this.buildFromTree(this.tree.remove(item)) ### --------------------------------------------------------------------------------------------- Indexed interface --------------------------------------------------------------------------------------------- ### ###* Returns an mugs.Option with the value at the given index if it exists, otherwise mugs.None @param index The index of the item to get. @return An mugs.Option with the value at the given index if it exists, otherwise mugs.None ### mugs.LLRBSet.prototype.get = ( index ) -> this.tree.getAt(index) ###* Update the value at a given index. @param index The index of the item to update @param item The new item to store at the given index @return A new collection with the value at the given index updated. ### mugs.LLRBSet.prototype.update = (index, item) -> itm = this.get(index) this.buildFromTree(this.tree.insert(itm,item)) ###* Returns a new collection without the item at the given index @param index the index of the item to remove from the collection. @return A new collection without the item at the given index ### mugs.LLRBSet.prototype.removeAt = (index) -> itm = this.get(index).get() this.buildFromTree(this.tree.remove(itm)) ###* Return the first item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. @return The first item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. ### mugs.LLRBSet.prototype.first = () -> this.get(0) ###* Return the tail of the collection. @return The tail of the collection ### mugs.LLRBSet.prototype.tail = () -> this.removeAt(0) ###* Return the last item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. @return The last item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. ### mugs.LLRBSet.prototype.last = () -> this.get(this.size()-1) ###* Return the head of the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. Is the equivalent to first. @return The head of the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. ### mugs.LLRBSet.prototype.head = () -> this.get(0).get() ###* Applies a binary operator on all items of this collection going left to right and ending with the seed value. This is a curried function that takes a seed value which returns a function that takes a function which will then be applied to the items. The function is binary where the first parameter is the value of the fold so far and the second is the current item. @param {*} seed The value to use when the collection is empty @return {function(function(*, *):*):*} A function which takes a binary function ### mugs.LLRBSet.prototype.foldLeft = (seed) -> (f) => this.tree.values().foldLeft(seed)(f) ###* Applies a binary operator on all items of this collection going right to left and ending with the seed value. This is a curried function that takes a seed value which returns a function that takes a function which will then be applied to the items. The function is binary where the first parameter is the value of the fold so far and the second is the current item. @param {*} seed The value to use when the collection is empty @return {function(function(*, *):*):*} A function which takes a binary function ### mugs.LLRBSet.prototype.foldRight = (seed) -> (f) => this.tree.values().foldRight(seed)(f)
217511
###* @fileoverview Contains the implementation of the Set data structure based on a Left Leaning Red-Black Tree @author <NAME> (<EMAIL>) ### mugs.provide("mugs.LLRBSet") mugs.require("mugs.LLRBNode") mugs.require("mugs.LLRBLeaf") mugs.require("mugs.Indexed") ###* mugs.LLRBSet provides the implementation of the abstract data type 'Set' based on a Left-Leaning Red Black Tree. The LLRBSet contains the following operations <pre> insert(key,value) O(log n) get(index) O(n) (TODO: can be greatly improved) remove(index) O(log n) keys() O(n) values() O(n) isEmpty() O(1) forEach(f) O(n*O(f)) update O(n) removeAt O(n) first O(1) last O(n) head O(1) tail O(log n) foldLeft(seed)(f) O(n*O(f)) foldRight(seed)(f) O(n*O(f)) </pre> @public @augments mugs.Indexed @class mugs.LLRBSet Contains the implementation of the Set data structure based on a Left Leaning Red-Black Tree @param items An array of items to construct the LLRBSet from @param comparator A comparator function that can compare the keys (optional). Will use a default comparator if no comparator is given. The default one uses the < and > operators. ### mugs.LLRBSet = (items,comparator) -> treeUnderConstruction = new mugs.LLRBLeaf(comparator) if items instanceof Array and items.length > 0 for item in items treeUnderConstruction = treeUnderConstruction.insert(item, item) this.tree = treeUnderConstruction this.tree.comparator = comparator if comparator? this mugs.LLRBSet.prototype = new mugs.Indexed() ###* The elements of the set @return {List} A list containing all the element of the set ### mugs.LLRBSet.prototype.values = () -> this.tree.values() ###* Used to construct a TreeMap from mugs.RedBlackTree. This is intended for internal use only. Would've marked it private if I could. @private ### mugs.LLRBSet.prototype.buildFromTree = (tree) -> set = new mugs.LLRBSet(this.comparator) set.tree = tree set ### --------------------------------------------------------------------------------------------- Methods related to Collection prototype --------------------------------------------------------------------------------------------- ### ###* Tests if the set contains the element @param element The element to check for ### mugs.LLRBSet.prototype.contains = ( element ) -> this.tree.containsKey( element ) ###* Checks if the collection is empty @return true if the collection is empty, otherwise false ### mugs.LLRBSet.prototype.isEmpty = () -> this.tree.isEmpty() ### --------------------------------------------------------------------------------------------- Methods related to Collection prototype --------------------------------------------------------------------------------------------- ### ###* @private ### mugs.LLRBSet.prototype.buildFromArray = (arr) -> new mugs.LLRBSet(arr, this.comparator) ###* Applies function 'f' on each value in the collection. This return nothing and is only invoked for the side-effects of f. @param f The unary function to apply on each element in the collection. @see mugs.Collection ### mugs.LLRBSet.prototype.forEach = ( f ) -> # the tree that the set is based on stores key-value pair on each node so we only # have to apply the function on the key and then just return that value. q = (kv) -> newValue = f(kv.key) { key: newValue, value: newValue } this.tree.inorderTraversal( q ) ### --------------------------------------------------------------------------------------------- Extensible interface --------------------------------------------------------------------------------------------- ### ###* Creates a new Set with the item inserted @param item The Item to insert into the Set @return A new LLRBSet with the item inserted ### mugs.LLRBSet.prototype.insert = ( item ) -> this.buildFromTree(this.tree.insert(item,item)) ###* Creates a new Set without the given item @param item The item to remove from the set @return A new Set without the given item ### mugs.LLRBSet.prototype.remove = ( item ) -> this.buildFromTree(this.tree.remove(item)) ### --------------------------------------------------------------------------------------------- Indexed interface --------------------------------------------------------------------------------------------- ### ###* Returns an mugs.Option with the value at the given index if it exists, otherwise mugs.None @param index The index of the item to get. @return An mugs.Option with the value at the given index if it exists, otherwise mugs.None ### mugs.LLRBSet.prototype.get = ( index ) -> this.tree.getAt(index) ###* Update the value at a given index. @param index The index of the item to update @param item The new item to store at the given index @return A new collection with the value at the given index updated. ### mugs.LLRBSet.prototype.update = (index, item) -> itm = this.get(index) this.buildFromTree(this.tree.insert(itm,item)) ###* Returns a new collection without the item at the given index @param index the index of the item to remove from the collection. @return A new collection without the item at the given index ### mugs.LLRBSet.prototype.removeAt = (index) -> itm = this.get(index).get() this.buildFromTree(this.tree.remove(itm)) ###* Return the first item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. @return The first item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. ### mugs.LLRBSet.prototype.first = () -> this.get(0) ###* Return the tail of the collection. @return The tail of the collection ### mugs.LLRBSet.prototype.tail = () -> this.removeAt(0) ###* Return the last item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. @return The last item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. ### mugs.LLRBSet.prototype.last = () -> this.get(this.size()-1) ###* Return the head of the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. Is the equivalent to first. @return The head of the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. ### mugs.LLRBSet.prototype.head = () -> this.get(0).get() ###* Applies a binary operator on all items of this collection going left to right and ending with the seed value. This is a curried function that takes a seed value which returns a function that takes a function which will then be applied to the items. The function is binary where the first parameter is the value of the fold so far and the second is the current item. @param {*} seed The value to use when the collection is empty @return {function(function(*, *):*):*} A function which takes a binary function ### mugs.LLRBSet.prototype.foldLeft = (seed) -> (f) => this.tree.values().foldLeft(seed)(f) ###* Applies a binary operator on all items of this collection going right to left and ending with the seed value. This is a curried function that takes a seed value which returns a function that takes a function which will then be applied to the items. The function is binary where the first parameter is the value of the fold so far and the second is the current item. @param {*} seed The value to use when the collection is empty @return {function(function(*, *):*):*} A function which takes a binary function ### mugs.LLRBSet.prototype.foldRight = (seed) -> (f) => this.tree.values().foldRight(seed)(f)
true
###* @fileoverview Contains the implementation of the Set data structure based on a Left Leaning Red-Black Tree @author PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) ### mugs.provide("mugs.LLRBSet") mugs.require("mugs.LLRBNode") mugs.require("mugs.LLRBLeaf") mugs.require("mugs.Indexed") ###* mugs.LLRBSet provides the implementation of the abstract data type 'Set' based on a Left-Leaning Red Black Tree. The LLRBSet contains the following operations <pre> insert(key,value) O(log n) get(index) O(n) (TODO: can be greatly improved) remove(index) O(log n) keys() O(n) values() O(n) isEmpty() O(1) forEach(f) O(n*O(f)) update O(n) removeAt O(n) first O(1) last O(n) head O(1) tail O(log n) foldLeft(seed)(f) O(n*O(f)) foldRight(seed)(f) O(n*O(f)) </pre> @public @augments mugs.Indexed @class mugs.LLRBSet Contains the implementation of the Set data structure based on a Left Leaning Red-Black Tree @param items An array of items to construct the LLRBSet from @param comparator A comparator function that can compare the keys (optional). Will use a default comparator if no comparator is given. The default one uses the < and > operators. ### mugs.LLRBSet = (items,comparator) -> treeUnderConstruction = new mugs.LLRBLeaf(comparator) if items instanceof Array and items.length > 0 for item in items treeUnderConstruction = treeUnderConstruction.insert(item, item) this.tree = treeUnderConstruction this.tree.comparator = comparator if comparator? this mugs.LLRBSet.prototype = new mugs.Indexed() ###* The elements of the set @return {List} A list containing all the element of the set ### mugs.LLRBSet.prototype.values = () -> this.tree.values() ###* Used to construct a TreeMap from mugs.RedBlackTree. This is intended for internal use only. Would've marked it private if I could. @private ### mugs.LLRBSet.prototype.buildFromTree = (tree) -> set = new mugs.LLRBSet(this.comparator) set.tree = tree set ### --------------------------------------------------------------------------------------------- Methods related to Collection prototype --------------------------------------------------------------------------------------------- ### ###* Tests if the set contains the element @param element The element to check for ### mugs.LLRBSet.prototype.contains = ( element ) -> this.tree.containsKey( element ) ###* Checks if the collection is empty @return true if the collection is empty, otherwise false ### mugs.LLRBSet.prototype.isEmpty = () -> this.tree.isEmpty() ### --------------------------------------------------------------------------------------------- Methods related to Collection prototype --------------------------------------------------------------------------------------------- ### ###* @private ### mugs.LLRBSet.prototype.buildFromArray = (arr) -> new mugs.LLRBSet(arr, this.comparator) ###* Applies function 'f' on each value in the collection. This return nothing and is only invoked for the side-effects of f. @param f The unary function to apply on each element in the collection. @see mugs.Collection ### mugs.LLRBSet.prototype.forEach = ( f ) -> # the tree that the set is based on stores key-value pair on each node so we only # have to apply the function on the key and then just return that value. q = (kv) -> newValue = f(kv.key) { key: newValue, value: newValue } this.tree.inorderTraversal( q ) ### --------------------------------------------------------------------------------------------- Extensible interface --------------------------------------------------------------------------------------------- ### ###* Creates a new Set with the item inserted @param item The Item to insert into the Set @return A new LLRBSet with the item inserted ### mugs.LLRBSet.prototype.insert = ( item ) -> this.buildFromTree(this.tree.insert(item,item)) ###* Creates a new Set without the given item @param item The item to remove from the set @return A new Set without the given item ### mugs.LLRBSet.prototype.remove = ( item ) -> this.buildFromTree(this.tree.remove(item)) ### --------------------------------------------------------------------------------------------- Indexed interface --------------------------------------------------------------------------------------------- ### ###* Returns an mugs.Option with the value at the given index if it exists, otherwise mugs.None @param index The index of the item to get. @return An mugs.Option with the value at the given index if it exists, otherwise mugs.None ### mugs.LLRBSet.prototype.get = ( index ) -> this.tree.getAt(index) ###* Update the value at a given index. @param index The index of the item to update @param item The new item to store at the given index @return A new collection with the value at the given index updated. ### mugs.LLRBSet.prototype.update = (index, item) -> itm = this.get(index) this.buildFromTree(this.tree.insert(itm,item)) ###* Returns a new collection without the item at the given index @param index the index of the item to remove from the collection. @return A new collection without the item at the given index ### mugs.LLRBSet.prototype.removeAt = (index) -> itm = this.get(index).get() this.buildFromTree(this.tree.remove(itm)) ###* Return the first item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. @return The first item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. ### mugs.LLRBSet.prototype.first = () -> this.get(0) ###* Return the tail of the collection. @return The tail of the collection ### mugs.LLRBSet.prototype.tail = () -> this.removeAt(0) ###* Return the last item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. @return The last item in the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. ### mugs.LLRBSet.prototype.last = () -> this.get(this.size()-1) ###* Return the head of the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. Is the equivalent to first. @return The head of the collection wrapped in mugs.Some if the collection is non-empty, otherwise a mugs.None. ### mugs.LLRBSet.prototype.head = () -> this.get(0).get() ###* Applies a binary operator on all items of this collection going left to right and ending with the seed value. This is a curried function that takes a seed value which returns a function that takes a function which will then be applied to the items. The function is binary where the first parameter is the value of the fold so far and the second is the current item. @param {*} seed The value to use when the collection is empty @return {function(function(*, *):*):*} A function which takes a binary function ### mugs.LLRBSet.prototype.foldLeft = (seed) -> (f) => this.tree.values().foldLeft(seed)(f) ###* Applies a binary operator on all items of this collection going right to left and ending with the seed value. This is a curried function that takes a seed value which returns a function that takes a function which will then be applied to the items. The function is binary where the first parameter is the value of the fold so far and the second is the current item. @param {*} seed The value to use when the collection is empty @return {function(function(*, *):*):*} A function which takes a binary function ### mugs.LLRBSet.prototype.foldRight = (seed) -> (f) => this.tree.values().foldRight(seed)(f)
[ { "context": "itialValue = []\n\n func = (ac, v) ->\n key = grouper(v)\n existingGroup = new Linq(ac).FirstOrDefault", "end": 6826, "score": 0.8999357223510742, "start": 6816, "tag": "KEY", "value": "grouper(v)" } ]
src/coffee/linq.coffee
Lxsbw/linqjs
0
### LINQ to CoffeeScript (Language Integrated Query) ### class Linq ### Defaults the elements of the list ### constructor: (elements) -> elements = [] if not elements this._elements = elements #region Method alias this.add = this.Add this.append = this.Append this.prepend = this.Prepend this.addRange = this.AddRange this.aggregate = this.Aggregate this.all = this.All this.any = this.Any this.average = this.Average this.cast = this.Cast this.clear = this.Clear this.concat = this.Concat this.contains = this.Contains this.count = this.Count this.defaultIfEmpty = this.DefaultIfEmpty this.distinct = this.Distinct this.distinctBy = this.DistinctBy this.elementAt = this.ElementAt this.elementAtOrDefault = this.ElementAtOrDefault this.except = this.Except this.first = this.First this.firstOrDefault = this.FirstOrDefault this.forEach = this.ForEach this.groupBy = this.GroupBy this.groupJoin = this.GroupJoin this.indexOf = this.IndexOf this.insert = this.Insert this.intersect = this.Intersect this.join = this.Join this.last = this.Last this.lastOrDefault = this.LastOrDefault this.max = this.Max this.min = this.Min this.ofType = this.OfType this.orderBy = this.OrderBy this.orderByDescending = this.OrderByDescending this.thenBy = this.ThenBy this.thenByDescending = this.ThenByDescending this.remove = this.Remove this.removeAll = this.RemoveAll this.removeAt = this.RemoveAt this.reverse = this.Reverse this.select = this.Select this.selectMany = this.SelectMany this.sequenceEqual = this.SequenceEqual this.single = this.Single this.singleOrDefault = this.SingleOrDefault this.skip = this.Skip this.skipLast = this.SkipLast this.skipWhile = this.SkipWhile this.sum = this.Sum this.take = this.Take this.takeLast = this.TakeLast this.takeWhile = this.TakeWhile this.toArray = this.ToArray this.toDictionary = this.ToDictionary this.toList = this.ToList this.toLookup = this.ToLookup this.union = this.Union this.where = this.Where this.zip = this.Zip #endregion ### Adds an object to the end of the List<T>. ### Add: (element) -> this._elements.push(element) ### Appends an object to the end of the List<T>. ### Append: (element) -> this.Add(element) ### Add an object to the start of the List<T>. ### Prepend: (element) -> this._elements.unshift(element) ### Adds the elements of the specified collection to the end of the List<T>. ### AddRange: (elements) -> _a (_a = this._elements).push.apply(_a, elements) ### Applies an accumulator function over a sequence. ### Aggregate: (accumulator, initialValue) -> return this._elements.reduce(accumulator, initialValue) ### Determines whether all elements of a sequence satisfy a condition. ### All: (predicate) -> return this._elements.every(predicate) ### Determines whether a sequence contains any elements. ### Any: (predicate) -> return if predicate then this._elements.some(predicate) else this._elements.length > 0 ### Computes the average of a sequence of number values that are obtained by invoking a transform function on each element of the input sequence. ### Average: (transform) -> return tools.calcNumDiv(this.Sum(transform), this.Count()) ### Casts the elements of a sequence to the specified type. ### Cast: () -> return new Linq(this._elements) ### Removes all elements from the List<T>. ### Clear: () -> this._elements.length = 0 ### Concatenates two sequences. ### Concat: (list) -> return new Linq(this._elements.concat(list.ToArray())) ### Determines whether an element is in the List<T>. ### Contains: (element) -> return this.Any((x) -> x is element) ### Returns the number of elements in a sequence. ### Count: (predicate) -> return if predicate then this.Where(predicate).Count() else this._elements.length ### Returns the elements of the specified sequence or the type parameter's default value in a singleton collection if the sequence is empty. ### DefaultIfEmpty: (defaultValue) -> return if this.Count() then this else new Linq([defaultValue]) ### Returns distinct elements from a sequence by using the default equality comparer to compare values. ### Distinct: () -> return this.Where((value, index, iter) -> return ( (if tools.isObj(value) then iter.findIndex((obj) -> tools.equal(obj, value)) else iter.indexOf(value)) is index ) ) ### Returns distinct elements from a sequence according to specified key selector. ### DistinctBy: (keySelector) -> groups = this.GroupBy(keySelector) func = (res, key) -> curr = new Linq(groups).FirstOrDefault((x) -> tools.equal(x.key, key)) res.Add(curr.elements[0]) return res return new Linq(groups).Select((x) -> x.key).ToArray().reduce(func, new Linq()) ### Returns the element at a specified index in a sequence. ### ElementAt: (index) -> if (index < this.Count() && index >= 0) return this._elements[index] else throw new Error('ArgumentOutOfRangeException: index is less than 0 or greater than or equal to the number of elements in source.') ### Returns the element at a specified index in a sequence or a default value if the index is out of range. ### ElementAtOrDefault: (index) -> return if index < this.Count() && index >= 0 then this._elements[index] else undefined ### Produces the set difference of two sequences by using the default equality comparer to compare values. ### Except: (source) -> return this.Where((x) -> !source.Contains(x)) ### Returns the first element of a sequence. ### First: (predicate) -> if this.Count() return if predicate then this.Where(predicate).First() else this._elements[0] else throw new Error( 'InvalidOperationException: The source sequence is empty.') ### Returns the first element of a sequence, or a default value if the sequence contains no elements. ### FirstOrDefault: (predicate) -> return if this.Count(predicate) then this.First(predicate) else undefined ### Performs the specified action on each element of the List<T>. ### ForEach: (action) -> return this._elements.forEach(action) ### Groups the elements of a sequence according to a specified key selector function. ### GroupBy: (grouper, mapper) -> if (mapper is undefined) mapper = (val) -> val initialValue = [] func = (ac, v) -> key = grouper(v) existingGroup = new Linq(ac).FirstOrDefault((x) -> tools.equal(x.key, key)) mappedValue = mapper(v) if existingGroup existingGroup.elements.push(mappedValue) existingGroup.count++ else existingMap = { key: key, count: 1, elements: [mappedValue] } ac.push(existingMap) return ac return this.Aggregate(func, initialValue) ### Correlates the elements of two sequences based on equality of keys and groups the results. The default equality comparer is used to compare keys. ### GroupJoin: (list, key1, key2, result) -> return this.Select((x) -> return result x, list.Where((z) -> key1(x) is key2(z)) ) ### Returns the index of the first occurence of an element in the List. ### IndexOf: (element) -> return this._elements.indexOf(element) ### Inserts an element into the List<T> at the specified index. ### Insert: (index, element) -> if (index < 0 || index > this._elements.length) throw new Error('Index is out of range.') this._elements.splice(index, 0, element) ### Produces the set intersection of two sequences by using the default equality comparer to compare values. ### Intersect: (source) -> return this.Where((x) -> source.Contains(x)) ### Correlates the elements of two sequences based on matching keys. The default equality comparer is used to compare keys. ### Join: (list, key1, key2, result) -> selectmany = (selector) => return this.Aggregate(((ac, _, i) => ac.AddRange(this.Select(selector).ElementAt(i).ToArray()) ac ), new Linq()) return selectmany((x) -> return list .Where((y) -> key2(y) is key1(x)) .Select((z) -> result(x, z)) ) ### Returns the last element of a sequence. ### Last: (predicate) -> if this.Count() return if predicate then this.Where(predicate).Last() else this._elements[this.Count() - 1] else throw Error('InvalidOperationException: The source sequence is empty.') ### Returns the last element of a sequence, or a default value if the sequence contains no elements. ### LastOrDefault: (predicate) -> return if this.Count(predicate) then this.Last(predicate) else undefined ### Returns the maximum value in a generic sequence. ### Max: (selector) -> id = (x) -> x return Math.max.apply(Math, this._elements.map(selector || id)) ### Returns the minimum value in a generic sequence. ### Min: (selector) -> id = (x) -> x return Math.min.apply(Math, this._elements.map(selector || id)) ### Filters the elements of a sequence based on a specified type. ### OfType: (type) -> typeName switch (type) when Number typeName = typeof 0 break when String typeName = typeof '' break when Boolean typeName = typeof true break when Function typeName = typeof () -> # tslint:disable-line no-empty break else typeName = null break return if typeName is null then this.Where((x) -> x instanceof type).Cast() else this.Where((x) -> typeof x is typeName).Cast() ### Sorts the elements of a sequence in ascending order according to a key. ### OrderBy: (keySelector, comparer) -> if (comparer is undefined) comparer = tools.keyComparer(keySelector, false) # tslint:disable-next-line: no-use-before-declare return new OrderedList(tools.cloneDeep(this._elements), comparer) ### Sorts the elements of a sequence in descending order according to a key. ### OrderByDescending: (keySelector, comparer) -> if (comparer is undefined) comparer = tools.keyComparer(keySelector, true) # tslint:disable-next-line: no-use-before-declare return new OrderedList(tools.cloneDeep(this._elements), comparer) ### Performs a subsequent ordering of the elements in a sequence in ascending order according to a key. ### ThenBy: (keySelector) -> return this.OrderBy(keySelector) ### Performs a subsequent ordering of the elements in a sequence in descending order, according to a key. ### ThenByDescending: (keySelector) -> return this.OrderByDescending(keySelector) ### Removes the first occurrence of a specific object from the List<T>. ### Remove: (element) -> return if this.IndexOf(element) isnt -1 then (this.RemoveAt(this.IndexOf(element)); true) else false ### Removes all the elements that match the conditions defined by the specified predicate. ### RemoveAll: (predicate) -> return this.Where(tools.negate(predicate)) ### Removes the element at the specified index of the List<T>. ### RemoveAt: (index) -> this._elements.splice(index, 1) ### Reverses the order of the elements in the entire List<T>. ### Reverse: () -> return new Linq(this._elements.reverse()) ### Projects each element of a sequence into a new form. ### Select: (selector) -> return new Linq(this._elements.map(selector)) ### Projects each element of a sequence to a List<any> and flattens the resulting sequences into one sequence. ### SelectMany: (selector) -> _this = this return this.Aggregate(((ac, _, i) -> ac.AddRange(_this.Select(selector).ElementAt(i).ToArray()) ac ), new Linq()) ### Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type. ### SequenceEqual: (list) -> return this.All((e) -> list.Contains(e)) ### Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence. ### Single: (predicate) -> if (this.Count(predicate) isnt 1) throw new Error('The collection does not contain exactly one element.') else return this.First(predicate) ### Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence. ### SingleOrDefault: (predicate) -> return if this.Count(predicate) then this.Single(predicate) else undefined ### Bypasses a specified number of elements in a sequence and then returns the remaining elements. ### Skip: (amount) -> return new Linq(this._elements.slice(Math.max(0, amount))) ### Omit the last specified number of elements in a sequence and then returns the remaining elements. ### SkipLast: (amount) -> return new Linq(this._elements.slice(0, -Math.max(0, amount))) ### Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements. ### SkipWhile: (predicate) -> _this = this return this.Skip( this.Aggregate((ac) -> return if predicate(_this.ElementAt(ac)) then ++ac else ac , 0) ) ### Computes the sum of the sequence of number values that are obtained by invoking a transform function on each element of the input sequence. ### Sum: (transform) -> return if transform then this.Select(transform).Sum() else this.Aggregate(((ac, v) -> return (ac = tools.calcNum(ac, +v))), 0) ### Returns a specified number of contiguous elements from the start of a sequence. ### Take: (amount) -> return new Linq(this._elements.slice(0, Math.max(0, amount))) ### Returns a specified number of contiguous elements from the end of a sequence. ### TakeLast: (amount) -> return new Linq(this._elements.slice(-Math.max(0, amount))) ### Returns elements from a sequence as long as a specified condition is true. ### TakeWhile: (predicate) -> _this = this return this.Take( this.Aggregate((ac) -> return if predicate(_this.ElementAt(ac)) then ++ac else ac , 0) ) ### Copies the elements of the List<T> to a new array. ### ToArray: () -> return this._elements ### Creates a Dictionary<TKey, TValue> from a List<T> according to a specified key selector function. ### ToDictionary: (key, value) -> _this = this return this.Aggregate((dicc, v, i) -> dicc[_this.Select(key).ElementAt(i).toString()] = if value then _this.Select(value).ElementAt(i) else v dicc.Add({ Key: _this.Select(key).ElementAt(i), Value: if value then _this.Select(value).ElementAt(i) else v }) return dicc , new Linq()) ### Creates a List<T> from an Enumerable.List<T>. ### ToList: () -> return this ### Creates a Lookup<TKey, TElement> from an IEnumerable<T> according to specified key selector and element selector functions. ### ToLookup: (keySelector, elementSelector) -> return this.GroupBy(keySelector, elementSelector) ### Produces the set union of two sequences by using the default equality comparer. ### Union: (list) -> return this.Concat(list).Distinct() ### Filters a sequence of values based on a predicate. ### Where: (predicate) -> return new Linq(this._elements.filter(predicate)) ### Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results. ### Zip: (list, result) -> _this = this return if list.Count() < this.Count() then list.Select((x, y) -> result(_this.ElementAt(y), x)) else this.Select((x, y) -> result(x, list.ElementAt(y))) ### Represents a sorted sequence. The methods of this class are implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its ToDictionary, ToLookup, ToList or ToArray methods ### class OrderedList extends Linq constructor: (elements, @_comparer) -> super(elements) this._elements.sort(@_comparer) ### Performs a subsequent ordering of the elements in a sequence in ascending order according to a key. @override ### ThenBy: (keySelector) -> return new OrderedList( this._elements, tools.composeComparers @_comparer, tools.keyComparer(keySelector, false)) ### Performs a subsequent ordering of the elements in a sequence in descending order, according to a key. @override ### ThenByDescending: (keySelector) -> return new OrderedList( this._elements, tools.composeComparers @_comparer, tools.keyComparer(keySelector, true)) ### Tool method ### tools = { ### Checks if the argument passed is an object ### isObj: (x) -> return !!x && typeof x is 'object' ### Determine if two objects are equal ### equal: (a, b) -> if (a is b) then return true if (typeof a isnt typeof b) then return false if not (a instanceof Object) then return a is b return Object.entries(a).every((_a) => key = _a[0] val = _a[1] return if @isObj(val) then @equal(b[key], val) else b[key] is val) ### Creates a function that negates the result of the predicate ### negate: (pred) -> return () -> args = [] for _i of arguments args[_i] = arguments[_i] return !pred.apply(undefined, args) ### Comparer helpers ### composeComparers: (previousComparer, currentComparer) -> return (a, b) -> return previousComparer(a, b) || currentComparer(a, b) ### Key comparer ### keyComparer: (_keySelector, descending) -> return (a, b) -> sortKeyA = _keySelector(a) sortKeyB = _keySelector(b) if (sortKeyA > sortKeyB) return if !descending then 1 else -1 else if (sortKeyA < sortKeyB) return if !descending then -1 else 1 else return 0 ### Number calculate addition ### calcNum: (num1, num2) -> if (not @isNum num1) or (not @isNum num2) return 0 { mult, place } = @calcMultiple(num1, num2) return Number(((num1 * mult + num2 * mult) / mult).toFixed(place)) ### Number calculate division To be improved ### calcNumDiv: (num1, num2) -> return num1 / num2 ### Check number ### isNum: (args) -> return (typeof args is 'number') and (not isNaN(args)) ### Calculation multiple ### calcMultiple: (num1, num2) -> arrNum1 = num1.toString().split('.') arrNum2 = num2.toString().split('.') sq1 = if arrNum1.length > 1 then arrNum1[1].length else 0 sq2 = if arrNum2.length > 1 then arrNum2[1].length else 0 mult = Math.pow(10, Math.max(sq1, sq2)) place = if sq1 >= sq2 then sq1 else sq2 return { mult, place } ### Clone data ### cloneDeep: (obj) -> # Handle the 3 simple types, and null or undefined return obj if null is obj || "object" isnt typeof obj # Handle Date if obj instanceof Date result = new Date() result.setTime obj.getTime() return result # Handle RegExp if obj instanceof RegExp result = obj return result # Handle Array if obj instanceof Array result = (@cloneDeep o for o in obj) return result # Handle Object if obj instanceof Object result = {} result[k] = @cloneDeep v for k, v of obj when obj.hasOwnProperty k return result throw new Error("Unable to copy param! Its type isn't supported.") } module.exports = Linq
108976
### LINQ to CoffeeScript (Language Integrated Query) ### class Linq ### Defaults the elements of the list ### constructor: (elements) -> elements = [] if not elements this._elements = elements #region Method alias this.add = this.Add this.append = this.Append this.prepend = this.Prepend this.addRange = this.AddRange this.aggregate = this.Aggregate this.all = this.All this.any = this.Any this.average = this.Average this.cast = this.Cast this.clear = this.Clear this.concat = this.Concat this.contains = this.Contains this.count = this.Count this.defaultIfEmpty = this.DefaultIfEmpty this.distinct = this.Distinct this.distinctBy = this.DistinctBy this.elementAt = this.ElementAt this.elementAtOrDefault = this.ElementAtOrDefault this.except = this.Except this.first = this.First this.firstOrDefault = this.FirstOrDefault this.forEach = this.ForEach this.groupBy = this.GroupBy this.groupJoin = this.GroupJoin this.indexOf = this.IndexOf this.insert = this.Insert this.intersect = this.Intersect this.join = this.Join this.last = this.Last this.lastOrDefault = this.LastOrDefault this.max = this.Max this.min = this.Min this.ofType = this.OfType this.orderBy = this.OrderBy this.orderByDescending = this.OrderByDescending this.thenBy = this.ThenBy this.thenByDescending = this.ThenByDescending this.remove = this.Remove this.removeAll = this.RemoveAll this.removeAt = this.RemoveAt this.reverse = this.Reverse this.select = this.Select this.selectMany = this.SelectMany this.sequenceEqual = this.SequenceEqual this.single = this.Single this.singleOrDefault = this.SingleOrDefault this.skip = this.Skip this.skipLast = this.SkipLast this.skipWhile = this.SkipWhile this.sum = this.Sum this.take = this.Take this.takeLast = this.TakeLast this.takeWhile = this.TakeWhile this.toArray = this.ToArray this.toDictionary = this.ToDictionary this.toList = this.ToList this.toLookup = this.ToLookup this.union = this.Union this.where = this.Where this.zip = this.Zip #endregion ### Adds an object to the end of the List<T>. ### Add: (element) -> this._elements.push(element) ### Appends an object to the end of the List<T>. ### Append: (element) -> this.Add(element) ### Add an object to the start of the List<T>. ### Prepend: (element) -> this._elements.unshift(element) ### Adds the elements of the specified collection to the end of the List<T>. ### AddRange: (elements) -> _a (_a = this._elements).push.apply(_a, elements) ### Applies an accumulator function over a sequence. ### Aggregate: (accumulator, initialValue) -> return this._elements.reduce(accumulator, initialValue) ### Determines whether all elements of a sequence satisfy a condition. ### All: (predicate) -> return this._elements.every(predicate) ### Determines whether a sequence contains any elements. ### Any: (predicate) -> return if predicate then this._elements.some(predicate) else this._elements.length > 0 ### Computes the average of a sequence of number values that are obtained by invoking a transform function on each element of the input sequence. ### Average: (transform) -> return tools.calcNumDiv(this.Sum(transform), this.Count()) ### Casts the elements of a sequence to the specified type. ### Cast: () -> return new Linq(this._elements) ### Removes all elements from the List<T>. ### Clear: () -> this._elements.length = 0 ### Concatenates two sequences. ### Concat: (list) -> return new Linq(this._elements.concat(list.ToArray())) ### Determines whether an element is in the List<T>. ### Contains: (element) -> return this.Any((x) -> x is element) ### Returns the number of elements in a sequence. ### Count: (predicate) -> return if predicate then this.Where(predicate).Count() else this._elements.length ### Returns the elements of the specified sequence or the type parameter's default value in a singleton collection if the sequence is empty. ### DefaultIfEmpty: (defaultValue) -> return if this.Count() then this else new Linq([defaultValue]) ### Returns distinct elements from a sequence by using the default equality comparer to compare values. ### Distinct: () -> return this.Where((value, index, iter) -> return ( (if tools.isObj(value) then iter.findIndex((obj) -> tools.equal(obj, value)) else iter.indexOf(value)) is index ) ) ### Returns distinct elements from a sequence according to specified key selector. ### DistinctBy: (keySelector) -> groups = this.GroupBy(keySelector) func = (res, key) -> curr = new Linq(groups).FirstOrDefault((x) -> tools.equal(x.key, key)) res.Add(curr.elements[0]) return res return new Linq(groups).Select((x) -> x.key).ToArray().reduce(func, new Linq()) ### Returns the element at a specified index in a sequence. ### ElementAt: (index) -> if (index < this.Count() && index >= 0) return this._elements[index] else throw new Error('ArgumentOutOfRangeException: index is less than 0 or greater than or equal to the number of elements in source.') ### Returns the element at a specified index in a sequence or a default value if the index is out of range. ### ElementAtOrDefault: (index) -> return if index < this.Count() && index >= 0 then this._elements[index] else undefined ### Produces the set difference of two sequences by using the default equality comparer to compare values. ### Except: (source) -> return this.Where((x) -> !source.Contains(x)) ### Returns the first element of a sequence. ### First: (predicate) -> if this.Count() return if predicate then this.Where(predicate).First() else this._elements[0] else throw new Error( 'InvalidOperationException: The source sequence is empty.') ### Returns the first element of a sequence, or a default value if the sequence contains no elements. ### FirstOrDefault: (predicate) -> return if this.Count(predicate) then this.First(predicate) else undefined ### Performs the specified action on each element of the List<T>. ### ForEach: (action) -> return this._elements.forEach(action) ### Groups the elements of a sequence according to a specified key selector function. ### GroupBy: (grouper, mapper) -> if (mapper is undefined) mapper = (val) -> val initialValue = [] func = (ac, v) -> key = <KEY> existingGroup = new Linq(ac).FirstOrDefault((x) -> tools.equal(x.key, key)) mappedValue = mapper(v) if existingGroup existingGroup.elements.push(mappedValue) existingGroup.count++ else existingMap = { key: key, count: 1, elements: [mappedValue] } ac.push(existingMap) return ac return this.Aggregate(func, initialValue) ### Correlates the elements of two sequences based on equality of keys and groups the results. The default equality comparer is used to compare keys. ### GroupJoin: (list, key1, key2, result) -> return this.Select((x) -> return result x, list.Where((z) -> key1(x) is key2(z)) ) ### Returns the index of the first occurence of an element in the List. ### IndexOf: (element) -> return this._elements.indexOf(element) ### Inserts an element into the List<T> at the specified index. ### Insert: (index, element) -> if (index < 0 || index > this._elements.length) throw new Error('Index is out of range.') this._elements.splice(index, 0, element) ### Produces the set intersection of two sequences by using the default equality comparer to compare values. ### Intersect: (source) -> return this.Where((x) -> source.Contains(x)) ### Correlates the elements of two sequences based on matching keys. The default equality comparer is used to compare keys. ### Join: (list, key1, key2, result) -> selectmany = (selector) => return this.Aggregate(((ac, _, i) => ac.AddRange(this.Select(selector).ElementAt(i).ToArray()) ac ), new Linq()) return selectmany((x) -> return list .Where((y) -> key2(y) is key1(x)) .Select((z) -> result(x, z)) ) ### Returns the last element of a sequence. ### Last: (predicate) -> if this.Count() return if predicate then this.Where(predicate).Last() else this._elements[this.Count() - 1] else throw Error('InvalidOperationException: The source sequence is empty.') ### Returns the last element of a sequence, or a default value if the sequence contains no elements. ### LastOrDefault: (predicate) -> return if this.Count(predicate) then this.Last(predicate) else undefined ### Returns the maximum value in a generic sequence. ### Max: (selector) -> id = (x) -> x return Math.max.apply(Math, this._elements.map(selector || id)) ### Returns the minimum value in a generic sequence. ### Min: (selector) -> id = (x) -> x return Math.min.apply(Math, this._elements.map(selector || id)) ### Filters the elements of a sequence based on a specified type. ### OfType: (type) -> typeName switch (type) when Number typeName = typeof 0 break when String typeName = typeof '' break when Boolean typeName = typeof true break when Function typeName = typeof () -> # tslint:disable-line no-empty break else typeName = null break return if typeName is null then this.Where((x) -> x instanceof type).Cast() else this.Where((x) -> typeof x is typeName).Cast() ### Sorts the elements of a sequence in ascending order according to a key. ### OrderBy: (keySelector, comparer) -> if (comparer is undefined) comparer = tools.keyComparer(keySelector, false) # tslint:disable-next-line: no-use-before-declare return new OrderedList(tools.cloneDeep(this._elements), comparer) ### Sorts the elements of a sequence in descending order according to a key. ### OrderByDescending: (keySelector, comparer) -> if (comparer is undefined) comparer = tools.keyComparer(keySelector, true) # tslint:disable-next-line: no-use-before-declare return new OrderedList(tools.cloneDeep(this._elements), comparer) ### Performs a subsequent ordering of the elements in a sequence in ascending order according to a key. ### ThenBy: (keySelector) -> return this.OrderBy(keySelector) ### Performs a subsequent ordering of the elements in a sequence in descending order, according to a key. ### ThenByDescending: (keySelector) -> return this.OrderByDescending(keySelector) ### Removes the first occurrence of a specific object from the List<T>. ### Remove: (element) -> return if this.IndexOf(element) isnt -1 then (this.RemoveAt(this.IndexOf(element)); true) else false ### Removes all the elements that match the conditions defined by the specified predicate. ### RemoveAll: (predicate) -> return this.Where(tools.negate(predicate)) ### Removes the element at the specified index of the List<T>. ### RemoveAt: (index) -> this._elements.splice(index, 1) ### Reverses the order of the elements in the entire List<T>. ### Reverse: () -> return new Linq(this._elements.reverse()) ### Projects each element of a sequence into a new form. ### Select: (selector) -> return new Linq(this._elements.map(selector)) ### Projects each element of a sequence to a List<any> and flattens the resulting sequences into one sequence. ### SelectMany: (selector) -> _this = this return this.Aggregate(((ac, _, i) -> ac.AddRange(_this.Select(selector).ElementAt(i).ToArray()) ac ), new Linq()) ### Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type. ### SequenceEqual: (list) -> return this.All((e) -> list.Contains(e)) ### Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence. ### Single: (predicate) -> if (this.Count(predicate) isnt 1) throw new Error('The collection does not contain exactly one element.') else return this.First(predicate) ### Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence. ### SingleOrDefault: (predicate) -> return if this.Count(predicate) then this.Single(predicate) else undefined ### Bypasses a specified number of elements in a sequence and then returns the remaining elements. ### Skip: (amount) -> return new Linq(this._elements.slice(Math.max(0, amount))) ### Omit the last specified number of elements in a sequence and then returns the remaining elements. ### SkipLast: (amount) -> return new Linq(this._elements.slice(0, -Math.max(0, amount))) ### Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements. ### SkipWhile: (predicate) -> _this = this return this.Skip( this.Aggregate((ac) -> return if predicate(_this.ElementAt(ac)) then ++ac else ac , 0) ) ### Computes the sum of the sequence of number values that are obtained by invoking a transform function on each element of the input sequence. ### Sum: (transform) -> return if transform then this.Select(transform).Sum() else this.Aggregate(((ac, v) -> return (ac = tools.calcNum(ac, +v))), 0) ### Returns a specified number of contiguous elements from the start of a sequence. ### Take: (amount) -> return new Linq(this._elements.slice(0, Math.max(0, amount))) ### Returns a specified number of contiguous elements from the end of a sequence. ### TakeLast: (amount) -> return new Linq(this._elements.slice(-Math.max(0, amount))) ### Returns elements from a sequence as long as a specified condition is true. ### TakeWhile: (predicate) -> _this = this return this.Take( this.Aggregate((ac) -> return if predicate(_this.ElementAt(ac)) then ++ac else ac , 0) ) ### Copies the elements of the List<T> to a new array. ### ToArray: () -> return this._elements ### Creates a Dictionary<TKey, TValue> from a List<T> according to a specified key selector function. ### ToDictionary: (key, value) -> _this = this return this.Aggregate((dicc, v, i) -> dicc[_this.Select(key).ElementAt(i).toString()] = if value then _this.Select(value).ElementAt(i) else v dicc.Add({ Key: _this.Select(key).ElementAt(i), Value: if value then _this.Select(value).ElementAt(i) else v }) return dicc , new Linq()) ### Creates a List<T> from an Enumerable.List<T>. ### ToList: () -> return this ### Creates a Lookup<TKey, TElement> from an IEnumerable<T> according to specified key selector and element selector functions. ### ToLookup: (keySelector, elementSelector) -> return this.GroupBy(keySelector, elementSelector) ### Produces the set union of two sequences by using the default equality comparer. ### Union: (list) -> return this.Concat(list).Distinct() ### Filters a sequence of values based on a predicate. ### Where: (predicate) -> return new Linq(this._elements.filter(predicate)) ### Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results. ### Zip: (list, result) -> _this = this return if list.Count() < this.Count() then list.Select((x, y) -> result(_this.ElementAt(y), x)) else this.Select((x, y) -> result(x, list.ElementAt(y))) ### Represents a sorted sequence. The methods of this class are implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its ToDictionary, ToLookup, ToList or ToArray methods ### class OrderedList extends Linq constructor: (elements, @_comparer) -> super(elements) this._elements.sort(@_comparer) ### Performs a subsequent ordering of the elements in a sequence in ascending order according to a key. @override ### ThenBy: (keySelector) -> return new OrderedList( this._elements, tools.composeComparers @_comparer, tools.keyComparer(keySelector, false)) ### Performs a subsequent ordering of the elements in a sequence in descending order, according to a key. @override ### ThenByDescending: (keySelector) -> return new OrderedList( this._elements, tools.composeComparers @_comparer, tools.keyComparer(keySelector, true)) ### Tool method ### tools = { ### Checks if the argument passed is an object ### isObj: (x) -> return !!x && typeof x is 'object' ### Determine if two objects are equal ### equal: (a, b) -> if (a is b) then return true if (typeof a isnt typeof b) then return false if not (a instanceof Object) then return a is b return Object.entries(a).every((_a) => key = _a[0] val = _a[1] return if @isObj(val) then @equal(b[key], val) else b[key] is val) ### Creates a function that negates the result of the predicate ### negate: (pred) -> return () -> args = [] for _i of arguments args[_i] = arguments[_i] return !pred.apply(undefined, args) ### Comparer helpers ### composeComparers: (previousComparer, currentComparer) -> return (a, b) -> return previousComparer(a, b) || currentComparer(a, b) ### Key comparer ### keyComparer: (_keySelector, descending) -> return (a, b) -> sortKeyA = _keySelector(a) sortKeyB = _keySelector(b) if (sortKeyA > sortKeyB) return if !descending then 1 else -1 else if (sortKeyA < sortKeyB) return if !descending then -1 else 1 else return 0 ### Number calculate addition ### calcNum: (num1, num2) -> if (not @isNum num1) or (not @isNum num2) return 0 { mult, place } = @calcMultiple(num1, num2) return Number(((num1 * mult + num2 * mult) / mult).toFixed(place)) ### Number calculate division To be improved ### calcNumDiv: (num1, num2) -> return num1 / num2 ### Check number ### isNum: (args) -> return (typeof args is 'number') and (not isNaN(args)) ### Calculation multiple ### calcMultiple: (num1, num2) -> arrNum1 = num1.toString().split('.') arrNum2 = num2.toString().split('.') sq1 = if arrNum1.length > 1 then arrNum1[1].length else 0 sq2 = if arrNum2.length > 1 then arrNum2[1].length else 0 mult = Math.pow(10, Math.max(sq1, sq2)) place = if sq1 >= sq2 then sq1 else sq2 return { mult, place } ### Clone data ### cloneDeep: (obj) -> # Handle the 3 simple types, and null or undefined return obj if null is obj || "object" isnt typeof obj # Handle Date if obj instanceof Date result = new Date() result.setTime obj.getTime() return result # Handle RegExp if obj instanceof RegExp result = obj return result # Handle Array if obj instanceof Array result = (@cloneDeep o for o in obj) return result # Handle Object if obj instanceof Object result = {} result[k] = @cloneDeep v for k, v of obj when obj.hasOwnProperty k return result throw new Error("Unable to copy param! Its type isn't supported.") } module.exports = Linq
true
### LINQ to CoffeeScript (Language Integrated Query) ### class Linq ### Defaults the elements of the list ### constructor: (elements) -> elements = [] if not elements this._elements = elements #region Method alias this.add = this.Add this.append = this.Append this.prepend = this.Prepend this.addRange = this.AddRange this.aggregate = this.Aggregate this.all = this.All this.any = this.Any this.average = this.Average this.cast = this.Cast this.clear = this.Clear this.concat = this.Concat this.contains = this.Contains this.count = this.Count this.defaultIfEmpty = this.DefaultIfEmpty this.distinct = this.Distinct this.distinctBy = this.DistinctBy this.elementAt = this.ElementAt this.elementAtOrDefault = this.ElementAtOrDefault this.except = this.Except this.first = this.First this.firstOrDefault = this.FirstOrDefault this.forEach = this.ForEach this.groupBy = this.GroupBy this.groupJoin = this.GroupJoin this.indexOf = this.IndexOf this.insert = this.Insert this.intersect = this.Intersect this.join = this.Join this.last = this.Last this.lastOrDefault = this.LastOrDefault this.max = this.Max this.min = this.Min this.ofType = this.OfType this.orderBy = this.OrderBy this.orderByDescending = this.OrderByDescending this.thenBy = this.ThenBy this.thenByDescending = this.ThenByDescending this.remove = this.Remove this.removeAll = this.RemoveAll this.removeAt = this.RemoveAt this.reverse = this.Reverse this.select = this.Select this.selectMany = this.SelectMany this.sequenceEqual = this.SequenceEqual this.single = this.Single this.singleOrDefault = this.SingleOrDefault this.skip = this.Skip this.skipLast = this.SkipLast this.skipWhile = this.SkipWhile this.sum = this.Sum this.take = this.Take this.takeLast = this.TakeLast this.takeWhile = this.TakeWhile this.toArray = this.ToArray this.toDictionary = this.ToDictionary this.toList = this.ToList this.toLookup = this.ToLookup this.union = this.Union this.where = this.Where this.zip = this.Zip #endregion ### Adds an object to the end of the List<T>. ### Add: (element) -> this._elements.push(element) ### Appends an object to the end of the List<T>. ### Append: (element) -> this.Add(element) ### Add an object to the start of the List<T>. ### Prepend: (element) -> this._elements.unshift(element) ### Adds the elements of the specified collection to the end of the List<T>. ### AddRange: (elements) -> _a (_a = this._elements).push.apply(_a, elements) ### Applies an accumulator function over a sequence. ### Aggregate: (accumulator, initialValue) -> return this._elements.reduce(accumulator, initialValue) ### Determines whether all elements of a sequence satisfy a condition. ### All: (predicate) -> return this._elements.every(predicate) ### Determines whether a sequence contains any elements. ### Any: (predicate) -> return if predicate then this._elements.some(predicate) else this._elements.length > 0 ### Computes the average of a sequence of number values that are obtained by invoking a transform function on each element of the input sequence. ### Average: (transform) -> return tools.calcNumDiv(this.Sum(transform), this.Count()) ### Casts the elements of a sequence to the specified type. ### Cast: () -> return new Linq(this._elements) ### Removes all elements from the List<T>. ### Clear: () -> this._elements.length = 0 ### Concatenates two sequences. ### Concat: (list) -> return new Linq(this._elements.concat(list.ToArray())) ### Determines whether an element is in the List<T>. ### Contains: (element) -> return this.Any((x) -> x is element) ### Returns the number of elements in a sequence. ### Count: (predicate) -> return if predicate then this.Where(predicate).Count() else this._elements.length ### Returns the elements of the specified sequence or the type parameter's default value in a singleton collection if the sequence is empty. ### DefaultIfEmpty: (defaultValue) -> return if this.Count() then this else new Linq([defaultValue]) ### Returns distinct elements from a sequence by using the default equality comparer to compare values. ### Distinct: () -> return this.Where((value, index, iter) -> return ( (if tools.isObj(value) then iter.findIndex((obj) -> tools.equal(obj, value)) else iter.indexOf(value)) is index ) ) ### Returns distinct elements from a sequence according to specified key selector. ### DistinctBy: (keySelector) -> groups = this.GroupBy(keySelector) func = (res, key) -> curr = new Linq(groups).FirstOrDefault((x) -> tools.equal(x.key, key)) res.Add(curr.elements[0]) return res return new Linq(groups).Select((x) -> x.key).ToArray().reduce(func, new Linq()) ### Returns the element at a specified index in a sequence. ### ElementAt: (index) -> if (index < this.Count() && index >= 0) return this._elements[index] else throw new Error('ArgumentOutOfRangeException: index is less than 0 or greater than or equal to the number of elements in source.') ### Returns the element at a specified index in a sequence or a default value if the index is out of range. ### ElementAtOrDefault: (index) -> return if index < this.Count() && index >= 0 then this._elements[index] else undefined ### Produces the set difference of two sequences by using the default equality comparer to compare values. ### Except: (source) -> return this.Where((x) -> !source.Contains(x)) ### Returns the first element of a sequence. ### First: (predicate) -> if this.Count() return if predicate then this.Where(predicate).First() else this._elements[0] else throw new Error( 'InvalidOperationException: The source sequence is empty.') ### Returns the first element of a sequence, or a default value if the sequence contains no elements. ### FirstOrDefault: (predicate) -> return if this.Count(predicate) then this.First(predicate) else undefined ### Performs the specified action on each element of the List<T>. ### ForEach: (action) -> return this._elements.forEach(action) ### Groups the elements of a sequence according to a specified key selector function. ### GroupBy: (grouper, mapper) -> if (mapper is undefined) mapper = (val) -> val initialValue = [] func = (ac, v) -> key = PI:KEY:<KEY>END_PI existingGroup = new Linq(ac).FirstOrDefault((x) -> tools.equal(x.key, key)) mappedValue = mapper(v) if existingGroup existingGroup.elements.push(mappedValue) existingGroup.count++ else existingMap = { key: key, count: 1, elements: [mappedValue] } ac.push(existingMap) return ac return this.Aggregate(func, initialValue) ### Correlates the elements of two sequences based on equality of keys and groups the results. The default equality comparer is used to compare keys. ### GroupJoin: (list, key1, key2, result) -> return this.Select((x) -> return result x, list.Where((z) -> key1(x) is key2(z)) ) ### Returns the index of the first occurence of an element in the List. ### IndexOf: (element) -> return this._elements.indexOf(element) ### Inserts an element into the List<T> at the specified index. ### Insert: (index, element) -> if (index < 0 || index > this._elements.length) throw new Error('Index is out of range.') this._elements.splice(index, 0, element) ### Produces the set intersection of two sequences by using the default equality comparer to compare values. ### Intersect: (source) -> return this.Where((x) -> source.Contains(x)) ### Correlates the elements of two sequences based on matching keys. The default equality comparer is used to compare keys. ### Join: (list, key1, key2, result) -> selectmany = (selector) => return this.Aggregate(((ac, _, i) => ac.AddRange(this.Select(selector).ElementAt(i).ToArray()) ac ), new Linq()) return selectmany((x) -> return list .Where((y) -> key2(y) is key1(x)) .Select((z) -> result(x, z)) ) ### Returns the last element of a sequence. ### Last: (predicate) -> if this.Count() return if predicate then this.Where(predicate).Last() else this._elements[this.Count() - 1] else throw Error('InvalidOperationException: The source sequence is empty.') ### Returns the last element of a sequence, or a default value if the sequence contains no elements. ### LastOrDefault: (predicate) -> return if this.Count(predicate) then this.Last(predicate) else undefined ### Returns the maximum value in a generic sequence. ### Max: (selector) -> id = (x) -> x return Math.max.apply(Math, this._elements.map(selector || id)) ### Returns the minimum value in a generic sequence. ### Min: (selector) -> id = (x) -> x return Math.min.apply(Math, this._elements.map(selector || id)) ### Filters the elements of a sequence based on a specified type. ### OfType: (type) -> typeName switch (type) when Number typeName = typeof 0 break when String typeName = typeof '' break when Boolean typeName = typeof true break when Function typeName = typeof () -> # tslint:disable-line no-empty break else typeName = null break return if typeName is null then this.Where((x) -> x instanceof type).Cast() else this.Where((x) -> typeof x is typeName).Cast() ### Sorts the elements of a sequence in ascending order according to a key. ### OrderBy: (keySelector, comparer) -> if (comparer is undefined) comparer = tools.keyComparer(keySelector, false) # tslint:disable-next-line: no-use-before-declare return new OrderedList(tools.cloneDeep(this._elements), comparer) ### Sorts the elements of a sequence in descending order according to a key. ### OrderByDescending: (keySelector, comparer) -> if (comparer is undefined) comparer = tools.keyComparer(keySelector, true) # tslint:disable-next-line: no-use-before-declare return new OrderedList(tools.cloneDeep(this._elements), comparer) ### Performs a subsequent ordering of the elements in a sequence in ascending order according to a key. ### ThenBy: (keySelector) -> return this.OrderBy(keySelector) ### Performs a subsequent ordering of the elements in a sequence in descending order, according to a key. ### ThenByDescending: (keySelector) -> return this.OrderByDescending(keySelector) ### Removes the first occurrence of a specific object from the List<T>. ### Remove: (element) -> return if this.IndexOf(element) isnt -1 then (this.RemoveAt(this.IndexOf(element)); true) else false ### Removes all the elements that match the conditions defined by the specified predicate. ### RemoveAll: (predicate) -> return this.Where(tools.negate(predicate)) ### Removes the element at the specified index of the List<T>. ### RemoveAt: (index) -> this._elements.splice(index, 1) ### Reverses the order of the elements in the entire List<T>. ### Reverse: () -> return new Linq(this._elements.reverse()) ### Projects each element of a sequence into a new form. ### Select: (selector) -> return new Linq(this._elements.map(selector)) ### Projects each element of a sequence to a List<any> and flattens the resulting sequences into one sequence. ### SelectMany: (selector) -> _this = this return this.Aggregate(((ac, _, i) -> ac.AddRange(_this.Select(selector).ElementAt(i).ToArray()) ac ), new Linq()) ### Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type. ### SequenceEqual: (list) -> return this.All((e) -> list.Contains(e)) ### Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence. ### Single: (predicate) -> if (this.Count(predicate) isnt 1) throw new Error('The collection does not contain exactly one element.') else return this.First(predicate) ### Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence. ### SingleOrDefault: (predicate) -> return if this.Count(predicate) then this.Single(predicate) else undefined ### Bypasses a specified number of elements in a sequence and then returns the remaining elements. ### Skip: (amount) -> return new Linq(this._elements.slice(Math.max(0, amount))) ### Omit the last specified number of elements in a sequence and then returns the remaining elements. ### SkipLast: (amount) -> return new Linq(this._elements.slice(0, -Math.max(0, amount))) ### Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements. ### SkipWhile: (predicate) -> _this = this return this.Skip( this.Aggregate((ac) -> return if predicate(_this.ElementAt(ac)) then ++ac else ac , 0) ) ### Computes the sum of the sequence of number values that are obtained by invoking a transform function on each element of the input sequence. ### Sum: (transform) -> return if transform then this.Select(transform).Sum() else this.Aggregate(((ac, v) -> return (ac = tools.calcNum(ac, +v))), 0) ### Returns a specified number of contiguous elements from the start of a sequence. ### Take: (amount) -> return new Linq(this._elements.slice(0, Math.max(0, amount))) ### Returns a specified number of contiguous elements from the end of a sequence. ### TakeLast: (amount) -> return new Linq(this._elements.slice(-Math.max(0, amount))) ### Returns elements from a sequence as long as a specified condition is true. ### TakeWhile: (predicate) -> _this = this return this.Take( this.Aggregate((ac) -> return if predicate(_this.ElementAt(ac)) then ++ac else ac , 0) ) ### Copies the elements of the List<T> to a new array. ### ToArray: () -> return this._elements ### Creates a Dictionary<TKey, TValue> from a List<T> according to a specified key selector function. ### ToDictionary: (key, value) -> _this = this return this.Aggregate((dicc, v, i) -> dicc[_this.Select(key).ElementAt(i).toString()] = if value then _this.Select(value).ElementAt(i) else v dicc.Add({ Key: _this.Select(key).ElementAt(i), Value: if value then _this.Select(value).ElementAt(i) else v }) return dicc , new Linq()) ### Creates a List<T> from an Enumerable.List<T>. ### ToList: () -> return this ### Creates a Lookup<TKey, TElement> from an IEnumerable<T> according to specified key selector and element selector functions. ### ToLookup: (keySelector, elementSelector) -> return this.GroupBy(keySelector, elementSelector) ### Produces the set union of two sequences by using the default equality comparer. ### Union: (list) -> return this.Concat(list).Distinct() ### Filters a sequence of values based on a predicate. ### Where: (predicate) -> return new Linq(this._elements.filter(predicate)) ### Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results. ### Zip: (list, result) -> _this = this return if list.Count() < this.Count() then list.Select((x, y) -> result(_this.ElementAt(y), x)) else this.Select((x, y) -> result(x, list.ElementAt(y))) ### Represents a sorted sequence. The methods of this class are implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its ToDictionary, ToLookup, ToList or ToArray methods ### class OrderedList extends Linq constructor: (elements, @_comparer) -> super(elements) this._elements.sort(@_comparer) ### Performs a subsequent ordering of the elements in a sequence in ascending order according to a key. @override ### ThenBy: (keySelector) -> return new OrderedList( this._elements, tools.composeComparers @_comparer, tools.keyComparer(keySelector, false)) ### Performs a subsequent ordering of the elements in a sequence in descending order, according to a key. @override ### ThenByDescending: (keySelector) -> return new OrderedList( this._elements, tools.composeComparers @_comparer, tools.keyComparer(keySelector, true)) ### Tool method ### tools = { ### Checks if the argument passed is an object ### isObj: (x) -> return !!x && typeof x is 'object' ### Determine if two objects are equal ### equal: (a, b) -> if (a is b) then return true if (typeof a isnt typeof b) then return false if not (a instanceof Object) then return a is b return Object.entries(a).every((_a) => key = _a[0] val = _a[1] return if @isObj(val) then @equal(b[key], val) else b[key] is val) ### Creates a function that negates the result of the predicate ### negate: (pred) -> return () -> args = [] for _i of arguments args[_i] = arguments[_i] return !pred.apply(undefined, args) ### Comparer helpers ### composeComparers: (previousComparer, currentComparer) -> return (a, b) -> return previousComparer(a, b) || currentComparer(a, b) ### Key comparer ### keyComparer: (_keySelector, descending) -> return (a, b) -> sortKeyA = _keySelector(a) sortKeyB = _keySelector(b) if (sortKeyA > sortKeyB) return if !descending then 1 else -1 else if (sortKeyA < sortKeyB) return if !descending then -1 else 1 else return 0 ### Number calculate addition ### calcNum: (num1, num2) -> if (not @isNum num1) or (not @isNum num2) return 0 { mult, place } = @calcMultiple(num1, num2) return Number(((num1 * mult + num2 * mult) / mult).toFixed(place)) ### Number calculate division To be improved ### calcNumDiv: (num1, num2) -> return num1 / num2 ### Check number ### isNum: (args) -> return (typeof args is 'number') and (not isNaN(args)) ### Calculation multiple ### calcMultiple: (num1, num2) -> arrNum1 = num1.toString().split('.') arrNum2 = num2.toString().split('.') sq1 = if arrNum1.length > 1 then arrNum1[1].length else 0 sq2 = if arrNum2.length > 1 then arrNum2[1].length else 0 mult = Math.pow(10, Math.max(sq1, sq2)) place = if sq1 >= sq2 then sq1 else sq2 return { mult, place } ### Clone data ### cloneDeep: (obj) -> # Handle the 3 simple types, and null or undefined return obj if null is obj || "object" isnt typeof obj # Handle Date if obj instanceof Date result = new Date() result.setTime obj.getTime() return result # Handle RegExp if obj instanceof RegExp result = obj return result # Handle Array if obj instanceof Array result = (@cloneDeep o for o in obj) return result # Handle Object if obj instanceof Object result = {} result[k] = @cloneDeep v for k, v of obj when obj.hasOwnProperty k return result throw new Error("Unable to copy param! Its type isn't supported.") } module.exports = Linq
[ { "context": "# Copyright © 2013 All rights reserved\n# Author: nhim175@gmail.com\n\nModule = require '../module.coffee'\nLogger = req", "end": 66, "score": 0.9999107718467712, "start": 49, "tag": "EMAIL", "value": "nhim175@gmail.com" } ]
src/lib/gui/clock.coffee
nhim175/scorpionsmasher
0
# Copyright © 2013 All rights reserved # Author: nhim175@gmail.com Module = require '../module.coffee' Logger = require '../../mixins/logger.coffee' class GUIClock extends Module @include Logger logPrefix: 'GUIClock' seconds: 20 constructor: (game) -> @game = game @me = @game.add.group() @time = new Phaser.BitmapText @game, 0, 10, '8bit_wonder', '' + @getTime(), 40 @me.add @time @me.x = @game.world.centerX @me.y = 50 @timer = @game.time.create(false) @timer.loop 1000, @updateTime, @ @timer.start() updateTime: => unless @game.isOver @seconds-- $(@).trigger 'Time.Out' if @seconds < 0 getTime: -> minutes = Math.floor @seconds/60 seconds = @seconds%60 if minutes < 10 then minutes = '0' + minutes if seconds < 10 then seconds = '0' + seconds minutes + ':' + seconds getSeconds: -> @seconds reset: -> @seconds = 30 update: -> if not @game.isOver @time.text = @getTime() @me.x = @game.world.centerX - @time.width/2 else @me.visible = false module.exports = GUIClock
113724
# Copyright © 2013 All rights reserved # Author: <EMAIL> Module = require '../module.coffee' Logger = require '../../mixins/logger.coffee' class GUIClock extends Module @include Logger logPrefix: 'GUIClock' seconds: 20 constructor: (game) -> @game = game @me = @game.add.group() @time = new Phaser.BitmapText @game, 0, 10, '8bit_wonder', '' + @getTime(), 40 @me.add @time @me.x = @game.world.centerX @me.y = 50 @timer = @game.time.create(false) @timer.loop 1000, @updateTime, @ @timer.start() updateTime: => unless @game.isOver @seconds-- $(@).trigger 'Time.Out' if @seconds < 0 getTime: -> minutes = Math.floor @seconds/60 seconds = @seconds%60 if minutes < 10 then minutes = '0' + minutes if seconds < 10 then seconds = '0' + seconds minutes + ':' + seconds getSeconds: -> @seconds reset: -> @seconds = 30 update: -> if not @game.isOver @time.text = @getTime() @me.x = @game.world.centerX - @time.width/2 else @me.visible = false module.exports = GUIClock
true
# Copyright © 2013 All rights reserved # Author: PI:EMAIL:<EMAIL>END_PI Module = require '../module.coffee' Logger = require '../../mixins/logger.coffee' class GUIClock extends Module @include Logger logPrefix: 'GUIClock' seconds: 20 constructor: (game) -> @game = game @me = @game.add.group() @time = new Phaser.BitmapText @game, 0, 10, '8bit_wonder', '' + @getTime(), 40 @me.add @time @me.x = @game.world.centerX @me.y = 50 @timer = @game.time.create(false) @timer.loop 1000, @updateTime, @ @timer.start() updateTime: => unless @game.isOver @seconds-- $(@).trigger 'Time.Out' if @seconds < 0 getTime: -> minutes = Math.floor @seconds/60 seconds = @seconds%60 if minutes < 10 then minutes = '0' + minutes if seconds < 10 then seconds = '0' + seconds minutes + ':' + seconds getSeconds: -> @seconds reset: -> @seconds = 30 update: -> if not @game.isOver @time.text = @getTime() @me.x = @game.world.centerX - @time.width/2 else @me.visible = false module.exports = GUIClock
[ { "context": " 0\n )\n $scope.pieData.push {key: gettextCatalog.getString(\"Others\"), y: $scope.top.all - topSum}\n", "end": 3976, "score": 0.6485809683799744, "start": 3962, "tag": "KEY", "value": "gettextCatalog" }, { "context": "\n $scope.pieData.push {key: gettextCatalog.getString(\"Others\"), y: $scope.top.all - topSum}\n\n $scop", "end": 3986, "score": 0.708357036113739, "start": 3977, "tag": "KEY", "value": "getString" } ]
packages/custom/transparency/coffee/public/controllers/topEntriesController.coffee
AnotherCodeArtist/medien-transparenz.at
3
'use strict' app = angular.module 'mean.transparency' app.controller 'TopEntriesCtrl', ['$scope', 'TPAService', '$q', '$state','gettextCatalog','$rootScope', 'DTOptionsBuilder', 'DTColumnDefBuilder', 'DTColumnBuilder','$uibModal','$timeout' ($scope, TPAService, $q, $state, gettextCatalog, $rootScope, DTOptionsBuilder, DTColumnDefBuilder,DTColumnBuilder, $uibModal, $timeout) -> tc = this dataPromise = $q.defer() $scope.td = {} $scope.td.dtInstance = {} params = {} stateName = "topState" fieldsToStore = ['slider','periods','orgTypes','typesText','rank','orgType', 'selectedFederalState', 'includeGroupings', 'selectedOrgCategories'] $scope.periods = [] $scope.slider = from: 0 to: 0 options: step:5 floor:0 onEnd: -> change(1,2) translate: (value) -> $scope.periods.map((p) -> "#{p.year}/Q#{p.quarter}")[value/5] $scope.showSettings = false $scope.ranks = [3, 5, 10, 15, 20] $scope.rank = 10 $scope.pieData = [] window.scrollTo 0, 0 $scope.getFrom = -> if $scope.periods && $scope.periods.length > 0 "Q#{$scope.periods[$scope.slider.from/5].quarter}/#{$scope.periods[$scope.slider.from/5].year}" else "" $scope.getTo = -> if $scope.periods && $scope.periods.length > 0 "Q#{$scope.periods[$scope.slider.to/5].quarter}/#{$scope.periods[$scope.slider.to/5].year}" else "" $scope.selectedTypes = -> $scope.typesText.filter((t) -> t.checked).map (t) -> t.type $scope.selectedOrgType = -> if $scope.orgType is "org" then "Payers" else "Beneficiaries" # register watches to update chart when changes occur registerWatches = -> $scope.$watch('typesText', change, true) $scope.$watch('orgType', change, true) $scope.$watch('rank', change, true) $scope.$watch('selectedFederalState', change, true) $scope.$watch('includeGroupings', change, true) $scope.$watch('selectedOrgCategories', change, true) #construct the query parameters parameters = -> params = {} params.from = $scope.periods[$scope.slider.from/5].period params.to =$scope.periods[$scope.slider.to/5].period params.federalState = $scope.selectedFederalState.iso if $scope.selectedFederalState params.groupings = $scope.includeGroupings if $scope.includeGroupings types = (v.type for v in $scope.typesText when v.checked) (params.pType = types) if types.length > 0 params.x = $scope.rank params.orgType = $scope.orgType params.orgCategories = $scope.selectedOrgCategories params $scope.total = -> if $scope.top then $scope.top.all.toLocaleString() else "0" $scope.IntroOptions = null; $scope.selectedOrgCategories = []; $scope.goto = (l)-> $anchorScroll(l) $scope.showSettingsDialog = -> parent = $scope $uibModal.open( templateUrl: 'transparency/views/topSettingsDialog.html' scope: $scope size: 'lg' controller: ($scope, $uibModalInstance) -> $scope.close = -> $scope.$parent.orgType = $scope.orgType $scope.$parent.selectedOrgCategories = $scope.selectedOrgCategories $uibModalInstance.close() current = $scope.slider.options.draggableRangeOnly $timeout (-> $scope.slider.options.draggableRangeOnly = !current), 100 $timeout (-> $scope.slider.options.draggableRangeOnly = current), 120 ) buildPieModel = -> $scope.pieData = [] $scope.pieData.push {key: entry.organisation, y: entry.total, isGrouping: entry.isGrouping} for entry in $scope.top.top topSum = $scope.top.top.reduce( (sum, entry) -> sum + entry.total 0 ) $scope.pieData.push {key: gettextCatalog.getString("Others"), y: $scope.top.all - topSum} $scope.toolTipContentFunction = (e) -> link = if e.index < $scope.rank then '<br/><i class="fa fa-line-chart" aria-hidden="true"></i> '+gettextCatalog.getString("Click for Details") else "" numberOptions = {style:'currency',currency:'EUR'} """<div class='chartToolTip'> <h3>#{e.data.key}</h3> <p>#{e.data.y.toLocaleString(gettextCatalog.getCurrentLanguage(),numberOptions)} (#{(e.data.y/$scope.top.all *100).toFixed(2)}%)#{link}</p> </div>""" #fetch data from server and update the chart update = -> TPAService.top(parameters()) .then((res) -> init = true $scope.top = res.data dataPromise.resolve() buildPieModel() ) change = (oldValue, newValue) -> if (oldValue isnt newValue) dataPromise = $q.defer() $scope.td.dtInstance.reloadData() update() # Method for setting the intro-options (e.g. after translations) setIntroOptions = -> $scope.IntroOptions = steps: [ { element: document.querySelector('#topSettings') intro: gettextCatalog.getString 'It is possible to customize the pie chart. To do so, use the settings.' } { element: document.querySelector('#topSlider') intro: gettextCatalog.getString 'Move the sliders to define a range.' }, { element: document.querySelector('#fixSliderRange') intro: gettextCatalog.getString 'Fix slider range. With that it is possible to keep the range constant.' }, { element: document.querySelector('#grouping') intro: gettextCatalog.getString 'With groupings enabled single transfers will be taken together (e.g. to show umbrella organisations)' }, { element: document.querySelector('#orgTypesSelection') intro: gettextCatalog.getString 'It is possible to narrow down the results to specific organisation types' }, { element: document.querySelector('#spenderRecipient') intro: gettextCatalog.getString 'Display top spender or top recipient' }, { element: document.querySelector('#paymentTypes') intro: gettextCatalog.getString 'Transfers are divided in different payment types. Select the types to display.' }, { element: document.querySelector('#fedStateSelection') intro: gettextCatalog.getString 'It is possible to show the chart for a specific federal state.' }, { element: document.querySelector('#rank') intro: gettextCatalog.getString 'Select the numbers of elements in the pie chart' } ] showStepNumbers: false exitOnOverlayClick: true exitOnEsc: true nextLabel: gettextCatalog.getString 'Next info' prevLabel: gettextCatalog.getString 'Previous info' skipLabel: gettextCatalog.getString 'Skip info' doneLabel: gettextCatalog.getString 'End tour' initState = -> $scope.orgTypes = [ {name: gettextCatalog.getString('Spender'), value: 'org'}, {name: gettextCatalog.getString('Recipient'), value: 'media'} ] $scope.orgCategories = [] orgTypePromise = TPAService.organisationTypes() .then (res) -> for orgTypeObject in res.data $scope.orgCategories.push(name: gettextCatalog.getString(orgTypeObject.type), value: orgTypeObject.type) setIntroOptions() #Federal states selection $scope.federalStates = (name: gettextCatalog.getString(state.value), value: state.value, iso: state.iso for state in TPAService.staticData 'federal') #remove Austria if $scope.federalStates.length is 10 $scope.federalStates.pop() savedState = sessionStorage.getItem 'topState' if savedState TPAService.restoreState stateName, fieldsToStore, $scope orgTypePromise.then( => update()) registerWatches() else pY = TPAService.years() pY.then (res) -> $scope.years = (year: year, checked: false for year in res.data.years) $scope.years[0].checked = true; pP = TPAService.periods() pP.then (res) -> $scope.periods = res.data.reverse() $scope.slider.options.ceil = ($scope.periods.length - 1)*5 $scope.slider.from = $scope.slider.options.ceil $scope.slider.to = $scope.slider.options.ceil types = [2, 4, 31] $scope.typesText = (type: type, text: gettextCatalog.getString( TPAService.decodeType(type) ), checked: false for type in types) $scope.typesText[0].checked = true #Variables for the selection of federalState $scope.selectedFederalState = null $scope.orgType = $scope.orgTypes[0].value $scope.includeGroupings = false $q.all([pY, pP, orgTypePromise]).then (res) -> $scope.selectedOrgCategories.push(orgTypeObject.value) for orgTypeObject in $scope.orgCategories update() registerWatches() translate = -> $scope.orgTypes[0].name = gettextCatalog.getString('Spender') $scope.orgTypes[1].name = gettextCatalog.getString('Recipient') $scope.typesText.forEach (t) -> t.text = gettextCatalog.getString TPAService.decodeType t.type $scope.federalStates.forEach (state) -> state.name = gettextCatalog.getString state.value $scope.orgCategories.forEach (cat) -> cat.name = gettextCatalog.getString cat.value setIntroOptions() $scope.$on 'gettextLanguageChanged', translate initState() $scope.td.dtOptions = DTOptionsBuilder.fromFnPromise( -> defer = $q.defer() dataPromise.promise.then (result) -> defer.resolve($scope.top.top); defer.promise ) .withPaginationType('full_numbers') .withButtons(['copy','csv','excel']) .withBootstrap() angular.extend $scope.td.dtOptions, language: paginate: previous: gettextCatalog.getString('previous') next: gettextCatalog.getString('next') first: gettextCatalog.getString('first') last: gettextCatalog.getString('last') search: gettextCatalog.getString('search') info: gettextCatalog.getString('Showing page _PAGE_ of _PAGES_') lengthMenu: gettextCatalog.getString "Display _MENU_ records" $scope.td.dtColumns = [ DTColumnBuilder.newColumn('organisation').withTitle('Organisation'), DTColumnBuilder.newColumn('total').withTitle('Total') .renderWith((total,type) -> if type is 'display' total.toLocaleString($rootScope.language,{currency: "EUR", maximumFractionDigits:2,minimumFractionDigits:2}) else total) .withClass('text-right') ]; $scope.x = (d) -> d.key $scope.y = (d) -> d.y #prevents clicks on "Others" to trigger a navigation $scope.preventClickForOthers = (d) -> d.data.key in ["Others","Andere"] $rootScope.$on '$stateChangeStart', (event,toState) -> if toState.name isnt "top" TPAService.saveState stateName,fieldsToStore, $scope $scope.selectedFederalStateName = -> if $scope.selectedFederalState $scope.federalStates.filter( (v)->v.iso==$scope.selectedFederalState.iso)[0].name else gettextCatalog.getString('Austria') #navigate to some other page $scope.go = (d) -> window.scrollTo 0, 0 if d.data.isGrouping groupName = d.data.key.slice(4) # removing the group prefix "(G) " $state.go 'showflow', { name: d.data.key if not d.data.isGrouping orgType: $scope.orgType mediaGrp: "S:#{groupName}" if $scope.orgType is 'media' and d.data.isGrouping orgGrp: "S:#{groupName}" if $scope.orgType is 'org' and d.data.isGrouping from: $scope.periods[$scope.slider.from/5].period to: $scope.periods[$scope.slider.to/5].period fedState: $scope.selectedFederalState.iso if $scope.selectedFederalState pTypes: $scope.typesText.filter((t) -> t.checked).map (t) -> t.type }, location: true inherit: false reload: true ]
160152
'use strict' app = angular.module 'mean.transparency' app.controller 'TopEntriesCtrl', ['$scope', 'TPAService', '$q', '$state','gettextCatalog','$rootScope', 'DTOptionsBuilder', 'DTColumnDefBuilder', 'DTColumnBuilder','$uibModal','$timeout' ($scope, TPAService, $q, $state, gettextCatalog, $rootScope, DTOptionsBuilder, DTColumnDefBuilder,DTColumnBuilder, $uibModal, $timeout) -> tc = this dataPromise = $q.defer() $scope.td = {} $scope.td.dtInstance = {} params = {} stateName = "topState" fieldsToStore = ['slider','periods','orgTypes','typesText','rank','orgType', 'selectedFederalState', 'includeGroupings', 'selectedOrgCategories'] $scope.periods = [] $scope.slider = from: 0 to: 0 options: step:5 floor:0 onEnd: -> change(1,2) translate: (value) -> $scope.periods.map((p) -> "#{p.year}/Q#{p.quarter}")[value/5] $scope.showSettings = false $scope.ranks = [3, 5, 10, 15, 20] $scope.rank = 10 $scope.pieData = [] window.scrollTo 0, 0 $scope.getFrom = -> if $scope.periods && $scope.periods.length > 0 "Q#{$scope.periods[$scope.slider.from/5].quarter}/#{$scope.periods[$scope.slider.from/5].year}" else "" $scope.getTo = -> if $scope.periods && $scope.periods.length > 0 "Q#{$scope.periods[$scope.slider.to/5].quarter}/#{$scope.periods[$scope.slider.to/5].year}" else "" $scope.selectedTypes = -> $scope.typesText.filter((t) -> t.checked).map (t) -> t.type $scope.selectedOrgType = -> if $scope.orgType is "org" then "Payers" else "Beneficiaries" # register watches to update chart when changes occur registerWatches = -> $scope.$watch('typesText', change, true) $scope.$watch('orgType', change, true) $scope.$watch('rank', change, true) $scope.$watch('selectedFederalState', change, true) $scope.$watch('includeGroupings', change, true) $scope.$watch('selectedOrgCategories', change, true) #construct the query parameters parameters = -> params = {} params.from = $scope.periods[$scope.slider.from/5].period params.to =$scope.periods[$scope.slider.to/5].period params.federalState = $scope.selectedFederalState.iso if $scope.selectedFederalState params.groupings = $scope.includeGroupings if $scope.includeGroupings types = (v.type for v in $scope.typesText when v.checked) (params.pType = types) if types.length > 0 params.x = $scope.rank params.orgType = $scope.orgType params.orgCategories = $scope.selectedOrgCategories params $scope.total = -> if $scope.top then $scope.top.all.toLocaleString() else "0" $scope.IntroOptions = null; $scope.selectedOrgCategories = []; $scope.goto = (l)-> $anchorScroll(l) $scope.showSettingsDialog = -> parent = $scope $uibModal.open( templateUrl: 'transparency/views/topSettingsDialog.html' scope: $scope size: 'lg' controller: ($scope, $uibModalInstance) -> $scope.close = -> $scope.$parent.orgType = $scope.orgType $scope.$parent.selectedOrgCategories = $scope.selectedOrgCategories $uibModalInstance.close() current = $scope.slider.options.draggableRangeOnly $timeout (-> $scope.slider.options.draggableRangeOnly = !current), 100 $timeout (-> $scope.slider.options.draggableRangeOnly = current), 120 ) buildPieModel = -> $scope.pieData = [] $scope.pieData.push {key: entry.organisation, y: entry.total, isGrouping: entry.isGrouping} for entry in $scope.top.top topSum = $scope.top.top.reduce( (sum, entry) -> sum + entry.total 0 ) $scope.pieData.push {key: <KEY>.<KEY>("Others"), y: $scope.top.all - topSum} $scope.toolTipContentFunction = (e) -> link = if e.index < $scope.rank then '<br/><i class="fa fa-line-chart" aria-hidden="true"></i> '+gettextCatalog.getString("Click for Details") else "" numberOptions = {style:'currency',currency:'EUR'} """<div class='chartToolTip'> <h3>#{e.data.key}</h3> <p>#{e.data.y.toLocaleString(gettextCatalog.getCurrentLanguage(),numberOptions)} (#{(e.data.y/$scope.top.all *100).toFixed(2)}%)#{link}</p> </div>""" #fetch data from server and update the chart update = -> TPAService.top(parameters()) .then((res) -> init = true $scope.top = res.data dataPromise.resolve() buildPieModel() ) change = (oldValue, newValue) -> if (oldValue isnt newValue) dataPromise = $q.defer() $scope.td.dtInstance.reloadData() update() # Method for setting the intro-options (e.g. after translations) setIntroOptions = -> $scope.IntroOptions = steps: [ { element: document.querySelector('#topSettings') intro: gettextCatalog.getString 'It is possible to customize the pie chart. To do so, use the settings.' } { element: document.querySelector('#topSlider') intro: gettextCatalog.getString 'Move the sliders to define a range.' }, { element: document.querySelector('#fixSliderRange') intro: gettextCatalog.getString 'Fix slider range. With that it is possible to keep the range constant.' }, { element: document.querySelector('#grouping') intro: gettextCatalog.getString 'With groupings enabled single transfers will be taken together (e.g. to show umbrella organisations)' }, { element: document.querySelector('#orgTypesSelection') intro: gettextCatalog.getString 'It is possible to narrow down the results to specific organisation types' }, { element: document.querySelector('#spenderRecipient') intro: gettextCatalog.getString 'Display top spender or top recipient' }, { element: document.querySelector('#paymentTypes') intro: gettextCatalog.getString 'Transfers are divided in different payment types. Select the types to display.' }, { element: document.querySelector('#fedStateSelection') intro: gettextCatalog.getString 'It is possible to show the chart for a specific federal state.' }, { element: document.querySelector('#rank') intro: gettextCatalog.getString 'Select the numbers of elements in the pie chart' } ] showStepNumbers: false exitOnOverlayClick: true exitOnEsc: true nextLabel: gettextCatalog.getString 'Next info' prevLabel: gettextCatalog.getString 'Previous info' skipLabel: gettextCatalog.getString 'Skip info' doneLabel: gettextCatalog.getString 'End tour' initState = -> $scope.orgTypes = [ {name: gettextCatalog.getString('Spender'), value: 'org'}, {name: gettextCatalog.getString('Recipient'), value: 'media'} ] $scope.orgCategories = [] orgTypePromise = TPAService.organisationTypes() .then (res) -> for orgTypeObject in res.data $scope.orgCategories.push(name: gettextCatalog.getString(orgTypeObject.type), value: orgTypeObject.type) setIntroOptions() #Federal states selection $scope.federalStates = (name: gettextCatalog.getString(state.value), value: state.value, iso: state.iso for state in TPAService.staticData 'federal') #remove Austria if $scope.federalStates.length is 10 $scope.federalStates.pop() savedState = sessionStorage.getItem 'topState' if savedState TPAService.restoreState stateName, fieldsToStore, $scope orgTypePromise.then( => update()) registerWatches() else pY = TPAService.years() pY.then (res) -> $scope.years = (year: year, checked: false for year in res.data.years) $scope.years[0].checked = true; pP = TPAService.periods() pP.then (res) -> $scope.periods = res.data.reverse() $scope.slider.options.ceil = ($scope.periods.length - 1)*5 $scope.slider.from = $scope.slider.options.ceil $scope.slider.to = $scope.slider.options.ceil types = [2, 4, 31] $scope.typesText = (type: type, text: gettextCatalog.getString( TPAService.decodeType(type) ), checked: false for type in types) $scope.typesText[0].checked = true #Variables for the selection of federalState $scope.selectedFederalState = null $scope.orgType = $scope.orgTypes[0].value $scope.includeGroupings = false $q.all([pY, pP, orgTypePromise]).then (res) -> $scope.selectedOrgCategories.push(orgTypeObject.value) for orgTypeObject in $scope.orgCategories update() registerWatches() translate = -> $scope.orgTypes[0].name = gettextCatalog.getString('Spender') $scope.orgTypes[1].name = gettextCatalog.getString('Recipient') $scope.typesText.forEach (t) -> t.text = gettextCatalog.getString TPAService.decodeType t.type $scope.federalStates.forEach (state) -> state.name = gettextCatalog.getString state.value $scope.orgCategories.forEach (cat) -> cat.name = gettextCatalog.getString cat.value setIntroOptions() $scope.$on 'gettextLanguageChanged', translate initState() $scope.td.dtOptions = DTOptionsBuilder.fromFnPromise( -> defer = $q.defer() dataPromise.promise.then (result) -> defer.resolve($scope.top.top); defer.promise ) .withPaginationType('full_numbers') .withButtons(['copy','csv','excel']) .withBootstrap() angular.extend $scope.td.dtOptions, language: paginate: previous: gettextCatalog.getString('previous') next: gettextCatalog.getString('next') first: gettextCatalog.getString('first') last: gettextCatalog.getString('last') search: gettextCatalog.getString('search') info: gettextCatalog.getString('Showing page _PAGE_ of _PAGES_') lengthMenu: gettextCatalog.getString "Display _MENU_ records" $scope.td.dtColumns = [ DTColumnBuilder.newColumn('organisation').withTitle('Organisation'), DTColumnBuilder.newColumn('total').withTitle('Total') .renderWith((total,type) -> if type is 'display' total.toLocaleString($rootScope.language,{currency: "EUR", maximumFractionDigits:2,minimumFractionDigits:2}) else total) .withClass('text-right') ]; $scope.x = (d) -> d.key $scope.y = (d) -> d.y #prevents clicks on "Others" to trigger a navigation $scope.preventClickForOthers = (d) -> d.data.key in ["Others","Andere"] $rootScope.$on '$stateChangeStart', (event,toState) -> if toState.name isnt "top" TPAService.saveState stateName,fieldsToStore, $scope $scope.selectedFederalStateName = -> if $scope.selectedFederalState $scope.federalStates.filter( (v)->v.iso==$scope.selectedFederalState.iso)[0].name else gettextCatalog.getString('Austria') #navigate to some other page $scope.go = (d) -> window.scrollTo 0, 0 if d.data.isGrouping groupName = d.data.key.slice(4) # removing the group prefix "(G) " $state.go 'showflow', { name: d.data.key if not d.data.isGrouping orgType: $scope.orgType mediaGrp: "S:#{groupName}" if $scope.orgType is 'media' and d.data.isGrouping orgGrp: "S:#{groupName}" if $scope.orgType is 'org' and d.data.isGrouping from: $scope.periods[$scope.slider.from/5].period to: $scope.periods[$scope.slider.to/5].period fedState: $scope.selectedFederalState.iso if $scope.selectedFederalState pTypes: $scope.typesText.filter((t) -> t.checked).map (t) -> t.type }, location: true inherit: false reload: true ]
true
'use strict' app = angular.module 'mean.transparency' app.controller 'TopEntriesCtrl', ['$scope', 'TPAService', '$q', '$state','gettextCatalog','$rootScope', 'DTOptionsBuilder', 'DTColumnDefBuilder', 'DTColumnBuilder','$uibModal','$timeout' ($scope, TPAService, $q, $state, gettextCatalog, $rootScope, DTOptionsBuilder, DTColumnDefBuilder,DTColumnBuilder, $uibModal, $timeout) -> tc = this dataPromise = $q.defer() $scope.td = {} $scope.td.dtInstance = {} params = {} stateName = "topState" fieldsToStore = ['slider','periods','orgTypes','typesText','rank','orgType', 'selectedFederalState', 'includeGroupings', 'selectedOrgCategories'] $scope.periods = [] $scope.slider = from: 0 to: 0 options: step:5 floor:0 onEnd: -> change(1,2) translate: (value) -> $scope.periods.map((p) -> "#{p.year}/Q#{p.quarter}")[value/5] $scope.showSettings = false $scope.ranks = [3, 5, 10, 15, 20] $scope.rank = 10 $scope.pieData = [] window.scrollTo 0, 0 $scope.getFrom = -> if $scope.periods && $scope.periods.length > 0 "Q#{$scope.periods[$scope.slider.from/5].quarter}/#{$scope.periods[$scope.slider.from/5].year}" else "" $scope.getTo = -> if $scope.periods && $scope.periods.length > 0 "Q#{$scope.periods[$scope.slider.to/5].quarter}/#{$scope.periods[$scope.slider.to/5].year}" else "" $scope.selectedTypes = -> $scope.typesText.filter((t) -> t.checked).map (t) -> t.type $scope.selectedOrgType = -> if $scope.orgType is "org" then "Payers" else "Beneficiaries" # register watches to update chart when changes occur registerWatches = -> $scope.$watch('typesText', change, true) $scope.$watch('orgType', change, true) $scope.$watch('rank', change, true) $scope.$watch('selectedFederalState', change, true) $scope.$watch('includeGroupings', change, true) $scope.$watch('selectedOrgCategories', change, true) #construct the query parameters parameters = -> params = {} params.from = $scope.periods[$scope.slider.from/5].period params.to =$scope.periods[$scope.slider.to/5].period params.federalState = $scope.selectedFederalState.iso if $scope.selectedFederalState params.groupings = $scope.includeGroupings if $scope.includeGroupings types = (v.type for v in $scope.typesText when v.checked) (params.pType = types) if types.length > 0 params.x = $scope.rank params.orgType = $scope.orgType params.orgCategories = $scope.selectedOrgCategories params $scope.total = -> if $scope.top then $scope.top.all.toLocaleString() else "0" $scope.IntroOptions = null; $scope.selectedOrgCategories = []; $scope.goto = (l)-> $anchorScroll(l) $scope.showSettingsDialog = -> parent = $scope $uibModal.open( templateUrl: 'transparency/views/topSettingsDialog.html' scope: $scope size: 'lg' controller: ($scope, $uibModalInstance) -> $scope.close = -> $scope.$parent.orgType = $scope.orgType $scope.$parent.selectedOrgCategories = $scope.selectedOrgCategories $uibModalInstance.close() current = $scope.slider.options.draggableRangeOnly $timeout (-> $scope.slider.options.draggableRangeOnly = !current), 100 $timeout (-> $scope.slider.options.draggableRangeOnly = current), 120 ) buildPieModel = -> $scope.pieData = [] $scope.pieData.push {key: entry.organisation, y: entry.total, isGrouping: entry.isGrouping} for entry in $scope.top.top topSum = $scope.top.top.reduce( (sum, entry) -> sum + entry.total 0 ) $scope.pieData.push {key: PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI("Others"), y: $scope.top.all - topSum} $scope.toolTipContentFunction = (e) -> link = if e.index < $scope.rank then '<br/><i class="fa fa-line-chart" aria-hidden="true"></i> '+gettextCatalog.getString("Click for Details") else "" numberOptions = {style:'currency',currency:'EUR'} """<div class='chartToolTip'> <h3>#{e.data.key}</h3> <p>#{e.data.y.toLocaleString(gettextCatalog.getCurrentLanguage(),numberOptions)} (#{(e.data.y/$scope.top.all *100).toFixed(2)}%)#{link}</p> </div>""" #fetch data from server and update the chart update = -> TPAService.top(parameters()) .then((res) -> init = true $scope.top = res.data dataPromise.resolve() buildPieModel() ) change = (oldValue, newValue) -> if (oldValue isnt newValue) dataPromise = $q.defer() $scope.td.dtInstance.reloadData() update() # Method for setting the intro-options (e.g. after translations) setIntroOptions = -> $scope.IntroOptions = steps: [ { element: document.querySelector('#topSettings') intro: gettextCatalog.getString 'It is possible to customize the pie chart. To do so, use the settings.' } { element: document.querySelector('#topSlider') intro: gettextCatalog.getString 'Move the sliders to define a range.' }, { element: document.querySelector('#fixSliderRange') intro: gettextCatalog.getString 'Fix slider range. With that it is possible to keep the range constant.' }, { element: document.querySelector('#grouping') intro: gettextCatalog.getString 'With groupings enabled single transfers will be taken together (e.g. to show umbrella organisations)' }, { element: document.querySelector('#orgTypesSelection') intro: gettextCatalog.getString 'It is possible to narrow down the results to specific organisation types' }, { element: document.querySelector('#spenderRecipient') intro: gettextCatalog.getString 'Display top spender or top recipient' }, { element: document.querySelector('#paymentTypes') intro: gettextCatalog.getString 'Transfers are divided in different payment types. Select the types to display.' }, { element: document.querySelector('#fedStateSelection') intro: gettextCatalog.getString 'It is possible to show the chart for a specific federal state.' }, { element: document.querySelector('#rank') intro: gettextCatalog.getString 'Select the numbers of elements in the pie chart' } ] showStepNumbers: false exitOnOverlayClick: true exitOnEsc: true nextLabel: gettextCatalog.getString 'Next info' prevLabel: gettextCatalog.getString 'Previous info' skipLabel: gettextCatalog.getString 'Skip info' doneLabel: gettextCatalog.getString 'End tour' initState = -> $scope.orgTypes = [ {name: gettextCatalog.getString('Spender'), value: 'org'}, {name: gettextCatalog.getString('Recipient'), value: 'media'} ] $scope.orgCategories = [] orgTypePromise = TPAService.organisationTypes() .then (res) -> for orgTypeObject in res.data $scope.orgCategories.push(name: gettextCatalog.getString(orgTypeObject.type), value: orgTypeObject.type) setIntroOptions() #Federal states selection $scope.federalStates = (name: gettextCatalog.getString(state.value), value: state.value, iso: state.iso for state in TPAService.staticData 'federal') #remove Austria if $scope.federalStates.length is 10 $scope.federalStates.pop() savedState = sessionStorage.getItem 'topState' if savedState TPAService.restoreState stateName, fieldsToStore, $scope orgTypePromise.then( => update()) registerWatches() else pY = TPAService.years() pY.then (res) -> $scope.years = (year: year, checked: false for year in res.data.years) $scope.years[0].checked = true; pP = TPAService.periods() pP.then (res) -> $scope.periods = res.data.reverse() $scope.slider.options.ceil = ($scope.periods.length - 1)*5 $scope.slider.from = $scope.slider.options.ceil $scope.slider.to = $scope.slider.options.ceil types = [2, 4, 31] $scope.typesText = (type: type, text: gettextCatalog.getString( TPAService.decodeType(type) ), checked: false for type in types) $scope.typesText[0].checked = true #Variables for the selection of federalState $scope.selectedFederalState = null $scope.orgType = $scope.orgTypes[0].value $scope.includeGroupings = false $q.all([pY, pP, orgTypePromise]).then (res) -> $scope.selectedOrgCategories.push(orgTypeObject.value) for orgTypeObject in $scope.orgCategories update() registerWatches() translate = -> $scope.orgTypes[0].name = gettextCatalog.getString('Spender') $scope.orgTypes[1].name = gettextCatalog.getString('Recipient') $scope.typesText.forEach (t) -> t.text = gettextCatalog.getString TPAService.decodeType t.type $scope.federalStates.forEach (state) -> state.name = gettextCatalog.getString state.value $scope.orgCategories.forEach (cat) -> cat.name = gettextCatalog.getString cat.value setIntroOptions() $scope.$on 'gettextLanguageChanged', translate initState() $scope.td.dtOptions = DTOptionsBuilder.fromFnPromise( -> defer = $q.defer() dataPromise.promise.then (result) -> defer.resolve($scope.top.top); defer.promise ) .withPaginationType('full_numbers') .withButtons(['copy','csv','excel']) .withBootstrap() angular.extend $scope.td.dtOptions, language: paginate: previous: gettextCatalog.getString('previous') next: gettextCatalog.getString('next') first: gettextCatalog.getString('first') last: gettextCatalog.getString('last') search: gettextCatalog.getString('search') info: gettextCatalog.getString('Showing page _PAGE_ of _PAGES_') lengthMenu: gettextCatalog.getString "Display _MENU_ records" $scope.td.dtColumns = [ DTColumnBuilder.newColumn('organisation').withTitle('Organisation'), DTColumnBuilder.newColumn('total').withTitle('Total') .renderWith((total,type) -> if type is 'display' total.toLocaleString($rootScope.language,{currency: "EUR", maximumFractionDigits:2,minimumFractionDigits:2}) else total) .withClass('text-right') ]; $scope.x = (d) -> d.key $scope.y = (d) -> d.y #prevents clicks on "Others" to trigger a navigation $scope.preventClickForOthers = (d) -> d.data.key in ["Others","Andere"] $rootScope.$on '$stateChangeStart', (event,toState) -> if toState.name isnt "top" TPAService.saveState stateName,fieldsToStore, $scope $scope.selectedFederalStateName = -> if $scope.selectedFederalState $scope.federalStates.filter( (v)->v.iso==$scope.selectedFederalState.iso)[0].name else gettextCatalog.getString('Austria') #navigate to some other page $scope.go = (d) -> window.scrollTo 0, 0 if d.data.isGrouping groupName = d.data.key.slice(4) # removing the group prefix "(G) " $state.go 'showflow', { name: d.data.key if not d.data.isGrouping orgType: $scope.orgType mediaGrp: "S:#{groupName}" if $scope.orgType is 'media' and d.data.isGrouping orgGrp: "S:#{groupName}" if $scope.orgType is 'org' and d.data.isGrouping from: $scope.periods[$scope.slider.from/5].period to: $scope.periods[$scope.slider.to/5].period fedState: $scope.selectedFederalState.iso if $scope.selectedFederalState pTypes: $scope.typesText.filter((t) -> t.checked).map (t) -> t.type }, location: true inherit: false reload: true ]
[ { "context": "header\",\n credentials:\n key: \"dasdfasdf\"\n algorithm: \"sha256\"\n\n ts: 1", "end": 476, "score": 0.9995412230491638, "start": 467, "tag": "KEY", "value": "dasdfasdf" }, { "context": "header\",\n credentials:\n key: \"dasdfasdf\"\n algorithm: \"sha256\"\n\n ts: 1", "end": 997, "score": 0.9995465874671936, "start": 988, "tag": "KEY", "value": "dasdfasdf" }, { "context": "header\",\n credentials:\n key: \"dasdfasdf\"\n algorithm: \"sha256\"\n\n ts: 1", "end": 1588, "score": 0.9995407462120056, "start": 1579, "tag": "KEY", "value": "dasdfasdf" } ]
deps/npm/node_modules/request/node_modules/hawk/test/crypto.coffee
lxe/io.coffee
0
# Load modules Lab = require("lab") Hawk = require("../lib") # Declare internals internals = {} # Test shortcuts expect = Lab.expect before = Lab.before after = Lab.after describe = Lab.experiment it = Lab.test describe "Hawk", -> describe "Crypto", -> describe "#generateNormalizedString", -> it "should return a valid normalized string", (done) -> expect(Hawk.crypto.generateNormalizedString("header", credentials: key: "dasdfasdf" algorithm: "sha256" ts: 1357747017 nonce: "k3k4j5" method: "GET" resource: "/resource/something" host: "example.com" port: 8080 )).to.equal "hawk.1.header\n1357747017\nk3k4j5\nGET\n/resource/something\nexample.com\n8080\n\n\n" done() return it "should return a valid normalized string (ext)", (done) -> expect(Hawk.crypto.generateNormalizedString("header", credentials: key: "dasdfasdf" algorithm: "sha256" ts: 1357747017 nonce: "k3k4j5" method: "GET" resource: "/resource/something" host: "example.com" port: 8080 ext: "this is some app data" )).to.equal "hawk.1.header\n1357747017\nk3k4j5\nGET\n/resource/something\nexample.com\n8080\n\nthis is some app data\n" done() return it "should return a valid normalized string (payload + ext)", (done) -> expect(Hawk.crypto.generateNormalizedString("header", credentials: key: "dasdfasdf" algorithm: "sha256" ts: 1357747017 nonce: "k3k4j5" method: "GET" resource: "/resource/something" host: "example.com" port: 8080 hash: "U4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=" ext: "this is some app data" )).to.equal "hawk.1.header\n1357747017\nk3k4j5\nGET\n/resource/something\nexample.com\n8080\nU4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=\nthis is some app data\n" done() return return return return
52977
# Load modules Lab = require("lab") Hawk = require("../lib") # Declare internals internals = {} # Test shortcuts expect = Lab.expect before = Lab.before after = Lab.after describe = Lab.experiment it = Lab.test describe "Hawk", -> describe "Crypto", -> describe "#generateNormalizedString", -> it "should return a valid normalized string", (done) -> expect(Hawk.crypto.generateNormalizedString("header", credentials: key: "<KEY>" algorithm: "sha256" ts: 1357747017 nonce: "k3k4j5" method: "GET" resource: "/resource/something" host: "example.com" port: 8080 )).to.equal "hawk.1.header\n1357747017\nk3k4j5\nGET\n/resource/something\nexample.com\n8080\n\n\n" done() return it "should return a valid normalized string (ext)", (done) -> expect(Hawk.crypto.generateNormalizedString("header", credentials: key: "<KEY>" algorithm: "sha256" ts: 1357747017 nonce: "k3k4j5" method: "GET" resource: "/resource/something" host: "example.com" port: 8080 ext: "this is some app data" )).to.equal "hawk.1.header\n1357747017\nk3k4j5\nGET\n/resource/something\nexample.com\n8080\n\nthis is some app data\n" done() return it "should return a valid normalized string (payload + ext)", (done) -> expect(Hawk.crypto.generateNormalizedString("header", credentials: key: "<KEY>" algorithm: "sha256" ts: 1357747017 nonce: "k3k4j5" method: "GET" resource: "/resource/something" host: "example.com" port: 8080 hash: "U4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=" ext: "this is some app data" )).to.equal "hawk.1.header\n1357747017\nk3k4j5\nGET\n/resource/something\nexample.com\n8080\nU4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=\nthis is some app data\n" done() return return return return
true
# Load modules Lab = require("lab") Hawk = require("../lib") # Declare internals internals = {} # Test shortcuts expect = Lab.expect before = Lab.before after = Lab.after describe = Lab.experiment it = Lab.test describe "Hawk", -> describe "Crypto", -> describe "#generateNormalizedString", -> it "should return a valid normalized string", (done) -> expect(Hawk.crypto.generateNormalizedString("header", credentials: key: "PI:KEY:<KEY>END_PI" algorithm: "sha256" ts: 1357747017 nonce: "k3k4j5" method: "GET" resource: "/resource/something" host: "example.com" port: 8080 )).to.equal "hawk.1.header\n1357747017\nk3k4j5\nGET\n/resource/something\nexample.com\n8080\n\n\n" done() return it "should return a valid normalized string (ext)", (done) -> expect(Hawk.crypto.generateNormalizedString("header", credentials: key: "PI:KEY:<KEY>END_PI" algorithm: "sha256" ts: 1357747017 nonce: "k3k4j5" method: "GET" resource: "/resource/something" host: "example.com" port: 8080 ext: "this is some app data" )).to.equal "hawk.1.header\n1357747017\nk3k4j5\nGET\n/resource/something\nexample.com\n8080\n\nthis is some app data\n" done() return it "should return a valid normalized string (payload + ext)", (done) -> expect(Hawk.crypto.generateNormalizedString("header", credentials: key: "PI:KEY:<KEY>END_PI" algorithm: "sha256" ts: 1357747017 nonce: "k3k4j5" method: "GET" resource: "/resource/something" host: "example.com" port: 8080 hash: "U4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=" ext: "this is some app data" )).to.equal "hawk.1.header\n1357747017\nk3k4j5\nGET\n/resource/something\nexample.com\n8080\nU4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=\nthis is some app data\n" done() return return return return
[ { "context": "\n# Helper returns a random key\nrandomKey = () ->\n\trandomString(8)\n\n# Helper returns a random value\nrandomV", "end": 510, "score": 0.5568974614143372, "start": 504, "tag": "KEY", "value": "random" } ]
server/redis/r-timeseries.coffee
willroberts/duelyst
5
_ = require 'underscore' Promise = require 'bluebird' moment = require 'moment' crypto = require 'crypto' config = require '../../config/config.js' Logger = require '../../app/common/logger.coffee' env = config.get("env") # Helper returns the Redis key prefix keyPrefix = () -> return "#{env}:ts:" # Helper returns a random string of specified length randomString = (length) -> crypto.randomBytes(Math.ceil(length/2)).toString('hex').slice(0,length) # Helper returns a random key randomKey = () -> randomString(8) # Helper returns a random value randomValue = () -> randomString(32) # Defaults used in constructor defaults = name: randomKey() ###* # Class 'RedisTimeSeries' # Manages time series data structure in Redis # Time series are sorted sets, sorted by a UTC timestamp # Since values must be unique, we also prefix the value w/ the timestamp ### module.exports = class RedisTimeSeries ###* # Constructor # Gives itself a random name if none specified # @param {Object} redis, a promisified redis connection # @param {Object} options, opts.name sets the time series' name ### constructor: (redis, opts = {}) -> # TODO: add check to ensure Redis client is already promisified @redis = redis @name = opts.name || defaults.name @ts = keyPrefix() + @name @createdAt = moment.utc().valueOf() # Logger.module("REDIS").log("ts(#{@name})") return ###* # Mark a hit in the time series # Will use a random value if none specified # Note this may cause collisions if random string is short # Deletes / prunes hits that are older than 72 hours on insert # @param {String} unique value to assosicate with hit # @return {Promise} returns 1 if success, 0 if fail ### hit: (value = randomValue()) -> # Logger.module("REDIS-TS").log("hit(#{value})") timestamp = moment.utc().valueOf() score = timestamp # we add a timestamp to the value also to ensure some uniqueness # as you cannot have duplicate values in a sorted set value = timestamp + ":" + value # prune data older than 72 hours, TODO: make this configurable old = moment.utc().subtract(72,'hours').valueOf() # delete + insert multi = @redis.multi() multi.zremrangebyscore(@ts, 0, old) multi.zadd(@ts, score, value) return multi.execAsync() ###* # Query the time series # @param {Object} options # @return {Promise} returns object contain all hits in query range # opts.range, hours to query the time series, defaults to 1hr # opts.limit, limit the number of results, defaults to 1000 # opts.withScores, include the scores, defaults to true ### query: (opts = {}) -> range = opts.range || 1 limit = opts.limit || 1000 withScores = opts.withScores || true # Logger.module("REDIS-TS").log("query(#{range})") now = moment.utc().valueOf() previous = moment.utc().subtract(range,'hours').valueOf() if withScores args = [ @ts, previous, now, 'WITHSCORES', 'LIMIT', 0, limit ] else # TODO : fix without scores option args = [ @ts, previous, now, 'WITHSCORES', 'LIMIT', 0, limit ] @redis.zrangebyscoreAsync(args) .then (scores) -> # TODO : this only works WITHSCORES = true values = [] # scores is an array [] where even/odd pairs are the value, score # zip up the array into an object keyed by score while scores.length > 0 value = scores.shift() score = scores.shift() # remove the timestamp added to the value values.push(value.split(':')[1]) return values ###* # Query the time series # @param {Integer} range, number of hours to query back # @return {Promise} number of hits in time series query ### countHits: (range = 1) -> return @query({range: range}).then(_).call('size')
181414
_ = require 'underscore' Promise = require 'bluebird' moment = require 'moment' crypto = require 'crypto' config = require '../../config/config.js' Logger = require '../../app/common/logger.coffee' env = config.get("env") # Helper returns the Redis key prefix keyPrefix = () -> return "#{env}:ts:" # Helper returns a random string of specified length randomString = (length) -> crypto.randomBytes(Math.ceil(length/2)).toString('hex').slice(0,length) # Helper returns a random key randomKey = () -> <KEY>String(8) # Helper returns a random value randomValue = () -> randomString(32) # Defaults used in constructor defaults = name: randomKey() ###* # Class 'RedisTimeSeries' # Manages time series data structure in Redis # Time series are sorted sets, sorted by a UTC timestamp # Since values must be unique, we also prefix the value w/ the timestamp ### module.exports = class RedisTimeSeries ###* # Constructor # Gives itself a random name if none specified # @param {Object} redis, a promisified redis connection # @param {Object} options, opts.name sets the time series' name ### constructor: (redis, opts = {}) -> # TODO: add check to ensure Redis client is already promisified @redis = redis @name = opts.name || defaults.name @ts = keyPrefix() + @name @createdAt = moment.utc().valueOf() # Logger.module("REDIS").log("ts(#{@name})") return ###* # Mark a hit in the time series # Will use a random value if none specified # Note this may cause collisions if random string is short # Deletes / prunes hits that are older than 72 hours on insert # @param {String} unique value to assosicate with hit # @return {Promise} returns 1 if success, 0 if fail ### hit: (value = randomValue()) -> # Logger.module("REDIS-TS").log("hit(#{value})") timestamp = moment.utc().valueOf() score = timestamp # we add a timestamp to the value also to ensure some uniqueness # as you cannot have duplicate values in a sorted set value = timestamp + ":" + value # prune data older than 72 hours, TODO: make this configurable old = moment.utc().subtract(72,'hours').valueOf() # delete + insert multi = @redis.multi() multi.zremrangebyscore(@ts, 0, old) multi.zadd(@ts, score, value) return multi.execAsync() ###* # Query the time series # @param {Object} options # @return {Promise} returns object contain all hits in query range # opts.range, hours to query the time series, defaults to 1hr # opts.limit, limit the number of results, defaults to 1000 # opts.withScores, include the scores, defaults to true ### query: (opts = {}) -> range = opts.range || 1 limit = opts.limit || 1000 withScores = opts.withScores || true # Logger.module("REDIS-TS").log("query(#{range})") now = moment.utc().valueOf() previous = moment.utc().subtract(range,'hours').valueOf() if withScores args = [ @ts, previous, now, 'WITHSCORES', 'LIMIT', 0, limit ] else # TODO : fix without scores option args = [ @ts, previous, now, 'WITHSCORES', 'LIMIT', 0, limit ] @redis.zrangebyscoreAsync(args) .then (scores) -> # TODO : this only works WITHSCORES = true values = [] # scores is an array [] where even/odd pairs are the value, score # zip up the array into an object keyed by score while scores.length > 0 value = scores.shift() score = scores.shift() # remove the timestamp added to the value values.push(value.split(':')[1]) return values ###* # Query the time series # @param {Integer} range, number of hours to query back # @return {Promise} number of hits in time series query ### countHits: (range = 1) -> return @query({range: range}).then(_).call('size')
true
_ = require 'underscore' Promise = require 'bluebird' moment = require 'moment' crypto = require 'crypto' config = require '../../config/config.js' Logger = require '../../app/common/logger.coffee' env = config.get("env") # Helper returns the Redis key prefix keyPrefix = () -> return "#{env}:ts:" # Helper returns a random string of specified length randomString = (length) -> crypto.randomBytes(Math.ceil(length/2)).toString('hex').slice(0,length) # Helper returns a random key randomKey = () -> PI:KEY:<KEY>END_PIString(8) # Helper returns a random value randomValue = () -> randomString(32) # Defaults used in constructor defaults = name: randomKey() ###* # Class 'RedisTimeSeries' # Manages time series data structure in Redis # Time series are sorted sets, sorted by a UTC timestamp # Since values must be unique, we also prefix the value w/ the timestamp ### module.exports = class RedisTimeSeries ###* # Constructor # Gives itself a random name if none specified # @param {Object} redis, a promisified redis connection # @param {Object} options, opts.name sets the time series' name ### constructor: (redis, opts = {}) -> # TODO: add check to ensure Redis client is already promisified @redis = redis @name = opts.name || defaults.name @ts = keyPrefix() + @name @createdAt = moment.utc().valueOf() # Logger.module("REDIS").log("ts(#{@name})") return ###* # Mark a hit in the time series # Will use a random value if none specified # Note this may cause collisions if random string is short # Deletes / prunes hits that are older than 72 hours on insert # @param {String} unique value to assosicate with hit # @return {Promise} returns 1 if success, 0 if fail ### hit: (value = randomValue()) -> # Logger.module("REDIS-TS").log("hit(#{value})") timestamp = moment.utc().valueOf() score = timestamp # we add a timestamp to the value also to ensure some uniqueness # as you cannot have duplicate values in a sorted set value = timestamp + ":" + value # prune data older than 72 hours, TODO: make this configurable old = moment.utc().subtract(72,'hours').valueOf() # delete + insert multi = @redis.multi() multi.zremrangebyscore(@ts, 0, old) multi.zadd(@ts, score, value) return multi.execAsync() ###* # Query the time series # @param {Object} options # @return {Promise} returns object contain all hits in query range # opts.range, hours to query the time series, defaults to 1hr # opts.limit, limit the number of results, defaults to 1000 # opts.withScores, include the scores, defaults to true ### query: (opts = {}) -> range = opts.range || 1 limit = opts.limit || 1000 withScores = opts.withScores || true # Logger.module("REDIS-TS").log("query(#{range})") now = moment.utc().valueOf() previous = moment.utc().subtract(range,'hours').valueOf() if withScores args = [ @ts, previous, now, 'WITHSCORES', 'LIMIT', 0, limit ] else # TODO : fix without scores option args = [ @ts, previous, now, 'WITHSCORES', 'LIMIT', 0, limit ] @redis.zrangebyscoreAsync(args) .then (scores) -> # TODO : this only works WITHSCORES = true values = [] # scores is an array [] where even/odd pairs are the value, score # zip up the array into an object keyed by score while scores.length > 0 value = scores.shift() score = scores.shift() # remove the timestamp added to the value values.push(value.split(':')[1]) return values ###* # Query the time series # @param {Integer} range, number of hours to query back # @return {Promise} number of hits in time series query ### countHits: (range = 1) -> return @query({range: range}).then(_).call('size')
[ { "context": "\n preventDuplicates: true\n tokenValue: \"pid\"\n onResult: (results) ->\n pidsToFilte", "end": 326, "score": 0.9946509003639221, "start": 323, "tag": "KEY", "value": "pid" } ]
app/assets/javascripts/worthwhile/select_works.js.coffee
flyingzumwalt/worthwhile
7
jQuery -> $('.autocomplete').each( (index, el) -> $targetElement = $(el) $targetElement.tokenInput $targetElement.data("url"), { theme: 'facebook' prePopulate: $('.autocomplete').data('load') jsonContainer: "docs" propertyToSearch: "title" preventDuplicates: true tokenValue: "pid" onResult: (results) -> pidsToFilter = $targetElement.data('exclude') $.each(results.docs, (index, value) -> # Filter out anything listed in data-exclude. ie. the current object. if (pidsToFilter.indexOf(value.pid) > -1) results.docs.splice(index, 1) ) return results } )
34572
jQuery -> $('.autocomplete').each( (index, el) -> $targetElement = $(el) $targetElement.tokenInput $targetElement.data("url"), { theme: 'facebook' prePopulate: $('.autocomplete').data('load') jsonContainer: "docs" propertyToSearch: "title" preventDuplicates: true tokenValue: "<KEY>" onResult: (results) -> pidsToFilter = $targetElement.data('exclude') $.each(results.docs, (index, value) -> # Filter out anything listed in data-exclude. ie. the current object. if (pidsToFilter.indexOf(value.pid) > -1) results.docs.splice(index, 1) ) return results } )
true
jQuery -> $('.autocomplete').each( (index, el) -> $targetElement = $(el) $targetElement.tokenInput $targetElement.data("url"), { theme: 'facebook' prePopulate: $('.autocomplete').data('load') jsonContainer: "docs" propertyToSearch: "title" preventDuplicates: true tokenValue: "PI:KEY:<KEY>END_PI" onResult: (results) -> pidsToFilter = $targetElement.data('exclude') $.each(results.docs, (index, value) -> # Filter out anything listed in data-exclude. ie. the current object. if (pidsToFilter.indexOf(value.pid) > -1) results.docs.splice(index, 1) ) return results } )
[ { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ", "end": 38, "score": 0.9998876452445984, "start": 25, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino Garcia <jespin", "end": 52, "score": 0.999931275844574, "start": 40, "tag": "EMAIL", "value": "niwi@niwi.be" }, { "context": " Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David B", "end": 94, "score": 0.9998799562454224, "start": 75, "tag": "NAME", "value": "Jesús Espino Garcia" }, { "context": "iwi.be>\n# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David Barragán Merino <bame", "end": 114, "score": 0.999934196472168, "start": 96, "tag": "EMAIL", "value": "jespinog@gmail.com" }, { "context": "o Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>\n#\n# This program is free s", "end": 158, "score": 0.9998828172683716, "start": 137, "tag": "NAME", "value": "David Barragán Merino" }, { "context": ".com>\n# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>\n#\n# This program is free software: you can redis", "end": 180, "score": 0.9999350309371948, "start": 160, "tag": "EMAIL", "value": "bameda@dbarragan.com" } ]
public/taiga-front/app/coffee/modules/backlog/sortable.coffee
mabotech/maboss
0
### # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com> # Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com> # # 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/>. # # File: modules/backlog/sortable.coffee ### taiga = @.taiga mixOf = @.taiga.mixOf toggleText = @.taiga.toggleText scopeDefer = @.taiga.scopeDefer bindOnce = @.taiga.bindOnce groupBy = @.taiga.groupBy module = angular.module("taigaBacklog") ############################################################################# ## Sortable Directive ############################################################################# deleteElement = (el) -> el.scope().$destroy() el.off() el.remove() BacklogSortableDirective = ($repo, $rs, $rootscope, $tgConfirm) -> # Notes about jquery bug: # http://stackoverflow.com/questions/5791886/jquery-draggable-shows- # helper-in-wrong-place-when-scrolled-down-page link = ($scope, $el, $attrs) -> bindOnce $scope, "project", (project) -> # If the user has not enough permissions we don't enable the sortable if not (project.my_permissions.indexOf("modify_us") > -1) return filterError = -> $tgConfirm.notify("error", "You can't drop on backlog when filters are open") #TODO: i18n $el.sortable({ connectWith: ".sprint-table" containment: ".wrapper" dropOnEmpty: true placeholder: "row us-item-row us-item-drag sortable-placeholder" scroll: true # A consequence of length of backlog user story item # the default tolerance ("intersection") not works properly. tolerance: "pointer" # Revert on backlog is disabled bacause it works bad. Something # on the current taiga backlog structure or style makes jquery ui # works unexpectly (in some circumstances calculates wrong # position for revert). revert: false cursorAt: {right: 15} stop: () -> if $el.hasClass("active-filters") $el.sortable("cancel") filterError() }) $el.on "multiplesortreceive", (event, ui) -> if $el.hasClass("active-filters") ui.source.sortable("cancel") filterError() return itemUs = ui.item.scope().us itemIndex = ui.item.index() deleteElement(ui.item) $scope.$emit("sprint:us:move", [itemUs], itemIndex, null) ui.item.find('a').removeClass('noclick') $el.on "multiplesortstop", (event, ui) -> # When parent not exists, do nothing if $(ui.items[0]).parent().length == 0 return items = _.sortBy ui.items, (item) -> return $(item).index() index = _.min _.map items, (item) -> return $(item).index() us = _.map items, (item) -> item = $(item) itemUs = item.scope().us # HACK: setTimeout prevents that firefox click # event fires just after drag ends setTimeout ( => item.find('a').removeClass('noclick') ), 300 return itemUs $scope.$emit("sprint:us:move", us, index, null) $el.on "sortstart", (event, ui) -> ui.item.find('a').addClass('noclick') $scope.$on "$destroy", -> $el.off() return {link: link} BacklogEmptySortableDirective = ($repo, $rs, $rootscope) -> # Notes about jquery bug: # http://stackoverflow.com/questions/5791886/jquery-draggable-shows- # helper-in-wrong-place-when-scrolled-down-page link = ($scope, $el, $attrs) -> bindOnce $scope, "project", (project) -> # If the user has not enough permissions we don't enable the sortable if project.my_permissions.indexOf("modify_us") > -1 $el.sortable({ dropOnEmpty: true }) $el.on "sortreceive", (event, ui) -> itemUs = ui.item.scope().us itemIndex = ui.item.index() deleteElement(ui.item) $scope.$emit("sprint:us:move", [itemUs], itemIndex, null) ui.item.find('a').removeClass('noclick') $scope.$on "$destroy", -> $el.off() return {link: link} SprintSortableDirective = ($repo, $rs, $rootscope) -> link = ($scope, $el, $attrs) -> bindOnce $scope, "project", (project) -> # If the user has not enough permissions we don't enable the sortable if project.my_permissions.indexOf("modify_us") > -1 $el.sortable({ scroll: true dropOnEmpty: true connectWith: ".sprint-table,.backlog-table-body,.empty-backlog" }) $el.on "multiplesortreceive", (event, ui) -> items = _.sortBy ui.items, (item) -> return $(item).index() index = _.min _.map items, (item) -> return $(item).index() us = _.map items, (item) -> item = $(item) itemUs = item.scope().us deleteElement(item) return itemUs $scope.$emit("sprint:us:move", us, index, $scope.sprint.id) $el.on "multiplesortstop", (event, ui) -> # When parent not exists, do nothing if ui.item.parent().length == 0 return itemUs = ui.item.scope().us itemIndex = ui.item.index() # HACK: setTimeout prevents that firefox click # event fires just after drag ends setTimeout ( => ui.item.find('a').removeClass('noclick') ), 300 $scope.$emit("sprint:us:move", [itemUs], itemIndex, $scope.sprint.id) $el.on "sortstart", (event, ui) -> ui.item.find('a').addClass('noclick') return {link:link} module.directive("tgBacklogSortable", [ "$tgRepo", "$tgResources", "$rootScope", "$tgConfirm", BacklogSortableDirective ]) module.directive("tgBacklogEmptySortable", [ "$tgRepo", "$tgResources", "$rootScope", BacklogEmptySortableDirective ]) module.directive("tgSprintSortable", [ "$tgRepo", "$tgResources", "$rootScope", SprintSortableDirective ])
47087
### # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # # 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/>. # # File: modules/backlog/sortable.coffee ### taiga = @.taiga mixOf = @.taiga.mixOf toggleText = @.taiga.toggleText scopeDefer = @.taiga.scopeDefer bindOnce = @.taiga.bindOnce groupBy = @.taiga.groupBy module = angular.module("taigaBacklog") ############################################################################# ## Sortable Directive ############################################################################# deleteElement = (el) -> el.scope().$destroy() el.off() el.remove() BacklogSortableDirective = ($repo, $rs, $rootscope, $tgConfirm) -> # Notes about jquery bug: # http://stackoverflow.com/questions/5791886/jquery-draggable-shows- # helper-in-wrong-place-when-scrolled-down-page link = ($scope, $el, $attrs) -> bindOnce $scope, "project", (project) -> # If the user has not enough permissions we don't enable the sortable if not (project.my_permissions.indexOf("modify_us") > -1) return filterError = -> $tgConfirm.notify("error", "You can't drop on backlog when filters are open") #TODO: i18n $el.sortable({ connectWith: ".sprint-table" containment: ".wrapper" dropOnEmpty: true placeholder: "row us-item-row us-item-drag sortable-placeholder" scroll: true # A consequence of length of backlog user story item # the default tolerance ("intersection") not works properly. tolerance: "pointer" # Revert on backlog is disabled bacause it works bad. Something # on the current taiga backlog structure or style makes jquery ui # works unexpectly (in some circumstances calculates wrong # position for revert). revert: false cursorAt: {right: 15} stop: () -> if $el.hasClass("active-filters") $el.sortable("cancel") filterError() }) $el.on "multiplesortreceive", (event, ui) -> if $el.hasClass("active-filters") ui.source.sortable("cancel") filterError() return itemUs = ui.item.scope().us itemIndex = ui.item.index() deleteElement(ui.item) $scope.$emit("sprint:us:move", [itemUs], itemIndex, null) ui.item.find('a').removeClass('noclick') $el.on "multiplesortstop", (event, ui) -> # When parent not exists, do nothing if $(ui.items[0]).parent().length == 0 return items = _.sortBy ui.items, (item) -> return $(item).index() index = _.min _.map items, (item) -> return $(item).index() us = _.map items, (item) -> item = $(item) itemUs = item.scope().us # HACK: setTimeout prevents that firefox click # event fires just after drag ends setTimeout ( => item.find('a').removeClass('noclick') ), 300 return itemUs $scope.$emit("sprint:us:move", us, index, null) $el.on "sortstart", (event, ui) -> ui.item.find('a').addClass('noclick') $scope.$on "$destroy", -> $el.off() return {link: link} BacklogEmptySortableDirective = ($repo, $rs, $rootscope) -> # Notes about jquery bug: # http://stackoverflow.com/questions/5791886/jquery-draggable-shows- # helper-in-wrong-place-when-scrolled-down-page link = ($scope, $el, $attrs) -> bindOnce $scope, "project", (project) -> # If the user has not enough permissions we don't enable the sortable if project.my_permissions.indexOf("modify_us") > -1 $el.sortable({ dropOnEmpty: true }) $el.on "sortreceive", (event, ui) -> itemUs = ui.item.scope().us itemIndex = ui.item.index() deleteElement(ui.item) $scope.$emit("sprint:us:move", [itemUs], itemIndex, null) ui.item.find('a').removeClass('noclick') $scope.$on "$destroy", -> $el.off() return {link: link} SprintSortableDirective = ($repo, $rs, $rootscope) -> link = ($scope, $el, $attrs) -> bindOnce $scope, "project", (project) -> # If the user has not enough permissions we don't enable the sortable if project.my_permissions.indexOf("modify_us") > -1 $el.sortable({ scroll: true dropOnEmpty: true connectWith: ".sprint-table,.backlog-table-body,.empty-backlog" }) $el.on "multiplesortreceive", (event, ui) -> items = _.sortBy ui.items, (item) -> return $(item).index() index = _.min _.map items, (item) -> return $(item).index() us = _.map items, (item) -> item = $(item) itemUs = item.scope().us deleteElement(item) return itemUs $scope.$emit("sprint:us:move", us, index, $scope.sprint.id) $el.on "multiplesortstop", (event, ui) -> # When parent not exists, do nothing if ui.item.parent().length == 0 return itemUs = ui.item.scope().us itemIndex = ui.item.index() # HACK: setTimeout prevents that firefox click # event fires just after drag ends setTimeout ( => ui.item.find('a').removeClass('noclick') ), 300 $scope.$emit("sprint:us:move", [itemUs], itemIndex, $scope.sprint.id) $el.on "sortstart", (event, ui) -> ui.item.find('a').addClass('noclick') return {link:link} module.directive("tgBacklogSortable", [ "$tgRepo", "$tgResources", "$rootScope", "$tgConfirm", BacklogSortableDirective ]) module.directive("tgBacklogEmptySortable", [ "$tgRepo", "$tgResources", "$rootScope", BacklogEmptySortableDirective ]) module.directive("tgSprintSortable", [ "$tgRepo", "$tgResources", "$rootScope", SprintSortableDirective ])
true
### # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # 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/>. # # File: modules/backlog/sortable.coffee ### taiga = @.taiga mixOf = @.taiga.mixOf toggleText = @.taiga.toggleText scopeDefer = @.taiga.scopeDefer bindOnce = @.taiga.bindOnce groupBy = @.taiga.groupBy module = angular.module("taigaBacklog") ############################################################################# ## Sortable Directive ############################################################################# deleteElement = (el) -> el.scope().$destroy() el.off() el.remove() BacklogSortableDirective = ($repo, $rs, $rootscope, $tgConfirm) -> # Notes about jquery bug: # http://stackoverflow.com/questions/5791886/jquery-draggable-shows- # helper-in-wrong-place-when-scrolled-down-page link = ($scope, $el, $attrs) -> bindOnce $scope, "project", (project) -> # If the user has not enough permissions we don't enable the sortable if not (project.my_permissions.indexOf("modify_us") > -1) return filterError = -> $tgConfirm.notify("error", "You can't drop on backlog when filters are open") #TODO: i18n $el.sortable({ connectWith: ".sprint-table" containment: ".wrapper" dropOnEmpty: true placeholder: "row us-item-row us-item-drag sortable-placeholder" scroll: true # A consequence of length of backlog user story item # the default tolerance ("intersection") not works properly. tolerance: "pointer" # Revert on backlog is disabled bacause it works bad. Something # on the current taiga backlog structure or style makes jquery ui # works unexpectly (in some circumstances calculates wrong # position for revert). revert: false cursorAt: {right: 15} stop: () -> if $el.hasClass("active-filters") $el.sortable("cancel") filterError() }) $el.on "multiplesortreceive", (event, ui) -> if $el.hasClass("active-filters") ui.source.sortable("cancel") filterError() return itemUs = ui.item.scope().us itemIndex = ui.item.index() deleteElement(ui.item) $scope.$emit("sprint:us:move", [itemUs], itemIndex, null) ui.item.find('a').removeClass('noclick') $el.on "multiplesortstop", (event, ui) -> # When parent not exists, do nothing if $(ui.items[0]).parent().length == 0 return items = _.sortBy ui.items, (item) -> return $(item).index() index = _.min _.map items, (item) -> return $(item).index() us = _.map items, (item) -> item = $(item) itemUs = item.scope().us # HACK: setTimeout prevents that firefox click # event fires just after drag ends setTimeout ( => item.find('a').removeClass('noclick') ), 300 return itemUs $scope.$emit("sprint:us:move", us, index, null) $el.on "sortstart", (event, ui) -> ui.item.find('a').addClass('noclick') $scope.$on "$destroy", -> $el.off() return {link: link} BacklogEmptySortableDirective = ($repo, $rs, $rootscope) -> # Notes about jquery bug: # http://stackoverflow.com/questions/5791886/jquery-draggable-shows- # helper-in-wrong-place-when-scrolled-down-page link = ($scope, $el, $attrs) -> bindOnce $scope, "project", (project) -> # If the user has not enough permissions we don't enable the sortable if project.my_permissions.indexOf("modify_us") > -1 $el.sortable({ dropOnEmpty: true }) $el.on "sortreceive", (event, ui) -> itemUs = ui.item.scope().us itemIndex = ui.item.index() deleteElement(ui.item) $scope.$emit("sprint:us:move", [itemUs], itemIndex, null) ui.item.find('a').removeClass('noclick') $scope.$on "$destroy", -> $el.off() return {link: link} SprintSortableDirective = ($repo, $rs, $rootscope) -> link = ($scope, $el, $attrs) -> bindOnce $scope, "project", (project) -> # If the user has not enough permissions we don't enable the sortable if project.my_permissions.indexOf("modify_us") > -1 $el.sortable({ scroll: true dropOnEmpty: true connectWith: ".sprint-table,.backlog-table-body,.empty-backlog" }) $el.on "multiplesortreceive", (event, ui) -> items = _.sortBy ui.items, (item) -> return $(item).index() index = _.min _.map items, (item) -> return $(item).index() us = _.map items, (item) -> item = $(item) itemUs = item.scope().us deleteElement(item) return itemUs $scope.$emit("sprint:us:move", us, index, $scope.sprint.id) $el.on "multiplesortstop", (event, ui) -> # When parent not exists, do nothing if ui.item.parent().length == 0 return itemUs = ui.item.scope().us itemIndex = ui.item.index() # HACK: setTimeout prevents that firefox click # event fires just after drag ends setTimeout ( => ui.item.find('a').removeClass('noclick') ), 300 $scope.$emit("sprint:us:move", [itemUs], itemIndex, $scope.sprint.id) $el.on "sortstart", (event, ui) -> ui.item.find('a').addClass('noclick') return {link:link} module.directive("tgBacklogSortable", [ "$tgRepo", "$tgResources", "$rootScope", "$tgConfirm", BacklogSortableDirective ]) module.directive("tgBacklogEmptySortable", [ "$tgRepo", "$tgResources", "$rootScope", BacklogEmptySortableDirective ]) module.directive("tgSprintSortable", [ "$tgRepo", "$tgResources", "$rootScope", SprintSortableDirective ])
[ { "context": "empMeshblu.identity uuid: 'invalid-uuid', token: 'invalid-token'\n @eventForwarder.on 'message', (message) ", "end": 10093, "score": 0.7354905605316162, "start": 10080, "tag": "KEY", "value": "invalid-token" } ]
integration/websocket-forwarder-spec.coffee
CESARBR/knot-cloud-source
4
_ = require 'lodash' path = require 'path' debug = require('debug')('meshblu:integration:websocket') MeshbluConfig = require 'meshblu-config' MeshbluHTTP = require 'meshblu-http' MeshbluWebsocket = require 'meshblu-websocket' MeshbluSocketLogic = require 'meshblu' describe 'WebSocket Forwarder Events', -> before (done) -> filename = path.join __dirname, 'meshblu.json' @config = new MeshbluConfig(filename: filename).toJSON() @eventForwarder = new MeshbluWebsocket @config @eventForwarder.connect => @eventForwarder.subscribe @config.uuid done() before (done) -> meshbluHTTP = new MeshbluHTTP _.pick @config, 'server', 'port' meshbluHTTP.register {}, (error, device) => return done error if error? @device = device @meshblu = new MeshbluWebsocket uuid: @device.uuid, token: @device.token, host: @config.host, protocol: @config.protocol @meshblu.connect (error) => done error @meshblu.on 'error', (error) => debug '@meshblu error', error it 'should get here', -> expect(true).to.be.true describe 'EVENT devices', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.devices {} @eventForwarder.on 'message', (message) => if message.topic == 'devices' @message = message @eventForwarder.removeAllListeners 'message' done() it 'should send a "devices" message', -> expect(@message.topic).to.deep.equal 'devices' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: {} } describe 'when called with an invalid request', -> beforeEach (done) -> @meshblu.devices {uuid: 'invalid-uuid'} @eventForwarder.once 'message', (@message) => done() it 'should send a "devices-error" message', -> expect(@message.topic).to.deep.equal 'devices-error' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid error: "Devices not found" request: uuid: 'invalid-uuid' } describe 'EVENT device', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.device @device.uuid @eventForwarder.once 'message', (@message) => done() it 'should send a "devices" message', -> expect(@message.topic).to.deep.equal 'devices' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: uuid: @device.uuid } describe 'when called with an invalid request', -> beforeEach (done) -> @meshblu.device 'invalid-uuid' @eventForwarder.once 'message', (@message) => done() it 'should send a "devices-error" message', -> expect(@message.topic).to.deep.equal 'devices-error' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid error: 'unauthorized' request: uuid: 'invalid-uuid' } describe 'EVENT whoami', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.whoami() @eventForwarder.once 'message', (@message) => done() it 'should send a "whoami" message', -> expect(@message.topic).to.deep.equal 'devices' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: {uuid: @device.uuid} } describe 'EVENT update', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.update {uuid: @device.uuid}, {foo: 'bar'} @eventForwarder.once 'message', (@message) => done() it 'should send a "update" message', -> expect(@message.topic).to.deep.equal 'update' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: query: {uuid: @device.uuid} params: {$set: {foo: 'bar'}} } describe 'when called with an invalid request', -> beforeEach (done) -> @meshblu.update {uuid: 'invalid-uuid'}, {foo: 'bar'} @eventForwarder.once 'message', (@message) => done() it 'should send an "update-error" message', -> expect(@message.topic).to.deep.equal 'update-error' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid error: "Device does not have sufficient permissions for update" request: query: {uuid: 'invalid-uuid'} params: {$set: {foo: 'bar'}} } describe 'EVENT register', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.register {foo: 'bar'} @eventForwarder.once 'message', (@message) => done() it 'should send a "register" message', -> expect(@message.topic).to.deep.equal 'register' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: {foo: 'bar'} } describe 'when called with an invalid request', -> beforeEach (done) -> @meshblu.register uuid: 'not-allowed' @eventForwarder.once 'message', (@message) => done() it 'should send an "register-error" message', -> expect(@message.topic).to.deep.equal 'register-error' expect(_.omit @message.payload, '_timestamp').to.deep.equal { error: 'Device not updated' fromUuid: @device.uuid request: uuid: 'not-allowed' } describe 'EVENT unregister', -> describe 'when called with a valid request without token', -> beforeEach (done) -> @meshblu.register {configureWhitelist: [@device.uuid]} @meshblu.once 'registered', (data) => @newDevice = data done() beforeEach (done) -> @meshblu.unregister uuid: @newDevice.uuid @eventForwarder.on 'message', (message) => if message.topic == 'unregister' @message = message @eventForwarder.removeAllListeners 'message' done() it 'should send a "unregister" message', -> expect(@message.topic).to.deep.equal 'unregister' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: {uuid: @newDevice.uuid} } describe 'when called with an invalid request', -> beforeEach (done) -> @meshblu.unregister uuid: 'invalid-uuid' @eventForwarder.once 'message', (@message) => done() it 'should send an "unregister-error" message', -> expect(@message.topic).to.deep.equal 'unregister-error' expect(_.omit @message.payload, '_timestamp').to.deep.equal { error: 'invalid device to unregister' fromUuid: @device.uuid request: {uuid: 'invalid-uuid'} } describe 'EVENT mydevices', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.register owner: @device.uuid, discoverWhitelist: [@device.uuid] @meshblu.once 'registered', (data) => @newDevice = data done() beforeEach (done) -> @meshblu.mydevices() @eventForwarder.on 'message', (message) => if message.topic == 'devices' @message = message @eventForwarder.removeAllListeners 'message' done() it 'should send a "devices" message', -> expect(@message.topic).to.deep.equal 'devices' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: owner: @device.uuid } describe 'EVENT subscribe', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.subscribe @device.uuid @eventForwarder.once 'message', (@message) => done() it 'should send a "subscribe" message', -> expect(@message.topic).to.deep.equal 'subscribe' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: uuid: @device.uuid } describe 'EVENT unsubscribe', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.unsubscribe @device.uuid @eventForwarder.once 'message', (@message) => done() it 'should send a "unsubscribe" message', -> expect(@message.topic).to.deep.equal 'unsubscribe' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: uuid: @device.uuid } describe 'EVENT identity', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.identity uuid: @device.uuid, token: @device.token @eventForwarder.once 'message', (@message) => done() it 'should send a "identity" message', -> expect(@message.topic).to.deep.equal 'identity' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: uuid: @device.uuid } describe 'when called with an invalid request', -> beforeEach (done) -> @meshblu.register() @meshblu.on 'registered', (device) => @newDevice = device done() beforeEach (done) -> @tempMeshblu = new MeshbluWebsocket uuid: @newDevice.uuid, token: @newDevice.token, host: @config.host, protocol: @config.protocol @tempMeshblu.connect (error) => done error @tempMeshblu.on 'error', (error) => debug '@tempMeshblu error', error beforeEach (done) -> @tempMeshblu.identity uuid: 'invalid-uuid', token: 'invalid-token' @eventForwarder.on 'message', (message) => if message.topic == 'identity-error' @message = message @eventForwarder.removeAllListeners 'message' done() it 'should send a "identity-error" message', -> expect(@message.topic).to.deep.equal 'identity-error' expect(_.omit @message.payload, '_timestamp').to.deep.equal { error: "Invalid Device UUID" fromUuid: 'invalid-uuid' request: uuid: 'invalid-uuid' } describe 'EVENT message', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.message {devices: ['some-uuid']} @eventForwarder.on 'message', (message) => if message.topic == 'message' @message = message @eventForwarder.removeAllListeners 'message' done() it 'should send a "message" message', -> expect(@message.topic).to.deep.equal 'message' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: devices: ['some-uuid'] }
199668
_ = require 'lodash' path = require 'path' debug = require('debug')('meshblu:integration:websocket') MeshbluConfig = require 'meshblu-config' MeshbluHTTP = require 'meshblu-http' MeshbluWebsocket = require 'meshblu-websocket' MeshbluSocketLogic = require 'meshblu' describe 'WebSocket Forwarder Events', -> before (done) -> filename = path.join __dirname, 'meshblu.json' @config = new MeshbluConfig(filename: filename).toJSON() @eventForwarder = new MeshbluWebsocket @config @eventForwarder.connect => @eventForwarder.subscribe @config.uuid done() before (done) -> meshbluHTTP = new MeshbluHTTP _.pick @config, 'server', 'port' meshbluHTTP.register {}, (error, device) => return done error if error? @device = device @meshblu = new MeshbluWebsocket uuid: @device.uuid, token: @device.token, host: @config.host, protocol: @config.protocol @meshblu.connect (error) => done error @meshblu.on 'error', (error) => debug '@meshblu error', error it 'should get here', -> expect(true).to.be.true describe 'EVENT devices', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.devices {} @eventForwarder.on 'message', (message) => if message.topic == 'devices' @message = message @eventForwarder.removeAllListeners 'message' done() it 'should send a "devices" message', -> expect(@message.topic).to.deep.equal 'devices' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: {} } describe 'when called with an invalid request', -> beforeEach (done) -> @meshblu.devices {uuid: 'invalid-uuid'} @eventForwarder.once 'message', (@message) => done() it 'should send a "devices-error" message', -> expect(@message.topic).to.deep.equal 'devices-error' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid error: "Devices not found" request: uuid: 'invalid-uuid' } describe 'EVENT device', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.device @device.uuid @eventForwarder.once 'message', (@message) => done() it 'should send a "devices" message', -> expect(@message.topic).to.deep.equal 'devices' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: uuid: @device.uuid } describe 'when called with an invalid request', -> beforeEach (done) -> @meshblu.device 'invalid-uuid' @eventForwarder.once 'message', (@message) => done() it 'should send a "devices-error" message', -> expect(@message.topic).to.deep.equal 'devices-error' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid error: 'unauthorized' request: uuid: 'invalid-uuid' } describe 'EVENT whoami', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.whoami() @eventForwarder.once 'message', (@message) => done() it 'should send a "whoami" message', -> expect(@message.topic).to.deep.equal 'devices' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: {uuid: @device.uuid} } describe 'EVENT update', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.update {uuid: @device.uuid}, {foo: 'bar'} @eventForwarder.once 'message', (@message) => done() it 'should send a "update" message', -> expect(@message.topic).to.deep.equal 'update' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: query: {uuid: @device.uuid} params: {$set: {foo: 'bar'}} } describe 'when called with an invalid request', -> beforeEach (done) -> @meshblu.update {uuid: 'invalid-uuid'}, {foo: 'bar'} @eventForwarder.once 'message', (@message) => done() it 'should send an "update-error" message', -> expect(@message.topic).to.deep.equal 'update-error' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid error: "Device does not have sufficient permissions for update" request: query: {uuid: 'invalid-uuid'} params: {$set: {foo: 'bar'}} } describe 'EVENT register', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.register {foo: 'bar'} @eventForwarder.once 'message', (@message) => done() it 'should send a "register" message', -> expect(@message.topic).to.deep.equal 'register' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: {foo: 'bar'} } describe 'when called with an invalid request', -> beforeEach (done) -> @meshblu.register uuid: 'not-allowed' @eventForwarder.once 'message', (@message) => done() it 'should send an "register-error" message', -> expect(@message.topic).to.deep.equal 'register-error' expect(_.omit @message.payload, '_timestamp').to.deep.equal { error: 'Device not updated' fromUuid: @device.uuid request: uuid: 'not-allowed' } describe 'EVENT unregister', -> describe 'when called with a valid request without token', -> beforeEach (done) -> @meshblu.register {configureWhitelist: [@device.uuid]} @meshblu.once 'registered', (data) => @newDevice = data done() beforeEach (done) -> @meshblu.unregister uuid: @newDevice.uuid @eventForwarder.on 'message', (message) => if message.topic == 'unregister' @message = message @eventForwarder.removeAllListeners 'message' done() it 'should send a "unregister" message', -> expect(@message.topic).to.deep.equal 'unregister' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: {uuid: @newDevice.uuid} } describe 'when called with an invalid request', -> beforeEach (done) -> @meshblu.unregister uuid: 'invalid-uuid' @eventForwarder.once 'message', (@message) => done() it 'should send an "unregister-error" message', -> expect(@message.topic).to.deep.equal 'unregister-error' expect(_.omit @message.payload, '_timestamp').to.deep.equal { error: 'invalid device to unregister' fromUuid: @device.uuid request: {uuid: 'invalid-uuid'} } describe 'EVENT mydevices', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.register owner: @device.uuid, discoverWhitelist: [@device.uuid] @meshblu.once 'registered', (data) => @newDevice = data done() beforeEach (done) -> @meshblu.mydevices() @eventForwarder.on 'message', (message) => if message.topic == 'devices' @message = message @eventForwarder.removeAllListeners 'message' done() it 'should send a "devices" message', -> expect(@message.topic).to.deep.equal 'devices' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: owner: @device.uuid } describe 'EVENT subscribe', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.subscribe @device.uuid @eventForwarder.once 'message', (@message) => done() it 'should send a "subscribe" message', -> expect(@message.topic).to.deep.equal 'subscribe' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: uuid: @device.uuid } describe 'EVENT unsubscribe', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.unsubscribe @device.uuid @eventForwarder.once 'message', (@message) => done() it 'should send a "unsubscribe" message', -> expect(@message.topic).to.deep.equal 'unsubscribe' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: uuid: @device.uuid } describe 'EVENT identity', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.identity uuid: @device.uuid, token: @device.token @eventForwarder.once 'message', (@message) => done() it 'should send a "identity" message', -> expect(@message.topic).to.deep.equal 'identity' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: uuid: @device.uuid } describe 'when called with an invalid request', -> beforeEach (done) -> @meshblu.register() @meshblu.on 'registered', (device) => @newDevice = device done() beforeEach (done) -> @tempMeshblu = new MeshbluWebsocket uuid: @newDevice.uuid, token: @newDevice.token, host: @config.host, protocol: @config.protocol @tempMeshblu.connect (error) => done error @tempMeshblu.on 'error', (error) => debug '@tempMeshblu error', error beforeEach (done) -> @tempMeshblu.identity uuid: 'invalid-uuid', token: '<KEY>' @eventForwarder.on 'message', (message) => if message.topic == 'identity-error' @message = message @eventForwarder.removeAllListeners 'message' done() it 'should send a "identity-error" message', -> expect(@message.topic).to.deep.equal 'identity-error' expect(_.omit @message.payload, '_timestamp').to.deep.equal { error: "Invalid Device UUID" fromUuid: 'invalid-uuid' request: uuid: 'invalid-uuid' } describe 'EVENT message', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.message {devices: ['some-uuid']} @eventForwarder.on 'message', (message) => if message.topic == 'message' @message = message @eventForwarder.removeAllListeners 'message' done() it 'should send a "message" message', -> expect(@message.topic).to.deep.equal 'message' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: devices: ['some-uuid'] }
true
_ = require 'lodash' path = require 'path' debug = require('debug')('meshblu:integration:websocket') MeshbluConfig = require 'meshblu-config' MeshbluHTTP = require 'meshblu-http' MeshbluWebsocket = require 'meshblu-websocket' MeshbluSocketLogic = require 'meshblu' describe 'WebSocket Forwarder Events', -> before (done) -> filename = path.join __dirname, 'meshblu.json' @config = new MeshbluConfig(filename: filename).toJSON() @eventForwarder = new MeshbluWebsocket @config @eventForwarder.connect => @eventForwarder.subscribe @config.uuid done() before (done) -> meshbluHTTP = new MeshbluHTTP _.pick @config, 'server', 'port' meshbluHTTP.register {}, (error, device) => return done error if error? @device = device @meshblu = new MeshbluWebsocket uuid: @device.uuid, token: @device.token, host: @config.host, protocol: @config.protocol @meshblu.connect (error) => done error @meshblu.on 'error', (error) => debug '@meshblu error', error it 'should get here', -> expect(true).to.be.true describe 'EVENT devices', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.devices {} @eventForwarder.on 'message', (message) => if message.topic == 'devices' @message = message @eventForwarder.removeAllListeners 'message' done() it 'should send a "devices" message', -> expect(@message.topic).to.deep.equal 'devices' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: {} } describe 'when called with an invalid request', -> beforeEach (done) -> @meshblu.devices {uuid: 'invalid-uuid'} @eventForwarder.once 'message', (@message) => done() it 'should send a "devices-error" message', -> expect(@message.topic).to.deep.equal 'devices-error' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid error: "Devices not found" request: uuid: 'invalid-uuid' } describe 'EVENT device', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.device @device.uuid @eventForwarder.once 'message', (@message) => done() it 'should send a "devices" message', -> expect(@message.topic).to.deep.equal 'devices' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: uuid: @device.uuid } describe 'when called with an invalid request', -> beforeEach (done) -> @meshblu.device 'invalid-uuid' @eventForwarder.once 'message', (@message) => done() it 'should send a "devices-error" message', -> expect(@message.topic).to.deep.equal 'devices-error' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid error: 'unauthorized' request: uuid: 'invalid-uuid' } describe 'EVENT whoami', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.whoami() @eventForwarder.once 'message', (@message) => done() it 'should send a "whoami" message', -> expect(@message.topic).to.deep.equal 'devices' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: {uuid: @device.uuid} } describe 'EVENT update', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.update {uuid: @device.uuid}, {foo: 'bar'} @eventForwarder.once 'message', (@message) => done() it 'should send a "update" message', -> expect(@message.topic).to.deep.equal 'update' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: query: {uuid: @device.uuid} params: {$set: {foo: 'bar'}} } describe 'when called with an invalid request', -> beforeEach (done) -> @meshblu.update {uuid: 'invalid-uuid'}, {foo: 'bar'} @eventForwarder.once 'message', (@message) => done() it 'should send an "update-error" message', -> expect(@message.topic).to.deep.equal 'update-error' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid error: "Device does not have sufficient permissions for update" request: query: {uuid: 'invalid-uuid'} params: {$set: {foo: 'bar'}} } describe 'EVENT register', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.register {foo: 'bar'} @eventForwarder.once 'message', (@message) => done() it 'should send a "register" message', -> expect(@message.topic).to.deep.equal 'register' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: {foo: 'bar'} } describe 'when called with an invalid request', -> beforeEach (done) -> @meshblu.register uuid: 'not-allowed' @eventForwarder.once 'message', (@message) => done() it 'should send an "register-error" message', -> expect(@message.topic).to.deep.equal 'register-error' expect(_.omit @message.payload, '_timestamp').to.deep.equal { error: 'Device not updated' fromUuid: @device.uuid request: uuid: 'not-allowed' } describe 'EVENT unregister', -> describe 'when called with a valid request without token', -> beforeEach (done) -> @meshblu.register {configureWhitelist: [@device.uuid]} @meshblu.once 'registered', (data) => @newDevice = data done() beforeEach (done) -> @meshblu.unregister uuid: @newDevice.uuid @eventForwarder.on 'message', (message) => if message.topic == 'unregister' @message = message @eventForwarder.removeAllListeners 'message' done() it 'should send a "unregister" message', -> expect(@message.topic).to.deep.equal 'unregister' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: {uuid: @newDevice.uuid} } describe 'when called with an invalid request', -> beforeEach (done) -> @meshblu.unregister uuid: 'invalid-uuid' @eventForwarder.once 'message', (@message) => done() it 'should send an "unregister-error" message', -> expect(@message.topic).to.deep.equal 'unregister-error' expect(_.omit @message.payload, '_timestamp').to.deep.equal { error: 'invalid device to unregister' fromUuid: @device.uuid request: {uuid: 'invalid-uuid'} } describe 'EVENT mydevices', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.register owner: @device.uuid, discoverWhitelist: [@device.uuid] @meshblu.once 'registered', (data) => @newDevice = data done() beforeEach (done) -> @meshblu.mydevices() @eventForwarder.on 'message', (message) => if message.topic == 'devices' @message = message @eventForwarder.removeAllListeners 'message' done() it 'should send a "devices" message', -> expect(@message.topic).to.deep.equal 'devices' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: owner: @device.uuid } describe 'EVENT subscribe', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.subscribe @device.uuid @eventForwarder.once 'message', (@message) => done() it 'should send a "subscribe" message', -> expect(@message.topic).to.deep.equal 'subscribe' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: uuid: @device.uuid } describe 'EVENT unsubscribe', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.unsubscribe @device.uuid @eventForwarder.once 'message', (@message) => done() it 'should send a "unsubscribe" message', -> expect(@message.topic).to.deep.equal 'unsubscribe' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: uuid: @device.uuid } describe 'EVENT identity', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.identity uuid: @device.uuid, token: @device.token @eventForwarder.once 'message', (@message) => done() it 'should send a "identity" message', -> expect(@message.topic).to.deep.equal 'identity' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: uuid: @device.uuid } describe 'when called with an invalid request', -> beforeEach (done) -> @meshblu.register() @meshblu.on 'registered', (device) => @newDevice = device done() beforeEach (done) -> @tempMeshblu = new MeshbluWebsocket uuid: @newDevice.uuid, token: @newDevice.token, host: @config.host, protocol: @config.protocol @tempMeshblu.connect (error) => done error @tempMeshblu.on 'error', (error) => debug '@tempMeshblu error', error beforeEach (done) -> @tempMeshblu.identity uuid: 'invalid-uuid', token: 'PI:KEY:<KEY>END_PI' @eventForwarder.on 'message', (message) => if message.topic == 'identity-error' @message = message @eventForwarder.removeAllListeners 'message' done() it 'should send a "identity-error" message', -> expect(@message.topic).to.deep.equal 'identity-error' expect(_.omit @message.payload, '_timestamp').to.deep.equal { error: "Invalid Device UUID" fromUuid: 'invalid-uuid' request: uuid: 'invalid-uuid' } describe 'EVENT message', -> describe 'when called with a valid request', -> beforeEach (done) -> @meshblu.message {devices: ['some-uuid']} @eventForwarder.on 'message', (message) => if message.topic == 'message' @message = message @eventForwarder.removeAllListeners 'message' done() it 'should send a "message" message', -> expect(@message.topic).to.deep.equal 'message' expect(_.omit @message.payload, '_timestamp').to.deep.equal { fromUuid: @device.uuid request: devices: ['some-uuid'] }
[ { "context": "T')\n events : events\n user : 'contact@courseshark.com'\n data\n\n\n Schedule\n)", "end": 4848, "score": 0.9999251365661621, "start": 4825, "tag": "EMAIL", "value": "contact@courseshark.com" } ]
public/scripts/backbone-schedule/models/schedule.coffee
courseshark/courseshark
1
define(['jQuery' 'Underscore' 'Backbone' 'models/model' 'dateFormat' 'collections/schedule-sections' 'models/course' 'models/section' 'text!tmpl/scheduler/schedule/downloads/ics.ejs'], ($, _, Backbone, SharkModel, dateFormat, ScheduleSections, Course, Section, icsTemplate) -> class Schedule extends SharkModel idAttribute: "_id" urlRoot: "/schedules/" defaults: name: "" sections: new ScheduleSections initialize: -> @icsDownloadTemplate = _.template icsTemplate.replace(/\n/g, '#\n').trim() toJSON: -> res = {} for prop of @attributes if typeof @attributes[prop] is 'object' res[prop] = _.clone(@attributes[prop].toJSON?()) else res[prop] = _.clone(@attributes[prop]) return res; new: (term) -> @.unset '__v' @.unset '_id' @.set 'name', '' @.get('sections').reset() @.set 'term', term or Shark.term load: (success) -> @.fetch error: -> console.log '[error] could not load schedule' success: => # Set the global term to this schedule's @setLive(success) setLive: (success) -> Shark.term = @.get 'term' # Set the sections Shark.schedule.get('sections').reset() @.get('sections').each (section) -> Shark.schedule.get('sections').add section # Set the other properties (minus sections) # Here we make a clone, then unset the sections attribute # If we dont do this, then all the views that bind to the # schedule's sections list will become unbound. setClone = @.clone() setClone.unset 'sections' Shark.schedule.set setClone success?() # Trigger the loaded event Shark.schedule.trigger 'load' ensureScheduleLoaded: (id, options) -> if typeof options is 'function' options.success = options if @.id is id options.success?() return schedule = Shark.schedulesList.get id if schedule schedule.load options.success return else Shark.schedulesList.fetch success: -> schedule = Shark.schedulesList.get id if schedule schedule.load options.success else options.failure?() parse: (response) -> response = response[0] if response.length > 0 if response.sections response.sections = new ScheduleSections response.sections.map (s) -> s.course = (new Course s.course).id s response.term = Shark.terms.get response.term response addSection: (section) -> @.get('sections').add section removeSection: (section) -> @.get('sections').remove @.get('sections').get(section.get('_id')) contains: (section) -> @.get('sections').where({_id: section.get('_id')}).length > 0 # Exports the schedule into a .ics file export: -> resultLink = 'data:text/Calendar;base64,' icsTxt = @icsDownloadTemplate @_generateIcsData() icsTxt = icsTxt.replace(/#\s*/g, "\r\n").trim() resultLink+$.base64.encode(icsTxt) # Helper function to generate the ics file on export _generateIcsData: -> days = 'monday' : 'MO' 'tuesday' : 'TU' 'wednesday' : 'WE' 'thursday' : 'TH' 'friday' : 'FR' 'saturday' : 'SA' 'sunday' : 'SU' events = [] for section in @.get('sections').models evnt = name : section.get('name').replace(/\s?#[0-9]+$/,'') daysets : [] timeCombine = {} timeCombineTime = {} for ts in section.get 'timeslots' startTime = new Date ts.startTime endTime = new Date ts.endTime endDate = (new Date ts.endDate).format('yyyymmdd') startString = startTime.format('yyyymmdd HHMMss').replace(' ','T') endString = endTime.format('yyyymmdd HHMMss').replace(' ','T') k = startString+'---'+endString if not timeCombine[k] timeCombine[k] = [] timeCombineTime[k] = 'start' : startString 'end' : endString 'location' : ts.location.toString() 'endDate' : endDate+'T'+endTime.format("HHMMss") timeCombine[k] = ts.days.map (v,i) -> days[v] for timeStr of timeCombine evnt['daysets'].push $.extend timeCombineTime[timeStr], days: timeCombine[timeStr].join ',' events.push evnt now = new Date() data = name : this.name timezone : 'America/New_York' now : now.format('yyyymmdd HHMMss').replace(' ','T') events : events user : 'contact@courseshark.com' data Schedule )
199550
define(['jQuery' 'Underscore' 'Backbone' 'models/model' 'dateFormat' 'collections/schedule-sections' 'models/course' 'models/section' 'text!tmpl/scheduler/schedule/downloads/ics.ejs'], ($, _, Backbone, SharkModel, dateFormat, ScheduleSections, Course, Section, icsTemplate) -> class Schedule extends SharkModel idAttribute: "_id" urlRoot: "/schedules/" defaults: name: "" sections: new ScheduleSections initialize: -> @icsDownloadTemplate = _.template icsTemplate.replace(/\n/g, '#\n').trim() toJSON: -> res = {} for prop of @attributes if typeof @attributes[prop] is 'object' res[prop] = _.clone(@attributes[prop].toJSON?()) else res[prop] = _.clone(@attributes[prop]) return res; new: (term) -> @.unset '__v' @.unset '_id' @.set 'name', '' @.get('sections').reset() @.set 'term', term or Shark.term load: (success) -> @.fetch error: -> console.log '[error] could not load schedule' success: => # Set the global term to this schedule's @setLive(success) setLive: (success) -> Shark.term = @.get 'term' # Set the sections Shark.schedule.get('sections').reset() @.get('sections').each (section) -> Shark.schedule.get('sections').add section # Set the other properties (minus sections) # Here we make a clone, then unset the sections attribute # If we dont do this, then all the views that bind to the # schedule's sections list will become unbound. setClone = @.clone() setClone.unset 'sections' Shark.schedule.set setClone success?() # Trigger the loaded event Shark.schedule.trigger 'load' ensureScheduleLoaded: (id, options) -> if typeof options is 'function' options.success = options if @.id is id options.success?() return schedule = Shark.schedulesList.get id if schedule schedule.load options.success return else Shark.schedulesList.fetch success: -> schedule = Shark.schedulesList.get id if schedule schedule.load options.success else options.failure?() parse: (response) -> response = response[0] if response.length > 0 if response.sections response.sections = new ScheduleSections response.sections.map (s) -> s.course = (new Course s.course).id s response.term = Shark.terms.get response.term response addSection: (section) -> @.get('sections').add section removeSection: (section) -> @.get('sections').remove @.get('sections').get(section.get('_id')) contains: (section) -> @.get('sections').where({_id: section.get('_id')}).length > 0 # Exports the schedule into a .ics file export: -> resultLink = 'data:text/Calendar;base64,' icsTxt = @icsDownloadTemplate @_generateIcsData() icsTxt = icsTxt.replace(/#\s*/g, "\r\n").trim() resultLink+$.base64.encode(icsTxt) # Helper function to generate the ics file on export _generateIcsData: -> days = 'monday' : 'MO' 'tuesday' : 'TU' 'wednesday' : 'WE' 'thursday' : 'TH' 'friday' : 'FR' 'saturday' : 'SA' 'sunday' : 'SU' events = [] for section in @.get('sections').models evnt = name : section.get('name').replace(/\s?#[0-9]+$/,'') daysets : [] timeCombine = {} timeCombineTime = {} for ts in section.get 'timeslots' startTime = new Date ts.startTime endTime = new Date ts.endTime endDate = (new Date ts.endDate).format('yyyymmdd') startString = startTime.format('yyyymmdd HHMMss').replace(' ','T') endString = endTime.format('yyyymmdd HHMMss').replace(' ','T') k = startString+'---'+endString if not timeCombine[k] timeCombine[k] = [] timeCombineTime[k] = 'start' : startString 'end' : endString 'location' : ts.location.toString() 'endDate' : endDate+'T'+endTime.format("HHMMss") timeCombine[k] = ts.days.map (v,i) -> days[v] for timeStr of timeCombine evnt['daysets'].push $.extend timeCombineTime[timeStr], days: timeCombine[timeStr].join ',' events.push evnt now = new Date() data = name : this.name timezone : 'America/New_York' now : now.format('yyyymmdd HHMMss').replace(' ','T') events : events user : '<EMAIL>' data Schedule )
true
define(['jQuery' 'Underscore' 'Backbone' 'models/model' 'dateFormat' 'collections/schedule-sections' 'models/course' 'models/section' 'text!tmpl/scheduler/schedule/downloads/ics.ejs'], ($, _, Backbone, SharkModel, dateFormat, ScheduleSections, Course, Section, icsTemplate) -> class Schedule extends SharkModel idAttribute: "_id" urlRoot: "/schedules/" defaults: name: "" sections: new ScheduleSections initialize: -> @icsDownloadTemplate = _.template icsTemplate.replace(/\n/g, '#\n').trim() toJSON: -> res = {} for prop of @attributes if typeof @attributes[prop] is 'object' res[prop] = _.clone(@attributes[prop].toJSON?()) else res[prop] = _.clone(@attributes[prop]) return res; new: (term) -> @.unset '__v' @.unset '_id' @.set 'name', '' @.get('sections').reset() @.set 'term', term or Shark.term load: (success) -> @.fetch error: -> console.log '[error] could not load schedule' success: => # Set the global term to this schedule's @setLive(success) setLive: (success) -> Shark.term = @.get 'term' # Set the sections Shark.schedule.get('sections').reset() @.get('sections').each (section) -> Shark.schedule.get('sections').add section # Set the other properties (minus sections) # Here we make a clone, then unset the sections attribute # If we dont do this, then all the views that bind to the # schedule's sections list will become unbound. setClone = @.clone() setClone.unset 'sections' Shark.schedule.set setClone success?() # Trigger the loaded event Shark.schedule.trigger 'load' ensureScheduleLoaded: (id, options) -> if typeof options is 'function' options.success = options if @.id is id options.success?() return schedule = Shark.schedulesList.get id if schedule schedule.load options.success return else Shark.schedulesList.fetch success: -> schedule = Shark.schedulesList.get id if schedule schedule.load options.success else options.failure?() parse: (response) -> response = response[0] if response.length > 0 if response.sections response.sections = new ScheduleSections response.sections.map (s) -> s.course = (new Course s.course).id s response.term = Shark.terms.get response.term response addSection: (section) -> @.get('sections').add section removeSection: (section) -> @.get('sections').remove @.get('sections').get(section.get('_id')) contains: (section) -> @.get('sections').where({_id: section.get('_id')}).length > 0 # Exports the schedule into a .ics file export: -> resultLink = 'data:text/Calendar;base64,' icsTxt = @icsDownloadTemplate @_generateIcsData() icsTxt = icsTxt.replace(/#\s*/g, "\r\n").trim() resultLink+$.base64.encode(icsTxt) # Helper function to generate the ics file on export _generateIcsData: -> days = 'monday' : 'MO' 'tuesday' : 'TU' 'wednesday' : 'WE' 'thursday' : 'TH' 'friday' : 'FR' 'saturday' : 'SA' 'sunday' : 'SU' events = [] for section in @.get('sections').models evnt = name : section.get('name').replace(/\s?#[0-9]+$/,'') daysets : [] timeCombine = {} timeCombineTime = {} for ts in section.get 'timeslots' startTime = new Date ts.startTime endTime = new Date ts.endTime endDate = (new Date ts.endDate).format('yyyymmdd') startString = startTime.format('yyyymmdd HHMMss').replace(' ','T') endString = endTime.format('yyyymmdd HHMMss').replace(' ','T') k = startString+'---'+endString if not timeCombine[k] timeCombine[k] = [] timeCombineTime[k] = 'start' : startString 'end' : endString 'location' : ts.location.toString() 'endDate' : endDate+'T'+endTime.format("HHMMss") timeCombine[k] = ts.days.map (v,i) -> days[v] for timeStr of timeCombine evnt['daysets'].push $.extend timeCombineTime[timeStr], days: timeCombine[timeStr].join ',' events.push evnt now = new Date() data = name : this.name timezone : 'America/New_York' now : now.format('yyyymmdd HHMMss').replace(' ','T') events : events user : 'PI:EMAIL:<EMAIL>END_PI' data Schedule )
[ { "context": "ount/login', {\n email: email,\n password: password\n }, (err, resp, metaData) =>\n\n if err i", "end": 1754, "score": 0.998742938041687, "start": 1746, "tag": "PASSWORD", "value": "password" }, { "context": "posted, then edited)\n # See https://github.com/anroots/hubot-fleep/issues/4\n if event.revision_messag", "end": 5202, "score": 0.9996906518936157, "start": 5195, "tag": "USERNAME", "value": "anroots" } ]
src/fleepClient.coffee
jimeh/hubot-fleep
0
{EventEmitter} = require 'events' {TextMessage, EnterMessage, LeaveMessage, TopicMessage} = require 'hubot' WebRequest = require './webRequest' Util = require './util' async = require 'async' S = require 'string' module.exports = class FleepClient extends EventEmitter constructor: (@options, @robot) -> @ticket = null @token_id = null # Fleep profile info for the bot user @profile = account_id : null, display_name : null @on 'pollcomplete', (resp) => @robot.logger.debug 'Poll complete' @handleStreamEvents resp @poll() # Send a POST request to Fleep post: (path, body = {}, callback = ->) -> request = new WebRequest @robot.logger, @ticket, @token_id request.post path, body, (error, response, metaData) => if response?.ticket? @robot.logger.debug "Response contains ticket: #{response.ticket}" @ticket = response.ticket if metaData?.token_id? @robot.logger.debug 'Response contains token_id: ' + metaData.token_id @token_id = metaData.token_id callback error, response, metaData # Return the ID of the last seen Fleep event horizon getLastEventHorizon: -> last = @robot.brain.get 'fleep_last_horizon' @robot.logger.debug 'Last event horizon from robot brain: '+last last or 0 # Set the last seen Fleep event horizon to robot brain setLastEventHorizon: (horizon) -> @robot.brain.set 'fleep_last_horizon', horizon # Login to Fleep with the specified email and password # Creates a new session with Fleep and sets the token_id and ticket vars login: (email, password) => @robot.logger.debug 'Attempting to log in...' @post 'account/login', { email: email, password: password }, (err, resp, metaData) => if err isnt null @robot.logger.emergency 'Unable to login to Fleep: ' + err.error_message process.exit 1 # Save Fleep profile info @profile.account_id = resp.account_id @profile.display_name = resp.display_name # Tell Hubot we're connected so it can load scripts @robot.logger.info "Successfully connected #{@options.name} with Fleep" @emit 'authenticated', @ # Destroy Fleep session logout: -> @post 'account/logout', {}, (err, resp) -> if err isnt null return @robot.logger.error 'Unable to destroy Fleep session' @robot.logger.debug 'User session with Fleep closed.' # The result of a long poll request to account/poll is passed here # Handle all of its 'stream' items (conversations, contacts...) ie # events that happened during the poll request handleStreamEvents: (resp) => # The poll response gives us our next "last seen" event horizon if resp.event_horizon? @setLastEventHorizon resp.event_horizon @robot.logger.debug 'Updating last seen event horizon to '+ resp.event_horizon # Handle stream items individually if resp.stream? and resp.stream.length @handleStreamEvent event for event in resp.stream else @robot.logger.debug 'Response stream length 0, nothing to parse.' @robot.logger.debug 'Finished handling long poll response' # Save the conversation into the internal "known conversations" list # The message number indicates the last known seen message saveConversation: (conversation_id, message_nr) => conversations = @getKnownConversations() conversations[conversation_id] = {last_message_nr:message_nr} @robot.brain.set 'conversations', conversations @markRead conversation_id, message_nr # Processes a single Event object in a list of Fleep events handleStreamEvent: (event) => @robot.logger.debug 'Handling event: '+JSON.stringify event eventRecType = event.mk_rec_type or null # Event does not have a rec_type, API error? if eventRecType is null @robot.logger.error 'Invalid response from the server, no rec_type' return # New contact information if eventRecType is 'contact' user = @robot.brain.userForId event.account_id # Save the contact name if it's currently unknown if not user.name? or user.name is user.id user.name = event.display_name @robot.logger.debug "New contact: id #{user.id}, name #{user.name}" if not user.email? and event.email? user.email = event.email return # Skip everything but text message events if eventRecType isnt 'message' @robot.logger.debug 'Skipping stream item ' + eventRecType + ', not a message type of event' return # Detected a new conversation unless @getKnownConversations()?[event.conversation_id]? @robot.logger.debug "New conversation! Conversation " + "#{event.conversation_id} was not in the list of monitored " + "conversations, adding it now" @saveConversation event.conversation_id, event.message_nr return # This message is an echo of our own message, ignore if event.account_id is @profile.account_id @robot.logger.debug 'It is my own message, ignore it' return # Ignore edited messages (messages that were posted, then edited) # See https://github.com/anroots/hubot-fleep/issues/4 if event.revision_message_nr? and event.mk_message_type isnt 'topic' @robot.logger.debug 'This is an edited message, skipping...' return # Patch the received text message to Hubot @handleMessage event # Determines whether a particular message in # a particular message has been seen isMessageSeen: (conversation_id, message_nr) => @getKnownConversations()?[conversation_id]?['last_message_nr'] >= message_nr # Parses an incoming message and passes it to Hubot # Message is a Fleep event response object handleMessage: (message) => messageText = message.message or null conversationId = message.conversation_id or null # Extract the message type. One of text|kick|topic|add messageType = message.mk_message_type or null if messageType is 'topic' # A topic message is funny. It's number is in message_nr # unless the topic was edited before some other message was posted. # Then we need to fetch it's message number from revision_message_nr messageNumber = message.message_nr or message.revision_message_nr else messageNumber = message.message_nr or null # Do nothing if the message is already seen if @isMessageSeen conversationId, messageNumber @robot.logger.debug 'Already seen message ' + messageNumber return @robot.logger.info 'Got message: ' + JSON.stringify message # Strip HTML tags if messageText isnt null and messageType is 'text' messageText = S(message.message).stripTags().s # Mark message as read @markRead conversationId, messageNumber # Extract sender ID if messageType in ['kick','add'] # Kick and Add messages have the sender encoded # as a JSON string in the message key senderId = JSON.parse(message.message).members[0] else senderId = message.account_id # Create a Hubot user object author = @robot.brain.userForId senderId author.room = conversationId author.reply_to = senderId messageObject = @createMessage( author, messageText, messageType, messageNumber ) @emit 'gotMessage', messageObject # Returns a correct Message subtype object depending on the message type createMessage: (author, message, type, messageNumber = null) -> switch type when 'kick' @robot.logger.debug "#{author.name} kicked from #{author.room}" return new LeaveMessage author when 'add' @robot.logger.debug "#{author.name} joined #{author.room}" return new EnterMessage author when 'topic' topic = JSON.parse(message).topic @robot.logger.debug "#{author.room} topic is now #{topic}" return new TopicMessage author, topic, messageNumber else return new TextMessage author, message, messageNumber # Send a new long poll request to the Fleep API # The request will wait ~90 seconds # If new information is available, the server will respond immediately poll: => @robot.logger.debug 'Starting long poll request' data = wait: true, event_horizon: @getLastEventHorizon() poll_flags: ['skip_hidden'] @post 'account/poll', data, (err, resp) => @emit 'pollcomplete', resp # Send a new message to Fleep send: (envelope, message) => @robot.logger.debug 'Sending new message to conversation ' + envelope.room @post "message/send/#{envelope.room}", {message: message}, (err, resp) -> if err isnt null @robot.logger.error 'Unable to send a message: '+JSON.stringify err # Send a private message to a user reply: (envelope, message) -> @robot.logger.debug 'Sending private message to user ' + envelope.user.id @post 'conversation/create', { topic: null, # Topic is currently empty, the default is the bot's name emails:envelope.user.email, message: message }, (err, resp) -> if err isnt null @robot.logger.error 'Unable to send a 1:1 message: '+JSON.stringify err # Get a hash of known conversations getKnownConversations: => @robot.brain.get('conversations') ? {} # Mark a Fleep message as 'seen' by the bot markRead: (conversation_id, message_nr) => # Save the last message number into an internal tracker conversations = @robot.brain.get 'conversations' conversations[conversation_id]['last_message_nr'] = message_nr @robot.brain.set 'conversations', conversations # Do not mark it as 'seen' in Fleep if not enabled return unless @options.markSeen @robot.logger.debug "Marking message #{message_nr} of conversation " + "#{conversation_id} as read" @post "message/mark_read/#{conversation_id}", { message_nr: message_nr }, (err, resp) -> @robot.logger.debug 'Message marked as read.' if err is null # Change the topic of a conversation topic: (conversation_id, topic) => @robot.logger.debug "Setting conversation #{conversation_id} "+ "topic to #{topic}" @post "conversation/set_topic/#{conversation_id}", { topic: topic }, (err,resp) -> @robot.logger.error 'Unable to set topic' if err isnt null # Syncs the list of known conversations populateConversationList: (callback) => @post 'conversation/list', {sync_horizon: 0}, (err, resp) => unless resp.conversations? and resp.conversations.length return for conv in resp.conversations unless @getKnownConversations()?[conv.conversation_id]? @saveConversation conv.conversation_id, conv.last_message_nr @robot.logger.debug 'Conversation list synced' callback() # Sync last seen event horizon syncEventHorizon: (callback) => @post 'account/sync', {}, (err, resp) => @setLastEventHorizon resp.event_horizon @robot.logger.debug 'Event horizon synced' callback() # Change the Fleep user name to the Bot name changeNick: (callback) => @post 'account/configure', {display_name: @options.name}, (err, resp) => @robot.logger.debug resp @robot.logger.debug 'Nick changed' callback() # Sync the list of known contacts syncContacts: (callback) => @post 'contact/sync/all', {ignore: []}, (err, resp) => @handleStreamEvent contact for contact in resp.contacts @robot.logger.debug 'Contacts in sync' callback() # Synchronizes some initial data with Fleep # list of conversations / bot nick / contacts / event_horizon sync: => @robot.logger.debug "Syncing..." # Does synchronization operations in parallel # Calls the callback function only if all operations are complete async.parallel [ (cb) => @populateConversationList cb, (cb) => @syncEventHorizon cb, (cb) => @changeNick cb, (cb) => @syncContacts cb ], (err, results) => if err isnt null @robot.logger.error 'Error during data sync: '+JSON.stringify err @robot.logger.debug 'Everything synced, ready to go!' @emit 'synced', @
159648
{EventEmitter} = require 'events' {TextMessage, EnterMessage, LeaveMessage, TopicMessage} = require 'hubot' WebRequest = require './webRequest' Util = require './util' async = require 'async' S = require 'string' module.exports = class FleepClient extends EventEmitter constructor: (@options, @robot) -> @ticket = null @token_id = null # Fleep profile info for the bot user @profile = account_id : null, display_name : null @on 'pollcomplete', (resp) => @robot.logger.debug 'Poll complete' @handleStreamEvents resp @poll() # Send a POST request to Fleep post: (path, body = {}, callback = ->) -> request = new WebRequest @robot.logger, @ticket, @token_id request.post path, body, (error, response, metaData) => if response?.ticket? @robot.logger.debug "Response contains ticket: #{response.ticket}" @ticket = response.ticket if metaData?.token_id? @robot.logger.debug 'Response contains token_id: ' + metaData.token_id @token_id = metaData.token_id callback error, response, metaData # Return the ID of the last seen Fleep event horizon getLastEventHorizon: -> last = @robot.brain.get 'fleep_last_horizon' @robot.logger.debug 'Last event horizon from robot brain: '+last last or 0 # Set the last seen Fleep event horizon to robot brain setLastEventHorizon: (horizon) -> @robot.brain.set 'fleep_last_horizon', horizon # Login to Fleep with the specified email and password # Creates a new session with Fleep and sets the token_id and ticket vars login: (email, password) => @robot.logger.debug 'Attempting to log in...' @post 'account/login', { email: email, password: <PASSWORD> }, (err, resp, metaData) => if err isnt null @robot.logger.emergency 'Unable to login to Fleep: ' + err.error_message process.exit 1 # Save Fleep profile info @profile.account_id = resp.account_id @profile.display_name = resp.display_name # Tell Hubot we're connected so it can load scripts @robot.logger.info "Successfully connected #{@options.name} with Fleep" @emit 'authenticated', @ # Destroy Fleep session logout: -> @post 'account/logout', {}, (err, resp) -> if err isnt null return @robot.logger.error 'Unable to destroy Fleep session' @robot.logger.debug 'User session with Fleep closed.' # The result of a long poll request to account/poll is passed here # Handle all of its 'stream' items (conversations, contacts...) ie # events that happened during the poll request handleStreamEvents: (resp) => # The poll response gives us our next "last seen" event horizon if resp.event_horizon? @setLastEventHorizon resp.event_horizon @robot.logger.debug 'Updating last seen event horizon to '+ resp.event_horizon # Handle stream items individually if resp.stream? and resp.stream.length @handleStreamEvent event for event in resp.stream else @robot.logger.debug 'Response stream length 0, nothing to parse.' @robot.logger.debug 'Finished handling long poll response' # Save the conversation into the internal "known conversations" list # The message number indicates the last known seen message saveConversation: (conversation_id, message_nr) => conversations = @getKnownConversations() conversations[conversation_id] = {last_message_nr:message_nr} @robot.brain.set 'conversations', conversations @markRead conversation_id, message_nr # Processes a single Event object in a list of Fleep events handleStreamEvent: (event) => @robot.logger.debug 'Handling event: '+JSON.stringify event eventRecType = event.mk_rec_type or null # Event does not have a rec_type, API error? if eventRecType is null @robot.logger.error 'Invalid response from the server, no rec_type' return # New contact information if eventRecType is 'contact' user = @robot.brain.userForId event.account_id # Save the contact name if it's currently unknown if not user.name? or user.name is user.id user.name = event.display_name @robot.logger.debug "New contact: id #{user.id}, name #{user.name}" if not user.email? and event.email? user.email = event.email return # Skip everything but text message events if eventRecType isnt 'message' @robot.logger.debug 'Skipping stream item ' + eventRecType + ', not a message type of event' return # Detected a new conversation unless @getKnownConversations()?[event.conversation_id]? @robot.logger.debug "New conversation! Conversation " + "#{event.conversation_id} was not in the list of monitored " + "conversations, adding it now" @saveConversation event.conversation_id, event.message_nr return # This message is an echo of our own message, ignore if event.account_id is @profile.account_id @robot.logger.debug 'It is my own message, ignore it' return # Ignore edited messages (messages that were posted, then edited) # See https://github.com/anroots/hubot-fleep/issues/4 if event.revision_message_nr? and event.mk_message_type isnt 'topic' @robot.logger.debug 'This is an edited message, skipping...' return # Patch the received text message to Hubot @handleMessage event # Determines whether a particular message in # a particular message has been seen isMessageSeen: (conversation_id, message_nr) => @getKnownConversations()?[conversation_id]?['last_message_nr'] >= message_nr # Parses an incoming message and passes it to Hubot # Message is a Fleep event response object handleMessage: (message) => messageText = message.message or null conversationId = message.conversation_id or null # Extract the message type. One of text|kick|topic|add messageType = message.mk_message_type or null if messageType is 'topic' # A topic message is funny. It's number is in message_nr # unless the topic was edited before some other message was posted. # Then we need to fetch it's message number from revision_message_nr messageNumber = message.message_nr or message.revision_message_nr else messageNumber = message.message_nr or null # Do nothing if the message is already seen if @isMessageSeen conversationId, messageNumber @robot.logger.debug 'Already seen message ' + messageNumber return @robot.logger.info 'Got message: ' + JSON.stringify message # Strip HTML tags if messageText isnt null and messageType is 'text' messageText = S(message.message).stripTags().s # Mark message as read @markRead conversationId, messageNumber # Extract sender ID if messageType in ['kick','add'] # Kick and Add messages have the sender encoded # as a JSON string in the message key senderId = JSON.parse(message.message).members[0] else senderId = message.account_id # Create a Hubot user object author = @robot.brain.userForId senderId author.room = conversationId author.reply_to = senderId messageObject = @createMessage( author, messageText, messageType, messageNumber ) @emit 'gotMessage', messageObject # Returns a correct Message subtype object depending on the message type createMessage: (author, message, type, messageNumber = null) -> switch type when 'kick' @robot.logger.debug "#{author.name} kicked from #{author.room}" return new LeaveMessage author when 'add' @robot.logger.debug "#{author.name} joined #{author.room}" return new EnterMessage author when 'topic' topic = JSON.parse(message).topic @robot.logger.debug "#{author.room} topic is now #{topic}" return new TopicMessage author, topic, messageNumber else return new TextMessage author, message, messageNumber # Send a new long poll request to the Fleep API # The request will wait ~90 seconds # If new information is available, the server will respond immediately poll: => @robot.logger.debug 'Starting long poll request' data = wait: true, event_horizon: @getLastEventHorizon() poll_flags: ['skip_hidden'] @post 'account/poll', data, (err, resp) => @emit 'pollcomplete', resp # Send a new message to Fleep send: (envelope, message) => @robot.logger.debug 'Sending new message to conversation ' + envelope.room @post "message/send/#{envelope.room}", {message: message}, (err, resp) -> if err isnt null @robot.logger.error 'Unable to send a message: '+JSON.stringify err # Send a private message to a user reply: (envelope, message) -> @robot.logger.debug 'Sending private message to user ' + envelope.user.id @post 'conversation/create', { topic: null, # Topic is currently empty, the default is the bot's name emails:envelope.user.email, message: message }, (err, resp) -> if err isnt null @robot.logger.error 'Unable to send a 1:1 message: '+JSON.stringify err # Get a hash of known conversations getKnownConversations: => @robot.brain.get('conversations') ? {} # Mark a Fleep message as 'seen' by the bot markRead: (conversation_id, message_nr) => # Save the last message number into an internal tracker conversations = @robot.brain.get 'conversations' conversations[conversation_id]['last_message_nr'] = message_nr @robot.brain.set 'conversations', conversations # Do not mark it as 'seen' in Fleep if not enabled return unless @options.markSeen @robot.logger.debug "Marking message #{message_nr} of conversation " + "#{conversation_id} as read" @post "message/mark_read/#{conversation_id}", { message_nr: message_nr }, (err, resp) -> @robot.logger.debug 'Message marked as read.' if err is null # Change the topic of a conversation topic: (conversation_id, topic) => @robot.logger.debug "Setting conversation #{conversation_id} "+ "topic to #{topic}" @post "conversation/set_topic/#{conversation_id}", { topic: topic }, (err,resp) -> @robot.logger.error 'Unable to set topic' if err isnt null # Syncs the list of known conversations populateConversationList: (callback) => @post 'conversation/list', {sync_horizon: 0}, (err, resp) => unless resp.conversations? and resp.conversations.length return for conv in resp.conversations unless @getKnownConversations()?[conv.conversation_id]? @saveConversation conv.conversation_id, conv.last_message_nr @robot.logger.debug 'Conversation list synced' callback() # Sync last seen event horizon syncEventHorizon: (callback) => @post 'account/sync', {}, (err, resp) => @setLastEventHorizon resp.event_horizon @robot.logger.debug 'Event horizon synced' callback() # Change the Fleep user name to the Bot name changeNick: (callback) => @post 'account/configure', {display_name: @options.name}, (err, resp) => @robot.logger.debug resp @robot.logger.debug 'Nick changed' callback() # Sync the list of known contacts syncContacts: (callback) => @post 'contact/sync/all', {ignore: []}, (err, resp) => @handleStreamEvent contact for contact in resp.contacts @robot.logger.debug 'Contacts in sync' callback() # Synchronizes some initial data with Fleep # list of conversations / bot nick / contacts / event_horizon sync: => @robot.logger.debug "Syncing..." # Does synchronization operations in parallel # Calls the callback function only if all operations are complete async.parallel [ (cb) => @populateConversationList cb, (cb) => @syncEventHorizon cb, (cb) => @changeNick cb, (cb) => @syncContacts cb ], (err, results) => if err isnt null @robot.logger.error 'Error during data sync: '+JSON.stringify err @robot.logger.debug 'Everything synced, ready to go!' @emit 'synced', @
true
{EventEmitter} = require 'events' {TextMessage, EnterMessage, LeaveMessage, TopicMessage} = require 'hubot' WebRequest = require './webRequest' Util = require './util' async = require 'async' S = require 'string' module.exports = class FleepClient extends EventEmitter constructor: (@options, @robot) -> @ticket = null @token_id = null # Fleep profile info for the bot user @profile = account_id : null, display_name : null @on 'pollcomplete', (resp) => @robot.logger.debug 'Poll complete' @handleStreamEvents resp @poll() # Send a POST request to Fleep post: (path, body = {}, callback = ->) -> request = new WebRequest @robot.logger, @ticket, @token_id request.post path, body, (error, response, metaData) => if response?.ticket? @robot.logger.debug "Response contains ticket: #{response.ticket}" @ticket = response.ticket if metaData?.token_id? @robot.logger.debug 'Response contains token_id: ' + metaData.token_id @token_id = metaData.token_id callback error, response, metaData # Return the ID of the last seen Fleep event horizon getLastEventHorizon: -> last = @robot.brain.get 'fleep_last_horizon' @robot.logger.debug 'Last event horizon from robot brain: '+last last or 0 # Set the last seen Fleep event horizon to robot brain setLastEventHorizon: (horizon) -> @robot.brain.set 'fleep_last_horizon', horizon # Login to Fleep with the specified email and password # Creates a new session with Fleep and sets the token_id and ticket vars login: (email, password) => @robot.logger.debug 'Attempting to log in...' @post 'account/login', { email: email, password: PI:PASSWORD:<PASSWORD>END_PI }, (err, resp, metaData) => if err isnt null @robot.logger.emergency 'Unable to login to Fleep: ' + err.error_message process.exit 1 # Save Fleep profile info @profile.account_id = resp.account_id @profile.display_name = resp.display_name # Tell Hubot we're connected so it can load scripts @robot.logger.info "Successfully connected #{@options.name} with Fleep" @emit 'authenticated', @ # Destroy Fleep session logout: -> @post 'account/logout', {}, (err, resp) -> if err isnt null return @robot.logger.error 'Unable to destroy Fleep session' @robot.logger.debug 'User session with Fleep closed.' # The result of a long poll request to account/poll is passed here # Handle all of its 'stream' items (conversations, contacts...) ie # events that happened during the poll request handleStreamEvents: (resp) => # The poll response gives us our next "last seen" event horizon if resp.event_horizon? @setLastEventHorizon resp.event_horizon @robot.logger.debug 'Updating last seen event horizon to '+ resp.event_horizon # Handle stream items individually if resp.stream? and resp.stream.length @handleStreamEvent event for event in resp.stream else @robot.logger.debug 'Response stream length 0, nothing to parse.' @robot.logger.debug 'Finished handling long poll response' # Save the conversation into the internal "known conversations" list # The message number indicates the last known seen message saveConversation: (conversation_id, message_nr) => conversations = @getKnownConversations() conversations[conversation_id] = {last_message_nr:message_nr} @robot.brain.set 'conversations', conversations @markRead conversation_id, message_nr # Processes a single Event object in a list of Fleep events handleStreamEvent: (event) => @robot.logger.debug 'Handling event: '+JSON.stringify event eventRecType = event.mk_rec_type or null # Event does not have a rec_type, API error? if eventRecType is null @robot.logger.error 'Invalid response from the server, no rec_type' return # New contact information if eventRecType is 'contact' user = @robot.brain.userForId event.account_id # Save the contact name if it's currently unknown if not user.name? or user.name is user.id user.name = event.display_name @robot.logger.debug "New contact: id #{user.id}, name #{user.name}" if not user.email? and event.email? user.email = event.email return # Skip everything but text message events if eventRecType isnt 'message' @robot.logger.debug 'Skipping stream item ' + eventRecType + ', not a message type of event' return # Detected a new conversation unless @getKnownConversations()?[event.conversation_id]? @robot.logger.debug "New conversation! Conversation " + "#{event.conversation_id} was not in the list of monitored " + "conversations, adding it now" @saveConversation event.conversation_id, event.message_nr return # This message is an echo of our own message, ignore if event.account_id is @profile.account_id @robot.logger.debug 'It is my own message, ignore it' return # Ignore edited messages (messages that were posted, then edited) # See https://github.com/anroots/hubot-fleep/issues/4 if event.revision_message_nr? and event.mk_message_type isnt 'topic' @robot.logger.debug 'This is an edited message, skipping...' return # Patch the received text message to Hubot @handleMessage event # Determines whether a particular message in # a particular message has been seen isMessageSeen: (conversation_id, message_nr) => @getKnownConversations()?[conversation_id]?['last_message_nr'] >= message_nr # Parses an incoming message and passes it to Hubot # Message is a Fleep event response object handleMessage: (message) => messageText = message.message or null conversationId = message.conversation_id or null # Extract the message type. One of text|kick|topic|add messageType = message.mk_message_type or null if messageType is 'topic' # A topic message is funny. It's number is in message_nr # unless the topic was edited before some other message was posted. # Then we need to fetch it's message number from revision_message_nr messageNumber = message.message_nr or message.revision_message_nr else messageNumber = message.message_nr or null # Do nothing if the message is already seen if @isMessageSeen conversationId, messageNumber @robot.logger.debug 'Already seen message ' + messageNumber return @robot.logger.info 'Got message: ' + JSON.stringify message # Strip HTML tags if messageText isnt null and messageType is 'text' messageText = S(message.message).stripTags().s # Mark message as read @markRead conversationId, messageNumber # Extract sender ID if messageType in ['kick','add'] # Kick and Add messages have the sender encoded # as a JSON string in the message key senderId = JSON.parse(message.message).members[0] else senderId = message.account_id # Create a Hubot user object author = @robot.brain.userForId senderId author.room = conversationId author.reply_to = senderId messageObject = @createMessage( author, messageText, messageType, messageNumber ) @emit 'gotMessage', messageObject # Returns a correct Message subtype object depending on the message type createMessage: (author, message, type, messageNumber = null) -> switch type when 'kick' @robot.logger.debug "#{author.name} kicked from #{author.room}" return new LeaveMessage author when 'add' @robot.logger.debug "#{author.name} joined #{author.room}" return new EnterMessage author when 'topic' topic = JSON.parse(message).topic @robot.logger.debug "#{author.room} topic is now #{topic}" return new TopicMessage author, topic, messageNumber else return new TextMessage author, message, messageNumber # Send a new long poll request to the Fleep API # The request will wait ~90 seconds # If new information is available, the server will respond immediately poll: => @robot.logger.debug 'Starting long poll request' data = wait: true, event_horizon: @getLastEventHorizon() poll_flags: ['skip_hidden'] @post 'account/poll', data, (err, resp) => @emit 'pollcomplete', resp # Send a new message to Fleep send: (envelope, message) => @robot.logger.debug 'Sending new message to conversation ' + envelope.room @post "message/send/#{envelope.room}", {message: message}, (err, resp) -> if err isnt null @robot.logger.error 'Unable to send a message: '+JSON.stringify err # Send a private message to a user reply: (envelope, message) -> @robot.logger.debug 'Sending private message to user ' + envelope.user.id @post 'conversation/create', { topic: null, # Topic is currently empty, the default is the bot's name emails:envelope.user.email, message: message }, (err, resp) -> if err isnt null @robot.logger.error 'Unable to send a 1:1 message: '+JSON.stringify err # Get a hash of known conversations getKnownConversations: => @robot.brain.get('conversations') ? {} # Mark a Fleep message as 'seen' by the bot markRead: (conversation_id, message_nr) => # Save the last message number into an internal tracker conversations = @robot.brain.get 'conversations' conversations[conversation_id]['last_message_nr'] = message_nr @robot.brain.set 'conversations', conversations # Do not mark it as 'seen' in Fleep if not enabled return unless @options.markSeen @robot.logger.debug "Marking message #{message_nr} of conversation " + "#{conversation_id} as read" @post "message/mark_read/#{conversation_id}", { message_nr: message_nr }, (err, resp) -> @robot.logger.debug 'Message marked as read.' if err is null # Change the topic of a conversation topic: (conversation_id, topic) => @robot.logger.debug "Setting conversation #{conversation_id} "+ "topic to #{topic}" @post "conversation/set_topic/#{conversation_id}", { topic: topic }, (err,resp) -> @robot.logger.error 'Unable to set topic' if err isnt null # Syncs the list of known conversations populateConversationList: (callback) => @post 'conversation/list', {sync_horizon: 0}, (err, resp) => unless resp.conversations? and resp.conversations.length return for conv in resp.conversations unless @getKnownConversations()?[conv.conversation_id]? @saveConversation conv.conversation_id, conv.last_message_nr @robot.logger.debug 'Conversation list synced' callback() # Sync last seen event horizon syncEventHorizon: (callback) => @post 'account/sync', {}, (err, resp) => @setLastEventHorizon resp.event_horizon @robot.logger.debug 'Event horizon synced' callback() # Change the Fleep user name to the Bot name changeNick: (callback) => @post 'account/configure', {display_name: @options.name}, (err, resp) => @robot.logger.debug resp @robot.logger.debug 'Nick changed' callback() # Sync the list of known contacts syncContacts: (callback) => @post 'contact/sync/all', {ignore: []}, (err, resp) => @handleStreamEvent contact for contact in resp.contacts @robot.logger.debug 'Contacts in sync' callback() # Synchronizes some initial data with Fleep # list of conversations / bot nick / contacts / event_horizon sync: => @robot.logger.debug "Syncing..." # Does synchronization operations in parallel # Calls the callback function only if all operations are complete async.parallel [ (cb) => @populateConversationList cb, (cb) => @syncEventHorizon cb, (cb) => @changeNick cb, (cb) => @syncContacts cb ], (err, results) => if err isnt null @robot.logger.error 'Error during data sync: '+JSON.stringify err @robot.logger.debug 'Everything synced, ready to go!' @emit 'synced', @
[ { "context": "# @author mr.doob / http://mrdoob.com/\n# @author alteredq / ht", "end": 12, "score": 0.9160505533218384, "start": 10, "tag": "USERNAME", "value": "mr" }, { "context": "# @author mr.doob / http://mrdoob.com/\n# @author alteredq / http://", "end": 17, "score": 0.6915410161018372, "start": 13, "tag": "NAME", "value": "doob" }, { "context": "# @author mr.doob / http://mrdoob.com/\n# @author alteredq / http://alteredqualia.com/\n# @author aladjev.and", "end": 57, "score": 0.9989213347434998, "start": 49, "tag": "USERNAME", "value": "alteredq" }, { "context": "hor alteredq / http://alteredqualia.com/\n# @author aladjev.andrew@gmail.com\n\n#= require new_src/core/vector_3\n#= require new_", "end": 120, "score": 0.999913215637207, "start": 96, "tag": "EMAIL", "value": "aladjev.andrew@gmail.com" } ]
source/javascripts/new_src/lights/directional.coffee
andrew-aladev/three.js
0
# @author mr.doob / http://mrdoob.com/ # @author alteredq / http://alteredqualia.com/ # @author aladjev.andrew@gmail.com #= require new_src/core/vector_3 #= require new_src/core/object_3d #= require new_src/lights/light class DirectionalLight extends THREE.Light constructor: (hex, intensity, distance) -> super hex @position = new THREE.Vector3(0, 1, 0) @target = new THREE.Object3D() @intensity = (if (intensity isnt undefined) then intensity else 1) @distance = (if (distance isnt undefined) then distance else 0) @castShadow = false @onlyShadow = false @shadowCameraNear = 50 @shadowCameraFar = 5000 @shadowCameraLeft = -500 @shadowCameraRight = 500 @shadowCameraTop = 500 @shadowCameraBottom = -500 @shadowCameraVisible = false @shadowBias = 0 @shadowDarkness = 0.5 @shadowMapWidth = 512 @shadowMapHeight = 512 @shadowCascade = false @shadowCascadeOffset = new THREE.Vector3(0, 0, -1000) @shadowCascadeCount = 2 @shadowCascadeBias = [ 0, 0, 0 ] @shadowCascadeWidth = [ 512, 512, 512 ] @shadowCascadeHeight = [ 512, 512, 512 ] @shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ] @shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ] @shadowCascadeArray = [] @shadowMap = null @shadowMapSize = null @shadowCamera = null @shadowMatrix = null namespace "THREE", (exports) -> exports.DirectionalLight = DirectionalLight
170878
# @author mr.<NAME> / http://mrdoob.com/ # @author alteredq / http://alteredqualia.com/ # @author <EMAIL> #= require new_src/core/vector_3 #= require new_src/core/object_3d #= require new_src/lights/light class DirectionalLight extends THREE.Light constructor: (hex, intensity, distance) -> super hex @position = new THREE.Vector3(0, 1, 0) @target = new THREE.Object3D() @intensity = (if (intensity isnt undefined) then intensity else 1) @distance = (if (distance isnt undefined) then distance else 0) @castShadow = false @onlyShadow = false @shadowCameraNear = 50 @shadowCameraFar = 5000 @shadowCameraLeft = -500 @shadowCameraRight = 500 @shadowCameraTop = 500 @shadowCameraBottom = -500 @shadowCameraVisible = false @shadowBias = 0 @shadowDarkness = 0.5 @shadowMapWidth = 512 @shadowMapHeight = 512 @shadowCascade = false @shadowCascadeOffset = new THREE.Vector3(0, 0, -1000) @shadowCascadeCount = 2 @shadowCascadeBias = [ 0, 0, 0 ] @shadowCascadeWidth = [ 512, 512, 512 ] @shadowCascadeHeight = [ 512, 512, 512 ] @shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ] @shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ] @shadowCascadeArray = [] @shadowMap = null @shadowMapSize = null @shadowCamera = null @shadowMatrix = null namespace "THREE", (exports) -> exports.DirectionalLight = DirectionalLight
true
# @author mr.PI:NAME:<NAME>END_PI / http://mrdoob.com/ # @author alteredq / http://alteredqualia.com/ # @author PI:EMAIL:<EMAIL>END_PI #= require new_src/core/vector_3 #= require new_src/core/object_3d #= require new_src/lights/light class DirectionalLight extends THREE.Light constructor: (hex, intensity, distance) -> super hex @position = new THREE.Vector3(0, 1, 0) @target = new THREE.Object3D() @intensity = (if (intensity isnt undefined) then intensity else 1) @distance = (if (distance isnt undefined) then distance else 0) @castShadow = false @onlyShadow = false @shadowCameraNear = 50 @shadowCameraFar = 5000 @shadowCameraLeft = -500 @shadowCameraRight = 500 @shadowCameraTop = 500 @shadowCameraBottom = -500 @shadowCameraVisible = false @shadowBias = 0 @shadowDarkness = 0.5 @shadowMapWidth = 512 @shadowMapHeight = 512 @shadowCascade = false @shadowCascadeOffset = new THREE.Vector3(0, 0, -1000) @shadowCascadeCount = 2 @shadowCascadeBias = [ 0, 0, 0 ] @shadowCascadeWidth = [ 512, 512, 512 ] @shadowCascadeHeight = [ 512, 512, 512 ] @shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ] @shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ] @shadowCascadeArray = [] @shadowMap = null @shadowMapSize = null @shadowCamera = null @shadowMatrix = null namespace "THREE", (exports) -> exports.DirectionalLight = DirectionalLight
[ { "context": " @model = new Essence.Models.Timelet\n name: 'Awesome timer'\n duration: 42\n @model.state.running = tr", "end": 120, "score": 0.9762643575668335, "start": 107, "tag": "NAME", "value": "Awesome timer" }, { "context": "ect(@view.ui.timelets.find('input')).toHaveValue 'Awesome timer'\n\n describe '#createTimelet', ->\n it 'adds a ", "end": 1301, "score": 0.8629276156425476, "start": 1288, "tag": "NAME", "value": "Awesome timer" } ]
spec/javascripts/modules/timelet/views/composites/timelets_spec.js.coffee
kaethorn/essence
0
describe 'Essence.Views.Timelets', -> beforeEach -> @model = new Essence.Models.Timelet name: 'Awesome timer' duration: 42 @model.state.running = true @model.state.timer = 10 @collection = new Essence.Collections.Timelets [@model] @parent = new Essence.Views.TimeletsPanel model: @model, collection: @collection @view = new Essence.Views.Timelets model: @model, collection: @collection, parent: @parent @html = @view.render().$el setFixtures @html afterEach -> clearInterval @view.runner describe '#constructor', -> it 'creates a composite view', -> expect(@view).toBeAnInstanceOf Backbone.Marionette.CompositeView it 'sets the model and collection', -> expect(@view.model).toBe @model expect(@view.collection).toBe @collection describe '#initialize', -> it 'loads the timelet on timelet load', -> stub = sinon.stub @view.options.parent, 'trigger' model = new Essence.Models.Timelet @view.collection.add model @view.trigger 'childview:timelet:load', model: model expect(stub).toHaveBeenCalledWith 'timelet:load', model.id stub.restore() describe '#render', -> it 'shows the timelets list', -> expect(@view.ui.timelets.find('input')).toHaveValue 'Awesome timer' describe '#createTimelet', -> it 'adds a new timelet to the collection', -> expect(@collection.length).toEqual 1 @view.createTimelet() expect(@collection.length).toEqual 2 it 'navigates to the index', -> @view.createTimelet() expect(@navigation).toHaveBeenCalledWith '/timelet'
149353
describe 'Essence.Views.Timelets', -> beforeEach -> @model = new Essence.Models.Timelet name: '<NAME>' duration: 42 @model.state.running = true @model.state.timer = 10 @collection = new Essence.Collections.Timelets [@model] @parent = new Essence.Views.TimeletsPanel model: @model, collection: @collection @view = new Essence.Views.Timelets model: @model, collection: @collection, parent: @parent @html = @view.render().$el setFixtures @html afterEach -> clearInterval @view.runner describe '#constructor', -> it 'creates a composite view', -> expect(@view).toBeAnInstanceOf Backbone.Marionette.CompositeView it 'sets the model and collection', -> expect(@view.model).toBe @model expect(@view.collection).toBe @collection describe '#initialize', -> it 'loads the timelet on timelet load', -> stub = sinon.stub @view.options.parent, 'trigger' model = new Essence.Models.Timelet @view.collection.add model @view.trigger 'childview:timelet:load', model: model expect(stub).toHaveBeenCalledWith 'timelet:load', model.id stub.restore() describe '#render', -> it 'shows the timelets list', -> expect(@view.ui.timelets.find('input')).toHaveValue '<NAME>' describe '#createTimelet', -> it 'adds a new timelet to the collection', -> expect(@collection.length).toEqual 1 @view.createTimelet() expect(@collection.length).toEqual 2 it 'navigates to the index', -> @view.createTimelet() expect(@navigation).toHaveBeenCalledWith '/timelet'
true
describe 'Essence.Views.Timelets', -> beforeEach -> @model = new Essence.Models.Timelet name: 'PI:NAME:<NAME>END_PI' duration: 42 @model.state.running = true @model.state.timer = 10 @collection = new Essence.Collections.Timelets [@model] @parent = new Essence.Views.TimeletsPanel model: @model, collection: @collection @view = new Essence.Views.Timelets model: @model, collection: @collection, parent: @parent @html = @view.render().$el setFixtures @html afterEach -> clearInterval @view.runner describe '#constructor', -> it 'creates a composite view', -> expect(@view).toBeAnInstanceOf Backbone.Marionette.CompositeView it 'sets the model and collection', -> expect(@view.model).toBe @model expect(@view.collection).toBe @collection describe '#initialize', -> it 'loads the timelet on timelet load', -> stub = sinon.stub @view.options.parent, 'trigger' model = new Essence.Models.Timelet @view.collection.add model @view.trigger 'childview:timelet:load', model: model expect(stub).toHaveBeenCalledWith 'timelet:load', model.id stub.restore() describe '#render', -> it 'shows the timelets list', -> expect(@view.ui.timelets.find('input')).toHaveValue 'PI:NAME:<NAME>END_PI' describe '#createTimelet', -> it 'adds a new timelet to the collection', -> expect(@collection.length).toEqual 1 @view.createTimelet() expect(@collection.length).toEqual 2 it 'navigates to the index', -> @view.createTimelet() expect(@navigation).toHaveBeenCalledWith '/timelet'
[ { "context": "###\n backbone-orm.js 0.5.12\n Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-orm\n Lice", "end": 58, "score": 0.9983751177787781, "start": 50, "tag": "NAME", "value": "Vidigami" }, { "context": " Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-orm\n License: MIT (http://www.opensourc", "end": 88, "score": 0.9997177124023438, "start": 80, "tag": "USERNAME", "value": "vidigami" } ]
src/cache/singletons.coffee
michaelBenin/backbone-orm
1
### backbone-orm.js 0.5.12 Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-orm License: MIT (http://www.opensource.org/licenses/mit-license.php) Dependencies: Backbone.js, Underscore.js, and Moment.js. ### module.exports = ModelCache: new (require('./model_cache'))() QueryCache: new (require('./query_cache'))() try module.exports.ModelTypeID = new (require('../node/model_type_id'))() catch e
19370
### backbone-orm.js 0.5.12 Copyright (c) 2013 <NAME> - https://github.com/vidigami/backbone-orm License: MIT (http://www.opensource.org/licenses/mit-license.php) Dependencies: Backbone.js, Underscore.js, and Moment.js. ### module.exports = ModelCache: new (require('./model_cache'))() QueryCache: new (require('./query_cache'))() try module.exports.ModelTypeID = new (require('../node/model_type_id'))() catch e
true
### backbone-orm.js 0.5.12 Copyright (c) 2013 PI:NAME:<NAME>END_PI - https://github.com/vidigami/backbone-orm License: MIT (http://www.opensource.org/licenses/mit-license.php) Dependencies: Backbone.js, Underscore.js, and Moment.js. ### module.exports = ModelCache: new (require('./model_cache'))() QueryCache: new (require('./query_cache'))() try module.exports.ModelTypeID = new (require('../node/model_type_id'))() catch e
[ { "context": ".internode.on.net') ⇒\n# [\n# { type: 'A', addr: '150.101.140.197' }\n# { type: 'A', addr: '216.58.220.100' }\n# ", "end": 444, "score": 0.9997532367706299, "start": 429, "tag": "IP_ADDRESS", "value": "150.101.140.197" }, { "context": "addr: '150.101.140.197' }\n# { type: 'A', addr: '216.58.220.100' }\n# { type: 'AAAA', addr: '2001:44b8:69:2:1::1", "end": 486, "score": 0.9997430443763733, "start": 472, "tag": "IP_ADDRESS", "value": "216.58.220.100" }, { "context": "dr: '216.58.220.100' }\n# { type: 'AAAA', addr: '2001:44b8:69:2:1::100' }\n# { type: 'AAAA', addr: '2404:6800:4006:801:", "end": 538, "score": 0.9997831583023071, "start": 517, "tag": "IP_ADDRESS", "value": "2001:44b8:69:2:1::100" }, { "context": "01:44b8:69:2:1::100' }\n# { type: 'AAAA', addr: '2404:6800:4006:801::2004' }\n# ]\nmodule.exports = (hostnames) ->\n resolveT", "end": 593, "score": 0.9997745156288147, "start": 569, "tag": "IP_ADDRESS", "value": "2404:6800:4006:801::2004" } ]
resolver.coffee
dit4c/designate-rr-monitor
1
'use strict' _ = require('lodash') Q = require('q') dns = require('dns') class DnsRecord constructor: (@type, @addr) -> # Nothing required resolve = (rrtype) -> (hostname) -> d = Q.defer() dns.resolve hostname, rrtype, (err, result) -> d.resolve(if err then [] else result) d.promise eqVal = (r) -> r.type+"!"+r.addr # eg. resolveAll('www.google.com', 'www.internode.on.net') ⇒ # [ # { type: 'A', addr: '150.101.140.197' } # { type: 'A', addr: '216.58.220.100' } # { type: 'AAAA', addr: '2001:44b8:69:2:1::100' } # { type: 'AAAA', addr: '2404:6800:4006:801::2004' } # ] module.exports = (hostnames) -> resolveType = (rrtype) -> Q.all(hostnames.map(resolve(rrtype))) .then _.flow(_.flatten, _.sortBy) .then (addrs) -> addrs.map (addr) -> new DnsRecord(rrtype, addr) resolveTypes = (types) -> Q.all(types.map(resolveType)) .then _.flow(_.flatten, (l) -> _.uniq(l, false, eqVal)) resolveTypes(['A', 'AAAA'])
104347
'use strict' _ = require('lodash') Q = require('q') dns = require('dns') class DnsRecord constructor: (@type, @addr) -> # Nothing required resolve = (rrtype) -> (hostname) -> d = Q.defer() dns.resolve hostname, rrtype, (err, result) -> d.resolve(if err then [] else result) d.promise eqVal = (r) -> r.type+"!"+r.addr # eg. resolveAll('www.google.com', 'www.internode.on.net') ⇒ # [ # { type: 'A', addr: '172.16.58.3' } # { type: 'A', addr: '172.16.31.10' } # { type: 'AAAA', addr: 'fc00:e968:6179::de52:7100' } # { type: 'AAAA', addr: 'fdf8:f53e:61e4::18' } # ] module.exports = (hostnames) -> resolveType = (rrtype) -> Q.all(hostnames.map(resolve(rrtype))) .then _.flow(_.flatten, _.sortBy) .then (addrs) -> addrs.map (addr) -> new DnsRecord(rrtype, addr) resolveTypes = (types) -> Q.all(types.map(resolveType)) .then _.flow(_.flatten, (l) -> _.uniq(l, false, eqVal)) resolveTypes(['A', 'AAAA'])
true
'use strict' _ = require('lodash') Q = require('q') dns = require('dns') class DnsRecord constructor: (@type, @addr) -> # Nothing required resolve = (rrtype) -> (hostname) -> d = Q.defer() dns.resolve hostname, rrtype, (err, result) -> d.resolve(if err then [] else result) d.promise eqVal = (r) -> r.type+"!"+r.addr # eg. resolveAll('www.google.com', 'www.internode.on.net') ⇒ # [ # { type: 'A', addr: 'PI:IP_ADDRESS:172.16.58.3END_PI' } # { type: 'A', addr: 'PI:IP_ADDRESS:172.16.31.10END_PI' } # { type: 'AAAA', addr: 'PI:IP_ADDRESS:fc00:e968:6179::de52:7100END_PI' } # { type: 'AAAA', addr: 'PI:IP_ADDRESS:fdf8:f53e:61e4::18END_PI' } # ] module.exports = (hostnames) -> resolveType = (rrtype) -> Q.all(hostnames.map(resolve(rrtype))) .then _.flow(_.flatten, _.sortBy) .then (addrs) -> addrs.map (addr) -> new DnsRecord(rrtype, addr) resolveTypes = (types) -> Q.all(types.map(resolveType)) .then _.flow(_.flatten, (l) -> _.uniq(l, false, eqVal)) resolveTypes(['A', 'AAAA'])
[ { "context": " companyName: ['Company']\n personName: ['Person']\n website: ['website']\n link: ['ur", "end": 217, "score": 0.9972208142280579, "start": 211, "tag": "NAME", "value": "Person" } ]
lib/services/map.coffee
FranzSkuffka/ner-unifier
0
fuzzymap = require 'fuzzymap' module.exports = (name) -> map = emailAddress: ['EmailAddress', 'emailAddress', 'email'] city: ['City'] companyName: ['Company'] personName: ['Person'] website: ['website'] link: ['url'] mapper = fuzzymap.defineMap map mapper.map name
189592
fuzzymap = require 'fuzzymap' module.exports = (name) -> map = emailAddress: ['EmailAddress', 'emailAddress', 'email'] city: ['City'] companyName: ['Company'] personName: ['<NAME>'] website: ['website'] link: ['url'] mapper = fuzzymap.defineMap map mapper.map name
true
fuzzymap = require 'fuzzymap' module.exports = (name) -> map = emailAddress: ['EmailAddress', 'emailAddress', 'email'] city: ['City'] companyName: ['Company'] personName: ['PI:NAME:<NAME>END_PI'] website: ['website'] link: ['url'] mapper = fuzzymap.defineMap map mapper.map name
[ { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri", "end": 42, "score": 0.9998461604118347, "start": 24, "tag": "NAME", "value": "Alexander Cherniuk" }, { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistribution and use in ", "end": 60, "score": 0.9999299049377441, "start": 44, "tag": "EMAIL", "value": "ts33kr@gmail.com" }, { "context": "Key = \"log:request:level\"\n assert formatKey = \"log:request:format\"\n format = try nconf.get(formatKey) or \"dev\"\n ", "end": 2224, "score": 0.6745012998580933, "start": 2206, "tag": "KEY", "value": "log:request:format" } ]
library/nucleus/plumbs.coffee
ts33kr/granite
6
### Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" assert = require "assert" uuid = require "node-uuid" asciify = require "asciify" connect = require "connect" logger = require "winston" send = require "response-send" platform = require "platform" colors = require "colors" nconf = require "nconf" https = require "https" http = require "http" util = require "util" url = require "url" {Negotiator} = require "negotiator" {RedisSession} = require "../shipped/session" # This middleware is really a wrapper around the `Connect` logger # that pipes all the request logs to the `Winston` instances that # is used throughout the framework to provide logging capabilities. # The format is takes from the `NConf` config or the default `dev`. # Refer to the implementation source code for more information. module.exports.logger = (kernel) -> assert levelKey = "log:request:level" assert formatKey = "log:request:format" format = try nconf.get(formatKey) or "dev" level = try nconf.get(levelKey) or "debug" filter = (s) -> s.replace "\n", new String() writer = (d) -> logger.log level, filter d msg = "Configure logger middleware at U=%s" assert _.isObject(kernel), "got no kernel" assert stamp = moment().unix().toString() options = new Object stream: write: writer assert options.format = format.toString() logger.debug msg.toString(), stamp.bold return try connect.logger options or {} # This middleware is really a wrapper around the `Connect` session # middleware. The reason it wraps it is to automatically configure # the session storage using the kernel and scoping configuration # data. This is automatically connected by the kernel instance. # Refer to the implementation source code for more information. module.exports.session = (kernel) -> nso = "no session configuration options" assert options = try nconf.get("session") assert shallow = try _.clone options or {} assert _.isObject(kernel), "got no kernel" redis = _.isObject nconf.get("redis") or 0 assert _.isObject(options), nso.toString() assert ux = moment().unix().toString().bold useRedis = "Using Redis session storage engine" message = "Configure session middleware at U=%s" shallow.store = RedisSession.obtain() if redis logger.debug message.toString(), ux.toString() logger.info useRedis.toString().blue if redis return connect.session shallow or new Object # This middleware is a wrapper around the `toobusy` module providing # the functinality that helps to prevent the server shutting down due # to the excessive load. This is done via monitoring of the event loop # polling and rating the loop lag time. If it's too big, the request # will not be processed, but simply dropped. This is a config wrapper. module.exports.threshold = (kernel) -> wrongReason = "no threshold reason supplied" wrongLagTime = "no valid lag time specified" noHeaders = "unable to locate request headers" options = nconf.get("threshold") or Object() assert _.isNumber(options?.lag), wrongLagTime assert _.isString(options?.reason), wrongReason assert _.isObject(kernel), "no kernel supplied" (busy = require "toobusy").maxLag try options.lag message = "Setting threshold maximum lag to %s ms" logger.info message.red, options.lag.toString().bold return (request, response) -> # middleware itself assert unix = moment().unix().toString().bold assert _.isObject(request?.headers), noHeaders message = "Running threshold middleware at U=%s" logger.debug message.toString(), unix.toString() assert _.isFunction next = _.last arguments return next undefined unless busy() is yes response.writeHead 503, options.reason return response.end options.reason # This middleware uses an external library to parse the incoming # user agent identification string into a platform description # object. If the user agent string is absent from the requesting # entity then the platform will not be defined on request object. # Refer to the implementation source code for more information. module.exports.platform = (kernel) -> (request, response) -> intern = "could not parse the platform data" noParser = "platform parse library malfunction" noPlatform = "missing platform middleware lib" noHeaders = "unable to locate request headers" assert _.isObject(platform or null), noPlatform assert _.isObject(request?.headers), noHeaders assert _.isFunction(platform?.parse), noParser agent = request.headers["user-agent"] or null return next() if not agent or _.isEmpty agent assert unix = moment().unix().toString().bold message = "Running platform middleware at U=%s" logger.debug message.toString(), unix.toString() request.platform = try (platform.parse agent) assert _.isObject(request.platform), intern assert _.isFunction next = _.last arguments return next() unless request.headersSent # This middleware uses an external library to parse the incoming # request metadata and then coerce it by using the standards to # a queriable form. This queriable forms allows to negotiate for # media types, accepted encoding, accepted language and so on. # Middleware can be used to serve the most appropriare content. module.exports.negotiate = (kernel) -> (request, response) -> terrible = "no valid request object found" noLibrary = "could not load negotiator lib" acked = "could not instantiate a negotiator" noHeaders = "unable to locate request headers" assert _.isObject(kernel), "no kernel supplied" assert _.isObject(Negotiator or 0), noLibrary assert _.isObject(request or null), terrible assert _.isObject(request?.headers), noHeaders request.negotiate = Negotiator request or {} assert _.isObject(request.negotiate), acked assert unix = moment().unix().toString().bold message = "Running negotiate middleware at U=%s" logger.debug message.toString(), unix.toString() assert _.isFunction next = _.last arguments return next() unless request.headersSent # A middleware that adds a `send` method to the response object. # This allows for automatic setting of `Content-Type` headers # based on the content that is being sent away. Use this method # rather than writing and ending the request in a direct way. # Is implemented using the external `response-send` library. module.exports.send = (kernel) -> (request, response) -> ack = "could not attach response sender method" noLibrary = "could not load the sender library" terrible = "got no valid response object found" noHeaders = "unable to locate request headers" assert _.isObject(kernel), "no kernel supplied" assert _.isFunction(try (send.json)), noLibrary assert _.isObject(response or null), terrible assert _.isObject(request?.headers), noHeaders try response.req = request unless response.req assert e = (seq) -> response.emit "send", seq... assert d = (seq) -> response.emit "sdat", seq... assert i = (seq) -> try _.isString _.first seq assert p = (seq, fn) -> fn.apply response, seq e = (f) -> (s...) -> e(s); (d(s) if i(s)); p(s, f) assert (try response.send = e send), ack.toString() assert response.json = try (e send.json spaces: 4) assert unix = moment().unix().toString().bold message = "Running sending middleware at U=%s" logger.debug message.toString(), unix.toString() assert _.isFunction next = _.last arguments return next() unless request.headersSent # A middeware that makes possible external specification of session # bearer via HTTP headers. This basically means - it allows for you # to explicitly specify a session ID via the `X-Session-ID` header. # It is a convenient way for the API client to identify themselves. # Beware that it might be used by clients to for misrepresentation. module.exports.extSession = (kernel) -> (request, response) -> key = nconf.get("session:key") or undefined enable = nconf.get("session:enableExternal") noKey = "no session key have been configured" noHeaders = "unable to locate request headers" terribles = "got no valid response object found" assert _.isObject(kernel), "no kernel supplied" assert _.isObject(request?.headers), noHeaders assert _.isObject(response or null), terribles assert not _.isEmpty(key or 0), noKey.toString() assert headers = request.headers or new Object() assert constant = "X-Session-ID".toLowerCase() assert unix = moment().unix().toString().bold message = "Running ext-session middleware at U=%s" logger.debug message.toString(), unix.toString() assert _.isFunction next = _.last arguments return next() unless enable and enable is yes return next() if request.cookies?[key] or 0 return next() if request.signedCookies[key] return next() unless id = headers[constant] request.signedCookies[key] = id; next() # This middleware is a little handy utility that merges the set # of parameters, specifically the ones transferred via query or # via body mechanism into one object that can be used to easily # access the parameters without thinking about transfer mechanism. # This method also does capturing of some of the internal params. module.exports.parameters = (kernel) -> (request, response) -> noHeaders = "unable to locate request headers" terribles = "got no valid response object found" assert _.isObject(kernel), "no kernel supplied" assert _.isObject(request?.headers), noHeaders assert _.isObject(response or null), terribles assert try query = request.query or new Object() assert try body = request.body or new Object() assert _.isObject request.params = new Object() assert _.isObject parsed = url.parse request.url try _.extend request.params, query # query params try _.extend request.params, body # body params assert try request.path = parsed.pathname # path assert try request.date = new Date # timstamped assert try request.kernel = kernel # kernelized assert try request.uuid = uuid.v1() # UUID tag assert unix = moment().unix().toString().bold message = "Running parameters middleware at U=%s" logger.debug message.toString(), unix.toString() assert _.isFunction next = _.last arguments return next() unless request.headersSent # This plumbing add an `accepts` method onto the HTTP resonse object # which check if the request/response pair has an HTTP accept header # set to any of the values supplied when invoking this method. It is # very useful to use this method to negiotate the content type field. # This is a very dummy way of asking if a client supports something, # for a propert content negotiation please see the `send` plumbing. module.exports.accepts = (kernel) -> (request, response) -> noHeaders = "unable to locate request headers" terribles = "got no valid response object found" assert _.isObject(kernel), "no kernel supplied" assert _.isObject(request?.headers), noHeaders assert _.isObject(response or null), terribles assert unix = moment().unix().toString().bold message = "Running accepting middleware at U=%s" logger.debug message.toString(), unix.toString() assert _.isFunction next = try _.last arguments fn = (arg) -> next() unless request.headersSent fn response.accepts = (mimes...) -> # response fn handles = (pattern) -> try pattern.test accept patternize = (s) -> new RegExp RegExp.escape s accept = do -> request?.headers?.accept or "" regexps = _.filter mimes, (sx) ->_.isRegExp sx strings = _.filter mimes, (sx) ->_.isString sx strings = _.map strings, patternize.bind this assert merged = try _.merge(regexps, strings) return _.find(merged, handles) or undefined # A middleware that adds a `redirect` method to the response object. # This redirects to the supplied URL with the 302 status code and # the corresponding reason phrase. This method also sets some of the # necessary headers, such as nullary `Content-Length` and some other. # The redirected-to URL should be a valid, qualified URL to send to. module.exports.redirect = (kernel) -> assert redirect = "Redirecting from %s to %s" noHeaders = "unable to locate request headers" terribles = "got no valid response object found" assert _.isObject(kernel), "no kernel supplied" assert codes = http.STATUS_CODES or new Object() return (request, response) -> # middleware itself assert _.isObject(request?.headers), noHeaders assert _.isObject(response or null), terribles assert _.isFunction next = try _.last arguments assert unix = moment().unix().toString().bold message = "Running redirect middleware at U=%s" logger.debug message.toString(), unix.toString() fn = (arg) -> next() unless request.headersSent fn assert response.redirect = (url, status) -> assert to = try url.toString().underline assert from = try request.url?.underline assert relocated = status or 302 or null assert message = codes[relocated] or null response.setHeader "Location", url # to response.setHeader "Content-Length", 0 response.writeHead relocated, message logger.debug redirect.red, from, to return try response.end undefined
114141
### Copyright (c) 2013, <NAME> <<EMAIL>> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" assert = require "assert" uuid = require "node-uuid" asciify = require "asciify" connect = require "connect" logger = require "winston" send = require "response-send" platform = require "platform" colors = require "colors" nconf = require "nconf" https = require "https" http = require "http" util = require "util" url = require "url" {Negotiator} = require "negotiator" {RedisSession} = require "../shipped/session" # This middleware is really a wrapper around the `Connect` logger # that pipes all the request logs to the `Winston` instances that # is used throughout the framework to provide logging capabilities. # The format is takes from the `NConf` config or the default `dev`. # Refer to the implementation source code for more information. module.exports.logger = (kernel) -> assert levelKey = "log:request:level" assert formatKey = "<KEY>" format = try nconf.get(formatKey) or "dev" level = try nconf.get(levelKey) or "debug" filter = (s) -> s.replace "\n", new String() writer = (d) -> logger.log level, filter d msg = "Configure logger middleware at U=%s" assert _.isObject(kernel), "got no kernel" assert stamp = moment().unix().toString() options = new Object stream: write: writer assert options.format = format.toString() logger.debug msg.toString(), stamp.bold return try connect.logger options or {} # This middleware is really a wrapper around the `Connect` session # middleware. The reason it wraps it is to automatically configure # the session storage using the kernel and scoping configuration # data. This is automatically connected by the kernel instance. # Refer to the implementation source code for more information. module.exports.session = (kernel) -> nso = "no session configuration options" assert options = try nconf.get("session") assert shallow = try _.clone options or {} assert _.isObject(kernel), "got no kernel" redis = _.isObject nconf.get("redis") or 0 assert _.isObject(options), nso.toString() assert ux = moment().unix().toString().bold useRedis = "Using Redis session storage engine" message = "Configure session middleware at U=%s" shallow.store = RedisSession.obtain() if redis logger.debug message.toString(), ux.toString() logger.info useRedis.toString().blue if redis return connect.session shallow or new Object # This middleware is a wrapper around the `toobusy` module providing # the functinality that helps to prevent the server shutting down due # to the excessive load. This is done via monitoring of the event loop # polling and rating the loop lag time. If it's too big, the request # will not be processed, but simply dropped. This is a config wrapper. module.exports.threshold = (kernel) -> wrongReason = "no threshold reason supplied" wrongLagTime = "no valid lag time specified" noHeaders = "unable to locate request headers" options = nconf.get("threshold") or Object() assert _.isNumber(options?.lag), wrongLagTime assert _.isString(options?.reason), wrongReason assert _.isObject(kernel), "no kernel supplied" (busy = require "toobusy").maxLag try options.lag message = "Setting threshold maximum lag to %s ms" logger.info message.red, options.lag.toString().bold return (request, response) -> # middleware itself assert unix = moment().unix().toString().bold assert _.isObject(request?.headers), noHeaders message = "Running threshold middleware at U=%s" logger.debug message.toString(), unix.toString() assert _.isFunction next = _.last arguments return next undefined unless busy() is yes response.writeHead 503, options.reason return response.end options.reason # This middleware uses an external library to parse the incoming # user agent identification string into a platform description # object. If the user agent string is absent from the requesting # entity then the platform will not be defined on request object. # Refer to the implementation source code for more information. module.exports.platform = (kernel) -> (request, response) -> intern = "could not parse the platform data" noParser = "platform parse library malfunction" noPlatform = "missing platform middleware lib" noHeaders = "unable to locate request headers" assert _.isObject(platform or null), noPlatform assert _.isObject(request?.headers), noHeaders assert _.isFunction(platform?.parse), noParser agent = request.headers["user-agent"] or null return next() if not agent or _.isEmpty agent assert unix = moment().unix().toString().bold message = "Running platform middleware at U=%s" logger.debug message.toString(), unix.toString() request.platform = try (platform.parse agent) assert _.isObject(request.platform), intern assert _.isFunction next = _.last arguments return next() unless request.headersSent # This middleware uses an external library to parse the incoming # request metadata and then coerce it by using the standards to # a queriable form. This queriable forms allows to negotiate for # media types, accepted encoding, accepted language and so on. # Middleware can be used to serve the most appropriare content. module.exports.negotiate = (kernel) -> (request, response) -> terrible = "no valid request object found" noLibrary = "could not load negotiator lib" acked = "could not instantiate a negotiator" noHeaders = "unable to locate request headers" assert _.isObject(kernel), "no kernel supplied" assert _.isObject(Negotiator or 0), noLibrary assert _.isObject(request or null), terrible assert _.isObject(request?.headers), noHeaders request.negotiate = Negotiator request or {} assert _.isObject(request.negotiate), acked assert unix = moment().unix().toString().bold message = "Running negotiate middleware at U=%s" logger.debug message.toString(), unix.toString() assert _.isFunction next = _.last arguments return next() unless request.headersSent # A middleware that adds a `send` method to the response object. # This allows for automatic setting of `Content-Type` headers # based on the content that is being sent away. Use this method # rather than writing and ending the request in a direct way. # Is implemented using the external `response-send` library. module.exports.send = (kernel) -> (request, response) -> ack = "could not attach response sender method" noLibrary = "could not load the sender library" terrible = "got no valid response object found" noHeaders = "unable to locate request headers" assert _.isObject(kernel), "no kernel supplied" assert _.isFunction(try (send.json)), noLibrary assert _.isObject(response or null), terrible assert _.isObject(request?.headers), noHeaders try response.req = request unless response.req assert e = (seq) -> response.emit "send", seq... assert d = (seq) -> response.emit "sdat", seq... assert i = (seq) -> try _.isString _.first seq assert p = (seq, fn) -> fn.apply response, seq e = (f) -> (s...) -> e(s); (d(s) if i(s)); p(s, f) assert (try response.send = e send), ack.toString() assert response.json = try (e send.json spaces: 4) assert unix = moment().unix().toString().bold message = "Running sending middleware at U=%s" logger.debug message.toString(), unix.toString() assert _.isFunction next = _.last arguments return next() unless request.headersSent # A middeware that makes possible external specification of session # bearer via HTTP headers. This basically means - it allows for you # to explicitly specify a session ID via the `X-Session-ID` header. # It is a convenient way for the API client to identify themselves. # Beware that it might be used by clients to for misrepresentation. module.exports.extSession = (kernel) -> (request, response) -> key = nconf.get("session:key") or undefined enable = nconf.get("session:enableExternal") noKey = "no session key have been configured" noHeaders = "unable to locate request headers" terribles = "got no valid response object found" assert _.isObject(kernel), "no kernel supplied" assert _.isObject(request?.headers), noHeaders assert _.isObject(response or null), terribles assert not _.isEmpty(key or 0), noKey.toString() assert headers = request.headers or new Object() assert constant = "X-Session-ID".toLowerCase() assert unix = moment().unix().toString().bold message = "Running ext-session middleware at U=%s" logger.debug message.toString(), unix.toString() assert _.isFunction next = _.last arguments return next() unless enable and enable is yes return next() if request.cookies?[key] or 0 return next() if request.signedCookies[key] return next() unless id = headers[constant] request.signedCookies[key] = id; next() # This middleware is a little handy utility that merges the set # of parameters, specifically the ones transferred via query or # via body mechanism into one object that can be used to easily # access the parameters without thinking about transfer mechanism. # This method also does capturing of some of the internal params. module.exports.parameters = (kernel) -> (request, response) -> noHeaders = "unable to locate request headers" terribles = "got no valid response object found" assert _.isObject(kernel), "no kernel supplied" assert _.isObject(request?.headers), noHeaders assert _.isObject(response or null), terribles assert try query = request.query or new Object() assert try body = request.body or new Object() assert _.isObject request.params = new Object() assert _.isObject parsed = url.parse request.url try _.extend request.params, query # query params try _.extend request.params, body # body params assert try request.path = parsed.pathname # path assert try request.date = new Date # timstamped assert try request.kernel = kernel # kernelized assert try request.uuid = uuid.v1() # UUID tag assert unix = moment().unix().toString().bold message = "Running parameters middleware at U=%s" logger.debug message.toString(), unix.toString() assert _.isFunction next = _.last arguments return next() unless request.headersSent # This plumbing add an `accepts` method onto the HTTP resonse object # which check if the request/response pair has an HTTP accept header # set to any of the values supplied when invoking this method. It is # very useful to use this method to negiotate the content type field. # This is a very dummy way of asking if a client supports something, # for a propert content negotiation please see the `send` plumbing. module.exports.accepts = (kernel) -> (request, response) -> noHeaders = "unable to locate request headers" terribles = "got no valid response object found" assert _.isObject(kernel), "no kernel supplied" assert _.isObject(request?.headers), noHeaders assert _.isObject(response or null), terribles assert unix = moment().unix().toString().bold message = "Running accepting middleware at U=%s" logger.debug message.toString(), unix.toString() assert _.isFunction next = try _.last arguments fn = (arg) -> next() unless request.headersSent fn response.accepts = (mimes...) -> # response fn handles = (pattern) -> try pattern.test accept patternize = (s) -> new RegExp RegExp.escape s accept = do -> request?.headers?.accept or "" regexps = _.filter mimes, (sx) ->_.isRegExp sx strings = _.filter mimes, (sx) ->_.isString sx strings = _.map strings, patternize.bind this assert merged = try _.merge(regexps, strings) return _.find(merged, handles) or undefined # A middleware that adds a `redirect` method to the response object. # This redirects to the supplied URL with the 302 status code and # the corresponding reason phrase. This method also sets some of the # necessary headers, such as nullary `Content-Length` and some other. # The redirected-to URL should be a valid, qualified URL to send to. module.exports.redirect = (kernel) -> assert redirect = "Redirecting from %s to %s" noHeaders = "unable to locate request headers" terribles = "got no valid response object found" assert _.isObject(kernel), "no kernel supplied" assert codes = http.STATUS_CODES or new Object() return (request, response) -> # middleware itself assert _.isObject(request?.headers), noHeaders assert _.isObject(response or null), terribles assert _.isFunction next = try _.last arguments assert unix = moment().unix().toString().bold message = "Running redirect middleware at U=%s" logger.debug message.toString(), unix.toString() fn = (arg) -> next() unless request.headersSent fn assert response.redirect = (url, status) -> assert to = try url.toString().underline assert from = try request.url?.underline assert relocated = status or 302 or null assert message = codes[relocated] or null response.setHeader "Location", url # to response.setHeader "Content-Length", 0 response.writeHead relocated, message logger.debug redirect.red, from, to return try response.end undefined
true
### Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" assert = require "assert" uuid = require "node-uuid" asciify = require "asciify" connect = require "connect" logger = require "winston" send = require "response-send" platform = require "platform" colors = require "colors" nconf = require "nconf" https = require "https" http = require "http" util = require "util" url = require "url" {Negotiator} = require "negotiator" {RedisSession} = require "../shipped/session" # This middleware is really a wrapper around the `Connect` logger # that pipes all the request logs to the `Winston` instances that # is used throughout the framework to provide logging capabilities. # The format is takes from the `NConf` config or the default `dev`. # Refer to the implementation source code for more information. module.exports.logger = (kernel) -> assert levelKey = "log:request:level" assert formatKey = "PI:KEY:<KEY>END_PI" format = try nconf.get(formatKey) or "dev" level = try nconf.get(levelKey) or "debug" filter = (s) -> s.replace "\n", new String() writer = (d) -> logger.log level, filter d msg = "Configure logger middleware at U=%s" assert _.isObject(kernel), "got no kernel" assert stamp = moment().unix().toString() options = new Object stream: write: writer assert options.format = format.toString() logger.debug msg.toString(), stamp.bold return try connect.logger options or {} # This middleware is really a wrapper around the `Connect` session # middleware. The reason it wraps it is to automatically configure # the session storage using the kernel and scoping configuration # data. This is automatically connected by the kernel instance. # Refer to the implementation source code for more information. module.exports.session = (kernel) -> nso = "no session configuration options" assert options = try nconf.get("session") assert shallow = try _.clone options or {} assert _.isObject(kernel), "got no kernel" redis = _.isObject nconf.get("redis") or 0 assert _.isObject(options), nso.toString() assert ux = moment().unix().toString().bold useRedis = "Using Redis session storage engine" message = "Configure session middleware at U=%s" shallow.store = RedisSession.obtain() if redis logger.debug message.toString(), ux.toString() logger.info useRedis.toString().blue if redis return connect.session shallow or new Object # This middleware is a wrapper around the `toobusy` module providing # the functinality that helps to prevent the server shutting down due # to the excessive load. This is done via monitoring of the event loop # polling and rating the loop lag time. If it's too big, the request # will not be processed, but simply dropped. This is a config wrapper. module.exports.threshold = (kernel) -> wrongReason = "no threshold reason supplied" wrongLagTime = "no valid lag time specified" noHeaders = "unable to locate request headers" options = nconf.get("threshold") or Object() assert _.isNumber(options?.lag), wrongLagTime assert _.isString(options?.reason), wrongReason assert _.isObject(kernel), "no kernel supplied" (busy = require "toobusy").maxLag try options.lag message = "Setting threshold maximum lag to %s ms" logger.info message.red, options.lag.toString().bold return (request, response) -> # middleware itself assert unix = moment().unix().toString().bold assert _.isObject(request?.headers), noHeaders message = "Running threshold middleware at U=%s" logger.debug message.toString(), unix.toString() assert _.isFunction next = _.last arguments return next undefined unless busy() is yes response.writeHead 503, options.reason return response.end options.reason # This middleware uses an external library to parse the incoming # user agent identification string into a platform description # object. If the user agent string is absent from the requesting # entity then the platform will not be defined on request object. # Refer to the implementation source code for more information. module.exports.platform = (kernel) -> (request, response) -> intern = "could not parse the platform data" noParser = "platform parse library malfunction" noPlatform = "missing platform middleware lib" noHeaders = "unable to locate request headers" assert _.isObject(platform or null), noPlatform assert _.isObject(request?.headers), noHeaders assert _.isFunction(platform?.parse), noParser agent = request.headers["user-agent"] or null return next() if not agent or _.isEmpty agent assert unix = moment().unix().toString().bold message = "Running platform middleware at U=%s" logger.debug message.toString(), unix.toString() request.platform = try (platform.parse agent) assert _.isObject(request.platform), intern assert _.isFunction next = _.last arguments return next() unless request.headersSent # This middleware uses an external library to parse the incoming # request metadata and then coerce it by using the standards to # a queriable form. This queriable forms allows to negotiate for # media types, accepted encoding, accepted language and so on. # Middleware can be used to serve the most appropriare content. module.exports.negotiate = (kernel) -> (request, response) -> terrible = "no valid request object found" noLibrary = "could not load negotiator lib" acked = "could not instantiate a negotiator" noHeaders = "unable to locate request headers" assert _.isObject(kernel), "no kernel supplied" assert _.isObject(Negotiator or 0), noLibrary assert _.isObject(request or null), terrible assert _.isObject(request?.headers), noHeaders request.negotiate = Negotiator request or {} assert _.isObject(request.negotiate), acked assert unix = moment().unix().toString().bold message = "Running negotiate middleware at U=%s" logger.debug message.toString(), unix.toString() assert _.isFunction next = _.last arguments return next() unless request.headersSent # A middleware that adds a `send` method to the response object. # This allows for automatic setting of `Content-Type` headers # based on the content that is being sent away. Use this method # rather than writing and ending the request in a direct way. # Is implemented using the external `response-send` library. module.exports.send = (kernel) -> (request, response) -> ack = "could not attach response sender method" noLibrary = "could not load the sender library" terrible = "got no valid response object found" noHeaders = "unable to locate request headers" assert _.isObject(kernel), "no kernel supplied" assert _.isFunction(try (send.json)), noLibrary assert _.isObject(response or null), terrible assert _.isObject(request?.headers), noHeaders try response.req = request unless response.req assert e = (seq) -> response.emit "send", seq... assert d = (seq) -> response.emit "sdat", seq... assert i = (seq) -> try _.isString _.first seq assert p = (seq, fn) -> fn.apply response, seq e = (f) -> (s...) -> e(s); (d(s) if i(s)); p(s, f) assert (try response.send = e send), ack.toString() assert response.json = try (e send.json spaces: 4) assert unix = moment().unix().toString().bold message = "Running sending middleware at U=%s" logger.debug message.toString(), unix.toString() assert _.isFunction next = _.last arguments return next() unless request.headersSent # A middeware that makes possible external specification of session # bearer via HTTP headers. This basically means - it allows for you # to explicitly specify a session ID via the `X-Session-ID` header. # It is a convenient way for the API client to identify themselves. # Beware that it might be used by clients to for misrepresentation. module.exports.extSession = (kernel) -> (request, response) -> key = nconf.get("session:key") or undefined enable = nconf.get("session:enableExternal") noKey = "no session key have been configured" noHeaders = "unable to locate request headers" terribles = "got no valid response object found" assert _.isObject(kernel), "no kernel supplied" assert _.isObject(request?.headers), noHeaders assert _.isObject(response or null), terribles assert not _.isEmpty(key or 0), noKey.toString() assert headers = request.headers or new Object() assert constant = "X-Session-ID".toLowerCase() assert unix = moment().unix().toString().bold message = "Running ext-session middleware at U=%s" logger.debug message.toString(), unix.toString() assert _.isFunction next = _.last arguments return next() unless enable and enable is yes return next() if request.cookies?[key] or 0 return next() if request.signedCookies[key] return next() unless id = headers[constant] request.signedCookies[key] = id; next() # This middleware is a little handy utility that merges the set # of parameters, specifically the ones transferred via query or # via body mechanism into one object that can be used to easily # access the parameters without thinking about transfer mechanism. # This method also does capturing of some of the internal params. module.exports.parameters = (kernel) -> (request, response) -> noHeaders = "unable to locate request headers" terribles = "got no valid response object found" assert _.isObject(kernel), "no kernel supplied" assert _.isObject(request?.headers), noHeaders assert _.isObject(response or null), terribles assert try query = request.query or new Object() assert try body = request.body or new Object() assert _.isObject request.params = new Object() assert _.isObject parsed = url.parse request.url try _.extend request.params, query # query params try _.extend request.params, body # body params assert try request.path = parsed.pathname # path assert try request.date = new Date # timstamped assert try request.kernel = kernel # kernelized assert try request.uuid = uuid.v1() # UUID tag assert unix = moment().unix().toString().bold message = "Running parameters middleware at U=%s" logger.debug message.toString(), unix.toString() assert _.isFunction next = _.last arguments return next() unless request.headersSent # This plumbing add an `accepts` method onto the HTTP resonse object # which check if the request/response pair has an HTTP accept header # set to any of the values supplied when invoking this method. It is # very useful to use this method to negiotate the content type field. # This is a very dummy way of asking if a client supports something, # for a propert content negotiation please see the `send` plumbing. module.exports.accepts = (kernel) -> (request, response) -> noHeaders = "unable to locate request headers" terribles = "got no valid response object found" assert _.isObject(kernel), "no kernel supplied" assert _.isObject(request?.headers), noHeaders assert _.isObject(response or null), terribles assert unix = moment().unix().toString().bold message = "Running accepting middleware at U=%s" logger.debug message.toString(), unix.toString() assert _.isFunction next = try _.last arguments fn = (arg) -> next() unless request.headersSent fn response.accepts = (mimes...) -> # response fn handles = (pattern) -> try pattern.test accept patternize = (s) -> new RegExp RegExp.escape s accept = do -> request?.headers?.accept or "" regexps = _.filter mimes, (sx) ->_.isRegExp sx strings = _.filter mimes, (sx) ->_.isString sx strings = _.map strings, patternize.bind this assert merged = try _.merge(regexps, strings) return _.find(merged, handles) or undefined # A middleware that adds a `redirect` method to the response object. # This redirects to the supplied URL with the 302 status code and # the corresponding reason phrase. This method also sets some of the # necessary headers, such as nullary `Content-Length` and some other. # The redirected-to URL should be a valid, qualified URL to send to. module.exports.redirect = (kernel) -> assert redirect = "Redirecting from %s to %s" noHeaders = "unable to locate request headers" terribles = "got no valid response object found" assert _.isObject(kernel), "no kernel supplied" assert codes = http.STATUS_CODES or new Object() return (request, response) -> # middleware itself assert _.isObject(request?.headers), noHeaders assert _.isObject(response or null), terribles assert _.isFunction next = try _.last arguments assert unix = moment().unix().toString().bold message = "Running redirect middleware at U=%s" logger.debug message.toString(), unix.toString() fn = (arg) -> next() unless request.headersSent fn assert response.redirect = (url, status) -> assert to = try url.toString().underline assert from = try request.url?.underline assert relocated = status or 302 or null assert message = codes[relocated] or null response.setHeader "Location", url # to response.setHeader "Content-Length", 0 response.writeHead relocated, message logger.debug redirect.red, from, to return try response.end undefined
[ { "context": "adyPurchased')\n supportEmail: \"<a href='mailto:support@codecombat.com'>support@codecombat.com</a>\"\n }\n\n events:\n '", "end": 825, "score": 0.9999265670776367, "start": 803, "tag": "EMAIL", "value": "support@codecombat.com" }, { "context": "rtEmail: \"<a href='mailto:support@codecombat.com'>support@codecombat.com</a>\"\n }\n\n events:\n 'input input[name=\"quanti", "end": 849, "score": 0.9999246597290039, "start": 827, "tag": "EMAIL", "value": "support@codecombat.com" } ]
app/views/teachers/PurchaseStarterLicensesModal.coffee
michaelrn/codecombat
3
require('app/styles/teachers/purchase-starter-licenses-modal.sass') ModalView = require 'views/core/ModalView' State = require 'models/State' utils = require 'core/utils' Products = require 'collections/Products' Prepaids = require 'collections/Prepaids' stripeHandler = require 'core/services/stripe' { STARTER_LICENCE_LENGTH_MONTHS } = require 'app/core/constants' module.exports = class PurchaseStarterLicensesModal extends ModalView id: 'purchase-starter-licenses-modal' template: require 'templates/teachers/purchase-starter-licenses-modal' maxQuantityStarterLicenses: 75 i18nData: -> { @maxQuantityStarterLicenses, starterLicenseLengthMonths: STARTER_LICENCE_LENGTH_MONTHS, quantityAlreadyPurchased: @state.get('quantityAlreadyPurchased') supportEmail: "<a href='mailto:support@codecombat.com'>support@codecombat.com</a>" } events: 'input input[name="quantity"]': 'onInputQuantity' 'change input[name="quantity"]': 'onInputQuantity' 'click .pay-now-btn': 'onClickPayNowButton' initialize: (options) -> window.tracker?.trackEvent 'Purchase Starter License: Modal Opened', category: 'Teachers', ['Mixpanel'] @listenTo stripeHandler, 'received-token', @onStripeReceivedToken @state = new State({ quantityToBuy: 10 centsPerStudent: undefined dollarsPerStudent: undefined quantityAlreadyPurchased: undefined quantityAllowedToPurchase: undefined }) @products = new Products() @supermodel.loadCollection(@products, 'products') @listenTo @products, 'sync change update', @onProductsUpdated @prepaids = new Prepaids() @supermodel.trackRequest @prepaids.fetchByCreator(me.id) @listenTo @prepaids, 'sync change update', @onPrepaidsUpdated @listenTo @state, 'change', -> @render() super(options) onLoaded: -> super() getDollarsPerStudentString: -> utils.formatDollarValue(@state.get('dollarsPerStudent')) getTotalPriceString: -> utils.formatDollarValue(@state.get('dollarsPerStudent') * @state.get('quantityToBuy')) boundedValue: (value) -> Math.max(Math.min(value, @state.get('quantityAllowedToPurchase')), 0) onPrepaidsUpdated: -> starterLicenses = new Prepaids(@prepaids.where({ type: 'starter_license' })) quantityAlreadyPurchased = starterLicenses.totalMaxRedeemers() quantityAllowedToPurchase = Math.max(@maxQuantityStarterLicenses - quantityAlreadyPurchased, 0) @state.set { quantityAlreadyPurchased quantityAllowedToPurchase quantityToBuy: Math.max(Math.min(@state.get('quantityToBuy'), quantityAllowedToPurchase), 0) } onProductsUpdated: -> starterLicense = @products.findWhere({ name: 'starter_license' }) @state.set { centsPerStudent: starterLicense.get('amount') dollarsPerStudent: starterLicense.get('amount') / 100 } onInputQuantity: (e) -> $input = $(e.currentTarget) inputValue = parseFloat($input.val()) or 0 boundedValue = inputValue if $input.val() isnt '' boundedValue = @boundedValue(inputValue) if boundedValue isnt inputValue $input.val(boundedValue) @state.set { quantityToBuy: boundedValue } onClickPayNowButton: -> window.tracker?.trackEvent 'Purchase Starter License: Pay Now Clicked', category: 'Teachers', ['Mixpanel'] @state.set({ purchaseProgress: undefined purchaseProgressMessage: undefined }) application.tracker?.trackEvent 'Started course prepaid purchase', { price: @state.get('centsPerStudent'), students: @state.get('quantityToBuy') } stripeHandler.open amount: @state.get('quantityToBuy') * @state.get('centsPerStudent') description: "Starter course access for #{@state.get('quantityToBuy')} students" bitcoin: true alipay: if me.get('country') is 'china' or (me.get('preferredLanguage') or 'en-US')[...2] is 'zh' then true else 'auto' onStripeReceivedToken: (e) -> @state.set({ purchaseProgress: 'purchasing' }) @render?() data = maxRedeemers: @state.get('quantityToBuy') type: 'starter_license' stripe: token: e.token.id timestamp: new Date().getTime() $.ajax({ url: '/db/starter-license-prepaid', data: data, method: 'POST', context: @ success: -> application.tracker?.trackEvent 'Finished starter license purchase', {price: @state.get('centsPerStudent'), seats: @state.get('quantityToBuy')} @state.set({ purchaseProgress: 'purchased' }) application.router.navigate('/teachers/licenses', { trigger: true }) error: (jqxhr, textStatus, errorThrown) -> application.tracker?.trackEvent 'Failed starter license purchase', status: textStatus if jqxhr.status is 402 @state.set({ purchaseProgress: 'error' purchaseProgressMessage: arguments[2] }) else @state.set({ purchaseProgress: 'error' purchaseProgressMessage: "#{jqxhr.status}: #{jqxhr.responseJSON?.message or 'Unknown Error'}" }) @render?() })
87063
require('app/styles/teachers/purchase-starter-licenses-modal.sass') ModalView = require 'views/core/ModalView' State = require 'models/State' utils = require 'core/utils' Products = require 'collections/Products' Prepaids = require 'collections/Prepaids' stripeHandler = require 'core/services/stripe' { STARTER_LICENCE_LENGTH_MONTHS } = require 'app/core/constants' module.exports = class PurchaseStarterLicensesModal extends ModalView id: 'purchase-starter-licenses-modal' template: require 'templates/teachers/purchase-starter-licenses-modal' maxQuantityStarterLicenses: 75 i18nData: -> { @maxQuantityStarterLicenses, starterLicenseLengthMonths: STARTER_LICENCE_LENGTH_MONTHS, quantityAlreadyPurchased: @state.get('quantityAlreadyPurchased') supportEmail: "<a href='mailto:<EMAIL>'><EMAIL></a>" } events: 'input input[name="quantity"]': 'onInputQuantity' 'change input[name="quantity"]': 'onInputQuantity' 'click .pay-now-btn': 'onClickPayNowButton' initialize: (options) -> window.tracker?.trackEvent 'Purchase Starter License: Modal Opened', category: 'Teachers', ['Mixpanel'] @listenTo stripeHandler, 'received-token', @onStripeReceivedToken @state = new State({ quantityToBuy: 10 centsPerStudent: undefined dollarsPerStudent: undefined quantityAlreadyPurchased: undefined quantityAllowedToPurchase: undefined }) @products = new Products() @supermodel.loadCollection(@products, 'products') @listenTo @products, 'sync change update', @onProductsUpdated @prepaids = new Prepaids() @supermodel.trackRequest @prepaids.fetchByCreator(me.id) @listenTo @prepaids, 'sync change update', @onPrepaidsUpdated @listenTo @state, 'change', -> @render() super(options) onLoaded: -> super() getDollarsPerStudentString: -> utils.formatDollarValue(@state.get('dollarsPerStudent')) getTotalPriceString: -> utils.formatDollarValue(@state.get('dollarsPerStudent') * @state.get('quantityToBuy')) boundedValue: (value) -> Math.max(Math.min(value, @state.get('quantityAllowedToPurchase')), 0) onPrepaidsUpdated: -> starterLicenses = new Prepaids(@prepaids.where({ type: 'starter_license' })) quantityAlreadyPurchased = starterLicenses.totalMaxRedeemers() quantityAllowedToPurchase = Math.max(@maxQuantityStarterLicenses - quantityAlreadyPurchased, 0) @state.set { quantityAlreadyPurchased quantityAllowedToPurchase quantityToBuy: Math.max(Math.min(@state.get('quantityToBuy'), quantityAllowedToPurchase), 0) } onProductsUpdated: -> starterLicense = @products.findWhere({ name: 'starter_license' }) @state.set { centsPerStudent: starterLicense.get('amount') dollarsPerStudent: starterLicense.get('amount') / 100 } onInputQuantity: (e) -> $input = $(e.currentTarget) inputValue = parseFloat($input.val()) or 0 boundedValue = inputValue if $input.val() isnt '' boundedValue = @boundedValue(inputValue) if boundedValue isnt inputValue $input.val(boundedValue) @state.set { quantityToBuy: boundedValue } onClickPayNowButton: -> window.tracker?.trackEvent 'Purchase Starter License: Pay Now Clicked', category: 'Teachers', ['Mixpanel'] @state.set({ purchaseProgress: undefined purchaseProgressMessage: undefined }) application.tracker?.trackEvent 'Started course prepaid purchase', { price: @state.get('centsPerStudent'), students: @state.get('quantityToBuy') } stripeHandler.open amount: @state.get('quantityToBuy') * @state.get('centsPerStudent') description: "Starter course access for #{@state.get('quantityToBuy')} students" bitcoin: true alipay: if me.get('country') is 'china' or (me.get('preferredLanguage') or 'en-US')[...2] is 'zh' then true else 'auto' onStripeReceivedToken: (e) -> @state.set({ purchaseProgress: 'purchasing' }) @render?() data = maxRedeemers: @state.get('quantityToBuy') type: 'starter_license' stripe: token: e.token.id timestamp: new Date().getTime() $.ajax({ url: '/db/starter-license-prepaid', data: data, method: 'POST', context: @ success: -> application.tracker?.trackEvent 'Finished starter license purchase', {price: @state.get('centsPerStudent'), seats: @state.get('quantityToBuy')} @state.set({ purchaseProgress: 'purchased' }) application.router.navigate('/teachers/licenses', { trigger: true }) error: (jqxhr, textStatus, errorThrown) -> application.tracker?.trackEvent 'Failed starter license purchase', status: textStatus if jqxhr.status is 402 @state.set({ purchaseProgress: 'error' purchaseProgressMessage: arguments[2] }) else @state.set({ purchaseProgress: 'error' purchaseProgressMessage: "#{jqxhr.status}: #{jqxhr.responseJSON?.message or 'Unknown Error'}" }) @render?() })
true
require('app/styles/teachers/purchase-starter-licenses-modal.sass') ModalView = require 'views/core/ModalView' State = require 'models/State' utils = require 'core/utils' Products = require 'collections/Products' Prepaids = require 'collections/Prepaids' stripeHandler = require 'core/services/stripe' { STARTER_LICENCE_LENGTH_MONTHS } = require 'app/core/constants' module.exports = class PurchaseStarterLicensesModal extends ModalView id: 'purchase-starter-licenses-modal' template: require 'templates/teachers/purchase-starter-licenses-modal' maxQuantityStarterLicenses: 75 i18nData: -> { @maxQuantityStarterLicenses, starterLicenseLengthMonths: STARTER_LICENCE_LENGTH_MONTHS, quantityAlreadyPurchased: @state.get('quantityAlreadyPurchased') supportEmail: "<a href='mailto:PI:EMAIL:<EMAIL>END_PI'>PI:EMAIL:<EMAIL>END_PI</a>" } events: 'input input[name="quantity"]': 'onInputQuantity' 'change input[name="quantity"]': 'onInputQuantity' 'click .pay-now-btn': 'onClickPayNowButton' initialize: (options) -> window.tracker?.trackEvent 'Purchase Starter License: Modal Opened', category: 'Teachers', ['Mixpanel'] @listenTo stripeHandler, 'received-token', @onStripeReceivedToken @state = new State({ quantityToBuy: 10 centsPerStudent: undefined dollarsPerStudent: undefined quantityAlreadyPurchased: undefined quantityAllowedToPurchase: undefined }) @products = new Products() @supermodel.loadCollection(@products, 'products') @listenTo @products, 'sync change update', @onProductsUpdated @prepaids = new Prepaids() @supermodel.trackRequest @prepaids.fetchByCreator(me.id) @listenTo @prepaids, 'sync change update', @onPrepaidsUpdated @listenTo @state, 'change', -> @render() super(options) onLoaded: -> super() getDollarsPerStudentString: -> utils.formatDollarValue(@state.get('dollarsPerStudent')) getTotalPriceString: -> utils.formatDollarValue(@state.get('dollarsPerStudent') * @state.get('quantityToBuy')) boundedValue: (value) -> Math.max(Math.min(value, @state.get('quantityAllowedToPurchase')), 0) onPrepaidsUpdated: -> starterLicenses = new Prepaids(@prepaids.where({ type: 'starter_license' })) quantityAlreadyPurchased = starterLicenses.totalMaxRedeemers() quantityAllowedToPurchase = Math.max(@maxQuantityStarterLicenses - quantityAlreadyPurchased, 0) @state.set { quantityAlreadyPurchased quantityAllowedToPurchase quantityToBuy: Math.max(Math.min(@state.get('quantityToBuy'), quantityAllowedToPurchase), 0) } onProductsUpdated: -> starterLicense = @products.findWhere({ name: 'starter_license' }) @state.set { centsPerStudent: starterLicense.get('amount') dollarsPerStudent: starterLicense.get('amount') / 100 } onInputQuantity: (e) -> $input = $(e.currentTarget) inputValue = parseFloat($input.val()) or 0 boundedValue = inputValue if $input.val() isnt '' boundedValue = @boundedValue(inputValue) if boundedValue isnt inputValue $input.val(boundedValue) @state.set { quantityToBuy: boundedValue } onClickPayNowButton: -> window.tracker?.trackEvent 'Purchase Starter License: Pay Now Clicked', category: 'Teachers', ['Mixpanel'] @state.set({ purchaseProgress: undefined purchaseProgressMessage: undefined }) application.tracker?.trackEvent 'Started course prepaid purchase', { price: @state.get('centsPerStudent'), students: @state.get('quantityToBuy') } stripeHandler.open amount: @state.get('quantityToBuy') * @state.get('centsPerStudent') description: "Starter course access for #{@state.get('quantityToBuy')} students" bitcoin: true alipay: if me.get('country') is 'china' or (me.get('preferredLanguage') or 'en-US')[...2] is 'zh' then true else 'auto' onStripeReceivedToken: (e) -> @state.set({ purchaseProgress: 'purchasing' }) @render?() data = maxRedeemers: @state.get('quantityToBuy') type: 'starter_license' stripe: token: e.token.id timestamp: new Date().getTime() $.ajax({ url: '/db/starter-license-prepaid', data: data, method: 'POST', context: @ success: -> application.tracker?.trackEvent 'Finished starter license purchase', {price: @state.get('centsPerStudent'), seats: @state.get('quantityToBuy')} @state.set({ purchaseProgress: 'purchased' }) application.router.navigate('/teachers/licenses', { trigger: true }) error: (jqxhr, textStatus, errorThrown) -> application.tracker?.trackEvent 'Failed starter license purchase', status: textStatus if jqxhr.status is 402 @state.set({ purchaseProgress: 'error' purchaseProgressMessage: arguments[2] }) else @state.set({ purchaseProgress: 'error' purchaseProgressMessage: "#{jqxhr.status}: #{jqxhr.responseJSON?.message or 'Unknown Error'}" }) @render?() })
[ { "context": "/01/resizing-images-in-browser-using-canvas.html\n# Patrick Oswald version from comment, coffeescript and further si", "end": 5566, "score": 0.9991756677627563, "start": 5552, "tag": "NAME", "value": "Patrick Oswald" } ]
node_modules/wiki-client/lib/factory.coffee
jpietrok-pnnl/wiki
0
# A Factory plugin provides a drop zone for desktop content # destined to be one or another kind of item. Double click # will turn it into a normal paragraph. neighborhood = require './neighborhood' plugin = require './plugin' resolve = require './resolve' pageHandler = require './pageHandler' editor = require './editor' synopsis = require './synopsis' drop = require './drop' active = require './active' escape = (line) -> line .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/\n/g, '<br>') emit = ($item, item) -> $item.append '<p>Double-Click to Edit<br>Drop Text or Image to Insert</p>' showMenu = -> menu = $item.find('p').append """ <br>Or Choose a Plugin <center> <table style="text-align:left;"> <tr><td><ul id=format><td><ul id=data><td><ul id=other> """ for info in window.catalog column = info.category || 'other' column = 'other' unless column in ['format', 'data'] menu.find('#'+column).append """ <li><a class="menu" href="#" title="#{info.title}">#{info.name}</a></li> """ menu.find('a.menu').click (evt)-> $item.removeClass('factory').addClass(item.type=evt.target.text.toLowerCase()) $item.unbind() evt.preventDefault() active.set $item.parents(".page") editor.textEditor $item, item showPrompt = -> $item.append "<p>#{resolve.resolveLinks(item.prompt, escape)}</b>" if item.prompt showPrompt() else if window.catalog? showMenu() else wiki.origin.get 'system/factories.json', (error, data) -> console.log 'factory', data window.catalog = data showMenu() bind = ($item, item) -> syncEditAction = -> $item.empty().unbind() $item.removeClass("factory").addClass(item.type) $page = $item.parents('.page:first') try $item.data 'pageElement', $page $item.data 'item', item plugin.getPlugin item.type, (plugin) -> plugin.emit $item, item plugin.bind $item, item catch err $item.append "<p class='error'>#{err}</p>" pageHandler.put $page, {type: 'edit', id: item.id, item: item} punt = (data) -> item.prompt = "Unexpected Item\nWe can't make sense of the drop.\nTry something else or see [[About Factory Plugin]]." data.userAgent = navigator.userAgent item.punt = data syncEditAction() addReference = (data) -> wiki.site(data.site).get "#{data.slug}.json", (err, remote) -> if !err item.type = 'reference' item.site = data.site item.slug = data.slug item.title = remote.title || data.slug item.text = synopsis remote syncEditAction() neighborhood.registerNeighbor item.site if item.site? addVideo = (video) -> item.type = 'video' item.text = "#{video.text}\n(double-click to edit caption)\n" syncEditAction() readFile = (file) -> if file? [majorType, minorType] = file.type.split("/") reader = new FileReader() if majorType == "image" reader.onload = (loadEvent) -> item.type = 'image' item.url = resizeImage loadEvent.target.result item.caption ||= "Uploaded image" syncEditAction() reader.readAsDataURL(file) else if majorType == "text" reader.onload = (loadEvent) -> result = loadEvent.target.result if minorType == 'csv' item.type = 'data' item.columns = (array = csvToArray result)[0] item.data = arrayToJson array item.text = file.fileName else item.type = 'paragraph' item.text = result syncEditAction() reader.readAsText(file) else punt name: file.name type: file.type size: file.size fileName: file.fileName lastModified: file.lastModified $item.dblclick (e) -> if e.shiftKey editor.textEditor $item, item, {field: 'prompt'} else $item.removeClass('factory').addClass(item.type = 'paragraph') $item.unbind() editor.textEditor $item, item $item.bind 'dragenter', (evt) -> evt.preventDefault() $item.bind 'dragover', (evt) -> evt.preventDefault() $item.bind "drop", drop.dispatch page: addReference file: readFile video: addVideo punt: punt # from http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm # via http://stackoverflow.com/questions/1293147/javascript-code-to-parse-csv-data csvToArray = (strData, strDelimiter) -> strDelimiter = (strDelimiter or ",") objPattern = new RegExp(("(\\" + strDelimiter + "|\\r?\\n|\\r|^)" + "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" + "([^\"\\" + strDelimiter + "\\r\\n]*))"), "gi") arrData = [ [] ] arrMatches = null while arrMatches = objPattern.exec(strData) strMatchedDelimiter = arrMatches[1] arrData.push [] if strMatchedDelimiter.length and (strMatchedDelimiter isnt strDelimiter) if arrMatches[2] strMatchedValue = arrMatches[2].replace(new RegExp("\"\"", "g"), "\"") else strMatchedValue = arrMatches[3] arrData[arrData.length - 1].push strMatchedValue arrData arrayToJson = (array) -> cols = array.shift() rowToObject = (row) -> obj = {} for [k, v] in _.zip(cols, row) obj[k] = v if v? && (v.match /\S/) && v != 'NULL' obj (rowToObject row for row in array) # from http://www.benknowscode.com/2014/01/resizing-images-in-browser-using-canvas.html # Patrick Oswald version from comment, coffeescript and further simplification for wiki resizeImage = (dataURL) -> smallEnough = (src) -> src.width <= 500 || src.height <= 300 squeezeSteps = (src) -> return src if smallEnough src canvas = document.createElement 'canvas' canvas.width = cW = src.width / 2 canvas.height = cH = src.height / 2 context = canvas.getContext '2d' context.drawImage src, 0, 0, cW, cH return squeezeSteps canvas img = new Image img.src = dataURL return dataURL if smallEnough img squeezeSteps(img).toDataURL 'image/jpeg', .5 # medium quality encoding module.exports = {emit, bind}
81096
# A Factory plugin provides a drop zone for desktop content # destined to be one or another kind of item. Double click # will turn it into a normal paragraph. neighborhood = require './neighborhood' plugin = require './plugin' resolve = require './resolve' pageHandler = require './pageHandler' editor = require './editor' synopsis = require './synopsis' drop = require './drop' active = require './active' escape = (line) -> line .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/\n/g, '<br>') emit = ($item, item) -> $item.append '<p>Double-Click to Edit<br>Drop Text or Image to Insert</p>' showMenu = -> menu = $item.find('p').append """ <br>Or Choose a Plugin <center> <table style="text-align:left;"> <tr><td><ul id=format><td><ul id=data><td><ul id=other> """ for info in window.catalog column = info.category || 'other' column = 'other' unless column in ['format', 'data'] menu.find('#'+column).append """ <li><a class="menu" href="#" title="#{info.title}">#{info.name}</a></li> """ menu.find('a.menu').click (evt)-> $item.removeClass('factory').addClass(item.type=evt.target.text.toLowerCase()) $item.unbind() evt.preventDefault() active.set $item.parents(".page") editor.textEditor $item, item showPrompt = -> $item.append "<p>#{resolve.resolveLinks(item.prompt, escape)}</b>" if item.prompt showPrompt() else if window.catalog? showMenu() else wiki.origin.get 'system/factories.json', (error, data) -> console.log 'factory', data window.catalog = data showMenu() bind = ($item, item) -> syncEditAction = -> $item.empty().unbind() $item.removeClass("factory").addClass(item.type) $page = $item.parents('.page:first') try $item.data 'pageElement', $page $item.data 'item', item plugin.getPlugin item.type, (plugin) -> plugin.emit $item, item plugin.bind $item, item catch err $item.append "<p class='error'>#{err}</p>" pageHandler.put $page, {type: 'edit', id: item.id, item: item} punt = (data) -> item.prompt = "Unexpected Item\nWe can't make sense of the drop.\nTry something else or see [[About Factory Plugin]]." data.userAgent = navigator.userAgent item.punt = data syncEditAction() addReference = (data) -> wiki.site(data.site).get "#{data.slug}.json", (err, remote) -> if !err item.type = 'reference' item.site = data.site item.slug = data.slug item.title = remote.title || data.slug item.text = synopsis remote syncEditAction() neighborhood.registerNeighbor item.site if item.site? addVideo = (video) -> item.type = 'video' item.text = "#{video.text}\n(double-click to edit caption)\n" syncEditAction() readFile = (file) -> if file? [majorType, minorType] = file.type.split("/") reader = new FileReader() if majorType == "image" reader.onload = (loadEvent) -> item.type = 'image' item.url = resizeImage loadEvent.target.result item.caption ||= "Uploaded image" syncEditAction() reader.readAsDataURL(file) else if majorType == "text" reader.onload = (loadEvent) -> result = loadEvent.target.result if minorType == 'csv' item.type = 'data' item.columns = (array = csvToArray result)[0] item.data = arrayToJson array item.text = file.fileName else item.type = 'paragraph' item.text = result syncEditAction() reader.readAsText(file) else punt name: file.name type: file.type size: file.size fileName: file.fileName lastModified: file.lastModified $item.dblclick (e) -> if e.shiftKey editor.textEditor $item, item, {field: 'prompt'} else $item.removeClass('factory').addClass(item.type = 'paragraph') $item.unbind() editor.textEditor $item, item $item.bind 'dragenter', (evt) -> evt.preventDefault() $item.bind 'dragover', (evt) -> evt.preventDefault() $item.bind "drop", drop.dispatch page: addReference file: readFile video: addVideo punt: punt # from http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm # via http://stackoverflow.com/questions/1293147/javascript-code-to-parse-csv-data csvToArray = (strData, strDelimiter) -> strDelimiter = (strDelimiter or ",") objPattern = new RegExp(("(\\" + strDelimiter + "|\\r?\\n|\\r|^)" + "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" + "([^\"\\" + strDelimiter + "\\r\\n]*))"), "gi") arrData = [ [] ] arrMatches = null while arrMatches = objPattern.exec(strData) strMatchedDelimiter = arrMatches[1] arrData.push [] if strMatchedDelimiter.length and (strMatchedDelimiter isnt strDelimiter) if arrMatches[2] strMatchedValue = arrMatches[2].replace(new RegExp("\"\"", "g"), "\"") else strMatchedValue = arrMatches[3] arrData[arrData.length - 1].push strMatchedValue arrData arrayToJson = (array) -> cols = array.shift() rowToObject = (row) -> obj = {} for [k, v] in _.zip(cols, row) obj[k] = v if v? && (v.match /\S/) && v != 'NULL' obj (rowToObject row for row in array) # from http://www.benknowscode.com/2014/01/resizing-images-in-browser-using-canvas.html # <NAME> version from comment, coffeescript and further simplification for wiki resizeImage = (dataURL) -> smallEnough = (src) -> src.width <= 500 || src.height <= 300 squeezeSteps = (src) -> return src if smallEnough src canvas = document.createElement 'canvas' canvas.width = cW = src.width / 2 canvas.height = cH = src.height / 2 context = canvas.getContext '2d' context.drawImage src, 0, 0, cW, cH return squeezeSteps canvas img = new Image img.src = dataURL return dataURL if smallEnough img squeezeSteps(img).toDataURL 'image/jpeg', .5 # medium quality encoding module.exports = {emit, bind}
true
# A Factory plugin provides a drop zone for desktop content # destined to be one or another kind of item. Double click # will turn it into a normal paragraph. neighborhood = require './neighborhood' plugin = require './plugin' resolve = require './resolve' pageHandler = require './pageHandler' editor = require './editor' synopsis = require './synopsis' drop = require './drop' active = require './active' escape = (line) -> line .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/\n/g, '<br>') emit = ($item, item) -> $item.append '<p>Double-Click to Edit<br>Drop Text or Image to Insert</p>' showMenu = -> menu = $item.find('p').append """ <br>Or Choose a Plugin <center> <table style="text-align:left;"> <tr><td><ul id=format><td><ul id=data><td><ul id=other> """ for info in window.catalog column = info.category || 'other' column = 'other' unless column in ['format', 'data'] menu.find('#'+column).append """ <li><a class="menu" href="#" title="#{info.title}">#{info.name}</a></li> """ menu.find('a.menu').click (evt)-> $item.removeClass('factory').addClass(item.type=evt.target.text.toLowerCase()) $item.unbind() evt.preventDefault() active.set $item.parents(".page") editor.textEditor $item, item showPrompt = -> $item.append "<p>#{resolve.resolveLinks(item.prompt, escape)}</b>" if item.prompt showPrompt() else if window.catalog? showMenu() else wiki.origin.get 'system/factories.json', (error, data) -> console.log 'factory', data window.catalog = data showMenu() bind = ($item, item) -> syncEditAction = -> $item.empty().unbind() $item.removeClass("factory").addClass(item.type) $page = $item.parents('.page:first') try $item.data 'pageElement', $page $item.data 'item', item plugin.getPlugin item.type, (plugin) -> plugin.emit $item, item plugin.bind $item, item catch err $item.append "<p class='error'>#{err}</p>" pageHandler.put $page, {type: 'edit', id: item.id, item: item} punt = (data) -> item.prompt = "Unexpected Item\nWe can't make sense of the drop.\nTry something else or see [[About Factory Plugin]]." data.userAgent = navigator.userAgent item.punt = data syncEditAction() addReference = (data) -> wiki.site(data.site).get "#{data.slug}.json", (err, remote) -> if !err item.type = 'reference' item.site = data.site item.slug = data.slug item.title = remote.title || data.slug item.text = synopsis remote syncEditAction() neighborhood.registerNeighbor item.site if item.site? addVideo = (video) -> item.type = 'video' item.text = "#{video.text}\n(double-click to edit caption)\n" syncEditAction() readFile = (file) -> if file? [majorType, minorType] = file.type.split("/") reader = new FileReader() if majorType == "image" reader.onload = (loadEvent) -> item.type = 'image' item.url = resizeImage loadEvent.target.result item.caption ||= "Uploaded image" syncEditAction() reader.readAsDataURL(file) else if majorType == "text" reader.onload = (loadEvent) -> result = loadEvent.target.result if minorType == 'csv' item.type = 'data' item.columns = (array = csvToArray result)[0] item.data = arrayToJson array item.text = file.fileName else item.type = 'paragraph' item.text = result syncEditAction() reader.readAsText(file) else punt name: file.name type: file.type size: file.size fileName: file.fileName lastModified: file.lastModified $item.dblclick (e) -> if e.shiftKey editor.textEditor $item, item, {field: 'prompt'} else $item.removeClass('factory').addClass(item.type = 'paragraph') $item.unbind() editor.textEditor $item, item $item.bind 'dragenter', (evt) -> evt.preventDefault() $item.bind 'dragover', (evt) -> evt.preventDefault() $item.bind "drop", drop.dispatch page: addReference file: readFile video: addVideo punt: punt # from http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm # via http://stackoverflow.com/questions/1293147/javascript-code-to-parse-csv-data csvToArray = (strData, strDelimiter) -> strDelimiter = (strDelimiter or ",") objPattern = new RegExp(("(\\" + strDelimiter + "|\\r?\\n|\\r|^)" + "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" + "([^\"\\" + strDelimiter + "\\r\\n]*))"), "gi") arrData = [ [] ] arrMatches = null while arrMatches = objPattern.exec(strData) strMatchedDelimiter = arrMatches[1] arrData.push [] if strMatchedDelimiter.length and (strMatchedDelimiter isnt strDelimiter) if arrMatches[2] strMatchedValue = arrMatches[2].replace(new RegExp("\"\"", "g"), "\"") else strMatchedValue = arrMatches[3] arrData[arrData.length - 1].push strMatchedValue arrData arrayToJson = (array) -> cols = array.shift() rowToObject = (row) -> obj = {} for [k, v] in _.zip(cols, row) obj[k] = v if v? && (v.match /\S/) && v != 'NULL' obj (rowToObject row for row in array) # from http://www.benknowscode.com/2014/01/resizing-images-in-browser-using-canvas.html # PI:NAME:<NAME>END_PI version from comment, coffeescript and further simplification for wiki resizeImage = (dataURL) -> smallEnough = (src) -> src.width <= 500 || src.height <= 300 squeezeSteps = (src) -> return src if smallEnough src canvas = document.createElement 'canvas' canvas.width = cW = src.width / 2 canvas.height = cH = src.height / 2 context = canvas.getContext '2d' context.drawImage src, 0, 0, cW, cH return squeezeSteps canvas img = new Image img.src = dataURL return dataURL if smallEnough img squeezeSteps(img).toDataURL 'image/jpeg', .5 # medium quality encoding module.exports = {emit, bind}
[ { "context": "\n###\nCopyright (C) 2012, Bill Burdick, Tiny Concepts: https://github.com/zot/Leisure\n\n(", "end": 37, "score": 0.9998344779014587, "start": 25, "tag": "NAME", "value": "Bill Burdick" }, { "context": ", Bill Burdick, Tiny Concepts: https://github.com/zot/Leisure\n\n(licensed with ZLIB license)\n\nThis softw", "end": 76, "score": 0.9994666576385498, "start": 73, "tag": "USERNAME", "value": "zot" } ]
METEOR-OLD/client/16-ast.coffee
zot/Leisure
58
### Copyright (C) 2012, Bill Burdick, Tiny Concepts: https://github.com/zot/Leisure (licensed with ZLIB license) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ### { resolve, lazy, nsLog, } = root = (module ? {}).exports = require '15-base' _ = require('lodash.min') rz = resolve lz = lazy lc = Leisure_call ###### ###### naming ###### charCodes = "'": '$a' ',': '$b' '$': '$$' '@': '$d' '?': '$e' '/': '$f' '*': '$g' '&': '$h' '^': '$i' '!': '$k' '`': '$l' '~': '$m' '-': '$_' '+': '$o' '=': '$p' '|': '$q' '[': '$r' ']': '$s' '{': '$t' '}': '$u' '"': '$v' ':': '$w' ';': '$x' '<': '$y' '>': '$z' '%': '$A' '.': '$B' '#': '$C' # ' ' is used for syntactically impossible characters, like gensyms ' ': '$S' nameSub = (name)-> s = '' for i in [0...name.length] code = charCodes[name[i]] s += code ? name[i] s ###### ###### definitions ###### setDataType = (func, dataType)-> if dataType then func.dataType = dataType func setType = (func, type)-> if type then func.type = type func.__proto__ = (ensureLeisureClass type).prototype func class LeisureObject LeisureObject.prototype.__proto__ = Function.prototype LeisureObject.prototype.className = 'LeisureObject' if !global? && (typeof window != 'undefined') then window.global = window global.Leisure_Object = LeisureObject supertypes = {} root.leisureClassChange = 0 ensureLeisureClass = (leisureClass)-> cl = "Leisure_#{nameSub leisureClass}" if !global[cl]? global[cl] = eval "(function #{cl}(){})" supertypes[cl] = 'Leisure_Object' global[cl].prototype.__proto__ = LeisureObject.prototype root.leisureClassChange++ global[cl] makeSuper = (type, supertype)-> supertypes["Leisure_#{nameSub type}"] = "Leisure_#{nameSub supertype}" root.leisureClassChange++ ensureLeisureClass 'cons' ensureLeisureClass 'nil' supertypes.Leisure_cons = 'Leisure_Object' supertypes.Leisure_nil = 'Leisure_Object' isNil = (obj)-> obj instanceof Leisure_nil ensureLeisureClass 'ast' ensureLeisureClass 'lit' Leisure_lit.prototype.toString = -> "lit(#{getLitVal @})" ensureLeisureClass 'ref' Leisure_ref.prototype.toString = -> "ref(#{getRefName @})" ensureLeisureClass 'lambda' Leisure_lambda.prototype.toString = -> "lambda(#{astString @})" ensureLeisureClass 'apply' Leisure_apply.prototype.toString = -> "apply(#{astString @})" ensureLeisureClass 'let' Leisure_let.prototype.toString = -> "let(#{astString @})" ensureLeisureClass 'anno' Leisure_anno.prototype.toString = -> "anno(#{astString @})" ensureLeisureClass 'doc' ensureLeisureClass 'srcLocation' ensureLeisureClass 'pattern' makeSuper 'lit', 'ast' makeSuper 'ref', 'ast' makeSuper 'lambda', 'ast' makeSuper 'apply', 'ast' makeSuper 'let', 'ast' makeSuper 'anno', 'ast' astString = (ast)-> switch getType ast when 'lit' then getLitVal ast when 'ref' then getRefName ast when 'apply' funcStr = astString getApplyFunc ast if getType(getApplyFunc ast) in ['lambda', 'let'] then funcStr = "(#{funcStr})" argStr = astString getApplyArg ast if getType(getApplyArg ast) == 'apply' then argStr = "(#{argStr})" "#{funcStr} #{argStr}" when 'lambda' then "\\#{getLambdaVar ast} . #{astString getLambdaBody ast}" when 'let' then "\\\\#{letStr ast}" when 'anno' then "\\@#{getAnnoName ast} #{getAnnoData ast} . #{astString getAnnoBody ast}" letStr = (ast)-> body = getLetBody ast binding = "(#{getLetName ast} = #{astString getLetValue ast})" if body instanceof Leisure_let then "#{binding} #{letStr body}" else "#{binding} . #{astString body}" ######### ######### LISTS ######### class Leisure_BaseCons extends LeisureObject head: -> throw new Error("Not Implemented") tail: -> throw new Error("Not Implemented") isNil: -> false find: (func)-> if func(@head()) then @head() else @tail().find(func) removeAll: (func)-> t = @tail().removeAll(func) if func(@head()) then t else if t == @tail() then @ else cons(@head(), t) map: (func)-> cons func(@head()), @tail().map func foldl: (func, arg)-> @tail().foldl func, func(arg, @head()) foldl1: (func)-> @tail().foldl func, @head() foldr: (func, arg)-> func @head(), @tail().foldr(func, arg) foldr1: (func)-> if @tail() == Nil then @head() else func @head(), @tail().foldr1(func) toArray: -> @foldl ((i, el)-> i.push(el); i), [] join: (str)->@toArray().join(str) intersperse: (item)-> cons @head(), @tail().foldr ((el, res)-> cons item, cons el, res), Nil reverse: -> @rev Nil rev: (result)-> @tail().rev cons(@head(), result) elementString: -> "#{if @head()?.constructor == @.constructor || @head() instanceof Leisure_nil then '[' + @head().elementString() + ']' else @head()}#{if @tail() instanceof Leisure_nil then '' else if @tail() instanceof Leisure_BaseCons then " #{@tail().elementString()}" else " | #{@tail()}"}" equals: (other)-> @ == other or (other instanceof Leisure_BaseCons and consEq(@head(), other.head()) and consEq(@tail(), other.tail())) each: (block)-> block(@head()) @tail().each(block) length: -> @foldl ((i, el)-> i + 1), 0 last: -> t = @tail() if t == Nil then @head() else t.last() append: (l)->cons @head(), @tail().append(l) toString: -> "#{@stringName()}[#{@elementString()}]" stringName: -> "BaseCons" consEq = (a, b)-> a == b or (a instanceof Leisure_BaseCons and a.equals(b)) # cons and Nil are Leisure-based so that Leisure code can work with it transparently # they look like ordinary JS classes, but the "instances" are actually functions class Leisure_cons extends Leisure_BaseCons head: -> @ ->(a)->(b)->rz a tail: -> @ ->(a)->(b)->rz b stringName: -> "Cons" global.Leisure_cons = Leisure_cons class Leisure_nil extends LeisureObject isNil: -> true find: -> @ removeAll: -> @ map: (func)-> Nil foldl: (func, arg)-> arg foldr: (func, arg)-> arg reverse: -> @ rev: (result)-> result equals: (other)-> other instanceof Leisure_nil each: -> toArray: -> [] join: -> '' append: (l)-> l toString: -> "Cons[]" elementString: -> '' global.Leisure_nil = Leisure_nil jsType = (v)-> t = typeof v if t == 'object' then v.constructor || t else t mkProto = (protoFunc, value)-> value.__proto__ = protoFunc.prototype value throwError = (msg)-> throw (if msg instanceof Error then msg else new Error(String(msg))) checkType = (value, type)-> if !(value instanceof type) then throwError("Type error: expected type: #{type}, but got: #{jsType value}") primCons = setDataType(((a)->(b)-> mkProto Leisure_cons, setType ((f)-> rz(f)(a)(b)), 'cons'), 'cons') Nil = mkProto Leisure_nil, setDataType(setType(((a)->(b)->rz b), 'nil'), 'nil') cons = (a, b)-> primCons(lz a)(lz b) foldLeft = (func, val, thing)-> if thing instanceof Leisure_cons then thing.foldl func, val else primFoldLeft func, val, thing, 0 primFoldLeft = (func, val, array, index)-> if index < array.length then primFoldLeft func, func(val, array[index]), array, index + 1 else val global.leisureFuncs = {} global.leisureFuncNames = Nil leisureAddFunc = global.leisureAddFunc = (nm)-> global.leisureFuncNames = cons(nm, global.leisureFuncNames) root.evalFunc = evalFunc = eval root.functionCount = 0 global.LeisureFunctionInfo = functionInfo = {} # name a function on the first access nameFunc = (func, name)-> f = null -> if f == null f = rz func if typeof f == 'function' then f.leisureName = name f else f global.LeisureNameSpaces = core: {} parser: {} # use AST, instead of arity? define = (name, func, arity, src, method, namespace, isNew) -> func.leisureName = name nakedDefine name, lz(func), arity, src, method, namespace, isNew nakedDefine = (name, func, arity, src, method, namespace, isNew) -> #can't use func(), because it might do something or might fail #if typeof func() == 'function' # func().src = src # func().leisureContexts = [] # func().leisureName = name # func().leisureArity = arity functionInfo[name] = src: src arity: arity leisureName: name alts: {} altList: [] if isNew then functionInfo[name].newArity = true nm = 'L_' + nameSub(name) if !method and global.noredefs and global[nm]? then throwError("[DEF] Attempt to redefine definition: #{name}") #namedFunc = functionInfo[name].mainDef = global[nm] = global.leisureFuncs[nm] = nameFunc(func, name) namedFunc = functionInfo[name].mainDef = global[nm] = global.leisureFuncs[nm] = if typeof func == 'function' && func.memo func.leisureName = name func else nameFunc(func, name) if root.currentNameSpace LeisureNameSpaces[namespace ? root.currentNameSpace][nameSub(name)] = namedFunc nsLog "DEFINING #{name} FOR #{root.currentNameSpace}" leisureAddFunc name root.functionCount++ func ###### ###### ASTs ###### # Make an AST for these # add node numder and source start and end into leisure structure # make lit, ref, lambda, apply, let, and anno subclasses of AST # # LET syntax: \\ (f a1 a2 = body1) (var = value) . expr # # let binds a name to a value in a body and uses two backslashes in a row # the body can be another let node and values can refer to any names in the let bindings # # ANNOTATION syntax: \@ name1 value1 name2 value2 . body # # Annotations associate key-values pairs with code # name, data, body -- associates a name and data with a body of code # You can nest them, so body could be another annotation # lit, ref, lambda, let each need a range L_lit = setDataType ((_x)-> (_r)-> setType ((_f)-> rz(_f)(_x)(_r)), 'lit'), 'lit' L_ref = setDataType ((_x)-> (_r)-> setType ((_f)-> rz(_f)(_x)(_r)), 'ref'), 'ref' L_lambda = setDataType ((_v)-> (_f)-> (_r)-> setType ((_g)-> rz(_g)(_v)(_f)(_r)), 'lambda'), 'lambda' L_let = setDataType ((_n)-> (_v)-> (_b)-> (_r)-> setType ((_f)-> rz(_f)(_n)(_v)(_b)(_r)), 'let'), 'let' L_apply = setDataType ((_func)-> (_arg)-> setType ((_f)-> rz(_f)(_func)(_arg)), 'apply'), 'apply' L_anno = setDataType ((_name)->(_data)->(_body)-> setType ((_f)-> rz(_f)(_name)(_data)(_body)), 'anno'), 'anno' getType = (f)-> t = typeof f if t == 'null' then "*null" else if t == 'undefined' then "*undefined" else if f.leisureType then f.leisureType else (t == 'function' and f?.type) or "*#{((t == 'object') && f.constructor?.name) || t}" define 'getType', ((value)-> getType rz value), 1 getDataType = (f)-> (typeof f == 'function' && f.dataType) || f?.leisureDataType || '' define 'getDataType', ((value)-> getDataType rz value), 1 save = {} # lit, ref, lambda, let each need a range save.lit = lit = (l, range)-> L_lit(lz l)(lz range) save.ref = ref = (r, range)-> L_ref(lz r)(lz range) save.lambda = lambda = (v, body, range)->L_lambda(lz v)(lz body)(lz range) save.llet = llet = (n, v, b, range)->L_let(lz n)(lz v)(lz b)(lz range) save.apply = apply = (f, a)->L_apply(lz f)(lz a) save.anno = anno = (name, data, body)-> L_anno(lz name)(lz data)(lz body) save.cons = cons dummyPosition = cons 1, cons 0, Nil getPos = (ast)-> switch getType(ast) when 'lit' then getLitRange ast when 'ref' then getRefRange ast when 'lambda' then getLambdaRange ast when 'apply' then getApplyRange ast when 'let' then getLetRange ast when 'anno' then getAnnoRange ast firstRange = (a, b)-> if !a || !b then console.log "NIL = #{Nil}" [lineA, colA] = a.toArray() [lineB, colB] = b.toArray() if lineA? && lineB? if lineA < lineB || (lineA == lineB && colA < colB) then a else b else if lineA then a else b getLitVal = (lt)-> lt lz (v)-> (r)-> rz v getLitRange = (lt)-> lt lz (v)-> (r)-> rz r getRefName = (rf)-> rf lz (v)-> (r)-> rz v getRefRange = (rf)-> rf lz (v)-> (r)-> rz r getLambdaVar = (lam)-> lam lz (v)->(b)-> (r)-> rz v getLambdaBody = (lam)-> lam lz (v)->(b)-> (r)-> rz b getLambdaRange = (lam)-> lam lz (v)->(b)-> (r)-> rz r getLetName = (lt)-> lt lz (n)->(v)->(b)-> (r)-> rz n getLetValue = (lt)-> lt lz (n)->(v)->(b)-> (r)-> rz v getLetBody = (lt)-> lt lz (n)->(v)->(b)-> (r)-> rz b getLetRange = (lt)-> lt lz (n)->(v)->(b)-> (r)-> rz r getApplyFunc = (apl)-> apl lz (a)->(b)-> rz a getApplyArg = (apl)-> apl lz (a)->(b)-> rz b getApplyRange = (apl) -> firstRange (getPos getApplyFunc apl), (getPos getApplyArg apl) getAnnoName = (anno)-> anno lz (name)->(data)->(body)-> rz name getAnnoData = (anno)-> anno lz (name)->(data)->(body)-> rz data getAnnoBody = (anno)-> anno lz (name)->(data)->(body)-> rz body getAnnoRange = (anno)-> getPos getAnnoBody anno ###### ###### JSON-to-AST ###### #jsonToRange = (json)-> lz json2Ast json #rangeToJson = (range)-> ast2Json range jsonToRange = (json)-> lz consFrom(json) rangeToJson = (range)-> range.toArray() json2AstEncodings = lit: (json)-> L_lit(lz json.value)(jsonToRange json.range) ref: (json)-> L_ref(lz json.varName)(jsonToRange json.range) lambda: (json)-> L_lambda(lz json.varName)(lz json2Ast json.body)(jsonToRange json.range) let: (json)-> L_let(lz json.varName)(lz json2Ast(json.value))(lz json2Ast(json.body))(jsonToRange json.range) apply: (json)-> L_apply(lz json2Ast(json.func))(lz json2Ast json.arg) anno: (json)-> L_anno(lz json.name)(lz json2Ast json.data)(lz json2Ast json.body) cons: (json)-> save.cons json2Ast(json.head), json2Ast(json.tail) nil: (json)-> Nil # need these because my CS mod names the above functions with the field names :-/ lit = save.lit ref = save.ref lambda = save.lambda apply = save.apply llet = save.llet anno = save.anno cons = save.cons json2Ast = (json)-> if typeof json == 'object' then json2AstEncodings[json._type] json else json ast2JsonEncodings = Leisure_lit: (ast)-> _type: 'lit' value: getLitVal ast range: rangeToJson getLitRange ast Leisure_ref: (ast)-> _type: 'ref' varName: getRefName ast range: rangeToJson getRefRange ast Leisure_lambda: (ast)-> _type: 'lambda' varName: getLambdaVar ast body: ast2Json getLambdaBody ast range: rangeToJson getLambdaRange ast Leisure_let: (ast)-> _type: 'let' varName: getLetName ast value: ast2Json getLetValue ast body: ast2Json getLetBody ast range: rangeToJson getLetRange ast Leisure_apply: (ast)-> _type: 'apply' func: ast2Json getApplyFunc ast arg: ast2Json getApplyArg ast Leisure_anno: (ast)-> _type: 'anno' name: getAnnoName ast data: ast2Json getAnnoData ast body: ast2Json getAnnoBody ast Leisure_cons: (ast)-> _type: 'cons' head: ast2Json ast.head() tail: ast2Json ast.tail() Leisure_nil: (ast)-> _type: 'nil' ast2Json = (ast)-> if ast2JsonEncodings[ast.constructor?.name] then ast2JsonEncodings[ast.constructor.name] ast else ast # Leisure interface to the JSON AST codec define 'json2Ast', ((json)-> json2Ast JSON.parse rz json), null, null, null, 'parser' define 'ast2Json', ((ast)-> JSON.stringify ast2Json rz ast), null, null, null, 'parser' consFrom = (array, i)-> i = i || 0 if i < array.length then cons array[i], consFrom(array, i + 1) else Nil head = (l)-> l.head() tail = (l)-> l.tail() root.head = head root.tail = tail root.consFrom = consFrom root.nameSub = nameSub root.setDataType = setDataType root.setType = setType root.mkProto = mkProto root.Nil = Nil root.cons = cons root.primCons = primCons root.define = define root.nakedDefine = nakedDefine root.getType = getType root.getDataType = getDataType root.lit = lit root.ref = ref root.lambda = lambda root.apply = apply root.anno = anno root.llet = llet root.getRefName = getRefName root.getRefRange = getRefRange root.getLitVal = getLitVal root.getLambdaBody = getLambdaBody root.getLambdaVar = getLambdaVar root.getApplyFunc = getApplyFunc root.getApplyArg = getApplyArg root.getLetName = getLetName root.getLetValue = getLetValue root.getLetBody = getLetBody root.getAnnoName = getAnnoName root.getAnnoData = getAnnoData root.getAnnoBody = getAnnoBody root.throwError = throwError root.foldLeft = foldLeft root.LeisureObject = LeisureObject root.evalFunc = evalFunc root.json2Ast = json2Ast root.ast2Json = ast2Json root.Leisure_lit = Leisure_lit root.Leisure_ref = Leisure_ref root.Leisure_lambda = Leisure_lambda root.Leisure_apply = Leisure_apply root.Leisure_let = Leisure_let root.Leisure_anno = Leisure_anno root.ensureLeisureClass = ensureLeisureClass root.makeSuper = makeSuper root.supertypes = supertypes root.functionInfo = functionInfo root.getPos = getPos root.dummyPosition = dummyPosition root.isNil = isNil
209297
### Copyright (C) 2012, <NAME>, Tiny Concepts: https://github.com/zot/Leisure (licensed with ZLIB license) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ### { resolve, lazy, nsLog, } = root = (module ? {}).exports = require '15-base' _ = require('lodash.min') rz = resolve lz = lazy lc = Leisure_call ###### ###### naming ###### charCodes = "'": '$a' ',': '$b' '$': '$$' '@': '$d' '?': '$e' '/': '$f' '*': '$g' '&': '$h' '^': '$i' '!': '$k' '`': '$l' '~': '$m' '-': '$_' '+': '$o' '=': '$p' '|': '$q' '[': '$r' ']': '$s' '{': '$t' '}': '$u' '"': '$v' ':': '$w' ';': '$x' '<': '$y' '>': '$z' '%': '$A' '.': '$B' '#': '$C' # ' ' is used for syntactically impossible characters, like gensyms ' ': '$S' nameSub = (name)-> s = '' for i in [0...name.length] code = charCodes[name[i]] s += code ? name[i] s ###### ###### definitions ###### setDataType = (func, dataType)-> if dataType then func.dataType = dataType func setType = (func, type)-> if type then func.type = type func.__proto__ = (ensureLeisureClass type).prototype func class LeisureObject LeisureObject.prototype.__proto__ = Function.prototype LeisureObject.prototype.className = 'LeisureObject' if !global? && (typeof window != 'undefined') then window.global = window global.Leisure_Object = LeisureObject supertypes = {} root.leisureClassChange = 0 ensureLeisureClass = (leisureClass)-> cl = "Leisure_#{nameSub leisureClass}" if !global[cl]? global[cl] = eval "(function #{cl}(){})" supertypes[cl] = 'Leisure_Object' global[cl].prototype.__proto__ = LeisureObject.prototype root.leisureClassChange++ global[cl] makeSuper = (type, supertype)-> supertypes["Leisure_#{nameSub type}"] = "Leisure_#{nameSub supertype}" root.leisureClassChange++ ensureLeisureClass 'cons' ensureLeisureClass 'nil' supertypes.Leisure_cons = 'Leisure_Object' supertypes.Leisure_nil = 'Leisure_Object' isNil = (obj)-> obj instanceof Leisure_nil ensureLeisureClass 'ast' ensureLeisureClass 'lit' Leisure_lit.prototype.toString = -> "lit(#{getLitVal @})" ensureLeisureClass 'ref' Leisure_ref.prototype.toString = -> "ref(#{getRefName @})" ensureLeisureClass 'lambda' Leisure_lambda.prototype.toString = -> "lambda(#{astString @})" ensureLeisureClass 'apply' Leisure_apply.prototype.toString = -> "apply(#{astString @})" ensureLeisureClass 'let' Leisure_let.prototype.toString = -> "let(#{astString @})" ensureLeisureClass 'anno' Leisure_anno.prototype.toString = -> "anno(#{astString @})" ensureLeisureClass 'doc' ensureLeisureClass 'srcLocation' ensureLeisureClass 'pattern' makeSuper 'lit', 'ast' makeSuper 'ref', 'ast' makeSuper 'lambda', 'ast' makeSuper 'apply', 'ast' makeSuper 'let', 'ast' makeSuper 'anno', 'ast' astString = (ast)-> switch getType ast when 'lit' then getLitVal ast when 'ref' then getRefName ast when 'apply' funcStr = astString getApplyFunc ast if getType(getApplyFunc ast) in ['lambda', 'let'] then funcStr = "(#{funcStr})" argStr = astString getApplyArg ast if getType(getApplyArg ast) == 'apply' then argStr = "(#{argStr})" "#{funcStr} #{argStr}" when 'lambda' then "\\#{getLambdaVar ast} . #{astString getLambdaBody ast}" when 'let' then "\\\\#{letStr ast}" when 'anno' then "\\@#{getAnnoName ast} #{getAnnoData ast} . #{astString getAnnoBody ast}" letStr = (ast)-> body = getLetBody ast binding = "(#{getLetName ast} = #{astString getLetValue ast})" if body instanceof Leisure_let then "#{binding} #{letStr body}" else "#{binding} . #{astString body}" ######### ######### LISTS ######### class Leisure_BaseCons extends LeisureObject head: -> throw new Error("Not Implemented") tail: -> throw new Error("Not Implemented") isNil: -> false find: (func)-> if func(@head()) then @head() else @tail().find(func) removeAll: (func)-> t = @tail().removeAll(func) if func(@head()) then t else if t == @tail() then @ else cons(@head(), t) map: (func)-> cons func(@head()), @tail().map func foldl: (func, arg)-> @tail().foldl func, func(arg, @head()) foldl1: (func)-> @tail().foldl func, @head() foldr: (func, arg)-> func @head(), @tail().foldr(func, arg) foldr1: (func)-> if @tail() == Nil then @head() else func @head(), @tail().foldr1(func) toArray: -> @foldl ((i, el)-> i.push(el); i), [] join: (str)->@toArray().join(str) intersperse: (item)-> cons @head(), @tail().foldr ((el, res)-> cons item, cons el, res), Nil reverse: -> @rev Nil rev: (result)-> @tail().rev cons(@head(), result) elementString: -> "#{if @head()?.constructor == @.constructor || @head() instanceof Leisure_nil then '[' + @head().elementString() + ']' else @head()}#{if @tail() instanceof Leisure_nil then '' else if @tail() instanceof Leisure_BaseCons then " #{@tail().elementString()}" else " | #{@tail()}"}" equals: (other)-> @ == other or (other instanceof Leisure_BaseCons and consEq(@head(), other.head()) and consEq(@tail(), other.tail())) each: (block)-> block(@head()) @tail().each(block) length: -> @foldl ((i, el)-> i + 1), 0 last: -> t = @tail() if t == Nil then @head() else t.last() append: (l)->cons @head(), @tail().append(l) toString: -> "#{@stringName()}[#{@elementString()}]" stringName: -> "BaseCons" consEq = (a, b)-> a == b or (a instanceof Leisure_BaseCons and a.equals(b)) # cons and Nil are Leisure-based so that Leisure code can work with it transparently # they look like ordinary JS classes, but the "instances" are actually functions class Leisure_cons extends Leisure_BaseCons head: -> @ ->(a)->(b)->rz a tail: -> @ ->(a)->(b)->rz b stringName: -> "Cons" global.Leisure_cons = Leisure_cons class Leisure_nil extends LeisureObject isNil: -> true find: -> @ removeAll: -> @ map: (func)-> Nil foldl: (func, arg)-> arg foldr: (func, arg)-> arg reverse: -> @ rev: (result)-> result equals: (other)-> other instanceof Leisure_nil each: -> toArray: -> [] join: -> '' append: (l)-> l toString: -> "Cons[]" elementString: -> '' global.Leisure_nil = Leisure_nil jsType = (v)-> t = typeof v if t == 'object' then v.constructor || t else t mkProto = (protoFunc, value)-> value.__proto__ = protoFunc.prototype value throwError = (msg)-> throw (if msg instanceof Error then msg else new Error(String(msg))) checkType = (value, type)-> if !(value instanceof type) then throwError("Type error: expected type: #{type}, but got: #{jsType value}") primCons = setDataType(((a)->(b)-> mkProto Leisure_cons, setType ((f)-> rz(f)(a)(b)), 'cons'), 'cons') Nil = mkProto Leisure_nil, setDataType(setType(((a)->(b)->rz b), 'nil'), 'nil') cons = (a, b)-> primCons(lz a)(lz b) foldLeft = (func, val, thing)-> if thing instanceof Leisure_cons then thing.foldl func, val else primFoldLeft func, val, thing, 0 primFoldLeft = (func, val, array, index)-> if index < array.length then primFoldLeft func, func(val, array[index]), array, index + 1 else val global.leisureFuncs = {} global.leisureFuncNames = Nil leisureAddFunc = global.leisureAddFunc = (nm)-> global.leisureFuncNames = cons(nm, global.leisureFuncNames) root.evalFunc = evalFunc = eval root.functionCount = 0 global.LeisureFunctionInfo = functionInfo = {} # name a function on the first access nameFunc = (func, name)-> f = null -> if f == null f = rz func if typeof f == 'function' then f.leisureName = name f else f global.LeisureNameSpaces = core: {} parser: {} # use AST, instead of arity? define = (name, func, arity, src, method, namespace, isNew) -> func.leisureName = name nakedDefine name, lz(func), arity, src, method, namespace, isNew nakedDefine = (name, func, arity, src, method, namespace, isNew) -> #can't use func(), because it might do something or might fail #if typeof func() == 'function' # func().src = src # func().leisureContexts = [] # func().leisureName = name # func().leisureArity = arity functionInfo[name] = src: src arity: arity leisureName: name alts: {} altList: [] if isNew then functionInfo[name].newArity = true nm = 'L_' + nameSub(name) if !method and global.noredefs and global[nm]? then throwError("[DEF] Attempt to redefine definition: #{name}") #namedFunc = functionInfo[name].mainDef = global[nm] = global.leisureFuncs[nm] = nameFunc(func, name) namedFunc = functionInfo[name].mainDef = global[nm] = global.leisureFuncs[nm] = if typeof func == 'function' && func.memo func.leisureName = name func else nameFunc(func, name) if root.currentNameSpace LeisureNameSpaces[namespace ? root.currentNameSpace][nameSub(name)] = namedFunc nsLog "DEFINING #{name} FOR #{root.currentNameSpace}" leisureAddFunc name root.functionCount++ func ###### ###### ASTs ###### # Make an AST for these # add node numder and source start and end into leisure structure # make lit, ref, lambda, apply, let, and anno subclasses of AST # # LET syntax: \\ (f a1 a2 = body1) (var = value) . expr # # let binds a name to a value in a body and uses two backslashes in a row # the body can be another let node and values can refer to any names in the let bindings # # ANNOTATION syntax: \@ name1 value1 name2 value2 . body # # Annotations associate key-values pairs with code # name, data, body -- associates a name and data with a body of code # You can nest them, so body could be another annotation # lit, ref, lambda, let each need a range L_lit = setDataType ((_x)-> (_r)-> setType ((_f)-> rz(_f)(_x)(_r)), 'lit'), 'lit' L_ref = setDataType ((_x)-> (_r)-> setType ((_f)-> rz(_f)(_x)(_r)), 'ref'), 'ref' L_lambda = setDataType ((_v)-> (_f)-> (_r)-> setType ((_g)-> rz(_g)(_v)(_f)(_r)), 'lambda'), 'lambda' L_let = setDataType ((_n)-> (_v)-> (_b)-> (_r)-> setType ((_f)-> rz(_f)(_n)(_v)(_b)(_r)), 'let'), 'let' L_apply = setDataType ((_func)-> (_arg)-> setType ((_f)-> rz(_f)(_func)(_arg)), 'apply'), 'apply' L_anno = setDataType ((_name)->(_data)->(_body)-> setType ((_f)-> rz(_f)(_name)(_data)(_body)), 'anno'), 'anno' getType = (f)-> t = typeof f if t == 'null' then "*null" else if t == 'undefined' then "*undefined" else if f.leisureType then f.leisureType else (t == 'function' and f?.type) or "*#{((t == 'object') && f.constructor?.name) || t}" define 'getType', ((value)-> getType rz value), 1 getDataType = (f)-> (typeof f == 'function' && f.dataType) || f?.leisureDataType || '' define 'getDataType', ((value)-> getDataType rz value), 1 save = {} # lit, ref, lambda, let each need a range save.lit = lit = (l, range)-> L_lit(lz l)(lz range) save.ref = ref = (r, range)-> L_ref(lz r)(lz range) save.lambda = lambda = (v, body, range)->L_lambda(lz v)(lz body)(lz range) save.llet = llet = (n, v, b, range)->L_let(lz n)(lz v)(lz b)(lz range) save.apply = apply = (f, a)->L_apply(lz f)(lz a) save.anno = anno = (name, data, body)-> L_anno(lz name)(lz data)(lz body) save.cons = cons dummyPosition = cons 1, cons 0, Nil getPos = (ast)-> switch getType(ast) when 'lit' then getLitRange ast when 'ref' then getRefRange ast when 'lambda' then getLambdaRange ast when 'apply' then getApplyRange ast when 'let' then getLetRange ast when 'anno' then getAnnoRange ast firstRange = (a, b)-> if !a || !b then console.log "NIL = #{Nil}" [lineA, colA] = a.toArray() [lineB, colB] = b.toArray() if lineA? && lineB? if lineA < lineB || (lineA == lineB && colA < colB) then a else b else if lineA then a else b getLitVal = (lt)-> lt lz (v)-> (r)-> rz v getLitRange = (lt)-> lt lz (v)-> (r)-> rz r getRefName = (rf)-> rf lz (v)-> (r)-> rz v getRefRange = (rf)-> rf lz (v)-> (r)-> rz r getLambdaVar = (lam)-> lam lz (v)->(b)-> (r)-> rz v getLambdaBody = (lam)-> lam lz (v)->(b)-> (r)-> rz b getLambdaRange = (lam)-> lam lz (v)->(b)-> (r)-> rz r getLetName = (lt)-> lt lz (n)->(v)->(b)-> (r)-> rz n getLetValue = (lt)-> lt lz (n)->(v)->(b)-> (r)-> rz v getLetBody = (lt)-> lt lz (n)->(v)->(b)-> (r)-> rz b getLetRange = (lt)-> lt lz (n)->(v)->(b)-> (r)-> rz r getApplyFunc = (apl)-> apl lz (a)->(b)-> rz a getApplyArg = (apl)-> apl lz (a)->(b)-> rz b getApplyRange = (apl) -> firstRange (getPos getApplyFunc apl), (getPos getApplyArg apl) getAnnoName = (anno)-> anno lz (name)->(data)->(body)-> rz name getAnnoData = (anno)-> anno lz (name)->(data)->(body)-> rz data getAnnoBody = (anno)-> anno lz (name)->(data)->(body)-> rz body getAnnoRange = (anno)-> getPos getAnnoBody anno ###### ###### JSON-to-AST ###### #jsonToRange = (json)-> lz json2Ast json #rangeToJson = (range)-> ast2Json range jsonToRange = (json)-> lz consFrom(json) rangeToJson = (range)-> range.toArray() json2AstEncodings = lit: (json)-> L_lit(lz json.value)(jsonToRange json.range) ref: (json)-> L_ref(lz json.varName)(jsonToRange json.range) lambda: (json)-> L_lambda(lz json.varName)(lz json2Ast json.body)(jsonToRange json.range) let: (json)-> L_let(lz json.varName)(lz json2Ast(json.value))(lz json2Ast(json.body))(jsonToRange json.range) apply: (json)-> L_apply(lz json2Ast(json.func))(lz json2Ast json.arg) anno: (json)-> L_anno(lz json.name)(lz json2Ast json.data)(lz json2Ast json.body) cons: (json)-> save.cons json2Ast(json.head), json2Ast(json.tail) nil: (json)-> Nil # need these because my CS mod names the above functions with the field names :-/ lit = save.lit ref = save.ref lambda = save.lambda apply = save.apply llet = save.llet anno = save.anno cons = save.cons json2Ast = (json)-> if typeof json == 'object' then json2AstEncodings[json._type] json else json ast2JsonEncodings = Leisure_lit: (ast)-> _type: 'lit' value: getLitVal ast range: rangeToJson getLitRange ast Leisure_ref: (ast)-> _type: 'ref' varName: getRefName ast range: rangeToJson getRefRange ast Leisure_lambda: (ast)-> _type: 'lambda' varName: getLambdaVar ast body: ast2Json getLambdaBody ast range: rangeToJson getLambdaRange ast Leisure_let: (ast)-> _type: 'let' varName: getLetName ast value: ast2Json getLetValue ast body: ast2Json getLetBody ast range: rangeToJson getLetRange ast Leisure_apply: (ast)-> _type: 'apply' func: ast2Json getApplyFunc ast arg: ast2Json getApplyArg ast Leisure_anno: (ast)-> _type: 'anno' name: getAnnoName ast data: ast2Json getAnnoData ast body: ast2Json getAnnoBody ast Leisure_cons: (ast)-> _type: 'cons' head: ast2Json ast.head() tail: ast2Json ast.tail() Leisure_nil: (ast)-> _type: 'nil' ast2Json = (ast)-> if ast2JsonEncodings[ast.constructor?.name] then ast2JsonEncodings[ast.constructor.name] ast else ast # Leisure interface to the JSON AST codec define 'json2Ast', ((json)-> json2Ast JSON.parse rz json), null, null, null, 'parser' define 'ast2Json', ((ast)-> JSON.stringify ast2Json rz ast), null, null, null, 'parser' consFrom = (array, i)-> i = i || 0 if i < array.length then cons array[i], consFrom(array, i + 1) else Nil head = (l)-> l.head() tail = (l)-> l.tail() root.head = head root.tail = tail root.consFrom = consFrom root.nameSub = nameSub root.setDataType = setDataType root.setType = setType root.mkProto = mkProto root.Nil = Nil root.cons = cons root.primCons = primCons root.define = define root.nakedDefine = nakedDefine root.getType = getType root.getDataType = getDataType root.lit = lit root.ref = ref root.lambda = lambda root.apply = apply root.anno = anno root.llet = llet root.getRefName = getRefName root.getRefRange = getRefRange root.getLitVal = getLitVal root.getLambdaBody = getLambdaBody root.getLambdaVar = getLambdaVar root.getApplyFunc = getApplyFunc root.getApplyArg = getApplyArg root.getLetName = getLetName root.getLetValue = getLetValue root.getLetBody = getLetBody root.getAnnoName = getAnnoName root.getAnnoData = getAnnoData root.getAnnoBody = getAnnoBody root.throwError = throwError root.foldLeft = foldLeft root.LeisureObject = LeisureObject root.evalFunc = evalFunc root.json2Ast = json2Ast root.ast2Json = ast2Json root.Leisure_lit = Leisure_lit root.Leisure_ref = Leisure_ref root.Leisure_lambda = Leisure_lambda root.Leisure_apply = Leisure_apply root.Leisure_let = Leisure_let root.Leisure_anno = Leisure_anno root.ensureLeisureClass = ensureLeisureClass root.makeSuper = makeSuper root.supertypes = supertypes root.functionInfo = functionInfo root.getPos = getPos root.dummyPosition = dummyPosition root.isNil = isNil
true
### Copyright (C) 2012, PI:NAME:<NAME>END_PI, Tiny Concepts: https://github.com/zot/Leisure (licensed with ZLIB license) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ### { resolve, lazy, nsLog, } = root = (module ? {}).exports = require '15-base' _ = require('lodash.min') rz = resolve lz = lazy lc = Leisure_call ###### ###### naming ###### charCodes = "'": '$a' ',': '$b' '$': '$$' '@': '$d' '?': '$e' '/': '$f' '*': '$g' '&': '$h' '^': '$i' '!': '$k' '`': '$l' '~': '$m' '-': '$_' '+': '$o' '=': '$p' '|': '$q' '[': '$r' ']': '$s' '{': '$t' '}': '$u' '"': '$v' ':': '$w' ';': '$x' '<': '$y' '>': '$z' '%': '$A' '.': '$B' '#': '$C' # ' ' is used for syntactically impossible characters, like gensyms ' ': '$S' nameSub = (name)-> s = '' for i in [0...name.length] code = charCodes[name[i]] s += code ? name[i] s ###### ###### definitions ###### setDataType = (func, dataType)-> if dataType then func.dataType = dataType func setType = (func, type)-> if type then func.type = type func.__proto__ = (ensureLeisureClass type).prototype func class LeisureObject LeisureObject.prototype.__proto__ = Function.prototype LeisureObject.prototype.className = 'LeisureObject' if !global? && (typeof window != 'undefined') then window.global = window global.Leisure_Object = LeisureObject supertypes = {} root.leisureClassChange = 0 ensureLeisureClass = (leisureClass)-> cl = "Leisure_#{nameSub leisureClass}" if !global[cl]? global[cl] = eval "(function #{cl}(){})" supertypes[cl] = 'Leisure_Object' global[cl].prototype.__proto__ = LeisureObject.prototype root.leisureClassChange++ global[cl] makeSuper = (type, supertype)-> supertypes["Leisure_#{nameSub type}"] = "Leisure_#{nameSub supertype}" root.leisureClassChange++ ensureLeisureClass 'cons' ensureLeisureClass 'nil' supertypes.Leisure_cons = 'Leisure_Object' supertypes.Leisure_nil = 'Leisure_Object' isNil = (obj)-> obj instanceof Leisure_nil ensureLeisureClass 'ast' ensureLeisureClass 'lit' Leisure_lit.prototype.toString = -> "lit(#{getLitVal @})" ensureLeisureClass 'ref' Leisure_ref.prototype.toString = -> "ref(#{getRefName @})" ensureLeisureClass 'lambda' Leisure_lambda.prototype.toString = -> "lambda(#{astString @})" ensureLeisureClass 'apply' Leisure_apply.prototype.toString = -> "apply(#{astString @})" ensureLeisureClass 'let' Leisure_let.prototype.toString = -> "let(#{astString @})" ensureLeisureClass 'anno' Leisure_anno.prototype.toString = -> "anno(#{astString @})" ensureLeisureClass 'doc' ensureLeisureClass 'srcLocation' ensureLeisureClass 'pattern' makeSuper 'lit', 'ast' makeSuper 'ref', 'ast' makeSuper 'lambda', 'ast' makeSuper 'apply', 'ast' makeSuper 'let', 'ast' makeSuper 'anno', 'ast' astString = (ast)-> switch getType ast when 'lit' then getLitVal ast when 'ref' then getRefName ast when 'apply' funcStr = astString getApplyFunc ast if getType(getApplyFunc ast) in ['lambda', 'let'] then funcStr = "(#{funcStr})" argStr = astString getApplyArg ast if getType(getApplyArg ast) == 'apply' then argStr = "(#{argStr})" "#{funcStr} #{argStr}" when 'lambda' then "\\#{getLambdaVar ast} . #{astString getLambdaBody ast}" when 'let' then "\\\\#{letStr ast}" when 'anno' then "\\@#{getAnnoName ast} #{getAnnoData ast} . #{astString getAnnoBody ast}" letStr = (ast)-> body = getLetBody ast binding = "(#{getLetName ast} = #{astString getLetValue ast})" if body instanceof Leisure_let then "#{binding} #{letStr body}" else "#{binding} . #{astString body}" ######### ######### LISTS ######### class Leisure_BaseCons extends LeisureObject head: -> throw new Error("Not Implemented") tail: -> throw new Error("Not Implemented") isNil: -> false find: (func)-> if func(@head()) then @head() else @tail().find(func) removeAll: (func)-> t = @tail().removeAll(func) if func(@head()) then t else if t == @tail() then @ else cons(@head(), t) map: (func)-> cons func(@head()), @tail().map func foldl: (func, arg)-> @tail().foldl func, func(arg, @head()) foldl1: (func)-> @tail().foldl func, @head() foldr: (func, arg)-> func @head(), @tail().foldr(func, arg) foldr1: (func)-> if @tail() == Nil then @head() else func @head(), @tail().foldr1(func) toArray: -> @foldl ((i, el)-> i.push(el); i), [] join: (str)->@toArray().join(str) intersperse: (item)-> cons @head(), @tail().foldr ((el, res)-> cons item, cons el, res), Nil reverse: -> @rev Nil rev: (result)-> @tail().rev cons(@head(), result) elementString: -> "#{if @head()?.constructor == @.constructor || @head() instanceof Leisure_nil then '[' + @head().elementString() + ']' else @head()}#{if @tail() instanceof Leisure_nil then '' else if @tail() instanceof Leisure_BaseCons then " #{@tail().elementString()}" else " | #{@tail()}"}" equals: (other)-> @ == other or (other instanceof Leisure_BaseCons and consEq(@head(), other.head()) and consEq(@tail(), other.tail())) each: (block)-> block(@head()) @tail().each(block) length: -> @foldl ((i, el)-> i + 1), 0 last: -> t = @tail() if t == Nil then @head() else t.last() append: (l)->cons @head(), @tail().append(l) toString: -> "#{@stringName()}[#{@elementString()}]" stringName: -> "BaseCons" consEq = (a, b)-> a == b or (a instanceof Leisure_BaseCons and a.equals(b)) # cons and Nil are Leisure-based so that Leisure code can work with it transparently # they look like ordinary JS classes, but the "instances" are actually functions class Leisure_cons extends Leisure_BaseCons head: -> @ ->(a)->(b)->rz a tail: -> @ ->(a)->(b)->rz b stringName: -> "Cons" global.Leisure_cons = Leisure_cons class Leisure_nil extends LeisureObject isNil: -> true find: -> @ removeAll: -> @ map: (func)-> Nil foldl: (func, arg)-> arg foldr: (func, arg)-> arg reverse: -> @ rev: (result)-> result equals: (other)-> other instanceof Leisure_nil each: -> toArray: -> [] join: -> '' append: (l)-> l toString: -> "Cons[]" elementString: -> '' global.Leisure_nil = Leisure_nil jsType = (v)-> t = typeof v if t == 'object' then v.constructor || t else t mkProto = (protoFunc, value)-> value.__proto__ = protoFunc.prototype value throwError = (msg)-> throw (if msg instanceof Error then msg else new Error(String(msg))) checkType = (value, type)-> if !(value instanceof type) then throwError("Type error: expected type: #{type}, but got: #{jsType value}") primCons = setDataType(((a)->(b)-> mkProto Leisure_cons, setType ((f)-> rz(f)(a)(b)), 'cons'), 'cons') Nil = mkProto Leisure_nil, setDataType(setType(((a)->(b)->rz b), 'nil'), 'nil') cons = (a, b)-> primCons(lz a)(lz b) foldLeft = (func, val, thing)-> if thing instanceof Leisure_cons then thing.foldl func, val else primFoldLeft func, val, thing, 0 primFoldLeft = (func, val, array, index)-> if index < array.length then primFoldLeft func, func(val, array[index]), array, index + 1 else val global.leisureFuncs = {} global.leisureFuncNames = Nil leisureAddFunc = global.leisureAddFunc = (nm)-> global.leisureFuncNames = cons(nm, global.leisureFuncNames) root.evalFunc = evalFunc = eval root.functionCount = 0 global.LeisureFunctionInfo = functionInfo = {} # name a function on the first access nameFunc = (func, name)-> f = null -> if f == null f = rz func if typeof f == 'function' then f.leisureName = name f else f global.LeisureNameSpaces = core: {} parser: {} # use AST, instead of arity? define = (name, func, arity, src, method, namespace, isNew) -> func.leisureName = name nakedDefine name, lz(func), arity, src, method, namespace, isNew nakedDefine = (name, func, arity, src, method, namespace, isNew) -> #can't use func(), because it might do something or might fail #if typeof func() == 'function' # func().src = src # func().leisureContexts = [] # func().leisureName = name # func().leisureArity = arity functionInfo[name] = src: src arity: arity leisureName: name alts: {} altList: [] if isNew then functionInfo[name].newArity = true nm = 'L_' + nameSub(name) if !method and global.noredefs and global[nm]? then throwError("[DEF] Attempt to redefine definition: #{name}") #namedFunc = functionInfo[name].mainDef = global[nm] = global.leisureFuncs[nm] = nameFunc(func, name) namedFunc = functionInfo[name].mainDef = global[nm] = global.leisureFuncs[nm] = if typeof func == 'function' && func.memo func.leisureName = name func else nameFunc(func, name) if root.currentNameSpace LeisureNameSpaces[namespace ? root.currentNameSpace][nameSub(name)] = namedFunc nsLog "DEFINING #{name} FOR #{root.currentNameSpace}" leisureAddFunc name root.functionCount++ func ###### ###### ASTs ###### # Make an AST for these # add node numder and source start and end into leisure structure # make lit, ref, lambda, apply, let, and anno subclasses of AST # # LET syntax: \\ (f a1 a2 = body1) (var = value) . expr # # let binds a name to a value in a body and uses two backslashes in a row # the body can be another let node and values can refer to any names in the let bindings # # ANNOTATION syntax: \@ name1 value1 name2 value2 . body # # Annotations associate key-values pairs with code # name, data, body -- associates a name and data with a body of code # You can nest them, so body could be another annotation # lit, ref, lambda, let each need a range L_lit = setDataType ((_x)-> (_r)-> setType ((_f)-> rz(_f)(_x)(_r)), 'lit'), 'lit' L_ref = setDataType ((_x)-> (_r)-> setType ((_f)-> rz(_f)(_x)(_r)), 'ref'), 'ref' L_lambda = setDataType ((_v)-> (_f)-> (_r)-> setType ((_g)-> rz(_g)(_v)(_f)(_r)), 'lambda'), 'lambda' L_let = setDataType ((_n)-> (_v)-> (_b)-> (_r)-> setType ((_f)-> rz(_f)(_n)(_v)(_b)(_r)), 'let'), 'let' L_apply = setDataType ((_func)-> (_arg)-> setType ((_f)-> rz(_f)(_func)(_arg)), 'apply'), 'apply' L_anno = setDataType ((_name)->(_data)->(_body)-> setType ((_f)-> rz(_f)(_name)(_data)(_body)), 'anno'), 'anno' getType = (f)-> t = typeof f if t == 'null' then "*null" else if t == 'undefined' then "*undefined" else if f.leisureType then f.leisureType else (t == 'function' and f?.type) or "*#{((t == 'object') && f.constructor?.name) || t}" define 'getType', ((value)-> getType rz value), 1 getDataType = (f)-> (typeof f == 'function' && f.dataType) || f?.leisureDataType || '' define 'getDataType', ((value)-> getDataType rz value), 1 save = {} # lit, ref, lambda, let each need a range save.lit = lit = (l, range)-> L_lit(lz l)(lz range) save.ref = ref = (r, range)-> L_ref(lz r)(lz range) save.lambda = lambda = (v, body, range)->L_lambda(lz v)(lz body)(lz range) save.llet = llet = (n, v, b, range)->L_let(lz n)(lz v)(lz b)(lz range) save.apply = apply = (f, a)->L_apply(lz f)(lz a) save.anno = anno = (name, data, body)-> L_anno(lz name)(lz data)(lz body) save.cons = cons dummyPosition = cons 1, cons 0, Nil getPos = (ast)-> switch getType(ast) when 'lit' then getLitRange ast when 'ref' then getRefRange ast when 'lambda' then getLambdaRange ast when 'apply' then getApplyRange ast when 'let' then getLetRange ast when 'anno' then getAnnoRange ast firstRange = (a, b)-> if !a || !b then console.log "NIL = #{Nil}" [lineA, colA] = a.toArray() [lineB, colB] = b.toArray() if lineA? && lineB? if lineA < lineB || (lineA == lineB && colA < colB) then a else b else if lineA then a else b getLitVal = (lt)-> lt lz (v)-> (r)-> rz v getLitRange = (lt)-> lt lz (v)-> (r)-> rz r getRefName = (rf)-> rf lz (v)-> (r)-> rz v getRefRange = (rf)-> rf lz (v)-> (r)-> rz r getLambdaVar = (lam)-> lam lz (v)->(b)-> (r)-> rz v getLambdaBody = (lam)-> lam lz (v)->(b)-> (r)-> rz b getLambdaRange = (lam)-> lam lz (v)->(b)-> (r)-> rz r getLetName = (lt)-> lt lz (n)->(v)->(b)-> (r)-> rz n getLetValue = (lt)-> lt lz (n)->(v)->(b)-> (r)-> rz v getLetBody = (lt)-> lt lz (n)->(v)->(b)-> (r)-> rz b getLetRange = (lt)-> lt lz (n)->(v)->(b)-> (r)-> rz r getApplyFunc = (apl)-> apl lz (a)->(b)-> rz a getApplyArg = (apl)-> apl lz (a)->(b)-> rz b getApplyRange = (apl) -> firstRange (getPos getApplyFunc apl), (getPos getApplyArg apl) getAnnoName = (anno)-> anno lz (name)->(data)->(body)-> rz name getAnnoData = (anno)-> anno lz (name)->(data)->(body)-> rz data getAnnoBody = (anno)-> anno lz (name)->(data)->(body)-> rz body getAnnoRange = (anno)-> getPos getAnnoBody anno ###### ###### JSON-to-AST ###### #jsonToRange = (json)-> lz json2Ast json #rangeToJson = (range)-> ast2Json range jsonToRange = (json)-> lz consFrom(json) rangeToJson = (range)-> range.toArray() json2AstEncodings = lit: (json)-> L_lit(lz json.value)(jsonToRange json.range) ref: (json)-> L_ref(lz json.varName)(jsonToRange json.range) lambda: (json)-> L_lambda(lz json.varName)(lz json2Ast json.body)(jsonToRange json.range) let: (json)-> L_let(lz json.varName)(lz json2Ast(json.value))(lz json2Ast(json.body))(jsonToRange json.range) apply: (json)-> L_apply(lz json2Ast(json.func))(lz json2Ast json.arg) anno: (json)-> L_anno(lz json.name)(lz json2Ast json.data)(lz json2Ast json.body) cons: (json)-> save.cons json2Ast(json.head), json2Ast(json.tail) nil: (json)-> Nil # need these because my CS mod names the above functions with the field names :-/ lit = save.lit ref = save.ref lambda = save.lambda apply = save.apply llet = save.llet anno = save.anno cons = save.cons json2Ast = (json)-> if typeof json == 'object' then json2AstEncodings[json._type] json else json ast2JsonEncodings = Leisure_lit: (ast)-> _type: 'lit' value: getLitVal ast range: rangeToJson getLitRange ast Leisure_ref: (ast)-> _type: 'ref' varName: getRefName ast range: rangeToJson getRefRange ast Leisure_lambda: (ast)-> _type: 'lambda' varName: getLambdaVar ast body: ast2Json getLambdaBody ast range: rangeToJson getLambdaRange ast Leisure_let: (ast)-> _type: 'let' varName: getLetName ast value: ast2Json getLetValue ast body: ast2Json getLetBody ast range: rangeToJson getLetRange ast Leisure_apply: (ast)-> _type: 'apply' func: ast2Json getApplyFunc ast arg: ast2Json getApplyArg ast Leisure_anno: (ast)-> _type: 'anno' name: getAnnoName ast data: ast2Json getAnnoData ast body: ast2Json getAnnoBody ast Leisure_cons: (ast)-> _type: 'cons' head: ast2Json ast.head() tail: ast2Json ast.tail() Leisure_nil: (ast)-> _type: 'nil' ast2Json = (ast)-> if ast2JsonEncodings[ast.constructor?.name] then ast2JsonEncodings[ast.constructor.name] ast else ast # Leisure interface to the JSON AST codec define 'json2Ast', ((json)-> json2Ast JSON.parse rz json), null, null, null, 'parser' define 'ast2Json', ((ast)-> JSON.stringify ast2Json rz ast), null, null, null, 'parser' consFrom = (array, i)-> i = i || 0 if i < array.length then cons array[i], consFrom(array, i + 1) else Nil head = (l)-> l.head() tail = (l)-> l.tail() root.head = head root.tail = tail root.consFrom = consFrom root.nameSub = nameSub root.setDataType = setDataType root.setType = setType root.mkProto = mkProto root.Nil = Nil root.cons = cons root.primCons = primCons root.define = define root.nakedDefine = nakedDefine root.getType = getType root.getDataType = getDataType root.lit = lit root.ref = ref root.lambda = lambda root.apply = apply root.anno = anno root.llet = llet root.getRefName = getRefName root.getRefRange = getRefRange root.getLitVal = getLitVal root.getLambdaBody = getLambdaBody root.getLambdaVar = getLambdaVar root.getApplyFunc = getApplyFunc root.getApplyArg = getApplyArg root.getLetName = getLetName root.getLetValue = getLetValue root.getLetBody = getLetBody root.getAnnoName = getAnnoName root.getAnnoData = getAnnoData root.getAnnoBody = getAnnoBody root.throwError = throwError root.foldLeft = foldLeft root.LeisureObject = LeisureObject root.evalFunc = evalFunc root.json2Ast = json2Ast root.ast2Json = ast2Json root.Leisure_lit = Leisure_lit root.Leisure_ref = Leisure_ref root.Leisure_lambda = Leisure_lambda root.Leisure_apply = Leisure_apply root.Leisure_let = Leisure_let root.Leisure_anno = Leisure_anno root.ensureLeisureClass = ensureLeisureClass root.makeSuper = makeSuper root.supertypes = supertypes root.functionInfo = functionInfo root.getPos = getPos root.dummyPosition = dummyPosition root.isNil = isNil
[ { "context": "ubject: 'Invitation to Stitch',\n\t\t\t\t\tfrom_email: 'support@teamstitch.com',\n\t\t\t\t\tfrom_name: 'Stitch',\n\t\t\t\t\t\"to\": [{\"email\":", "end": 403, "score": 0.9999223947525024, "start": 381, "tag": "EMAIL", "value": "support@teamstitch.com" }, { "context": "email: 'support@teamstitch.com',\n\t\t\t\t\tfrom_name: 'Stitch',\n\t\t\t\t\t\"to\": [{\"email\": email}],\n\t\t\t\t\timportant: ", "end": 429, "score": 0.9991697669029236, "start": 423, "tag": "NAME", "value": "Stitch" } ]
packages/rocketchat-lib/server/methods/sendInvitationEmail.coffee
akio46/Stitch
0
Meteor.methods sendInvitationEmail: (emails) -> if not Meteor.userId() throw new Meteor.Error 'invalid-user', "[methods] sendInvitationEmail -> Invalid user" for email in emails Mandrill.messages.sendTemplate({ "template_name": "meteor-introduction-to-stitch", "template_content": [{}], "message": { subject: 'Invitation to Stitch', from_email: 'support@teamstitch.com', from_name: 'Stitch', "to": [{"email": email}], important: true } }); return emails
120207
Meteor.methods sendInvitationEmail: (emails) -> if not Meteor.userId() throw new Meteor.Error 'invalid-user', "[methods] sendInvitationEmail -> Invalid user" for email in emails Mandrill.messages.sendTemplate({ "template_name": "meteor-introduction-to-stitch", "template_content": [{}], "message": { subject: 'Invitation to Stitch', from_email: '<EMAIL>', from_name: '<NAME>', "to": [{"email": email}], important: true } }); return emails
true
Meteor.methods sendInvitationEmail: (emails) -> if not Meteor.userId() throw new Meteor.Error 'invalid-user', "[methods] sendInvitationEmail -> Invalid user" for email in emails Mandrill.messages.sendTemplate({ "template_name": "meteor-introduction-to-stitch", "template_content": [{}], "message": { subject: 'Invitation to Stitch', from_email: 'PI:EMAIL:<EMAIL>END_PI', from_name: 'PI:NAME:<NAME>END_PI', "to": [{"email": email}], important: true } }); return emails
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9993084073066711, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-net-reconnect-error.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") net = require("net") assert = require("assert") N = 50 client_error_count = 0 disconnect_count = 0 # Hopefully nothing is running on common.PORT c = net.createConnection(common.PORT) c.on "connect", -> console.error "CLIENT connected" assert.ok false return c.on "error", (e) -> console.error "CLIENT error: " + e.code client_error_count++ assert.equal "ECONNREFUSED", e.code return c.on "close", -> console.log "CLIENT disconnect" c.connect common.PORT if disconnect_count++ < N # reconnect return process.on "exit", -> assert.equal N + 1, disconnect_count assert.equal N + 1, client_error_count return
93425
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") net = require("net") assert = require("assert") N = 50 client_error_count = 0 disconnect_count = 0 # Hopefully nothing is running on common.PORT c = net.createConnection(common.PORT) c.on "connect", -> console.error "CLIENT connected" assert.ok false return c.on "error", (e) -> console.error "CLIENT error: " + e.code client_error_count++ assert.equal "ECONNREFUSED", e.code return c.on "close", -> console.log "CLIENT disconnect" c.connect common.PORT if disconnect_count++ < N # reconnect return process.on "exit", -> assert.equal N + 1, disconnect_count assert.equal N + 1, client_error_count return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") net = require("net") assert = require("assert") N = 50 client_error_count = 0 disconnect_count = 0 # Hopefully nothing is running on common.PORT c = net.createConnection(common.PORT) c.on "connect", -> console.error "CLIENT connected" assert.ok false return c.on "error", (e) -> console.error "CLIENT error: " + e.code client_error_count++ assert.equal "ECONNREFUSED", e.code return c.on "close", -> console.log "CLIENT disconnect" c.connect common.PORT if disconnect_count++ < N # reconnect return process.on "exit", -> assert.equal N + 1, disconnect_count assert.equal N + 1, client_error_count return
[ { "context": "ystem = require(\"system\")\r\nenv = system.env\r\nkey = undefined\r\nfor key of env\r\n console.log key + \"=\" + env[ke", "end": 61, "score": 0.6303043961524963, "start": 52, "tag": "KEY", "value": "undefined" } ]
node_modules/phantomjs/lib/phantom/examples/printenv.coffee
sigilworks/mysweeper
4
system = require("system") env = system.env key = undefined for key of env console.log key + "=" + env[key] if env.hasOwnProperty(key) phantom.exit()
52492
system = require("system") env = system.env key = <KEY> for key of env console.log key + "=" + env[key] if env.hasOwnProperty(key) phantom.exit()
true
system = require("system") env = system.env key = PI:KEY:<KEY>END_PI for key of env console.log key + "=" + env[key] if env.hasOwnProperty(key) phantom.exit()
[ { "context": " @registerCommand 'setusername', ownerOptions, @setusernameFunc\n @registerCommand 'blacklist', ownerOptions, @", "end": 958, "score": 0.8278089165687561, "start": 943, "tag": "USERNAME", "value": "setusernameFunc" }, { "context": "iff\n + [focaBot@#{os.hostname()} ~]$ #{args}\n\n #{s", "end": 2623, "score": 0.5421339273452759, "start": 2615, "tag": "EMAIL", "value": "hostname" } ]
modules/admin/index.coffee
Caydeh/xde
0
reload = require('require-reload')(require) childProcess = require 'child_process' os = require 'os' request = require 'request' Blacklist = reload './blacklist' class AdminModule extends BotModule init: => { @permissions } = @engine @blacklist = new Blacklist @blacklist.init() # Admin Commands adminOptions = adminOnly: true @registerCommand 'setnick', adminOptions, @setnickFunc @registerCommand 'clean', adminOptions, @cleanFunc @registerCommand 'purge', adminOptions, @purgeFunc # Owner Commands ownerOptions = ownerOnly: true allowDM: true @registerCommand 'restart', ownerOptions, @restartFunc @registerCommand 'update', ownerOptions, @updateFunc @registerCommand 'pull', ownerOptions, @pullFunc @registerCommand 'exec', ownerOptions, @execFunc @registerCommand 'setavatar', ownerOptions, @setavatarFunc @registerCommand 'setusername', ownerOptions, @setusernameFunc @registerCommand 'blacklist', ownerOptions, @blacklistFunc @registerCommand 'unblacklist', ownerOptions, @unblacklistFunc # Module Management modOptions = ownerOnly: true allowDM: true argSeparator: ',' @registerCommand 'load', modOptions, @loadFunc @registerCommand 'unload', modOptions, @unloadFunc @registerCommand 'reload', modOptions, @reloadFunc setnickFunc: (msg, args)=> @bot.User.memberOf(msg.guild).setNickname args .then ()=> msg.reply 'Nickname changed succesfully!' .catch (error)=> console.error error msg.reply "Couldn't set nickname for the bot. Make sure it has enough permissions." setusernameFunc: (msg, args)=> @bot.User.setUsername args .then => msg.reply 'Username changed.' .catch => msg.reply "Couldn't change the username." setavatarFunc: (msg,args)=> return if not msg.attachments[0] request { url: msg.attachments[0].url, encoding: null }, (error, response, body)=> @bot.User.setAvatar body if not error and response.statusCode == 200 restartFunc: (msg)=> msg.channel.sendMessage 'FocaBot is restarting...' .then ()-> childProcess.exec('pm2 restart focaBot') updateFunc: (msg,args,d,bot)=> @pullFunc msg, args, bot .then ()=> @restartFunc msg,args,bot pullFunc: (msg,args,d,bot)=> @execFunc msg, 'git pull', bot execFunc: (msg, args, bot)=> new Promise (resolve)=> childProcess.exec args, (error, stdout, stderr)-> if stderr then stderr = '\n-' + stderr msg.channel.sendMessage """ ```diff + [focaBot@#{os.hostname()} ~]$ #{args} #{stdout}#{stderr} ``` """ resolve() cleanFunc: (msg,args,d,bot)=> hasError = false bot.Messages.deleteMessages(msg.channel.messages.filter((m)=> m.author.id is bot.User.id or m.content.indexOf(Core.settings.prefix) is 0 or m.content.indexOf(d.data.prefix) is 0 ).slice(0 - (parseInt(args) or 50))) .catch => msg.channel.sendMessage "Couldn't delete some messages." purgeFunc: (msg, args, d, bot)=> limit = parseInt(args) or 50 msg.channel.fetchMessages limit .then (e)=> bot.Messages.deleteMessages e.messages blacklistFunc: (msg)=> return msg.reply 'No user specified' unless msg.mentions[0] u = msg.mentions[0] await @blacklist.add(u) return msg.reply "Successfully blacklisted **#{u.username}##{u.discriminator}**." unblacklistFunc: (msg)=> return msg.reply 'No user specified' unless msg.mentions[0] u = msg.mentions[0] await @blacklist.remove(u) return msg.reply """ Successfully removed **#{u.username}##{u.discriminator}** from the blacklist. """ # Module management loadFunc: (msg, args)=> try Core.modules.load(args) msg.reply('Success!') unloadFunc: (msg, args)=> try Core.modules.unload(args) msg.reply('Success!') reloadFunc: (msg, args)=> try Core.modules.reload(args) msg.reply('Success!') module.exports = AdminModule
67299
reload = require('require-reload')(require) childProcess = require 'child_process' os = require 'os' request = require 'request' Blacklist = reload './blacklist' class AdminModule extends BotModule init: => { @permissions } = @engine @blacklist = new Blacklist @blacklist.init() # Admin Commands adminOptions = adminOnly: true @registerCommand 'setnick', adminOptions, @setnickFunc @registerCommand 'clean', adminOptions, @cleanFunc @registerCommand 'purge', adminOptions, @purgeFunc # Owner Commands ownerOptions = ownerOnly: true allowDM: true @registerCommand 'restart', ownerOptions, @restartFunc @registerCommand 'update', ownerOptions, @updateFunc @registerCommand 'pull', ownerOptions, @pullFunc @registerCommand 'exec', ownerOptions, @execFunc @registerCommand 'setavatar', ownerOptions, @setavatarFunc @registerCommand 'setusername', ownerOptions, @setusernameFunc @registerCommand 'blacklist', ownerOptions, @blacklistFunc @registerCommand 'unblacklist', ownerOptions, @unblacklistFunc # Module Management modOptions = ownerOnly: true allowDM: true argSeparator: ',' @registerCommand 'load', modOptions, @loadFunc @registerCommand 'unload', modOptions, @unloadFunc @registerCommand 'reload', modOptions, @reloadFunc setnickFunc: (msg, args)=> @bot.User.memberOf(msg.guild).setNickname args .then ()=> msg.reply 'Nickname changed succesfully!' .catch (error)=> console.error error msg.reply "Couldn't set nickname for the bot. Make sure it has enough permissions." setusernameFunc: (msg, args)=> @bot.User.setUsername args .then => msg.reply 'Username changed.' .catch => msg.reply "Couldn't change the username." setavatarFunc: (msg,args)=> return if not msg.attachments[0] request { url: msg.attachments[0].url, encoding: null }, (error, response, body)=> @bot.User.setAvatar body if not error and response.statusCode == 200 restartFunc: (msg)=> msg.channel.sendMessage 'FocaBot is restarting...' .then ()-> childProcess.exec('pm2 restart focaBot') updateFunc: (msg,args,d,bot)=> @pullFunc msg, args, bot .then ()=> @restartFunc msg,args,bot pullFunc: (msg,args,d,bot)=> @execFunc msg, 'git pull', bot execFunc: (msg, args, bot)=> new Promise (resolve)=> childProcess.exec args, (error, stdout, stderr)-> if stderr then stderr = '\n-' + stderr msg.channel.sendMessage """ ```diff + [focaBot@#{os.<EMAIL>()} ~]$ #{args} #{stdout}#{stderr} ``` """ resolve() cleanFunc: (msg,args,d,bot)=> hasError = false bot.Messages.deleteMessages(msg.channel.messages.filter((m)=> m.author.id is bot.User.id or m.content.indexOf(Core.settings.prefix) is 0 or m.content.indexOf(d.data.prefix) is 0 ).slice(0 - (parseInt(args) or 50))) .catch => msg.channel.sendMessage "Couldn't delete some messages." purgeFunc: (msg, args, d, bot)=> limit = parseInt(args) or 50 msg.channel.fetchMessages limit .then (e)=> bot.Messages.deleteMessages e.messages blacklistFunc: (msg)=> return msg.reply 'No user specified' unless msg.mentions[0] u = msg.mentions[0] await @blacklist.add(u) return msg.reply "Successfully blacklisted **#{u.username}##{u.discriminator}**." unblacklistFunc: (msg)=> return msg.reply 'No user specified' unless msg.mentions[0] u = msg.mentions[0] await @blacklist.remove(u) return msg.reply """ Successfully removed **#{u.username}##{u.discriminator}** from the blacklist. """ # Module management loadFunc: (msg, args)=> try Core.modules.load(args) msg.reply('Success!') unloadFunc: (msg, args)=> try Core.modules.unload(args) msg.reply('Success!') reloadFunc: (msg, args)=> try Core.modules.reload(args) msg.reply('Success!') module.exports = AdminModule
true
reload = require('require-reload')(require) childProcess = require 'child_process' os = require 'os' request = require 'request' Blacklist = reload './blacklist' class AdminModule extends BotModule init: => { @permissions } = @engine @blacklist = new Blacklist @blacklist.init() # Admin Commands adminOptions = adminOnly: true @registerCommand 'setnick', adminOptions, @setnickFunc @registerCommand 'clean', adminOptions, @cleanFunc @registerCommand 'purge', adminOptions, @purgeFunc # Owner Commands ownerOptions = ownerOnly: true allowDM: true @registerCommand 'restart', ownerOptions, @restartFunc @registerCommand 'update', ownerOptions, @updateFunc @registerCommand 'pull', ownerOptions, @pullFunc @registerCommand 'exec', ownerOptions, @execFunc @registerCommand 'setavatar', ownerOptions, @setavatarFunc @registerCommand 'setusername', ownerOptions, @setusernameFunc @registerCommand 'blacklist', ownerOptions, @blacklistFunc @registerCommand 'unblacklist', ownerOptions, @unblacklistFunc # Module Management modOptions = ownerOnly: true allowDM: true argSeparator: ',' @registerCommand 'load', modOptions, @loadFunc @registerCommand 'unload', modOptions, @unloadFunc @registerCommand 'reload', modOptions, @reloadFunc setnickFunc: (msg, args)=> @bot.User.memberOf(msg.guild).setNickname args .then ()=> msg.reply 'Nickname changed succesfully!' .catch (error)=> console.error error msg.reply "Couldn't set nickname for the bot. Make sure it has enough permissions." setusernameFunc: (msg, args)=> @bot.User.setUsername args .then => msg.reply 'Username changed.' .catch => msg.reply "Couldn't change the username." setavatarFunc: (msg,args)=> return if not msg.attachments[0] request { url: msg.attachments[0].url, encoding: null }, (error, response, body)=> @bot.User.setAvatar body if not error and response.statusCode == 200 restartFunc: (msg)=> msg.channel.sendMessage 'FocaBot is restarting...' .then ()-> childProcess.exec('pm2 restart focaBot') updateFunc: (msg,args,d,bot)=> @pullFunc msg, args, bot .then ()=> @restartFunc msg,args,bot pullFunc: (msg,args,d,bot)=> @execFunc msg, 'git pull', bot execFunc: (msg, args, bot)=> new Promise (resolve)=> childProcess.exec args, (error, stdout, stderr)-> if stderr then stderr = '\n-' + stderr msg.channel.sendMessage """ ```diff + [focaBot@#{os.PI:EMAIL:<EMAIL>END_PI()} ~]$ #{args} #{stdout}#{stderr} ``` """ resolve() cleanFunc: (msg,args,d,bot)=> hasError = false bot.Messages.deleteMessages(msg.channel.messages.filter((m)=> m.author.id is bot.User.id or m.content.indexOf(Core.settings.prefix) is 0 or m.content.indexOf(d.data.prefix) is 0 ).slice(0 - (parseInt(args) or 50))) .catch => msg.channel.sendMessage "Couldn't delete some messages." purgeFunc: (msg, args, d, bot)=> limit = parseInt(args) or 50 msg.channel.fetchMessages limit .then (e)=> bot.Messages.deleteMessages e.messages blacklistFunc: (msg)=> return msg.reply 'No user specified' unless msg.mentions[0] u = msg.mentions[0] await @blacklist.add(u) return msg.reply "Successfully blacklisted **#{u.username}##{u.discriminator}**." unblacklistFunc: (msg)=> return msg.reply 'No user specified' unless msg.mentions[0] u = msg.mentions[0] await @blacklist.remove(u) return msg.reply """ Successfully removed **#{u.username}##{u.discriminator}** from the blacklist. """ # Module management loadFunc: (msg, args)=> try Core.modules.load(args) msg.reply('Success!') unloadFunc: (msg, args)=> try Core.modules.unload(args) msg.reply('Success!') reloadFunc: (msg, args)=> try Core.modules.reload(args) msg.reply('Success!') module.exports = AdminModule
[ { "context": "ire 'pubnub'\n\npubnub = PUBNUB.init\n\tpublish_key: 'pub-c-84f589ef-0369-4651-8efd-74ae5a369e4f'\n\tsubscribe_key: 'sub-c-188dbfd8-32a0-11e3-a365-0", "end": 340, "score": 0.9997707009315491, "start": 298, "tag": "KEY", "value": "pub-c-84f589ef-0369-4651-8efd-74ae5a369e4f" }, { "context": "9ef-0369-4651-8efd-74ae5a369e4f'\n\tsubscribe_key: 'sub-c-188dbfd8-32a0-11e3-a365-02ee2ddab7fe'\n\nv0 = null\nkickoffTries = 0\n\nsession = session\n\t", "end": 401, "score": 0.9997711181640625, "start": 359, "tag": "KEY", "value": "sub-c-188dbfd8-32a0-11e3-a365-02ee2ddab7fe" } ]
index.coffee
waltzio/cy
1
global.configs = require './configs' global.mongoose = require 'mongoose' session = require './lib/session' api = require 'simple-api' fs = require 'fs' url = require 'url' request = require 'request' formidable = require 'formidable' PUBNUB = require 'pubnub' pubnub = PUBNUB.init publish_key: 'pub-c-84f589ef-0369-4651-8efd-74ae5a369e4f' subscribe_key: 'sub-c-188dbfd8-32a0-11e3-a365-02ee2ddab7fe' v0 = null kickoffTries = 0 session = session secret: configs.secret_key cookie: maxAge: 365 * 24 * 60 * 60 * 1000 kickoff = () -> kickoffTries++ mongoose.connect configs.mongoURL, (err) -> if not err #Create API Server v0 = new api prefix: ["api", "v0"] host: null port: configs.port before: prepareAPIRequest fallback: apiFallback logLevel: 5 oldRespond = v0.responses.respond v0.responses.respond = (res, message, statusCode) -> oldRespond res, message, statusCode #Load Controllers v0.Controller "keys", require "#{__dirname}/api/v0/controllers/keys.coffee" #Mock simple-api model format require "#{__dirname}/api/v0/models/keys.coffee" require "#{__dirname}/api/v0/models/users.coffee" console.log "#{configs.name} is now running at #{configs.host}:#{configs.port}" else if err & kickoffTries < 20 console.log "Mongoose didn't work. That's a bummer. Let's try it again in half a second" setTimeout () -> kickoff() , 1000 else if err console.log "Mongo server seems to really be down. We tried 5 times. Tough luck." prepareAPIRequest = (req, res, controller) -> session req, res, () -> apiFallback = (req, res) -> try session req, res, () -> urlParts = url.parse req.url, true if urlParts.pathname == "/login" fs.readFile './views/login.html', 'utf8', (err, data) -> if err v0.responses.internalError res else template = data template = template.replace "{{url}}", configs.url template = template.replace "{{app_id}}", configs.clef.app_id v0.responses.respond res, template else if urlParts.pathname == "/v1/login" fs.readFile './views/v1/login.html', 'utf8', (err, data) -> if err v0.responses.internalError res else template = data template = template.replace "{{url}}", configs.url template = template.replace "{{app_id}}", configs.clef.app_id v0.responses.respond res, template else if urlParts.pathname == "/clefCallback" handleClefCallback req, res else if urlParts.pathname == "/clefLogout" handleClefLogout req, res else if urlParts.pathname == "/logout" handleBrowserLogout req, res else if urlParts.pathname == "/check" handleAuthenticationCheck req, res else v0.responses.notAvailable res catch error v0.responses.internalError res console.log "API Fallback error!" console.log error handleClefLogout = (req, res) -> urlParts = url.parse req.url, true form = new formidable.IncomingForm console.log "Parsing logout request" form.parse req, (err, fields, files) -> return console.log err if err console.log "Logout request parsed: #{fields}" data = app_id: configs.clef.app_id app_secret: configs.clef.app_secret logout_token: fields.logout_token console.log "Attempting Clef logout request" request.post url: 'https://clef.io/api/v1/logout' form: data (err, resp, body) -> if err msg = "ERROR in clef logout request: #{err}" console.log msg return v0.response.internalError res, msg console.log "Clef logout request recieved #{body}" try userInfo = JSON.parse body if err or !userInfo.success? or !userInfo.success console.log "Error getting clef user info", err v0.responses.notAuth res else Users = mongoose.model "Users" Users.getByIdentifier userInfo.clef_id, (err, existingUser) -> try if err or !existingUser.length console.log "Error finding user with Clef ID #{userInfo.clef_id}", err v0.responses.internalError res, "Error finding your user. This probably isn't your fault. Try again." else user = existingUser[0] user.logged_out_at = Date.now() user.save (err) -> if err console.log "Error saving user with Clef ID #{userInfo.clef_id}", err v0.responses.internalError res, "Error saving the user: #{err}" else console.log "User logged out" pubnub.publish channel: user.identifier message: "logout" v0.responses.respond res catch error v0.responses.internalError res console.log "Error logging user out of Cy" console.log error catch error v0.responses.internalError res console.log "Error handling response from Clef logout!" console.log error handleBrowserLogout = (req, res) -> if req.session req.session = {} v0.responses.respond res handleAuthenticationCheck = (req, res) -> try if req.session? and req.session.user Users = mongoose.model "Users" Users.getByIdentifier req.session.user.identifier, (err, existingUser) -> try if err or !existingUser.length v0.responses.respond res, user: false else user = existingUser[0] if user.logged_out_at > req.session.logged_in_at req.session = {} v0.responses.respond res, user: false else v0.responses.respond res, user: req.session.user.identifier catch error v0.responses.internalError res, "Error checking your user's session. This probably isn't your fault." console.log "Error checking user's current session!" console.log error else v0.responses.respond res, user: false catch error v0.responses.internalError res console.log "Error handling authentication check!" console.log error handleClefCallback = (req, res) -> try urlParts = url.parse req.url, true code = urlParts.query.code form = app_id: configs.clef.app_id app_secret: configs.clef.app_secret code: code request.post url: 'https://clef.io/api/v1/authorize' form: form , (err, resp, body) -> try clefResponse = JSON.parse body if err or not clefResponse.access_token? console.log "Error getting CLEF access token", err, clefResponse v0.responses.notAuth res else req.session.clefAccessToken = JSON.parse(body)['access_token'] request.get "https://clef.io/api/v1/info?access_token=#{req.session.clefAccessToken}", (err, resp, body) -> try userInfo = JSON.parse body if err or !userInfo.success? or !userInfo.success console.log "Error getting clef user info", err v0.responses.notAuth res else Users = mongoose.model "Users" Users.getByIdentifier userInfo.info.id, (err, existingUser) -> if err v0.responses.internalError res, "Error finding your user. This probably isn't your fault. Try again." else if !existingUser.length #User doesn't exist. Let's create one! Users.createWithIdentifier userInfo.info.id, (err, newUser) -> if err v0.responses.internalError res, "Error creating user. This probably isn't your fault. Try again." else #New user created! Woohoo! req.session.logged_in_at = Date.now() req.session.user = newUser v0.responses.respond res, "<script type='text/javascript'>parent.postMessage({auth: true}, '*');</script>" else #user already exists. Let's use that. req.session.logged_in_at = Date.now() req.session.user = existingUser[0] v0.responses.respond res, "<script type='text/javascript'>parent.postMessage({auth: true}, '*');</script>" catch error v0.responses.internalError res, "Error getting user information from Clef. This probably isn't your fault." console.log "Error parsing user response from Clef!" console.log error catch error v0.responses.internalError res, "Error getting authentication from Clef. This probaby isn't your fault." console.log "Error parsing authentication response from Clef!" console.log error catch error v0.responses.internalError res console.log "Error handling Clef callback!" console.log error kickoff()
165004
global.configs = require './configs' global.mongoose = require 'mongoose' session = require './lib/session' api = require 'simple-api' fs = require 'fs' url = require 'url' request = require 'request' formidable = require 'formidable' PUBNUB = require 'pubnub' pubnub = PUBNUB.init publish_key: '<KEY>' subscribe_key: '<KEY>' v0 = null kickoffTries = 0 session = session secret: configs.secret_key cookie: maxAge: 365 * 24 * 60 * 60 * 1000 kickoff = () -> kickoffTries++ mongoose.connect configs.mongoURL, (err) -> if not err #Create API Server v0 = new api prefix: ["api", "v0"] host: null port: configs.port before: prepareAPIRequest fallback: apiFallback logLevel: 5 oldRespond = v0.responses.respond v0.responses.respond = (res, message, statusCode) -> oldRespond res, message, statusCode #Load Controllers v0.Controller "keys", require "#{__dirname}/api/v0/controllers/keys.coffee" #Mock simple-api model format require "#{__dirname}/api/v0/models/keys.coffee" require "#{__dirname}/api/v0/models/users.coffee" console.log "#{configs.name} is now running at #{configs.host}:#{configs.port}" else if err & kickoffTries < 20 console.log "Mongoose didn't work. That's a bummer. Let's try it again in half a second" setTimeout () -> kickoff() , 1000 else if err console.log "Mongo server seems to really be down. We tried 5 times. Tough luck." prepareAPIRequest = (req, res, controller) -> session req, res, () -> apiFallback = (req, res) -> try session req, res, () -> urlParts = url.parse req.url, true if urlParts.pathname == "/login" fs.readFile './views/login.html', 'utf8', (err, data) -> if err v0.responses.internalError res else template = data template = template.replace "{{url}}", configs.url template = template.replace "{{app_id}}", configs.clef.app_id v0.responses.respond res, template else if urlParts.pathname == "/v1/login" fs.readFile './views/v1/login.html', 'utf8', (err, data) -> if err v0.responses.internalError res else template = data template = template.replace "{{url}}", configs.url template = template.replace "{{app_id}}", configs.clef.app_id v0.responses.respond res, template else if urlParts.pathname == "/clefCallback" handleClefCallback req, res else if urlParts.pathname == "/clefLogout" handleClefLogout req, res else if urlParts.pathname == "/logout" handleBrowserLogout req, res else if urlParts.pathname == "/check" handleAuthenticationCheck req, res else v0.responses.notAvailable res catch error v0.responses.internalError res console.log "API Fallback error!" console.log error handleClefLogout = (req, res) -> urlParts = url.parse req.url, true form = new formidable.IncomingForm console.log "Parsing logout request" form.parse req, (err, fields, files) -> return console.log err if err console.log "Logout request parsed: #{fields}" data = app_id: configs.clef.app_id app_secret: configs.clef.app_secret logout_token: fields.logout_token console.log "Attempting Clef logout request" request.post url: 'https://clef.io/api/v1/logout' form: data (err, resp, body) -> if err msg = "ERROR in clef logout request: #{err}" console.log msg return v0.response.internalError res, msg console.log "Clef logout request recieved #{body}" try userInfo = JSON.parse body if err or !userInfo.success? or !userInfo.success console.log "Error getting clef user info", err v0.responses.notAuth res else Users = mongoose.model "Users" Users.getByIdentifier userInfo.clef_id, (err, existingUser) -> try if err or !existingUser.length console.log "Error finding user with Clef ID #{userInfo.clef_id}", err v0.responses.internalError res, "Error finding your user. This probably isn't your fault. Try again." else user = existingUser[0] user.logged_out_at = Date.now() user.save (err) -> if err console.log "Error saving user with Clef ID #{userInfo.clef_id}", err v0.responses.internalError res, "Error saving the user: #{err}" else console.log "User logged out" pubnub.publish channel: user.identifier message: "logout" v0.responses.respond res catch error v0.responses.internalError res console.log "Error logging user out of Cy" console.log error catch error v0.responses.internalError res console.log "Error handling response from Clef logout!" console.log error handleBrowserLogout = (req, res) -> if req.session req.session = {} v0.responses.respond res handleAuthenticationCheck = (req, res) -> try if req.session? and req.session.user Users = mongoose.model "Users" Users.getByIdentifier req.session.user.identifier, (err, existingUser) -> try if err or !existingUser.length v0.responses.respond res, user: false else user = existingUser[0] if user.logged_out_at > req.session.logged_in_at req.session = {} v0.responses.respond res, user: false else v0.responses.respond res, user: req.session.user.identifier catch error v0.responses.internalError res, "Error checking your user's session. This probably isn't your fault." console.log "Error checking user's current session!" console.log error else v0.responses.respond res, user: false catch error v0.responses.internalError res console.log "Error handling authentication check!" console.log error handleClefCallback = (req, res) -> try urlParts = url.parse req.url, true code = urlParts.query.code form = app_id: configs.clef.app_id app_secret: configs.clef.app_secret code: code request.post url: 'https://clef.io/api/v1/authorize' form: form , (err, resp, body) -> try clefResponse = JSON.parse body if err or not clefResponse.access_token? console.log "Error getting CLEF access token", err, clefResponse v0.responses.notAuth res else req.session.clefAccessToken = JSON.parse(body)['access_token'] request.get "https://clef.io/api/v1/info?access_token=#{req.session.clefAccessToken}", (err, resp, body) -> try userInfo = JSON.parse body if err or !userInfo.success? or !userInfo.success console.log "Error getting clef user info", err v0.responses.notAuth res else Users = mongoose.model "Users" Users.getByIdentifier userInfo.info.id, (err, existingUser) -> if err v0.responses.internalError res, "Error finding your user. This probably isn't your fault. Try again." else if !existingUser.length #User doesn't exist. Let's create one! Users.createWithIdentifier userInfo.info.id, (err, newUser) -> if err v0.responses.internalError res, "Error creating user. This probably isn't your fault. Try again." else #New user created! Woohoo! req.session.logged_in_at = Date.now() req.session.user = newUser v0.responses.respond res, "<script type='text/javascript'>parent.postMessage({auth: true}, '*');</script>" else #user already exists. Let's use that. req.session.logged_in_at = Date.now() req.session.user = existingUser[0] v0.responses.respond res, "<script type='text/javascript'>parent.postMessage({auth: true}, '*');</script>" catch error v0.responses.internalError res, "Error getting user information from Clef. This probably isn't your fault." console.log "Error parsing user response from Clef!" console.log error catch error v0.responses.internalError res, "Error getting authentication from Clef. This probaby isn't your fault." console.log "Error parsing authentication response from Clef!" console.log error catch error v0.responses.internalError res console.log "Error handling Clef callback!" console.log error kickoff()
true
global.configs = require './configs' global.mongoose = require 'mongoose' session = require './lib/session' api = require 'simple-api' fs = require 'fs' url = require 'url' request = require 'request' formidable = require 'formidable' PUBNUB = require 'pubnub' pubnub = PUBNUB.init publish_key: 'PI:KEY:<KEY>END_PI' subscribe_key: 'PI:KEY:<KEY>END_PI' v0 = null kickoffTries = 0 session = session secret: configs.secret_key cookie: maxAge: 365 * 24 * 60 * 60 * 1000 kickoff = () -> kickoffTries++ mongoose.connect configs.mongoURL, (err) -> if not err #Create API Server v0 = new api prefix: ["api", "v0"] host: null port: configs.port before: prepareAPIRequest fallback: apiFallback logLevel: 5 oldRespond = v0.responses.respond v0.responses.respond = (res, message, statusCode) -> oldRespond res, message, statusCode #Load Controllers v0.Controller "keys", require "#{__dirname}/api/v0/controllers/keys.coffee" #Mock simple-api model format require "#{__dirname}/api/v0/models/keys.coffee" require "#{__dirname}/api/v0/models/users.coffee" console.log "#{configs.name} is now running at #{configs.host}:#{configs.port}" else if err & kickoffTries < 20 console.log "Mongoose didn't work. That's a bummer. Let's try it again in half a second" setTimeout () -> kickoff() , 1000 else if err console.log "Mongo server seems to really be down. We tried 5 times. Tough luck." prepareAPIRequest = (req, res, controller) -> session req, res, () -> apiFallback = (req, res) -> try session req, res, () -> urlParts = url.parse req.url, true if urlParts.pathname == "/login" fs.readFile './views/login.html', 'utf8', (err, data) -> if err v0.responses.internalError res else template = data template = template.replace "{{url}}", configs.url template = template.replace "{{app_id}}", configs.clef.app_id v0.responses.respond res, template else if urlParts.pathname == "/v1/login" fs.readFile './views/v1/login.html', 'utf8', (err, data) -> if err v0.responses.internalError res else template = data template = template.replace "{{url}}", configs.url template = template.replace "{{app_id}}", configs.clef.app_id v0.responses.respond res, template else if urlParts.pathname == "/clefCallback" handleClefCallback req, res else if urlParts.pathname == "/clefLogout" handleClefLogout req, res else if urlParts.pathname == "/logout" handleBrowserLogout req, res else if urlParts.pathname == "/check" handleAuthenticationCheck req, res else v0.responses.notAvailable res catch error v0.responses.internalError res console.log "API Fallback error!" console.log error handleClefLogout = (req, res) -> urlParts = url.parse req.url, true form = new formidable.IncomingForm console.log "Parsing logout request" form.parse req, (err, fields, files) -> return console.log err if err console.log "Logout request parsed: #{fields}" data = app_id: configs.clef.app_id app_secret: configs.clef.app_secret logout_token: fields.logout_token console.log "Attempting Clef logout request" request.post url: 'https://clef.io/api/v1/logout' form: data (err, resp, body) -> if err msg = "ERROR in clef logout request: #{err}" console.log msg return v0.response.internalError res, msg console.log "Clef logout request recieved #{body}" try userInfo = JSON.parse body if err or !userInfo.success? or !userInfo.success console.log "Error getting clef user info", err v0.responses.notAuth res else Users = mongoose.model "Users" Users.getByIdentifier userInfo.clef_id, (err, existingUser) -> try if err or !existingUser.length console.log "Error finding user with Clef ID #{userInfo.clef_id}", err v0.responses.internalError res, "Error finding your user. This probably isn't your fault. Try again." else user = existingUser[0] user.logged_out_at = Date.now() user.save (err) -> if err console.log "Error saving user with Clef ID #{userInfo.clef_id}", err v0.responses.internalError res, "Error saving the user: #{err}" else console.log "User logged out" pubnub.publish channel: user.identifier message: "logout" v0.responses.respond res catch error v0.responses.internalError res console.log "Error logging user out of Cy" console.log error catch error v0.responses.internalError res console.log "Error handling response from Clef logout!" console.log error handleBrowserLogout = (req, res) -> if req.session req.session = {} v0.responses.respond res handleAuthenticationCheck = (req, res) -> try if req.session? and req.session.user Users = mongoose.model "Users" Users.getByIdentifier req.session.user.identifier, (err, existingUser) -> try if err or !existingUser.length v0.responses.respond res, user: false else user = existingUser[0] if user.logged_out_at > req.session.logged_in_at req.session = {} v0.responses.respond res, user: false else v0.responses.respond res, user: req.session.user.identifier catch error v0.responses.internalError res, "Error checking your user's session. This probably isn't your fault." console.log "Error checking user's current session!" console.log error else v0.responses.respond res, user: false catch error v0.responses.internalError res console.log "Error handling authentication check!" console.log error handleClefCallback = (req, res) -> try urlParts = url.parse req.url, true code = urlParts.query.code form = app_id: configs.clef.app_id app_secret: configs.clef.app_secret code: code request.post url: 'https://clef.io/api/v1/authorize' form: form , (err, resp, body) -> try clefResponse = JSON.parse body if err or not clefResponse.access_token? console.log "Error getting CLEF access token", err, clefResponse v0.responses.notAuth res else req.session.clefAccessToken = JSON.parse(body)['access_token'] request.get "https://clef.io/api/v1/info?access_token=#{req.session.clefAccessToken}", (err, resp, body) -> try userInfo = JSON.parse body if err or !userInfo.success? or !userInfo.success console.log "Error getting clef user info", err v0.responses.notAuth res else Users = mongoose.model "Users" Users.getByIdentifier userInfo.info.id, (err, existingUser) -> if err v0.responses.internalError res, "Error finding your user. This probably isn't your fault. Try again." else if !existingUser.length #User doesn't exist. Let's create one! Users.createWithIdentifier userInfo.info.id, (err, newUser) -> if err v0.responses.internalError res, "Error creating user. This probably isn't your fault. Try again." else #New user created! Woohoo! req.session.logged_in_at = Date.now() req.session.user = newUser v0.responses.respond res, "<script type='text/javascript'>parent.postMessage({auth: true}, '*');</script>" else #user already exists. Let's use that. req.session.logged_in_at = Date.now() req.session.user = existingUser[0] v0.responses.respond res, "<script type='text/javascript'>parent.postMessage({auth: true}, '*');</script>" catch error v0.responses.internalError res, "Error getting user information from Clef. This probably isn't your fault." console.log "Error parsing user response from Clef!" console.log error catch error v0.responses.internalError res, "Error getting authentication from Clef. This probaby isn't your fault." console.log "Error parsing authentication response from Clef!" console.log error catch error v0.responses.internalError res console.log "Error handling Clef callback!" console.log error kickoff()