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": "erver/users/User'\n\ntestPost =\n data:\n email: 'scott@codecombat.com'\n id: '12345678'\n merges:\n INTERESTS: ",
"end": 161,
"score": 0.9999237060546875,
"start": 141,
"tag": "EMAIL",
"value": "scott@codecombat.com"
},
{
"context": ", Diplomats, Ambassadors, Artisans'\n FNAME: 'Scott'\n LNAME: 'Erickson'\n\ndescribe 'handleProfile",
"end": 313,
"score": 0.9998363256454468,
"start": 308,
"tag": "NAME",
"value": "Scott"
},
{
"context": "ors, Artisans'\n FNAME: 'Scott'\n LNAME: 'Erickson'\n\ndescribe 'handleProfileUpdate', ->\n it 'update",
"end": 337,
"score": 0.9998237490653992,
"start": 329,
"tag": "NAME",
"value": "Erickson"
}
] | test/server/functional/mail.spec.coffee | madawei2699/codecombat | 0 | require '../common'
mail = require '../../../server/routes/mail'
User = require '../../../server/users/User'
testPost =
data:
email: 'scott@codecombat.com'
id: '12345678'
merges:
INTERESTS: 'Announcements, Adventurers, Archmages, Scribes, Diplomats, Ambassadors, Artisans'
FNAME: 'Scott'
LNAME: 'Erickson'
describe 'handleProfileUpdate', ->
it 'updates emails from the data passed in', (done) ->
u = new User()
mail.handleProfileUpdate(u, testPost)
expect(u.isEmailSubscriptionEnabled('generalNews')).toBeTruthy()
expect(u.isEmailSubscriptionEnabled('adventurerNews')).toBeTruthy()
expect(u.isEmailSubscriptionEnabled('archmageNews')).toBeTruthy()
expect(u.isEmailSubscriptionEnabled('scribeNews')).toBeTruthy()
expect(u.isEmailSubscriptionEnabled('diplomatNews')).toBeTruthy()
expect(u.isEmailSubscriptionEnabled('ambassadorNews')).toBeTruthy()
expect(u.isEmailSubscriptionEnabled('artisanNews')).toBeTruthy()
done()
describe 'handleUnsubscribe', ->
it 'turns off all news and notifications', (done) ->
u = new User({generalNews: {enabled:true}, archmageNews: {enabled:true}, anyNotes: {enabled:true}})
mail.handleUnsubscribe(u)
expect(u.isEmailSubscriptionEnabled('generalNews')).toBeFalsy()
expect(u.isEmailSubscriptionEnabled('adventurerNews')).toBeFalsy()
expect(u.isEmailSubscriptionEnabled('archmageNews')).toBeFalsy()
expect(u.isEmailSubscriptionEnabled('scribeNews')).toBeFalsy()
expect(u.isEmailSubscriptionEnabled('diplomatNews')).toBeFalsy()
expect(u.isEmailSubscriptionEnabled('ambassadorNews')).toBeFalsy()
expect(u.isEmailSubscriptionEnabled('artisanNews')).toBeFalsy()
done()
| 67934 | require '../common'
mail = require '../../../server/routes/mail'
User = require '../../../server/users/User'
testPost =
data:
email: '<EMAIL>'
id: '12345678'
merges:
INTERESTS: 'Announcements, Adventurers, Archmages, Scribes, Diplomats, Ambassadors, Artisans'
FNAME: '<NAME>'
LNAME: '<NAME>'
describe 'handleProfileUpdate', ->
it 'updates emails from the data passed in', (done) ->
u = new User()
mail.handleProfileUpdate(u, testPost)
expect(u.isEmailSubscriptionEnabled('generalNews')).toBeTruthy()
expect(u.isEmailSubscriptionEnabled('adventurerNews')).toBeTruthy()
expect(u.isEmailSubscriptionEnabled('archmageNews')).toBeTruthy()
expect(u.isEmailSubscriptionEnabled('scribeNews')).toBeTruthy()
expect(u.isEmailSubscriptionEnabled('diplomatNews')).toBeTruthy()
expect(u.isEmailSubscriptionEnabled('ambassadorNews')).toBeTruthy()
expect(u.isEmailSubscriptionEnabled('artisanNews')).toBeTruthy()
done()
describe 'handleUnsubscribe', ->
it 'turns off all news and notifications', (done) ->
u = new User({generalNews: {enabled:true}, archmageNews: {enabled:true}, anyNotes: {enabled:true}})
mail.handleUnsubscribe(u)
expect(u.isEmailSubscriptionEnabled('generalNews')).toBeFalsy()
expect(u.isEmailSubscriptionEnabled('adventurerNews')).toBeFalsy()
expect(u.isEmailSubscriptionEnabled('archmageNews')).toBeFalsy()
expect(u.isEmailSubscriptionEnabled('scribeNews')).toBeFalsy()
expect(u.isEmailSubscriptionEnabled('diplomatNews')).toBeFalsy()
expect(u.isEmailSubscriptionEnabled('ambassadorNews')).toBeFalsy()
expect(u.isEmailSubscriptionEnabled('artisanNews')).toBeFalsy()
done()
| true | require '../common'
mail = require '../../../server/routes/mail'
User = require '../../../server/users/User'
testPost =
data:
email: 'PI:EMAIL:<EMAIL>END_PI'
id: '12345678'
merges:
INTERESTS: 'Announcements, Adventurers, Archmages, Scribes, Diplomats, Ambassadors, Artisans'
FNAME: 'PI:NAME:<NAME>END_PI'
LNAME: 'PI:NAME:<NAME>END_PI'
describe 'handleProfileUpdate', ->
it 'updates emails from the data passed in', (done) ->
u = new User()
mail.handleProfileUpdate(u, testPost)
expect(u.isEmailSubscriptionEnabled('generalNews')).toBeTruthy()
expect(u.isEmailSubscriptionEnabled('adventurerNews')).toBeTruthy()
expect(u.isEmailSubscriptionEnabled('archmageNews')).toBeTruthy()
expect(u.isEmailSubscriptionEnabled('scribeNews')).toBeTruthy()
expect(u.isEmailSubscriptionEnabled('diplomatNews')).toBeTruthy()
expect(u.isEmailSubscriptionEnabled('ambassadorNews')).toBeTruthy()
expect(u.isEmailSubscriptionEnabled('artisanNews')).toBeTruthy()
done()
describe 'handleUnsubscribe', ->
it 'turns off all news and notifications', (done) ->
u = new User({generalNews: {enabled:true}, archmageNews: {enabled:true}, anyNotes: {enabled:true}})
mail.handleUnsubscribe(u)
expect(u.isEmailSubscriptionEnabled('generalNews')).toBeFalsy()
expect(u.isEmailSubscriptionEnabled('adventurerNews')).toBeFalsy()
expect(u.isEmailSubscriptionEnabled('archmageNews')).toBeFalsy()
expect(u.isEmailSubscriptionEnabled('scribeNews')).toBeFalsy()
expect(u.isEmailSubscriptionEnabled('diplomatNews')).toBeFalsy()
expect(u.isEmailSubscriptionEnabled('ambassadorNews')).toBeFalsy()
expect(u.isEmailSubscriptionEnabled('artisanNews')).toBeFalsy()
done()
|
[
{
"context": " @store.pushPayload \"salsa\",\n data:\n id: \"seinaru iyazoi\"\n type: \"salsas\"\n attributes:\n i",
"end": 1710,
"score": 0.9936254620552063,
"start": 1696,
"tag": "NAME",
"value": "seinaru iyazoi"
},
{
"context": "ment()\n updatedAt: moment()\n name: \"Verde Ultra\"\n price: 2342\n secretSauce: \"soy\"\n ",
"end": 1834,
"score": 0.9998102188110352,
"start": 1823,
"tag": "NAME",
"value": "Verde Ultra"
}
] | tests/acceptance/field-schema-engine-test.coffee | foxnewsnetwork/autox | 0 | `import Ember from 'ember'`
`import { test } from 'qunit'`
`import moduleForAcceptance from '../../tests/helpers/module-for-acceptance'`
`import _ from 'lodash/lodash'`
{chain} = _
moduleForAcceptance 'Acceptance: FieldSchemaEngine'
test 'shop fields', (assert) ->
@container = @application.__container__
visit "/"
andThen =>
assert.ok(shops = @container.lookup "field:shop")
assert.notOk shops.create, "collections are instances, not classes"
assert.equal shops.constructor.modelName, "shop", "we should have the proper model name"
assert.ok(nameField = @container.lookup "field:shop/name")
assert.notOk nameField.create, "name field should be an instance, not a class"
assert.equal nameField.constructor.fieldName, "name", "the field constructor should have proper info"
assert.equal typeof nameField.initState, "function", "field instances should be able to init state"
assert.ok Ember.getOwner(shops), "collection should have owner"
chain(shops.get "fields")
.tap (fields) ->
assert.ok fields, "we should get all the fields related to the shop model"
.map (field) ->
fn = field?.constructor?.fieldName
assert.notOk field.create, "a field is an instance, not a class #{fn}"
assert.ok fn, "fields all should have a field name #{fn}"
assert.equal typeof field.initState, "function", "all fields should be able to init state #{fn}"
.value()
visit "/shops/new"
andThen =>
assert.equal currentPath(), "shops.new"
test "salsa fields", (assert) ->
@container = @application.__container__
@store = @container.lookup("service:store")
visit "/"
@store.pushPayload "salsa",
data:
id: "seinaru iyazoi"
type: "salsas"
attributes:
insertedAt: moment()
updatedAt: moment()
name: "Verde Ultra"
price: 2342
secretSauce: "soy"
andThen =>
salsas = @container.lookup "field:salsa"
assert.ok salsas, "the salsas collection should be present"
mateActionField = @container.lookup "field:salsa/mate-with-shop"
assert.ok mateActionField, "we should have found the mate field"
rawG = mateActionField.get("rawGen")
assert.equal typeof rawG, "function", "the raw generator is a function"
g = mateActionField.get("generator")
assert.ok g, "we should have found the generator"
assert.equal typeof g, "function", "the generator is a function"
assert.equal g.constructor.name, "GeneratorFunction", "generator funtions are named so"
salsa = @store.peekRecord "salsa", "seinaru iyazoi"
assert.ok salsa
mateActionField.initState(routeAction: "model#index", model: salsa)
.then (state) =>
assert.ok (@sally = state), "we should have an action state"
assert.equal typeof state.get("iterator").next, "function", "the iterator should be there"
assert.ok state.get("isVirgin"), "start out as virgins"
assert.notOk state.get("activeNeed"), "who aren't needy"
andThen =>
@sally.invokeAction()
andThen =>
assert.notOk @sally.get("isVirgin"), "should no longer be a virgin"
assert.ok @sally.get("isNeedy"), "should now be needy"
assert.ok (need = @sally.get("activeNeed")), "sally now has an active need"
assert.equal need.get("modelName"), "shop", "that need is to shop"
assert.equal need.get("amount"), 1, "just once is enough" | 39155 | `import Ember from 'ember'`
`import { test } from 'qunit'`
`import moduleForAcceptance from '../../tests/helpers/module-for-acceptance'`
`import _ from 'lodash/lodash'`
{chain} = _
moduleForAcceptance 'Acceptance: FieldSchemaEngine'
test 'shop fields', (assert) ->
@container = @application.__container__
visit "/"
andThen =>
assert.ok(shops = @container.lookup "field:shop")
assert.notOk shops.create, "collections are instances, not classes"
assert.equal shops.constructor.modelName, "shop", "we should have the proper model name"
assert.ok(nameField = @container.lookup "field:shop/name")
assert.notOk nameField.create, "name field should be an instance, not a class"
assert.equal nameField.constructor.fieldName, "name", "the field constructor should have proper info"
assert.equal typeof nameField.initState, "function", "field instances should be able to init state"
assert.ok Ember.getOwner(shops), "collection should have owner"
chain(shops.get "fields")
.tap (fields) ->
assert.ok fields, "we should get all the fields related to the shop model"
.map (field) ->
fn = field?.constructor?.fieldName
assert.notOk field.create, "a field is an instance, not a class #{fn}"
assert.ok fn, "fields all should have a field name #{fn}"
assert.equal typeof field.initState, "function", "all fields should be able to init state #{fn}"
.value()
visit "/shops/new"
andThen =>
assert.equal currentPath(), "shops.new"
test "salsa fields", (assert) ->
@container = @application.__container__
@store = @container.lookup("service:store")
visit "/"
@store.pushPayload "salsa",
data:
id: "<NAME>"
type: "salsas"
attributes:
insertedAt: moment()
updatedAt: moment()
name: "<NAME>"
price: 2342
secretSauce: "soy"
andThen =>
salsas = @container.lookup "field:salsa"
assert.ok salsas, "the salsas collection should be present"
mateActionField = @container.lookup "field:salsa/mate-with-shop"
assert.ok mateActionField, "we should have found the mate field"
rawG = mateActionField.get("rawGen")
assert.equal typeof rawG, "function", "the raw generator is a function"
g = mateActionField.get("generator")
assert.ok g, "we should have found the generator"
assert.equal typeof g, "function", "the generator is a function"
assert.equal g.constructor.name, "GeneratorFunction", "generator funtions are named so"
salsa = @store.peekRecord "salsa", "seinaru iyazoi"
assert.ok salsa
mateActionField.initState(routeAction: "model#index", model: salsa)
.then (state) =>
assert.ok (@sally = state), "we should have an action state"
assert.equal typeof state.get("iterator").next, "function", "the iterator should be there"
assert.ok state.get("isVirgin"), "start out as virgins"
assert.notOk state.get("activeNeed"), "who aren't needy"
andThen =>
@sally.invokeAction()
andThen =>
assert.notOk @sally.get("isVirgin"), "should no longer be a virgin"
assert.ok @sally.get("isNeedy"), "should now be needy"
assert.ok (need = @sally.get("activeNeed")), "sally now has an active need"
assert.equal need.get("modelName"), "shop", "that need is to shop"
assert.equal need.get("amount"), 1, "just once is enough" | true | `import Ember from 'ember'`
`import { test } from 'qunit'`
`import moduleForAcceptance from '../../tests/helpers/module-for-acceptance'`
`import _ from 'lodash/lodash'`
{chain} = _
moduleForAcceptance 'Acceptance: FieldSchemaEngine'
test 'shop fields', (assert) ->
@container = @application.__container__
visit "/"
andThen =>
assert.ok(shops = @container.lookup "field:shop")
assert.notOk shops.create, "collections are instances, not classes"
assert.equal shops.constructor.modelName, "shop", "we should have the proper model name"
assert.ok(nameField = @container.lookup "field:shop/name")
assert.notOk nameField.create, "name field should be an instance, not a class"
assert.equal nameField.constructor.fieldName, "name", "the field constructor should have proper info"
assert.equal typeof nameField.initState, "function", "field instances should be able to init state"
assert.ok Ember.getOwner(shops), "collection should have owner"
chain(shops.get "fields")
.tap (fields) ->
assert.ok fields, "we should get all the fields related to the shop model"
.map (field) ->
fn = field?.constructor?.fieldName
assert.notOk field.create, "a field is an instance, not a class #{fn}"
assert.ok fn, "fields all should have a field name #{fn}"
assert.equal typeof field.initState, "function", "all fields should be able to init state #{fn}"
.value()
visit "/shops/new"
andThen =>
assert.equal currentPath(), "shops.new"
test "salsa fields", (assert) ->
@container = @application.__container__
@store = @container.lookup("service:store")
visit "/"
@store.pushPayload "salsa",
data:
id: "PI:NAME:<NAME>END_PI"
type: "salsas"
attributes:
insertedAt: moment()
updatedAt: moment()
name: "PI:NAME:<NAME>END_PI"
price: 2342
secretSauce: "soy"
andThen =>
salsas = @container.lookup "field:salsa"
assert.ok salsas, "the salsas collection should be present"
mateActionField = @container.lookup "field:salsa/mate-with-shop"
assert.ok mateActionField, "we should have found the mate field"
rawG = mateActionField.get("rawGen")
assert.equal typeof rawG, "function", "the raw generator is a function"
g = mateActionField.get("generator")
assert.ok g, "we should have found the generator"
assert.equal typeof g, "function", "the generator is a function"
assert.equal g.constructor.name, "GeneratorFunction", "generator funtions are named so"
salsa = @store.peekRecord "salsa", "seinaru iyazoi"
assert.ok salsa
mateActionField.initState(routeAction: "model#index", model: salsa)
.then (state) =>
assert.ok (@sally = state), "we should have an action state"
assert.equal typeof state.get("iterator").next, "function", "the iterator should be there"
assert.ok state.get("isVirgin"), "start out as virgins"
assert.notOk state.get("activeNeed"), "who aren't needy"
andThen =>
@sally.invokeAction()
andThen =>
assert.notOk @sally.get("isVirgin"), "should no longer be a virgin"
assert.ok @sally.get("isNeedy"), "should now be needy"
assert.ok (need = @sally.get("activeNeed")), "sally now has an active need"
assert.equal need.get("modelName"), "shop", "that need is to shop"
assert.equal need.get("amount"), 1, "just once is enough" |
[
{
"context": "].tracingConfig ?= \"PassThrough\"\n\n if key in [\"viewerRequest\", \"viewerResponse\"]\n include secondar",
"end": 5882,
"score": 0.5878767371177673,
"start": 5876,
"tag": "KEY",
"value": "viewer"
},
{
"context": "sThrough\"\n\n if key in [\"viewerRequest\", \"viewerResponse\"]\n include secondary[key], memorySize: 128\n ",
"end": 5907,
"score": 0.6572861671447754,
"start": 5899,
"tag": "KEY",
"value": "Response"
}
] | src/configuration/preprocessor/lambdas.coffee | pandastrike/haiku9 | 10 | import {flow} from "panda-garden"
import {resolve, parse, relative} from "path"
import {resolve as resolveURL} from "url"
import {isEmpty, include, dashed, clone} from "panda-parchment"
import {read, rm, rmr, mkdir, mkdirp, glob, write} from "panda-quill"
import PandaTemplate from "panda-template"
import {shell} from "../../utils"
import {zip, gzip, brotli, md5} from "../../helpers"
T = new PandaTemplate()
defaultDir = resolve __dirname, "..", "..", "..", "..", "..",
"files", "default-lambdas"
deployDir = resolve process.cwd(), "haiku9-deploy"
cleanDirectory = (config) ->
console.log "cleaning Haiku deploy directory"
await rmr "haiku9-deploy"
await mkdir "0777", "haiku9-deploy"
config
startEdgeConfig = (config) ->
config.environment.edge ?= {}
config.environment.edge.primary = clone config.environment.edge
config
buildSecondaryLambda = (config) ->
{hostnames} = config.environment
sourceDir = resolve defaultDir, "secondary", "origin-request", "lib"
targetDir = resolve deployDir, "secondary"
await mkdirp "0777", targetDir
await shell "cp -R #{sourceDir} #{targetDir}"
path = resolve targetDir, "lib", "environment.hbs"
template = await read path
await rm path
url = "https://#{hostnames[0]}"
file = T.render template, {url}
await write (resolve targetDir, "lib", "environment.js"), file
await zip targetDir, "lib", "origin-request.zip"
await shell "rm -rf lib", "haiku9-deploy/secondary"
applySecondaryLambdas = (config) ->
{hostnames} = config.environment
if hostnames.length > 1
console.log "loading secondary hostname redirect lambdas."
await buildSecondaryLambda config
config.environment.edge.secondary =
originRequest:
runtime: "nodejs12.x"
src: resolve "haiku9-deploy", "secondary", "origin-request.zip"
handler: "lib/index.handler"
config
buildPrimaryLambdas = (config) ->
unless config.source?
throw new Error "The default origin-request and origin-response edge lambdas require source to be specified as your assets directory."
unless config.site?.index? && config.site?.error
throw new Error "The default origin-request and origin-response edge lambdas require site.index and site.error to be specified from an assets directory."
# Origin Requst Lambda
source = config.source
indexKey = config.site.index
indexFile = await read (resolve source, indexKey), "buffer"
indexFileGzip = await gzip indexFile
indexFileBrotli = await brotli indexFile
sourceDir = resolve defaultDir, "primary", "origin-request", "lib"
targetDir = resolve deployDir, "primary"
await mkdirp "0777", targetDir
await shell "cp -R #{sourceDir} #{targetDir}"
path = resolve targetDir, "lib", "index-files"
await mkdir "0777", path
await write (resolve path, "identity"), indexFile
await write (resolve path, "gzip"), indexFileGzip
await write (resolve path, "brotli"), indexFileBrotli
await zip targetDir, "lib", "origin-request.zip"
await shell "rm -rf lib", "haiku9-deploy/primary"
# Origin Response Lambda
source = config.source
errorKey = config.site.error
errorFile = await read (resolve source, errorKey), "buffer"
errorFileGzip = await gzip errorFile
errorFileBrotli = await brotli errorFile
sourceDir = resolve defaultDir, "primary", "origin-response", "lib"
targetDir = resolve deployDir, "primary"
await mkdirp "0777", targetDir
await shell "cp -R #{sourceDir} #{targetDir}"
path = resolve targetDir, "lib", "error-files"
await mkdir "0777", path
await write (resolve path, "identity"), errorFile
await write (resolve path, "gzip"), errorFileGzip
await write (resolve path, "brotli"), errorFileBrotli
await zip targetDir, "lib", "origin-response.zip"
await shell "rm -rf lib", "haiku9-deploy/primary"
compressLambda = (lambda) ->
{type, src} = lambda
# Origin Requst Lambda
sourceDir = resolve src
targetDir = resolve deployDir, "primary", "lib"
await mkdirp "0777", targetDir
await shell "cp -R #{sourceDir} #{targetDir}"
await zip (resolve deployDir, "primary"), "lib", "#{type}.zip"
await shell "rm -rf lib", "haiku9-deploy/primary"
applyDefaultPrimaryLambdas = (config) ->
if isEmpty config.environment.edge.primary
console.log "loading default static site lambdas"
await buildPrimaryLambdas config
config.environment.edge.primary =
viewerRequest:
runtime: "nodejs12.x"
src: resolve defaultDir, "primary", "viewer-request.zip"
handler: "lib/index.handler"
originRequest:
runtime: "nodejs12.x"
src: resolve "haiku9-deploy", "primary", "origin-request.zip"
handler: "lib/index.handler"
memorySize: 1600
originResponse:
runtime: "nodejs12.x"
src: resolve "haiku9-deploy", "primary", "origin-response.zip"
handler: "lib/index.handler"
memorySize: 1600
config
expandConfig = (config) ->
{name, env} = config
{hostnames, edge:{primary, secondary}} = config.environment
for key of primary
include primary[key],
name: "haiku9-#{name}-#{env}-primary-#{dashed key}"
type: dashed key
primary[key].src = resolve process.cwd(), primary[key].src
primary[key].handler ?= "index.handler"
primary[key].tracingConfig ?= "PassThrough"
if key in ["viewerRequest", "viewerResponse"]
include primary[key], memorySize: 128
primary[key].timeout ?= 5
else
primary[key].memorySize ?= 128
primary[key].timeout ?= 30
config.environment.edge.primary = primary
for key of secondary
include secondary[key],
name: "haiku9-#{name}-#{env}-secondary-#{dashed key}"
type: dashed key
secondary[key].src = resolve process.cwd(), secondary[key].src
secondary[key].handler ?= "index.handler"
secondary[key].tracingConfig ?= "PassThrough"
if key in ["viewerRequest", "viewerResponse"]
include secondary[key], memorySize: 128
secondary[key].timeout ?= 5
else
secondary[key].memorySize ?= 128
secondary[key].timeout ?= 30
config.environment.edge.secondary = secondary
config.environment.edge.src = "lambdas-#{hostnames[0]}"
config.environment.edge.role = "haiku9-#{name}-#{env}-edge-lambdas"
config.environment.edge.originAccess = "haiku9-#{name}-#{env}"
config
checkForZipFlag = (config) ->
for _, lambda of config.environment.edge.primary when lambda.zip == true
await compressLambda lambda
lambda.src = resolve deployDir, "primary", "#{lambda.type}.zip"
config
go = flow [
cleanDirectory
startEdgeConfig
applySecondaryLambdas
applyDefaultPrimaryLambdas
expandConfig
checkForZipFlag
]
export default go
| 213027 | import {flow} from "panda-garden"
import {resolve, parse, relative} from "path"
import {resolve as resolveURL} from "url"
import {isEmpty, include, dashed, clone} from "panda-parchment"
import {read, rm, rmr, mkdir, mkdirp, glob, write} from "panda-quill"
import PandaTemplate from "panda-template"
import {shell} from "../../utils"
import {zip, gzip, brotli, md5} from "../../helpers"
T = new PandaTemplate()
defaultDir = resolve __dirname, "..", "..", "..", "..", "..",
"files", "default-lambdas"
deployDir = resolve process.cwd(), "haiku9-deploy"
cleanDirectory = (config) ->
console.log "cleaning Haiku deploy directory"
await rmr "haiku9-deploy"
await mkdir "0777", "haiku9-deploy"
config
startEdgeConfig = (config) ->
config.environment.edge ?= {}
config.environment.edge.primary = clone config.environment.edge
config
buildSecondaryLambda = (config) ->
{hostnames} = config.environment
sourceDir = resolve defaultDir, "secondary", "origin-request", "lib"
targetDir = resolve deployDir, "secondary"
await mkdirp "0777", targetDir
await shell "cp -R #{sourceDir} #{targetDir}"
path = resolve targetDir, "lib", "environment.hbs"
template = await read path
await rm path
url = "https://#{hostnames[0]}"
file = T.render template, {url}
await write (resolve targetDir, "lib", "environment.js"), file
await zip targetDir, "lib", "origin-request.zip"
await shell "rm -rf lib", "haiku9-deploy/secondary"
applySecondaryLambdas = (config) ->
{hostnames} = config.environment
if hostnames.length > 1
console.log "loading secondary hostname redirect lambdas."
await buildSecondaryLambda config
config.environment.edge.secondary =
originRequest:
runtime: "nodejs12.x"
src: resolve "haiku9-deploy", "secondary", "origin-request.zip"
handler: "lib/index.handler"
config
buildPrimaryLambdas = (config) ->
unless config.source?
throw new Error "The default origin-request and origin-response edge lambdas require source to be specified as your assets directory."
unless config.site?.index? && config.site?.error
throw new Error "The default origin-request and origin-response edge lambdas require site.index and site.error to be specified from an assets directory."
# Origin Requst Lambda
source = config.source
indexKey = config.site.index
indexFile = await read (resolve source, indexKey), "buffer"
indexFileGzip = await gzip indexFile
indexFileBrotli = await brotli indexFile
sourceDir = resolve defaultDir, "primary", "origin-request", "lib"
targetDir = resolve deployDir, "primary"
await mkdirp "0777", targetDir
await shell "cp -R #{sourceDir} #{targetDir}"
path = resolve targetDir, "lib", "index-files"
await mkdir "0777", path
await write (resolve path, "identity"), indexFile
await write (resolve path, "gzip"), indexFileGzip
await write (resolve path, "brotli"), indexFileBrotli
await zip targetDir, "lib", "origin-request.zip"
await shell "rm -rf lib", "haiku9-deploy/primary"
# Origin Response Lambda
source = config.source
errorKey = config.site.error
errorFile = await read (resolve source, errorKey), "buffer"
errorFileGzip = await gzip errorFile
errorFileBrotli = await brotli errorFile
sourceDir = resolve defaultDir, "primary", "origin-response", "lib"
targetDir = resolve deployDir, "primary"
await mkdirp "0777", targetDir
await shell "cp -R #{sourceDir} #{targetDir}"
path = resolve targetDir, "lib", "error-files"
await mkdir "0777", path
await write (resolve path, "identity"), errorFile
await write (resolve path, "gzip"), errorFileGzip
await write (resolve path, "brotli"), errorFileBrotli
await zip targetDir, "lib", "origin-response.zip"
await shell "rm -rf lib", "haiku9-deploy/primary"
compressLambda = (lambda) ->
{type, src} = lambda
# Origin Requst Lambda
sourceDir = resolve src
targetDir = resolve deployDir, "primary", "lib"
await mkdirp "0777", targetDir
await shell "cp -R #{sourceDir} #{targetDir}"
await zip (resolve deployDir, "primary"), "lib", "#{type}.zip"
await shell "rm -rf lib", "haiku9-deploy/primary"
applyDefaultPrimaryLambdas = (config) ->
if isEmpty config.environment.edge.primary
console.log "loading default static site lambdas"
await buildPrimaryLambdas config
config.environment.edge.primary =
viewerRequest:
runtime: "nodejs12.x"
src: resolve defaultDir, "primary", "viewer-request.zip"
handler: "lib/index.handler"
originRequest:
runtime: "nodejs12.x"
src: resolve "haiku9-deploy", "primary", "origin-request.zip"
handler: "lib/index.handler"
memorySize: 1600
originResponse:
runtime: "nodejs12.x"
src: resolve "haiku9-deploy", "primary", "origin-response.zip"
handler: "lib/index.handler"
memorySize: 1600
config
expandConfig = (config) ->
{name, env} = config
{hostnames, edge:{primary, secondary}} = config.environment
for key of primary
include primary[key],
name: "haiku9-#{name}-#{env}-primary-#{dashed key}"
type: dashed key
primary[key].src = resolve process.cwd(), primary[key].src
primary[key].handler ?= "index.handler"
primary[key].tracingConfig ?= "PassThrough"
if key in ["viewerRequest", "viewerResponse"]
include primary[key], memorySize: 128
primary[key].timeout ?= 5
else
primary[key].memorySize ?= 128
primary[key].timeout ?= 30
config.environment.edge.primary = primary
for key of secondary
include secondary[key],
name: "haiku9-#{name}-#{env}-secondary-#{dashed key}"
type: dashed key
secondary[key].src = resolve process.cwd(), secondary[key].src
secondary[key].handler ?= "index.handler"
secondary[key].tracingConfig ?= "PassThrough"
if key in ["<KEY>Request", "viewer<KEY>"]
include secondary[key], memorySize: 128
secondary[key].timeout ?= 5
else
secondary[key].memorySize ?= 128
secondary[key].timeout ?= 30
config.environment.edge.secondary = secondary
config.environment.edge.src = "lambdas-#{hostnames[0]}"
config.environment.edge.role = "haiku9-#{name}-#{env}-edge-lambdas"
config.environment.edge.originAccess = "haiku9-#{name}-#{env}"
config
checkForZipFlag = (config) ->
for _, lambda of config.environment.edge.primary when lambda.zip == true
await compressLambda lambda
lambda.src = resolve deployDir, "primary", "#{lambda.type}.zip"
config
go = flow [
cleanDirectory
startEdgeConfig
applySecondaryLambdas
applyDefaultPrimaryLambdas
expandConfig
checkForZipFlag
]
export default go
| true | import {flow} from "panda-garden"
import {resolve, parse, relative} from "path"
import {resolve as resolveURL} from "url"
import {isEmpty, include, dashed, clone} from "panda-parchment"
import {read, rm, rmr, mkdir, mkdirp, glob, write} from "panda-quill"
import PandaTemplate from "panda-template"
import {shell} from "../../utils"
import {zip, gzip, brotli, md5} from "../../helpers"
T = new PandaTemplate()
defaultDir = resolve __dirname, "..", "..", "..", "..", "..",
"files", "default-lambdas"
deployDir = resolve process.cwd(), "haiku9-deploy"
cleanDirectory = (config) ->
console.log "cleaning Haiku deploy directory"
await rmr "haiku9-deploy"
await mkdir "0777", "haiku9-deploy"
config
startEdgeConfig = (config) ->
config.environment.edge ?= {}
config.environment.edge.primary = clone config.environment.edge
config
buildSecondaryLambda = (config) ->
{hostnames} = config.environment
sourceDir = resolve defaultDir, "secondary", "origin-request", "lib"
targetDir = resolve deployDir, "secondary"
await mkdirp "0777", targetDir
await shell "cp -R #{sourceDir} #{targetDir}"
path = resolve targetDir, "lib", "environment.hbs"
template = await read path
await rm path
url = "https://#{hostnames[0]}"
file = T.render template, {url}
await write (resolve targetDir, "lib", "environment.js"), file
await zip targetDir, "lib", "origin-request.zip"
await shell "rm -rf lib", "haiku9-deploy/secondary"
applySecondaryLambdas = (config) ->
{hostnames} = config.environment
if hostnames.length > 1
console.log "loading secondary hostname redirect lambdas."
await buildSecondaryLambda config
config.environment.edge.secondary =
originRequest:
runtime: "nodejs12.x"
src: resolve "haiku9-deploy", "secondary", "origin-request.zip"
handler: "lib/index.handler"
config
buildPrimaryLambdas = (config) ->
unless config.source?
throw new Error "The default origin-request and origin-response edge lambdas require source to be specified as your assets directory."
unless config.site?.index? && config.site?.error
throw new Error "The default origin-request and origin-response edge lambdas require site.index and site.error to be specified from an assets directory."
# Origin Requst Lambda
source = config.source
indexKey = config.site.index
indexFile = await read (resolve source, indexKey), "buffer"
indexFileGzip = await gzip indexFile
indexFileBrotli = await brotli indexFile
sourceDir = resolve defaultDir, "primary", "origin-request", "lib"
targetDir = resolve deployDir, "primary"
await mkdirp "0777", targetDir
await shell "cp -R #{sourceDir} #{targetDir}"
path = resolve targetDir, "lib", "index-files"
await mkdir "0777", path
await write (resolve path, "identity"), indexFile
await write (resolve path, "gzip"), indexFileGzip
await write (resolve path, "brotli"), indexFileBrotli
await zip targetDir, "lib", "origin-request.zip"
await shell "rm -rf lib", "haiku9-deploy/primary"
# Origin Response Lambda
source = config.source
errorKey = config.site.error
errorFile = await read (resolve source, errorKey), "buffer"
errorFileGzip = await gzip errorFile
errorFileBrotli = await brotli errorFile
sourceDir = resolve defaultDir, "primary", "origin-response", "lib"
targetDir = resolve deployDir, "primary"
await mkdirp "0777", targetDir
await shell "cp -R #{sourceDir} #{targetDir}"
path = resolve targetDir, "lib", "error-files"
await mkdir "0777", path
await write (resolve path, "identity"), errorFile
await write (resolve path, "gzip"), errorFileGzip
await write (resolve path, "brotli"), errorFileBrotli
await zip targetDir, "lib", "origin-response.zip"
await shell "rm -rf lib", "haiku9-deploy/primary"
compressLambda = (lambda) ->
{type, src} = lambda
# Origin Requst Lambda
sourceDir = resolve src
targetDir = resolve deployDir, "primary", "lib"
await mkdirp "0777", targetDir
await shell "cp -R #{sourceDir} #{targetDir}"
await zip (resolve deployDir, "primary"), "lib", "#{type}.zip"
await shell "rm -rf lib", "haiku9-deploy/primary"
applyDefaultPrimaryLambdas = (config) ->
if isEmpty config.environment.edge.primary
console.log "loading default static site lambdas"
await buildPrimaryLambdas config
config.environment.edge.primary =
viewerRequest:
runtime: "nodejs12.x"
src: resolve defaultDir, "primary", "viewer-request.zip"
handler: "lib/index.handler"
originRequest:
runtime: "nodejs12.x"
src: resolve "haiku9-deploy", "primary", "origin-request.zip"
handler: "lib/index.handler"
memorySize: 1600
originResponse:
runtime: "nodejs12.x"
src: resolve "haiku9-deploy", "primary", "origin-response.zip"
handler: "lib/index.handler"
memorySize: 1600
config
expandConfig = (config) ->
{name, env} = config
{hostnames, edge:{primary, secondary}} = config.environment
for key of primary
include primary[key],
name: "haiku9-#{name}-#{env}-primary-#{dashed key}"
type: dashed key
primary[key].src = resolve process.cwd(), primary[key].src
primary[key].handler ?= "index.handler"
primary[key].tracingConfig ?= "PassThrough"
if key in ["viewerRequest", "viewerResponse"]
include primary[key], memorySize: 128
primary[key].timeout ?= 5
else
primary[key].memorySize ?= 128
primary[key].timeout ?= 30
config.environment.edge.primary = primary
for key of secondary
include secondary[key],
name: "haiku9-#{name}-#{env}-secondary-#{dashed key}"
type: dashed key
secondary[key].src = resolve process.cwd(), secondary[key].src
secondary[key].handler ?= "index.handler"
secondary[key].tracingConfig ?= "PassThrough"
if key in ["PI:KEY:<KEY>END_PIRequest", "viewerPI:KEY:<KEY>END_PI"]
include secondary[key], memorySize: 128
secondary[key].timeout ?= 5
else
secondary[key].memorySize ?= 128
secondary[key].timeout ?= 30
config.environment.edge.secondary = secondary
config.environment.edge.src = "lambdas-#{hostnames[0]}"
config.environment.edge.role = "haiku9-#{name}-#{env}-edge-lambdas"
config.environment.edge.originAccess = "haiku9-#{name}-#{env}"
config
checkForZipFlag = (config) ->
for _, lambda of config.environment.edge.primary when lambda.zip == true
await compressLambda lambda
lambda.src = resolve deployDir, "primary", "#{lambda.type}.zip"
config
go = flow [
cleanDirectory
startEdgeConfig
applySecondaryLambdas
applyDefaultPrimaryLambdas
expandConfig
checkForZipFlag
]
export default go
|
[
{
"context": "#########\n#\n# Resume view of solution\n# Created by Markus on 15/11/2015.\n#\n################################",
"end": 94,
"score": 0.9996324777603149,
"start": 88,
"tag": "NAME",
"value": "Markus"
}
] | client/views/portfolio/portfolio.coffee | MooqitaSFH/worklearn | 0 | ##############################################
#
# Resume view of solution
# Created by Markus on 15/11/2015.
#
##############################################
##########################################################
# import
##########################################################
##########################################################
import { FlowRouter } from 'meteor/ostrio:flow-router-extra'
##############################################
# resume list
##############################################
##############################################
Template.portfolio.onCreated () ->
self = this
Meteor.call 'get_quiz_scores',
(err, res) ->
Session.set('quiz_scores', res)
self.autorun () ->
s_id = FlowRouter.getParam("user_id")
if !s_id
s_id = Meteor.userId()
self.subscribe "user_resumes", s_id
##############################################
Template.portfolio.helpers
current_resume: () ->
res = UserResumes.findOne()
return res
##############################################
# resume solution
##############################################
##############################################
Template.portfolio_solution.onCreated () ->
this.reviews_visible = new ReactiveVar(false)
##############################################
Template.portfolio_solution.helpers
average_rating: () ->
if this.average
return this.average
return "-/-"
reviews_visible: () ->
return Template.instance().reviews_visible.get()
##############################################
Template.portfolio_solution.events
"click #show_reviews": () ->
rv = Template.instance().reviews_visible
rv.set !rv.get()
##############################################
# portfolio review
##############################################
##############################################
Template.portfolio_review.helpers
average_rating: () ->
if this.rating
return this.rating
return "-/-"
##############################################
Template.portfolio_review.helpers
portfolio_url: () ->
return ""#get_response_url(this.owner_id)
Template.portfolio_basic.helpers
quiz_scores: () ->
return Session.get('quiz_scores')
| 20846 | ##############################################
#
# Resume view of solution
# Created by <NAME> on 15/11/2015.
#
##############################################
##########################################################
# import
##########################################################
##########################################################
import { FlowRouter } from 'meteor/ostrio:flow-router-extra'
##############################################
# resume list
##############################################
##############################################
Template.portfolio.onCreated () ->
self = this
Meteor.call 'get_quiz_scores',
(err, res) ->
Session.set('quiz_scores', res)
self.autorun () ->
s_id = FlowRouter.getParam("user_id")
if !s_id
s_id = Meteor.userId()
self.subscribe "user_resumes", s_id
##############################################
Template.portfolio.helpers
current_resume: () ->
res = UserResumes.findOne()
return res
##############################################
# resume solution
##############################################
##############################################
Template.portfolio_solution.onCreated () ->
this.reviews_visible = new ReactiveVar(false)
##############################################
Template.portfolio_solution.helpers
average_rating: () ->
if this.average
return this.average
return "-/-"
reviews_visible: () ->
return Template.instance().reviews_visible.get()
##############################################
Template.portfolio_solution.events
"click #show_reviews": () ->
rv = Template.instance().reviews_visible
rv.set !rv.get()
##############################################
# portfolio review
##############################################
##############################################
Template.portfolio_review.helpers
average_rating: () ->
if this.rating
return this.rating
return "-/-"
##############################################
Template.portfolio_review.helpers
portfolio_url: () ->
return ""#get_response_url(this.owner_id)
Template.portfolio_basic.helpers
quiz_scores: () ->
return Session.get('quiz_scores')
| true | ##############################################
#
# Resume view of solution
# Created by PI:NAME:<NAME>END_PI on 15/11/2015.
#
##############################################
##########################################################
# import
##########################################################
##########################################################
import { FlowRouter } from 'meteor/ostrio:flow-router-extra'
##############################################
# resume list
##############################################
##############################################
Template.portfolio.onCreated () ->
self = this
Meteor.call 'get_quiz_scores',
(err, res) ->
Session.set('quiz_scores', res)
self.autorun () ->
s_id = FlowRouter.getParam("user_id")
if !s_id
s_id = Meteor.userId()
self.subscribe "user_resumes", s_id
##############################################
Template.portfolio.helpers
current_resume: () ->
res = UserResumes.findOne()
return res
##############################################
# resume solution
##############################################
##############################################
Template.portfolio_solution.onCreated () ->
this.reviews_visible = new ReactiveVar(false)
##############################################
Template.portfolio_solution.helpers
average_rating: () ->
if this.average
return this.average
return "-/-"
reviews_visible: () ->
return Template.instance().reviews_visible.get()
##############################################
Template.portfolio_solution.events
"click #show_reviews": () ->
rv = Template.instance().reviews_visible
rv.set !rv.get()
##############################################
# portfolio review
##############################################
##############################################
Template.portfolio_review.helpers
average_rating: () ->
if this.rating
return this.rating
return "-/-"
##############################################
Template.portfolio_review.helpers
portfolio_url: () ->
return ""#get_response_url(this.owner_id)
Template.portfolio_basic.helpers
quiz_scores: () ->
return Session.get('quiz_scores')
|
[
{
"context": "# parsing Ruby code\n#\n# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# L",
"end": 57,
"score": 0.9998731017112732,
"start": 43,
"tag": "NAME",
"value": "JeongHoon Byun"
},
{
"context": "y code\n#\n# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# Licensed under ",
"end": 71,
"score": 0.9569353461265564,
"start": 63,
"tag": "USERNAME",
"value": "Outsider"
}
] | src/parser/ruby-parser.coffee | uppalapatisujitha/CodingConventionofCommitHistory | 421 | # parsing Ruby code
#
# Copyright (c) 2013 JeongHoon Byun aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
helpers = require '../helpers'
_ = require 'underscore'
rubyParser = module.exports =
lang: 'rb'
parse: (line, convention, commitUrl) ->
convention = this.indent line, convention, commitUrl
convention = this.linelength line, convention, commitUrl
convention = this.whitespace line, convention, commitUrl
convention = this.asignDefaultValue line, convention, commitUrl
convention = this.numericLiteral line, convention, commitUrl
convention = this.defNoArgs line, convention, commitUrl
convention = this.defArgs line, convention, commitUrl
indent: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.indent =
title: "Space vs. Tab"
column: [
{
key: "tab", display: "Tab",
code: """
def foo(test)
# use tab for indentation
Thread.new do |blockvar|
# use tab for indentation
ABC::DEF.reverse(:a_symbol, :'a symbol', :<=>, 'test' + test)
end.join
end
"""
}
{
key: "space", display: "Space",
code: """
def foo(test)
Thread.new do |blockvar|
ABC::DEF.reverse(:a_symbol, :'a symbol', :<=>, 'test' + test)
end.join
end
"""
}
]
tab: 0
space: 0
commits: []
) unless convention.indent
tab = /^\t+.*/
space = /^\s+.*/
convention.indent.tab = convention.indent.tab + 1 if tab.test line
convention.indent.space = convention.indent.space + 1 if space.test line
convention.indent.commits.push commitUrl if tab.test(line) or space.test(line)
convention.indent.commits = _.uniq convention.indent.commits
convention
linelength: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.linelength =
title: "Line length is over 80 characters?"
column: [
{
key: "char80", display: "Line length is within 80 characters.",
code: "# width is within 80 characters"
}
{
key: "char120", display: "Line length is within 120 characters",
code: "# width is within 120 characters"
}
{
key: "char150", display: "Line length is within 150 characters",
code: "# width is within 150 characters"
}
]
char80: 0
char120: 0
char150: 0
commits: []
) unless convention.linelength
width = line.length
tabcount = line.split('\t').length - 1
# assume tab size is 4 space
width += tabcount * 3
if width < 80
convention.linelength.char80 = convention.linelength.char80 + 1
else if width < 120
convention.linelength.char120 = convention.linelength.char120 + 1
else
convention.linelength.char150 = convention.linelength.char150 + 1
convention.linelength.commits.push commitUrl
convention.linelength.commits = _.uniq convention.linelength.commits
convention
whitespace: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.whitespace =
title: "Whitespace around operators, colons, { and }, after commas, semicolons"
column: [
{
key: "spaces", display: "Using spaces",
code: """
sum = 1 + 2
a, b = 1, 2
1 > 2 ? true : false; puts 'Hi'
[1, 2, 3].each { |e| puts e }
"""
}
{
key: "nospace", display: "Using no space",
code: """
sum = 1 +2
a,b = 1, 2
1>2 ? true : false;puts 'Hi'
[1, 2, 3].each {|e| puts e}
"""
}
]
spaces: 0
nospace: 0
commits: []
) unless convention.whitespace
placeholder = "CONVENTION-PLACEHOLDER"
operators = '[+=*/%>?:{}]'
symbols = '[,;]'
spaces = (line) ->
temp = line.replace /'.*?'/g, placeholder
temp = temp.replace /".*?"/g, placeholder
!///\w+#{operators}///.test(temp) and !///#{operators}\w+///.test(temp) and
!///#{symbols}\w+///.test(temp) and
(///\s+#{operators}\s+///.test temp or ///#{symbols}\s+///.test(temp))
nospace = (line) ->
temp = line.replace /'.*?'/g, placeholder
temp = temp.replace /".*?"/g, placeholder
///\w+#{operators}///.test(temp) or ///#{operators}\w+///.test(temp) or
///#{symbols}\w+///.test(temp)
convention.whitespace.spaces = convention.whitespace.spaces + 1 if spaces line
convention.whitespace.nospace = convention.whitespace.nospace + 1 if nospace line
convention.whitespace.commits.push commitUrl if spaces(line) or nospace(line)
convention.whitespace.commits = _.uniq convention.whitespace .commits
convention
asignDefaultValue: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.asignDefaultValue =
title: "How to write assigning default values to method parameters"
column: [
{
key: "space", display: "Use spaces",
code: """
def some_method(arg1 = :default, arg2 = nil, arg3 = [])
# do something...
end
"""
}
{
key: "nospace", display: "Use spaces before = or after =",
code: """
def some_method(arg1=:default, arg2=nil, arg3=[])
# do something...
end
"""
}
]
space: 0
nospace: 0
commits: []
) unless convention.asignDefaultValue
space = /^[\s\t]*def.*\((\s*\w+\s+=\s+[\[\]:\w,]+\s*)+\)/
nospace = /^[\s\t]*def.*\((\s*\w+=[\[\]:\w,]+\s*)+\)/
convention.asignDefaultValue.space = convention.asignDefaultValue.space + 1 if space.test line
convention.asignDefaultValue.nospace = convention.asignDefaultValue.nospace + 1 if nospace.test line
convention.asignDefaultValue.commits.push commitUrl if space.test(line) or nospace.test(line)
convention.asignDefaultValue.commits = _.uniq convention.asignDefaultValue.commits
convention
numericLiteral: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.numericLiteral =
title: "How to write large numeric literals"
column: [
{
key: "underscore", display: "Write with underscore",
code: """
num = 1_000_000
"""
}
{
key: "nounderscore", display: "Write without underscore",
code: """
num = 1000000
"""
}
]
underscore: 0
nounderscore: 0
commits: []
) unless convention.numericLiteral
placeholder = "CONVENTION-PLACEHOLDER"
underscore = (line) ->
temp = line.replace /'.*?'/g, placeholder
temp = temp.replace /".*?"/g, placeholder
/[0-9]+(_[0-9]{3,})+/.test(temp)
nounderscore = (line) ->
temp = line.replace /'.*?'/g, placeholder
temp = temp.replace /".*?"/g, placeholder
/[0-9]{4,}/.test(temp)
convention.numericLiteral.underscore = convention.numericLiteral.underscore + 1 if underscore line
convention.numericLiteral.nounderscore = convention.numericLiteral.nounderscore + 1 if nounderscore line
convention.numericLiteral.commits.push commitUrl if underscore(line) or nounderscore(line)
convention.numericLiteral.commits = _.uniq convention.numericLiteral.commits
convention
defNoArgs: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.defNoArgs =
title: "Omit parentheses when there aren't any arguments"
column: [
{
key: "omit", display: "Omit",
code: """
def some_method
# do something...
end
"""
}
{
key: "use", display: "Use the parentheses",
code: """
def some_method()
# do something...
end
"""
}
]
omit: 0
use: 0
commits: []
) unless convention.defNoArgs
omit = /^[\s\t]*def\s+\w+\s*[^(),\w]*(#+.*)*$/
use = /^[\s\t]*def\s+\w+\s*\(\s*\)/
convention.defNoArgs.omit = convention.defNoArgs.omit + 1 if omit.test line
convention.defNoArgs.use = convention.defNoArgs.use + 1 if use.test line
convention.defNoArgs.commits.push commitUrl if omit.test(line) or use.test(line)
convention.defNoArgs.commits = _.uniq convention.defNoArgs.commits
convention
defArgs: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.defArgs =
title: "Parentheses around arguments in def"
column: [
{
key: "omit", display: "Omit",
code: """
def some_method arg1, arg2
# do something...
end
"""
}
{
key: "use", display: "Use the parentheses",
code: """
def some_method(arg1, arg2)
# do something...
end
"""
}
]
omit: 0
use: 0
commits: []
) unless convention.defArgs
omit = /^[\s\t]*def\s+\w+\s+\w[^()]*(#+.*)*$/
use = /^[\s\t]*def\s+\w+\s*\((\s*[\w=]+,?)+\s*/
convention.defArgs.omit = convention.defArgs.omit + 1 if omit.test line
convention.defArgs.use = convention.defArgs.use + 1 if use.test line
convention.defArgs.commits.push commitUrl if omit.test(line) or use.test(line)
convention.defArgs.commits = _.uniq convention.defArgs.commits
convention
| 236 | # parsing Ruby code
#
# Copyright (c) 2013 <NAME> aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
helpers = require '../helpers'
_ = require 'underscore'
rubyParser = module.exports =
lang: 'rb'
parse: (line, convention, commitUrl) ->
convention = this.indent line, convention, commitUrl
convention = this.linelength line, convention, commitUrl
convention = this.whitespace line, convention, commitUrl
convention = this.asignDefaultValue line, convention, commitUrl
convention = this.numericLiteral line, convention, commitUrl
convention = this.defNoArgs line, convention, commitUrl
convention = this.defArgs line, convention, commitUrl
indent: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.indent =
title: "Space vs. Tab"
column: [
{
key: "tab", display: "Tab",
code: """
def foo(test)
# use tab for indentation
Thread.new do |blockvar|
# use tab for indentation
ABC::DEF.reverse(:a_symbol, :'a symbol', :<=>, 'test' + test)
end.join
end
"""
}
{
key: "space", display: "Space",
code: """
def foo(test)
Thread.new do |blockvar|
ABC::DEF.reverse(:a_symbol, :'a symbol', :<=>, 'test' + test)
end.join
end
"""
}
]
tab: 0
space: 0
commits: []
) unless convention.indent
tab = /^\t+.*/
space = /^\s+.*/
convention.indent.tab = convention.indent.tab + 1 if tab.test line
convention.indent.space = convention.indent.space + 1 if space.test line
convention.indent.commits.push commitUrl if tab.test(line) or space.test(line)
convention.indent.commits = _.uniq convention.indent.commits
convention
linelength: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.linelength =
title: "Line length is over 80 characters?"
column: [
{
key: "char80", display: "Line length is within 80 characters.",
code: "# width is within 80 characters"
}
{
key: "char120", display: "Line length is within 120 characters",
code: "# width is within 120 characters"
}
{
key: "char150", display: "Line length is within 150 characters",
code: "# width is within 150 characters"
}
]
char80: 0
char120: 0
char150: 0
commits: []
) unless convention.linelength
width = line.length
tabcount = line.split('\t').length - 1
# assume tab size is 4 space
width += tabcount * 3
if width < 80
convention.linelength.char80 = convention.linelength.char80 + 1
else if width < 120
convention.linelength.char120 = convention.linelength.char120 + 1
else
convention.linelength.char150 = convention.linelength.char150 + 1
convention.linelength.commits.push commitUrl
convention.linelength.commits = _.uniq convention.linelength.commits
convention
whitespace: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.whitespace =
title: "Whitespace around operators, colons, { and }, after commas, semicolons"
column: [
{
key: "spaces", display: "Using spaces",
code: """
sum = 1 + 2
a, b = 1, 2
1 > 2 ? true : false; puts 'Hi'
[1, 2, 3].each { |e| puts e }
"""
}
{
key: "nospace", display: "Using no space",
code: """
sum = 1 +2
a,b = 1, 2
1>2 ? true : false;puts 'Hi'
[1, 2, 3].each {|e| puts e}
"""
}
]
spaces: 0
nospace: 0
commits: []
) unless convention.whitespace
placeholder = "CONVENTION-PLACEHOLDER"
operators = '[+=*/%>?:{}]'
symbols = '[,;]'
spaces = (line) ->
temp = line.replace /'.*?'/g, placeholder
temp = temp.replace /".*?"/g, placeholder
!///\w+#{operators}///.test(temp) and !///#{operators}\w+///.test(temp) and
!///#{symbols}\w+///.test(temp) and
(///\s+#{operators}\s+///.test temp or ///#{symbols}\s+///.test(temp))
nospace = (line) ->
temp = line.replace /'.*?'/g, placeholder
temp = temp.replace /".*?"/g, placeholder
///\w+#{operators}///.test(temp) or ///#{operators}\w+///.test(temp) or
///#{symbols}\w+///.test(temp)
convention.whitespace.spaces = convention.whitespace.spaces + 1 if spaces line
convention.whitespace.nospace = convention.whitespace.nospace + 1 if nospace line
convention.whitespace.commits.push commitUrl if spaces(line) or nospace(line)
convention.whitespace.commits = _.uniq convention.whitespace .commits
convention
asignDefaultValue: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.asignDefaultValue =
title: "How to write assigning default values to method parameters"
column: [
{
key: "space", display: "Use spaces",
code: """
def some_method(arg1 = :default, arg2 = nil, arg3 = [])
# do something...
end
"""
}
{
key: "nospace", display: "Use spaces before = or after =",
code: """
def some_method(arg1=:default, arg2=nil, arg3=[])
# do something...
end
"""
}
]
space: 0
nospace: 0
commits: []
) unless convention.asignDefaultValue
space = /^[\s\t]*def.*\((\s*\w+\s+=\s+[\[\]:\w,]+\s*)+\)/
nospace = /^[\s\t]*def.*\((\s*\w+=[\[\]:\w,]+\s*)+\)/
convention.asignDefaultValue.space = convention.asignDefaultValue.space + 1 if space.test line
convention.asignDefaultValue.nospace = convention.asignDefaultValue.nospace + 1 if nospace.test line
convention.asignDefaultValue.commits.push commitUrl if space.test(line) or nospace.test(line)
convention.asignDefaultValue.commits = _.uniq convention.asignDefaultValue.commits
convention
numericLiteral: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.numericLiteral =
title: "How to write large numeric literals"
column: [
{
key: "underscore", display: "Write with underscore",
code: """
num = 1_000_000
"""
}
{
key: "nounderscore", display: "Write without underscore",
code: """
num = 1000000
"""
}
]
underscore: 0
nounderscore: 0
commits: []
) unless convention.numericLiteral
placeholder = "CONVENTION-PLACEHOLDER"
underscore = (line) ->
temp = line.replace /'.*?'/g, placeholder
temp = temp.replace /".*?"/g, placeholder
/[0-9]+(_[0-9]{3,})+/.test(temp)
nounderscore = (line) ->
temp = line.replace /'.*?'/g, placeholder
temp = temp.replace /".*?"/g, placeholder
/[0-9]{4,}/.test(temp)
convention.numericLiteral.underscore = convention.numericLiteral.underscore + 1 if underscore line
convention.numericLiteral.nounderscore = convention.numericLiteral.nounderscore + 1 if nounderscore line
convention.numericLiteral.commits.push commitUrl if underscore(line) or nounderscore(line)
convention.numericLiteral.commits = _.uniq convention.numericLiteral.commits
convention
defNoArgs: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.defNoArgs =
title: "Omit parentheses when there aren't any arguments"
column: [
{
key: "omit", display: "Omit",
code: """
def some_method
# do something...
end
"""
}
{
key: "use", display: "Use the parentheses",
code: """
def some_method()
# do something...
end
"""
}
]
omit: 0
use: 0
commits: []
) unless convention.defNoArgs
omit = /^[\s\t]*def\s+\w+\s*[^(),\w]*(#+.*)*$/
use = /^[\s\t]*def\s+\w+\s*\(\s*\)/
convention.defNoArgs.omit = convention.defNoArgs.omit + 1 if omit.test line
convention.defNoArgs.use = convention.defNoArgs.use + 1 if use.test line
convention.defNoArgs.commits.push commitUrl if omit.test(line) or use.test(line)
convention.defNoArgs.commits = _.uniq convention.defNoArgs.commits
convention
defArgs: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.defArgs =
title: "Parentheses around arguments in def"
column: [
{
key: "omit", display: "Omit",
code: """
def some_method arg1, arg2
# do something...
end
"""
}
{
key: "use", display: "Use the parentheses",
code: """
def some_method(arg1, arg2)
# do something...
end
"""
}
]
omit: 0
use: 0
commits: []
) unless convention.defArgs
omit = /^[\s\t]*def\s+\w+\s+\w[^()]*(#+.*)*$/
use = /^[\s\t]*def\s+\w+\s*\((\s*[\w=]+,?)+\s*/
convention.defArgs.omit = convention.defArgs.omit + 1 if omit.test line
convention.defArgs.use = convention.defArgs.use + 1 if use.test line
convention.defArgs.commits.push commitUrl if omit.test(line) or use.test(line)
convention.defArgs.commits = _.uniq convention.defArgs.commits
convention
| true | # parsing Ruby code
#
# Copyright (c) 2013 PI:NAME:<NAME>END_PI aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
helpers = require '../helpers'
_ = require 'underscore'
rubyParser = module.exports =
lang: 'rb'
parse: (line, convention, commitUrl) ->
convention = this.indent line, convention, commitUrl
convention = this.linelength line, convention, commitUrl
convention = this.whitespace line, convention, commitUrl
convention = this.asignDefaultValue line, convention, commitUrl
convention = this.numericLiteral line, convention, commitUrl
convention = this.defNoArgs line, convention, commitUrl
convention = this.defArgs line, convention, commitUrl
indent: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.indent =
title: "Space vs. Tab"
column: [
{
key: "tab", display: "Tab",
code: """
def foo(test)
# use tab for indentation
Thread.new do |blockvar|
# use tab for indentation
ABC::DEF.reverse(:a_symbol, :'a symbol', :<=>, 'test' + test)
end.join
end
"""
}
{
key: "space", display: "Space",
code: """
def foo(test)
Thread.new do |blockvar|
ABC::DEF.reverse(:a_symbol, :'a symbol', :<=>, 'test' + test)
end.join
end
"""
}
]
tab: 0
space: 0
commits: []
) unless convention.indent
tab = /^\t+.*/
space = /^\s+.*/
convention.indent.tab = convention.indent.tab + 1 if tab.test line
convention.indent.space = convention.indent.space + 1 if space.test line
convention.indent.commits.push commitUrl if tab.test(line) or space.test(line)
convention.indent.commits = _.uniq convention.indent.commits
convention
linelength: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.linelength =
title: "Line length is over 80 characters?"
column: [
{
key: "char80", display: "Line length is within 80 characters.",
code: "# width is within 80 characters"
}
{
key: "char120", display: "Line length is within 120 characters",
code: "# width is within 120 characters"
}
{
key: "char150", display: "Line length is within 150 characters",
code: "# width is within 150 characters"
}
]
char80: 0
char120: 0
char150: 0
commits: []
) unless convention.linelength
width = line.length
tabcount = line.split('\t').length - 1
# assume tab size is 4 space
width += tabcount * 3
if width < 80
convention.linelength.char80 = convention.linelength.char80 + 1
else if width < 120
convention.linelength.char120 = convention.linelength.char120 + 1
else
convention.linelength.char150 = convention.linelength.char150 + 1
convention.linelength.commits.push commitUrl
convention.linelength.commits = _.uniq convention.linelength.commits
convention
whitespace: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.whitespace =
title: "Whitespace around operators, colons, { and }, after commas, semicolons"
column: [
{
key: "spaces", display: "Using spaces",
code: """
sum = 1 + 2
a, b = 1, 2
1 > 2 ? true : false; puts 'Hi'
[1, 2, 3].each { |e| puts e }
"""
}
{
key: "nospace", display: "Using no space",
code: """
sum = 1 +2
a,b = 1, 2
1>2 ? true : false;puts 'Hi'
[1, 2, 3].each {|e| puts e}
"""
}
]
spaces: 0
nospace: 0
commits: []
) unless convention.whitespace
placeholder = "CONVENTION-PLACEHOLDER"
operators = '[+=*/%>?:{}]'
symbols = '[,;]'
spaces = (line) ->
temp = line.replace /'.*?'/g, placeholder
temp = temp.replace /".*?"/g, placeholder
!///\w+#{operators}///.test(temp) and !///#{operators}\w+///.test(temp) and
!///#{symbols}\w+///.test(temp) and
(///\s+#{operators}\s+///.test temp or ///#{symbols}\s+///.test(temp))
nospace = (line) ->
temp = line.replace /'.*?'/g, placeholder
temp = temp.replace /".*?"/g, placeholder
///\w+#{operators}///.test(temp) or ///#{operators}\w+///.test(temp) or
///#{symbols}\w+///.test(temp)
convention.whitespace.spaces = convention.whitespace.spaces + 1 if spaces line
convention.whitespace.nospace = convention.whitespace.nospace + 1 if nospace line
convention.whitespace.commits.push commitUrl if spaces(line) or nospace(line)
convention.whitespace.commits = _.uniq convention.whitespace .commits
convention
asignDefaultValue: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.asignDefaultValue =
title: "How to write assigning default values to method parameters"
column: [
{
key: "space", display: "Use spaces",
code: """
def some_method(arg1 = :default, arg2 = nil, arg3 = [])
# do something...
end
"""
}
{
key: "nospace", display: "Use spaces before = or after =",
code: """
def some_method(arg1=:default, arg2=nil, arg3=[])
# do something...
end
"""
}
]
space: 0
nospace: 0
commits: []
) unless convention.asignDefaultValue
space = /^[\s\t]*def.*\((\s*\w+\s+=\s+[\[\]:\w,]+\s*)+\)/
nospace = /^[\s\t]*def.*\((\s*\w+=[\[\]:\w,]+\s*)+\)/
convention.asignDefaultValue.space = convention.asignDefaultValue.space + 1 if space.test line
convention.asignDefaultValue.nospace = convention.asignDefaultValue.nospace + 1 if nospace.test line
convention.asignDefaultValue.commits.push commitUrl if space.test(line) or nospace.test(line)
convention.asignDefaultValue.commits = _.uniq convention.asignDefaultValue.commits
convention
numericLiteral: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.numericLiteral =
title: "How to write large numeric literals"
column: [
{
key: "underscore", display: "Write with underscore",
code: """
num = 1_000_000
"""
}
{
key: "nounderscore", display: "Write without underscore",
code: """
num = 1000000
"""
}
]
underscore: 0
nounderscore: 0
commits: []
) unless convention.numericLiteral
placeholder = "CONVENTION-PLACEHOLDER"
underscore = (line) ->
temp = line.replace /'.*?'/g, placeholder
temp = temp.replace /".*?"/g, placeholder
/[0-9]+(_[0-9]{3,})+/.test(temp)
nounderscore = (line) ->
temp = line.replace /'.*?'/g, placeholder
temp = temp.replace /".*?"/g, placeholder
/[0-9]{4,}/.test(temp)
convention.numericLiteral.underscore = convention.numericLiteral.underscore + 1 if underscore line
convention.numericLiteral.nounderscore = convention.numericLiteral.nounderscore + 1 if nounderscore line
convention.numericLiteral.commits.push commitUrl if underscore(line) or nounderscore(line)
convention.numericLiteral.commits = _.uniq convention.numericLiteral.commits
convention
defNoArgs: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.defNoArgs =
title: "Omit parentheses when there aren't any arguments"
column: [
{
key: "omit", display: "Omit",
code: """
def some_method
# do something...
end
"""
}
{
key: "use", display: "Use the parentheses",
code: """
def some_method()
# do something...
end
"""
}
]
omit: 0
use: 0
commits: []
) unless convention.defNoArgs
omit = /^[\s\t]*def\s+\w+\s*[^(),\w]*(#+.*)*$/
use = /^[\s\t]*def\s+\w+\s*\(\s*\)/
convention.defNoArgs.omit = convention.defNoArgs.omit + 1 if omit.test line
convention.defNoArgs.use = convention.defNoArgs.use + 1 if use.test line
convention.defNoArgs.commits.push commitUrl if omit.test(line) or use.test(line)
convention.defNoArgs.commits = _.uniq convention.defNoArgs.commits
convention
defArgs: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.defArgs =
title: "Parentheses around arguments in def"
column: [
{
key: "omit", display: "Omit",
code: """
def some_method arg1, arg2
# do something...
end
"""
}
{
key: "use", display: "Use the parentheses",
code: """
def some_method(arg1, arg2)
# do something...
end
"""
}
]
omit: 0
use: 0
commits: []
) unless convention.defArgs
omit = /^[\s\t]*def\s+\w+\s+\w[^()]*(#+.*)*$/
use = /^[\s\t]*def\s+\w+\s*\((\s*[\w=]+,?)+\s*/
convention.defArgs.omit = convention.defArgs.omit + 1 if omit.test line
convention.defArgs.use = convention.defArgs.use + 1 if use.test line
convention.defArgs.commits.push commitUrl if omit.test(line) or use.test(line)
convention.defArgs.commits = _.uniq convention.defArgs.commits
convention
|
[
{
"context": "ormation, please see the LICENSE file\n\n@author Bryan Conrad <bkconrad@gmail.com>\n@copyright 2015 Bryan Conra",
"end": 181,
"score": 0.9998961687088013,
"start": 169,
"tag": "NAME",
"value": "Bryan Conrad"
},
{
"context": "e see the LICENSE file\n\n@author Bryan Conrad <bkconrad@gmail.com>\n@copyright 2015 Bryan Conrad\n@link https:",
"end": 201,
"score": 0.999926745891571,
"start": 183,
"tag": "EMAIL",
"value": "bkconrad@gmail.com"
},
{
"context": "Bryan Conrad <bkconrad@gmail.com>\n@copyright 2015 Bryan Conrad\n@link https://github.com/kaen/node-nested-o",
"end": 232,
"score": 0.9998966455459595,
"start": 220,
"tag": "NAME",
"value": "Bryan Conrad"
},
{
"context": "015 Bryan Conrad\n@link https://github.com/kaen/node-nested-object-mask\n@license http://choose",
"end": 268,
"score": 0.8256966471672058,
"start": 266,
"tag": "USERNAME",
"value": "en"
},
{
"context": "ples below in [this gist](https://gist.github.com/bkconrad/4a809a7f6076474e56d8)\n\n @example Nested masking\n",
"end": 693,
"score": 0.9977977871894836,
"start": 685,
"tag": "USERNAME",
"value": "bkconrad"
}
] | src/nested_object_mask.coffee | bkconrad/node-nested-object-mask | 1 | _ = require 'lodash'
###
kaen\recursive-object-mask
Licensed under the MIT license
For full copyright and license information, please see the LICENSE file
@author Bryan Conrad <bkconrad@gmail.com>
@copyright 2015 Bryan Conrad
@link https://github.com/kaen/node-nested-object-mask
@license http://choosealicense.com/licenses/MIT MIT License
###
###
@mixin Masker
@since 0.1.0
###
Masker =
###
The only function you'll ever need :)
See the examples below for details about options and general rules of
operation.
If you can not read coffeescript object literals, you can read the compiled
JS of the examples below in [this gist](https://gist.github.com/bkconrad/4a809a7f6076474e56d8)
@example Nested masking
object =
keepThisKey: 'some value'
subObject:
alsoKeepThisKey: 'will do'
dropThisKey: 'good bye :<'
mask =
keepThisKey: true
# mask within a mask -- maskception
subObject:
alsoKeepThisKey: true
dropThisKey: false
expected =
keepThisKey: 'some value'
subObject:
alsoKeepThisKey: 'will do'
@example Pruning
# You can also prune empty objects and arrays from the result. Simply pass
# `pruneEmpty: true` in the options hash:
object =
empty: { }
emptyWhenFiltered:
foo: 'bar'
notEmptyWhenFiltered:
keepMe: 'some value'
mask =
empty: true
emptyWhenFiltered:
doesNotExist: true
notEmptyWhenFiltered:
keepMe: true
expected =
notEmptyWhenFiltered:
keepMe: 'some value'
result = masker.mask object, mask, pruneEmpty: true
# Without pruning, the result of the above would retain the empty objects,
# and would instead look like:
empty: { }
emptyWhenFiltered: { }
notEmptyWhenFiltered:
keepMe: 'some value'
@example The '*' Key
# If you need to keep **all** "own" keys in an object, specify a `'*'` key
# in the mask, like so:
object =
thing1: { foo: 1, bar: 2 }
thing2: { foo: 2, baz: 2 }
mask =
"*": { foo: true }
expected =
thing1: { foo: 1 }
thing2: { foo: 2 }
assert.deepEqual result, expected
# Note that actual globbing is not currently supported, and that you will
# need to quote the key. Nesting `'*'` keys is also valid, like so:
mask =
'*': { '*': true }
@example Truthiness
# It is **highly recommended** that you construct your mask using only
# `true`, `false`, and objects when possible. When creating a mask by
# iterating over a domain object, make sure to set each value to a boolean
# for the least complications.
# If you can not create an ideal `true`/`false`-based mask, NOM will apply
# general JavaScript "truthiness" to your keys. You should at least be aware
# of some caveats (the empty string in particular):
object:
trueTrue: 'kept'
trueOne: 'kept'
trueString: 'kept'
trueObject: 'kept'
trueArray: 'kept'
trueRegex: 'kept'
falseFalse: 'dropped'
falseString: 'dropped'
falseNull: 'dropped'
falseZero: 'dropped'
falseNaN: 'dropped'
falseUndefined: 'dropped'
mask:
trueTrue: true
trueOne: 1
trueString: 'yes'
trueObject: {}
trueArray: []
trueRegex: /asdf/
falseFalse: false
falseString: ''
falseNull: null
falseZero: 0
falseNaN: NaN
falseUndefined: undefined
expected:
trueTrue: 'kept'
trueOne: 'kept'
trueString: 'kept'
trueObject: 'kept'
trueArray: 'kept'
trueRegex: 'kept'
@param {any} object The object to filter via `mask`
@param {any} mask The mask to filter `object` with
@param {object} options Options to use while masking
@option options [boolean] pruneEmpty When true, recursively prunes empty objects and arrays from the result
@return any
@since 0.1.0
###
mask: (object, mask, options) ->
options = options || { }
return undefined unless mask
return object unless _.isObject(object) or _.isArray(object)
# if the mask contains a key that is simply an asterisk, all of the
# object's "own" properties will be passed through. this is achieved by
# simply setting the original object as the "iteratee" rather than the
# mask
result = if _.isArray(object) then [] else {}
permitAll = _.has(mask, '*') or mask == true
iteratee = if permitAll then object else mask
for own k,v of iteratee
subMask = undefined
if _.has(mask, k)
subMask = mask[k]
else # if permitAll <-- this is always true here
if _.has(mask, '*')
subMask = mask['*']
else
subMask = { '*': true }
maskedSubObject = module.exports.mask(object[k], subMask, options)
shouldPruneValue = (options.pruneEmpty && _.isEmpty(maskedSubObject))
valueWasEmpty = object[k] == undefined
valueIsEmpty = maskedSubObject == undefined
unless shouldPruneValue or valueWasEmpty or valueIsEmpty
result[k] = maskedSubObject
result
module.exports = Masker
| 83503 | _ = require 'lodash'
###
kaen\recursive-object-mask
Licensed under the MIT license
For full copyright and license information, please see the LICENSE file
@author <NAME> <<EMAIL>>
@copyright 2015 <NAME>
@link https://github.com/kaen/node-nested-object-mask
@license http://choosealicense.com/licenses/MIT MIT License
###
###
@mixin Masker
@since 0.1.0
###
Masker =
###
The only function you'll ever need :)
See the examples below for details about options and general rules of
operation.
If you can not read coffeescript object literals, you can read the compiled
JS of the examples below in [this gist](https://gist.github.com/bkconrad/4a809a7f6076474e56d8)
@example Nested masking
object =
keepThisKey: 'some value'
subObject:
alsoKeepThisKey: 'will do'
dropThisKey: 'good bye :<'
mask =
keepThisKey: true
# mask within a mask -- maskception
subObject:
alsoKeepThisKey: true
dropThisKey: false
expected =
keepThisKey: 'some value'
subObject:
alsoKeepThisKey: 'will do'
@example Pruning
# You can also prune empty objects and arrays from the result. Simply pass
# `pruneEmpty: true` in the options hash:
object =
empty: { }
emptyWhenFiltered:
foo: 'bar'
notEmptyWhenFiltered:
keepMe: 'some value'
mask =
empty: true
emptyWhenFiltered:
doesNotExist: true
notEmptyWhenFiltered:
keepMe: true
expected =
notEmptyWhenFiltered:
keepMe: 'some value'
result = masker.mask object, mask, pruneEmpty: true
# Without pruning, the result of the above would retain the empty objects,
# and would instead look like:
empty: { }
emptyWhenFiltered: { }
notEmptyWhenFiltered:
keepMe: 'some value'
@example The '*' Key
# If you need to keep **all** "own" keys in an object, specify a `'*'` key
# in the mask, like so:
object =
thing1: { foo: 1, bar: 2 }
thing2: { foo: 2, baz: 2 }
mask =
"*": { foo: true }
expected =
thing1: { foo: 1 }
thing2: { foo: 2 }
assert.deepEqual result, expected
# Note that actual globbing is not currently supported, and that you will
# need to quote the key. Nesting `'*'` keys is also valid, like so:
mask =
'*': { '*': true }
@example Truthiness
# It is **highly recommended** that you construct your mask using only
# `true`, `false`, and objects when possible. When creating a mask by
# iterating over a domain object, make sure to set each value to a boolean
# for the least complications.
# If you can not create an ideal `true`/`false`-based mask, NOM will apply
# general JavaScript "truthiness" to your keys. You should at least be aware
# of some caveats (the empty string in particular):
object:
trueTrue: 'kept'
trueOne: 'kept'
trueString: 'kept'
trueObject: 'kept'
trueArray: 'kept'
trueRegex: 'kept'
falseFalse: 'dropped'
falseString: 'dropped'
falseNull: 'dropped'
falseZero: 'dropped'
falseNaN: 'dropped'
falseUndefined: 'dropped'
mask:
trueTrue: true
trueOne: 1
trueString: 'yes'
trueObject: {}
trueArray: []
trueRegex: /asdf/
falseFalse: false
falseString: ''
falseNull: null
falseZero: 0
falseNaN: NaN
falseUndefined: undefined
expected:
trueTrue: 'kept'
trueOne: 'kept'
trueString: 'kept'
trueObject: 'kept'
trueArray: 'kept'
trueRegex: 'kept'
@param {any} object The object to filter via `mask`
@param {any} mask The mask to filter `object` with
@param {object} options Options to use while masking
@option options [boolean] pruneEmpty When true, recursively prunes empty objects and arrays from the result
@return any
@since 0.1.0
###
mask: (object, mask, options) ->
options = options || { }
return undefined unless mask
return object unless _.isObject(object) or _.isArray(object)
# if the mask contains a key that is simply an asterisk, all of the
# object's "own" properties will be passed through. this is achieved by
# simply setting the original object as the "iteratee" rather than the
# mask
result = if _.isArray(object) then [] else {}
permitAll = _.has(mask, '*') or mask == true
iteratee = if permitAll then object else mask
for own k,v of iteratee
subMask = undefined
if _.has(mask, k)
subMask = mask[k]
else # if permitAll <-- this is always true here
if _.has(mask, '*')
subMask = mask['*']
else
subMask = { '*': true }
maskedSubObject = module.exports.mask(object[k], subMask, options)
shouldPruneValue = (options.pruneEmpty && _.isEmpty(maskedSubObject))
valueWasEmpty = object[k] == undefined
valueIsEmpty = maskedSubObject == undefined
unless shouldPruneValue or valueWasEmpty or valueIsEmpty
result[k] = maskedSubObject
result
module.exports = Masker
| true | _ = require 'lodash'
###
kaen\recursive-object-mask
Licensed under the MIT license
For full copyright and license information, please see the LICENSE file
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
@copyright 2015 PI:NAME:<NAME>END_PI
@link https://github.com/kaen/node-nested-object-mask
@license http://choosealicense.com/licenses/MIT MIT License
###
###
@mixin Masker
@since 0.1.0
###
Masker =
###
The only function you'll ever need :)
See the examples below for details about options and general rules of
operation.
If you can not read coffeescript object literals, you can read the compiled
JS of the examples below in [this gist](https://gist.github.com/bkconrad/4a809a7f6076474e56d8)
@example Nested masking
object =
keepThisKey: 'some value'
subObject:
alsoKeepThisKey: 'will do'
dropThisKey: 'good bye :<'
mask =
keepThisKey: true
# mask within a mask -- maskception
subObject:
alsoKeepThisKey: true
dropThisKey: false
expected =
keepThisKey: 'some value'
subObject:
alsoKeepThisKey: 'will do'
@example Pruning
# You can also prune empty objects and arrays from the result. Simply pass
# `pruneEmpty: true` in the options hash:
object =
empty: { }
emptyWhenFiltered:
foo: 'bar'
notEmptyWhenFiltered:
keepMe: 'some value'
mask =
empty: true
emptyWhenFiltered:
doesNotExist: true
notEmptyWhenFiltered:
keepMe: true
expected =
notEmptyWhenFiltered:
keepMe: 'some value'
result = masker.mask object, mask, pruneEmpty: true
# Without pruning, the result of the above would retain the empty objects,
# and would instead look like:
empty: { }
emptyWhenFiltered: { }
notEmptyWhenFiltered:
keepMe: 'some value'
@example The '*' Key
# If you need to keep **all** "own" keys in an object, specify a `'*'` key
# in the mask, like so:
object =
thing1: { foo: 1, bar: 2 }
thing2: { foo: 2, baz: 2 }
mask =
"*": { foo: true }
expected =
thing1: { foo: 1 }
thing2: { foo: 2 }
assert.deepEqual result, expected
# Note that actual globbing is not currently supported, and that you will
# need to quote the key. Nesting `'*'` keys is also valid, like so:
mask =
'*': { '*': true }
@example Truthiness
# It is **highly recommended** that you construct your mask using only
# `true`, `false`, and objects when possible. When creating a mask by
# iterating over a domain object, make sure to set each value to a boolean
# for the least complications.
# If you can not create an ideal `true`/`false`-based mask, NOM will apply
# general JavaScript "truthiness" to your keys. You should at least be aware
# of some caveats (the empty string in particular):
object:
trueTrue: 'kept'
trueOne: 'kept'
trueString: 'kept'
trueObject: 'kept'
trueArray: 'kept'
trueRegex: 'kept'
falseFalse: 'dropped'
falseString: 'dropped'
falseNull: 'dropped'
falseZero: 'dropped'
falseNaN: 'dropped'
falseUndefined: 'dropped'
mask:
trueTrue: true
trueOne: 1
trueString: 'yes'
trueObject: {}
trueArray: []
trueRegex: /asdf/
falseFalse: false
falseString: ''
falseNull: null
falseZero: 0
falseNaN: NaN
falseUndefined: undefined
expected:
trueTrue: 'kept'
trueOne: 'kept'
trueString: 'kept'
trueObject: 'kept'
trueArray: 'kept'
trueRegex: 'kept'
@param {any} object The object to filter via `mask`
@param {any} mask The mask to filter `object` with
@param {object} options Options to use while masking
@option options [boolean] pruneEmpty When true, recursively prunes empty objects and arrays from the result
@return any
@since 0.1.0
###
mask: (object, mask, options) ->
options = options || { }
return undefined unless mask
return object unless _.isObject(object) or _.isArray(object)
# if the mask contains a key that is simply an asterisk, all of the
# object's "own" properties will be passed through. this is achieved by
# simply setting the original object as the "iteratee" rather than the
# mask
result = if _.isArray(object) then [] else {}
permitAll = _.has(mask, '*') or mask == true
iteratee = if permitAll then object else mask
for own k,v of iteratee
subMask = undefined
if _.has(mask, k)
subMask = mask[k]
else # if permitAll <-- this is always true here
if _.has(mask, '*')
subMask = mask['*']
else
subMask = { '*': true }
maskedSubObject = module.exports.mask(object[k], subMask, options)
shouldPruneValue = (options.pruneEmpty && _.isEmpty(maskedSubObject))
valueWasEmpty = object[k] == undefined
valueIsEmpty = maskedSubObject == undefined
unless shouldPruneValue or valueWasEmpty or valueIsEmpty
result[k] = maskedSubObject
result
module.exports = Masker
|
[
{
"context": "lse\r\n admin_role_name: \"admin\"\r\n username: \"Guest\"\r\n session: null\r\n auth: {role: '', user: '",
"end": 318,
"score": 0.9931026697158813,
"start": 313,
"tag": "USERNAME",
"value": "Guest"
},
{
"context": "en(f())\r\n\r\n reset: ->\r\n this.auth.username = \"Guest\";\r\n this.auth.is_login = false;\r\n this.auth",
"end": 839,
"score": 0.9983930587768555,
"start": 834,
"tag": "USERNAME",
"value": "Guest"
},
{
"context": "d)->\r\n l = {\r\n csrf: ''\r\n login_name: user\r\n login_password: password\r\n project_na",
"end": 1910,
"score": 0.8462249040603638,
"start": 1906,
"tag": "USERNAME",
"value": "user"
},
{
"context": " ''\r\n login_name: user\r\n login_password: password\r\n project_name: project\r\n }\r\n project_",
"end": 1942,
"score": 0.998986542224884,
"start": 1934,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "me': l.login_name\r\n 'login_password': md5(md5(l.login_password) + kadmin.auth.csrf)\r\n ",
"end": 2702,
"score": 0.9529767036437988,
"start": 2699,
"tag": "PASSWORD",
"value": "md5"
},
{
"context": "l.login_name\r\n 'login_password': md5(md5(l.login_password) + kadmin.auth.csrf)\r\n ",
"end": 2706,
"score": 0.9097952842712402,
"start": 2703,
"tag": "PASSWORD",
"value": "md5"
}
] | resources/public/admin/kadmin.coffee | PranceCloud/Kaleido | 0 | kadmin =
setting:
admin_project: 'kaleido'
admin_url: 'm'
base_url: '/'
project_prefix_url: 'project'
project:
name: 'kaleido'
path: ''
allow_manage_ip: ''
model: []
auth:
is_login: false
is_admin: false
admin_role_name: "admin"
username: "Guest"
session: null
auth: {role: '', user: ''}
csrf: '?'
projects: []
require: {}
with_csrf: (call)->
f = (dtd) ->
dtd = $.Deferred()
$.getJSON(kadmin.setting.base_url + 'csrf')
.done((d)->
if typeof d == "object"
kadmin.auth.csrf = d.csrf
console.log("with_csrf resolve!")
dtd.resolve()
call() if typeof call == 'function'
)
dtd.promise()
$.when(f())
reset: ->
this.auth.username = "Guest";
this.auth.is_login = false;
this.auth.is_admin = false;
this.project.name = '';
this.project.model = [];
me: (call)->
$.getJSON(kadmin.setting.base_url + 'me').done((data) ->
if _.isObject(data.account) && (_.size(data.account) > 0)
_.each(data.account, (val, key)->
kadmin.auth.username = val.auth.login_name
kadmin.auth.userrole = val.auth.role
kadmin.auth.session = val.auth
kadmin.project.name = key
kadmin.auth.is_login = true
kadmin.auth.is_admin = true if (key == kadmin.admin_project)
)
).always(->
call() if typeof call == 'function'
)
logout: (call) ->
f = (dtd) ->
dtd = $.Deferred()
$.getJSON(kadmin.setting.base_url + kadmin.setting.admin_url + '/auth/logout', ->
kadmin.reset()
dtd.resolve()
call() if typeof call == 'function'
)
dtd.promise()
$.when(f())
login: (project, user, password)->
l = {
csrf: ''
login_name: user
login_password: password
project_name: project
}
project_auth_url = kadmin.setting.admin_url;
if not (l.project_name == kadmin.setting.admin_project)
project_auth_url = kadmin.setting.project_prefix_url + "/" + l.project_name;
f = (dtd) ->
dtd = $.Deferred()
kadmin.with_csrf().done(->
$.ajaxPrefilter((options, originalOptions, jqXHR) ->
jqXHR.setRequestHeader('X-CSRF-Token', kadmin.auth.csrf)
)
console.log("kadmin login beforeSend =>", kadmin.auth.csrf)
$.ajax(
{
url: kadmin.setting.base_url + project_auth_url + '/auth/login',
method: 'POST',
data: {
'login_name': l.login_name
'login_password': md5(md5(l.login_password) + kadmin.auth.csrf)
'csrf': kadmin.auth.csrf
}
})
.done((data) ->
if data.status == true
kadmin.auth.is_login = true
kadmin.auth.username = data.value.login_name
kadmin.auth.userrole = data.value.role
kadmin.project.name = l.project_name
kadmin.auth.is_login = true
if l.project_name == kadmin.setting.admin_project
kadmin.auth.is_admin = true
else
kadmin.auth.is_login = false
console.log("login resolve!")
dtd.resolve()
)
)
dtd.promise()
$.when(f())
project_load: (call)->
f = (dtd) ->
dtd = $.Deferred()
$.getJSON(kadmin.setting.base_url + kadmin.setting.project_prefix_url + '/' + kadmin.project.name + '/')
.done((data) ->
kadmin.project.model = data.model.data
kadmin.project.path = data.path
kadmin.project.allow_manage_ip = data.allowIP
dtd.resolve()
call() if typeof call == 'function'
)
dtd.promise()
$.when(f())
model_parse: (call)->
f = (dtd) ->
dtd = $.Deferred()
if not (kadmin.project.name == '') && kadmin.project.model?
console.log(kadmin.project.model)
dtd.resolve()
call() if typeof call == 'function'
dtd.promise()
$.when(f())
field_join_value: (current_model, call) ->
# console.log(current_model, kadmin.project.model)
models = _.filter(kadmin.project.model, (m)->
return m.name != current_model
)
# fields = _.flatten(_.map(models, (m)-> m.fields))
_fields = _.filter(
_.flatten(_.map(models, (m)->
mm = m
_.map(m.fields, (m1) ->
nm = m1
nm.model_name = mm.name
nm)
)),
(m)->
not (_.contains(["join", "json"], m.type))
)
fields = _.map(_fields, (f)-> return f.model_name + "." + f.name)
console.log(fields)
fields
# ["123123", '12312331', '234234432', new Date().getTime().toString()]
model_destroy: (model, call)->
m = model
f = (dtd) ->
dtd = $.Deferred()
console.log("kadmin model_destroy => ", m)
kadmin.with_csrf().done(->
$.ajaxPrefilter((options, originalOptions, jqXHR) ->
jqXHR.setRequestHeader('X-CSRF-Token', kadmin.auth.csrf)
)
$.ajax(
{
url: kadmin.setting.base_url + kadmin.setting.project_prefix_url + '/' + kadmin.project.name + '/destroy/model',
contentType: 'application/json'
method: 'POST'
data: JSON.stringify(m)
})
.done((data) ->
dtd.resolve()
call() if typeof call == 'function'
)
)
dtd.promise()
$.when(f())
model_save: (values, call)->
model_value = values
f = (dtd) ->
dtd = $.Deferred()
console.log("kadmin model_save => ", model_value)
kadmin.with_csrf().done(->
$.ajaxPrefilter((options, originalOptions, jqXHR) ->
jqXHR.setRequestHeader('X-CSRF-Token', kadmin.auth.csrf)
)
$.ajax(
{
url: kadmin.setting.base_url + kadmin.setting.project_prefix_url + '/' + kadmin.project.name + '/update/model',
contentType: 'application/json'
method: 'POST'
data: JSON.stringify(model_value)
})
.done((data) ->
kadmin.require = data
dtd.resolve()
call() if typeof call == 'function'
)
)
dtd.promise()
$.when(f())
project_save: (values, call)->
project_value = values
f = (dtd) ->
dtd = $.Deferred()
console.log(project_value)
kadmin.with_csrf().done(->
$.ajaxPrefilter((options, originalOptions, jqXHR) ->
jqXHR.setRequestHeader('X-CSRF-Token', kadmin.auth.csrf)
)
$.ajax(
{
url: kadmin.setting.base_url + kadmin.setting.project_prefix_url + '/' + project_value.name + '/update/model',
contentType: 'application/json'
method: 'POST',
data: JSON.stringify(project_value)
})
.done((data) ->
dtd.resolve()
call() if typeof call == 'function'
)
)
dtd.promise()
$.when(f())
project_delete: (name, call) ->
f = (dtd) ->
dtd = $.Deferred()
console.log(name)
dtd.resolve()
call() if typeof call == 'function'
dtd.promise()
$.when(f())
| 154358 | kadmin =
setting:
admin_project: 'kaleido'
admin_url: 'm'
base_url: '/'
project_prefix_url: 'project'
project:
name: 'kaleido'
path: ''
allow_manage_ip: ''
model: []
auth:
is_login: false
is_admin: false
admin_role_name: "admin"
username: "Guest"
session: null
auth: {role: '', user: ''}
csrf: '?'
projects: []
require: {}
with_csrf: (call)->
f = (dtd) ->
dtd = $.Deferred()
$.getJSON(kadmin.setting.base_url + 'csrf')
.done((d)->
if typeof d == "object"
kadmin.auth.csrf = d.csrf
console.log("with_csrf resolve!")
dtd.resolve()
call() if typeof call == 'function'
)
dtd.promise()
$.when(f())
reset: ->
this.auth.username = "Guest";
this.auth.is_login = false;
this.auth.is_admin = false;
this.project.name = '';
this.project.model = [];
me: (call)->
$.getJSON(kadmin.setting.base_url + 'me').done((data) ->
if _.isObject(data.account) && (_.size(data.account) > 0)
_.each(data.account, (val, key)->
kadmin.auth.username = val.auth.login_name
kadmin.auth.userrole = val.auth.role
kadmin.auth.session = val.auth
kadmin.project.name = key
kadmin.auth.is_login = true
kadmin.auth.is_admin = true if (key == kadmin.admin_project)
)
).always(->
call() if typeof call == 'function'
)
logout: (call) ->
f = (dtd) ->
dtd = $.Deferred()
$.getJSON(kadmin.setting.base_url + kadmin.setting.admin_url + '/auth/logout', ->
kadmin.reset()
dtd.resolve()
call() if typeof call == 'function'
)
dtd.promise()
$.when(f())
login: (project, user, password)->
l = {
csrf: ''
login_name: user
login_password: <PASSWORD>
project_name: project
}
project_auth_url = kadmin.setting.admin_url;
if not (l.project_name == kadmin.setting.admin_project)
project_auth_url = kadmin.setting.project_prefix_url + "/" + l.project_name;
f = (dtd) ->
dtd = $.Deferred()
kadmin.with_csrf().done(->
$.ajaxPrefilter((options, originalOptions, jqXHR) ->
jqXHR.setRequestHeader('X-CSRF-Token', kadmin.auth.csrf)
)
console.log("kadmin login beforeSend =>", kadmin.auth.csrf)
$.ajax(
{
url: kadmin.setting.base_url + project_auth_url + '/auth/login',
method: 'POST',
data: {
'login_name': l.login_name
'login_password': <PASSWORD>(<PASSWORD>(l.login_password) + kadmin.auth.csrf)
'csrf': kadmin.auth.csrf
}
})
.done((data) ->
if data.status == true
kadmin.auth.is_login = true
kadmin.auth.username = data.value.login_name
kadmin.auth.userrole = data.value.role
kadmin.project.name = l.project_name
kadmin.auth.is_login = true
if l.project_name == kadmin.setting.admin_project
kadmin.auth.is_admin = true
else
kadmin.auth.is_login = false
console.log("login resolve!")
dtd.resolve()
)
)
dtd.promise()
$.when(f())
project_load: (call)->
f = (dtd) ->
dtd = $.Deferred()
$.getJSON(kadmin.setting.base_url + kadmin.setting.project_prefix_url + '/' + kadmin.project.name + '/')
.done((data) ->
kadmin.project.model = data.model.data
kadmin.project.path = data.path
kadmin.project.allow_manage_ip = data.allowIP
dtd.resolve()
call() if typeof call == 'function'
)
dtd.promise()
$.when(f())
model_parse: (call)->
f = (dtd) ->
dtd = $.Deferred()
if not (kadmin.project.name == '') && kadmin.project.model?
console.log(kadmin.project.model)
dtd.resolve()
call() if typeof call == 'function'
dtd.promise()
$.when(f())
field_join_value: (current_model, call) ->
# console.log(current_model, kadmin.project.model)
models = _.filter(kadmin.project.model, (m)->
return m.name != current_model
)
# fields = _.flatten(_.map(models, (m)-> m.fields))
_fields = _.filter(
_.flatten(_.map(models, (m)->
mm = m
_.map(m.fields, (m1) ->
nm = m1
nm.model_name = mm.name
nm)
)),
(m)->
not (_.contains(["join", "json"], m.type))
)
fields = _.map(_fields, (f)-> return f.model_name + "." + f.name)
console.log(fields)
fields
# ["123123", '12312331', '234234432', new Date().getTime().toString()]
model_destroy: (model, call)->
m = model
f = (dtd) ->
dtd = $.Deferred()
console.log("kadmin model_destroy => ", m)
kadmin.with_csrf().done(->
$.ajaxPrefilter((options, originalOptions, jqXHR) ->
jqXHR.setRequestHeader('X-CSRF-Token', kadmin.auth.csrf)
)
$.ajax(
{
url: kadmin.setting.base_url + kadmin.setting.project_prefix_url + '/' + kadmin.project.name + '/destroy/model',
contentType: 'application/json'
method: 'POST'
data: JSON.stringify(m)
})
.done((data) ->
dtd.resolve()
call() if typeof call == 'function'
)
)
dtd.promise()
$.when(f())
model_save: (values, call)->
model_value = values
f = (dtd) ->
dtd = $.Deferred()
console.log("kadmin model_save => ", model_value)
kadmin.with_csrf().done(->
$.ajaxPrefilter((options, originalOptions, jqXHR) ->
jqXHR.setRequestHeader('X-CSRF-Token', kadmin.auth.csrf)
)
$.ajax(
{
url: kadmin.setting.base_url + kadmin.setting.project_prefix_url + '/' + kadmin.project.name + '/update/model',
contentType: 'application/json'
method: 'POST'
data: JSON.stringify(model_value)
})
.done((data) ->
kadmin.require = data
dtd.resolve()
call() if typeof call == 'function'
)
)
dtd.promise()
$.when(f())
project_save: (values, call)->
project_value = values
f = (dtd) ->
dtd = $.Deferred()
console.log(project_value)
kadmin.with_csrf().done(->
$.ajaxPrefilter((options, originalOptions, jqXHR) ->
jqXHR.setRequestHeader('X-CSRF-Token', kadmin.auth.csrf)
)
$.ajax(
{
url: kadmin.setting.base_url + kadmin.setting.project_prefix_url + '/' + project_value.name + '/update/model',
contentType: 'application/json'
method: 'POST',
data: JSON.stringify(project_value)
})
.done((data) ->
dtd.resolve()
call() if typeof call == 'function'
)
)
dtd.promise()
$.when(f())
project_delete: (name, call) ->
f = (dtd) ->
dtd = $.Deferred()
console.log(name)
dtd.resolve()
call() if typeof call == 'function'
dtd.promise()
$.when(f())
| true | kadmin =
setting:
admin_project: 'kaleido'
admin_url: 'm'
base_url: '/'
project_prefix_url: 'project'
project:
name: 'kaleido'
path: ''
allow_manage_ip: ''
model: []
auth:
is_login: false
is_admin: false
admin_role_name: "admin"
username: "Guest"
session: null
auth: {role: '', user: ''}
csrf: '?'
projects: []
require: {}
with_csrf: (call)->
f = (dtd) ->
dtd = $.Deferred()
$.getJSON(kadmin.setting.base_url + 'csrf')
.done((d)->
if typeof d == "object"
kadmin.auth.csrf = d.csrf
console.log("with_csrf resolve!")
dtd.resolve()
call() if typeof call == 'function'
)
dtd.promise()
$.when(f())
reset: ->
this.auth.username = "Guest";
this.auth.is_login = false;
this.auth.is_admin = false;
this.project.name = '';
this.project.model = [];
me: (call)->
$.getJSON(kadmin.setting.base_url + 'me').done((data) ->
if _.isObject(data.account) && (_.size(data.account) > 0)
_.each(data.account, (val, key)->
kadmin.auth.username = val.auth.login_name
kadmin.auth.userrole = val.auth.role
kadmin.auth.session = val.auth
kadmin.project.name = key
kadmin.auth.is_login = true
kadmin.auth.is_admin = true if (key == kadmin.admin_project)
)
).always(->
call() if typeof call == 'function'
)
logout: (call) ->
f = (dtd) ->
dtd = $.Deferred()
$.getJSON(kadmin.setting.base_url + kadmin.setting.admin_url + '/auth/logout', ->
kadmin.reset()
dtd.resolve()
call() if typeof call == 'function'
)
dtd.promise()
$.when(f())
login: (project, user, password)->
l = {
csrf: ''
login_name: user
login_password: PI:PASSWORD:<PASSWORD>END_PI
project_name: project
}
project_auth_url = kadmin.setting.admin_url;
if not (l.project_name == kadmin.setting.admin_project)
project_auth_url = kadmin.setting.project_prefix_url + "/" + l.project_name;
f = (dtd) ->
dtd = $.Deferred()
kadmin.with_csrf().done(->
$.ajaxPrefilter((options, originalOptions, jqXHR) ->
jqXHR.setRequestHeader('X-CSRF-Token', kadmin.auth.csrf)
)
console.log("kadmin login beforeSend =>", kadmin.auth.csrf)
$.ajax(
{
url: kadmin.setting.base_url + project_auth_url + '/auth/login',
method: 'POST',
data: {
'login_name': l.login_name
'login_password': PI:PASSWORD:<PASSWORD>END_PI(PI:PASSWORD:<PASSWORD>END_PI(l.login_password) + kadmin.auth.csrf)
'csrf': kadmin.auth.csrf
}
})
.done((data) ->
if data.status == true
kadmin.auth.is_login = true
kadmin.auth.username = data.value.login_name
kadmin.auth.userrole = data.value.role
kadmin.project.name = l.project_name
kadmin.auth.is_login = true
if l.project_name == kadmin.setting.admin_project
kadmin.auth.is_admin = true
else
kadmin.auth.is_login = false
console.log("login resolve!")
dtd.resolve()
)
)
dtd.promise()
$.when(f())
project_load: (call)->
f = (dtd) ->
dtd = $.Deferred()
$.getJSON(kadmin.setting.base_url + kadmin.setting.project_prefix_url + '/' + kadmin.project.name + '/')
.done((data) ->
kadmin.project.model = data.model.data
kadmin.project.path = data.path
kadmin.project.allow_manage_ip = data.allowIP
dtd.resolve()
call() if typeof call == 'function'
)
dtd.promise()
$.when(f())
model_parse: (call)->
f = (dtd) ->
dtd = $.Deferred()
if not (kadmin.project.name == '') && kadmin.project.model?
console.log(kadmin.project.model)
dtd.resolve()
call() if typeof call == 'function'
dtd.promise()
$.when(f())
field_join_value: (current_model, call) ->
# console.log(current_model, kadmin.project.model)
models = _.filter(kadmin.project.model, (m)->
return m.name != current_model
)
# fields = _.flatten(_.map(models, (m)-> m.fields))
_fields = _.filter(
_.flatten(_.map(models, (m)->
mm = m
_.map(m.fields, (m1) ->
nm = m1
nm.model_name = mm.name
nm)
)),
(m)->
not (_.contains(["join", "json"], m.type))
)
fields = _.map(_fields, (f)-> return f.model_name + "." + f.name)
console.log(fields)
fields
# ["123123", '12312331', '234234432', new Date().getTime().toString()]
model_destroy: (model, call)->
m = model
f = (dtd) ->
dtd = $.Deferred()
console.log("kadmin model_destroy => ", m)
kadmin.with_csrf().done(->
$.ajaxPrefilter((options, originalOptions, jqXHR) ->
jqXHR.setRequestHeader('X-CSRF-Token', kadmin.auth.csrf)
)
$.ajax(
{
url: kadmin.setting.base_url + kadmin.setting.project_prefix_url + '/' + kadmin.project.name + '/destroy/model',
contentType: 'application/json'
method: 'POST'
data: JSON.stringify(m)
})
.done((data) ->
dtd.resolve()
call() if typeof call == 'function'
)
)
dtd.promise()
$.when(f())
model_save: (values, call)->
model_value = values
f = (dtd) ->
dtd = $.Deferred()
console.log("kadmin model_save => ", model_value)
kadmin.with_csrf().done(->
$.ajaxPrefilter((options, originalOptions, jqXHR) ->
jqXHR.setRequestHeader('X-CSRF-Token', kadmin.auth.csrf)
)
$.ajax(
{
url: kadmin.setting.base_url + kadmin.setting.project_prefix_url + '/' + kadmin.project.name + '/update/model',
contentType: 'application/json'
method: 'POST'
data: JSON.stringify(model_value)
})
.done((data) ->
kadmin.require = data
dtd.resolve()
call() if typeof call == 'function'
)
)
dtd.promise()
$.when(f())
project_save: (values, call)->
project_value = values
f = (dtd) ->
dtd = $.Deferred()
console.log(project_value)
kadmin.with_csrf().done(->
$.ajaxPrefilter((options, originalOptions, jqXHR) ->
jqXHR.setRequestHeader('X-CSRF-Token', kadmin.auth.csrf)
)
$.ajax(
{
url: kadmin.setting.base_url + kadmin.setting.project_prefix_url + '/' + project_value.name + '/update/model',
contentType: 'application/json'
method: 'POST',
data: JSON.stringify(project_value)
})
.done((data) ->
dtd.resolve()
call() if typeof call == 'function'
)
)
dtd.promise()
$.when(f())
project_delete: (name, call) ->
f = (dtd) ->
dtd = $.Deferred()
console.log(name)
dtd.resolve()
call() if typeof call == 'function'
dtd.promise()
$.when(f())
|
[
{
"context": "to get to the elasticsearch cluster\n#\n# Author:\n# Paul Stack\n\n_esAliases = {}\n\nQS = require 'querystring'\n\nmod",
"end": 1645,
"score": 0.9998335838317871,
"start": 1635,
"tag": "NAME",
"value": "Paul Stack"
}
] | src/elasticsearch.coffee | stack72/hubot-elasticsearch | 23 | # Description:
# Get ElasticSearch Cluster Information
#
# Commands:
# hubot: elasticsearch cluster health [cluster] - Gets the cluster health for the given server or alias
# hubot: elasticsearch cat nodes [cluster] - Gets the information from the cat nodes endpoint for the given server or alias
# hubot: elasticsearch cat indexes [cluster] - Gets the information from the cat indexes endpoint for the given server or alias
# hubot: elasticsearch cat allocation [cluster] - Gets the information from the cat allocation endpoint for the given server or alias
# hubot: elasticsearch clear cache [cluster] - Clears the cache for the specified cluster
# hubot: elasticsearch cluster settings [cluster] - Gets a list of all of the settings stored for the cluster
# hubot: elasticsearch index settings [cluster] [index] - Gets a list of all of the settings stored for a particular index
# hubot: elasticsearch disable allocation [cluster] - disables shard allocation to allow nodes to be taken offline
# hubot: elasticsearch enable allocation [cluster] - renables shard allocation
# hubot: elasticsearch show aliases - shows the aliases for the list of ElasticSearch instances
# hubot: elasticsearch add alias [alias name] [url] - sets the alias for a given url
# hubot: elasticsearch clear alias [alias name] - please note that this needs to include any port numbers as appropriate
#
# Notes:
# The server must be a fqdn (with the port!) to get to the elasticsearch cluster
#
# Author:
# Paul Stack
_esAliases = {}
QS = require 'querystring'
module.exports = (robot) ->
robot.brain.on 'loaded', ->
if robot.brain.data.elasticsearch_aliases?
_esAliases = robot.brain.data.elasticsearch_aliases
clusterHealth = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.http("#{cluster_url}/_cat/health?pretty=true")
.get() (err, res, body) ->
msg.send("/code #{body}")
catNodes = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Getting the cat stats for the cluster: #{cluster_url}")
msg.http("#{cluster_url}/_cat/nodes?h=host,heapPercent,load,segmentsMemory,fielddataMemory,filterCacheMemory,idCacheMemory,percolateMemory,u,heapMax,nodeRole,master")
.get() (err, res, body) ->
lines = body.split("\n")
header = lines.shift()
list = [header].concat(lines.sort().reverse()).join("\n")
msg.send("/code #{list}")
catIndexes = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Getting the cat indices for the cluster: #{cluster_url}")
msg.http("#{cluster_url}/_cat/indices/logstash-*?h=idx,sm,fm,fcm,im,pm,ss,sc,dc&v")
.get() (err, res, body) ->
lines = body.split("\n")
header = lines.shift()
list = [header].concat(lines.sort().reverse()).join("\n")
msg.send("/code #{list}")
catAllocation = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Getting the cat allocation for the cluster: #{cluster_url}")
msg.http("#{cluster_url}/_cat/allocation/?h=disk.percent,node,shards,disk.used,disk.avail")
.get() (err, res, body) ->
lines = body.split("\n")
header = lines.shift()
list = [header].concat(lines.sort().reverse()).join("\n")
msg.send("/code #{list}")
clearCache = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Clearing the cache for the cluster: #{cluster_url}")
msg.http("#{cluster_url}/_cache/clear")
.post() (err, res, body) ->
json = JSON.parse(body)
shards = json['_shards']['total']
successful = json['_shards']['successful']
failure = json['_shards']['failed']
msg.send "Results: \n Total Shards: #{shards} \n Successful: #{successful} \n Failure: #{failure}"
disableAllocation = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Disabling Allocation for the cluster #{cluster_url}")
data = {
'transient': {
'cluster.routing.allocation.enable': 'none'
}
}
json = JSON.stringify(data)
msg.http("#{cluster_url}/_cluster/settings")
.put(json) (err, res, body) ->
msg.send("/code #{body}")
enableAllocation = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Enabling Allocation for the cluster #{cluster_url}")
data = {
'transient': {
'cluster.routing.allocation.enable': 'all'
}
}
json = JSON.stringify(data)
msg.http("#{cluster_url}/_cluster/settings")
.put(json) (err, res, body) ->
msg.send("/code #{body}")
showClusterSettings = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Getting the Cluster settings for #{cluster_url}")
msg.http("#{cluster_url}/_cluster/settings?pretty=true")
.get() (err, res, body) ->
msg.send("/code #{body}")
showIndexSettings = (msg, alias, index) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Getting the Index settings for #{index} on #{cluster_url}")
msg.http("#{cluster_url}/#{index}/_settings?pretty=true")
.get() (err, res, body) ->
msg.send("/code #{body}")
showAliases = (msg) ->
if _esAliases == null
msg.send("I cannot find any ElasticSearch Cluster aliases")
else
for alias of _esAliases
msg.send("I found '#{alias}' as an alias for the cluster: #{_esAliases[alias]}")
clearAlias = (msg, alias) ->
delete _esAliases[alias]
robot.brain.data.elasticsearch_aliases = _esAliases
msg.send("The cluster alias #{alias} has been removed")
setAlias = (msg, alias, url) ->
_esAliases[alias] = url
robot.brain.data.elasticsearch_aliases = _esAliases
msg.send("The cluster alias #{alias} for #{url} has been added to the brain")
robot.hear /elasticsearch cat nodes (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
catNodes msg, msg.match[1], (text) ->
msg.send text
robot.hear /elasticsearch cat indexes (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
catIndexes msg, msg.match[1], (text) ->
msg.send text
robot.hear /elasticsearch cat allocation (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
catAllocation msg, msg.match[1], (text) ->
msg.send text
robot.hear /elasticsearch cluster settings (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
showClusterSettings msg, msg.match[1], (text) ->
msg.send(text)
robot.hear /elasticsearch cluster health (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
clusterHealth msg, msg.match[1], (text) ->
msg.send text
robot.hear /elasticsearch index settings (.*) (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
showIndexSettings msg, msg.match[1], msg.match[2], (text) ->
msg.send text
robot.hear /elasticsearch show aliases/i, (msg) ->
if msg.message.user.id is robot.name
return
showAliases msg, (text) ->
msg.send(text)
robot.hear /elasticsearch add alias (.*) (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
setAlias msg, msg.match[1], msg.match[2], (text) ->
msg.send(text)
robot.hear /elasticsearch clear alias (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
clearAlias msg, msg.match[1], (text) ->
msg.send(text)
robot.respond /elasticsearch clear cache (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
clearCache msg, msg.match[1], (text) ->
msg.send(text)
robot.respond /elasticsearch disable allocation (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
disableAllocation msg, msg.match[1], (text) ->
msg.send(text)
robot.respond /elasticsearch enable allocation (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
enableAllocation msg, msg.match[1], (text) ->
msg.send(text)
| 72441 | # Description:
# Get ElasticSearch Cluster Information
#
# Commands:
# hubot: elasticsearch cluster health [cluster] - Gets the cluster health for the given server or alias
# hubot: elasticsearch cat nodes [cluster] - Gets the information from the cat nodes endpoint for the given server or alias
# hubot: elasticsearch cat indexes [cluster] - Gets the information from the cat indexes endpoint for the given server or alias
# hubot: elasticsearch cat allocation [cluster] - Gets the information from the cat allocation endpoint for the given server or alias
# hubot: elasticsearch clear cache [cluster] - Clears the cache for the specified cluster
# hubot: elasticsearch cluster settings [cluster] - Gets a list of all of the settings stored for the cluster
# hubot: elasticsearch index settings [cluster] [index] - Gets a list of all of the settings stored for a particular index
# hubot: elasticsearch disable allocation [cluster] - disables shard allocation to allow nodes to be taken offline
# hubot: elasticsearch enable allocation [cluster] - renables shard allocation
# hubot: elasticsearch show aliases - shows the aliases for the list of ElasticSearch instances
# hubot: elasticsearch add alias [alias name] [url] - sets the alias for a given url
# hubot: elasticsearch clear alias [alias name] - please note that this needs to include any port numbers as appropriate
#
# Notes:
# The server must be a fqdn (with the port!) to get to the elasticsearch cluster
#
# Author:
# <NAME>
_esAliases = {}
QS = require 'querystring'
module.exports = (robot) ->
robot.brain.on 'loaded', ->
if robot.brain.data.elasticsearch_aliases?
_esAliases = robot.brain.data.elasticsearch_aliases
clusterHealth = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.http("#{cluster_url}/_cat/health?pretty=true")
.get() (err, res, body) ->
msg.send("/code #{body}")
catNodes = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Getting the cat stats for the cluster: #{cluster_url}")
msg.http("#{cluster_url}/_cat/nodes?h=host,heapPercent,load,segmentsMemory,fielddataMemory,filterCacheMemory,idCacheMemory,percolateMemory,u,heapMax,nodeRole,master")
.get() (err, res, body) ->
lines = body.split("\n")
header = lines.shift()
list = [header].concat(lines.sort().reverse()).join("\n")
msg.send("/code #{list}")
catIndexes = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Getting the cat indices for the cluster: #{cluster_url}")
msg.http("#{cluster_url}/_cat/indices/logstash-*?h=idx,sm,fm,fcm,im,pm,ss,sc,dc&v")
.get() (err, res, body) ->
lines = body.split("\n")
header = lines.shift()
list = [header].concat(lines.sort().reverse()).join("\n")
msg.send("/code #{list}")
catAllocation = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Getting the cat allocation for the cluster: #{cluster_url}")
msg.http("#{cluster_url}/_cat/allocation/?h=disk.percent,node,shards,disk.used,disk.avail")
.get() (err, res, body) ->
lines = body.split("\n")
header = lines.shift()
list = [header].concat(lines.sort().reverse()).join("\n")
msg.send("/code #{list}")
clearCache = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Clearing the cache for the cluster: #{cluster_url}")
msg.http("#{cluster_url}/_cache/clear")
.post() (err, res, body) ->
json = JSON.parse(body)
shards = json['_shards']['total']
successful = json['_shards']['successful']
failure = json['_shards']['failed']
msg.send "Results: \n Total Shards: #{shards} \n Successful: #{successful} \n Failure: #{failure}"
disableAllocation = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Disabling Allocation for the cluster #{cluster_url}")
data = {
'transient': {
'cluster.routing.allocation.enable': 'none'
}
}
json = JSON.stringify(data)
msg.http("#{cluster_url}/_cluster/settings")
.put(json) (err, res, body) ->
msg.send("/code #{body}")
enableAllocation = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Enabling Allocation for the cluster #{cluster_url}")
data = {
'transient': {
'cluster.routing.allocation.enable': 'all'
}
}
json = JSON.stringify(data)
msg.http("#{cluster_url}/_cluster/settings")
.put(json) (err, res, body) ->
msg.send("/code #{body}")
showClusterSettings = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Getting the Cluster settings for #{cluster_url}")
msg.http("#{cluster_url}/_cluster/settings?pretty=true")
.get() (err, res, body) ->
msg.send("/code #{body}")
showIndexSettings = (msg, alias, index) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Getting the Index settings for #{index} on #{cluster_url}")
msg.http("#{cluster_url}/#{index}/_settings?pretty=true")
.get() (err, res, body) ->
msg.send("/code #{body}")
showAliases = (msg) ->
if _esAliases == null
msg.send("I cannot find any ElasticSearch Cluster aliases")
else
for alias of _esAliases
msg.send("I found '#{alias}' as an alias for the cluster: #{_esAliases[alias]}")
clearAlias = (msg, alias) ->
delete _esAliases[alias]
robot.brain.data.elasticsearch_aliases = _esAliases
msg.send("The cluster alias #{alias} has been removed")
setAlias = (msg, alias, url) ->
_esAliases[alias] = url
robot.brain.data.elasticsearch_aliases = _esAliases
msg.send("The cluster alias #{alias} for #{url} has been added to the brain")
robot.hear /elasticsearch cat nodes (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
catNodes msg, msg.match[1], (text) ->
msg.send text
robot.hear /elasticsearch cat indexes (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
catIndexes msg, msg.match[1], (text) ->
msg.send text
robot.hear /elasticsearch cat allocation (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
catAllocation msg, msg.match[1], (text) ->
msg.send text
robot.hear /elasticsearch cluster settings (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
showClusterSettings msg, msg.match[1], (text) ->
msg.send(text)
robot.hear /elasticsearch cluster health (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
clusterHealth msg, msg.match[1], (text) ->
msg.send text
robot.hear /elasticsearch index settings (.*) (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
showIndexSettings msg, msg.match[1], msg.match[2], (text) ->
msg.send text
robot.hear /elasticsearch show aliases/i, (msg) ->
if msg.message.user.id is robot.name
return
showAliases msg, (text) ->
msg.send(text)
robot.hear /elasticsearch add alias (.*) (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
setAlias msg, msg.match[1], msg.match[2], (text) ->
msg.send(text)
robot.hear /elasticsearch clear alias (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
clearAlias msg, msg.match[1], (text) ->
msg.send(text)
robot.respond /elasticsearch clear cache (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
clearCache msg, msg.match[1], (text) ->
msg.send(text)
robot.respond /elasticsearch disable allocation (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
disableAllocation msg, msg.match[1], (text) ->
msg.send(text)
robot.respond /elasticsearch enable allocation (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
enableAllocation msg, msg.match[1], (text) ->
msg.send(text)
| true | # Description:
# Get ElasticSearch Cluster Information
#
# Commands:
# hubot: elasticsearch cluster health [cluster] - Gets the cluster health for the given server or alias
# hubot: elasticsearch cat nodes [cluster] - Gets the information from the cat nodes endpoint for the given server or alias
# hubot: elasticsearch cat indexes [cluster] - Gets the information from the cat indexes endpoint for the given server or alias
# hubot: elasticsearch cat allocation [cluster] - Gets the information from the cat allocation endpoint for the given server or alias
# hubot: elasticsearch clear cache [cluster] - Clears the cache for the specified cluster
# hubot: elasticsearch cluster settings [cluster] - Gets a list of all of the settings stored for the cluster
# hubot: elasticsearch index settings [cluster] [index] - Gets a list of all of the settings stored for a particular index
# hubot: elasticsearch disable allocation [cluster] - disables shard allocation to allow nodes to be taken offline
# hubot: elasticsearch enable allocation [cluster] - renables shard allocation
# hubot: elasticsearch show aliases - shows the aliases for the list of ElasticSearch instances
# hubot: elasticsearch add alias [alias name] [url] - sets the alias for a given url
# hubot: elasticsearch clear alias [alias name] - please note that this needs to include any port numbers as appropriate
#
# Notes:
# The server must be a fqdn (with the port!) to get to the elasticsearch cluster
#
# Author:
# PI:NAME:<NAME>END_PI
_esAliases = {}
QS = require 'querystring'
module.exports = (robot) ->
robot.brain.on 'loaded', ->
if robot.brain.data.elasticsearch_aliases?
_esAliases = robot.brain.data.elasticsearch_aliases
clusterHealth = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.http("#{cluster_url}/_cat/health?pretty=true")
.get() (err, res, body) ->
msg.send("/code #{body}")
catNodes = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Getting the cat stats for the cluster: #{cluster_url}")
msg.http("#{cluster_url}/_cat/nodes?h=host,heapPercent,load,segmentsMemory,fielddataMemory,filterCacheMemory,idCacheMemory,percolateMemory,u,heapMax,nodeRole,master")
.get() (err, res, body) ->
lines = body.split("\n")
header = lines.shift()
list = [header].concat(lines.sort().reverse()).join("\n")
msg.send("/code #{list}")
catIndexes = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Getting the cat indices for the cluster: #{cluster_url}")
msg.http("#{cluster_url}/_cat/indices/logstash-*?h=idx,sm,fm,fcm,im,pm,ss,sc,dc&v")
.get() (err, res, body) ->
lines = body.split("\n")
header = lines.shift()
list = [header].concat(lines.sort().reverse()).join("\n")
msg.send("/code #{list}")
catAllocation = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Getting the cat allocation for the cluster: #{cluster_url}")
msg.http("#{cluster_url}/_cat/allocation/?h=disk.percent,node,shards,disk.used,disk.avail")
.get() (err, res, body) ->
lines = body.split("\n")
header = lines.shift()
list = [header].concat(lines.sort().reverse()).join("\n")
msg.send("/code #{list}")
clearCache = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Clearing the cache for the cluster: #{cluster_url}")
msg.http("#{cluster_url}/_cache/clear")
.post() (err, res, body) ->
json = JSON.parse(body)
shards = json['_shards']['total']
successful = json['_shards']['successful']
failure = json['_shards']['failed']
msg.send "Results: \n Total Shards: #{shards} \n Successful: #{successful} \n Failure: #{failure}"
disableAllocation = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Disabling Allocation for the cluster #{cluster_url}")
data = {
'transient': {
'cluster.routing.allocation.enable': 'none'
}
}
json = JSON.stringify(data)
msg.http("#{cluster_url}/_cluster/settings")
.put(json) (err, res, body) ->
msg.send("/code #{body}")
enableAllocation = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Enabling Allocation for the cluster #{cluster_url}")
data = {
'transient': {
'cluster.routing.allocation.enable': 'all'
}
}
json = JSON.stringify(data)
msg.http("#{cluster_url}/_cluster/settings")
.put(json) (err, res, body) ->
msg.send("/code #{body}")
showClusterSettings = (msg, alias) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Getting the Cluster settings for #{cluster_url}")
msg.http("#{cluster_url}/_cluster/settings?pretty=true")
.get() (err, res, body) ->
msg.send("/code #{body}")
showIndexSettings = (msg, alias, index) ->
cluster_url = _esAliases[alias]
if cluster_url == "" || cluster_url == undefined
msg.send("Do not recognise the cluster alias: #{alias}")
else
msg.send("Getting the Index settings for #{index} on #{cluster_url}")
msg.http("#{cluster_url}/#{index}/_settings?pretty=true")
.get() (err, res, body) ->
msg.send("/code #{body}")
showAliases = (msg) ->
if _esAliases == null
msg.send("I cannot find any ElasticSearch Cluster aliases")
else
for alias of _esAliases
msg.send("I found '#{alias}' as an alias for the cluster: #{_esAliases[alias]}")
clearAlias = (msg, alias) ->
delete _esAliases[alias]
robot.brain.data.elasticsearch_aliases = _esAliases
msg.send("The cluster alias #{alias} has been removed")
setAlias = (msg, alias, url) ->
_esAliases[alias] = url
robot.brain.data.elasticsearch_aliases = _esAliases
msg.send("The cluster alias #{alias} for #{url} has been added to the brain")
robot.hear /elasticsearch cat nodes (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
catNodes msg, msg.match[1], (text) ->
msg.send text
robot.hear /elasticsearch cat indexes (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
catIndexes msg, msg.match[1], (text) ->
msg.send text
robot.hear /elasticsearch cat allocation (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
catAllocation msg, msg.match[1], (text) ->
msg.send text
robot.hear /elasticsearch cluster settings (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
showClusterSettings msg, msg.match[1], (text) ->
msg.send(text)
robot.hear /elasticsearch cluster health (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
clusterHealth msg, msg.match[1], (text) ->
msg.send text
robot.hear /elasticsearch index settings (.*) (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
showIndexSettings msg, msg.match[1], msg.match[2], (text) ->
msg.send text
robot.hear /elasticsearch show aliases/i, (msg) ->
if msg.message.user.id is robot.name
return
showAliases msg, (text) ->
msg.send(text)
robot.hear /elasticsearch add alias (.*) (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
setAlias msg, msg.match[1], msg.match[2], (text) ->
msg.send(text)
robot.hear /elasticsearch clear alias (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
clearAlias msg, msg.match[1], (text) ->
msg.send(text)
robot.respond /elasticsearch clear cache (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
clearCache msg, msg.match[1], (text) ->
msg.send(text)
robot.respond /elasticsearch disable allocation (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
disableAllocation msg, msg.match[1], (text) ->
msg.send(text)
robot.respond /elasticsearch enable allocation (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
enableAllocation msg, msg.match[1], (text) ->
msg.send(text)
|
[
{
"context": "[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)///gi\r\n\t,\r\n\t\tosis: [\"Jonah\", \"Job\", \"Josh\", \"Joel\"]\r\n\t\tregexp: ///(^|#{bcv_p",
"end": 25266,
"score": 0.9994688034057617,
"start": 25261,
"tag": "NAME",
"value": "Jonah"
},
{
"context": "~\\-\\u2013\\u2014])|$)///gi\r\n\t,\r\n\t\tosis: [\"Jonah\", \"Job\", \"Josh\", \"Joel\"]\r\n\t\tregexp: ///(^|#{bcv_parser::",
"end": 25273,
"score": 0.9960538148880005,
"start": 25270,
"tag": "NAME",
"value": "Job"
},
{
"context": "13\\u2014])|$)///gi\r\n\t,\r\n\t\tosis: [\"Jonah\", \"Job\", \"Josh\", \"Joel\"]\r\n\t\tregexp: ///(^|#{bcv_parser::regexps.",
"end": 25281,
"score": 0.9997377395629883,
"start": 25277,
"tag": "NAME",
"value": "Josh"
},
{
"context": "])|$)///gi\r\n\t,\r\n\t\tosis: [\"Jonah\", \"Job\", \"Josh\", \"Joel\"]\r\n\t\tregexp: ///(^|#{bcv_parser::regexps.pre_book",
"end": 25289,
"score": 0.9995954632759094,
"start": 25285,
"tag": "NAME",
"value": "Joel"
},
{
"context": "[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)///gi\r\n\t,\r\n\t\tosis: [\"Judg\", \"Jude\"]\r\n\t\tregexp: ///(^|#{bcv_parser::regexps.",
"end": 25457,
"score": 0.9908638596534729,
"start": 25453,
"tag": "NAME",
"value": "Judg"
},
{
"context": "=~\\-\\u2013\\u2014])|$)///gi\r\n\t,\r\n\t\tosis: [\"Judg\", \"Jude\"]\r\n\t\tregexp: ///(^|#{bcv_parser::regexps.pre_book",
"end": 25465,
"score": 0.9844562411308289,
"start": 25461,
"tag": "NAME",
"value": "Jude"
},
{
"context": "\\-\\u2013\\u2014])|$)///gi\r\n\t,\r\n\t\tosis: [\"Phil\", \"Phlm\"]\r\n\t\tregexp: ///(^|#{bcv_parser::regexps.pre_book",
"end": 25641,
"score": 0.6132885217666626,
"start": 25639,
"tag": "NAME",
"value": "lm"
}
] | src/fr/regexps.coffee | phillipb/Bible-Passage-Reference-Parser | 149 | bcv_parser::regexps.space = "[\\s\\xa0]"
bcv_parser::regexps.escaped_passage = ///
(?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3`
(
# Start inverted book/chapter (cb)
(?:
(?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: \d+ (?: th | nd | st ) \s*
ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* )
)? # End inverted book/chapter (cb)
\x1f(\d+)(?:/\d+)?\x1f #book
(?:
/\d+\x1f #special Psalm chapters
| [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014]
| titre (?! [a-z] ) #could be followed by a number
| et(?!#{bcv_parser::regexps.space}+suivant) | et#{bcv_parser::regexps.space}+suivant | chapitres | chapitre | comparer | versets | verset | chap | vers | chs | ver | ch | vv | á | v
| [a-e] (?! \w ) #a-e allows 1:1a
| $ #or the end of the string
)+
)
///gi
# These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff.
bcv_parser::regexps.match_end_split = ///
\d \W* titre
| \d \W* et#{bcv_parser::regexps.space}+suivant (?: [\s\xa0*]* \.)?
| \d [\s\xa0*]* [a-e] (?! \w )
| \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis
| [\d\x1f]
///gi
bcv_parser::regexps.control = /[\x1e\x1f]/g
bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]"
bcv_parser::regexps.first = "(?:Premi[èe]res?|Premiers?|1[èe]?re|1er|1|I)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "(?:Deuxi[èe]mes?|2[èe]me|2d?e?|II)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "(?:Troisi[èe]mes?|3[èe]me|3e?|III)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|(?:et(?!#{bcv_parser::regexps.space}+suivant)|comparer)|á)"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|á)"
# Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself.
bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) ->
books = [
osis: ["Ps"]
apocrypha: true
extra: "2"
regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit.
Ps151
# Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own.
)(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS.
,
osis: ["Gen"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:G(?:e(?:n(?:[e\xE8]se)?)?|n))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ex(?:o(?:de?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bel(?:[\s\xa0]*et[\s\xa0]*le[\s\xa0]*(?:[Ss]erpent|[Dd]ragon))?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:[e\xE9](?:v(?:itique)?)?|v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:N(?:o(?:m(?:b(?:res)?)?)?|[bm]|um))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Eccl[e\xE9]siastiqu|Siracid)e|Sir?|Sagesse[\s\xa0]*de[\s\xa0]*Ben[\s\xa0]*Sira|La[\s\xa0]*Sagesse[\s\xa0]*de[\s\xa0]*Ben[\s\xa0]*Sira)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:agesse(?:[\s\xa0]*de[\s\xa0]*Salomon)?|g)|Wis)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:a(?:m(?:entations(?:[\s\xa0]*de[\s\xa0]*J[e\xE9]r[e\xE9]mie)?)?)?|m))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ep(?:(?:\.[\s\xa0]*J[e\xE9]r[e\xE9]|[\s\xa0]*J[e\xE9]r[e\xE9])mie|(?:\.[\s\xa0]*J[e\xE9]|[\s\xa0]*J[e\xE9]|Je)r|[i\xEE]tre[\s\xa0]*de[\s\xa0]*J[e\xE9]r[e\xE9]mie)|\xC9p(?:(?:\.[\s\xa0]*J[e\xE9]r[e\xE9]|[\s\xa0]*J[e\xE9]r[e\xE9])mie|(?:\.[\s\xa0]*J[e\xE9]|[\s\xa0]*J[e\xE9])r|[i\xEE]tre[\s\xa0]*de[\s\xa0]*J[e\xE9]r[e\xE9]mie))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ap(?:o(?:c(?:alypse(?:[\s\xa0]*de[\s\xa0]*Jean)?)?)?|c)?|Rev)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Pr(?:\.?[\s\xa0]*Manass[e\xE9]|(?:\.?[\s\xa0]*)?Man|i[e\xE8]re[\s\xa0]*de[\s\xa0]*Manass[e\xE9])|La[\s\xa0]*Pri[e\xE8]re[\s\xa0]*de[\s\xa0]*Manass[e\xE9])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:D(?:eu(?:t(?:[e\xE9]ronome)?)?|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jos(?:u[e\xE9]|h)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:u(?:g(?:es)?|dg)|g))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:R(?:u(?:th?)?|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Esdras)|(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Esdras|1(?:[\s\xa0]*Esdr|Esd|[\s\xa0]*Esd?)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Esdras|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Esdras)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Esdras)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Esdras|2(?:[\s\xa0]*Esdr|Esd|[\s\xa0]*Esd?)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Esdras|Deuxi[e\xE8]mes?[\s\xa0]*Esdras)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[EI\xC9]s(?:a(?:[i\xEF]e)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Samuel)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Samuel|2(?:[\s\xa0]*?Sam|[\s\xa0]*Sa?)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Samuel|Deuxi[e\xE8]mes?[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Samuel)|(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Samuel|1(?:[\s\xa0]*?Sam|[\s\xa0]*Sa?)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Samuel|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Rois)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Rois|2(?:Kgs|[\s\xa0]*R)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Rois|Deuxi[e\xE8]mes?[\s\xa0]*Rois)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:re\.)?[\s\xa0]*Rois)|(?:1re[\s\xa0]*Rois)|(?:(?:1(?:\xE8re|ere?)|I)[\s\xa0]*Rois|1(?:Kgs|[\s\xa0]*R)|(?:1(?:\xE8re|ere?)?|I)\.[\s\xa0]*Rois|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Rois)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Chroniques)|(?:2[\s\xa0]*Chron)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Chroniques|2(?:[\s\xa0]*Chro|Chr|[\s\xa0]*Chr?)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Chroniques|Deuxi[e\xE8]mes?[\s\xa0]*Chroniques)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Chroniques)|(?:1[\s\xa0]*Chron)|(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Chroniques|1(?:[\s\xa0]*Chro|Chr|[\s\xa0]*Chr?)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Chroniques|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Chroniques)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:E(?:sd(?:r(?:as)?)?|zra))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:N[e\xE9](?:h(?:[e\xE9]mie)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Esth(?:er[\s\xa0]*(?:[Gg]rec|[Gg]r|\([Gg]rec\))|[\s\xa0]*[Gg]r)|GkEsth)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Esth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Est(?:h(?:er)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Job"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jo?b)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ps(?:a(?:u(?:mes?)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Pr(?:i[e\xE8]re[\s\xa0]*d['’]Azaria[hs]|(?:\.[\s\xa0]*|[\s\xa0]*)?Azar)|La[\s\xa0]*Pri[e\xE8]re[\s\xa0]*d['’]Azaria[hs])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Pr(?:o(?:v(?:erbes)?)?|v)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ec(?:cl(?:[e\xE9]s(?:iaste)?)?)?|Qoheleth?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:C(?:antique[\s\xa0]*des[\s\xa0]*(?:Trois|3)[\s\xa0]*Enfants|t[\s\xa0]*3[\s\xa0]*E)|SgThree)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:C(?:a(?:ntique(?:[\s\xa0]*des[\s\xa0]*[Cc]antiques|s)?)?|n?t)|Song)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:[e\xE9](?:r(?:[e\xE9]m(?:ie)?)?)?|r))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez(?:e(?:ch(?:iel)?|k)?|\xE9ch(?:iel)?|\xE9)?|\xC9z[e\xE9]ch(?:iel)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:D(?:a(?:n(?:iel)?)?|n))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Os(?:[e\xE9]e)?|Hos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:o[e\xEB]l?|l))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Am(?:os?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ab(?:d(?:ias)?)?|Obad)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jonah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jon(?:a[hs])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mi(?:c(?:h(?:[e\xE9]e)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Na(?:h(?:oum|um)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ha(?:b(?:a(?:kuk|quq|k|c(?:uc)?))?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:So(?:ph(?:onie)?)?|Zeph)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ag(?:g(?:[e\xE9]e)?)?|Hag)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Z(?:a(?:c(?:c(?:h(?:arie)?)?|h(?:arie)?)?|h)?|ech|c))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:al(?:ac(?:h(?:ie)?)?|ch|c)?|l))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:at(?:t(?:h(?:ieu)?)?)?|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mark"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:ar[ck]?|[cr]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:u(?:ke|c)?|c))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Jea|1(?:Joh|[\s\xa0]*J|[\s\xa0]*Jea)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Jea|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Jea)n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Jea|2(?:Joh|[\s\xa0]*J|[\s\xa0]*Jea)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Jea|Deuxi[e\xE8]mes?[\s\xa0]*Jea)n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:3(?:e(?:me)?|\xE8me)|III)[\s\xa0]*Jea|3(?:Joh|[\s\xa0]*J|[\s\xa0]*Jea)|(?:3(?:e(?:me)?|\xE8me)?|III)\.[\s\xa0]*Jea|Troisi[e\xE8]mes?[\s\xa0]*Jea)n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["John"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:ea|oh)?n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ac(?:t(?:es(?:[\s\xa0]*des[\s\xa0]*Ap[o\xF4]tres)?|s)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:R(?:o(?:m(?:ains)?)?|m))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Corinthiens|2(?:[\s\xa0]*Corinthiens|[\s\xa0]*Cor?|Cor)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Corinthiens|Deuxi[e\xE8]mes?[\s\xa0]*Corinthiens)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Corinthiens|1(?:[\s\xa0]*Corinthiens|[\s\xa0]*Cor?|Cor)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Corinthiens|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Corinthiens)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:G(?:a(?:l(?:ates)?)?|l))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[E\xC9]p(?:h(?:[e\xE9](?:s(?:iens)?)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ph(?:il(?:ippiens)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Col(?:ossiens)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Thess?aloniciens)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Thess?aloniciens|2(?:[\s\xa0]*Th(?:ess|es)?|Thess)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Thess?aloniciens|Deuxi[e\xE8]me(?:s[\s\xa0]*Thess?|[\s\xa0]*Thess?)aloniciens)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Thess?aloniciens)|(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Thess?aloniciens|1(?:[\s\xa0]*Th(?:ess|es)?|Thess)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Thess?aloniciens|Premi(?:er(?:e(?:s[\s\xa0]*Thess?|[\s\xa0]*Thess?)|s[\s\xa0]*Thess?|[\s\xa0]*Thess?)|\xE8re(?:s[\s\xa0]*Thess?|[\s\xa0]*Thess?))aloniciens)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Timoth[e\xE9]e)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Timoth[e\xE9]e|2(?:(?:[\s\xa0]*Ti?|Ti)m|[\s\xa0]*Ti)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Timoth[e\xE9]e|Deuxi[e\xE8]me(?:s[\s\xa0]*Timoth[e\xE9]|[\s\xa0]*Timoth[e\xE9])e)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Timoth[e\xE9]e)|(?:Premi(?:er(?:e(?:s[\s\xa0]*Timoth[e\xE9]|[\s\xa0]*Timoth[e\xE9])|s[\s\xa0]*Timoth[e\xE9]|[\s\xa0]*Timoth[e\xE9])|\xE8re(?:s[\s\xa0]*Timoth[e\xE9]|[\s\xa0]*Timoth[e\xE9]))e|(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Timoth[e\xE9]e|1(?:(?:[\s\xa0]*Ti?|Ti)m|[\s\xa0]*Ti)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Timoth[e\xE9]e)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:it(?:us|e)?|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ph(?:il[e\xE9]mon|l?m))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:H[e\xE9](?:b(?:r(?:eux)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:a(?:c(?:q(?:ues)?)?|ques|s)?|c))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Pierre|Pet))|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Pierre|2[\s\xa0]*Pi?|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Pierre|Deuxi[e\xE8]mes?[\s\xa0]*Pierre)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*Pierre|Pet))|(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Pierre|1[\s\xa0]*Pi?|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Pierre|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Pierre)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:ude?|d))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:ob(?:ie)?|b))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:udith|dt))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ba(?:r(?:uch)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Su[sz](?:anne(?:[\s\xa0]*(?:et[\s\xa0]*les[\s\xa0]*(?:deux[\s\xa0]*)?vieillards|au[\s\xa0]*bain))?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Maccab[e\xE9]es)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Maccab[e\xE9]es|2(?:[\s\xa0]*?Macc|[\s\xa0]*M)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Maccab[e\xE9]es|Deuxi[e\xE8]me(?:s[\s\xa0]*Maccab[e\xE9]|[\s\xa0]*Maccab[e\xE9])es)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3[\s\xa0]*Maccab[e\xE9]es)|(?:(?:3(?:e(?:me)?|\xE8me)|III)[\s\xa0]*Maccab[e\xE9]es|3(?:[\s\xa0]*?Macc|[\s\xa0]*M)|(?:3(?:e(?:me)?|\xE8me)?|III)\.[\s\xa0]*Maccab[e\xE9]es|Troisi[e\xE8]me(?:s[\s\xa0]*Maccab[e\xE9]|[\s\xa0]*Maccab[e\xE9])es)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:4[\s\xa0]*Maccab[e\xE9]es)|(?:(?:4(?:e(?:me)?|\xE8me)|IV)[\s\xa0]*Maccab[e\xE9]es|4(?:[\s\xa0]*?Macc|[\s\xa0]*M)|(?:4(?:e(?:me)?|\xE8me)?|IV)\.[\s\xa0]*Maccab[e\xE9]es|Quatri[e\xE8]me(?:s[\s\xa0]*Maccab[e\xE9]|[\s\xa0]*Maccab[e\xE9])es)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Maccab[e\xE9]es)|(?:Premi(?:er(?:e(?:s[\s\xa0]*Maccab[e\xE9]|[\s\xa0]*Maccab[e\xE9])|s[\s\xa0]*Maccab[e\xE9]|[\s\xa0]*Maccab[e\xE9])|\xE8re(?:s[\s\xa0]*Maccab[e\xE9]|[\s\xa0]*Maccab[e\xE9]))es|(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Maccab[e\xE9]es|1(?:[\s\xa0]*?Macc|[\s\xa0]*M)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Maccab[e\xE9]es)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jonah", "Job", "Josh", "Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg", "Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ju)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil", "Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Phl?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
]
# Short-circuit the look if we know we want all the books.
return books if include_apocrypha is true and case_sensitive is "none"
# Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9.
out = []
for book in books
continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true
if case_sensitive is "books"
book.regexp = new RegExp book.regexp.source, "g"
out.push book
out
# Default to not using the Apocrypha
bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
| 152859 | bcv_parser::regexps.space = "[\\s\\xa0]"
bcv_parser::regexps.escaped_passage = ///
(?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3`
(
# Start inverted book/chapter (cb)
(?:
(?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: \d+ (?: th | nd | st ) \s*
ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* )
)? # End inverted book/chapter (cb)
\x1f(\d+)(?:/\d+)?\x1f #book
(?:
/\d+\x1f #special Psalm chapters
| [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014]
| titre (?! [a-z] ) #could be followed by a number
| et(?!#{bcv_parser::regexps.space}+suivant) | et#{bcv_parser::regexps.space}+suivant | chapitres | chapitre | comparer | versets | verset | chap | vers | chs | ver | ch | vv | á | v
| [a-e] (?! \w ) #a-e allows 1:1a
| $ #or the end of the string
)+
)
///gi
# These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff.
bcv_parser::regexps.match_end_split = ///
\d \W* titre
| \d \W* et#{bcv_parser::regexps.space}+suivant (?: [\s\xa0*]* \.)?
| \d [\s\xa0*]* [a-e] (?! \w )
| \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis
| [\d\x1f]
///gi
bcv_parser::regexps.control = /[\x1e\x1f]/g
bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]"
bcv_parser::regexps.first = "(?:Premi[èe]res?|Premiers?|1[èe]?re|1er|1|I)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "(?:Deuxi[èe]mes?|2[èe]me|2d?e?|II)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "(?:Troisi[èe]mes?|3[èe]me|3e?|III)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|(?:et(?!#{bcv_parser::regexps.space}+suivant)|comparer)|á)"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|á)"
# Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself.
bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) ->
books = [
osis: ["Ps"]
apocrypha: true
extra: "2"
regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit.
Ps151
# Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own.
)(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS.
,
osis: ["Gen"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:G(?:e(?:n(?:[e\xE8]se)?)?|n))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ex(?:o(?:de?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bel(?:[\s\xa0]*et[\s\xa0]*le[\s\xa0]*(?:[Ss]erpent|[Dd]ragon))?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:[e\xE9](?:v(?:itique)?)?|v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:N(?:o(?:m(?:b(?:res)?)?)?|[bm]|um))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Eccl[e\xE9]siastiqu|Siracid)e|Sir?|Sagesse[\s\xa0]*de[\s\xa0]*Ben[\s\xa0]*Sira|La[\s\xa0]*Sagesse[\s\xa0]*de[\s\xa0]*Ben[\s\xa0]*Sira)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:agesse(?:[\s\xa0]*de[\s\xa0]*Salomon)?|g)|Wis)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:a(?:m(?:entations(?:[\s\xa0]*de[\s\xa0]*J[e\xE9]r[e\xE9]mie)?)?)?|m))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ep(?:(?:\.[\s\xa0]*J[e\xE9]r[e\xE9]|[\s\xa0]*J[e\xE9]r[e\xE9])mie|(?:\.[\s\xa0]*J[e\xE9]|[\s\xa0]*J[e\xE9]|Je)r|[i\xEE]tre[\s\xa0]*de[\s\xa0]*J[e\xE9]r[e\xE9]mie)|\xC9p(?:(?:\.[\s\xa0]*J[e\xE9]r[e\xE9]|[\s\xa0]*J[e\xE9]r[e\xE9])mie|(?:\.[\s\xa0]*J[e\xE9]|[\s\xa0]*J[e\xE9])r|[i\xEE]tre[\s\xa0]*de[\s\xa0]*J[e\xE9]r[e\xE9]mie))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ap(?:o(?:c(?:alypse(?:[\s\xa0]*de[\s\xa0]*Jean)?)?)?|c)?|Rev)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Pr(?:\.?[\s\xa0]*Manass[e\xE9]|(?:\.?[\s\xa0]*)?Man|i[e\xE8]re[\s\xa0]*de[\s\xa0]*Manass[e\xE9])|La[\s\xa0]*Pri[e\xE8]re[\s\xa0]*de[\s\xa0]*Manass[e\xE9])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:D(?:eu(?:t(?:[e\xE9]ronome)?)?|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jos(?:u[e\xE9]|h)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:u(?:g(?:es)?|dg)|g))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:R(?:u(?:th?)?|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Esdras)|(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Esdras|1(?:[\s\xa0]*Esdr|Esd|[\s\xa0]*Esd?)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Esdras|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Esdras)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Esdras)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Esdras|2(?:[\s\xa0]*Esdr|Esd|[\s\xa0]*Esd?)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Esdras|Deuxi[e\xE8]mes?[\s\xa0]*Esdras)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[EI\xC9]s(?:a(?:[i\xEF]e)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Samuel)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Samuel|2(?:[\s\xa0]*?Sam|[\s\xa0]*Sa?)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Samuel|Deuxi[e\xE8]mes?[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Samuel)|(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Samuel|1(?:[\s\xa0]*?Sam|[\s\xa0]*Sa?)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Samuel|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Rois)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Rois|2(?:Kgs|[\s\xa0]*R)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Rois|Deuxi[e\xE8]mes?[\s\xa0]*Rois)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:re\.)?[\s\xa0]*Rois)|(?:1re[\s\xa0]*Rois)|(?:(?:1(?:\xE8re|ere?)|I)[\s\xa0]*Rois|1(?:Kgs|[\s\xa0]*R)|(?:1(?:\xE8re|ere?)?|I)\.[\s\xa0]*Rois|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Rois)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Chroniques)|(?:2[\s\xa0]*Chron)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Chroniques|2(?:[\s\xa0]*Chro|Chr|[\s\xa0]*Chr?)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Chroniques|Deuxi[e\xE8]mes?[\s\xa0]*Chroniques)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Chroniques)|(?:1[\s\xa0]*Chron)|(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Chroniques|1(?:[\s\xa0]*Chro|Chr|[\s\xa0]*Chr?)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Chroniques|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Chroniques)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:E(?:sd(?:r(?:as)?)?|zra))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:N[e\xE9](?:h(?:[e\xE9]mie)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Esth(?:er[\s\xa0]*(?:[Gg]rec|[Gg]r|\([Gg]rec\))|[\s\xa0]*[Gg]r)|GkEsth)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Esth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Est(?:h(?:er)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Job"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jo?b)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ps(?:a(?:u(?:mes?)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Pr(?:i[e\xE8]re[\s\xa0]*d['’]Azaria[hs]|(?:\.[\s\xa0]*|[\s\xa0]*)?Azar)|La[\s\xa0]*Pri[e\xE8]re[\s\xa0]*d['’]Azaria[hs])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Pr(?:o(?:v(?:erbes)?)?|v)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ec(?:cl(?:[e\xE9]s(?:iaste)?)?)?|Qoheleth?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:C(?:antique[\s\xa0]*des[\s\xa0]*(?:Trois|3)[\s\xa0]*Enfants|t[\s\xa0]*3[\s\xa0]*E)|SgThree)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:C(?:a(?:ntique(?:[\s\xa0]*des[\s\xa0]*[Cc]antiques|s)?)?|n?t)|Song)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:[e\xE9](?:r(?:[e\xE9]m(?:ie)?)?)?|r))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez(?:e(?:ch(?:iel)?|k)?|\xE9ch(?:iel)?|\xE9)?|\xC9z[e\xE9]ch(?:iel)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:D(?:a(?:n(?:iel)?)?|n))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Os(?:[e\xE9]e)?|Hos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:o[e\xEB]l?|l))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Am(?:os?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ab(?:d(?:ias)?)?|Obad)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jonah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jon(?:a[hs])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mi(?:c(?:h(?:[e\xE9]e)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Na(?:h(?:oum|um)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ha(?:b(?:a(?:kuk|quq|k|c(?:uc)?))?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:So(?:ph(?:onie)?)?|Zeph)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ag(?:g(?:[e\xE9]e)?)?|Hag)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Z(?:a(?:c(?:c(?:h(?:arie)?)?|h(?:arie)?)?|h)?|ech|c))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:al(?:ac(?:h(?:ie)?)?|ch|c)?|l))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:at(?:t(?:h(?:ieu)?)?)?|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mark"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:ar[ck]?|[cr]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:u(?:ke|c)?|c))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Jea|1(?:Joh|[\s\xa0]*J|[\s\xa0]*Jea)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Jea|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Jea)n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Jea|2(?:Joh|[\s\xa0]*J|[\s\xa0]*Jea)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Jea|Deuxi[e\xE8]mes?[\s\xa0]*Jea)n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:3(?:e(?:me)?|\xE8me)|III)[\s\xa0]*Jea|3(?:Joh|[\s\xa0]*J|[\s\xa0]*Jea)|(?:3(?:e(?:me)?|\xE8me)?|III)\.[\s\xa0]*Jea|Troisi[e\xE8]mes?[\s\xa0]*Jea)n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["John"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:ea|oh)?n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ac(?:t(?:es(?:[\s\xa0]*des[\s\xa0]*Ap[o\xF4]tres)?|s)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:R(?:o(?:m(?:ains)?)?|m))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Corinthiens|2(?:[\s\xa0]*Corinthiens|[\s\xa0]*Cor?|Cor)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Corinthiens|Deuxi[e\xE8]mes?[\s\xa0]*Corinthiens)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Corinthiens|1(?:[\s\xa0]*Corinthiens|[\s\xa0]*Cor?|Cor)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Corinthiens|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Corinthiens)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:G(?:a(?:l(?:ates)?)?|l))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[E\xC9]p(?:h(?:[e\xE9](?:s(?:iens)?)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ph(?:il(?:ippiens)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Col(?:ossiens)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Thess?aloniciens)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Thess?aloniciens|2(?:[\s\xa0]*Th(?:ess|es)?|Thess)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Thess?aloniciens|Deuxi[e\xE8]me(?:s[\s\xa0]*Thess?|[\s\xa0]*Thess?)aloniciens)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Thess?aloniciens)|(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Thess?aloniciens|1(?:[\s\xa0]*Th(?:ess|es)?|Thess)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Thess?aloniciens|Premi(?:er(?:e(?:s[\s\xa0]*Thess?|[\s\xa0]*Thess?)|s[\s\xa0]*Thess?|[\s\xa0]*Thess?)|\xE8re(?:s[\s\xa0]*Thess?|[\s\xa0]*Thess?))aloniciens)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Timoth[e\xE9]e)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Timoth[e\xE9]e|2(?:(?:[\s\xa0]*Ti?|Ti)m|[\s\xa0]*Ti)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Timoth[e\xE9]e|Deuxi[e\xE8]me(?:s[\s\xa0]*Timoth[e\xE9]|[\s\xa0]*Timoth[e\xE9])e)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Timoth[e\xE9]e)|(?:Premi(?:er(?:e(?:s[\s\xa0]*Timoth[e\xE9]|[\s\xa0]*Timoth[e\xE9])|s[\s\xa0]*Timoth[e\xE9]|[\s\xa0]*Timoth[e\xE9])|\xE8re(?:s[\s\xa0]*Timoth[e\xE9]|[\s\xa0]*Timoth[e\xE9]))e|(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Timoth[e\xE9]e|1(?:(?:[\s\xa0]*Ti?|Ti)m|[\s\xa0]*Ti)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Timoth[e\xE9]e)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:it(?:us|e)?|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ph(?:il[e\xE9]mon|l?m))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:H[e\xE9](?:b(?:r(?:eux)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:a(?:c(?:q(?:ues)?)?|ques|s)?|c))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Pierre|Pet))|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Pierre|2[\s\xa0]*Pi?|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Pierre|Deuxi[e\xE8]mes?[\s\xa0]*Pierre)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*Pierre|Pet))|(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Pierre|1[\s\xa0]*Pi?|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Pierre|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Pierre)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:ude?|d))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:ob(?:ie)?|b))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:udith|dt))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ba(?:r(?:uch)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Su[sz](?:anne(?:[\s\xa0]*(?:et[\s\xa0]*les[\s\xa0]*(?:deux[\s\xa0]*)?vieillards|au[\s\xa0]*bain))?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Maccab[e\xE9]es)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Maccab[e\xE9]es|2(?:[\s\xa0]*?Macc|[\s\xa0]*M)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Maccab[e\xE9]es|Deuxi[e\xE8]me(?:s[\s\xa0]*Maccab[e\xE9]|[\s\xa0]*Maccab[e\xE9])es)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3[\s\xa0]*Maccab[e\xE9]es)|(?:(?:3(?:e(?:me)?|\xE8me)|III)[\s\xa0]*Maccab[e\xE9]es|3(?:[\s\xa0]*?Macc|[\s\xa0]*M)|(?:3(?:e(?:me)?|\xE8me)?|III)\.[\s\xa0]*Maccab[e\xE9]es|Troisi[e\xE8]me(?:s[\s\xa0]*Maccab[e\xE9]|[\s\xa0]*Maccab[e\xE9])es)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:4[\s\xa0]*Maccab[e\xE9]es)|(?:(?:4(?:e(?:me)?|\xE8me)|IV)[\s\xa0]*Maccab[e\xE9]es|4(?:[\s\xa0]*?Macc|[\s\xa0]*M)|(?:4(?:e(?:me)?|\xE8me)?|IV)\.[\s\xa0]*Maccab[e\xE9]es|Quatri[e\xE8]me(?:s[\s\xa0]*Maccab[e\xE9]|[\s\xa0]*Maccab[e\xE9])es)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Maccab[e\xE9]es)|(?:Premi(?:er(?:e(?:s[\s\xa0]*Maccab[e\xE9]|[\s\xa0]*Maccab[e\xE9])|s[\s\xa0]*Maccab[e\xE9]|[\s\xa0]*Maccab[e\xE9])|\xE8re(?:s[\s\xa0]*Maccab[e\xE9]|[\s\xa0]*Maccab[e\xE9]))es|(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Maccab[e\xE9]es|1(?:[\s\xa0]*?Macc|[\s\xa0]*M)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Maccab[e\xE9]es)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["<NAME>", "<NAME>", "<NAME>", "<NAME>"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["<NAME>", "<NAME>"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ju)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil", "Ph<NAME>"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Phl?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
]
# Short-circuit the look if we know we want all the books.
return books if include_apocrypha is true and case_sensitive is "none"
# Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9.
out = []
for book in books
continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true
if case_sensitive is "books"
book.regexp = new RegExp book.regexp.source, "g"
out.push book
out
# Default to not using the Apocrypha
bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
| true | bcv_parser::regexps.space = "[\\s\\xa0]"
bcv_parser::regexps.escaped_passage = ///
(?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3`
(
# Start inverted book/chapter (cb)
(?:
(?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: \d+ (?: th | nd | st ) \s*
ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* )
)? # End inverted book/chapter (cb)
\x1f(\d+)(?:/\d+)?\x1f #book
(?:
/\d+\x1f #special Psalm chapters
| [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014]
| titre (?! [a-z] ) #could be followed by a number
| et(?!#{bcv_parser::regexps.space}+suivant) | et#{bcv_parser::regexps.space}+suivant | chapitres | chapitre | comparer | versets | verset | chap | vers | chs | ver | ch | vv | á | v
| [a-e] (?! \w ) #a-e allows 1:1a
| $ #or the end of the string
)+
)
///gi
# These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff.
bcv_parser::regexps.match_end_split = ///
\d \W* titre
| \d \W* et#{bcv_parser::regexps.space}+suivant (?: [\s\xa0*]* \.)?
| \d [\s\xa0*]* [a-e] (?! \w )
| \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis
| [\d\x1f]
///gi
bcv_parser::regexps.control = /[\x1e\x1f]/g
bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]"
bcv_parser::regexps.first = "(?:Premi[èe]res?|Premiers?|1[èe]?re|1er|1|I)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "(?:Deuxi[èe]mes?|2[èe]me|2d?e?|II)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "(?:Troisi[èe]mes?|3[èe]me|3e?|III)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|(?:et(?!#{bcv_parser::regexps.space}+suivant)|comparer)|á)"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|á)"
# Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself.
bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) ->
books = [
osis: ["Ps"]
apocrypha: true
extra: "2"
regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit.
Ps151
# Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own.
)(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS.
,
osis: ["Gen"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:G(?:e(?:n(?:[e\xE8]se)?)?|n))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ex(?:o(?:de?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bel(?:[\s\xa0]*et[\s\xa0]*le[\s\xa0]*(?:[Ss]erpent|[Dd]ragon))?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:[e\xE9](?:v(?:itique)?)?|v))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:N(?:o(?:m(?:b(?:res)?)?)?|[bm]|um))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Eccl[e\xE9]siastiqu|Siracid)e|Sir?|Sagesse[\s\xa0]*de[\s\xa0]*Ben[\s\xa0]*Sira|La[\s\xa0]*Sagesse[\s\xa0]*de[\s\xa0]*Ben[\s\xa0]*Sira)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:agesse(?:[\s\xa0]*de[\s\xa0]*Salomon)?|g)|Wis)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:a(?:m(?:entations(?:[\s\xa0]*de[\s\xa0]*J[e\xE9]r[e\xE9]mie)?)?)?|m))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ep(?:(?:\.[\s\xa0]*J[e\xE9]r[e\xE9]|[\s\xa0]*J[e\xE9]r[e\xE9])mie|(?:\.[\s\xa0]*J[e\xE9]|[\s\xa0]*J[e\xE9]|Je)r|[i\xEE]tre[\s\xa0]*de[\s\xa0]*J[e\xE9]r[e\xE9]mie)|\xC9p(?:(?:\.[\s\xa0]*J[e\xE9]r[e\xE9]|[\s\xa0]*J[e\xE9]r[e\xE9])mie|(?:\.[\s\xa0]*J[e\xE9]|[\s\xa0]*J[e\xE9])r|[i\xEE]tre[\s\xa0]*de[\s\xa0]*J[e\xE9]r[e\xE9]mie))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ap(?:o(?:c(?:alypse(?:[\s\xa0]*de[\s\xa0]*Jean)?)?)?|c)?|Rev)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Pr(?:\.?[\s\xa0]*Manass[e\xE9]|(?:\.?[\s\xa0]*)?Man|i[e\xE8]re[\s\xa0]*de[\s\xa0]*Manass[e\xE9])|La[\s\xa0]*Pri[e\xE8]re[\s\xa0]*de[\s\xa0]*Manass[e\xE9])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:D(?:eu(?:t(?:[e\xE9]ronome)?)?|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jos(?:u[e\xE9]|h)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:u(?:g(?:es)?|dg)|g))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:R(?:u(?:th?)?|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Esdras)|(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Esdras|1(?:[\s\xa0]*Esdr|Esd|[\s\xa0]*Esd?)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Esdras|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Esdras)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Esdras)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Esdras|2(?:[\s\xa0]*Esdr|Esd|[\s\xa0]*Esd?)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Esdras|Deuxi[e\xE8]mes?[\s\xa0]*Esdras)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[EI\xC9]s(?:a(?:[i\xEF]e)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Samuel)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Samuel|2(?:[\s\xa0]*?Sam|[\s\xa0]*Sa?)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Samuel|Deuxi[e\xE8]mes?[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Samuel)|(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Samuel|1(?:[\s\xa0]*?Sam|[\s\xa0]*Sa?)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Samuel|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Rois)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Rois|2(?:Kgs|[\s\xa0]*R)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Rois|Deuxi[e\xE8]mes?[\s\xa0]*Rois)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:re\.)?[\s\xa0]*Rois)|(?:1re[\s\xa0]*Rois)|(?:(?:1(?:\xE8re|ere?)|I)[\s\xa0]*Rois|1(?:Kgs|[\s\xa0]*R)|(?:1(?:\xE8re|ere?)?|I)\.[\s\xa0]*Rois|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Rois)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Chroniques)|(?:2[\s\xa0]*Chron)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Chroniques|2(?:[\s\xa0]*Chro|Chr|[\s\xa0]*Chr?)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Chroniques|Deuxi[e\xE8]mes?[\s\xa0]*Chroniques)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Chroniques)|(?:1[\s\xa0]*Chron)|(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Chroniques|1(?:[\s\xa0]*Chro|Chr|[\s\xa0]*Chr?)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Chroniques|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Chroniques)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:E(?:sd(?:r(?:as)?)?|zra))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:N[e\xE9](?:h(?:[e\xE9]mie)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Esth(?:er[\s\xa0]*(?:[Gg]rec|[Gg]r|\([Gg]rec\))|[\s\xa0]*[Gg]r)|GkEsth)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Esth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Est(?:h(?:er)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Job"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jo?b)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ps(?:a(?:u(?:mes?)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Pr(?:i[e\xE8]re[\s\xa0]*d['’]Azaria[hs]|(?:\.[\s\xa0]*|[\s\xa0]*)?Azar)|La[\s\xa0]*Pri[e\xE8]re[\s\xa0]*d['’]Azaria[hs])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Pr(?:o(?:v(?:erbes)?)?|v)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ec(?:cl(?:[e\xE9]s(?:iaste)?)?)?|Qoheleth?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:C(?:antique[\s\xa0]*des[\s\xa0]*(?:Trois|3)[\s\xa0]*Enfants|t[\s\xa0]*3[\s\xa0]*E)|SgThree)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:C(?:a(?:ntique(?:[\s\xa0]*des[\s\xa0]*[Cc]antiques|s)?)?|n?t)|Song)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:[e\xE9](?:r(?:[e\xE9]m(?:ie)?)?)?|r))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez(?:e(?:ch(?:iel)?|k)?|\xE9ch(?:iel)?|\xE9)?|\xC9z[e\xE9]ch(?:iel)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:D(?:a(?:n(?:iel)?)?|n))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Os(?:[e\xE9]e)?|Hos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:o[e\xEB]l?|l))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Am(?:os?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ab(?:d(?:ias)?)?|Obad)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jonah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jon(?:a[hs])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mi(?:c(?:h(?:[e\xE9]e)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Na(?:h(?:oum|um)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ha(?:b(?:a(?:kuk|quq|k|c(?:uc)?))?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:So(?:ph(?:onie)?)?|Zeph)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ag(?:g(?:[e\xE9]e)?)?|Hag)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Z(?:a(?:c(?:c(?:h(?:arie)?)?|h(?:arie)?)?|h)?|ech|c))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:al(?:ac(?:h(?:ie)?)?|ch|c)?|l))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:at(?:t(?:h(?:ieu)?)?)?|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mark"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:ar[ck]?|[cr]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:u(?:ke|c)?|c))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Jea|1(?:Joh|[\s\xa0]*J|[\s\xa0]*Jea)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Jea|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Jea)n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Jea|2(?:Joh|[\s\xa0]*J|[\s\xa0]*Jea)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Jea|Deuxi[e\xE8]mes?[\s\xa0]*Jea)n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:(?:3(?:e(?:me)?|\xE8me)|III)[\s\xa0]*Jea|3(?:Joh|[\s\xa0]*J|[\s\xa0]*Jea)|(?:3(?:e(?:me)?|\xE8me)?|III)\.[\s\xa0]*Jea|Troisi[e\xE8]mes?[\s\xa0]*Jea)n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["John"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:ea|oh)?n)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ac(?:t(?:es(?:[\s\xa0]*des[\s\xa0]*Ap[o\xF4]tres)?|s)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:R(?:o(?:m(?:ains)?)?|m))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Corinthiens|2(?:[\s\xa0]*Corinthiens|[\s\xa0]*Cor?|Cor)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Corinthiens|Deuxi[e\xE8]mes?[\s\xa0]*Corinthiens)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Corinthiens|1(?:[\s\xa0]*Corinthiens|[\s\xa0]*Cor?|Cor)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Corinthiens|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Corinthiens)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:G(?:a(?:l(?:ates)?)?|l))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[E\xC9]p(?:h(?:[e\xE9](?:s(?:iens)?)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ph(?:il(?:ippiens)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Col(?:ossiens)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Thess?aloniciens)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Thess?aloniciens|2(?:[\s\xa0]*Th(?:ess|es)?|Thess)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Thess?aloniciens|Deuxi[e\xE8]me(?:s[\s\xa0]*Thess?|[\s\xa0]*Thess?)aloniciens)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Thess?aloniciens)|(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Thess?aloniciens|1(?:[\s\xa0]*Th(?:ess|es)?|Thess)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Thess?aloniciens|Premi(?:er(?:e(?:s[\s\xa0]*Thess?|[\s\xa0]*Thess?)|s[\s\xa0]*Thess?|[\s\xa0]*Thess?)|\xE8re(?:s[\s\xa0]*Thess?|[\s\xa0]*Thess?))aloniciens)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Timoth[e\xE9]e)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Timoth[e\xE9]e|2(?:(?:[\s\xa0]*Ti?|Ti)m|[\s\xa0]*Ti)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Timoth[e\xE9]e|Deuxi[e\xE8]me(?:s[\s\xa0]*Timoth[e\xE9]|[\s\xa0]*Timoth[e\xE9])e)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Timoth[e\xE9]e)|(?:Premi(?:er(?:e(?:s[\s\xa0]*Timoth[e\xE9]|[\s\xa0]*Timoth[e\xE9])|s[\s\xa0]*Timoth[e\xE9]|[\s\xa0]*Timoth[e\xE9])|\xE8re(?:s[\s\xa0]*Timoth[e\xE9]|[\s\xa0]*Timoth[e\xE9]))e|(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Timoth[e\xE9]e|1(?:(?:[\s\xa0]*Ti?|Ti)m|[\s\xa0]*Ti)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Timoth[e\xE9]e)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:it(?:us|e)?|t))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ph(?:il[e\xE9]mon|l?m))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:H[e\xE9](?:b(?:r(?:eux)?)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:a(?:c(?:q(?:ues)?)?|ques|s)?|c))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Pierre|Pet))|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Pierre|2[\s\xa0]*Pi?|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Pierre|Deuxi[e\xE8]mes?[\s\xa0]*Pierre)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*Pierre|Pet))|(?:(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Pierre|1[\s\xa0]*Pi?|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Pierre|Premi(?:er(?:es?|s)?|\xE8res?)[\s\xa0]*Pierre)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:ude?|d))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:ob(?:ie)?|b))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:udith|dt))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ba(?:r(?:uch)?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Su[sz](?:anne(?:[\s\xa0]*(?:et[\s\xa0]*les[\s\xa0]*(?:deux[\s\xa0]*)?vieillards|au[\s\xa0]*bain))?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Maccab[e\xE9]es)|(?:(?:2(?:\xE8me|de?|e(?:me)?)|II)[\s\xa0]*Maccab[e\xE9]es|2(?:[\s\xa0]*?Macc|[\s\xa0]*M)|(?:2(?:\xE8me|de|d|e(?:me)?)?|II)\.[\s\xa0]*Maccab[e\xE9]es|Deuxi[e\xE8]me(?:s[\s\xa0]*Maccab[e\xE9]|[\s\xa0]*Maccab[e\xE9])es)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3[\s\xa0]*Maccab[e\xE9]es)|(?:(?:3(?:e(?:me)?|\xE8me)|III)[\s\xa0]*Maccab[e\xE9]es|3(?:[\s\xa0]*?Macc|[\s\xa0]*M)|(?:3(?:e(?:me)?|\xE8me)?|III)\.[\s\xa0]*Maccab[e\xE9]es|Troisi[e\xE8]me(?:s[\s\xa0]*Maccab[e\xE9]|[\s\xa0]*Maccab[e\xE9])es)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:4[\s\xa0]*Maccab[e\xE9]es)|(?:(?:4(?:e(?:me)?|\xE8me)|IV)[\s\xa0]*Maccab[e\xE9]es|4(?:[\s\xa0]*?Macc|[\s\xa0]*M)|(?:4(?:e(?:me)?|\xE8me)?|IV)\.[\s\xa0]*Maccab[e\xE9]es|Quatri[e\xE8]me(?:s[\s\xa0]*Maccab[e\xE9]|[\s\xa0]*Maccab[e\xE9])es)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Maccab[e\xE9]es)|(?:Premi(?:er(?:e(?:s[\s\xa0]*Maccab[e\xE9]|[\s\xa0]*Maccab[e\xE9])|s[\s\xa0]*Maccab[e\xE9]|[\s\xa0]*Maccab[e\xE9])|\xE8re(?:s[\s\xa0]*Maccab[e\xE9]|[\s\xa0]*Maccab[e\xE9]))es|(?:1(?:\xE8?re|ere?)|I)[\s\xa0]*Maccab[e\xE9]es|1(?:[\s\xa0]*?Macc|[\s\xa0]*M)|(?:1(?:\xE8?re|ere?)?|I)\.[\s\xa0]*Maccab[e\xE9]es)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jo)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ju)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil", "PhPI:NAME:<NAME>END_PI"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Phl?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
]
# Short-circuit the look if we know we want all the books.
return books if include_apocrypha is true and case_sensitive is "none"
# Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9.
out = []
for book in books
continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true
if case_sensitive is "books"
book.regexp = new RegExp book.regexp.source, "g"
out.push book
out
# Default to not using the Apocrypha
bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
|
[
{
"context": "class HelloWorld\n hello: (name = 'World') ->\n \"Hello, #{name}!\"\n\nmodule.exports = Hell",
"end": 40,
"score": 0.9424713850021362,
"start": 35,
"tag": "NAME",
"value": "World"
}
] | coffeescript/hello-world/hello_world.coffee | rootulp/exercism | 41 | class HelloWorld
hello: (name = 'World') ->
"Hello, #{name}!"
module.exports = HelloWorld
| 127653 | class HelloWorld
hello: (name = '<NAME>') ->
"Hello, #{name}!"
module.exports = HelloWorld
| true | class HelloWorld
hello: (name = 'PI:NAME:<NAME>END_PI') ->
"Hello, #{name}!"
module.exports = HelloWorld
|
[
{
"context": "ema for the Post table in the database.\n * @module mystic-noggin\n * @submodule server/database/schemas/post-schema",
"end": 79,
"score": 0.6436048150062561,
"start": 66,
"tag": "USERNAME",
"value": "mystic-noggin"
},
{
"context": " Date.now }\n name: { type: String, default: 'Anonymous' }\n ]\n )\n\n Post = mongoose.model('Post', pos",
"end": 2501,
"score": 0.8368548154830933,
"start": 2492,
"tag": "NAME",
"value": "Anonymous"
}
] | src/server/database/schemas/post-schema.coffee | ingshtrom/mystic-noggin | 0 | ###
* Post Schema for the Post table in the database.
* @module mystic-noggin
* @submodule server/database/schemas/post-schema
* @requires {module} mongoose
* @requires {module} bluebird
* @requires {submodule} server/database/schemas/tag-schema
* @requires {submodule} server/database/schemas/post-type-schema
* @requires {submodule} server/database/schemas/user-schema
###
mongoose = require('mongoose')
P = require 'bluebird'
tagsSchema = require('./tag-schema').schema
postTypeSchema = require('./post-type-schema').schema
userSchema = require('./user-schema').schema
logger = require('../../logger').logger
###
* The model for Posts. This can
* be assumed to be set because
* load() should be called on startup.
* @type {object}
###
module.exports.model = {}
###
* The schema for Posts. This can
* be assumed to be set because
* load() should be called on app startup.
* @type {object}
###
module.exports.schema = {}
###
* Load up this schema and set the model.
* This should be called while the app is
* starting up (in ./_bootstrap.load())
* @function load
* @return {void}
###
module.exports.load = ->
Schema = mongoose.Schema
###
@schema Post
@param {string} title
@param {objectid,required} author - see (server/database/schemas/user-schema)
@param {date,default=Date.now} created
@param {date,default=Date.now} updated
@param {string,required} content
@param {objectid,required} type - see (server/database/schemas/post-schema)
@param {[objectid]} tags - see (server/database/schemas/tag-schema)
@param {[document]} comments
@param {string,required} comments.body
@param {date,default=Date.now} comments.date
@param {string,default="Anonymous"} comments.name
###
module.exports.schema = postSchema = new Schema(
title: { type: String, unique: true }
author: { type: Schema.Types.ObjectId, ref: 'User', require: true }
created: { type: Date, default: Date.now }
updated: { type: Date, default: Date.now }
content: { type: String, required: true, unique: true }
type: { type: Schema.Types.ObjectId, ref: 'PostType', required: true }
tags: [{ type: Schema.Types.ObjectId, ref: 'Tag' }]
comments: [
body: { type: String, required: true }
date: { type: Date, default: Date.now }
name: { type: String, default: 'Anonymous' }
]
)
Post = mongoose.model('Post', postSchema)
P.promisifyAll(Post)
P.promisifyAll(Post.prototype)
module.exports.model = Post
logger.debug 'loaded Post model into mongoose'
| 69805 | ###
* Post Schema for the Post table in the database.
* @module mystic-noggin
* @submodule server/database/schemas/post-schema
* @requires {module} mongoose
* @requires {module} bluebird
* @requires {submodule} server/database/schemas/tag-schema
* @requires {submodule} server/database/schemas/post-type-schema
* @requires {submodule} server/database/schemas/user-schema
###
mongoose = require('mongoose')
P = require 'bluebird'
tagsSchema = require('./tag-schema').schema
postTypeSchema = require('./post-type-schema').schema
userSchema = require('./user-schema').schema
logger = require('../../logger').logger
###
* The model for Posts. This can
* be assumed to be set because
* load() should be called on startup.
* @type {object}
###
module.exports.model = {}
###
* The schema for Posts. This can
* be assumed to be set because
* load() should be called on app startup.
* @type {object}
###
module.exports.schema = {}
###
* Load up this schema and set the model.
* This should be called while the app is
* starting up (in ./_bootstrap.load())
* @function load
* @return {void}
###
module.exports.load = ->
Schema = mongoose.Schema
###
@schema Post
@param {string} title
@param {objectid,required} author - see (server/database/schemas/user-schema)
@param {date,default=Date.now} created
@param {date,default=Date.now} updated
@param {string,required} content
@param {objectid,required} type - see (server/database/schemas/post-schema)
@param {[objectid]} tags - see (server/database/schemas/tag-schema)
@param {[document]} comments
@param {string,required} comments.body
@param {date,default=Date.now} comments.date
@param {string,default="Anonymous"} comments.name
###
module.exports.schema = postSchema = new Schema(
title: { type: String, unique: true }
author: { type: Schema.Types.ObjectId, ref: 'User', require: true }
created: { type: Date, default: Date.now }
updated: { type: Date, default: Date.now }
content: { type: String, required: true, unique: true }
type: { type: Schema.Types.ObjectId, ref: 'PostType', required: true }
tags: [{ type: Schema.Types.ObjectId, ref: 'Tag' }]
comments: [
body: { type: String, required: true }
date: { type: Date, default: Date.now }
name: { type: String, default: '<NAME>' }
]
)
Post = mongoose.model('Post', postSchema)
P.promisifyAll(Post)
P.promisifyAll(Post.prototype)
module.exports.model = Post
logger.debug 'loaded Post model into mongoose'
| true | ###
* Post Schema for the Post table in the database.
* @module mystic-noggin
* @submodule server/database/schemas/post-schema
* @requires {module} mongoose
* @requires {module} bluebird
* @requires {submodule} server/database/schemas/tag-schema
* @requires {submodule} server/database/schemas/post-type-schema
* @requires {submodule} server/database/schemas/user-schema
###
mongoose = require('mongoose')
P = require 'bluebird'
tagsSchema = require('./tag-schema').schema
postTypeSchema = require('./post-type-schema').schema
userSchema = require('./user-schema').schema
logger = require('../../logger').logger
###
* The model for Posts. This can
* be assumed to be set because
* load() should be called on startup.
* @type {object}
###
module.exports.model = {}
###
* The schema for Posts. This can
* be assumed to be set because
* load() should be called on app startup.
* @type {object}
###
module.exports.schema = {}
###
* Load up this schema and set the model.
* This should be called while the app is
* starting up (in ./_bootstrap.load())
* @function load
* @return {void}
###
module.exports.load = ->
Schema = mongoose.Schema
###
@schema Post
@param {string} title
@param {objectid,required} author - see (server/database/schemas/user-schema)
@param {date,default=Date.now} created
@param {date,default=Date.now} updated
@param {string,required} content
@param {objectid,required} type - see (server/database/schemas/post-schema)
@param {[objectid]} tags - see (server/database/schemas/tag-schema)
@param {[document]} comments
@param {string,required} comments.body
@param {date,default=Date.now} comments.date
@param {string,default="Anonymous"} comments.name
###
module.exports.schema = postSchema = new Schema(
title: { type: String, unique: true }
author: { type: Schema.Types.ObjectId, ref: 'User', require: true }
created: { type: Date, default: Date.now }
updated: { type: Date, default: Date.now }
content: { type: String, required: true, unique: true }
type: { type: Schema.Types.ObjectId, ref: 'PostType', required: true }
tags: [{ type: Schema.Types.ObjectId, ref: 'Tag' }]
comments: [
body: { type: String, required: true }
date: { type: Date, default: Date.now }
name: { type: String, default: 'PI:NAME:<NAME>END_PI' }
]
)
Post = mongoose.model('Post', postSchema)
P.promisifyAll(Post)
P.promisifyAll(Post.prototype)
module.exports.model = Post
logger.debug 'loaded Post model into mongoose'
|
[
{
"context": "8'\n window.Templates.user(users: ['fred', 'steve']).should.equal userFile\n ",
"end": 1031,
"score": 0.974148690700531,
"start": 1027,
"tag": "NAME",
"value": "fred"
},
{
"context": " window.Templates.user(users: ['fred', 'steve']).should.equal userFile\n done()\n\n",
"end": 1040,
"score": 0.8959623575210571,
"start": 1035,
"tag": "NAME",
"value": "steve"
},
{
"context": "8'\n window.Templates.user(users: ['fred', 'steve']).should.equal userFile\n ",
"end": 2105,
"score": 0.955488920211792,
"start": 2101,
"tag": "NAME",
"value": "fred"
},
{
"context": " window.Templates.user(users: ['fred', 'steve']).should.equal userFile\n dependen",
"end": 2114,
"score": 0.6631115674972534,
"start": 2109,
"tag": "NAME",
"value": "steve"
},
{
"context": "8'\n window.Templates.user(users: ['fred', 'steve']).should.equal userFile\n ",
"end": 3184,
"score": 0.7071317434310913,
"start": 3180,
"tag": "USERNAME",
"value": "fred"
},
{
"context": " window.Templates.user(users: ['fred', 'steve']).should.equal userFile\n done()\n\n",
"end": 3193,
"score": 0.7132296562194824,
"start": 3188,
"tag": "USERNAME",
"value": "steve"
}
] | test/jade.coffee | lgs/asset-rack | 1 |
should = require('chai').should()
rack = require '../.'
express = require 'express.io'
easyrequest = require 'request'
fs = require 'fs'
describe 'a jade asset', ->
app = null
fixturesDir = "#{__dirname}/fixtures/jade"
it 'should work', (done) ->
compiled = fs.readFileSync "#{fixturesDir}/templates.js", 'utf8'
app = express().http()
app.use new rack.JadeAsset
dirname: fixturesDir
url: '/templates.js'
app.listen 7076, ->
easyrequest 'http://localhost:7076/templates.js', (error, response, body) ->
response.headers['content-type'].should.equal 'text/javascript'
body.should.equal compiled
window = {}
eval(body)
testFile = fs.readFileSync "#{fixturesDir}/test.html", 'utf8'
window.Templates.test().should.equal testFile
userFile = fs.readFileSync "#{fixturesDir}/user.html", 'utf8'
window.Templates.user(users: ['fred', 'steve']).should.equal userFile
done()
it 'should work in a rack', (done) ->
compiled = fs.readFileSync "#{fixturesDir}/templates-rack.js", 'utf8'
app = express().http()
app.use new rack.AssetRack [
new rack.Asset
url: '/image.png'
contents: fs.readFileSync "#{fixturesDir}/image.png", 'utf8'
new rack.JadeAsset
dirname: fixturesDir
url: '/templates-rack.js'
]
app.listen 7076, ->
easyrequest 'http://localhost:7076/templates-rack.js', (error, response, body) ->
response.headers['content-type'].should.equal 'text/javascript'
body.should.equal compiled
window = {}
eval(body)
testFile = fs.readFileSync "#{fixturesDir}/test.html", 'utf8'
window.Templates.test().should.equal testFile
userFile = fs.readFileSync "#{fixturesDir}/user.html", 'utf8'
window.Templates.user(users: ['fred', 'steve']).should.equal userFile
dependencyFile = fs.readFileSync "#{fixturesDir}/dependency.html", 'utf8'
window.Templates.dependency().should.equal dependencyFile
done()
it 'should work compressed', (done) ->
compiled = fs.readFileSync "#{fixturesDir}/templates.min.js", 'utf8'
app = express().http()
app.use new rack.JadeAsset
dirname: "#{fixturesDir}"
url: '/templates.min.js'
compress: true
app.listen 7076, ->
easyrequest 'http://localhost:7076/templates.min.js', (error, response, body) ->
response.headers['content-type'].should.equal 'text/javascript'
body.should.equal compiled
window = {}
eval(body)
testFile = fs.readFileSync "#{fixturesDir}/test.html", 'utf8'
window.Templates.test().should.equal testFile
userFile = fs.readFileSync "#{fixturesDir}/user.html", 'utf8'
window.Templates.user(users: ['fred', 'steve']).should.equal userFile
done()
afterEach (done) -> process.nextTick ->
app.server.close done
| 225481 |
should = require('chai').should()
rack = require '../.'
express = require 'express.io'
easyrequest = require 'request'
fs = require 'fs'
describe 'a jade asset', ->
app = null
fixturesDir = "#{__dirname}/fixtures/jade"
it 'should work', (done) ->
compiled = fs.readFileSync "#{fixturesDir}/templates.js", 'utf8'
app = express().http()
app.use new rack.JadeAsset
dirname: fixturesDir
url: '/templates.js'
app.listen 7076, ->
easyrequest 'http://localhost:7076/templates.js', (error, response, body) ->
response.headers['content-type'].should.equal 'text/javascript'
body.should.equal compiled
window = {}
eval(body)
testFile = fs.readFileSync "#{fixturesDir}/test.html", 'utf8'
window.Templates.test().should.equal testFile
userFile = fs.readFileSync "#{fixturesDir}/user.html", 'utf8'
window.Templates.user(users: ['<NAME>', '<NAME>']).should.equal userFile
done()
it 'should work in a rack', (done) ->
compiled = fs.readFileSync "#{fixturesDir}/templates-rack.js", 'utf8'
app = express().http()
app.use new rack.AssetRack [
new rack.Asset
url: '/image.png'
contents: fs.readFileSync "#{fixturesDir}/image.png", 'utf8'
new rack.JadeAsset
dirname: fixturesDir
url: '/templates-rack.js'
]
app.listen 7076, ->
easyrequest 'http://localhost:7076/templates-rack.js', (error, response, body) ->
response.headers['content-type'].should.equal 'text/javascript'
body.should.equal compiled
window = {}
eval(body)
testFile = fs.readFileSync "#{fixturesDir}/test.html", 'utf8'
window.Templates.test().should.equal testFile
userFile = fs.readFileSync "#{fixturesDir}/user.html", 'utf8'
window.Templates.user(users: ['<NAME>', '<NAME>']).should.equal userFile
dependencyFile = fs.readFileSync "#{fixturesDir}/dependency.html", 'utf8'
window.Templates.dependency().should.equal dependencyFile
done()
it 'should work compressed', (done) ->
compiled = fs.readFileSync "#{fixturesDir}/templates.min.js", 'utf8'
app = express().http()
app.use new rack.JadeAsset
dirname: "#{fixturesDir}"
url: '/templates.min.js'
compress: true
app.listen 7076, ->
easyrequest 'http://localhost:7076/templates.min.js', (error, response, body) ->
response.headers['content-type'].should.equal 'text/javascript'
body.should.equal compiled
window = {}
eval(body)
testFile = fs.readFileSync "#{fixturesDir}/test.html", 'utf8'
window.Templates.test().should.equal testFile
userFile = fs.readFileSync "#{fixturesDir}/user.html", 'utf8'
window.Templates.user(users: ['fred', 'steve']).should.equal userFile
done()
afterEach (done) -> process.nextTick ->
app.server.close done
| true |
should = require('chai').should()
rack = require '../.'
express = require 'express.io'
easyrequest = require 'request'
fs = require 'fs'
describe 'a jade asset', ->
app = null
fixturesDir = "#{__dirname}/fixtures/jade"
it 'should work', (done) ->
compiled = fs.readFileSync "#{fixturesDir}/templates.js", 'utf8'
app = express().http()
app.use new rack.JadeAsset
dirname: fixturesDir
url: '/templates.js'
app.listen 7076, ->
easyrequest 'http://localhost:7076/templates.js', (error, response, body) ->
response.headers['content-type'].should.equal 'text/javascript'
body.should.equal compiled
window = {}
eval(body)
testFile = fs.readFileSync "#{fixturesDir}/test.html", 'utf8'
window.Templates.test().should.equal testFile
userFile = fs.readFileSync "#{fixturesDir}/user.html", 'utf8'
window.Templates.user(users: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']).should.equal userFile
done()
it 'should work in a rack', (done) ->
compiled = fs.readFileSync "#{fixturesDir}/templates-rack.js", 'utf8'
app = express().http()
app.use new rack.AssetRack [
new rack.Asset
url: '/image.png'
contents: fs.readFileSync "#{fixturesDir}/image.png", 'utf8'
new rack.JadeAsset
dirname: fixturesDir
url: '/templates-rack.js'
]
app.listen 7076, ->
easyrequest 'http://localhost:7076/templates-rack.js', (error, response, body) ->
response.headers['content-type'].should.equal 'text/javascript'
body.should.equal compiled
window = {}
eval(body)
testFile = fs.readFileSync "#{fixturesDir}/test.html", 'utf8'
window.Templates.test().should.equal testFile
userFile = fs.readFileSync "#{fixturesDir}/user.html", 'utf8'
window.Templates.user(users: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']).should.equal userFile
dependencyFile = fs.readFileSync "#{fixturesDir}/dependency.html", 'utf8'
window.Templates.dependency().should.equal dependencyFile
done()
it 'should work compressed', (done) ->
compiled = fs.readFileSync "#{fixturesDir}/templates.min.js", 'utf8'
app = express().http()
app.use new rack.JadeAsset
dirname: "#{fixturesDir}"
url: '/templates.min.js'
compress: true
app.listen 7076, ->
easyrequest 'http://localhost:7076/templates.min.js', (error, response, body) ->
response.headers['content-type'].should.equal 'text/javascript'
body.should.equal compiled
window = {}
eval(body)
testFile = fs.readFileSync "#{fixturesDir}/test.html", 'utf8'
window.Templates.test().should.equal testFile
userFile = fs.readFileSync "#{fixturesDir}/user.html", 'utf8'
window.Templates.user(users: ['fred', 'steve']).should.equal userFile
done()
afterEach (done) -> process.nextTick ->
app.server.close done
|
[
{
"context": "ation.ConfigError()\n\t\t\treturn\n\n\t\tcredentialToken = Random.secret()\n\t\tloginStyle = OAuth._loginStyle @name, ",
"end": 2059,
"score": 0.44245538115501404,
"start": 2053,
"tag": "KEY",
"value": "Random"
}
] | packages/rocketchat-custom-oauth/custom_oauth_client.coffee | dotdatait/prueba | 2 | # Request custom OAuth credentials for the user
# @param options {optional}
# @param credentialRequestCompleteCallback {Function} Callback function to call on
# completion. Takes one argument, credentialToken on success, or Error on
# error.
class CustomOAuth
constructor: (@name, options) ->
if not Match.test @name, String
return throw new Meteor.Error 'CustomOAuth: Name is required and must be String'
@configure options
Accounts.oauth.registerService @name
@configureLogin()
configure: (options) ->
if not Match.test options, Object
return throw new Meteor.Error 'CustomOAuth: Options is required and must be Object'
if not Match.test options.serverURL, String
return throw new Meteor.Error 'CustomOAuth: Options.serverURL is required and must be String'
if not Match.test options.authorizePath, String
options.authorizePath = '/oauth/authorize'
if not Match.test options.scope, String
options.scope = 'openid'
@serverURL = options.serverURL
@authorizePath = options.authorizePath
@scope = options.scope
if not /^https?:\/\/.+/.test @authorizePath
@authorizePath = @serverURL + @authorizePath
configureLogin: ->
self = @
loginWithService = "loginWith" + s.capitalize(@name)
Meteor[loginWithService] = (options, callback) ->
# support a callback without options
if not callback and typeof options is "function"
callback = options
options = null
credentialRequestCompleteCallback = Accounts.oauth.credentialRequestCompleteHandler(callback)
self.requestCredential(options, credentialRequestCompleteCallback)
requestCredential: (options, credentialRequestCompleteCallback) ->
# support both (options, callback) and (callback).
if not credentialRequestCompleteCallback and typeof options is 'function'
credentialRequestCompleteCallback = options
options = {}
config = ServiceConfiguration.configurations.findOne service: @name
if not config
credentialRequestCompleteCallback? new ServiceConfiguration.ConfigError()
return
credentialToken = Random.secret()
loginStyle = OAuth._loginStyle @name, config, options
loginUrl = @authorizePath +
'?client_id=' + config.clientId +
'&redirect_uri=' + OAuth._redirectUri(@name, config) +
'&response_type=code' +
'&state=' + OAuth._stateParam(loginStyle, credentialToken, options.redirectUrl) +
'&scope=' + @scope
OAuth.launchLogin
loginService: @name
loginStyle: loginStyle
loginUrl: loginUrl
credentialRequestCompleteCallback: credentialRequestCompleteCallback
credentialToken: credentialToken
popupOptions:
width: 900
height: 450
| 159363 | # Request custom OAuth credentials for the user
# @param options {optional}
# @param credentialRequestCompleteCallback {Function} Callback function to call on
# completion. Takes one argument, credentialToken on success, or Error on
# error.
class CustomOAuth
constructor: (@name, options) ->
if not Match.test @name, String
return throw new Meteor.Error 'CustomOAuth: Name is required and must be String'
@configure options
Accounts.oauth.registerService @name
@configureLogin()
configure: (options) ->
if not Match.test options, Object
return throw new Meteor.Error 'CustomOAuth: Options is required and must be Object'
if not Match.test options.serverURL, String
return throw new Meteor.Error 'CustomOAuth: Options.serverURL is required and must be String'
if not Match.test options.authorizePath, String
options.authorizePath = '/oauth/authorize'
if not Match.test options.scope, String
options.scope = 'openid'
@serverURL = options.serverURL
@authorizePath = options.authorizePath
@scope = options.scope
if not /^https?:\/\/.+/.test @authorizePath
@authorizePath = @serverURL + @authorizePath
configureLogin: ->
self = @
loginWithService = "loginWith" + s.capitalize(@name)
Meteor[loginWithService] = (options, callback) ->
# support a callback without options
if not callback and typeof options is "function"
callback = options
options = null
credentialRequestCompleteCallback = Accounts.oauth.credentialRequestCompleteHandler(callback)
self.requestCredential(options, credentialRequestCompleteCallback)
requestCredential: (options, credentialRequestCompleteCallback) ->
# support both (options, callback) and (callback).
if not credentialRequestCompleteCallback and typeof options is 'function'
credentialRequestCompleteCallback = options
options = {}
config = ServiceConfiguration.configurations.findOne service: @name
if not config
credentialRequestCompleteCallback? new ServiceConfiguration.ConfigError()
return
credentialToken = <KEY>.secret()
loginStyle = OAuth._loginStyle @name, config, options
loginUrl = @authorizePath +
'?client_id=' + config.clientId +
'&redirect_uri=' + OAuth._redirectUri(@name, config) +
'&response_type=code' +
'&state=' + OAuth._stateParam(loginStyle, credentialToken, options.redirectUrl) +
'&scope=' + @scope
OAuth.launchLogin
loginService: @name
loginStyle: loginStyle
loginUrl: loginUrl
credentialRequestCompleteCallback: credentialRequestCompleteCallback
credentialToken: credentialToken
popupOptions:
width: 900
height: 450
| true | # Request custom OAuth credentials for the user
# @param options {optional}
# @param credentialRequestCompleteCallback {Function} Callback function to call on
# completion. Takes one argument, credentialToken on success, or Error on
# error.
class CustomOAuth
constructor: (@name, options) ->
if not Match.test @name, String
return throw new Meteor.Error 'CustomOAuth: Name is required and must be String'
@configure options
Accounts.oauth.registerService @name
@configureLogin()
configure: (options) ->
if not Match.test options, Object
return throw new Meteor.Error 'CustomOAuth: Options is required and must be Object'
if not Match.test options.serverURL, String
return throw new Meteor.Error 'CustomOAuth: Options.serverURL is required and must be String'
if not Match.test options.authorizePath, String
options.authorizePath = '/oauth/authorize'
if not Match.test options.scope, String
options.scope = 'openid'
@serverURL = options.serverURL
@authorizePath = options.authorizePath
@scope = options.scope
if not /^https?:\/\/.+/.test @authorizePath
@authorizePath = @serverURL + @authorizePath
configureLogin: ->
self = @
loginWithService = "loginWith" + s.capitalize(@name)
Meteor[loginWithService] = (options, callback) ->
# support a callback without options
if not callback and typeof options is "function"
callback = options
options = null
credentialRequestCompleteCallback = Accounts.oauth.credentialRequestCompleteHandler(callback)
self.requestCredential(options, credentialRequestCompleteCallback)
requestCredential: (options, credentialRequestCompleteCallback) ->
# support both (options, callback) and (callback).
if not credentialRequestCompleteCallback and typeof options is 'function'
credentialRequestCompleteCallback = options
options = {}
config = ServiceConfiguration.configurations.findOne service: @name
if not config
credentialRequestCompleteCallback? new ServiceConfiguration.ConfigError()
return
credentialToken = PI:KEY:<KEY>END_PI.secret()
loginStyle = OAuth._loginStyle @name, config, options
loginUrl = @authorizePath +
'?client_id=' + config.clientId +
'&redirect_uri=' + OAuth._redirectUri(@name, config) +
'&response_type=code' +
'&state=' + OAuth._stateParam(loginStyle, credentialToken, options.redirectUrl) +
'&scope=' + @scope
OAuth.launchLogin
loginService: @name
loginStyle: loginStyle
loginUrl: loginUrl
credentialRequestCompleteCallback: credentialRequestCompleteCallback
credentialToken: credentialToken
popupOptions:
width: 900
height: 450
|
[
{
"context": "mponents/sdk/index.js'\n Digits.init(consumerKey:\"9rGXb3mmlyfOrY8sTBl7uG61n\")\n module.exports.Digits = Digits\n\nelse\n modu",
"end": 144,
"score": 0.7421388030052185,
"start": 119,
"tag": "KEY",
"value": "9rGXb3mmlyfOrY8sTBl7uG61n"
}
] | client/scripts/components/digits.coffee | corydolphin/sendthistome | 1 | if typeof window is "undefined"
Digits = require '../../../bower_components/sdk/index.js'
Digits.init(consumerKey:"9rGXb3mmlyfOrY8sTBl7uG61n")
module.exports.Digits = Digits
else
module.exports.Digits =
getLoginStatus: ->
fail: (fun)->
done: (fun)->
login: ->
fail: (fun)->
done: (fun)->
| 130051 | if typeof window is "undefined"
Digits = require '../../../bower_components/sdk/index.js'
Digits.init(consumerKey:"<KEY>")
module.exports.Digits = Digits
else
module.exports.Digits =
getLoginStatus: ->
fail: (fun)->
done: (fun)->
login: ->
fail: (fun)->
done: (fun)->
| true | if typeof window is "undefined"
Digits = require '../../../bower_components/sdk/index.js'
Digits.init(consumerKey:"PI:KEY:<KEY>END_PI")
module.exports.Digits = Digits
else
module.exports.Digits =
getLoginStatus: ->
fail: (fun)->
done: (fun)->
login: ->
fail: (fun)->
done: (fun)->
|
[
{
"context": "':\n# topic: new Foo\n# email: 'Abc@abc.com'\n# \n# 'lowercase email': ({ email",
"end": 457,
"score": 0.9998374581336975,
"start": 446,
"tag": "EMAIL",
"value": "Abc@abc.com"
},
{
"context": "({ email }) ->\n# assert.equal email, 'abc@abc.com'\n# \n# 'validate':\n# t",
"end": 560,
"score": 0.9998602867126465,
"start": 549,
"tag": "EMAIL",
"value": "abc@abc.com"
},
{
"context": ": ->\n# async.map [\n# 'a@a.us'\n# 'root@localhost'\n# ",
"end": 848,
"score": 0.9977983236312866,
"start": 842,
"tag": "EMAIL",
"value": "a@a.us"
},
{
"context": "'root@localhost'\n# 'Jim.D.Green-J_123+ebay@gmail.com'\n# 'wang@vip.sina.com.cn'\n# ",
"end": 936,
"score": 0.8085446357727051,
"start": 918,
"tag": "EMAIL",
"value": "123+ebay@gmail.com"
},
{
"context": ".D.Green-J_123+ebay@gmail.com'\n# 'wang@vip.sina.com.cn'\n# 'monkey@acfun.tv'\n# ",
"end": 977,
"score": 0.999740719795227,
"start": 957,
"tag": "EMAIL",
"value": "wang@vip.sina.com.cn"
},
{
"context": " 'wang@vip.sina.com.cn'\n# 'monkey@acfun.tv'\n# ], (email, callback) ->\n# ",
"end": 1013,
"score": 0.9998326897621155,
"start": 998,
"tag": "EMAIL",
"value": "monkey@acfun.tv"
},
{
"context": "a'\n# 'abc-123'\n# 'a@go_go.com'\n# 'a@go.*'\n# ], (ema",
"end": 1517,
"score": 0.9436593651771545,
"start": 1506,
"tag": "EMAIL",
"value": "a@go_go.com"
}
] | test/models/plugins/email.coffee | cncolder/vcvs | 0 | # { _, vows, assert, async, cwd, mongoose } = require '../../helper'
# { email } = require "#{cwd}/models/plugins"
#
# schema = new mongoose.Schema
# name:
# type: String
#
# schema.plugin email
#
# Foo = mongoose.model 'Foo', schema
#
# vows
# .describe(email)
# .addBatch
# teardown: ->
# Foo.remove {}, @callback
# return
#
# 'A model':
# topic: new Foo
# email: 'Abc@abc.com'
#
# 'lowercase email': ({ email }) ->
# assert.equal email, 'abc@abc.com'
#
# 'validate':
# topic: (foo) ->
# foo.validate @callback
#
# 'pass': (err, doc) ->
# assert.isNull err
#
# 'Valid email':
# topic: ->
# async.map [
# 'a@a.us'
# 'root@localhost'
# 'Jim.D.Green-J_123+ebay@gmail.com'
# 'wang@vip.sina.com.cn'
# 'monkey@acfun.tv'
# ], (email, callback) ->
# foo = new Foo
# email: email
# foo.validate (err, doc) ->
# callback null, err
# , @callback
#
# 'be pass': (err, errors) ->
# assert.ifError err
# assert.isUndefined err for err in errors
#
# 'Invalid email':
# topic: ->
# async.map [
# 'a'
# 'abc-123'
# 'a@go_go.com'
# 'a@go.*'
# ], (email, callback) ->
# foo = new Foo
# email: email
# foo.validate (err, doc) ->
# callback null, err
# , @callback
#
# 'get many errors': (err, errors) ->
# assert.ifError err
# assert.equal err?.errors?.email?.name, 'ValidatorError' for err in errors
#
# .export module
| 122326 | # { _, vows, assert, async, cwd, mongoose } = require '../../helper'
# { email } = require "#{cwd}/models/plugins"
#
# schema = new mongoose.Schema
# name:
# type: String
#
# schema.plugin email
#
# Foo = mongoose.model 'Foo', schema
#
# vows
# .describe(email)
# .addBatch
# teardown: ->
# Foo.remove {}, @callback
# return
#
# 'A model':
# topic: new Foo
# email: '<EMAIL>'
#
# 'lowercase email': ({ email }) ->
# assert.equal email, '<EMAIL>'
#
# 'validate':
# topic: (foo) ->
# foo.validate @callback
#
# 'pass': (err, doc) ->
# assert.isNull err
#
# 'Valid email':
# topic: ->
# async.map [
# '<EMAIL>'
# 'root@localhost'
# 'Jim.D.Green-J_<EMAIL>'
# '<EMAIL>'
# '<EMAIL>'
# ], (email, callback) ->
# foo = new Foo
# email: email
# foo.validate (err, doc) ->
# callback null, err
# , @callback
#
# 'be pass': (err, errors) ->
# assert.ifError err
# assert.isUndefined err for err in errors
#
# 'Invalid email':
# topic: ->
# async.map [
# 'a'
# 'abc-123'
# '<EMAIL>'
# 'a@go.*'
# ], (email, callback) ->
# foo = new Foo
# email: email
# foo.validate (err, doc) ->
# callback null, err
# , @callback
#
# 'get many errors': (err, errors) ->
# assert.ifError err
# assert.equal err?.errors?.email?.name, 'ValidatorError' for err in errors
#
# .export module
| true | # { _, vows, assert, async, cwd, mongoose } = require '../../helper'
# { email } = require "#{cwd}/models/plugins"
#
# schema = new mongoose.Schema
# name:
# type: String
#
# schema.plugin email
#
# Foo = mongoose.model 'Foo', schema
#
# vows
# .describe(email)
# .addBatch
# teardown: ->
# Foo.remove {}, @callback
# return
#
# 'A model':
# topic: new Foo
# email: 'PI:EMAIL:<EMAIL>END_PI'
#
# 'lowercase email': ({ email }) ->
# assert.equal email, 'PI:EMAIL:<EMAIL>END_PI'
#
# 'validate':
# topic: (foo) ->
# foo.validate @callback
#
# 'pass': (err, doc) ->
# assert.isNull err
#
# 'Valid email':
# topic: ->
# async.map [
# 'PI:EMAIL:<EMAIL>END_PI'
# 'root@localhost'
# 'Jim.D.Green-J_PI:EMAIL:<EMAIL>END_PI'
# 'PI:EMAIL:<EMAIL>END_PI'
# 'PI:EMAIL:<EMAIL>END_PI'
# ], (email, callback) ->
# foo = new Foo
# email: email
# foo.validate (err, doc) ->
# callback null, err
# , @callback
#
# 'be pass': (err, errors) ->
# assert.ifError err
# assert.isUndefined err for err in errors
#
# 'Invalid email':
# topic: ->
# async.map [
# 'a'
# 'abc-123'
# 'PI:EMAIL:<EMAIL>END_PI'
# 'a@go.*'
# ], (email, callback) ->
# foo = new Foo
# email: email
# foo.validate (err, doc) ->
# callback null, err
# , @callback
#
# 'get many errors': (err, errors) ->
# assert.ifError err
# assert.equal err?.errors?.email?.name, 'ValidatorError' for err in errors
#
# .export module
|
[
{
"context": " name:\n honorifics: 'Mr'\n first: 'John'\n middle: 'Winston'\n last: 'Lennon'",
"end": 244,
"score": 0.9998337030410767,
"start": 240,
"tag": "NAME",
"value": "John"
},
{
"context": "fics: 'Mr'\n first: 'John'\n middle: 'Winston'\n last: 'Lennon'\n password: 'Working ",
"end": 270,
"score": 0.9997743368148804,
"start": 263,
"tag": "NAME",
"value": "Winston"
},
{
"context": ": 'John'\n middle: 'Winston'\n last: 'Lennon'\n password: 'Working Class Hero Is Something",
"end": 293,
"score": 0.9997363686561584,
"start": 287,
"tag": "NAME",
"value": "Lennon"
},
{
"context": "'Winston'\n last: 'Lennon'\n password: 'Working Class Hero Is Something To Be'\n repeatedPassword: 'Working Class Hero Is S",
"end": 349,
"score": 0.9993831515312195,
"start": 312,
"tag": "PASSWORD",
"value": "Working Class Hero Is Something To Be"
},
{
"context": "Hero Is Something To Be'\n repeatedPassword: 'Working Class Hero Is Something To Be'\n registrationDateTime: 1437721697343\n\n t",
"end": 413,
"score": 0.9993292689323425,
"start": 376,
"tag": "PASSWORD",
"value": "Working Class Hero Is Something To Be"
},
{
"context": " =\n# name:\n# honorifics: 'Mr'\n# first: 'John'\n# middle: 'Winston'\n# last: 'Lennon'\n# ",
"end": 1360,
"score": 0.9998108744621277,
"start": 1356,
"tag": "NAME",
"value": "John"
},
{
"context": "norifics: 'Mr'\n# first: 'John'\n# middle: 'Winston'\n# last: 'Lennon'\n# password: 'Working Clas",
"end": 1384,
"score": 0.9997996091842651,
"start": 1377,
"tag": "NAME",
"value": "Winston"
},
{
"context": "irst: 'John'\n# middle: 'Winston'\n# last: 'Lennon'\n# password: 'Working Class Hero Is Something T",
"end": 1405,
"score": 0.9997968077659607,
"start": 1399,
"tag": "NAME",
"value": "Lennon"
},
{
"context": "le: 'Winston'\n# last: 'Lennon'\n# password: 'Working Class Hero Is Something To Be'\n# repeatedPassword: 'Working Class Hero Is Som",
"end": 1459,
"score": 0.9993917346000671,
"start": 1422,
"tag": "PASSWORD",
"value": "Working Class Hero Is Something To Be"
},
{
"context": "s Hero Is Something To Be'\n# repeatedPassword: 'Working Class Hero Is Something To Be'\n# registrationDateTime: 1437721697343\n#\n# useN",
"end": 1521,
"score": 0.9993323087692261,
"start": 1484,
"tag": "PASSWORD",
"value": "Working Class Hero Is Something To Be"
}
] | src/test/temporary-active.coffee | bbs-enterprise/odse | 0 |
{ expect } = require 'chai'
{ ObjectDataStorageEngine } = require './../odse'
describe 'Active Temporary Test Cases' , ->
it.only 'Small Data Set', (doneCbfn)->
demoUserData =
name:
honorifics: 'Mr'
first: 'John'
middle: 'Winston'
last: 'Lennon'
password: 'Working Class Hero Is Something To Be'
repeatedPassword: 'Working Class Hero Is Something To Be'
registrationDateTime: 1437721697343
tree = ObjectDataStorageEngine.parse demoUserData
console.log tree
expect(tree).to.equal('TODO')
###
@testing
###
# possibleEvents = ['create', 'attach', 'set', 'remove', 'detach', 'update']
# monitorAllEvents = (name, node)->
# for ev in possibleEvents
# do (ev)->
# try
# node.once ev, (e)->
# # console.log (if e.origin is @ then e.origin.serial + ' ' else e.origin.serial + '->' + e.target.serial),'\t', name, e.name, (if e.detail.operation then e.detail.operation else '') #, # [e.detail]
# # console.log e.pathList.length
# str = ''
# for target, index in e.path
# str += (if index is 0 then '' else '->') + target.serial
#
# console.log e.name, e.detail.node.serial, '\t', str
#
# e.next()
# catch error
#
# demoUserData =
# name:
# honorifics: 'Mr'
# first: 'John'
# middle: 'Winston'
# last: 'Lennon'
# password: 'Working Class Hero Is Something To Be'
# repeatedPassword: 'Working Class Hero Is Something To Be'
# registrationDateTime: 1437721697343
#
# useNode = ObjectDataStorageEngine.parse demoUserData, (node)->
# monitorAllEvents '', node
#
#
# m1 = new ObjectNode
# monitorAllEvents 'm1', m1
#
# v1 = new ValueNode 'v1v1'
# monitorAllEvents 'v1', v1
# m1.addNode 'cn1', v1
#
# v2 = new ValueNode 'v2v1'
# monitorAllEvents 'v2', v2
# m1.addNode 'cn2', v2
#
#
# m1.forEach (key, node)->
# console.log key, node.serial
#
# m1.forEachAsync (next, key, node)->
# console.log key, node.serial
# next()
# .then ->
# console.log 'finished'
#
#
#
#
# v3 = new ValueNode 'v3v1'
# monitorAllEvents 'v3', v3
# m1.addNode 'cn1', v3
#
# v2.setValue 'v2v2'
#
# m2 = new ObjectNode
# monitorAllEvents 'm2', m2
# m1.addNode 'cn3', m2
#
# v4 = new ValueNode 'v4v1'
# monitorAllEvents 'v4', v4
# m2.addNode 'cn1', v4
#
# v4.setValue 'v4v2'
#
# m3 = new ObjectNode
# monitorAllEvents 'm3', m3
# m2.addNode 'cn2', m3
#
# v5 = new ValueNode 'v5v1'
# monitorAllEvents 'v5', v5
# m3.addNode 'cn1', v5
#
# v5.setValue 'v5v2'
# #
# # setTimeout =>
# # console.log 'gonna remove'
# # m3.remove()
# # , 300
#
# a1 = new ArrayNode
# monitorAllEvents 'a1', a1
# m3.addNode 'cnx', a1
#
# p1 = new PrimitiveNode 'v'
# monitorAllEvents 'p1', p1
# a1.pushNode p1
#
# p2 = new PrimitiveNode 'v'
# monitorAllEvents 'p2', p2
# a1.pushNode p2
#
# p3 = new PrimitiveNode 'v'
# monitorAllEvents 'p3', p3
# a1.pushNode p3
#
# a1.popNode()
# a1.popNode()
#
# p4 = new PrimitiveNode 'vv'
# monitorAllEvents 'p4', p4
# a1.pushNode p4
#
#
# master = new ObjectNode
# monitorAllEvents 'master', master
# master.addNode 'IN', ObjectDataStorageEngine.parse demoUserData
| 221013 |
{ expect } = require 'chai'
{ ObjectDataStorageEngine } = require './../odse'
describe 'Active Temporary Test Cases' , ->
it.only 'Small Data Set', (doneCbfn)->
demoUserData =
name:
honorifics: 'Mr'
first: '<NAME>'
middle: '<NAME>'
last: '<NAME>'
password: '<PASSWORD>'
repeatedPassword: '<PASSWORD>'
registrationDateTime: 1437721697343
tree = ObjectDataStorageEngine.parse demoUserData
console.log tree
expect(tree).to.equal('TODO')
###
@testing
###
# possibleEvents = ['create', 'attach', 'set', 'remove', 'detach', 'update']
# monitorAllEvents = (name, node)->
# for ev in possibleEvents
# do (ev)->
# try
# node.once ev, (e)->
# # console.log (if e.origin is @ then e.origin.serial + ' ' else e.origin.serial + '->' + e.target.serial),'\t', name, e.name, (if e.detail.operation then e.detail.operation else '') #, # [e.detail]
# # console.log e.pathList.length
# str = ''
# for target, index in e.path
# str += (if index is 0 then '' else '->') + target.serial
#
# console.log e.name, e.detail.node.serial, '\t', str
#
# e.next()
# catch error
#
# demoUserData =
# name:
# honorifics: 'Mr'
# first: '<NAME>'
# middle: '<NAME>'
# last: '<NAME>'
# password: '<PASSWORD>'
# repeatedPassword: '<PASSWORD>'
# registrationDateTime: 1437721697343
#
# useNode = ObjectDataStorageEngine.parse demoUserData, (node)->
# monitorAllEvents '', node
#
#
# m1 = new ObjectNode
# monitorAllEvents 'm1', m1
#
# v1 = new ValueNode 'v1v1'
# monitorAllEvents 'v1', v1
# m1.addNode 'cn1', v1
#
# v2 = new ValueNode 'v2v1'
# monitorAllEvents 'v2', v2
# m1.addNode 'cn2', v2
#
#
# m1.forEach (key, node)->
# console.log key, node.serial
#
# m1.forEachAsync (next, key, node)->
# console.log key, node.serial
# next()
# .then ->
# console.log 'finished'
#
#
#
#
# v3 = new ValueNode 'v3v1'
# monitorAllEvents 'v3', v3
# m1.addNode 'cn1', v3
#
# v2.setValue 'v2v2'
#
# m2 = new ObjectNode
# monitorAllEvents 'm2', m2
# m1.addNode 'cn3', m2
#
# v4 = new ValueNode 'v4v1'
# monitorAllEvents 'v4', v4
# m2.addNode 'cn1', v4
#
# v4.setValue 'v4v2'
#
# m3 = new ObjectNode
# monitorAllEvents 'm3', m3
# m2.addNode 'cn2', m3
#
# v5 = new ValueNode 'v5v1'
# monitorAllEvents 'v5', v5
# m3.addNode 'cn1', v5
#
# v5.setValue 'v5v2'
# #
# # setTimeout =>
# # console.log 'gonna remove'
# # m3.remove()
# # , 300
#
# a1 = new ArrayNode
# monitorAllEvents 'a1', a1
# m3.addNode 'cnx', a1
#
# p1 = new PrimitiveNode 'v'
# monitorAllEvents 'p1', p1
# a1.pushNode p1
#
# p2 = new PrimitiveNode 'v'
# monitorAllEvents 'p2', p2
# a1.pushNode p2
#
# p3 = new PrimitiveNode 'v'
# monitorAllEvents 'p3', p3
# a1.pushNode p3
#
# a1.popNode()
# a1.popNode()
#
# p4 = new PrimitiveNode 'vv'
# monitorAllEvents 'p4', p4
# a1.pushNode p4
#
#
# master = new ObjectNode
# monitorAllEvents 'master', master
# master.addNode 'IN', ObjectDataStorageEngine.parse demoUserData
| true |
{ expect } = require 'chai'
{ ObjectDataStorageEngine } = require './../odse'
describe 'Active Temporary Test Cases' , ->
it.only 'Small Data Set', (doneCbfn)->
demoUserData =
name:
honorifics: 'Mr'
first: 'PI:NAME:<NAME>END_PI'
middle: 'PI:NAME:<NAME>END_PI'
last: 'PI:NAME:<NAME>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
repeatedPassword: 'PI:PASSWORD:<PASSWORD>END_PI'
registrationDateTime: 1437721697343
tree = ObjectDataStorageEngine.parse demoUserData
console.log tree
expect(tree).to.equal('TODO')
###
@testing
###
# possibleEvents = ['create', 'attach', 'set', 'remove', 'detach', 'update']
# monitorAllEvents = (name, node)->
# for ev in possibleEvents
# do (ev)->
# try
# node.once ev, (e)->
# # console.log (if e.origin is @ then e.origin.serial + ' ' else e.origin.serial + '->' + e.target.serial),'\t', name, e.name, (if e.detail.operation then e.detail.operation else '') #, # [e.detail]
# # console.log e.pathList.length
# str = ''
# for target, index in e.path
# str += (if index is 0 then '' else '->') + target.serial
#
# console.log e.name, e.detail.node.serial, '\t', str
#
# e.next()
# catch error
#
# demoUserData =
# name:
# honorifics: 'Mr'
# first: 'PI:NAME:<NAME>END_PI'
# middle: 'PI:NAME:<NAME>END_PI'
# last: 'PI:NAME:<NAME>END_PI'
# password: 'PI:PASSWORD:<PASSWORD>END_PI'
# repeatedPassword: 'PI:PASSWORD:<PASSWORD>END_PI'
# registrationDateTime: 1437721697343
#
# useNode = ObjectDataStorageEngine.parse demoUserData, (node)->
# monitorAllEvents '', node
#
#
# m1 = new ObjectNode
# monitorAllEvents 'm1', m1
#
# v1 = new ValueNode 'v1v1'
# monitorAllEvents 'v1', v1
# m1.addNode 'cn1', v1
#
# v2 = new ValueNode 'v2v1'
# monitorAllEvents 'v2', v2
# m1.addNode 'cn2', v2
#
#
# m1.forEach (key, node)->
# console.log key, node.serial
#
# m1.forEachAsync (next, key, node)->
# console.log key, node.serial
# next()
# .then ->
# console.log 'finished'
#
#
#
#
# v3 = new ValueNode 'v3v1'
# monitorAllEvents 'v3', v3
# m1.addNode 'cn1', v3
#
# v2.setValue 'v2v2'
#
# m2 = new ObjectNode
# monitorAllEvents 'm2', m2
# m1.addNode 'cn3', m2
#
# v4 = new ValueNode 'v4v1'
# monitorAllEvents 'v4', v4
# m2.addNode 'cn1', v4
#
# v4.setValue 'v4v2'
#
# m3 = new ObjectNode
# monitorAllEvents 'm3', m3
# m2.addNode 'cn2', m3
#
# v5 = new ValueNode 'v5v1'
# monitorAllEvents 'v5', v5
# m3.addNode 'cn1', v5
#
# v5.setValue 'v5v2'
# #
# # setTimeout =>
# # console.log 'gonna remove'
# # m3.remove()
# # , 300
#
# a1 = new ArrayNode
# monitorAllEvents 'a1', a1
# m3.addNode 'cnx', a1
#
# p1 = new PrimitiveNode 'v'
# monitorAllEvents 'p1', p1
# a1.pushNode p1
#
# p2 = new PrimitiveNode 'v'
# monitorAllEvents 'p2', p2
# a1.pushNode p2
#
# p3 = new PrimitiveNode 'v'
# monitorAllEvents 'p3', p3
# a1.pushNode p3
#
# a1.popNode()
# a1.popNode()
#
# p4 = new PrimitiveNode 'vv'
# monitorAllEvents 'p4', p4
# a1.pushNode p4
#
#
# master = new ObjectNode
# monitorAllEvents 'master', master
# master.addNode 'IN', ObjectDataStorageEngine.parse demoUserData
|
[
{
"context": "til'\n\narticleHtml = \"\"\"\nHello, <mention data-id=\"1\">@Grace</mention>. It's been a long time since we me",
"end": 135,
"score": 0.9988084435462952,
"start": 129,
"tag": "USERNAME",
"value": "@Grace"
},
{
"context": "ime since we met last time.<br><mention data-id=\"2\">@Bran</mention> is very missing you.\n\"\"\"\n\narticleText =",
"end": 227,
"score": 0.9991236329078674,
"start": 222,
"tag": "USERNAME",
"value": "@Bran"
},
{
"context": "is very missing you.\n\"\"\"\n\narticleText = \"\"\"\nHello, @Grace. It's been a long time since we met last time.\n@B",
"end": 295,
"score": 0.9781326055526733,
"start": 289,
"tag": "USERNAME",
"value": "@Grace"
},
{
"context": "ce. It's been a long time since we met last time.\n@Bran is very missing you.\n\"\"\"\n\narticleData = [\n 'Hell",
"end": 348,
"score": 0.9917585253715515,
"start": 343,
"tag": "USERNAME",
"value": "@Bran"
},
{
"context": " = [\n 'Hello, '\n ,\n type: 'mention'\n text: '@Grace'\n data: id: '1'\n ,\n \". It's been a long time",
"end": 444,
"score": 0.9989945888519287,
"start": 437,
"tag": "USERNAME",
"value": "'@Grace"
},
{
"context": "et last time.\\n\"\n ,\n type: 'mention'\n text: '@Bran'\n data: id: '2'\n ,\n ' is very missing you.\\n",
"end": 562,
"score": 0.9989497065544128,
"start": 556,
"tag": "USERNAME",
"value": "'@Bran"
},
{
"context": "es = [\n util.createDOM 'Hello, '\n util.createDOM '@Grace', 'mention', {}, \"data-id\": \"1\"\n util.createDOM ",
"end": 685,
"score": 0.9991054534912109,
"start": 678,
"tag": "USERNAME",
"value": "'@Grace"
},
{
"context": "g time since we met last time.\\n\"\n util.createDOM '@Bran', 'mention', {}, \"data-id\": \"2\"\n util.createDOM ",
"end": 810,
"score": 0.9988045692443848,
"start": 804,
"tag": "USERNAME",
"value": "'@Bran"
},
{
"context": " # mention\n lex = lexer type: 'mention', text: '@user', data: id: '1'\n lex.html().should.eql '<menti",
"end": 1249,
"score": 0.993727445602417,
"start": 1243,
"tag": "USERNAME",
"value": "'@user"
},
{
"context": "'1'\n lex.html().should.eql '<mention data-id=\"1\">@user</mention>'\n lex.text().should.eql '@user'\n\n ",
"end": 1319,
"score": 0.8701843619346619,
"start": 1314,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "-id=\"1\">@user</mention>'\n lex.text().should.eql '@user'\n\n # htmlentities\n lex = lexer '<h1>hi</h1>",
"end": 1363,
"score": 0.767020583152771,
"start": 1357,
"tag": "USERNAME",
"value": "'@user"
},
{
"context": "d.eql ['hello world']\n\n nodes = [util.createDOM '@user', 'mention', {}, \"data-id\": \"1\"]\n lexer.parseD",
"end": 2465,
"score": 0.9748748540878296,
"start": 2459,
"tag": "USERNAME",
"value": "'@user"
},
{
"context": "\n .toJSON().should.eql [{type: 'mention', text: '@user', data: id: '1'}]\n\n lexer.parseDOM articleNode",
"end": 2580,
"score": 0.9894043207168579,
"start": 2574,
"tag": "USERNAME",
"value": "'@user"
},
{
"context": "parseDOM method\n nodes = [util.createDOM 'Hello @Graceand@Bran Good Afternoon']\n lexer.parseDOM nodes, m",
"end": 2758,
"score": 0.9722369313240051,
"start": 2749,
"tag": "USERNAME",
"value": "@Graceand"
},
{
"context": "thod\n nodes = [util.createDOM 'Hello @Graceand@Bran Good Afternoon']\n lexer.parseDOM nodes, mentio",
"end": 2763,
"score": 0.9965885877609253,
"start": 2759,
"tag": "USERNAME",
"value": "Bran"
},
{
"context": ".eql [\n 'Hello '\n type: 'mention', text: '@Grace', data: id: '1'\n 'and'\n type: 'mention'",
"end": 2960,
"score": 0.9991927742958069,
"start": 2953,
"tag": "USERNAME",
"value": "'@Grace"
},
{
"context": ": id: '1'\n 'and'\n type: 'mention', text: '@Bran', data: id: '2'\n ' Good Afternoon'\n ]\n\n ",
"end": 3024,
"score": 0.976453959941864,
"start": 3018,
"tag": "USERNAME",
"value": "'@Bran"
},
{
"context": "ot break emails\n nodes = [util.createDOM 'Hello user@gmail.com']\n lexer.parseDOM nodes, mention: [{match: 'us",
"end": 3147,
"score": 0.9999212026596069,
"start": 3133,
"tag": "EMAIL",
"value": "user@gmail.com"
},
{
"context": " id: '2'}]\n .toJSON().should.eql [\n 'Hello user@gmail.com'\n ]\n\n # Create a dom wrapped with div and b",
"end": 3272,
"score": 0.9999212026596069,
"start": 3258,
"tag": "EMAIL",
"value": "user@gmail.com"
},
{
"context": "ateElement', ->\n lexer.createElement('mention', '@Grace', data: id: 1).should.eql {type: 'mention', text:",
"end": 4501,
"score": 0.9984610080718994,
"start": 4494,
"tag": "USERNAME",
"value": "'@Grace"
},
{
"context": "', data: id: 1).should.eql {type: 'mention', text: '@Grace', data: id: 1}\n lexer.createElement('link', 'w",
"end": 4559,
"score": 0.9927521347999573,
"start": 4552,
"tag": "USERNAME",
"value": "'@Grace"
}
] | test/main.coffee | teambition/talk-lexer | 1 | should = require 'should'
lexer = require '../src/lexer'
util = require './util'
articleHtml = """
Hello, <mention data-id="1">@Grace</mention>. It's been a long time since we met last time.<br><mention data-id="2">@Bran</mention> is very missing you.
"""
articleText = """
Hello, @Grace. It's been a long time since we met last time.
@Bran is very missing you.
"""
articleData = [
'Hello, '
,
type: 'mention'
text: '@Grace'
data: id: '1'
,
". It's been a long time since we met last time.\n"
,
type: 'mention'
text: '@Bran'
data: id: '2'
,
' is very missing you.\n'
]
articleNodes = [
util.createDOM 'Hello, '
util.createDOM '@Grace', 'mention', {}, "data-id": "1"
util.createDOM ". It's been a long time since we met last time.\n"
util.createDOM '@Bran', 'mention', {}, "data-id": "2"
util.createDOM ' is very missing you.\n'
]
describe 'main', ->
it 'stringify', ->
# skip when not in whitelist
lex = lexer type: 'ack', text: 'nothing'
lex.html().should.eql ''
lex.text().should.eql ''
# text
lex = lexer 'hello world'
lex.html().should.eql 'hello world'
lex.text().should.eql 'hello world'
# mention
lex = lexer type: 'mention', text: '@user', data: id: '1'
lex.html().should.eql '<mention data-id="1">@user</mention>'
lex.text().should.eql '@user'
# htmlentities
lex = lexer '<h1>hi</h1>'
lex.html().should.eql '<h1>hi</h1>'
lex.text().should.eql '<h1>hi</h1>'
# htmlentities in the text value
lex = lexer([{type: 'highlight', text: '<h1>hi</h1>'}])
lex.html().should.eql '<em class="lexer-highlight"><h1>hi</h1></em>'
lex.text().should.eql '<h1>hi</h1>'
# mix text
lex = lexer articleData
lex.html().should.eql articleHtml
lex.text().should.eql articleText
# test replacement of url
lexer('I am head http://dn-talk.oss.aliyuncs.com/icons/rss@2x.png I am tail')
.html().should.eql 'I am head <a href="http://dn-talk.oss.aliyuncs.com/icons/rss@2x.png" target="_blank">http://dn-talk.oss.aliyuncs.com/icons/rss@2x.png</a> I am tail'
lexer('开博客可以查看详细:http://t.cn/Rz3I0cX\n小艾:)')
.html().should.eql '开博客可以查看详细:<a href="http://t.cn/Rz3I0cX" target="_blank">http://t.cn/Rz3I0cX</a><br>小艾:)'
it 'parseDOM', ->
nodes = [util.createDOM 'hello world']
lexer.parseDOM nodes
.toJSON().should.eql ['hello world']
nodes = [util.createDOM '@user', 'mention', {}, "data-id": "1"]
lexer.parseDOM nodes
.toJSON().should.eql [{type: 'mention', text: '@user', data: id: '1'}]
lexer.parseDOM articleNodes
.toJSON().should.eql articleData
# pass option params to parseDOM method
nodes = [util.createDOM 'Hello @Graceand@Bran Good Afternoon']
lexer.parseDOM nodes, mention: [{match: 'Grace', data: id: '1'}, {match: 'Bran', data: id: '2'}]
.toJSON().should.eql [
'Hello '
type: 'mention', text: '@Grace', data: id: '1'
'and'
type: 'mention', text: '@Bran', data: id: '2'
' Good Afternoon'
]
# do not break emails
nodes = [util.createDOM 'Hello user@gmail.com']
lexer.parseDOM nodes, mention: [{match: 'user', data: id: '2'}]
.toJSON().should.eql [
'Hello user@gmail.com'
]
# Create a dom wrapped with div and br
nodes = [
util.createDOM 'text', 'span'
util.createDOM 'div1', 'DIV'
util.createDOM 'div2', 'DIV'
util.createDOM '', 'BR'
util.createDOM 'tail', 'DIV'
]
lex = lexer.parseDOM nodes
lex.toJSON().should.eql [
'text'
'\ndiv1\n',
'div2\n'
'\n'
'tail\n'
]
lex.text().should.eql 'text\ndiv1\ndiv2\n\ntail'
lex.html().should.eql 'text<br>div1<br>div2<br><br>tail'
# Trim the empty dom before or after content
nodes = [
util.createDOM '', 'BR'
util.createDOM '', 'DIV'
util.createDOM "Hello", 'DIV'
util.createDOM 'World', 'DIV'
util.createDOM '', 'BR'
]
lex = lexer.parseDOM nodes
lex.toJSON().should.eql ['Hello\n', 'World\n']
lex.text().should.eql 'Hello\nWorld'
lex.html().should.eql 'Hello<br>World'
it 'isValid', ->
lexer('hello world').isValid().should.eql true
lexer(['hello world', {type: 'mention', test: '@abc'}]).isValid().should.eql true
lexer({type: 'men'}).isValid().should.eql false
lexer([{type: 'men'}]).isValid().should.eql false
it 'createElement', ->
lexer.createElement('mention', '@Grace', data: id: 1).should.eql {type: 'mention', text: '@Grace', data: id: 1}
lexer.createElement('link', 'www.baidu.com', href: 'http://www.baidu.com').should.eql {type: 'link', text: 'www.baidu.com', href: 'http://www.baidu.com'}
lexer.createElement('undefined', 'hello').should.eql 'hello'
# Test for different types
require './type'
| 147102 | should = require 'should'
lexer = require '../src/lexer'
util = require './util'
articleHtml = """
Hello, <mention data-id="1">@Grace</mention>. It's been a long time since we met last time.<br><mention data-id="2">@Bran</mention> is very missing you.
"""
articleText = """
Hello, @Grace. It's been a long time since we met last time.
@Bran is very missing you.
"""
articleData = [
'Hello, '
,
type: 'mention'
text: '@Grace'
data: id: '1'
,
". It's been a long time since we met last time.\n"
,
type: 'mention'
text: '@Bran'
data: id: '2'
,
' is very missing you.\n'
]
articleNodes = [
util.createDOM 'Hello, '
util.createDOM '@Grace', 'mention', {}, "data-id": "1"
util.createDOM ". It's been a long time since we met last time.\n"
util.createDOM '@Bran', 'mention', {}, "data-id": "2"
util.createDOM ' is very missing you.\n'
]
describe 'main', ->
it 'stringify', ->
# skip when not in whitelist
lex = lexer type: 'ack', text: 'nothing'
lex.html().should.eql ''
lex.text().should.eql ''
# text
lex = lexer 'hello world'
lex.html().should.eql 'hello world'
lex.text().should.eql 'hello world'
# mention
lex = lexer type: 'mention', text: '@user', data: id: '1'
lex.html().should.eql '<mention data-id="1">@user</mention>'
lex.text().should.eql '@user'
# htmlentities
lex = lexer '<h1>hi</h1>'
lex.html().should.eql '<h1>hi</h1>'
lex.text().should.eql '<h1>hi</h1>'
# htmlentities in the text value
lex = lexer([{type: 'highlight', text: '<h1>hi</h1>'}])
lex.html().should.eql '<em class="lexer-highlight"><h1>hi</h1></em>'
lex.text().should.eql '<h1>hi</h1>'
# mix text
lex = lexer articleData
lex.html().should.eql articleHtml
lex.text().should.eql articleText
# test replacement of url
lexer('I am head http://dn-talk.oss.aliyuncs.com/icons/rss@2x.png I am tail')
.html().should.eql 'I am head <a href="http://dn-talk.oss.aliyuncs.com/icons/rss@2x.png" target="_blank">http://dn-talk.oss.aliyuncs.com/icons/rss@2x.png</a> I am tail'
lexer('开博客可以查看详细:http://t.cn/Rz3I0cX\n小艾:)')
.html().should.eql '开博客可以查看详细:<a href="http://t.cn/Rz3I0cX" target="_blank">http://t.cn/Rz3I0cX</a><br>小艾:)'
it 'parseDOM', ->
nodes = [util.createDOM 'hello world']
lexer.parseDOM nodes
.toJSON().should.eql ['hello world']
nodes = [util.createDOM '@user', 'mention', {}, "data-id": "1"]
lexer.parseDOM nodes
.toJSON().should.eql [{type: 'mention', text: '@user', data: id: '1'}]
lexer.parseDOM articleNodes
.toJSON().should.eql articleData
# pass option params to parseDOM method
nodes = [util.createDOM 'Hello @Graceand@Bran Good Afternoon']
lexer.parseDOM nodes, mention: [{match: 'Grace', data: id: '1'}, {match: 'Bran', data: id: '2'}]
.toJSON().should.eql [
'Hello '
type: 'mention', text: '@Grace', data: id: '1'
'and'
type: 'mention', text: '@Bran', data: id: '2'
' Good Afternoon'
]
# do not break emails
nodes = [util.createDOM 'Hello <EMAIL>']
lexer.parseDOM nodes, mention: [{match: 'user', data: id: '2'}]
.toJSON().should.eql [
'Hello <EMAIL>'
]
# Create a dom wrapped with div and br
nodes = [
util.createDOM 'text', 'span'
util.createDOM 'div1', 'DIV'
util.createDOM 'div2', 'DIV'
util.createDOM '', 'BR'
util.createDOM 'tail', 'DIV'
]
lex = lexer.parseDOM nodes
lex.toJSON().should.eql [
'text'
'\ndiv1\n',
'div2\n'
'\n'
'tail\n'
]
lex.text().should.eql 'text\ndiv1\ndiv2\n\ntail'
lex.html().should.eql 'text<br>div1<br>div2<br><br>tail'
# Trim the empty dom before or after content
nodes = [
util.createDOM '', 'BR'
util.createDOM '', 'DIV'
util.createDOM "Hello", 'DIV'
util.createDOM 'World', 'DIV'
util.createDOM '', 'BR'
]
lex = lexer.parseDOM nodes
lex.toJSON().should.eql ['Hello\n', 'World\n']
lex.text().should.eql 'Hello\nWorld'
lex.html().should.eql 'Hello<br>World'
it 'isValid', ->
lexer('hello world').isValid().should.eql true
lexer(['hello world', {type: 'mention', test: '@abc'}]).isValid().should.eql true
lexer({type: 'men'}).isValid().should.eql false
lexer([{type: 'men'}]).isValid().should.eql false
it 'createElement', ->
lexer.createElement('mention', '@Grace', data: id: 1).should.eql {type: 'mention', text: '@Grace', data: id: 1}
lexer.createElement('link', 'www.baidu.com', href: 'http://www.baidu.com').should.eql {type: 'link', text: 'www.baidu.com', href: 'http://www.baidu.com'}
lexer.createElement('undefined', 'hello').should.eql 'hello'
# Test for different types
require './type'
| true | should = require 'should'
lexer = require '../src/lexer'
util = require './util'
articleHtml = """
Hello, <mention data-id="1">@Grace</mention>. It's been a long time since we met last time.<br><mention data-id="2">@Bran</mention> is very missing you.
"""
articleText = """
Hello, @Grace. It's been a long time since we met last time.
@Bran is very missing you.
"""
articleData = [
'Hello, '
,
type: 'mention'
text: '@Grace'
data: id: '1'
,
". It's been a long time since we met last time.\n"
,
type: 'mention'
text: '@Bran'
data: id: '2'
,
' is very missing you.\n'
]
articleNodes = [
util.createDOM 'Hello, '
util.createDOM '@Grace', 'mention', {}, "data-id": "1"
util.createDOM ". It's been a long time since we met last time.\n"
util.createDOM '@Bran', 'mention', {}, "data-id": "2"
util.createDOM ' is very missing you.\n'
]
describe 'main', ->
it 'stringify', ->
# skip when not in whitelist
lex = lexer type: 'ack', text: 'nothing'
lex.html().should.eql ''
lex.text().should.eql ''
# text
lex = lexer 'hello world'
lex.html().should.eql 'hello world'
lex.text().should.eql 'hello world'
# mention
lex = lexer type: 'mention', text: '@user', data: id: '1'
lex.html().should.eql '<mention data-id="1">@user</mention>'
lex.text().should.eql '@user'
# htmlentities
lex = lexer '<h1>hi</h1>'
lex.html().should.eql '<h1>hi</h1>'
lex.text().should.eql '<h1>hi</h1>'
# htmlentities in the text value
lex = lexer([{type: 'highlight', text: '<h1>hi</h1>'}])
lex.html().should.eql '<em class="lexer-highlight"><h1>hi</h1></em>'
lex.text().should.eql '<h1>hi</h1>'
# mix text
lex = lexer articleData
lex.html().should.eql articleHtml
lex.text().should.eql articleText
# test replacement of url
lexer('I am head http://dn-talk.oss.aliyuncs.com/icons/rss@2x.png I am tail')
.html().should.eql 'I am head <a href="http://dn-talk.oss.aliyuncs.com/icons/rss@2x.png" target="_blank">http://dn-talk.oss.aliyuncs.com/icons/rss@2x.png</a> I am tail'
lexer('开博客可以查看详细:http://t.cn/Rz3I0cX\n小艾:)')
.html().should.eql '开博客可以查看详细:<a href="http://t.cn/Rz3I0cX" target="_blank">http://t.cn/Rz3I0cX</a><br>小艾:)'
it 'parseDOM', ->
nodes = [util.createDOM 'hello world']
lexer.parseDOM nodes
.toJSON().should.eql ['hello world']
nodes = [util.createDOM '@user', 'mention', {}, "data-id": "1"]
lexer.parseDOM nodes
.toJSON().should.eql [{type: 'mention', text: '@user', data: id: '1'}]
lexer.parseDOM articleNodes
.toJSON().should.eql articleData
# pass option params to parseDOM method
nodes = [util.createDOM 'Hello @Graceand@Bran Good Afternoon']
lexer.parseDOM nodes, mention: [{match: 'Grace', data: id: '1'}, {match: 'Bran', data: id: '2'}]
.toJSON().should.eql [
'Hello '
type: 'mention', text: '@Grace', data: id: '1'
'and'
type: 'mention', text: '@Bran', data: id: '2'
' Good Afternoon'
]
# do not break emails
nodes = [util.createDOM 'Hello PI:EMAIL:<EMAIL>END_PI']
lexer.parseDOM nodes, mention: [{match: 'user', data: id: '2'}]
.toJSON().should.eql [
'Hello PI:EMAIL:<EMAIL>END_PI'
]
# Create a dom wrapped with div and br
nodes = [
util.createDOM 'text', 'span'
util.createDOM 'div1', 'DIV'
util.createDOM 'div2', 'DIV'
util.createDOM '', 'BR'
util.createDOM 'tail', 'DIV'
]
lex = lexer.parseDOM nodes
lex.toJSON().should.eql [
'text'
'\ndiv1\n',
'div2\n'
'\n'
'tail\n'
]
lex.text().should.eql 'text\ndiv1\ndiv2\n\ntail'
lex.html().should.eql 'text<br>div1<br>div2<br><br>tail'
# Trim the empty dom before or after content
nodes = [
util.createDOM '', 'BR'
util.createDOM '', 'DIV'
util.createDOM "Hello", 'DIV'
util.createDOM 'World', 'DIV'
util.createDOM '', 'BR'
]
lex = lexer.parseDOM nodes
lex.toJSON().should.eql ['Hello\n', 'World\n']
lex.text().should.eql 'Hello\nWorld'
lex.html().should.eql 'Hello<br>World'
it 'isValid', ->
lexer('hello world').isValid().should.eql true
lexer(['hello world', {type: 'mention', test: '@abc'}]).isValid().should.eql true
lexer({type: 'men'}).isValid().should.eql false
lexer([{type: 'men'}]).isValid().should.eql false
it 'createElement', ->
lexer.createElement('mention', '@Grace', data: id: 1).should.eql {type: 'mention', text: '@Grace', data: id: 1}
lexer.createElement('link', 'www.baidu.com', href: 'http://www.baidu.com').should.eql {type: 'link', text: 'www.baidu.com', href: 'http://www.baidu.com'}
lexer.createElement('undefined', 'hello').should.eql 'hello'
# Test for different types
require './type'
|
[
{
"context": "# Copyright (c) 2016-2017 Bennet Carstensen\n#\n# Permission is hereby granted, free of charge,",
"end": 43,
"score": 0.9998471140861511,
"start": 26,
"tag": "NAME",
"value": "Bennet Carstensen"
}
] | lib/config.coffee | BenSolus/linter-clcc | 0 | # Copyright (c) 2016-2017 Bennet Carstensen
#
# 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.
'use strict'
path = require 'path'
fs = require 'fs'
module.exports = () ->
if atom.project.getPaths()[0] != undefined
configFile = path.join(atom.project.getPaths()[0], '.opencl-config.json')
if fs.existsSync(configFile)
delete require.cache[configFile]
configData = require(configFile)
configs = {}
if configData.compilerFlags != undefined
configs.compilerFlags = configData.compilerFlags
else
configs.compilerFlags = atom.config.get('linter-opencl.compilerFlags')
if configData.includePaths != undefined
configs.includePaths = configData.includePaths
else
configs.includePaths = atom.config.get('linter-opencl.includePaths')
return {
compilerFlags: configs.compilerFlags,
includePaths: configs.includePaths
}
return {
compilerFlags: atom.config.get('linter-opencl.compilerFlags'),
includePaths: atom.config.get('linter-opencl.includePaths')
}
| 189360 | # Copyright (c) 2016-2017 <NAME>
#
# 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.
'use strict'
path = require 'path'
fs = require 'fs'
module.exports = () ->
if atom.project.getPaths()[0] != undefined
configFile = path.join(atom.project.getPaths()[0], '.opencl-config.json')
if fs.existsSync(configFile)
delete require.cache[configFile]
configData = require(configFile)
configs = {}
if configData.compilerFlags != undefined
configs.compilerFlags = configData.compilerFlags
else
configs.compilerFlags = atom.config.get('linter-opencl.compilerFlags')
if configData.includePaths != undefined
configs.includePaths = configData.includePaths
else
configs.includePaths = atom.config.get('linter-opencl.includePaths')
return {
compilerFlags: configs.compilerFlags,
includePaths: configs.includePaths
}
return {
compilerFlags: atom.config.get('linter-opencl.compilerFlags'),
includePaths: atom.config.get('linter-opencl.includePaths')
}
| true | # Copyright (c) 2016-2017 PI:NAME:<NAME>END_PI
#
# 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.
'use strict'
path = require 'path'
fs = require 'fs'
module.exports = () ->
if atom.project.getPaths()[0] != undefined
configFile = path.join(atom.project.getPaths()[0], '.opencl-config.json')
if fs.existsSync(configFile)
delete require.cache[configFile]
configData = require(configFile)
configs = {}
if configData.compilerFlags != undefined
configs.compilerFlags = configData.compilerFlags
else
configs.compilerFlags = atom.config.get('linter-opencl.compilerFlags')
if configData.includePaths != undefined
configs.includePaths = configData.includePaths
else
configs.includePaths = atom.config.get('linter-opencl.includePaths')
return {
compilerFlags: configs.compilerFlags,
includePaths: configs.includePaths
}
return {
compilerFlags: atom.config.get('linter-opencl.compilerFlags'),
includePaths: atom.config.get('linter-opencl.includePaths')
}
|
[
{
"context": "\n data =\n login: env.sipAgent\n password: env.sipSecret\n\n phone.notify = (call) ->\n console",
"end": 161,
"score": 0.9160267114639282,
"start": 158,
"tag": "PASSWORD",
"value": "env"
}
] | app/assets/javascripts/connections.js.coffee | fwoeck/voice-rails | 1 | app.setupPhone = ->
return unless phone.isWebRTCAvailable
return unless app.loadLocalKey('useWebRtc')
data =
login: env.sipAgent
password: env.sipSecret
phone.notify = (call) ->
console.log('SIP notify call:', call) if env.debug
phone.notifyAddCall = (call) ->
console.log('SIP add call:', call) if env.debug
if call.incoming
env.callDialogActive = true
name = app.sanitizeCallerName(call)
app.takeIncomingCall(call, name)
phone.notifyRemoveCall = (call) ->
console.log('SIP remove call:', call) if env.debug
if env.callDialogActive
env.callDialogActive = false
Voice.dialogController.cancel()
phone.notifyRegistered = (session) ->
console.log('SIP registered:', session) if env.debug
phone.app.login(data)
unless phone.app.hasAccessToAudio()
phone.app.getAccessToAudio()
app.setupSSE = ->
params = "?user_id=#{env.userId}&rails_env=#{env.railsEnv}&token=#{env.sessionToken}"
env.sseSource = new EventSource('/events' + params)
env.sseSource.onopen = (event) ->
env.sseErrors = 0
console.log(new Date, 'Opened SSE connection.') if env.debug
env.sseSource.onerror = (event) ->
console.log(new Date, 'SSE connection error', event)
env.sseErrors += 1
env.sseSource.close()
if env.sseErrors < 4
window.setTimeout app.setupSSE, 1000
else
app.dialog(i18n.dialog.lost_server_conn, 'error').then (->
app.logout()
)
env.sseSource.onmessage = (event) ->
Ember.run ->
data = JSON.parse(event.data)
console.log('SSE message:', data) if env.debug
app.parseIncomingData(data)
if env.railsEnv == 'test' && !data.servertime
env.messages.push(data)
| 115472 | app.setupPhone = ->
return unless phone.isWebRTCAvailable
return unless app.loadLocalKey('useWebRtc')
data =
login: env.sipAgent
password: <PASSWORD>.sipSecret
phone.notify = (call) ->
console.log('SIP notify call:', call) if env.debug
phone.notifyAddCall = (call) ->
console.log('SIP add call:', call) if env.debug
if call.incoming
env.callDialogActive = true
name = app.sanitizeCallerName(call)
app.takeIncomingCall(call, name)
phone.notifyRemoveCall = (call) ->
console.log('SIP remove call:', call) if env.debug
if env.callDialogActive
env.callDialogActive = false
Voice.dialogController.cancel()
phone.notifyRegistered = (session) ->
console.log('SIP registered:', session) if env.debug
phone.app.login(data)
unless phone.app.hasAccessToAudio()
phone.app.getAccessToAudio()
app.setupSSE = ->
params = "?user_id=#{env.userId}&rails_env=#{env.railsEnv}&token=#{env.sessionToken}"
env.sseSource = new EventSource('/events' + params)
env.sseSource.onopen = (event) ->
env.sseErrors = 0
console.log(new Date, 'Opened SSE connection.') if env.debug
env.sseSource.onerror = (event) ->
console.log(new Date, 'SSE connection error', event)
env.sseErrors += 1
env.sseSource.close()
if env.sseErrors < 4
window.setTimeout app.setupSSE, 1000
else
app.dialog(i18n.dialog.lost_server_conn, 'error').then (->
app.logout()
)
env.sseSource.onmessage = (event) ->
Ember.run ->
data = JSON.parse(event.data)
console.log('SSE message:', data) if env.debug
app.parseIncomingData(data)
if env.railsEnv == 'test' && !data.servertime
env.messages.push(data)
| true | app.setupPhone = ->
return unless phone.isWebRTCAvailable
return unless app.loadLocalKey('useWebRtc')
data =
login: env.sipAgent
password: PI:PASSWORD:<PASSWORD>END_PI.sipSecret
phone.notify = (call) ->
console.log('SIP notify call:', call) if env.debug
phone.notifyAddCall = (call) ->
console.log('SIP add call:', call) if env.debug
if call.incoming
env.callDialogActive = true
name = app.sanitizeCallerName(call)
app.takeIncomingCall(call, name)
phone.notifyRemoveCall = (call) ->
console.log('SIP remove call:', call) if env.debug
if env.callDialogActive
env.callDialogActive = false
Voice.dialogController.cancel()
phone.notifyRegistered = (session) ->
console.log('SIP registered:', session) if env.debug
phone.app.login(data)
unless phone.app.hasAccessToAudio()
phone.app.getAccessToAudio()
app.setupSSE = ->
params = "?user_id=#{env.userId}&rails_env=#{env.railsEnv}&token=#{env.sessionToken}"
env.sseSource = new EventSource('/events' + params)
env.sseSource.onopen = (event) ->
env.sseErrors = 0
console.log(new Date, 'Opened SSE connection.') if env.debug
env.sseSource.onerror = (event) ->
console.log(new Date, 'SSE connection error', event)
env.sseErrors += 1
env.sseSource.close()
if env.sseErrors < 4
window.setTimeout app.setupSSE, 1000
else
app.dialog(i18n.dialog.lost_server_conn, 'error').then (->
app.logout()
)
env.sseSource.onmessage = (event) ->
Ember.run ->
data = JSON.parse(event.data)
console.log('SSE message:', data) if env.debug
app.parseIncomingData(data)
if env.railsEnv == 'test' && !data.servertime
env.messages.push(data)
|
[
{
"context": " ], 'which-way'\n path.key.should.eql 'which-way'\n\n it 'sends the prompt', -> co ->\n d",
"end": 7979,
"score": 0.8081578612327576,
"start": 7970,
"tag": "KEY",
"value": "which-way"
}
] | test/unit/03-dialogue_test.coffee | PropertyUX/nubot-playbook | 0 | sinon = require 'sinon'
chai = require 'chai'
should = chai.should()
chai.use require 'sinon-chai'
co = require 'co'
_ = require 'lodash'
pretend = require 'hubot-pretend'
Dialogue = require '../../lib/modules/dialogue'
# get the null Timeout prototype instance for comparison
Timeout = setTimeout () ->
null
, 0
.constructor
# init some global test helpers
clock = null
testRes = null
matchRes = (value) ->
responseKeys = [ 'robot', 'message', 'match', 'envelope', 'dialogue' ]
difference = _.difference responseKeys, _.keys value
difference.length == 0
describe 'Dialogue', ->
beforeEach ->
pretend.start()
pretend.log.level = 'silent'
testRes = pretend.response 'tester', 'test', 'testing'
clock = sinon.useFakeTimers()
Object.getOwnPropertyNames(Dialogue.prototype).map (key) ->
sinon.spy Dialogue.prototype, key
afterEach ->
pretend.shutdown()
clock.restore()
Object.getOwnPropertyNames(Dialogue.prototype).map (key) ->
Dialogue.prototype[key].restore()
describe 'constructor', ->
it 'has null path', ->
dialogue = new Dialogue testRes
should.equal dialogue.path, null
it 'is not ended', ->
dialogue = new Dialogue testRes
dialogue.ended.should.be.false
it 'uses timeout from env', ->
process.env.DIALOGUE_TIMEOUT = 500
dialogue = new Dialogue testRes
dialogue.config.timeout.should.equal 500
delete process.env.DIALOGUE_TIMEOUT
describe '.end', ->
context 'before messages received', ->
it 'emits end with initial response', ->
dialogue = new Dialogue testRes
end = sinon.spy()
dialogue.on 'end', end
dialogue.end()
end.should.have.calledWith testRes
it 'sets ended to true', ->
dialogue = new Dialogue testRes
dialogue.end()
dialogue.ended.should.be.true
it 'returns true', ->
dialogue = new Dialogue testRes
dialogue.end()
.should.be.true
context 'after messages received', ->
it 'emits end with latest response (containing dialogue)', ->
dialogue = new Dialogue testRes
end = sinon.spy()
dialogue.on 'end', end
dialogue.receive testRes
dialogue.end()
end.should.have.calledWith sinon.match matchRes
context 'when timeout is running', ->
it 'clears the timeout', ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.startTimeout()
dialogue.end()
clock.tick 20
dialogue.clearTimeout.should.have.calledOnce
dialogue.onTimeout.should.not.have.called
context 'when already ended', ->
it 'returns false', ->
dialogue = new Dialogue testRes
dialogue.end()
dialogue.end()
.should.be.false
it 'should only emit end event once', ->
dialogue = new Dialogue testRes
end = sinon.spy()
dialogue.on 'end', end
dialogue.end()
dialogue.end()
end.should.have.calledOnce
describe '.send', ->
context 'with config.sendReplies set to false', ->
it 'sends to the room from original res', -> co ->
dialogue = new Dialogue testRes
yield dialogue.send 'test'
pretend.messages.pop().should.eql [ 'testing', 'hubot', 'test' ]
it 'emits send event with new response (containing dialogue)', -> co ->
dialogue = new Dialogue testRes
sendSpy = sinon.spy()
dialogue.on 'send', sendSpy
yield dialogue.send 'test'
sendSpy.should.have.calledWith sinon.match matchRes
it 'also emits with strings, methdod and original res', -> co ->
dialogue = new Dialogue testRes
sendSpy = sinon.spy()
dialogue.on 'send', sendSpy
yield dialogue.send 'test'
sendSpy.lastCall.args[1].should.eql
strings: [ 'test' ]
method: 'send'
received: testRes
context 'with config.sendReplies set to true', ->
it 'sends to room from original res, responding to the @user', -> co ->
dialogue = new Dialogue testRes, sendReplies: true
yield dialogue.send 'test'
pretend.messages.pop().should.eql [ 'testing', 'hubot', '@tester test' ]
describe '.onTimeout', ->
context 'default method', ->
it 'sends timeout message to room', ->
nextMessage = pretend.observer.next()
dialogue = new Dialogue testRes, timeout: 10
dialogue.startTimeout()
clock.tick 20
yield nextMessage
pretend.messages.pop().should.eql [
'testing', 'hubot', dialogue.config.timeoutText
]
context 'method override (as argument)', ->
it 'calls the override method', ->
dialogue = new Dialogue testRes, timeout: 10
timeout = sinon.spy()
dialogue.onTimeout timeout
dialogue.startTimeout()
clock.tick 20
dialogue.onTimeout.should.have.calledOnce
it 'does not send the default timeout message', ->
dialogue = new Dialogue testRes, timeout: 10
timeout = sinon.spy()
dialogue.onTimeout timeout
dialogue.startTimeout()
clock.tick 20
dialogue.send.should.not.have.called
context 'method override (by assignment)', ->
it 'calls the override method', ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.startTimeout()
clock.tick 20
dialogue.onTimeout.should.have.calledOnce
context 'method override with invalid function', ->
it 'throws exception', ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout -> throw new Error "Test exception"
override = sinon.spy dialogue, 'onTimeout'
dialogue.startTimeout()
try clock.tick 20
override.should.throw
describe '.clearTimeout', ->
describe '.startTimeout', ->
it 'emits timeout event', ->
dialogue = new Dialogue testRes, timeout: 10
timeoutMethod = sinon.spy()
dialogue.onTimeout timeoutMethod
timeoutEvent = sinon.spy()
dialogue.on 'timeout', timeoutEvent
dialogue.startTimeout()
clock.tick 20
timeoutEvent.should.have.calledOnce
it 'emits end event', ->
dialogue = new Dialogue testRes, timeout: 10
end = sinon.spy()
dialogue.on 'end', end
timeoutMethod = sinon.spy()
dialogue.onTimeout timeoutMethod
dialogue.startTimeout()
clock.tick 20
end.should.have.calledOnce
it 'clears existing timeout', ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.startTimeout()
dialogue.startTimeout()
clock.tick 20
dialogue.clearTimeout.should.have.calledOnce
dialogue.onTimeout.should.have.calledOnce
it 'calls onTimeout method', ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.startTimeout()
clock.tick 20
dialogue.onTimeout.should.have.calledOnce
it 'calls .end', ->
dialogue = new Dialogue testRes, timeout: 10, timeoutText: null
dialogue.startTimeout()
clock.tick 20
dialogue.end.should.have.calledOnce
describe '.addPath', ->
context 'with a prompt, branches and key', ->
it 'returns new Path instance', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath 'Turn left or right?', [
[ /left/, 'Ok, going left!' ]
[ /right/, 'Ok, going right!' ]
], 'which-way'
path.should.be.instanceof dialogue.Path
it 'passes options to path', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath 'Turn left or right?', [
[ /left/, 'Ok, going left!' ]
[ /right/, 'Ok, going right!' ]
], 'which-way'
path.key.should.eql 'which-way'
it 'sends the prompt', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath 'Turn left or right?', [
[ /left/, 'Ok, going left!' ]
[ /right/, 'Ok, going right!' ]
], 'which-way'
dialogue.send.should.have.calledWith 'Turn left or right?'
it 'starts timeout', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath 'Turn left or right?', [
[ /left/, 'Ok, going left!' ]
[ /right/, 'Ok, going right!' ]
], 'which-way'
dialogue.startTimeout.should.have.calledOnce
context 'with branches only', ->
it 'returns new Path instance', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath [
[ /1/, 'You get cake!' ]
[ /2/, 'You get cake!' ]
]
path.should.be.instanceof dialogue.Path
it 'sends nothing', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath [
[ /1/, 'You get cake!' ]
[ /2/, 'You get cake!' ]
]
dialogue.send.should.not.have.called
it 'starts timeout', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath [
[ /1/, 'You get cake!' ]
[ /2/, 'You get cake!' ]
]
dialogue.startTimeout.should.have.calledOnce
context 'without branches', ->
it 'returns new Path instance', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath "Don't say nothing."
path.should.be.instanceof dialogue.Path
it 'does not start timeout', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath "Don't say nothing."
dialogue.startTimeout.should.not.have.called
describe '.addBranch', ->
context 'with existing path', ->
it 'passes branch args on to path.addBranch', ->
dialogue = new Dialogue testRes
dialogue.path = addBranch: sinon.spy()
dialogue.addBranch /foo/, 'foo'
dialogue.path.addBranch.should.have.calledWith /foo/, 'foo'
it 'starts timeout', ->
dialogue = new Dialogue testRes
dialogue.path = addBranch: sinon.spy()
dialogue.addBranch /foo/, 'foo'
dialogue.startTimeout.should.have.calledOnce
context 'when no path exists', ->
it 'creates a new path', ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, 'foo'
dialogue.path.should.be.instanceof dialogue.Path
it 'passes branch args on to path.addBranch', ->
dialogue = new Dialogue testRes
sinon.spy dialogue.Path.prototype, 'addBranch'
dialogue.addBranch /foo/, 'foo'
dialogue.path.addBranch.should.have.calledWith /foo/, 'foo'
it 'starts timeout', ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, 'foo'
dialogue.startTimeout.should.have.calledOnce
context 'without further input', ->
it 'calls onTimeout', ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.addBranch /foo/, 'foo'
clock.tick 20
dialogue.onTimeout.should.have.calledOnce
describe '.receive', ->
it 'stores the latest response object', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /.*/, ->
yield dialogue.receive pretend.response 'tester', 'new test'
dialogue.res.message.text.should.equal 'new test'
it 'attaches itself to the response', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /.*/, ->
newTestRes = pretend.response 'tester', 'new test'
yield dialogue.receive newTestRes
newTestRes.dialogue.should.eql dialogue
context 'when already ended', ->
it 'returns false', -> co ->
dialogue = new Dialogue testRes
dialogue.end()
result = yield dialogue.receive testRes
result.should.be.false
it 'does not call the handler', -> co ->
dialogue = new Dialogue testRes
callback = sinon.spy()
dialogue.addBranch /.*/, callback
dialogue.end()
yield dialogue.receive testRes
callback.should.not.have.called
context 'on matching branch', ->
it 'clears timeout', -> co ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.addBranch /foo/, -> null
dialogue.onTimeout = sinon.spy()
yield dialogue.receive pretend.response 'tester', 'foo'
clock.tick 20
dialogue.clearTimeout.should.have.calledOnce
dialogue.onTimeout.should.not.have.called
it 'ends dialogue', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, -> null
yield dialogue.receive pretend.response 'tester', 'foo'
dialogue.end.should.have.calledOnce
it 'calls the branch handler', -> co ->
dialogue = new Dialogue testRes
callback = sinon.spy()
dialogue.addBranch /foo/, 'bar', callback
yield dialogue.receive pretend.response 'tester', 'foo'
callback.should.have.calledOnce
it 'sends the branch message', -> co ->
dialogue = new Dialogue testRes
callback = sinon.spy()
dialogue.addBranch /foo/, 'bar', callback
yield dialogue.receive pretend.response 'tester', 'foo'
dialogue.send.should.have.calledWith 'bar'
context 'on matching branches consecutively', ->
it 'only processes first match', -> co ->
dialogue = new Dialogue testRes
callback = sinon.spy()
dialogue.addBranch /foo/, callback
dialogue.addBranch /bar/, callback
yield dialogue.receive pretend.response 'tester', 'foo'
yield dialogue.receive pretend.response 'tester', 'bar'
callback.should.have.calledOnce
context 'on mismatch with catch', ->
it 'sends the catch message', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, ->
dialogue.path.config.catchMessage = 'huh?'
yield dialogue.receive pretend.response 'tester', '?'
dialogue.send.should.have.calledWith 'huh?'
it 'does not clear timeout', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, ->
dialogue.path.config.catchMessage = 'huh?'
yield dialogue.receive pretend.response 'tester', '?'
dialogue.clearTimeout.should.not.have.called
it 'does not call end', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, ->
dialogue.path.config.catchMessage = 'huh?'
yield dialogue.receive pretend.response 'tester', '?'
dialogue.end.should.not.have.called
context 'on mismatch without catch', ->
it 'does not clear timeout', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, ->
yield dialogue.receive pretend.response 'tester', '?'
dialogue.clearTimeout.should.not.have.called
it 'does not call end', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, ->
yield dialogue.receive pretend.response 'tester', '?'
dialogue.end.should.not.have.called
context 'on matching branch that adds a new branch', ->
it 'added branches to current path', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /more/, ->
dialogue.addBranch /1/, 'got 1'
dialogue.addBranch /2/, 'got 2'
yield dialogue.receive pretend.response 'tester', 'more'
_.map dialogue.path.branches, (branch) -> branch.regex
.should.eql [ /more/, /1/, /2/ ]
it 'does not call end', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /more/, ->
dialogue.addBranch /1/, 'got 1'
dialogue.addBranch /2/, 'got 2'
yield dialogue.receive pretend.response 'tester', 'more'
dialogue.end.should.not.have.called
it 'restarts the timeout', -> co ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.addBranch /more/, ->
dialogue.addBranch /1/, 'got 1',
dialogue.addBranch /2/, 'got 2',
yield dialogue.receive pretend.response 'tester', 'more'
dialogue.clearTimeout.callCount.should.equal 2
dialogue.startTimeout.callCount.should.equal 3
it 'calls onTimeout without input', -> co ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.addBranch /more/, ->
dialogue.addBranch /1/, 'got 1',
dialogue.addBranch /2/, 'got 2',
yield dialogue.receive pretend.response 'tester', 'more'
clock.tick 20
dialogue.onTimeout.should.have.called
context 'on matching branch that adds a new path', ->
it 'added new branches to new path, overwrites prev path', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /new/, ->
dialogue.addPath [ [ /1/, 'got 1' ], [ /2/, 'got 2' ] ]
yield dialogue.receive pretend.response 'tester', 'new'
_.map dialogue.path.branches, (branch) -> branch.regex
.should.eql [ /1/, /2/ ]
it 'does not call end', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /new/, ->
dialogue.addPath [ [ /1/, 'got 1' ], [ /2/, 'got 2' ] ]
yield dialogue.receive pretend.response 'tester', 'new'
dialogue.end.should.not.have.called
| 52954 | sinon = require 'sinon'
chai = require 'chai'
should = chai.should()
chai.use require 'sinon-chai'
co = require 'co'
_ = require 'lodash'
pretend = require 'hubot-pretend'
Dialogue = require '../../lib/modules/dialogue'
# get the null Timeout prototype instance for comparison
Timeout = setTimeout () ->
null
, 0
.constructor
# init some global test helpers
clock = null
testRes = null
matchRes = (value) ->
responseKeys = [ 'robot', 'message', 'match', 'envelope', 'dialogue' ]
difference = _.difference responseKeys, _.keys value
difference.length == 0
describe 'Dialogue', ->
beforeEach ->
pretend.start()
pretend.log.level = 'silent'
testRes = pretend.response 'tester', 'test', 'testing'
clock = sinon.useFakeTimers()
Object.getOwnPropertyNames(Dialogue.prototype).map (key) ->
sinon.spy Dialogue.prototype, key
afterEach ->
pretend.shutdown()
clock.restore()
Object.getOwnPropertyNames(Dialogue.prototype).map (key) ->
Dialogue.prototype[key].restore()
describe 'constructor', ->
it 'has null path', ->
dialogue = new Dialogue testRes
should.equal dialogue.path, null
it 'is not ended', ->
dialogue = new Dialogue testRes
dialogue.ended.should.be.false
it 'uses timeout from env', ->
process.env.DIALOGUE_TIMEOUT = 500
dialogue = new Dialogue testRes
dialogue.config.timeout.should.equal 500
delete process.env.DIALOGUE_TIMEOUT
describe '.end', ->
context 'before messages received', ->
it 'emits end with initial response', ->
dialogue = new Dialogue testRes
end = sinon.spy()
dialogue.on 'end', end
dialogue.end()
end.should.have.calledWith testRes
it 'sets ended to true', ->
dialogue = new Dialogue testRes
dialogue.end()
dialogue.ended.should.be.true
it 'returns true', ->
dialogue = new Dialogue testRes
dialogue.end()
.should.be.true
context 'after messages received', ->
it 'emits end with latest response (containing dialogue)', ->
dialogue = new Dialogue testRes
end = sinon.spy()
dialogue.on 'end', end
dialogue.receive testRes
dialogue.end()
end.should.have.calledWith sinon.match matchRes
context 'when timeout is running', ->
it 'clears the timeout', ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.startTimeout()
dialogue.end()
clock.tick 20
dialogue.clearTimeout.should.have.calledOnce
dialogue.onTimeout.should.not.have.called
context 'when already ended', ->
it 'returns false', ->
dialogue = new Dialogue testRes
dialogue.end()
dialogue.end()
.should.be.false
it 'should only emit end event once', ->
dialogue = new Dialogue testRes
end = sinon.spy()
dialogue.on 'end', end
dialogue.end()
dialogue.end()
end.should.have.calledOnce
describe '.send', ->
context 'with config.sendReplies set to false', ->
it 'sends to the room from original res', -> co ->
dialogue = new Dialogue testRes
yield dialogue.send 'test'
pretend.messages.pop().should.eql [ 'testing', 'hubot', 'test' ]
it 'emits send event with new response (containing dialogue)', -> co ->
dialogue = new Dialogue testRes
sendSpy = sinon.spy()
dialogue.on 'send', sendSpy
yield dialogue.send 'test'
sendSpy.should.have.calledWith sinon.match matchRes
it 'also emits with strings, methdod and original res', -> co ->
dialogue = new Dialogue testRes
sendSpy = sinon.spy()
dialogue.on 'send', sendSpy
yield dialogue.send 'test'
sendSpy.lastCall.args[1].should.eql
strings: [ 'test' ]
method: 'send'
received: testRes
context 'with config.sendReplies set to true', ->
it 'sends to room from original res, responding to the @user', -> co ->
dialogue = new Dialogue testRes, sendReplies: true
yield dialogue.send 'test'
pretend.messages.pop().should.eql [ 'testing', 'hubot', '@tester test' ]
describe '.onTimeout', ->
context 'default method', ->
it 'sends timeout message to room', ->
nextMessage = pretend.observer.next()
dialogue = new Dialogue testRes, timeout: 10
dialogue.startTimeout()
clock.tick 20
yield nextMessage
pretend.messages.pop().should.eql [
'testing', 'hubot', dialogue.config.timeoutText
]
context 'method override (as argument)', ->
it 'calls the override method', ->
dialogue = new Dialogue testRes, timeout: 10
timeout = sinon.spy()
dialogue.onTimeout timeout
dialogue.startTimeout()
clock.tick 20
dialogue.onTimeout.should.have.calledOnce
it 'does not send the default timeout message', ->
dialogue = new Dialogue testRes, timeout: 10
timeout = sinon.spy()
dialogue.onTimeout timeout
dialogue.startTimeout()
clock.tick 20
dialogue.send.should.not.have.called
context 'method override (by assignment)', ->
it 'calls the override method', ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.startTimeout()
clock.tick 20
dialogue.onTimeout.should.have.calledOnce
context 'method override with invalid function', ->
it 'throws exception', ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout -> throw new Error "Test exception"
override = sinon.spy dialogue, 'onTimeout'
dialogue.startTimeout()
try clock.tick 20
override.should.throw
describe '.clearTimeout', ->
describe '.startTimeout', ->
it 'emits timeout event', ->
dialogue = new Dialogue testRes, timeout: 10
timeoutMethod = sinon.spy()
dialogue.onTimeout timeoutMethod
timeoutEvent = sinon.spy()
dialogue.on 'timeout', timeoutEvent
dialogue.startTimeout()
clock.tick 20
timeoutEvent.should.have.calledOnce
it 'emits end event', ->
dialogue = new Dialogue testRes, timeout: 10
end = sinon.spy()
dialogue.on 'end', end
timeoutMethod = sinon.spy()
dialogue.onTimeout timeoutMethod
dialogue.startTimeout()
clock.tick 20
end.should.have.calledOnce
it 'clears existing timeout', ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.startTimeout()
dialogue.startTimeout()
clock.tick 20
dialogue.clearTimeout.should.have.calledOnce
dialogue.onTimeout.should.have.calledOnce
it 'calls onTimeout method', ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.startTimeout()
clock.tick 20
dialogue.onTimeout.should.have.calledOnce
it 'calls .end', ->
dialogue = new Dialogue testRes, timeout: 10, timeoutText: null
dialogue.startTimeout()
clock.tick 20
dialogue.end.should.have.calledOnce
describe '.addPath', ->
context 'with a prompt, branches and key', ->
it 'returns new Path instance', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath 'Turn left or right?', [
[ /left/, 'Ok, going left!' ]
[ /right/, 'Ok, going right!' ]
], 'which-way'
path.should.be.instanceof dialogue.Path
it 'passes options to path', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath 'Turn left or right?', [
[ /left/, 'Ok, going left!' ]
[ /right/, 'Ok, going right!' ]
], 'which-way'
path.key.should.eql '<KEY>'
it 'sends the prompt', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath 'Turn left or right?', [
[ /left/, 'Ok, going left!' ]
[ /right/, 'Ok, going right!' ]
], 'which-way'
dialogue.send.should.have.calledWith 'Turn left or right?'
it 'starts timeout', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath 'Turn left or right?', [
[ /left/, 'Ok, going left!' ]
[ /right/, 'Ok, going right!' ]
], 'which-way'
dialogue.startTimeout.should.have.calledOnce
context 'with branches only', ->
it 'returns new Path instance', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath [
[ /1/, 'You get cake!' ]
[ /2/, 'You get cake!' ]
]
path.should.be.instanceof dialogue.Path
it 'sends nothing', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath [
[ /1/, 'You get cake!' ]
[ /2/, 'You get cake!' ]
]
dialogue.send.should.not.have.called
it 'starts timeout', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath [
[ /1/, 'You get cake!' ]
[ /2/, 'You get cake!' ]
]
dialogue.startTimeout.should.have.calledOnce
context 'without branches', ->
it 'returns new Path instance', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath "Don't say nothing."
path.should.be.instanceof dialogue.Path
it 'does not start timeout', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath "Don't say nothing."
dialogue.startTimeout.should.not.have.called
describe '.addBranch', ->
context 'with existing path', ->
it 'passes branch args on to path.addBranch', ->
dialogue = new Dialogue testRes
dialogue.path = addBranch: sinon.spy()
dialogue.addBranch /foo/, 'foo'
dialogue.path.addBranch.should.have.calledWith /foo/, 'foo'
it 'starts timeout', ->
dialogue = new Dialogue testRes
dialogue.path = addBranch: sinon.spy()
dialogue.addBranch /foo/, 'foo'
dialogue.startTimeout.should.have.calledOnce
context 'when no path exists', ->
it 'creates a new path', ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, 'foo'
dialogue.path.should.be.instanceof dialogue.Path
it 'passes branch args on to path.addBranch', ->
dialogue = new Dialogue testRes
sinon.spy dialogue.Path.prototype, 'addBranch'
dialogue.addBranch /foo/, 'foo'
dialogue.path.addBranch.should.have.calledWith /foo/, 'foo'
it 'starts timeout', ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, 'foo'
dialogue.startTimeout.should.have.calledOnce
context 'without further input', ->
it 'calls onTimeout', ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.addBranch /foo/, 'foo'
clock.tick 20
dialogue.onTimeout.should.have.calledOnce
describe '.receive', ->
it 'stores the latest response object', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /.*/, ->
yield dialogue.receive pretend.response 'tester', 'new test'
dialogue.res.message.text.should.equal 'new test'
it 'attaches itself to the response', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /.*/, ->
newTestRes = pretend.response 'tester', 'new test'
yield dialogue.receive newTestRes
newTestRes.dialogue.should.eql dialogue
context 'when already ended', ->
it 'returns false', -> co ->
dialogue = new Dialogue testRes
dialogue.end()
result = yield dialogue.receive testRes
result.should.be.false
it 'does not call the handler', -> co ->
dialogue = new Dialogue testRes
callback = sinon.spy()
dialogue.addBranch /.*/, callback
dialogue.end()
yield dialogue.receive testRes
callback.should.not.have.called
context 'on matching branch', ->
it 'clears timeout', -> co ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.addBranch /foo/, -> null
dialogue.onTimeout = sinon.spy()
yield dialogue.receive pretend.response 'tester', 'foo'
clock.tick 20
dialogue.clearTimeout.should.have.calledOnce
dialogue.onTimeout.should.not.have.called
it 'ends dialogue', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, -> null
yield dialogue.receive pretend.response 'tester', 'foo'
dialogue.end.should.have.calledOnce
it 'calls the branch handler', -> co ->
dialogue = new Dialogue testRes
callback = sinon.spy()
dialogue.addBranch /foo/, 'bar', callback
yield dialogue.receive pretend.response 'tester', 'foo'
callback.should.have.calledOnce
it 'sends the branch message', -> co ->
dialogue = new Dialogue testRes
callback = sinon.spy()
dialogue.addBranch /foo/, 'bar', callback
yield dialogue.receive pretend.response 'tester', 'foo'
dialogue.send.should.have.calledWith 'bar'
context 'on matching branches consecutively', ->
it 'only processes first match', -> co ->
dialogue = new Dialogue testRes
callback = sinon.spy()
dialogue.addBranch /foo/, callback
dialogue.addBranch /bar/, callback
yield dialogue.receive pretend.response 'tester', 'foo'
yield dialogue.receive pretend.response 'tester', 'bar'
callback.should.have.calledOnce
context 'on mismatch with catch', ->
it 'sends the catch message', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, ->
dialogue.path.config.catchMessage = 'huh?'
yield dialogue.receive pretend.response 'tester', '?'
dialogue.send.should.have.calledWith 'huh?'
it 'does not clear timeout', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, ->
dialogue.path.config.catchMessage = 'huh?'
yield dialogue.receive pretend.response 'tester', '?'
dialogue.clearTimeout.should.not.have.called
it 'does not call end', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, ->
dialogue.path.config.catchMessage = 'huh?'
yield dialogue.receive pretend.response 'tester', '?'
dialogue.end.should.not.have.called
context 'on mismatch without catch', ->
it 'does not clear timeout', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, ->
yield dialogue.receive pretend.response 'tester', '?'
dialogue.clearTimeout.should.not.have.called
it 'does not call end', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, ->
yield dialogue.receive pretend.response 'tester', '?'
dialogue.end.should.not.have.called
context 'on matching branch that adds a new branch', ->
it 'added branches to current path', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /more/, ->
dialogue.addBranch /1/, 'got 1'
dialogue.addBranch /2/, 'got 2'
yield dialogue.receive pretend.response 'tester', 'more'
_.map dialogue.path.branches, (branch) -> branch.regex
.should.eql [ /more/, /1/, /2/ ]
it 'does not call end', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /more/, ->
dialogue.addBranch /1/, 'got 1'
dialogue.addBranch /2/, 'got 2'
yield dialogue.receive pretend.response 'tester', 'more'
dialogue.end.should.not.have.called
it 'restarts the timeout', -> co ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.addBranch /more/, ->
dialogue.addBranch /1/, 'got 1',
dialogue.addBranch /2/, 'got 2',
yield dialogue.receive pretend.response 'tester', 'more'
dialogue.clearTimeout.callCount.should.equal 2
dialogue.startTimeout.callCount.should.equal 3
it 'calls onTimeout without input', -> co ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.addBranch /more/, ->
dialogue.addBranch /1/, 'got 1',
dialogue.addBranch /2/, 'got 2',
yield dialogue.receive pretend.response 'tester', 'more'
clock.tick 20
dialogue.onTimeout.should.have.called
context 'on matching branch that adds a new path', ->
it 'added new branches to new path, overwrites prev path', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /new/, ->
dialogue.addPath [ [ /1/, 'got 1' ], [ /2/, 'got 2' ] ]
yield dialogue.receive pretend.response 'tester', 'new'
_.map dialogue.path.branches, (branch) -> branch.regex
.should.eql [ /1/, /2/ ]
it 'does not call end', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /new/, ->
dialogue.addPath [ [ /1/, 'got 1' ], [ /2/, 'got 2' ] ]
yield dialogue.receive pretend.response 'tester', 'new'
dialogue.end.should.not.have.called
| true | sinon = require 'sinon'
chai = require 'chai'
should = chai.should()
chai.use require 'sinon-chai'
co = require 'co'
_ = require 'lodash'
pretend = require 'hubot-pretend'
Dialogue = require '../../lib/modules/dialogue'
# get the null Timeout prototype instance for comparison
Timeout = setTimeout () ->
null
, 0
.constructor
# init some global test helpers
clock = null
testRes = null
matchRes = (value) ->
responseKeys = [ 'robot', 'message', 'match', 'envelope', 'dialogue' ]
difference = _.difference responseKeys, _.keys value
difference.length == 0
describe 'Dialogue', ->
beforeEach ->
pretend.start()
pretend.log.level = 'silent'
testRes = pretend.response 'tester', 'test', 'testing'
clock = sinon.useFakeTimers()
Object.getOwnPropertyNames(Dialogue.prototype).map (key) ->
sinon.spy Dialogue.prototype, key
afterEach ->
pretend.shutdown()
clock.restore()
Object.getOwnPropertyNames(Dialogue.prototype).map (key) ->
Dialogue.prototype[key].restore()
describe 'constructor', ->
it 'has null path', ->
dialogue = new Dialogue testRes
should.equal dialogue.path, null
it 'is not ended', ->
dialogue = new Dialogue testRes
dialogue.ended.should.be.false
it 'uses timeout from env', ->
process.env.DIALOGUE_TIMEOUT = 500
dialogue = new Dialogue testRes
dialogue.config.timeout.should.equal 500
delete process.env.DIALOGUE_TIMEOUT
describe '.end', ->
context 'before messages received', ->
it 'emits end with initial response', ->
dialogue = new Dialogue testRes
end = sinon.spy()
dialogue.on 'end', end
dialogue.end()
end.should.have.calledWith testRes
it 'sets ended to true', ->
dialogue = new Dialogue testRes
dialogue.end()
dialogue.ended.should.be.true
it 'returns true', ->
dialogue = new Dialogue testRes
dialogue.end()
.should.be.true
context 'after messages received', ->
it 'emits end with latest response (containing dialogue)', ->
dialogue = new Dialogue testRes
end = sinon.spy()
dialogue.on 'end', end
dialogue.receive testRes
dialogue.end()
end.should.have.calledWith sinon.match matchRes
context 'when timeout is running', ->
it 'clears the timeout', ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.startTimeout()
dialogue.end()
clock.tick 20
dialogue.clearTimeout.should.have.calledOnce
dialogue.onTimeout.should.not.have.called
context 'when already ended', ->
it 'returns false', ->
dialogue = new Dialogue testRes
dialogue.end()
dialogue.end()
.should.be.false
it 'should only emit end event once', ->
dialogue = new Dialogue testRes
end = sinon.spy()
dialogue.on 'end', end
dialogue.end()
dialogue.end()
end.should.have.calledOnce
describe '.send', ->
context 'with config.sendReplies set to false', ->
it 'sends to the room from original res', -> co ->
dialogue = new Dialogue testRes
yield dialogue.send 'test'
pretend.messages.pop().should.eql [ 'testing', 'hubot', 'test' ]
it 'emits send event with new response (containing dialogue)', -> co ->
dialogue = new Dialogue testRes
sendSpy = sinon.spy()
dialogue.on 'send', sendSpy
yield dialogue.send 'test'
sendSpy.should.have.calledWith sinon.match matchRes
it 'also emits with strings, methdod and original res', -> co ->
dialogue = new Dialogue testRes
sendSpy = sinon.spy()
dialogue.on 'send', sendSpy
yield dialogue.send 'test'
sendSpy.lastCall.args[1].should.eql
strings: [ 'test' ]
method: 'send'
received: testRes
context 'with config.sendReplies set to true', ->
it 'sends to room from original res, responding to the @user', -> co ->
dialogue = new Dialogue testRes, sendReplies: true
yield dialogue.send 'test'
pretend.messages.pop().should.eql [ 'testing', 'hubot', '@tester test' ]
describe '.onTimeout', ->
context 'default method', ->
it 'sends timeout message to room', ->
nextMessage = pretend.observer.next()
dialogue = new Dialogue testRes, timeout: 10
dialogue.startTimeout()
clock.tick 20
yield nextMessage
pretend.messages.pop().should.eql [
'testing', 'hubot', dialogue.config.timeoutText
]
context 'method override (as argument)', ->
it 'calls the override method', ->
dialogue = new Dialogue testRes, timeout: 10
timeout = sinon.spy()
dialogue.onTimeout timeout
dialogue.startTimeout()
clock.tick 20
dialogue.onTimeout.should.have.calledOnce
it 'does not send the default timeout message', ->
dialogue = new Dialogue testRes, timeout: 10
timeout = sinon.spy()
dialogue.onTimeout timeout
dialogue.startTimeout()
clock.tick 20
dialogue.send.should.not.have.called
context 'method override (by assignment)', ->
it 'calls the override method', ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.startTimeout()
clock.tick 20
dialogue.onTimeout.should.have.calledOnce
context 'method override with invalid function', ->
it 'throws exception', ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout -> throw new Error "Test exception"
override = sinon.spy dialogue, 'onTimeout'
dialogue.startTimeout()
try clock.tick 20
override.should.throw
describe '.clearTimeout', ->
describe '.startTimeout', ->
it 'emits timeout event', ->
dialogue = new Dialogue testRes, timeout: 10
timeoutMethod = sinon.spy()
dialogue.onTimeout timeoutMethod
timeoutEvent = sinon.spy()
dialogue.on 'timeout', timeoutEvent
dialogue.startTimeout()
clock.tick 20
timeoutEvent.should.have.calledOnce
it 'emits end event', ->
dialogue = new Dialogue testRes, timeout: 10
end = sinon.spy()
dialogue.on 'end', end
timeoutMethod = sinon.spy()
dialogue.onTimeout timeoutMethod
dialogue.startTimeout()
clock.tick 20
end.should.have.calledOnce
it 'clears existing timeout', ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.startTimeout()
dialogue.startTimeout()
clock.tick 20
dialogue.clearTimeout.should.have.calledOnce
dialogue.onTimeout.should.have.calledOnce
it 'calls onTimeout method', ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.startTimeout()
clock.tick 20
dialogue.onTimeout.should.have.calledOnce
it 'calls .end', ->
dialogue = new Dialogue testRes, timeout: 10, timeoutText: null
dialogue.startTimeout()
clock.tick 20
dialogue.end.should.have.calledOnce
describe '.addPath', ->
context 'with a prompt, branches and key', ->
it 'returns new Path instance', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath 'Turn left or right?', [
[ /left/, 'Ok, going left!' ]
[ /right/, 'Ok, going right!' ]
], 'which-way'
path.should.be.instanceof dialogue.Path
it 'passes options to path', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath 'Turn left or right?', [
[ /left/, 'Ok, going left!' ]
[ /right/, 'Ok, going right!' ]
], 'which-way'
path.key.should.eql 'PI:KEY:<KEY>END_PI'
it 'sends the prompt', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath 'Turn left or right?', [
[ /left/, 'Ok, going left!' ]
[ /right/, 'Ok, going right!' ]
], 'which-way'
dialogue.send.should.have.calledWith 'Turn left or right?'
it 'starts timeout', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath 'Turn left or right?', [
[ /left/, 'Ok, going left!' ]
[ /right/, 'Ok, going right!' ]
], 'which-way'
dialogue.startTimeout.should.have.calledOnce
context 'with branches only', ->
it 'returns new Path instance', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath [
[ /1/, 'You get cake!' ]
[ /2/, 'You get cake!' ]
]
path.should.be.instanceof dialogue.Path
it 'sends nothing', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath [
[ /1/, 'You get cake!' ]
[ /2/, 'You get cake!' ]
]
dialogue.send.should.not.have.called
it 'starts timeout', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath [
[ /1/, 'You get cake!' ]
[ /2/, 'You get cake!' ]
]
dialogue.startTimeout.should.have.calledOnce
context 'without branches', ->
it 'returns new Path instance', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath "Don't say nothing."
path.should.be.instanceof dialogue.Path
it 'does not start timeout', -> co ->
dialogue = new Dialogue testRes
path = yield dialogue.addPath "Don't say nothing."
dialogue.startTimeout.should.not.have.called
describe '.addBranch', ->
context 'with existing path', ->
it 'passes branch args on to path.addBranch', ->
dialogue = new Dialogue testRes
dialogue.path = addBranch: sinon.spy()
dialogue.addBranch /foo/, 'foo'
dialogue.path.addBranch.should.have.calledWith /foo/, 'foo'
it 'starts timeout', ->
dialogue = new Dialogue testRes
dialogue.path = addBranch: sinon.spy()
dialogue.addBranch /foo/, 'foo'
dialogue.startTimeout.should.have.calledOnce
context 'when no path exists', ->
it 'creates a new path', ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, 'foo'
dialogue.path.should.be.instanceof dialogue.Path
it 'passes branch args on to path.addBranch', ->
dialogue = new Dialogue testRes
sinon.spy dialogue.Path.prototype, 'addBranch'
dialogue.addBranch /foo/, 'foo'
dialogue.path.addBranch.should.have.calledWith /foo/, 'foo'
it 'starts timeout', ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, 'foo'
dialogue.startTimeout.should.have.calledOnce
context 'without further input', ->
it 'calls onTimeout', ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.addBranch /foo/, 'foo'
clock.tick 20
dialogue.onTimeout.should.have.calledOnce
describe '.receive', ->
it 'stores the latest response object', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /.*/, ->
yield dialogue.receive pretend.response 'tester', 'new test'
dialogue.res.message.text.should.equal 'new test'
it 'attaches itself to the response', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /.*/, ->
newTestRes = pretend.response 'tester', 'new test'
yield dialogue.receive newTestRes
newTestRes.dialogue.should.eql dialogue
context 'when already ended', ->
it 'returns false', -> co ->
dialogue = new Dialogue testRes
dialogue.end()
result = yield dialogue.receive testRes
result.should.be.false
it 'does not call the handler', -> co ->
dialogue = new Dialogue testRes
callback = sinon.spy()
dialogue.addBranch /.*/, callback
dialogue.end()
yield dialogue.receive testRes
callback.should.not.have.called
context 'on matching branch', ->
it 'clears timeout', -> co ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.addBranch /foo/, -> null
dialogue.onTimeout = sinon.spy()
yield dialogue.receive pretend.response 'tester', 'foo'
clock.tick 20
dialogue.clearTimeout.should.have.calledOnce
dialogue.onTimeout.should.not.have.called
it 'ends dialogue', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, -> null
yield dialogue.receive pretend.response 'tester', 'foo'
dialogue.end.should.have.calledOnce
it 'calls the branch handler', -> co ->
dialogue = new Dialogue testRes
callback = sinon.spy()
dialogue.addBranch /foo/, 'bar', callback
yield dialogue.receive pretend.response 'tester', 'foo'
callback.should.have.calledOnce
it 'sends the branch message', -> co ->
dialogue = new Dialogue testRes
callback = sinon.spy()
dialogue.addBranch /foo/, 'bar', callback
yield dialogue.receive pretend.response 'tester', 'foo'
dialogue.send.should.have.calledWith 'bar'
context 'on matching branches consecutively', ->
it 'only processes first match', -> co ->
dialogue = new Dialogue testRes
callback = sinon.spy()
dialogue.addBranch /foo/, callback
dialogue.addBranch /bar/, callback
yield dialogue.receive pretend.response 'tester', 'foo'
yield dialogue.receive pretend.response 'tester', 'bar'
callback.should.have.calledOnce
context 'on mismatch with catch', ->
it 'sends the catch message', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, ->
dialogue.path.config.catchMessage = 'huh?'
yield dialogue.receive pretend.response 'tester', '?'
dialogue.send.should.have.calledWith 'huh?'
it 'does not clear timeout', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, ->
dialogue.path.config.catchMessage = 'huh?'
yield dialogue.receive pretend.response 'tester', '?'
dialogue.clearTimeout.should.not.have.called
it 'does not call end', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, ->
dialogue.path.config.catchMessage = 'huh?'
yield dialogue.receive pretend.response 'tester', '?'
dialogue.end.should.not.have.called
context 'on mismatch without catch', ->
it 'does not clear timeout', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, ->
yield dialogue.receive pretend.response 'tester', '?'
dialogue.clearTimeout.should.not.have.called
it 'does not call end', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /foo/, ->
yield dialogue.receive pretend.response 'tester', '?'
dialogue.end.should.not.have.called
context 'on matching branch that adds a new branch', ->
it 'added branches to current path', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /more/, ->
dialogue.addBranch /1/, 'got 1'
dialogue.addBranch /2/, 'got 2'
yield dialogue.receive pretend.response 'tester', 'more'
_.map dialogue.path.branches, (branch) -> branch.regex
.should.eql [ /more/, /1/, /2/ ]
it 'does not call end', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /more/, ->
dialogue.addBranch /1/, 'got 1'
dialogue.addBranch /2/, 'got 2'
yield dialogue.receive pretend.response 'tester', 'more'
dialogue.end.should.not.have.called
it 'restarts the timeout', -> co ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.addBranch /more/, ->
dialogue.addBranch /1/, 'got 1',
dialogue.addBranch /2/, 'got 2',
yield dialogue.receive pretend.response 'tester', 'more'
dialogue.clearTimeout.callCount.should.equal 2
dialogue.startTimeout.callCount.should.equal 3
it 'calls onTimeout without input', -> co ->
dialogue = new Dialogue testRes, timeout: 10
dialogue.onTimeout = sinon.spy()
dialogue.addBranch /more/, ->
dialogue.addBranch /1/, 'got 1',
dialogue.addBranch /2/, 'got 2',
yield dialogue.receive pretend.response 'tester', 'more'
clock.tick 20
dialogue.onTimeout.should.have.called
context 'on matching branch that adds a new path', ->
it 'added new branches to new path, overwrites prev path', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /new/, ->
dialogue.addPath [ [ /1/, 'got 1' ], [ /2/, 'got 2' ] ]
yield dialogue.receive pretend.response 'tester', 'new'
_.map dialogue.path.branches, (branch) -> branch.regex
.should.eql [ /1/, /2/ ]
it 'does not call end', -> co ->
dialogue = new Dialogue testRes
dialogue.addBranch /new/, ->
dialogue.addPath [ [ /1/, 'got 1' ], [ /2/, 'got 2' ] ]
yield dialogue.receive pretend.response 'tester', 'new'
dialogue.end.should.not.have.called
|
[
{
"context": "ser: user }, (e, o) ->\n if o\n if o.pass == pass then callback(o) else callback(null)\n else\n ",
"end": 946,
"score": 0.559292733669281,
"start": 942,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": " callback null\n event.emit 'login',\n pass: pass\n user: user\n return\n return\n\nexports.man",
"end": 1053,
"score": 0.9135021567344666,
"start": 1049,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": "ser not found\"\n succes: false\n pass: pass\n user: user\n else\n validatePasswor",
"end": 1351,
"score": 0.9911696910858154,
"start": 1347,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": "tered\"\n succes: false\n pass: pass\n user: user\n return\n return\n",
"end": 1773,
"score": 0.9956989288330078,
"start": 1769,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": "counts.find { $and: [ {\n email: email\n pass: passHash\n } ] }, (e, o) ->\n callback if o then 'ok' el",
"end": 5062,
"score": 0.9890261292457581,
"start": 5054,
"tag": "PASSWORD",
"value": "passHash"
}
] | app/server/modules/account-manager.mongo.coffee | coderofsalvation/express-api-user-management-signup | 1 | crypto = require('crypto')
mongo = require('mongodb')
MongoClient = mongo.MongoClient
moment = require('moment')
EventEmitter = require('events').EventEmitter
event = exports.event = new EventEmitter
### establish the database connection ###
db = {}
accounts = {}
exports.init = (cfg) ->
dbPort = (cfg.port || 27017)
dbHost = (cfg.host || 'localhost')
dbName = (cfg.name || 'express-api-user-management-signup' )
url = "mongodb://";
url += cfg.username+":"+cfg.password+"@" if cfg.username && cfg.password
url += dbHost+":"+dbPort+"/"+dbName
MongoClient.connect url, (err,dbhandle) ->
db = dbhandle
status = 'connected to database'
if !err
accounts = db.collection('accounts')
else
status = "not "+status+" "+url+" :("
console.log status
### login validation methods ###
exports.autoLogin = (user, pass, callback) ->
accounts.findOne { user: user }, (e, o) ->
if o
if o.pass == pass then callback(o) else callback(null)
else
callback null
event.emit 'login',
pass: pass
user: user
return
return
exports.manualLogin = (user, pass, callback) ->
accounts.findOne { user: user }, (e, o) ->
console.dir o
if o == null
callback 'user-not-found'
event.emit 'login',
reason: "user not found"
succes: false
pass: pass
user: user
else
validatePassword pass, o.pass, (err, res) ->
if res
callback null, o
event.emit 'login',
reason: ""
succes: true
pass: pass
user: user
else
callback 'invalid-password'
event.emit 'login',
reason: "invalid password entered"
succes: false
pass: pass
user: user
return
return
return
### record insertion, update & deletion methods ###
exports.addNewAccount = (newData, callback) ->
accounts.findOne { user: newData.user }, (e, o) ->
if o
callback 'username-taken'
else
accounts.findOne { email: newData.email }, (e, o) ->
if o
callback 'email-taken'
else
saltAndHash newData.pass, (hash) ->
newData.pass = hash
generateApiKey hash, (apikey) ->
newData.apikey = apikey
# append date stamp when record was created //
newData.date = moment().format('MMMM Do YYYY, h:mm:ss a')
newData.inactive = false
newData.log = [ newData.date+" added account: "+JSON.stringify(newData) ]
accounts.insert newData, { safe: true }, callback
event.emit 'addNewAccount', newData
return
return
return
return
exports.updateAccount = (newData, callback) ->
accounts.findOne { user: newData.user }, (e, o) ->
o.name = newData.name
o.email = newData.email
o.country = newData.country
o.meta = newData.meta if newData.meta
o.log = [] if o.log is undefined # backwards compatible with older versions
if newData.pass == ''
o.log.push moment().format('MMMM Do YYYY, h:mm:ss a')+" updated account with: "+JSON.stringify(newData)
accounts.save o, { safe: true }, (err) ->
if err
callback err
else
callback null, o
return
else
saltAndHash newData.pass, (hash) ->
o.pass = hash
o.log.push moment().format('MMMM Do YYYY, h:mm:ss a')+" updated account + password"+JSON.stringify(newData)
accounts.save o, { safe: true}, (err) ->
if err
callback err
else
callback null, o
event.emit 'updateAccount', o
return
return
return
return
exports.updateApiKey = (user, newApiKey, callback) ->
accounts.findOne { user: user }, (e, o) ->
if e
callback e, null
else
o.apikey = newApiKey
console.dir o
o.log.push moment().format('MMMM Do YYYY, h:mm:ss a')+" apikey updated to "+o.apikey
accounts.save o, { safe: true }, callback
event.emit 'updateApikey', o
callback e, o
return
return
exports.updatePassword = (email, newPass, callback) ->
accounts.findOne { email: email }, (e, o) ->
if e
callback e, null
else
saltAndHash newPass, (hash) ->
o.pass = hash
accounts.save o, { safe: true }, callback
event.emit 'updatePassword', o
return
return
return
### account lookup methods ###
# don't delete because of 'oh I accidentally deleted our account'-requests
exports.deleteAccount = (id, callback) ->
accounts.save { _id: getObjectId(id), inactive:true }, callback
return
exports.purgeAccount = (id, callback) ->
accounts.remove { _id: getObjectId(id) }, callback
return
exports.getAccountByEmail = (email, callback) ->
accounts.findOne { email: email }, (e, o) ->
callback o
return
return
exports.validateResetLink = (email, passHash, callback) ->
accounts.find { $and: [ {
email: email
pass: passHash
} ] }, (e, o) ->
callback if o then 'ok' else null
return
return
exports.getAllRecords = (callback) ->
accounts.find().toArray (e, res) ->
if e
callback e
else
callback null, res
return
return
exports.delAllRecords = (callback) ->
accounts.remove {}, callback
# reset accounts collection for testing //
return
### private encryption & validation methods ###
generateSalt = ->
set = '0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ'
salt = ''
i = 0
while i < 10
p = Math.floor(Math.random() * set.length)
salt += set[p]
i++
salt
md5 = (str) ->
crypto.createHash('md5').update(str).digest 'hex'
saltAndHash = (pass, callback) ->
salt = generateSalt()
callback salt + md5(pass + salt)
return
validatePassword = (plainPass, hashedPass, callback) ->
salt = String(hashedPass).substr(0, 10)
validHash = salt + md5(plainPass + salt)
callback null, hashedPass == validHash
return
### auxiliary methods ###
getObjectId = (id) ->
accounts.db.bson_serializer.ObjectID.createFromHexString id
findById = (id, callback) ->
accounts.findOne { _id: getObjectId(id) }, (e, res) ->
if e
callback e
else
callback null, res
return
return
findByMultipleFields = (a, callback) ->
# this takes an array of name/val pairs to search against {fieldName : 'value'} //
accounts.find($or: a).toArray (e, results) ->
if e
callback e
else
callback null, results
return
return
generateApiKey = exports.generateApiKey = (hash,cb) ->
saltAndHash hash, (apikey) ->
cb( apikey.substr(0,24) )
# ---
# generated by js2coffee 2.0.3
| 179701 | crypto = require('crypto')
mongo = require('mongodb')
MongoClient = mongo.MongoClient
moment = require('moment')
EventEmitter = require('events').EventEmitter
event = exports.event = new EventEmitter
### establish the database connection ###
db = {}
accounts = {}
exports.init = (cfg) ->
dbPort = (cfg.port || 27017)
dbHost = (cfg.host || 'localhost')
dbName = (cfg.name || 'express-api-user-management-signup' )
url = "mongodb://";
url += cfg.username+":"+cfg.password+"@" if cfg.username && cfg.password
url += dbHost+":"+dbPort+"/"+dbName
MongoClient.connect url, (err,dbhandle) ->
db = dbhandle
status = 'connected to database'
if !err
accounts = db.collection('accounts')
else
status = "not "+status+" "+url+" :("
console.log status
### login validation methods ###
exports.autoLogin = (user, pass, callback) ->
accounts.findOne { user: user }, (e, o) ->
if o
if o.pass == <PASSWORD> then callback(o) else callback(null)
else
callback null
event.emit 'login',
pass: <PASSWORD>
user: user
return
return
exports.manualLogin = (user, pass, callback) ->
accounts.findOne { user: user }, (e, o) ->
console.dir o
if o == null
callback 'user-not-found'
event.emit 'login',
reason: "user not found"
succes: false
pass: <PASSWORD>
user: user
else
validatePassword pass, o.pass, (err, res) ->
if res
callback null, o
event.emit 'login',
reason: ""
succes: true
pass: pass
user: user
else
callback 'invalid-password'
event.emit 'login',
reason: "invalid password entered"
succes: false
pass: <PASSWORD>
user: user
return
return
return
### record insertion, update & deletion methods ###
exports.addNewAccount = (newData, callback) ->
accounts.findOne { user: newData.user }, (e, o) ->
if o
callback 'username-taken'
else
accounts.findOne { email: newData.email }, (e, o) ->
if o
callback 'email-taken'
else
saltAndHash newData.pass, (hash) ->
newData.pass = hash
generateApiKey hash, (apikey) ->
newData.apikey = apikey
# append date stamp when record was created //
newData.date = moment().format('MMMM Do YYYY, h:mm:ss a')
newData.inactive = false
newData.log = [ newData.date+" added account: "+JSON.stringify(newData) ]
accounts.insert newData, { safe: true }, callback
event.emit 'addNewAccount', newData
return
return
return
return
exports.updateAccount = (newData, callback) ->
accounts.findOne { user: newData.user }, (e, o) ->
o.name = newData.name
o.email = newData.email
o.country = newData.country
o.meta = newData.meta if newData.meta
o.log = [] if o.log is undefined # backwards compatible with older versions
if newData.pass == ''
o.log.push moment().format('MMMM Do YYYY, h:mm:ss a')+" updated account with: "+JSON.stringify(newData)
accounts.save o, { safe: true }, (err) ->
if err
callback err
else
callback null, o
return
else
saltAndHash newData.pass, (hash) ->
o.pass = hash
o.log.push moment().format('MMMM Do YYYY, h:mm:ss a')+" updated account + password"+JSON.stringify(newData)
accounts.save o, { safe: true}, (err) ->
if err
callback err
else
callback null, o
event.emit 'updateAccount', o
return
return
return
return
exports.updateApiKey = (user, newApiKey, callback) ->
accounts.findOne { user: user }, (e, o) ->
if e
callback e, null
else
o.apikey = newApiKey
console.dir o
o.log.push moment().format('MMMM Do YYYY, h:mm:ss a')+" apikey updated to "+o.apikey
accounts.save o, { safe: true }, callback
event.emit 'updateApikey', o
callback e, o
return
return
exports.updatePassword = (email, newPass, callback) ->
accounts.findOne { email: email }, (e, o) ->
if e
callback e, null
else
saltAndHash newPass, (hash) ->
o.pass = hash
accounts.save o, { safe: true }, callback
event.emit 'updatePassword', o
return
return
return
### account lookup methods ###
# don't delete because of 'oh I accidentally deleted our account'-requests
exports.deleteAccount = (id, callback) ->
accounts.save { _id: getObjectId(id), inactive:true }, callback
return
exports.purgeAccount = (id, callback) ->
accounts.remove { _id: getObjectId(id) }, callback
return
exports.getAccountByEmail = (email, callback) ->
accounts.findOne { email: email }, (e, o) ->
callback o
return
return
exports.validateResetLink = (email, passHash, callback) ->
accounts.find { $and: [ {
email: email
pass: <PASSWORD>
} ] }, (e, o) ->
callback if o then 'ok' else null
return
return
exports.getAllRecords = (callback) ->
accounts.find().toArray (e, res) ->
if e
callback e
else
callback null, res
return
return
exports.delAllRecords = (callback) ->
accounts.remove {}, callback
# reset accounts collection for testing //
return
### private encryption & validation methods ###
generateSalt = ->
set = '0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ'
salt = ''
i = 0
while i < 10
p = Math.floor(Math.random() * set.length)
salt += set[p]
i++
salt
md5 = (str) ->
crypto.createHash('md5').update(str).digest 'hex'
saltAndHash = (pass, callback) ->
salt = generateSalt()
callback salt + md5(pass + salt)
return
validatePassword = (plainPass, hashedPass, callback) ->
salt = String(hashedPass).substr(0, 10)
validHash = salt + md5(plainPass + salt)
callback null, hashedPass == validHash
return
### auxiliary methods ###
getObjectId = (id) ->
accounts.db.bson_serializer.ObjectID.createFromHexString id
findById = (id, callback) ->
accounts.findOne { _id: getObjectId(id) }, (e, res) ->
if e
callback e
else
callback null, res
return
return
findByMultipleFields = (a, callback) ->
# this takes an array of name/val pairs to search against {fieldName : 'value'} //
accounts.find($or: a).toArray (e, results) ->
if e
callback e
else
callback null, results
return
return
generateApiKey = exports.generateApiKey = (hash,cb) ->
saltAndHash hash, (apikey) ->
cb( apikey.substr(0,24) )
# ---
# generated by js2coffee 2.0.3
| true | crypto = require('crypto')
mongo = require('mongodb')
MongoClient = mongo.MongoClient
moment = require('moment')
EventEmitter = require('events').EventEmitter
event = exports.event = new EventEmitter
### establish the database connection ###
db = {}
accounts = {}
exports.init = (cfg) ->
dbPort = (cfg.port || 27017)
dbHost = (cfg.host || 'localhost')
dbName = (cfg.name || 'express-api-user-management-signup' )
url = "mongodb://";
url += cfg.username+":"+cfg.password+"@" if cfg.username && cfg.password
url += dbHost+":"+dbPort+"/"+dbName
MongoClient.connect url, (err,dbhandle) ->
db = dbhandle
status = 'connected to database'
if !err
accounts = db.collection('accounts')
else
status = "not "+status+" "+url+" :("
console.log status
### login validation methods ###
exports.autoLogin = (user, pass, callback) ->
accounts.findOne { user: user }, (e, o) ->
if o
if o.pass == PI:PASSWORD:<PASSWORD>END_PI then callback(o) else callback(null)
else
callback null
event.emit 'login',
pass: PI:PASSWORD:<PASSWORD>END_PI
user: user
return
return
exports.manualLogin = (user, pass, callback) ->
accounts.findOne { user: user }, (e, o) ->
console.dir o
if o == null
callback 'user-not-found'
event.emit 'login',
reason: "user not found"
succes: false
pass: PI:PASSWORD:<PASSWORD>END_PI
user: user
else
validatePassword pass, o.pass, (err, res) ->
if res
callback null, o
event.emit 'login',
reason: ""
succes: true
pass: pass
user: user
else
callback 'invalid-password'
event.emit 'login',
reason: "invalid password entered"
succes: false
pass: PI:PASSWORD:<PASSWORD>END_PI
user: user
return
return
return
### record insertion, update & deletion methods ###
exports.addNewAccount = (newData, callback) ->
accounts.findOne { user: newData.user }, (e, o) ->
if o
callback 'username-taken'
else
accounts.findOne { email: newData.email }, (e, o) ->
if o
callback 'email-taken'
else
saltAndHash newData.pass, (hash) ->
newData.pass = hash
generateApiKey hash, (apikey) ->
newData.apikey = apikey
# append date stamp when record was created //
newData.date = moment().format('MMMM Do YYYY, h:mm:ss a')
newData.inactive = false
newData.log = [ newData.date+" added account: "+JSON.stringify(newData) ]
accounts.insert newData, { safe: true }, callback
event.emit 'addNewAccount', newData
return
return
return
return
exports.updateAccount = (newData, callback) ->
accounts.findOne { user: newData.user }, (e, o) ->
o.name = newData.name
o.email = newData.email
o.country = newData.country
o.meta = newData.meta if newData.meta
o.log = [] if o.log is undefined # backwards compatible with older versions
if newData.pass == ''
o.log.push moment().format('MMMM Do YYYY, h:mm:ss a')+" updated account with: "+JSON.stringify(newData)
accounts.save o, { safe: true }, (err) ->
if err
callback err
else
callback null, o
return
else
saltAndHash newData.pass, (hash) ->
o.pass = hash
o.log.push moment().format('MMMM Do YYYY, h:mm:ss a')+" updated account + password"+JSON.stringify(newData)
accounts.save o, { safe: true}, (err) ->
if err
callback err
else
callback null, o
event.emit 'updateAccount', o
return
return
return
return
exports.updateApiKey = (user, newApiKey, callback) ->
accounts.findOne { user: user }, (e, o) ->
if e
callback e, null
else
o.apikey = newApiKey
console.dir o
o.log.push moment().format('MMMM Do YYYY, h:mm:ss a')+" apikey updated to "+o.apikey
accounts.save o, { safe: true }, callback
event.emit 'updateApikey', o
callback e, o
return
return
exports.updatePassword = (email, newPass, callback) ->
accounts.findOne { email: email }, (e, o) ->
if e
callback e, null
else
saltAndHash newPass, (hash) ->
o.pass = hash
accounts.save o, { safe: true }, callback
event.emit 'updatePassword', o
return
return
return
### account lookup methods ###
# don't delete because of 'oh I accidentally deleted our account'-requests
exports.deleteAccount = (id, callback) ->
accounts.save { _id: getObjectId(id), inactive:true }, callback
return
exports.purgeAccount = (id, callback) ->
accounts.remove { _id: getObjectId(id) }, callback
return
exports.getAccountByEmail = (email, callback) ->
accounts.findOne { email: email }, (e, o) ->
callback o
return
return
exports.validateResetLink = (email, passHash, callback) ->
accounts.find { $and: [ {
email: email
pass: PI:PASSWORD:<PASSWORD>END_PI
} ] }, (e, o) ->
callback if o then 'ok' else null
return
return
exports.getAllRecords = (callback) ->
accounts.find().toArray (e, res) ->
if e
callback e
else
callback null, res
return
return
exports.delAllRecords = (callback) ->
accounts.remove {}, callback
# reset accounts collection for testing //
return
### private encryption & validation methods ###
generateSalt = ->
set = '0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ'
salt = ''
i = 0
while i < 10
p = Math.floor(Math.random() * set.length)
salt += set[p]
i++
salt
md5 = (str) ->
crypto.createHash('md5').update(str).digest 'hex'
saltAndHash = (pass, callback) ->
salt = generateSalt()
callback salt + md5(pass + salt)
return
validatePassword = (plainPass, hashedPass, callback) ->
salt = String(hashedPass).substr(0, 10)
validHash = salt + md5(plainPass + salt)
callback null, hashedPass == validHash
return
### auxiliary methods ###
getObjectId = (id) ->
accounts.db.bson_serializer.ObjectID.createFromHexString id
findById = (id, callback) ->
accounts.findOne { _id: getObjectId(id) }, (e, res) ->
if e
callback e
else
callback null, res
return
return
findByMultipleFields = (a, callback) ->
# this takes an array of name/val pairs to search against {fieldName : 'value'} //
accounts.find($or: a).toArray (e, results) ->
if e
callback e
else
callback null, results
return
return
generateApiKey = exports.generateApiKey = (hash,cb) ->
saltAndHash hash, (apikey) ->
cb( apikey.substr(0,24) )
# ---
# generated by js2coffee 2.0.3
|
[
{
"context": "e: \"\"\n }\n ]\n\n Stations.insert\n name: \"Trevithick Dock\"\n system: \"LHS 3447\"\n type: \"outpost\"\n h",
"end": 672,
"score": 0.9988344311714172,
"start": 657,
"tag": "NAME",
"value": "Trevithick Dock"
},
{
"context": " bannedItems: []\n\n Stations.insert\n name: \"Dalton Gateway\"\n system: \"LHS 3447\"\n type: \"station\"\n h",
"end": 806,
"score": 0.98456209897995,
"start": 792,
"tag": "NAME",
"value": "Dalton Gateway"
},
{
"context": " bannedItems: []\n\n Stations.insert\n name: \"Oleskiw Station\"\n system: \"LHS 3447\"\n type: \"out",
"end": 930,
"score": 0.6841285228729248,
"start": 926,
"tag": "NAME",
"value": "Oles"
},
{
"context": " bannedItems: []\n\n Stations.insert\n name: \"Lawson Orbital\"\n system: \"LHS 3447\"\n type: \"outpost\"\n h",
"end": 1076,
"score": 0.9989107251167297,
"start": 1062,
"tag": "NAME",
"value": "Lawson Orbital"
}
] | server/fixtures.coffee | sean-clayton/elite-dangerous-market-tracker | 0 | console.log "Stations count: #{Stations.find().count()}"
if Stations.find().count() is 0
console.log "Creating stations"
# Creating initial stations
Stations.insert
name: "Fairbairn Station"
system: "LHS 3447"
type: "outpost"
hasBlackmarket: false
bannedItems: []
Stations.insert
name: "Worlidge Terminal"
system: "LHS 3447"
type: "station"
hasBlackmarket: true
bannedItems: []
Stations.insert
name: "Yaping Enterprise"
system: "LHS 3447"
type: "outpost"
hasBlackmarket: false
bannedItems: []
commodities: [
{
name: ""
}
]
Stations.insert
name: "Trevithick Dock"
system: "LHS 3447"
type: "outpost"
hasBlackmarket: true
bannedItems: []
Stations.insert
name: "Dalton Gateway"
system: "LHS 3447"
type: "station"
hasBlackmarket: true
bannedItems: []
Stations.insert
name: "Oleskiw Station"
system: "LHS 3447"
type: "outpost"
hasBlackmarket: false
bannedItems: []
Stations.insert
name: "Lawson Orbital"
system: "LHS 3447"
type: "outpost"
hasBlackmarket: true
bannedItems: []
console.log "Created #{Stations.find().count()} station(s)." | 170719 | console.log "Stations count: #{Stations.find().count()}"
if Stations.find().count() is 0
console.log "Creating stations"
# Creating initial stations
Stations.insert
name: "Fairbairn Station"
system: "LHS 3447"
type: "outpost"
hasBlackmarket: false
bannedItems: []
Stations.insert
name: "Worlidge Terminal"
system: "LHS 3447"
type: "station"
hasBlackmarket: true
bannedItems: []
Stations.insert
name: "Yaping Enterprise"
system: "LHS 3447"
type: "outpost"
hasBlackmarket: false
bannedItems: []
commodities: [
{
name: ""
}
]
Stations.insert
name: "<NAME>"
system: "LHS 3447"
type: "outpost"
hasBlackmarket: true
bannedItems: []
Stations.insert
name: "<NAME>"
system: "LHS 3447"
type: "station"
hasBlackmarket: true
bannedItems: []
Stations.insert
name: "<NAME>kiw Station"
system: "LHS 3447"
type: "outpost"
hasBlackmarket: false
bannedItems: []
Stations.insert
name: "<NAME>"
system: "LHS 3447"
type: "outpost"
hasBlackmarket: true
bannedItems: []
console.log "Created #{Stations.find().count()} station(s)." | true | console.log "Stations count: #{Stations.find().count()}"
if Stations.find().count() is 0
console.log "Creating stations"
# Creating initial stations
Stations.insert
name: "Fairbairn Station"
system: "LHS 3447"
type: "outpost"
hasBlackmarket: false
bannedItems: []
Stations.insert
name: "Worlidge Terminal"
system: "LHS 3447"
type: "station"
hasBlackmarket: true
bannedItems: []
Stations.insert
name: "Yaping Enterprise"
system: "LHS 3447"
type: "outpost"
hasBlackmarket: false
bannedItems: []
commodities: [
{
name: ""
}
]
Stations.insert
name: "PI:NAME:<NAME>END_PI"
system: "LHS 3447"
type: "outpost"
hasBlackmarket: true
bannedItems: []
Stations.insert
name: "PI:NAME:<NAME>END_PI"
system: "LHS 3447"
type: "station"
hasBlackmarket: true
bannedItems: []
Stations.insert
name: "PI:NAME:<NAME>END_PIkiw Station"
system: "LHS 3447"
type: "outpost"
hasBlackmarket: false
bannedItems: []
Stations.insert
name: "PI:NAME:<NAME>END_PI"
system: "LHS 3447"
type: "outpost"
hasBlackmarket: true
bannedItems: []
console.log "Created #{Stations.find().count()} station(s)." |
[
{
"context": "me,password} = request.query\n\n if username == 'meshblu' && password == @password\n return @client.se",
"end": 245,
"score": 0.9996412396430969,
"start": 238,
"tag": "USERNAME",
"value": "meshblu"
},
{
"context": " @meshbluConfig,\n uuid: username\n token: password\n\n meshblu = new MeshbluHttp options\n meshbl",
"end": 624,
"score": 0.7162489295005798,
"start": 616,
"tag": "PASSWORD",
"value": "password"
}
] | src/controllers/auth-controller.coffee | octoblu/meshblu-rabbitmq-auth-service | 0 | _ = require 'lodash'
MeshbluHttp = require 'meshblu-http'
class AuthController
constructor: ({@client,@meshbluConfig,@password}) ->
user: (request, response) =>
{username,password} = request.query
if username == 'meshblu' && password == @password
return @client.setex username, 30, new Date(), =>
return response.send('allow')
if username? && !password?
return @client.exists username, (error, exists) =>
return response.send('allow') if exists == 1
response.send('deny')
options = _.extend {}, @meshbluConfig,
uuid: username
token: password
meshblu = new MeshbluHttp options
meshblu.whoami (error) =>
return response.send('deny') if error?
@client.setex username, 30, new Date(), =>
response.send('allow')
vhost: (request, response) =>
response.send('allow')
resource: (request, response) =>
{username, resource, name, permission} = request.query
allow = false
if /^(amq\.gen-.*|amq.default)/.test(name) && permission = 'write'
allow = true
if _.startsWith name, username
allow = true
return response.send('allow') if allow
response.send('deny')
module.exports = AuthController
| 196005 | _ = require 'lodash'
MeshbluHttp = require 'meshblu-http'
class AuthController
constructor: ({@client,@meshbluConfig,@password}) ->
user: (request, response) =>
{username,password} = request.query
if username == 'meshblu' && password == @password
return @client.setex username, 30, new Date(), =>
return response.send('allow')
if username? && !password?
return @client.exists username, (error, exists) =>
return response.send('allow') if exists == 1
response.send('deny')
options = _.extend {}, @meshbluConfig,
uuid: username
token: <PASSWORD>
meshblu = new MeshbluHttp options
meshblu.whoami (error) =>
return response.send('deny') if error?
@client.setex username, 30, new Date(), =>
response.send('allow')
vhost: (request, response) =>
response.send('allow')
resource: (request, response) =>
{username, resource, name, permission} = request.query
allow = false
if /^(amq\.gen-.*|amq.default)/.test(name) && permission = 'write'
allow = true
if _.startsWith name, username
allow = true
return response.send('allow') if allow
response.send('deny')
module.exports = AuthController
| true | _ = require 'lodash'
MeshbluHttp = require 'meshblu-http'
class AuthController
constructor: ({@client,@meshbluConfig,@password}) ->
user: (request, response) =>
{username,password} = request.query
if username == 'meshblu' && password == @password
return @client.setex username, 30, new Date(), =>
return response.send('allow')
if username? && !password?
return @client.exists username, (error, exists) =>
return response.send('allow') if exists == 1
response.send('deny')
options = _.extend {}, @meshbluConfig,
uuid: username
token: PI:PASSWORD:<PASSWORD>END_PI
meshblu = new MeshbluHttp options
meshblu.whoami (error) =>
return response.send('deny') if error?
@client.setex username, 30, new Date(), =>
response.send('allow')
vhost: (request, response) =>
response.send('allow')
resource: (request, response) =>
{username, resource, name, permission} = request.query
allow = false
if /^(amq\.gen-.*|amq.default)/.test(name) && permission = 'write'
allow = true
if _.startsWith name, username
allow = true
return response.send('allow') if allow
response.send('deny')
module.exports = AuthController
|
[
{
"context": "ners = @options.maintainers\n @myEstimateKey = \"estimatedEffort[#{window.user.id}]\"\n @allEstimateKeys = (\"estimatedEffort[#{maint",
"end": 340,
"score": 0.9446669220924377,
"start": 306,
"tag": "KEY",
"value": "estimatedEffort[#{window.user.id}]"
},
{
"context": "fort[#{window.user.id}]\"\n @allEstimateKeys = (\"estimatedEffort[#{maintainer.id}]\" for maintainer in @maintainers)\n\n @$el.on 'click', '[role=\"menui",
"end": 419,
"score": 0.936671257019043,
"start": 367,
"tag": "KEY",
"value": "estimatedEffort[#{maintainer.id}]\" for maintainer in"
}
] | app/assets/javascripts/houston/scheduler/views/planning_poker.coffee | houston/houston-scheduler | 0 | class Scheduler.PlanningPoker extends Backbone.View
className: 'planning-poker'
initialize: (options)->
@options = options
@template = HandlebarsTemplates['houston/scheduler/tickets/planning_poker']
@tickets = @options.tickets
@maintainers = @options.maintainers
@myEstimateKey = "estimatedEffort[#{window.user.id}]"
@allEstimateKeys = ("estimatedEffort[#{maintainer.id}]" for maintainer in @maintainers)
@$el.on 'click', '[role="menuitem"]', _.bind(@setEstimate, @)
render: ->
tickets = @tickets.map (ticket)=>
ticket = ticket.toJSON()
ticket.myEstimate = ticket[@myEstimateKey]
ticket.estimates = for key in @allEstimateKeys when ticket[key]
estimate = ticket[key]
estimate = '—' if estimate is 'Pass'
estimate = 'Ø' if estimate is 'Unestimatable Ticket'
estimate
ticket.complete = @isComplete(ticket)
ticket.unanimous = @isUnanimous(ticket)
ticket
@$el.html @template
tickets: tickets
maintainers: @maintainers
$('.table-sortable').tablesorter
headers:
1: {sorter: 'sequence'}
@
isComplete: (ticket)->
_.intersection(_.keys(ticket), @allEstimateKeys).length == @allEstimateKeys.length
estimates: (ticket)->
_.map(@allEstimateKeys, (key)-> ticket[key])
isUnanimous: (ticket)->
_.uniq(@estimates(ticket)).length is 1
setEstimate: (e)->
e.preventDefault()
$a = $(e.target)
ticketId = $a.closest('.ticket').data('ticket-id')
estimate = $a.html()
if estimate is 'No Estimate'
estimate = ''
$a.closest('.dropdown').find('.estimate').addClass('no-estimate').html(estimate)
else
$a.closest('.dropdown').find('.estimate').removeClass('no-estimate').html(estimate)
ticket = @tickets.get(ticketId)
attributes = {}
attributes[@myEstimateKey] = estimate
allAttributes = ticket.toJSON()
allAttributes[@myEstimateKey] = estimate
if @isUnanimous(allAttributes)
switch estimate
when 'Unestimatable Ticket'
attributes['estimatedEffort'] = ''
attributes['unableToSetEstimatedEffort'] = true
when 'Pass'
# do nothing
else
attributes['estimatedEffort'] = estimate
attributes['unableToSetEstimatedEffort'] = false
else
attributes['estimatedEffort'] = ''
ticket.save attributes, patch: true
@render() # <-- maybe render just the ticket in the future
| 213490 | class Scheduler.PlanningPoker extends Backbone.View
className: 'planning-poker'
initialize: (options)->
@options = options
@template = HandlebarsTemplates['houston/scheduler/tickets/planning_poker']
@tickets = @options.tickets
@maintainers = @options.maintainers
@myEstimateKey = "<KEY>"
@allEstimateKeys = ("<KEY> @maintainers)
@$el.on 'click', '[role="menuitem"]', _.bind(@setEstimate, @)
render: ->
tickets = @tickets.map (ticket)=>
ticket = ticket.toJSON()
ticket.myEstimate = ticket[@myEstimateKey]
ticket.estimates = for key in @allEstimateKeys when ticket[key]
estimate = ticket[key]
estimate = '—' if estimate is 'Pass'
estimate = 'Ø' if estimate is 'Unestimatable Ticket'
estimate
ticket.complete = @isComplete(ticket)
ticket.unanimous = @isUnanimous(ticket)
ticket
@$el.html @template
tickets: tickets
maintainers: @maintainers
$('.table-sortable').tablesorter
headers:
1: {sorter: 'sequence'}
@
isComplete: (ticket)->
_.intersection(_.keys(ticket), @allEstimateKeys).length == @allEstimateKeys.length
estimates: (ticket)->
_.map(@allEstimateKeys, (key)-> ticket[key])
isUnanimous: (ticket)->
_.uniq(@estimates(ticket)).length is 1
setEstimate: (e)->
e.preventDefault()
$a = $(e.target)
ticketId = $a.closest('.ticket').data('ticket-id')
estimate = $a.html()
if estimate is 'No Estimate'
estimate = ''
$a.closest('.dropdown').find('.estimate').addClass('no-estimate').html(estimate)
else
$a.closest('.dropdown').find('.estimate').removeClass('no-estimate').html(estimate)
ticket = @tickets.get(ticketId)
attributes = {}
attributes[@myEstimateKey] = estimate
allAttributes = ticket.toJSON()
allAttributes[@myEstimateKey] = estimate
if @isUnanimous(allAttributes)
switch estimate
when 'Unestimatable Ticket'
attributes['estimatedEffort'] = ''
attributes['unableToSetEstimatedEffort'] = true
when 'Pass'
# do nothing
else
attributes['estimatedEffort'] = estimate
attributes['unableToSetEstimatedEffort'] = false
else
attributes['estimatedEffort'] = ''
ticket.save attributes, patch: true
@render() # <-- maybe render just the ticket in the future
| true | class Scheduler.PlanningPoker extends Backbone.View
className: 'planning-poker'
initialize: (options)->
@options = options
@template = HandlebarsTemplates['houston/scheduler/tickets/planning_poker']
@tickets = @options.tickets
@maintainers = @options.maintainers
@myEstimateKey = "PI:KEY:<KEY>END_PI"
@allEstimateKeys = ("PI:KEY:<KEY>END_PI @maintainers)
@$el.on 'click', '[role="menuitem"]', _.bind(@setEstimate, @)
render: ->
tickets = @tickets.map (ticket)=>
ticket = ticket.toJSON()
ticket.myEstimate = ticket[@myEstimateKey]
ticket.estimates = for key in @allEstimateKeys when ticket[key]
estimate = ticket[key]
estimate = '—' if estimate is 'Pass'
estimate = 'Ø' if estimate is 'Unestimatable Ticket'
estimate
ticket.complete = @isComplete(ticket)
ticket.unanimous = @isUnanimous(ticket)
ticket
@$el.html @template
tickets: tickets
maintainers: @maintainers
$('.table-sortable').tablesorter
headers:
1: {sorter: 'sequence'}
@
isComplete: (ticket)->
_.intersection(_.keys(ticket), @allEstimateKeys).length == @allEstimateKeys.length
estimates: (ticket)->
_.map(@allEstimateKeys, (key)-> ticket[key])
isUnanimous: (ticket)->
_.uniq(@estimates(ticket)).length is 1
setEstimate: (e)->
e.preventDefault()
$a = $(e.target)
ticketId = $a.closest('.ticket').data('ticket-id')
estimate = $a.html()
if estimate is 'No Estimate'
estimate = ''
$a.closest('.dropdown').find('.estimate').addClass('no-estimate').html(estimate)
else
$a.closest('.dropdown').find('.estimate').removeClass('no-estimate').html(estimate)
ticket = @tickets.get(ticketId)
attributes = {}
attributes[@myEstimateKey] = estimate
allAttributes = ticket.toJSON()
allAttributes[@myEstimateKey] = estimate
if @isUnanimous(allAttributes)
switch estimate
when 'Unestimatable Ticket'
attributes['estimatedEffort'] = ''
attributes['unableToSetEstimatedEffort'] = true
when 'Pass'
# do nothing
else
attributes['estimatedEffort'] = estimate
attributes['unableToSetEstimatedEffort'] = false
else
attributes['estimatedEffort'] = ''
ticket.save attributes, patch: true
@render() # <-- maybe render just the ticket in the future
|
[
{
"context": "3 Flarebyte.com Ltd. All rights reserved.\nCreator: Olivier Huin\nContributors:\n###\n\n'use strict'\n\n###\nModule depen",
"end": 151,
"score": 0.9998701214790344,
"start": 139,
"tag": "NAME",
"value": "Olivier Huin"
}
] | nodejs/flarebyte.net/0.8/node/flaming/live.coffee | flarebyte/wonderful-bazar | 0 | ###
GENERATED - DO NOT EDIT - Tue Jan 14 2014 22:25:31 GMT+0000 (GMT)
Copyright (c) 2013 Flarebyte.com Ltd. All rights reserved.
Creator: Olivier Huin
Contributors:
###
'use strict'
###
Module dependencies.
###
express = require("express")
init = require("fb-custom-init")
nconf = require("nconf")
winston = require("winston")
routes = require("./routes")
api = require("./routes/api")
http = require("http")
path = require("path")
_ = require("lodash")
app = express()
# all environments
app.set "port", 17017
app.set "views", __dirname + "/views"
app.set "view engine", "jade"
app.use express.favicon()
app.use express.logger("dev")
app.use express.bodyParser()
app.use express.methodOverride()
app.use express.cookieParser("hGu$!jSlbjD7GwMjF3?hyQU)%1(JSO")
app.use express.session(secret: "mozillapersona")
app.use app.router
app.use require("stylus").middleware(__dirname + "/public")
app.use express.static(path.join(__dirname, "public"))
# development only
app.use express.errorHandler() if "development" is app.get("env")
app.get '/', routes.index
app.get '/partials/:name', routes.partials
# Boolean value - true/false
RE_BOOLEAN_VALUE= /[TF]/
# Routing
app.get '/api/profile', (req, res)->
# List all profiles for the current user
if _.isEmpty req.query
api.doListAllProfile(req, res)
return
res.send(404)
app.get '/api/login', (req, res)->
# List all login options for the current user
if _.isEmpty req.query
api.doListAllLoginOptions(req, res)
return
res.send(404)
app.get '/api/compose', (req, res)->
# List all compose templates for the current user
if _.isEmpty req.query
api.doListAllComposeTemplates(req, res)
return
res.send(404)
app.get '/api/to-read', (req, res)->
# List all messages to read for the current user
if _.isEmpty req.query
api.doListAllMessagesToRead(req, res)
return
res.send(404)
app.get '/api/to-do', (req, res)->
# List all tasks to do for the current user
if _.isEmpty req.query
api.doListAllTasksToDo(req, res)
return
res.send(404)
app.get '/api/important', (req, res)->
# List all important messages for the current user
if _.isEmpty req.query
api.doListAllImportantMessages(req, res)
return
res.send(404)
app.get '/api/recent', (req, res)->
# List all recent messages for the current user
if _.isEmpty req.query
api.doListAllRecentMessages(req, res)
return
res.send(404)
app.get '/api/shared', (req, res)->
# List all shared messages for the current user
if _.isEmpty req.query
api.doListAllSharedMessages(req, res)
return
res.send(404)
app.get '/api/all', (req, res)->
# List all messages for the current user
if _.isEmpty req.query
api.doListAllMessages(req, res)
return
res.send(404)
app.get '/api/news', (req, res)->
# List all news for the current user
if _.isEmpty req.query
api.doListAllNews(req, res)
return
res.send(404)
app.get '/api/trash', (req, res)->
# List all trash for the current user
if _.isEmpty req.query
api.doListAllTrash(req, res)
return
res.send(404)
app.get '/api/dashboard', (req, res)->
# List all dashboards of the current user
if _.isEmpty req.query
api.doListAllDashboards(req, res)
return
res.send(404)
app.get '/api/contacts', (req, res)->
isImportant= RE_BOOLEAN_VALUE.test(req.query.important)
isSpam= RE_BOOLEAN_VALUE.test(req.query.spam)
isAccepted= RE_BOOLEAN_VALUE.test(req.query.accepted)
# List a selection of contacts of the current user
if isImportant and isSpam and isAccepted
api.doListASelectionOfContacts(req, res)
return
# List all contacts of the current user
if _.isEmpty req.query
api.doListAllContacts(req, res)
return
res.send(404)
app.get '/api/settings', (req, res)->
# List all settings of the current user
if _.isEmpty req.query
api.doListAllSettings(req, res)
return
res.send(404)
app.get '/api/help', (req, res)->
# List all help items of the current user
if _.isEmpty req.query
api.doListAllHelpItems(req, res)
return
res.send(404)
app.get '/api/faq', (req, res)->
# List all faq items of the current user
if _.isEmpty req.query
api.doListAllFaqItems(req, res)
return
res.send(404)
app.get '/api/privacy', (req, res)->
# List all privacy items of the current user
if _.isEmpty req.query
api.doListAllPrivacyItems(req, res)
return
res.send(404)
app.get '/api/terms', (req, res)->
# List all terms for the current user
if _.isEmpty req.query
api.doListAllTerms(req, res)
return
res.send(404)
http.createServer(app).listen app.get("port"), ->
console.log "Express server listening on port " + app.get("port")
| 191071 | ###
GENERATED - DO NOT EDIT - Tue Jan 14 2014 22:25:31 GMT+0000 (GMT)
Copyright (c) 2013 Flarebyte.com Ltd. All rights reserved.
Creator: <NAME>
Contributors:
###
'use strict'
###
Module dependencies.
###
express = require("express")
init = require("fb-custom-init")
nconf = require("nconf")
winston = require("winston")
routes = require("./routes")
api = require("./routes/api")
http = require("http")
path = require("path")
_ = require("lodash")
app = express()
# all environments
app.set "port", 17017
app.set "views", __dirname + "/views"
app.set "view engine", "jade"
app.use express.favicon()
app.use express.logger("dev")
app.use express.bodyParser()
app.use express.methodOverride()
app.use express.cookieParser("hGu$!jSlbjD7GwMjF3?hyQU)%1(JSO")
app.use express.session(secret: "mozillapersona")
app.use app.router
app.use require("stylus").middleware(__dirname + "/public")
app.use express.static(path.join(__dirname, "public"))
# development only
app.use express.errorHandler() if "development" is app.get("env")
app.get '/', routes.index
app.get '/partials/:name', routes.partials
# Boolean value - true/false
RE_BOOLEAN_VALUE= /[TF]/
# Routing
app.get '/api/profile', (req, res)->
# List all profiles for the current user
if _.isEmpty req.query
api.doListAllProfile(req, res)
return
res.send(404)
app.get '/api/login', (req, res)->
# List all login options for the current user
if _.isEmpty req.query
api.doListAllLoginOptions(req, res)
return
res.send(404)
app.get '/api/compose', (req, res)->
# List all compose templates for the current user
if _.isEmpty req.query
api.doListAllComposeTemplates(req, res)
return
res.send(404)
app.get '/api/to-read', (req, res)->
# List all messages to read for the current user
if _.isEmpty req.query
api.doListAllMessagesToRead(req, res)
return
res.send(404)
app.get '/api/to-do', (req, res)->
# List all tasks to do for the current user
if _.isEmpty req.query
api.doListAllTasksToDo(req, res)
return
res.send(404)
app.get '/api/important', (req, res)->
# List all important messages for the current user
if _.isEmpty req.query
api.doListAllImportantMessages(req, res)
return
res.send(404)
app.get '/api/recent', (req, res)->
# List all recent messages for the current user
if _.isEmpty req.query
api.doListAllRecentMessages(req, res)
return
res.send(404)
app.get '/api/shared', (req, res)->
# List all shared messages for the current user
if _.isEmpty req.query
api.doListAllSharedMessages(req, res)
return
res.send(404)
app.get '/api/all', (req, res)->
# List all messages for the current user
if _.isEmpty req.query
api.doListAllMessages(req, res)
return
res.send(404)
app.get '/api/news', (req, res)->
# List all news for the current user
if _.isEmpty req.query
api.doListAllNews(req, res)
return
res.send(404)
app.get '/api/trash', (req, res)->
# List all trash for the current user
if _.isEmpty req.query
api.doListAllTrash(req, res)
return
res.send(404)
app.get '/api/dashboard', (req, res)->
# List all dashboards of the current user
if _.isEmpty req.query
api.doListAllDashboards(req, res)
return
res.send(404)
app.get '/api/contacts', (req, res)->
isImportant= RE_BOOLEAN_VALUE.test(req.query.important)
isSpam= RE_BOOLEAN_VALUE.test(req.query.spam)
isAccepted= RE_BOOLEAN_VALUE.test(req.query.accepted)
# List a selection of contacts of the current user
if isImportant and isSpam and isAccepted
api.doListASelectionOfContacts(req, res)
return
# List all contacts of the current user
if _.isEmpty req.query
api.doListAllContacts(req, res)
return
res.send(404)
app.get '/api/settings', (req, res)->
# List all settings of the current user
if _.isEmpty req.query
api.doListAllSettings(req, res)
return
res.send(404)
app.get '/api/help', (req, res)->
# List all help items of the current user
if _.isEmpty req.query
api.doListAllHelpItems(req, res)
return
res.send(404)
app.get '/api/faq', (req, res)->
# List all faq items of the current user
if _.isEmpty req.query
api.doListAllFaqItems(req, res)
return
res.send(404)
app.get '/api/privacy', (req, res)->
# List all privacy items of the current user
if _.isEmpty req.query
api.doListAllPrivacyItems(req, res)
return
res.send(404)
app.get '/api/terms', (req, res)->
# List all terms for the current user
if _.isEmpty req.query
api.doListAllTerms(req, res)
return
res.send(404)
http.createServer(app).listen app.get("port"), ->
console.log "Express server listening on port " + app.get("port")
| true | ###
GENERATED - DO NOT EDIT - Tue Jan 14 2014 22:25:31 GMT+0000 (GMT)
Copyright (c) 2013 Flarebyte.com Ltd. All rights reserved.
Creator: PI:NAME:<NAME>END_PI
Contributors:
###
'use strict'
###
Module dependencies.
###
express = require("express")
init = require("fb-custom-init")
nconf = require("nconf")
winston = require("winston")
routes = require("./routes")
api = require("./routes/api")
http = require("http")
path = require("path")
_ = require("lodash")
app = express()
# all environments
app.set "port", 17017
app.set "views", __dirname + "/views"
app.set "view engine", "jade"
app.use express.favicon()
app.use express.logger("dev")
app.use express.bodyParser()
app.use express.methodOverride()
app.use express.cookieParser("hGu$!jSlbjD7GwMjF3?hyQU)%1(JSO")
app.use express.session(secret: "mozillapersona")
app.use app.router
app.use require("stylus").middleware(__dirname + "/public")
app.use express.static(path.join(__dirname, "public"))
# development only
app.use express.errorHandler() if "development" is app.get("env")
app.get '/', routes.index
app.get '/partials/:name', routes.partials
# Boolean value - true/false
RE_BOOLEAN_VALUE= /[TF]/
# Routing
app.get '/api/profile', (req, res)->
# List all profiles for the current user
if _.isEmpty req.query
api.doListAllProfile(req, res)
return
res.send(404)
app.get '/api/login', (req, res)->
# List all login options for the current user
if _.isEmpty req.query
api.doListAllLoginOptions(req, res)
return
res.send(404)
app.get '/api/compose', (req, res)->
# List all compose templates for the current user
if _.isEmpty req.query
api.doListAllComposeTemplates(req, res)
return
res.send(404)
app.get '/api/to-read', (req, res)->
# List all messages to read for the current user
if _.isEmpty req.query
api.doListAllMessagesToRead(req, res)
return
res.send(404)
app.get '/api/to-do', (req, res)->
# List all tasks to do for the current user
if _.isEmpty req.query
api.doListAllTasksToDo(req, res)
return
res.send(404)
app.get '/api/important', (req, res)->
# List all important messages for the current user
if _.isEmpty req.query
api.doListAllImportantMessages(req, res)
return
res.send(404)
app.get '/api/recent', (req, res)->
# List all recent messages for the current user
if _.isEmpty req.query
api.doListAllRecentMessages(req, res)
return
res.send(404)
app.get '/api/shared', (req, res)->
# List all shared messages for the current user
if _.isEmpty req.query
api.doListAllSharedMessages(req, res)
return
res.send(404)
app.get '/api/all', (req, res)->
# List all messages for the current user
if _.isEmpty req.query
api.doListAllMessages(req, res)
return
res.send(404)
app.get '/api/news', (req, res)->
# List all news for the current user
if _.isEmpty req.query
api.doListAllNews(req, res)
return
res.send(404)
app.get '/api/trash', (req, res)->
# List all trash for the current user
if _.isEmpty req.query
api.doListAllTrash(req, res)
return
res.send(404)
app.get '/api/dashboard', (req, res)->
# List all dashboards of the current user
if _.isEmpty req.query
api.doListAllDashboards(req, res)
return
res.send(404)
app.get '/api/contacts', (req, res)->
isImportant= RE_BOOLEAN_VALUE.test(req.query.important)
isSpam= RE_BOOLEAN_VALUE.test(req.query.spam)
isAccepted= RE_BOOLEAN_VALUE.test(req.query.accepted)
# List a selection of contacts of the current user
if isImportant and isSpam and isAccepted
api.doListASelectionOfContacts(req, res)
return
# List all contacts of the current user
if _.isEmpty req.query
api.doListAllContacts(req, res)
return
res.send(404)
app.get '/api/settings', (req, res)->
# List all settings of the current user
if _.isEmpty req.query
api.doListAllSettings(req, res)
return
res.send(404)
app.get '/api/help', (req, res)->
# List all help items of the current user
if _.isEmpty req.query
api.doListAllHelpItems(req, res)
return
res.send(404)
app.get '/api/faq', (req, res)->
# List all faq items of the current user
if _.isEmpty req.query
api.doListAllFaqItems(req, res)
return
res.send(404)
app.get '/api/privacy', (req, res)->
# List all privacy items of the current user
if _.isEmpty req.query
api.doListAllPrivacyItems(req, res)
return
res.send(404)
app.get '/api/terms', (req, res)->
# List all terms for the current user
if _.isEmpty req.query
api.doListAllTerms(req, res)
return
res.send(404)
http.createServer(app).listen app.get("port"), ->
console.log "Express server listening on port " + app.get("port")
|
[
{
"context": "\n label: \"DoveCot\"\n login: \"testuser\"\n password: \"applesauce\"\n s",
"end": 1776,
"score": 0.9996525049209595,
"start": 1768,
"tag": "USERNAME",
"value": "testuser"
},
{
"context": " login: \"testuser\"\n password: \"applesauce\"\n smtpMethod: \"NONE\"\n smtpS",
"end": 1811,
"score": 0.9987332820892334,
"start": 1801,
"tag": "PASSWORD",
"value": "applesauce"
},
{
"context": " smtpMethod: \"NONE\"\n smtpServer: \"127.0.0.1\"\n smtpPort: SMTP_PORT\n smtp",
"end": 1878,
"score": 0.9997491836547852,
"start": 1869,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | tests/index.coffee | gelnior/cozy-emails | 0 | global.appPath = if process.env.USEJS then '../build/' else '../'
should = require('should')
helpers = require './helpers'
fixtures = require 'cozy-fixtures'
DovecotTesting = require 'dovecot-testing'
SMTPTesting = require './smtp-testing/index'
Client = require('request-json').JsonClient
# CONSTANTS
SMTP_PORT = 8889
APP_PORT = '8888'
APP_HOST = 'localhost'
# UNIT TESTS
require './units/mailbox_flattening'
describe "Server tests", ->
# load the fixtures
unless process.env.SKIP_FIXTURES
before (done) ->
@timeout 120000
fixtures.removeDocumentsOf 'account', done
before (done) ->
@timeout 120000
fixtures.removeDocumentsOf 'message', done
before (done) ->
@timeout 120000
fixtures.removeDocumentsOf 'mailbox', done
before (done) ->
@timeout 120000
fixtures.removeDocumentsOf 'mailssettings', done
before (done) ->
@timeout 120000
fixtures.removeDocumentsOf 'contact', done
# setup test IMAP server
unless process.env.SKIP_DOVECOT
before DovecotTesting.setupEnvironment
# setup test SMTP server
before (done) ->
@timeout 3000
SMTPTesting.init SMTP_PORT, done
# start the app & prepare store
before helpers.prepareForCrypto
before helpers.startApp appPath, APP_HOST, APP_PORT
before ->
global.store = {}
global.helpers = helpers
global.SMTPTesting = SMTPTesting
global.DovecotTesting = DovecotTesting
global.client = new Client "http://#{APP_HOST}:#{APP_PORT}/"
# define the test account
before ->
store.accountDefinition =
label: "DoveCot"
login: "testuser"
password: "applesauce"
smtpMethod: "NONE"
smtpServer: "127.0.0.1"
smtpPort: SMTP_PORT
smtpSSL: false
smtpTLS: true
imapServer: DovecotTesting.serverIP()
imapPort: 993
imapSSL: true
# stop the app
after helpers.stopApp
after ->
delete global.appPath
delete global.store
delete global.helpers
delete global.SMTPTesting
delete global.DovecotTesting
delete global.client
# SERVER TESTS
require './00_index'
require './01_account_creation'
require './02_account_synchro'
require './03_mailbox_operations'
require './04_message_operations'
require './05_mailbox_deletion'
require './06_settings'
require './07_activities'
| 126103 | global.appPath = if process.env.USEJS then '../build/' else '../'
should = require('should')
helpers = require './helpers'
fixtures = require 'cozy-fixtures'
DovecotTesting = require 'dovecot-testing'
SMTPTesting = require './smtp-testing/index'
Client = require('request-json').JsonClient
# CONSTANTS
SMTP_PORT = 8889
APP_PORT = '8888'
APP_HOST = 'localhost'
# UNIT TESTS
require './units/mailbox_flattening'
describe "Server tests", ->
# load the fixtures
unless process.env.SKIP_FIXTURES
before (done) ->
@timeout 120000
fixtures.removeDocumentsOf 'account', done
before (done) ->
@timeout 120000
fixtures.removeDocumentsOf 'message', done
before (done) ->
@timeout 120000
fixtures.removeDocumentsOf 'mailbox', done
before (done) ->
@timeout 120000
fixtures.removeDocumentsOf 'mailssettings', done
before (done) ->
@timeout 120000
fixtures.removeDocumentsOf 'contact', done
# setup test IMAP server
unless process.env.SKIP_DOVECOT
before DovecotTesting.setupEnvironment
# setup test SMTP server
before (done) ->
@timeout 3000
SMTPTesting.init SMTP_PORT, done
# start the app & prepare store
before helpers.prepareForCrypto
before helpers.startApp appPath, APP_HOST, APP_PORT
before ->
global.store = {}
global.helpers = helpers
global.SMTPTesting = SMTPTesting
global.DovecotTesting = DovecotTesting
global.client = new Client "http://#{APP_HOST}:#{APP_PORT}/"
# define the test account
before ->
store.accountDefinition =
label: "DoveCot"
login: "testuser"
password: "<PASSWORD>"
smtpMethod: "NONE"
smtpServer: "127.0.0.1"
smtpPort: SMTP_PORT
smtpSSL: false
smtpTLS: true
imapServer: DovecotTesting.serverIP()
imapPort: 993
imapSSL: true
# stop the app
after helpers.stopApp
after ->
delete global.appPath
delete global.store
delete global.helpers
delete global.SMTPTesting
delete global.DovecotTesting
delete global.client
# SERVER TESTS
require './00_index'
require './01_account_creation'
require './02_account_synchro'
require './03_mailbox_operations'
require './04_message_operations'
require './05_mailbox_deletion'
require './06_settings'
require './07_activities'
| true | global.appPath = if process.env.USEJS then '../build/' else '../'
should = require('should')
helpers = require './helpers'
fixtures = require 'cozy-fixtures'
DovecotTesting = require 'dovecot-testing'
SMTPTesting = require './smtp-testing/index'
Client = require('request-json').JsonClient
# CONSTANTS
SMTP_PORT = 8889
APP_PORT = '8888'
APP_HOST = 'localhost'
# UNIT TESTS
require './units/mailbox_flattening'
describe "Server tests", ->
# load the fixtures
unless process.env.SKIP_FIXTURES
before (done) ->
@timeout 120000
fixtures.removeDocumentsOf 'account', done
before (done) ->
@timeout 120000
fixtures.removeDocumentsOf 'message', done
before (done) ->
@timeout 120000
fixtures.removeDocumentsOf 'mailbox', done
before (done) ->
@timeout 120000
fixtures.removeDocumentsOf 'mailssettings', done
before (done) ->
@timeout 120000
fixtures.removeDocumentsOf 'contact', done
# setup test IMAP server
unless process.env.SKIP_DOVECOT
before DovecotTesting.setupEnvironment
# setup test SMTP server
before (done) ->
@timeout 3000
SMTPTesting.init SMTP_PORT, done
# start the app & prepare store
before helpers.prepareForCrypto
before helpers.startApp appPath, APP_HOST, APP_PORT
before ->
global.store = {}
global.helpers = helpers
global.SMTPTesting = SMTPTesting
global.DovecotTesting = DovecotTesting
global.client = new Client "http://#{APP_HOST}:#{APP_PORT}/"
# define the test account
before ->
store.accountDefinition =
label: "DoveCot"
login: "testuser"
password: "PI:PASSWORD:<PASSWORD>END_PI"
smtpMethod: "NONE"
smtpServer: "127.0.0.1"
smtpPort: SMTP_PORT
smtpSSL: false
smtpTLS: true
imapServer: DovecotTesting.serverIP()
imapPort: 993
imapSSL: true
# stop the app
after helpers.stopApp
after ->
delete global.appPath
delete global.store
delete global.helpers
delete global.SMTPTesting
delete global.DovecotTesting
delete global.client
# SERVER TESTS
require './00_index'
require './01_account_creation'
require './02_account_synchro'
require './03_mailbox_operations'
require './04_message_operations'
require './05_mailbox_deletion'
require './06_settings'
require './07_activities'
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9983357787132263,
"start": 12,
"tag": "NAME",
"value": "Joyent"
},
{
"context": ".opensslCli, [\n \"s_client\"\n \"-connect\"\n \"127.0.0.1:\" + common.PORT\n ])\n out = \"\"\n client.stdout.s",
"end": 3215,
"score": 0.9994781017303467,
"start": 3206,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | test/simple/test-tls-securepair-server.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.
log = (a) ->
console.error "***server*** " + a
return
common = require("../common")
unless common.opensslCli
console.error "Skipping because node compiled without OpenSSL CLI."
process.exit 0
assert = require("assert")
join = require("path").join
net = require("net")
fs = require("fs")
tls = require("tls")
spawn = require("child_process").spawn
connections = 0
key = fs.readFileSync(join(common.fixturesDir, "agent.key")).toString()
cert = fs.readFileSync(join(common.fixturesDir, "agent.crt")).toString()
server = net.createServer((socket) ->
connections++
log "connection fd=" + socket.fd
sslcontext = tls.createSecureContext(
key: key
cert: cert
)
sslcontext.context.setCiphers "RC4-SHA:AES128-SHA:AES256-SHA"
pair = tls.createSecurePair(sslcontext, true)
assert.ok pair.encrypted.writable
assert.ok pair.cleartext.writable
pair.encrypted.pipe socket
socket.pipe pair.encrypted
log "i set it secure"
pair.on "secure", ->
log "connected+secure!"
pair.cleartext.write "hello\r\n"
log pair.cleartext.getPeerCertificate()
log pair.cleartext.getCipher()
return
pair.cleartext.on "data", (data) ->
log "read bytes " + data.length
pair.cleartext.write data
return
socket.on "end", ->
log "socket end"
return
pair.cleartext.on "error", (err) ->
log "got error: "
log err
log err.stack
socket.destroy()
return
pair.encrypted.on "error", (err) ->
log "encrypted error: "
log err
log err.stack
socket.destroy()
return
socket.on "error", (err) ->
log "socket error: "
log err
log err.stack
socket.destroy()
return
socket.on "close", (err) ->
log "socket closed"
return
pair.on "error", (err) ->
log "secure error: "
log err
log err.stack
socket.destroy()
return
return
)
gotHello = false
sentWorld = false
gotWorld = false
opensslExitCode = -1
server.listen common.PORT, ->
# To test use: openssl s_client -connect localhost:8000
client = spawn(common.opensslCli, [
"s_client"
"-connect"
"127.0.0.1:" + common.PORT
])
out = ""
client.stdout.setEncoding "utf8"
client.stdout.on "data", (d) ->
out += d
if not gotHello and /hello/.test(out)
gotHello = true
client.stdin.write "world\r\n"
sentWorld = true
if not gotWorld and /world/.test(out)
gotWorld = true
client.stdin.end()
return
client.stdout.pipe process.stdout,
end: false
client.on "exit", (code) ->
opensslExitCode = code
server.close()
return
return
process.on "exit", ->
assert.equal 1, connections
assert.ok gotHello
assert.ok sentWorld
assert.ok gotWorld
assert.equal 0, opensslExitCode
return
| 41714 | # 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.
log = (a) ->
console.error "***server*** " + a
return
common = require("../common")
unless common.opensslCli
console.error "Skipping because node compiled without OpenSSL CLI."
process.exit 0
assert = require("assert")
join = require("path").join
net = require("net")
fs = require("fs")
tls = require("tls")
spawn = require("child_process").spawn
connections = 0
key = fs.readFileSync(join(common.fixturesDir, "agent.key")).toString()
cert = fs.readFileSync(join(common.fixturesDir, "agent.crt")).toString()
server = net.createServer((socket) ->
connections++
log "connection fd=" + socket.fd
sslcontext = tls.createSecureContext(
key: key
cert: cert
)
sslcontext.context.setCiphers "RC4-SHA:AES128-SHA:AES256-SHA"
pair = tls.createSecurePair(sslcontext, true)
assert.ok pair.encrypted.writable
assert.ok pair.cleartext.writable
pair.encrypted.pipe socket
socket.pipe pair.encrypted
log "i set it secure"
pair.on "secure", ->
log "connected+secure!"
pair.cleartext.write "hello\r\n"
log pair.cleartext.getPeerCertificate()
log pair.cleartext.getCipher()
return
pair.cleartext.on "data", (data) ->
log "read bytes " + data.length
pair.cleartext.write data
return
socket.on "end", ->
log "socket end"
return
pair.cleartext.on "error", (err) ->
log "got error: "
log err
log err.stack
socket.destroy()
return
pair.encrypted.on "error", (err) ->
log "encrypted error: "
log err
log err.stack
socket.destroy()
return
socket.on "error", (err) ->
log "socket error: "
log err
log err.stack
socket.destroy()
return
socket.on "close", (err) ->
log "socket closed"
return
pair.on "error", (err) ->
log "secure error: "
log err
log err.stack
socket.destroy()
return
return
)
gotHello = false
sentWorld = false
gotWorld = false
opensslExitCode = -1
server.listen common.PORT, ->
# To test use: openssl s_client -connect localhost:8000
client = spawn(common.opensslCli, [
"s_client"
"-connect"
"127.0.0.1:" + common.PORT
])
out = ""
client.stdout.setEncoding "utf8"
client.stdout.on "data", (d) ->
out += d
if not gotHello and /hello/.test(out)
gotHello = true
client.stdin.write "world\r\n"
sentWorld = true
if not gotWorld and /world/.test(out)
gotWorld = true
client.stdin.end()
return
client.stdout.pipe process.stdout,
end: false
client.on "exit", (code) ->
opensslExitCode = code
server.close()
return
return
process.on "exit", ->
assert.equal 1, connections
assert.ok gotHello
assert.ok sentWorld
assert.ok gotWorld
assert.equal 0, opensslExitCode
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.
log = (a) ->
console.error "***server*** " + a
return
common = require("../common")
unless common.opensslCli
console.error "Skipping because node compiled without OpenSSL CLI."
process.exit 0
assert = require("assert")
join = require("path").join
net = require("net")
fs = require("fs")
tls = require("tls")
spawn = require("child_process").spawn
connections = 0
key = fs.readFileSync(join(common.fixturesDir, "agent.key")).toString()
cert = fs.readFileSync(join(common.fixturesDir, "agent.crt")).toString()
server = net.createServer((socket) ->
connections++
log "connection fd=" + socket.fd
sslcontext = tls.createSecureContext(
key: key
cert: cert
)
sslcontext.context.setCiphers "RC4-SHA:AES128-SHA:AES256-SHA"
pair = tls.createSecurePair(sslcontext, true)
assert.ok pair.encrypted.writable
assert.ok pair.cleartext.writable
pair.encrypted.pipe socket
socket.pipe pair.encrypted
log "i set it secure"
pair.on "secure", ->
log "connected+secure!"
pair.cleartext.write "hello\r\n"
log pair.cleartext.getPeerCertificate()
log pair.cleartext.getCipher()
return
pair.cleartext.on "data", (data) ->
log "read bytes " + data.length
pair.cleartext.write data
return
socket.on "end", ->
log "socket end"
return
pair.cleartext.on "error", (err) ->
log "got error: "
log err
log err.stack
socket.destroy()
return
pair.encrypted.on "error", (err) ->
log "encrypted error: "
log err
log err.stack
socket.destroy()
return
socket.on "error", (err) ->
log "socket error: "
log err
log err.stack
socket.destroy()
return
socket.on "close", (err) ->
log "socket closed"
return
pair.on "error", (err) ->
log "secure error: "
log err
log err.stack
socket.destroy()
return
return
)
gotHello = false
sentWorld = false
gotWorld = false
opensslExitCode = -1
server.listen common.PORT, ->
# To test use: openssl s_client -connect localhost:8000
client = spawn(common.opensslCli, [
"s_client"
"-connect"
"127.0.0.1:" + common.PORT
])
out = ""
client.stdout.setEncoding "utf8"
client.stdout.on "data", (d) ->
out += d
if not gotHello and /hello/.test(out)
gotHello = true
client.stdin.write "world\r\n"
sentWorld = true
if not gotWorld and /world/.test(out)
gotWorld = true
client.stdin.end()
return
client.stdout.pipe process.stdout,
end: false
client.on "exit", (code) ->
opensslExitCode = code
server.close()
return
return
process.on "exit", ->
assert.equal 1, connections
assert.ok gotHello
assert.ok sentWorld
assert.ok gotWorld
assert.equal 0, opensslExitCode
return
|
[
{
"context": ": process.env.PIN_AUTHENTICATOR_UUID\n token: process.env.PIN_AUTHENTICATOR_TOKEN\n server: process.e",
"end": 435,
"score": 0.33852899074554443,
"start": 428,
"tag": "KEY",
"value": "process"
},
{
"context": "ess.env.PIN_AUTHENTICATOR_UUID\n token: process.env.PIN_AUTHENTICATOR_TOKEN\n server: process.env.ME",
"end": 439,
"score": 0.44021105766296387,
"start": 436,
"tag": "PASSWORD",
"value": "env"
}
] | server.coffee | octoblu/meshblu-pin-trusted-device | 0 | express = require 'express'
morgan = require 'morgan'
errorHandler = require 'errorhandler'
meshbluHealthcheck = require 'express-meshblu-healthcheck'
bodyParser = require 'body-parser'
cors = require 'cors'
meshblu = require 'meshblu'
Routes = require './app/routes'
try
meshbluJSON = require './meshblu.json'
catch
meshbluJSON =
uuid: process.env.PIN_AUTHENTICATOR_UUID
token: process.env.PIN_AUTHENTICATOR_TOKEN
server: process.env.MESHBLU_HOST
port: process.env.MESHBLU_PORT
port = process.env.PIN_AUTHENTICATOR_PORT ? 80
app = express()
app.use meshbluHealthcheck()
app.use morgan('dev')
app.use errorHandler()
app.use bodyParser.json()
app.use bodyParser.urlencoded(extended: true)
app.use cors()
conn = meshblu.createConnection meshbluJSON
conn.once 'ready', ->
routes = new Routes app, meshbluJSON.uuid, conn
routes.register()
app.listen port, =>
console.log "listening at localhost:#{port}"
process.on 'SIGTERM', =>
console.log 'SIGTERM caught, exiting'
process.exit 0
conn.on 'notReady', ->
console.error "Unable to establish a connection to meshblu"
| 126346 | express = require 'express'
morgan = require 'morgan'
errorHandler = require 'errorhandler'
meshbluHealthcheck = require 'express-meshblu-healthcheck'
bodyParser = require 'body-parser'
cors = require 'cors'
meshblu = require 'meshblu'
Routes = require './app/routes'
try
meshbluJSON = require './meshblu.json'
catch
meshbluJSON =
uuid: process.env.PIN_AUTHENTICATOR_UUID
token: <KEY>.<PASSWORD>.PIN_AUTHENTICATOR_TOKEN
server: process.env.MESHBLU_HOST
port: process.env.MESHBLU_PORT
port = process.env.PIN_AUTHENTICATOR_PORT ? 80
app = express()
app.use meshbluHealthcheck()
app.use morgan('dev')
app.use errorHandler()
app.use bodyParser.json()
app.use bodyParser.urlencoded(extended: true)
app.use cors()
conn = meshblu.createConnection meshbluJSON
conn.once 'ready', ->
routes = new Routes app, meshbluJSON.uuid, conn
routes.register()
app.listen port, =>
console.log "listening at localhost:#{port}"
process.on 'SIGTERM', =>
console.log 'SIGTERM caught, exiting'
process.exit 0
conn.on 'notReady', ->
console.error "Unable to establish a connection to meshblu"
| true | express = require 'express'
morgan = require 'morgan'
errorHandler = require 'errorhandler'
meshbluHealthcheck = require 'express-meshblu-healthcheck'
bodyParser = require 'body-parser'
cors = require 'cors'
meshblu = require 'meshblu'
Routes = require './app/routes'
try
meshbluJSON = require './meshblu.json'
catch
meshbluJSON =
uuid: process.env.PIN_AUTHENTICATOR_UUID
token: PI:KEY:<KEY>END_PI.PI:PASSWORD:<PASSWORD>END_PI.PIN_AUTHENTICATOR_TOKEN
server: process.env.MESHBLU_HOST
port: process.env.MESHBLU_PORT
port = process.env.PIN_AUTHENTICATOR_PORT ? 80
app = express()
app.use meshbluHealthcheck()
app.use morgan('dev')
app.use errorHandler()
app.use bodyParser.json()
app.use bodyParser.urlencoded(extended: true)
app.use cors()
conn = meshblu.createConnection meshbluJSON
conn.once 'ready', ->
routes = new Routes app, meshbluJSON.uuid, conn
routes.register()
app.listen port, =>
console.log "listening at localhost:#{port}"
process.on 'SIGTERM', =>
console.log 'SIGTERM caught, exiting'
process.exit 0
conn.on 'notReady', ->
console.error "Unable to establish a connection to meshblu"
|
[
{
"context": "Welcome:\n tabTitle: \"Vitajte\"\n subtitle: {\n text1: \"Modifikovateľný ",
"end": 23,
"score": 0.70341956615448,
"start": 22,
"tag": "NAME",
"value": "V"
}
] | def/sk/welcome.cson | abilogos/atom-i18n | 76 | Welcome:
tabTitle: "Vitajte"
subtitle: {
text1: "Modifikovateľný editor pre 21"
superscript: ""
text2: " storočie"
}
help: {
forHelpVisit: "Pre pomoc prosím navštívte"
atomDocs: {
text1: ""
link: "Dokumentáciu Atomu"
text2: " pre Návody a API REFERENCIE."
_template: "${text1}<a>${link}</a>${text2}"
}
atomForum: {
text1: "Fórum atomu na: "
link: "discuss.atom.io"
text2: "" # optional
_template: "${text1}<a>${link}</a>${text2}"
}
atomOrg: {
text1: ""
link: "Atom org"
text2: ". Tuto nájdete všetky pluginy z Githubu pre Atom."
_template: "${text1}<a>${link}</a>${text2}"
}
}
showWelcomeGuide: "Zobraziť obrazovku \"Vitajte\" pri spustení Atomu"
| 39078 | Welcome:
tabTitle: "<NAME>itajte"
subtitle: {
text1: "Modifikovateľný editor pre 21"
superscript: ""
text2: " storočie"
}
help: {
forHelpVisit: "Pre pomoc prosím navštívte"
atomDocs: {
text1: ""
link: "Dokumentáciu Atomu"
text2: " pre Návody a API REFERENCIE."
_template: "${text1}<a>${link}</a>${text2}"
}
atomForum: {
text1: "Fórum atomu na: "
link: "discuss.atom.io"
text2: "" # optional
_template: "${text1}<a>${link}</a>${text2}"
}
atomOrg: {
text1: ""
link: "Atom org"
text2: ". Tuto nájdete všetky pluginy z Githubu pre Atom."
_template: "${text1}<a>${link}</a>${text2}"
}
}
showWelcomeGuide: "Zobraziť obrazovku \"Vitajte\" pri spustení Atomu"
| true | Welcome:
tabTitle: "PI:NAME:<NAME>END_PIitajte"
subtitle: {
text1: "Modifikovateľný editor pre 21"
superscript: ""
text2: " storočie"
}
help: {
forHelpVisit: "Pre pomoc prosím navštívte"
atomDocs: {
text1: ""
link: "Dokumentáciu Atomu"
text2: " pre Návody a API REFERENCIE."
_template: "${text1}<a>${link}</a>${text2}"
}
atomForum: {
text1: "Fórum atomu na: "
link: "discuss.atom.io"
text2: "" # optional
_template: "${text1}<a>${link}</a>${text2}"
}
atomOrg: {
text1: ""
link: "Atom org"
text2: ". Tuto nájdete všetky pluginy z Githubu pre Atom."
_template: "${text1}<a>${link}</a>${text2}"
}
}
showWelcomeGuide: "Zobraziť obrazovku \"Vitajte\" pri spustení Atomu"
|
[
{
"context": "\n CONTACT_PHONE: '13810906731'\n CONTACT_EMAIL: 'china@codecombat.com'\n}\n\nmodule.exports = {\n STARTER_LICENSE_COURSE_I",
"end": 1373,
"score": 0.9999211430549622,
"start": 1353,
"tag": "EMAIL",
"value": "china@codecombat.com"
}
] | app/core/constants.coffee | michaelrn/codecombat | 2 | STARTER_LICENSE_COURSE_IDS = [
"560f1a9f22961295f9427742" # Introduction to Computer Science
"5632661322961295f9428638" # Computer Science 2
"5789587aad86a6efb573701e" # Game Development 1
"5789587aad86a6efb573701f" # Web Development 1
]
LICENSE_PRESETS = {
'CS1+CS2+GD1+WD1': STARTER_LICENSE_COURSE_IDS
'CS1+CS2+CS3+CS4': [
'560f1a9f22961295f9427742' # Introduction to Computer Science
'5632661322961295f9428638' # CS 2
'56462f935afde0c6fd30fc8c' # CS 3
'56462f935afde0c6fd30fc8d' # CS 4
]
'CS1+CS2+CS3+CS4+CS5+CS6': [
'560f1a9f22961295f9427742' # Introduction to Computer Science
'5632661322961295f9428638' # CS 2
'56462f935afde0c6fd30fc8c' # CS 3
'56462f935afde0c6fd30fc8d' # CS 4
'569ed916efa72b0ced971447' # CS 5
'5817d673e85d1220db624ca4' # CS 6
]
'CS1+CS2+GD1+GD2+WD1+WD2': [
'560f1a9f22961295f9427742' # Introduction to Computer Science
'5632661322961295f9428638' # CS 2
'5789587aad86a6efb573701e' # Game Development 1
'57b621e7ad86a6efb5737e64' # GD 2
'5789587aad86a6efb573701f' # Web Development 1
'5789587aad86a6efb5737020' # WD 2
]
}
FREE_COURSE_IDS = [
"560f1a9f22961295f9427742" # Introduction to Computer Science
]
MAX_STARTER_LICENSES = 75
STARTER_LICENCE_LENGTH_MONTHS = 3
COCO_CHINA_CONST = {
CONTACT_PHONE: '13810906731'
CONTACT_EMAIL: 'china@codecombat.com'
}
module.exports = {
STARTER_LICENSE_COURSE_IDS
FREE_COURSE_IDS
MAX_STARTER_LICENSES
STARTER_LICENCE_LENGTH_MONTHS
COCO_CHINA_CONST
LICENSE_PRESETS
}
| 205383 | STARTER_LICENSE_COURSE_IDS = [
"560f1a9f22961295f9427742" # Introduction to Computer Science
"5632661322961295f9428638" # Computer Science 2
"5789587aad86a6efb573701e" # Game Development 1
"5789587aad86a6efb573701f" # Web Development 1
]
LICENSE_PRESETS = {
'CS1+CS2+GD1+WD1': STARTER_LICENSE_COURSE_IDS
'CS1+CS2+CS3+CS4': [
'560f1a9f22961295f9427742' # Introduction to Computer Science
'5632661322961295f9428638' # CS 2
'56462f935afde0c6fd30fc8c' # CS 3
'56462f935afde0c6fd30fc8d' # CS 4
]
'CS1+CS2+CS3+CS4+CS5+CS6': [
'560f1a9f22961295f9427742' # Introduction to Computer Science
'5632661322961295f9428638' # CS 2
'56462f935afde0c6fd30fc8c' # CS 3
'56462f935afde0c6fd30fc8d' # CS 4
'569ed916efa72b0ced971447' # CS 5
'5817d673e85d1220db624ca4' # CS 6
]
'CS1+CS2+GD1+GD2+WD1+WD2': [
'560f1a9f22961295f9427742' # Introduction to Computer Science
'5632661322961295f9428638' # CS 2
'5789587aad86a6efb573701e' # Game Development 1
'57b621e7ad86a6efb5737e64' # GD 2
'5789587aad86a6efb573701f' # Web Development 1
'5789587aad86a6efb5737020' # WD 2
]
}
FREE_COURSE_IDS = [
"560f1a9f22961295f9427742" # Introduction to Computer Science
]
MAX_STARTER_LICENSES = 75
STARTER_LICENCE_LENGTH_MONTHS = 3
COCO_CHINA_CONST = {
CONTACT_PHONE: '13810906731'
CONTACT_EMAIL: '<EMAIL>'
}
module.exports = {
STARTER_LICENSE_COURSE_IDS
FREE_COURSE_IDS
MAX_STARTER_LICENSES
STARTER_LICENCE_LENGTH_MONTHS
COCO_CHINA_CONST
LICENSE_PRESETS
}
| true | STARTER_LICENSE_COURSE_IDS = [
"560f1a9f22961295f9427742" # Introduction to Computer Science
"5632661322961295f9428638" # Computer Science 2
"5789587aad86a6efb573701e" # Game Development 1
"5789587aad86a6efb573701f" # Web Development 1
]
LICENSE_PRESETS = {
'CS1+CS2+GD1+WD1': STARTER_LICENSE_COURSE_IDS
'CS1+CS2+CS3+CS4': [
'560f1a9f22961295f9427742' # Introduction to Computer Science
'5632661322961295f9428638' # CS 2
'56462f935afde0c6fd30fc8c' # CS 3
'56462f935afde0c6fd30fc8d' # CS 4
]
'CS1+CS2+CS3+CS4+CS5+CS6': [
'560f1a9f22961295f9427742' # Introduction to Computer Science
'5632661322961295f9428638' # CS 2
'56462f935afde0c6fd30fc8c' # CS 3
'56462f935afde0c6fd30fc8d' # CS 4
'569ed916efa72b0ced971447' # CS 5
'5817d673e85d1220db624ca4' # CS 6
]
'CS1+CS2+GD1+GD2+WD1+WD2': [
'560f1a9f22961295f9427742' # Introduction to Computer Science
'5632661322961295f9428638' # CS 2
'5789587aad86a6efb573701e' # Game Development 1
'57b621e7ad86a6efb5737e64' # GD 2
'5789587aad86a6efb573701f' # Web Development 1
'5789587aad86a6efb5737020' # WD 2
]
}
FREE_COURSE_IDS = [
"560f1a9f22961295f9427742" # Introduction to Computer Science
]
MAX_STARTER_LICENSES = 75
STARTER_LICENCE_LENGTH_MONTHS = 3
COCO_CHINA_CONST = {
CONTACT_PHONE: '13810906731'
CONTACT_EMAIL: 'PI:EMAIL:<EMAIL>END_PI'
}
module.exports = {
STARTER_LICENSE_COURSE_IDS
FREE_COURSE_IDS
MAX_STARTER_LICENSES
STARTER_LICENCE_LENGTH_MONTHS
COCO_CHINA_CONST
LICENSE_PRESETS
}
|
[
{
"context": " CanvasFilmMovie\n Copyright(c) 2015 SHIFTBRAIN - Tsukasa Tokura\n This software is released under the MIT License",
"end": 69,
"score": 0.9998410940170288,
"start": 55,
"tag": "NAME",
"value": "Tsukasa Tokura"
}
] | src/CanvasFilmMovie.coffee | tsukasa-web/CanvasFilmMovie | 1 | ###
CanvasFilmMovie
Copyright(c) 2015 SHIFTBRAIN - Tsukasa Tokura
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
###
class CanvasFilmMovie
defaults :
acTime : 3 #フィルムの最大速度到達時間
acEasing : $.easing.easeInSine #加速のEasing
deTime : 2 #フィルムの停止到達時間
deEasing : $.easing.easeOutSine #減速のEasing
offsetValue : 1 #MAX時の移動方向・速度(正は右、負は逆)
targetImgArray : [] #使用画像が格納された配列
sceneWidth : false #読み込んだ画像の1シーンの横幅
sceneHeight : false #読み込んだ画像の1シーンの縦幅
fps : 30 #1秒あたりのコマ数
constructor : (_$targetParent, options) ->
#optionのマージ
@options = $.extend {}, @defaults, options
@imgWidth = null #読み込んだ画像の全体横幅
@imgHeight = null #読み込んだ画像の全体縦幅
@canvasPointArray = [] #canvs上の各パネル座標を格納する配列
@imgPointArray = [] #読み込んだ画像の各シーンの座標を格納する配列
@canvasPanelWidth = null #canvasのパネルの横幅
@canvasXPanelNum = null #canvasの横のパネル数
@imgPanelresizedWidth = null #canvasの高さに合わせて画像の1シーンを拡縮した際の横幅
@imgXPanelNum = null #読み込んだ画像の横のシーン数
@imgYPanelNum = null #読み込んだ画像の縦のシーン数
@acSpeedArray = [] #フレーム分割した加速度を格納する配列
@deSpeedArray = [] #フレーム分割した減速度を格納する配列
@currentFrame = 0 #現在のフレーム位置
@vector = 1 #反転のフラグ
@nowSpeed = 0 #現在の速度
@stopping = false #減速中かどうかのフラグ
@isDrawed = false #パネルが埋まっているかどうかのフラグ
@$targetParent = _$targetParent #canvasの親になる生成先
@canvas = null
@ctx = null
@requestId = null #RAFに使用するID
@setTimerId = null #Timeoutに使用するID
@fpsInterval = 1000 / @options.fps #RAFのfps調整に使用するフレーム間隔の変数
@timeLog = Date.now() #RAFのfps調整に使用する変数
#RAFの宣言(fallback付)
@requestAnimationFrame =
(window.requestAnimationFrame and window.requestAnimationFrame.bind(window)) or
(window.webkitRequestAnimationFrame and window.webkitRequestAnimationFrame.bind(window)) or
(window.mozRequestAnimationFrame and window.mozRequestAnimationFrame.bind(window)) or
(window.oRequestAnimationFrame and window.oRequestAnimationFrame.bind(window)) or
(window.msRequestAnimationFrame and window.msRequestAnimationFrame.bind(window)) or
(callback,element) ->
@setTimerId = window.setTimeout(callback, 1000 / 60)
#キャンセル用RAFの宣言(fallback付)
@cancelAnimationFrame =
(window.cancelAnimationFrame and window.cancelAnimationFrame.bind(window)) or
(window.webkitCancelAnimationFrame and window.webkitCancelAnimationFrame.bind(window)) or
(window.mozCancelAnimationFrame and window.mozCancelAnimationFrame.bind(window)) or
(window.oCancelAnimationFrame and window.oCancelAnimationFrame.bind(window)) or
(window.msCancelAnimationFrame and window.msCancelAnimationFrame.bind(window)) or
(callback,element) ->
window.clearTimeout(@setTimerId)
#初期処理
@_init()
_init: ->
#渡されたImgArrayが空、中のImgがロードされてない、中のImgがそもそも渡されていないとエラー
if @options.targetImgArray.length is 0
console.error('Image Array is empty.')
return false
for i in [0...@options.targetImgArray.length]
if @options.targetImgArray[i].width is 0 or !@options.targetImgArray[i]
console.error('Image not loaded.')
return false
#オプションにシーンの横幅と縦幅がないとエラー
if @options.sceneWidth is false or @options.sceneHeight is false
console.error('Input Scene Size.')
return false
#canvasの生成、contextの宣言
@$targetParent.append('<canvas class="canvas-film-sprite"></canvas>')
@canvas = @$targetParent.find('.canvas-film-sprite')[0]
@ctx = @canvas.getContext("2d")
@_canvasResize()
#liquid対応のリサイズイベント登録
$(window).on('resize', @_debounce(
()=> @_canvasResize()
,300))
return
#canvasのリサイズ関数
_canvasResize: =>
parentWidth = @$targetParent.width()
parentHeight = @$targetParent.height()
$(@canvas).attr({'width':parentWidth,'height':parentHeight})
#座標の計算
@_createCuttPoint(@options.targetImgObject)
#isDrawedなら最初から再描画、タイマーが回ってなければとりあえず再描画
if @isDrawed
if @nowSpeed >= @canvasPanelWidth
@nowSpeed = @canvasPanelWidth
if !@requestId
@_setSpriteImg()
@_calculateSpeed()
return
#実行回数の間引き
_debounce: (func, threshold, execAsap) ->
timeout = null
(args...) ->
obj = this
delayed = ->
func.apply(obj, args) unless execAsap
timeout = null
return
if timeout
clearTimeout(timeout)
else if (execAsap)
func.apply(obj, args)
timeout = setTimeout delayed, threshold || 100
#スピードフレームの計算
_calculateSpeed: ->
#フレーム分割した加速度の配列作成
@acSpeedArray = []
#(fps*到達までの時間)で全体フレーム数を算出
max = @options.fps * @options.acTime - 1
for i in [0..max]
@acSpeedArray[i] = @options.acEasing 0, i, 0, @canvasPanelWidth - @options.offsetValue, max
#フレーム分割した減速度の配列作成
@deSpeedArray = []
#(fps*到達までの時間)で全体フレーム数を算出
max = @options.fps * @options.deTime - 1
for i in [0..max]
@deSpeedArray[i] = @options.deEasing 0, max - i, 0, @canvasPanelWidth - @options.offsetValue, max
#console.log @acSpeedArray
#console.log @deSpeedArray
return
#各種幅や座標の計算
_createCuttPoint: ->
canvasWidth = @canvas.width
canvasHeight = @canvas.height
#console.log('canvas width = ' + canvasWidth)
#console.log('canvas height = ' + canvasHeight)
@canvasPanelWidth = @imgPanelresizedWidth = Math.ceil(@options.sceneWidth*(canvasHeight / @options.sceneHeight))
@canvasXPanelNum = Math.ceil(canvasWidth / @imgPanelresizedWidth)
#console.log('canvas scene width = ' + @canvasPanelWidth)
#console.log('canvas scene height = ' + canvasHeight)
#targetImgArrayからイメージの座標を結合して一つの配列を作る
if @imgPointArray.length is 0
for i in [0...@options.targetImgArray.length]
partsPointArray = @_imgPointPush(@options.targetImgArray[i])
for i in [0...partsPointArray.length]
@imgPointArray.push(partsPointArray[i])
#console.log(@imgPointArray)
@canvasPointArray = @_canvasPointPush()
#console.log('canvasの横一列パネル数(はみ出てるのも含め) = ' + @canvasPointArray.length)
#console.log('動画のシーン画像の数 = ' + @imgPointArray.length)
return
#canvas座標配列を返す関数
_canvasPointPush: ->
pointArray = []
for i in [0...@imgPointArray.length]
pointArray.push({x:i * @canvasPanelWidth, y:0})
#console.log(pointArray)
return pointArray
#シーン座標配列を返す関数
_imgPointPush: (targetImg)->
imgWidth = targetImg.width
imgHeight = targetImg.height
imgXPanelNum = Math.ceil(imgWidth / @options.sceneWidth)
imgYPanelNum = Math.ceil(imgHeight / @options.sceneHeight)
pointArray = []
nowPoint = 0
for i in [0...imgYPanelNum]
for i2 in [0...imgXPanelNum]
pointArray.push({x:i2 * @options.sceneWidth, y:nowPoint, img:targetImg})
if i2 is imgXPanelNum-1
nowPoint += @options.sceneHeight
#console.log(pointArray)
return pointArray
#スプライトの描画関数
_setSpriteImg: ->
#console.log('Single draw')
@isDrawed = true
for i in [0...@canvasPointArray.length]
@ctx.drawImage(
@imgPointArray[i].img
@imgPointArray[i].x
@imgPointArray[i].y
@options.sceneWidth
@options.sceneHeight
@canvasPointArray[i].x
@canvasPointArray[i].y
@canvasPanelWidth
@canvas.height
)
return
#スプライトの描画関数
_drawSpriteImg: ->
#RAFのフレーム調整
now = Date.now()
elapsed = now - @timeLog
if elapsed > @fpsInterval
@timeLog = now - (elapsed % @fpsInterval)
#------------ここからEasingの計算-----------------
if @stopping
if @vector > 0
@vector = -1
if @currentFrame < @acSpeedArray.length
val = @acSpeedArray[@currentFrame]
for v, i in @deSpeedArray
if val >= v
@currentFrame = i
break
else
@currentFrame = 0
@currentFrame = @deSpeedArray.length - 1 if @currentFrame >= @deSpeedArray.length
@nowSpeed = @deSpeedArray[@currentFrame]
if @nowSpeed == 0
@vector = 1
@nowSpeed = 0
@currentFrame = 0
@stopping = false
@drawLoopStop()
return
else
if @vector < 0
@vector = 1
if @currentFrame < @deSpeedArray.length
val = @deSpeedArray[@currentFrame]
for v, i in @acSpeedArray
if val <= v
@currentFrame = i
break
else
@currentFrame = @acSpeedArray.length - 1
@currentFrame = @acSpeedArray.length - 1 if @currentFrame >= @acSpeedArray.length
@nowSpeed = @acSpeedArray[@currentFrame]
@currentFrame++
#------------ここまでEasingの計算-----------------
#位置の計算
for i in [0...@canvasPointArray.length]
@canvasPointArray[i].x -= @nowSpeed
#計算後の位置ではみ出ているものは後ろの位置へ移動し、描画
for i in [0...@canvasPointArray.length]
if @canvasPointArray[i].x <= -(@canvasPanelWidth)
if i is 0
@canvasPointArray[i].x = @canvasPointArray[@canvasPointArray.length-1].x + @canvasPanelWidth
#console.log('before panel = ' + @canvasPointArray[@canvasPointArray.length-1][0])
else
@canvasPointArray[i].x = @canvasPointArray[i-1].x + @canvasPanelWidth
#console.log('before panel = ' + @canvasPointArray[i-1][0])
#console.log('this panel = ' + @canvasPointArray[i][0])
if @canvasPointArray[i].x > -(@canvasPanelWidth) and @canvasPointArray[i].x < @canvas.width
@ctx.drawImage(
@imgPointArray[i].img
@imgPointArray[i].x
@imgPointArray[i].y
@options.sceneWidth
@options.sceneHeight
@canvasPointArray[i].x
@canvasPointArray[i].y
@canvasPanelWidth
@canvas.height
)
return
#描画ループを加速
drawLoopSpeedUp: =>
#console.log('Loop Start + Speed Up')
@stopping = false
if !@requestId
@_drawLoop()
return
#描画ループを減速
drawLoopSpeedDown: =>
#console.log('Loop Start + Speed Down')
@stopping = true
return
#描画ループをスタート(加減速はしない)
drawLoopStart: =>
#console.log('Loop Start')
if !@requestId
@_drawLoop()
return
#描画ループをストップ
drawLoopStop: =>
#console.log('Loop Stop')
if @requestId
@cancelAnimationFrame(@requestId)
@requestId = null
return
#ループ関数
_drawLoop: =>
@requestId = @requestAnimationFrame(@_drawLoop)
@_drawSpriteImg()
return
#canvasの初期化
spriteClear: =>
#console.log('sprite clear')
@isDrawed = true
@ctx.clearRect(0, 0, @canvas.width, @canvas.height)
return
#fpsの変更
changeFps: (_changeFps) =>
if _changeFps isnt @options.fps
#console.log('change Fps = ' + _changeFps)
@options.fps = _changeFps
@fpsInterval = 1000 / @options.fps
@_calculateSpeed()
return
$.fn.CanvasFilmMovie = (options) ->
@each (i, el) ->
$el = $(el)
FilmMovie = new CanvasFilmMovie $el, options
$el.data 'CanvasFilmMovie', FilmMovie | 160803 | ###
CanvasFilmMovie
Copyright(c) 2015 SHIFTBRAIN - <NAME>
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
###
class CanvasFilmMovie
defaults :
acTime : 3 #フィルムの最大速度到達時間
acEasing : $.easing.easeInSine #加速のEasing
deTime : 2 #フィルムの停止到達時間
deEasing : $.easing.easeOutSine #減速のEasing
offsetValue : 1 #MAX時の移動方向・速度(正は右、負は逆)
targetImgArray : [] #使用画像が格納された配列
sceneWidth : false #読み込んだ画像の1シーンの横幅
sceneHeight : false #読み込んだ画像の1シーンの縦幅
fps : 30 #1秒あたりのコマ数
constructor : (_$targetParent, options) ->
#optionのマージ
@options = $.extend {}, @defaults, options
@imgWidth = null #読み込んだ画像の全体横幅
@imgHeight = null #読み込んだ画像の全体縦幅
@canvasPointArray = [] #canvs上の各パネル座標を格納する配列
@imgPointArray = [] #読み込んだ画像の各シーンの座標を格納する配列
@canvasPanelWidth = null #canvasのパネルの横幅
@canvasXPanelNum = null #canvasの横のパネル数
@imgPanelresizedWidth = null #canvasの高さに合わせて画像の1シーンを拡縮した際の横幅
@imgXPanelNum = null #読み込んだ画像の横のシーン数
@imgYPanelNum = null #読み込んだ画像の縦のシーン数
@acSpeedArray = [] #フレーム分割した加速度を格納する配列
@deSpeedArray = [] #フレーム分割した減速度を格納する配列
@currentFrame = 0 #現在のフレーム位置
@vector = 1 #反転のフラグ
@nowSpeed = 0 #現在の速度
@stopping = false #減速中かどうかのフラグ
@isDrawed = false #パネルが埋まっているかどうかのフラグ
@$targetParent = _$targetParent #canvasの親になる生成先
@canvas = null
@ctx = null
@requestId = null #RAFに使用するID
@setTimerId = null #Timeoutに使用するID
@fpsInterval = 1000 / @options.fps #RAFのfps調整に使用するフレーム間隔の変数
@timeLog = Date.now() #RAFのfps調整に使用する変数
#RAFの宣言(fallback付)
@requestAnimationFrame =
(window.requestAnimationFrame and window.requestAnimationFrame.bind(window)) or
(window.webkitRequestAnimationFrame and window.webkitRequestAnimationFrame.bind(window)) or
(window.mozRequestAnimationFrame and window.mozRequestAnimationFrame.bind(window)) or
(window.oRequestAnimationFrame and window.oRequestAnimationFrame.bind(window)) or
(window.msRequestAnimationFrame and window.msRequestAnimationFrame.bind(window)) or
(callback,element) ->
@setTimerId = window.setTimeout(callback, 1000 / 60)
#キャンセル用RAFの宣言(fallback付)
@cancelAnimationFrame =
(window.cancelAnimationFrame and window.cancelAnimationFrame.bind(window)) or
(window.webkitCancelAnimationFrame and window.webkitCancelAnimationFrame.bind(window)) or
(window.mozCancelAnimationFrame and window.mozCancelAnimationFrame.bind(window)) or
(window.oCancelAnimationFrame and window.oCancelAnimationFrame.bind(window)) or
(window.msCancelAnimationFrame and window.msCancelAnimationFrame.bind(window)) or
(callback,element) ->
window.clearTimeout(@setTimerId)
#初期処理
@_init()
_init: ->
#渡されたImgArrayが空、中のImgがロードされてない、中のImgがそもそも渡されていないとエラー
if @options.targetImgArray.length is 0
console.error('Image Array is empty.')
return false
for i in [0...@options.targetImgArray.length]
if @options.targetImgArray[i].width is 0 or !@options.targetImgArray[i]
console.error('Image not loaded.')
return false
#オプションにシーンの横幅と縦幅がないとエラー
if @options.sceneWidth is false or @options.sceneHeight is false
console.error('Input Scene Size.')
return false
#canvasの生成、contextの宣言
@$targetParent.append('<canvas class="canvas-film-sprite"></canvas>')
@canvas = @$targetParent.find('.canvas-film-sprite')[0]
@ctx = @canvas.getContext("2d")
@_canvasResize()
#liquid対応のリサイズイベント登録
$(window).on('resize', @_debounce(
()=> @_canvasResize()
,300))
return
#canvasのリサイズ関数
_canvasResize: =>
parentWidth = @$targetParent.width()
parentHeight = @$targetParent.height()
$(@canvas).attr({'width':parentWidth,'height':parentHeight})
#座標の計算
@_createCuttPoint(@options.targetImgObject)
#isDrawedなら最初から再描画、タイマーが回ってなければとりあえず再描画
if @isDrawed
if @nowSpeed >= @canvasPanelWidth
@nowSpeed = @canvasPanelWidth
if !@requestId
@_setSpriteImg()
@_calculateSpeed()
return
#実行回数の間引き
_debounce: (func, threshold, execAsap) ->
timeout = null
(args...) ->
obj = this
delayed = ->
func.apply(obj, args) unless execAsap
timeout = null
return
if timeout
clearTimeout(timeout)
else if (execAsap)
func.apply(obj, args)
timeout = setTimeout delayed, threshold || 100
#スピードフレームの計算
_calculateSpeed: ->
#フレーム分割した加速度の配列作成
@acSpeedArray = []
#(fps*到達までの時間)で全体フレーム数を算出
max = @options.fps * @options.acTime - 1
for i in [0..max]
@acSpeedArray[i] = @options.acEasing 0, i, 0, @canvasPanelWidth - @options.offsetValue, max
#フレーム分割した減速度の配列作成
@deSpeedArray = []
#(fps*到達までの時間)で全体フレーム数を算出
max = @options.fps * @options.deTime - 1
for i in [0..max]
@deSpeedArray[i] = @options.deEasing 0, max - i, 0, @canvasPanelWidth - @options.offsetValue, max
#console.log @acSpeedArray
#console.log @deSpeedArray
return
#各種幅や座標の計算
_createCuttPoint: ->
canvasWidth = @canvas.width
canvasHeight = @canvas.height
#console.log('canvas width = ' + canvasWidth)
#console.log('canvas height = ' + canvasHeight)
@canvasPanelWidth = @imgPanelresizedWidth = Math.ceil(@options.sceneWidth*(canvasHeight / @options.sceneHeight))
@canvasXPanelNum = Math.ceil(canvasWidth / @imgPanelresizedWidth)
#console.log('canvas scene width = ' + @canvasPanelWidth)
#console.log('canvas scene height = ' + canvasHeight)
#targetImgArrayからイメージの座標を結合して一つの配列を作る
if @imgPointArray.length is 0
for i in [0...@options.targetImgArray.length]
partsPointArray = @_imgPointPush(@options.targetImgArray[i])
for i in [0...partsPointArray.length]
@imgPointArray.push(partsPointArray[i])
#console.log(@imgPointArray)
@canvasPointArray = @_canvasPointPush()
#console.log('canvasの横一列パネル数(はみ出てるのも含め) = ' + @canvasPointArray.length)
#console.log('動画のシーン画像の数 = ' + @imgPointArray.length)
return
#canvas座標配列を返す関数
_canvasPointPush: ->
pointArray = []
for i in [0...@imgPointArray.length]
pointArray.push({x:i * @canvasPanelWidth, y:0})
#console.log(pointArray)
return pointArray
#シーン座標配列を返す関数
_imgPointPush: (targetImg)->
imgWidth = targetImg.width
imgHeight = targetImg.height
imgXPanelNum = Math.ceil(imgWidth / @options.sceneWidth)
imgYPanelNum = Math.ceil(imgHeight / @options.sceneHeight)
pointArray = []
nowPoint = 0
for i in [0...imgYPanelNum]
for i2 in [0...imgXPanelNum]
pointArray.push({x:i2 * @options.sceneWidth, y:nowPoint, img:targetImg})
if i2 is imgXPanelNum-1
nowPoint += @options.sceneHeight
#console.log(pointArray)
return pointArray
#スプライトの描画関数
_setSpriteImg: ->
#console.log('Single draw')
@isDrawed = true
for i in [0...@canvasPointArray.length]
@ctx.drawImage(
@imgPointArray[i].img
@imgPointArray[i].x
@imgPointArray[i].y
@options.sceneWidth
@options.sceneHeight
@canvasPointArray[i].x
@canvasPointArray[i].y
@canvasPanelWidth
@canvas.height
)
return
#スプライトの描画関数
_drawSpriteImg: ->
#RAFのフレーム調整
now = Date.now()
elapsed = now - @timeLog
if elapsed > @fpsInterval
@timeLog = now - (elapsed % @fpsInterval)
#------------ここからEasingの計算-----------------
if @stopping
if @vector > 0
@vector = -1
if @currentFrame < @acSpeedArray.length
val = @acSpeedArray[@currentFrame]
for v, i in @deSpeedArray
if val >= v
@currentFrame = i
break
else
@currentFrame = 0
@currentFrame = @deSpeedArray.length - 1 if @currentFrame >= @deSpeedArray.length
@nowSpeed = @deSpeedArray[@currentFrame]
if @nowSpeed == 0
@vector = 1
@nowSpeed = 0
@currentFrame = 0
@stopping = false
@drawLoopStop()
return
else
if @vector < 0
@vector = 1
if @currentFrame < @deSpeedArray.length
val = @deSpeedArray[@currentFrame]
for v, i in @acSpeedArray
if val <= v
@currentFrame = i
break
else
@currentFrame = @acSpeedArray.length - 1
@currentFrame = @acSpeedArray.length - 1 if @currentFrame >= @acSpeedArray.length
@nowSpeed = @acSpeedArray[@currentFrame]
@currentFrame++
#------------ここまでEasingの計算-----------------
#位置の計算
for i in [0...@canvasPointArray.length]
@canvasPointArray[i].x -= @nowSpeed
#計算後の位置ではみ出ているものは後ろの位置へ移動し、描画
for i in [0...@canvasPointArray.length]
if @canvasPointArray[i].x <= -(@canvasPanelWidth)
if i is 0
@canvasPointArray[i].x = @canvasPointArray[@canvasPointArray.length-1].x + @canvasPanelWidth
#console.log('before panel = ' + @canvasPointArray[@canvasPointArray.length-1][0])
else
@canvasPointArray[i].x = @canvasPointArray[i-1].x + @canvasPanelWidth
#console.log('before panel = ' + @canvasPointArray[i-1][0])
#console.log('this panel = ' + @canvasPointArray[i][0])
if @canvasPointArray[i].x > -(@canvasPanelWidth) and @canvasPointArray[i].x < @canvas.width
@ctx.drawImage(
@imgPointArray[i].img
@imgPointArray[i].x
@imgPointArray[i].y
@options.sceneWidth
@options.sceneHeight
@canvasPointArray[i].x
@canvasPointArray[i].y
@canvasPanelWidth
@canvas.height
)
return
#描画ループを加速
drawLoopSpeedUp: =>
#console.log('Loop Start + Speed Up')
@stopping = false
if !@requestId
@_drawLoop()
return
#描画ループを減速
drawLoopSpeedDown: =>
#console.log('Loop Start + Speed Down')
@stopping = true
return
#描画ループをスタート(加減速はしない)
drawLoopStart: =>
#console.log('Loop Start')
if !@requestId
@_drawLoop()
return
#描画ループをストップ
drawLoopStop: =>
#console.log('Loop Stop')
if @requestId
@cancelAnimationFrame(@requestId)
@requestId = null
return
#ループ関数
_drawLoop: =>
@requestId = @requestAnimationFrame(@_drawLoop)
@_drawSpriteImg()
return
#canvasの初期化
spriteClear: =>
#console.log('sprite clear')
@isDrawed = true
@ctx.clearRect(0, 0, @canvas.width, @canvas.height)
return
#fpsの変更
changeFps: (_changeFps) =>
if _changeFps isnt @options.fps
#console.log('change Fps = ' + _changeFps)
@options.fps = _changeFps
@fpsInterval = 1000 / @options.fps
@_calculateSpeed()
return
$.fn.CanvasFilmMovie = (options) ->
@each (i, el) ->
$el = $(el)
FilmMovie = new CanvasFilmMovie $el, options
$el.data 'CanvasFilmMovie', FilmMovie | true | ###
CanvasFilmMovie
Copyright(c) 2015 SHIFTBRAIN - PI:NAME:<NAME>END_PI
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
###
class CanvasFilmMovie
defaults :
acTime : 3 #フィルムの最大速度到達時間
acEasing : $.easing.easeInSine #加速のEasing
deTime : 2 #フィルムの停止到達時間
deEasing : $.easing.easeOutSine #減速のEasing
offsetValue : 1 #MAX時の移動方向・速度(正は右、負は逆)
targetImgArray : [] #使用画像が格納された配列
sceneWidth : false #読み込んだ画像の1シーンの横幅
sceneHeight : false #読み込んだ画像の1シーンの縦幅
fps : 30 #1秒あたりのコマ数
constructor : (_$targetParent, options) ->
#optionのマージ
@options = $.extend {}, @defaults, options
@imgWidth = null #読み込んだ画像の全体横幅
@imgHeight = null #読み込んだ画像の全体縦幅
@canvasPointArray = [] #canvs上の各パネル座標を格納する配列
@imgPointArray = [] #読み込んだ画像の各シーンの座標を格納する配列
@canvasPanelWidth = null #canvasのパネルの横幅
@canvasXPanelNum = null #canvasの横のパネル数
@imgPanelresizedWidth = null #canvasの高さに合わせて画像の1シーンを拡縮した際の横幅
@imgXPanelNum = null #読み込んだ画像の横のシーン数
@imgYPanelNum = null #読み込んだ画像の縦のシーン数
@acSpeedArray = [] #フレーム分割した加速度を格納する配列
@deSpeedArray = [] #フレーム分割した減速度を格納する配列
@currentFrame = 0 #現在のフレーム位置
@vector = 1 #反転のフラグ
@nowSpeed = 0 #現在の速度
@stopping = false #減速中かどうかのフラグ
@isDrawed = false #パネルが埋まっているかどうかのフラグ
@$targetParent = _$targetParent #canvasの親になる生成先
@canvas = null
@ctx = null
@requestId = null #RAFに使用するID
@setTimerId = null #Timeoutに使用するID
@fpsInterval = 1000 / @options.fps #RAFのfps調整に使用するフレーム間隔の変数
@timeLog = Date.now() #RAFのfps調整に使用する変数
#RAFの宣言(fallback付)
@requestAnimationFrame =
(window.requestAnimationFrame and window.requestAnimationFrame.bind(window)) or
(window.webkitRequestAnimationFrame and window.webkitRequestAnimationFrame.bind(window)) or
(window.mozRequestAnimationFrame and window.mozRequestAnimationFrame.bind(window)) or
(window.oRequestAnimationFrame and window.oRequestAnimationFrame.bind(window)) or
(window.msRequestAnimationFrame and window.msRequestAnimationFrame.bind(window)) or
(callback,element) ->
@setTimerId = window.setTimeout(callback, 1000 / 60)
#キャンセル用RAFの宣言(fallback付)
@cancelAnimationFrame =
(window.cancelAnimationFrame and window.cancelAnimationFrame.bind(window)) or
(window.webkitCancelAnimationFrame and window.webkitCancelAnimationFrame.bind(window)) or
(window.mozCancelAnimationFrame and window.mozCancelAnimationFrame.bind(window)) or
(window.oCancelAnimationFrame and window.oCancelAnimationFrame.bind(window)) or
(window.msCancelAnimationFrame and window.msCancelAnimationFrame.bind(window)) or
(callback,element) ->
window.clearTimeout(@setTimerId)
#初期処理
@_init()
_init: ->
#渡されたImgArrayが空、中のImgがロードされてない、中のImgがそもそも渡されていないとエラー
if @options.targetImgArray.length is 0
console.error('Image Array is empty.')
return false
for i in [0...@options.targetImgArray.length]
if @options.targetImgArray[i].width is 0 or !@options.targetImgArray[i]
console.error('Image not loaded.')
return false
#オプションにシーンの横幅と縦幅がないとエラー
if @options.sceneWidth is false or @options.sceneHeight is false
console.error('Input Scene Size.')
return false
#canvasの生成、contextの宣言
@$targetParent.append('<canvas class="canvas-film-sprite"></canvas>')
@canvas = @$targetParent.find('.canvas-film-sprite')[0]
@ctx = @canvas.getContext("2d")
@_canvasResize()
#liquid対応のリサイズイベント登録
$(window).on('resize', @_debounce(
()=> @_canvasResize()
,300))
return
#canvasのリサイズ関数
_canvasResize: =>
parentWidth = @$targetParent.width()
parentHeight = @$targetParent.height()
$(@canvas).attr({'width':parentWidth,'height':parentHeight})
#座標の計算
@_createCuttPoint(@options.targetImgObject)
#isDrawedなら最初から再描画、タイマーが回ってなければとりあえず再描画
if @isDrawed
if @nowSpeed >= @canvasPanelWidth
@nowSpeed = @canvasPanelWidth
if !@requestId
@_setSpriteImg()
@_calculateSpeed()
return
#実行回数の間引き
_debounce: (func, threshold, execAsap) ->
timeout = null
(args...) ->
obj = this
delayed = ->
func.apply(obj, args) unless execAsap
timeout = null
return
if timeout
clearTimeout(timeout)
else if (execAsap)
func.apply(obj, args)
timeout = setTimeout delayed, threshold || 100
#スピードフレームの計算
_calculateSpeed: ->
#フレーム分割した加速度の配列作成
@acSpeedArray = []
#(fps*到達までの時間)で全体フレーム数を算出
max = @options.fps * @options.acTime - 1
for i in [0..max]
@acSpeedArray[i] = @options.acEasing 0, i, 0, @canvasPanelWidth - @options.offsetValue, max
#フレーム分割した減速度の配列作成
@deSpeedArray = []
#(fps*到達までの時間)で全体フレーム数を算出
max = @options.fps * @options.deTime - 1
for i in [0..max]
@deSpeedArray[i] = @options.deEasing 0, max - i, 0, @canvasPanelWidth - @options.offsetValue, max
#console.log @acSpeedArray
#console.log @deSpeedArray
return
#各種幅や座標の計算
_createCuttPoint: ->
canvasWidth = @canvas.width
canvasHeight = @canvas.height
#console.log('canvas width = ' + canvasWidth)
#console.log('canvas height = ' + canvasHeight)
@canvasPanelWidth = @imgPanelresizedWidth = Math.ceil(@options.sceneWidth*(canvasHeight / @options.sceneHeight))
@canvasXPanelNum = Math.ceil(canvasWidth / @imgPanelresizedWidth)
#console.log('canvas scene width = ' + @canvasPanelWidth)
#console.log('canvas scene height = ' + canvasHeight)
#targetImgArrayからイメージの座標を結合して一つの配列を作る
if @imgPointArray.length is 0
for i in [0...@options.targetImgArray.length]
partsPointArray = @_imgPointPush(@options.targetImgArray[i])
for i in [0...partsPointArray.length]
@imgPointArray.push(partsPointArray[i])
#console.log(@imgPointArray)
@canvasPointArray = @_canvasPointPush()
#console.log('canvasの横一列パネル数(はみ出てるのも含め) = ' + @canvasPointArray.length)
#console.log('動画のシーン画像の数 = ' + @imgPointArray.length)
return
#canvas座標配列を返す関数
_canvasPointPush: ->
pointArray = []
for i in [0...@imgPointArray.length]
pointArray.push({x:i * @canvasPanelWidth, y:0})
#console.log(pointArray)
return pointArray
#シーン座標配列を返す関数
_imgPointPush: (targetImg)->
imgWidth = targetImg.width
imgHeight = targetImg.height
imgXPanelNum = Math.ceil(imgWidth / @options.sceneWidth)
imgYPanelNum = Math.ceil(imgHeight / @options.sceneHeight)
pointArray = []
nowPoint = 0
for i in [0...imgYPanelNum]
for i2 in [0...imgXPanelNum]
pointArray.push({x:i2 * @options.sceneWidth, y:nowPoint, img:targetImg})
if i2 is imgXPanelNum-1
nowPoint += @options.sceneHeight
#console.log(pointArray)
return pointArray
#スプライトの描画関数
_setSpriteImg: ->
#console.log('Single draw')
@isDrawed = true
for i in [0...@canvasPointArray.length]
@ctx.drawImage(
@imgPointArray[i].img
@imgPointArray[i].x
@imgPointArray[i].y
@options.sceneWidth
@options.sceneHeight
@canvasPointArray[i].x
@canvasPointArray[i].y
@canvasPanelWidth
@canvas.height
)
return
#スプライトの描画関数
_drawSpriteImg: ->
#RAFのフレーム調整
now = Date.now()
elapsed = now - @timeLog
if elapsed > @fpsInterval
@timeLog = now - (elapsed % @fpsInterval)
#------------ここからEasingの計算-----------------
if @stopping
if @vector > 0
@vector = -1
if @currentFrame < @acSpeedArray.length
val = @acSpeedArray[@currentFrame]
for v, i in @deSpeedArray
if val >= v
@currentFrame = i
break
else
@currentFrame = 0
@currentFrame = @deSpeedArray.length - 1 if @currentFrame >= @deSpeedArray.length
@nowSpeed = @deSpeedArray[@currentFrame]
if @nowSpeed == 0
@vector = 1
@nowSpeed = 0
@currentFrame = 0
@stopping = false
@drawLoopStop()
return
else
if @vector < 0
@vector = 1
if @currentFrame < @deSpeedArray.length
val = @deSpeedArray[@currentFrame]
for v, i in @acSpeedArray
if val <= v
@currentFrame = i
break
else
@currentFrame = @acSpeedArray.length - 1
@currentFrame = @acSpeedArray.length - 1 if @currentFrame >= @acSpeedArray.length
@nowSpeed = @acSpeedArray[@currentFrame]
@currentFrame++
#------------ここまでEasingの計算-----------------
#位置の計算
for i in [0...@canvasPointArray.length]
@canvasPointArray[i].x -= @nowSpeed
#計算後の位置ではみ出ているものは後ろの位置へ移動し、描画
for i in [0...@canvasPointArray.length]
if @canvasPointArray[i].x <= -(@canvasPanelWidth)
if i is 0
@canvasPointArray[i].x = @canvasPointArray[@canvasPointArray.length-1].x + @canvasPanelWidth
#console.log('before panel = ' + @canvasPointArray[@canvasPointArray.length-1][0])
else
@canvasPointArray[i].x = @canvasPointArray[i-1].x + @canvasPanelWidth
#console.log('before panel = ' + @canvasPointArray[i-1][0])
#console.log('this panel = ' + @canvasPointArray[i][0])
if @canvasPointArray[i].x > -(@canvasPanelWidth) and @canvasPointArray[i].x < @canvas.width
@ctx.drawImage(
@imgPointArray[i].img
@imgPointArray[i].x
@imgPointArray[i].y
@options.sceneWidth
@options.sceneHeight
@canvasPointArray[i].x
@canvasPointArray[i].y
@canvasPanelWidth
@canvas.height
)
return
#描画ループを加速
drawLoopSpeedUp: =>
#console.log('Loop Start + Speed Up')
@stopping = false
if !@requestId
@_drawLoop()
return
#描画ループを減速
drawLoopSpeedDown: =>
#console.log('Loop Start + Speed Down')
@stopping = true
return
#描画ループをスタート(加減速はしない)
drawLoopStart: =>
#console.log('Loop Start')
if !@requestId
@_drawLoop()
return
#描画ループをストップ
drawLoopStop: =>
#console.log('Loop Stop')
if @requestId
@cancelAnimationFrame(@requestId)
@requestId = null
return
#ループ関数
_drawLoop: =>
@requestId = @requestAnimationFrame(@_drawLoop)
@_drawSpriteImg()
return
#canvasの初期化
spriteClear: =>
#console.log('sprite clear')
@isDrawed = true
@ctx.clearRect(0, 0, @canvas.width, @canvas.height)
return
#fpsの変更
changeFps: (_changeFps) =>
if _changeFps isnt @options.fps
#console.log('change Fps = ' + _changeFps)
@options.fps = _changeFps
@fpsInterval = 1000 / @options.fps
@_calculateSpeed()
return
$.fn.CanvasFilmMovie = (options) ->
@each (i, el) ->
$el = $(el)
FilmMovie = new CanvasFilmMovie $el, options
$el.data 'CanvasFilmMovie', FilmMovie |
[
{
"context": "# Copyright (C) 2017 Alexandre Pielucha\n#\n# Permission to use, copy, modify, and/or distr",
"end": 39,
"score": 0.9998427033424377,
"start": 21,
"tag": "NAME",
"value": "Alexandre Pielucha"
},
{
"context": "rts =\n # IP Address of the server\n ip_address: '127.0.0.1'\n # Port listened by the server\n port: 8080\n #",
"end": 854,
"score": 0.9997584223747253,
"start": 845,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | src/app/http/server.coffee | Riemannn/ast_lab | 0 | # Copyright (C) 2017 Alexandre Pielucha
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
# OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
http = require 'http'
module.exports =
# IP Address of the server
ip_address: '127.0.0.1'
# Port listened by the server
port: 8080
# Server's logic
logic: (req, res) ->
res.writeHead 200,
'Content-Type': 'text/plain'
res.write 'Hello World!'
res.end()
# Set IP address & port
setHost: (ip, po) ->
this.ip_address = ip
this.port = po
# Set server's logic
setLogic: (lo) ->
this.logic = lo
# Starts the server
start: () ->
http.createServer(this.logic).listen(this.port, this.ip_adress)
# Returns an HTTP response containing a code and a message.
write: (http_code, mime, message, res) ->
res.writeHead http_code,
'Content-Type': mime
res.write message
res.end()
| 95412 | # Copyright (C) 2017 <NAME>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
# OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
http = require 'http'
module.exports =
# IP Address of the server
ip_address: '127.0.0.1'
# Port listened by the server
port: 8080
# Server's logic
logic: (req, res) ->
res.writeHead 200,
'Content-Type': 'text/plain'
res.write 'Hello World!'
res.end()
# Set IP address & port
setHost: (ip, po) ->
this.ip_address = ip
this.port = po
# Set server's logic
setLogic: (lo) ->
this.logic = lo
# Starts the server
start: () ->
http.createServer(this.logic).listen(this.port, this.ip_adress)
# Returns an HTTP response containing a code and a message.
write: (http_code, mime, message, res) ->
res.writeHead http_code,
'Content-Type': mime
res.write message
res.end()
| true | # Copyright (C) 2017 PI:NAME:<NAME>END_PI
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
# OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
http = require 'http'
module.exports =
# IP Address of the server
ip_address: '127.0.0.1'
# Port listened by the server
port: 8080
# Server's logic
logic: (req, res) ->
res.writeHead 200,
'Content-Type': 'text/plain'
res.write 'Hello World!'
res.end()
# Set IP address & port
setHost: (ip, po) ->
this.ip_address = ip
this.port = po
# Set server's logic
setLogic: (lo) ->
this.logic = lo
# Starts the server
start: () ->
http.createServer(this.logic).listen(this.port, this.ip_adress)
# Returns an HTTP response containing a code and a message.
write: (http_code, mime, message, res) ->
res.writeHead http_code,
'Content-Type': mime
res.write message
res.end()
|
[
{
"context": "module.exports = new Users(\n [\n {\n _id: \"student0\"\n name: \"Student Zero\"\n }\n \n {\n ",
"end": 95,
"score": 0.879551887512207,
"start": 87,
"tag": "USERNAME",
"value": "student0"
},
{
"context": "ers(\n [\n {\n _id: \"student0\"\n name: \"Student Zero\"\n }\n \n {\n _id: \"student1\"\n nam",
"end": 122,
"score": 0.9873814582824707,
"start": 110,
"tag": "NAME",
"value": "Student Zero"
},
{
"context": "name: \"Student Zero\"\n }\n \n {\n _id: \"student1\"\n name: \"Student One\"\n }\n \n {\n ",
"end": 161,
"score": 0.7761268615722656,
"start": 153,
"tag": "USERNAME",
"value": "student1"
},
{
"context": " }\n \n {\n _id: \"student1\"\n name: \"Student One\"\n }\n \n {\n _id: \"student2\"\n nam",
"end": 187,
"score": 0.9829088449478149,
"start": 176,
"tag": "NAME",
"value": "Student One"
},
{
"context": " name: \"Student One\"\n }\n \n {\n _id: \"student2\"\n name: \"Student Two\"\n }\n \n {\n ",
"end": 226,
"score": 0.7497422099113464,
"start": 218,
"tag": "USERNAME",
"value": "student2"
},
{
"context": " }\n \n {\n _id: \"student2\"\n name: \"Student Two\"\n }\n \n {\n _id: \"student3\"\n nam",
"end": 252,
"score": 0.9898762702941895,
"start": 241,
"tag": "NAME",
"value": "Student Two"
},
{
"context": " name: \"Student Two\"\n }\n \n {\n _id: \"student3\"\n name: \"Student Three\"\n }\n ]\n)\n",
"end": 291,
"score": 0.7522739171981812,
"start": 283,
"tag": "USERNAME",
"value": "student3"
},
{
"context": " }\n \n {\n _id: \"student3\"\n name: \"Student Three\"\n }\n ]\n)\n",
"end": 319,
"score": 0.9900667071342468,
"start": 306,
"tag": "NAME",
"value": "Student Three"
}
] | test/app/fixtures/students.coffee | cihatislamdede/codecombat | 4,858 | Users = require 'collections/Users'
module.exports = new Users(
[
{
_id: "student0"
name: "Student Zero"
}
{
_id: "student1"
name: "Student One"
}
{
_id: "student2"
name: "Student Two"
}
{
_id: "student3"
name: "Student Three"
}
]
)
| 28575 | Users = require 'collections/Users'
module.exports = new Users(
[
{
_id: "student0"
name: "<NAME>"
}
{
_id: "student1"
name: "<NAME>"
}
{
_id: "student2"
name: "<NAME>"
}
{
_id: "student3"
name: "<NAME>"
}
]
)
| true | Users = require 'collections/Users'
module.exports = new Users(
[
{
_id: "student0"
name: "PI:NAME:<NAME>END_PI"
}
{
_id: "student1"
name: "PI:NAME:<NAME>END_PI"
}
{
_id: "student2"
name: "PI:NAME:<NAME>END_PI"
}
{
_id: "student3"
name: "PI:NAME:<NAME>END_PI"
}
]
)
|
[
{
"context": "enario names\n nodeMap = {\n \"1\":\"533de20aa498867c56c6cba5\"\n \"2\":\"533de20aa498867c56c6cba7\"\n ",
"end": 1230,
"score": 0.9966341257095337,
"start": 1206,
"tag": "KEY",
"value": "533de20aa498867c56c6cba5"
},
{
"context": " \"1\":\"533de20aa498867c56c6cba5\"\n \"2\":\"533de20aa498867c56c6cba7\"\n \"3\":\"533de20aa498867c56c6cba9\"\n ",
"end": 1273,
"score": 0.9966866374015808,
"start": 1249,
"tag": "KEY",
"value": "533de20aa498867c56c6cba7"
},
{
"context": " \"2\":\"533de20aa498867c56c6cba7\"\n \"3\":\"533de20aa498867c56c6cba9\"\n \"4\":\"533de20aa498867c56c6cbab\"\n ",
"end": 1316,
"score": 0.9952616691589355,
"start": 1292,
"tag": "KEY",
"value": "533de20aa498867c56c6cba9"
},
{
"context": " \"3\":\"533de20aa498867c56c6cba9\"\n \"4\":\"533de20aa498867c56c6cbab\"\n \"5\":\"533de20aa498867c56c6cbad\"\n ",
"end": 1359,
"score": 0.9932626485824585,
"start": 1335,
"tag": "KEY",
"value": "533de20aa498867c56c6cbab"
},
{
"context": " \"4\":\"533de20aa498867c56c6cbab\"\n \"5\":\"533de20aa498867c56c6cbad\"\n \"6\":\"533de20aa498867c56c6cbaf\"\n ",
"end": 1402,
"score": 0.9942770004272461,
"start": 1378,
"tag": "KEY",
"value": "533de20aa498867c56c6cbad"
},
{
"context": " \"5\":\"533de20aa498867c56c6cbad\"\n \"6\":\"533de20aa498867c56c6cbaf\"\n \"7\":\"533de20aa498867c56c6cbb1\"\n ",
"end": 1445,
"score": 0.9947351217269897,
"start": 1421,
"tag": "KEY",
"value": "533de20aa498867c56c6cbaf"
},
{
"context": " \"6\":\"533de20aa498867c56c6cbaf\"\n \"7\":\"533de20aa498867c56c6cbb1\"\n \"8\":\"533de20aa498867c56c6cbb3\"\n ",
"end": 1488,
"score": 0.9954379200935364,
"start": 1464,
"tag": "KEY",
"value": "533de20aa498867c56c6cbb1"
}
] | scripts/habitatTab.coffee | mcclintock-lab/training-reports-v2 | 0 | ReportTab = require 'reportTab'
templates = require '../templates/templates.js'
class HabitatTab extends ReportTab
name: 'Habitat'
className: 'habitat'
template: templates.habitat
dependencies: [
'BarbudaHabitat'
'MarxanAnalysis'
]
paramName: 'Habitats'
timeout: 120000
heading: "Habitat Representation"
render: () ->
depName = @dependencies[0]
data = @recordSet(depName, @paramName).toArray()
context =
sketch: @model.forTemplate()
sketchClass: @sketchClass.forTemplate()
attributes: @model.getAttributes()
admin: @project.isAdmin window.user
habitats: data
heading: @heading
marxanAnalyses: _.map(@recordSet("MarxanAnalysis", "MarxanAnalysis")
.toArray(), (f) -> f.NAME)
@$el.html @template.render(context, templates)
@enableLayerTogglers(@$el)
@$('.chosen').chosen({disable_search_threshold: 10, width:'400px'})
@$('.chosen').change () =>
_.defer @renderMarxanAnalysis
@renderMarxanAnalysis()
renderMarxanAnalysis: () =>
if window.d3
name = @$('.chosen').val()
try
#hook up the checkboxes for marxan scenario names
nodeMap = {
"1":"533de20aa498867c56c6cba5"
"2":"533de20aa498867c56c6cba7"
"3":"533de20aa498867c56c6cba9"
"4":"533de20aa498867c56c6cbab"
"5":"533de20aa498867c56c6cbad"
"6":"533de20aa498867c56c6cbaf"
"7":"533de20aa498867c56c6cbb1"
"8":"533de20aa498867c56c6cbb3"
}
scenarioName = name.substring(0,1)
nodeId = nodeMap[scenarioName]
toc = window.app.getToc()
view = toc.getChildViewById(nodeId)
node = view.model
isVisible = node.get('visible')
@$('.marxan-node').attr('data-toggle-node', nodeId)
@$('.marxan-node').data('tocItem', view)
@$('.marxan-node').attr('checked', isVisible)
@$('.marxan-node').attr('data-visible', isVisible)
@$('.marxan-node').text('show \'Scenario '+scenarioName+'\' marxan layer')
catch e
console.log("error", e)
records = @recordSet("MarxanAnalysis", "MarxanAnalysis").toArray()
quantile_range = {"Q0":"very low", "Q20": "low","Q40": "mid","Q60": "high","Q80": "very high"}
data = _.find records, (record) -> record.NAME is name
histo = data.HISTO.slice(1, data.HISTO.length - 1).split(/\s/)
histo = _.filter histo, (s) -> s.length > 0
histo = _.map histo, (val) ->
parseInt(val)
quantiles = _.filter(_.keys(data), (key) -> key.indexOf('Q') is 0)
for q, i in quantiles
if parseFloat(data[q]) > parseFloat(data.SCORE) or i is quantiles.length - 1
max_q = quantiles[i]
min_q = quantiles[i - 1] or "Q0" # quantiles[i]
quantile_desc = quantile_range[min_q]
break
@$('.scenarioResults').html """
<a href="http://www.uq.edu.au/marxan/" target="_blank" >Marxan</a> is conservation planning software that provides decision support for a range of conservation planning problems.
In this analysis, the goal is to maximize the amount of habitat conserved. The score for a 200 square meter planning unit is the number of times it is selected in 100 runs,
with higher scores indicating greater conservation value. The average Marxan score for this zone is <strong>#{data.SCORE}</strong>, placing it in
the <strong>#{quantile_desc}</strong> quantile range <strong>(#{min_q.replace('Q', '')}% - #{max_q.replace('Q', '')}%)</strong>
for this region. The graph below shows the distribution of scores for all planning units within this project.
"""
@$('.scenarioDescription').html data.MARX_DESC
domain = _.map quantiles, (q) -> data[q]
domain.push 100
domain.unshift 0
color = d3.scale.linear()
.domain(domain)
.range(["#47ae43", "#6c0", "#ee0", "#eb4", "#ecbb89", "#eeaba0"].reverse())
quantiles = _.map quantiles, (key) ->
max = parseFloat(data[key])
min = parseFloat(data[quantiles[_.indexOf(quantiles, key) - 1]] or 0)
{
range: "#{parseInt(key.replace('Q', '')) - 20}-#{key.replace('Q', '')}%"
name: key
start: min
end: max
bg: color((max + min) / 2)
}
@$('.viz').html('')
el = @$('.viz')[0]
x = d3.scale.linear()
.domain([0, 100])
.range([0, 400])
# Histogram
margin =
top: 5
right: 20
bottom: 30
left: 45
width = 400 - margin.left - margin.right
height = 300 - margin.top - margin.bottom
x = d3.scale.linear()
.domain([0, 100])
.range([0, width])
y = d3.scale.linear()
.range([height, 0])
.domain([0, d3.max(histo)])
xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
yAxis = d3.svg.axis()
.scale(y)
.orient("left")
svg = d3.select(@$('.viz')[0]).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(#{margin.left}, #{margin.top})")
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0,#{height})")
.call(xAxis)
.append("text")
.attr("x", width / 2)
.attr("dy", "3em")
.style("text-anchor", "middle")
.text("Score")
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Number of Planning Units")
svg.selectAll(".bar")
.data(histo)
.enter().append("rect")
.attr("class", "bar")
.attr("x", (d, i) -> x(i))
.attr("width", (width / 100))
.attr("y", (d) -> y(d))
.attr("height", (d) -> height - y(d))
.style 'fill', (d, i) ->
q = _.find quantiles, (q) ->
i >= q.start and i <= q.end
q?.bg or "steelblue"
svg.selectAll(".score")
.data([Math.round(data.SCORE)])
.enter().append("text")
.attr("class", "score")
.attr("x", (d) -> (x(d) - 8 )+ 'px')
.attr("y", (d) -> (y(histo[d]) - 10) + 'px')
.text("▼")
svg.selectAll(".scoreText")
.data([Math.round(data.SCORE)])
.enter().append("text")
.attr("class", "scoreText")
.attr("x", (d) -> (x(d) - 6 )+ 'px')
.attr("y", (d) -> (y(histo[d]) - 30) + 'px')
.text((d) -> d)
@$('.viz').append '<div class="legends"></div>'
for quantile in quantiles
@$('.viz .legends').append """
<div class="legend"><span style="background-color:#{quantile.bg};"> </span>#{quantile.range}</div>
"""
@$('.viz').append '<br style="clear:both;">'
module.exports = HabitatTab | 15053 | ReportTab = require 'reportTab'
templates = require '../templates/templates.js'
class HabitatTab extends ReportTab
name: 'Habitat'
className: 'habitat'
template: templates.habitat
dependencies: [
'BarbudaHabitat'
'MarxanAnalysis'
]
paramName: 'Habitats'
timeout: 120000
heading: "Habitat Representation"
render: () ->
depName = @dependencies[0]
data = @recordSet(depName, @paramName).toArray()
context =
sketch: @model.forTemplate()
sketchClass: @sketchClass.forTemplate()
attributes: @model.getAttributes()
admin: @project.isAdmin window.user
habitats: data
heading: @heading
marxanAnalyses: _.map(@recordSet("MarxanAnalysis", "MarxanAnalysis")
.toArray(), (f) -> f.NAME)
@$el.html @template.render(context, templates)
@enableLayerTogglers(@$el)
@$('.chosen').chosen({disable_search_threshold: 10, width:'400px'})
@$('.chosen').change () =>
_.defer @renderMarxanAnalysis
@renderMarxanAnalysis()
renderMarxanAnalysis: () =>
if window.d3
name = @$('.chosen').val()
try
#hook up the checkboxes for marxan scenario names
nodeMap = {
"1":"<KEY>"
"2":"<KEY>"
"3":"<KEY>"
"4":"<KEY>"
"5":"<KEY>"
"6":"<KEY>"
"7":"<KEY>"
"8":"533de20aa498867c56c6cbb3"
}
scenarioName = name.substring(0,1)
nodeId = nodeMap[scenarioName]
toc = window.app.getToc()
view = toc.getChildViewById(nodeId)
node = view.model
isVisible = node.get('visible')
@$('.marxan-node').attr('data-toggle-node', nodeId)
@$('.marxan-node').data('tocItem', view)
@$('.marxan-node').attr('checked', isVisible)
@$('.marxan-node').attr('data-visible', isVisible)
@$('.marxan-node').text('show \'Scenario '+scenarioName+'\' marxan layer')
catch e
console.log("error", e)
records = @recordSet("MarxanAnalysis", "MarxanAnalysis").toArray()
quantile_range = {"Q0":"very low", "Q20": "low","Q40": "mid","Q60": "high","Q80": "very high"}
data = _.find records, (record) -> record.NAME is name
histo = data.HISTO.slice(1, data.HISTO.length - 1).split(/\s/)
histo = _.filter histo, (s) -> s.length > 0
histo = _.map histo, (val) ->
parseInt(val)
quantiles = _.filter(_.keys(data), (key) -> key.indexOf('Q') is 0)
for q, i in quantiles
if parseFloat(data[q]) > parseFloat(data.SCORE) or i is quantiles.length - 1
max_q = quantiles[i]
min_q = quantiles[i - 1] or "Q0" # quantiles[i]
quantile_desc = quantile_range[min_q]
break
@$('.scenarioResults').html """
<a href="http://www.uq.edu.au/marxan/" target="_blank" >Marxan</a> is conservation planning software that provides decision support for a range of conservation planning problems.
In this analysis, the goal is to maximize the amount of habitat conserved. The score for a 200 square meter planning unit is the number of times it is selected in 100 runs,
with higher scores indicating greater conservation value. The average Marxan score for this zone is <strong>#{data.SCORE}</strong>, placing it in
the <strong>#{quantile_desc}</strong> quantile range <strong>(#{min_q.replace('Q', '')}% - #{max_q.replace('Q', '')}%)</strong>
for this region. The graph below shows the distribution of scores for all planning units within this project.
"""
@$('.scenarioDescription').html data.MARX_DESC
domain = _.map quantiles, (q) -> data[q]
domain.push 100
domain.unshift 0
color = d3.scale.linear()
.domain(domain)
.range(["#47ae43", "#6c0", "#ee0", "#eb4", "#ecbb89", "#eeaba0"].reverse())
quantiles = _.map quantiles, (key) ->
max = parseFloat(data[key])
min = parseFloat(data[quantiles[_.indexOf(quantiles, key) - 1]] or 0)
{
range: "#{parseInt(key.replace('Q', '')) - 20}-#{key.replace('Q', '')}%"
name: key
start: min
end: max
bg: color((max + min) / 2)
}
@$('.viz').html('')
el = @$('.viz')[0]
x = d3.scale.linear()
.domain([0, 100])
.range([0, 400])
# Histogram
margin =
top: 5
right: 20
bottom: 30
left: 45
width = 400 - margin.left - margin.right
height = 300 - margin.top - margin.bottom
x = d3.scale.linear()
.domain([0, 100])
.range([0, width])
y = d3.scale.linear()
.range([height, 0])
.domain([0, d3.max(histo)])
xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
yAxis = d3.svg.axis()
.scale(y)
.orient("left")
svg = d3.select(@$('.viz')[0]).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(#{margin.left}, #{margin.top})")
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0,#{height})")
.call(xAxis)
.append("text")
.attr("x", width / 2)
.attr("dy", "3em")
.style("text-anchor", "middle")
.text("Score")
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Number of Planning Units")
svg.selectAll(".bar")
.data(histo)
.enter().append("rect")
.attr("class", "bar")
.attr("x", (d, i) -> x(i))
.attr("width", (width / 100))
.attr("y", (d) -> y(d))
.attr("height", (d) -> height - y(d))
.style 'fill', (d, i) ->
q = _.find quantiles, (q) ->
i >= q.start and i <= q.end
q?.bg or "steelblue"
svg.selectAll(".score")
.data([Math.round(data.SCORE)])
.enter().append("text")
.attr("class", "score")
.attr("x", (d) -> (x(d) - 8 )+ 'px')
.attr("y", (d) -> (y(histo[d]) - 10) + 'px')
.text("▼")
svg.selectAll(".scoreText")
.data([Math.round(data.SCORE)])
.enter().append("text")
.attr("class", "scoreText")
.attr("x", (d) -> (x(d) - 6 )+ 'px')
.attr("y", (d) -> (y(histo[d]) - 30) + 'px')
.text((d) -> d)
@$('.viz').append '<div class="legends"></div>'
for quantile in quantiles
@$('.viz .legends').append """
<div class="legend"><span style="background-color:#{quantile.bg};"> </span>#{quantile.range}</div>
"""
@$('.viz').append '<br style="clear:both;">'
module.exports = HabitatTab | true | ReportTab = require 'reportTab'
templates = require '../templates/templates.js'
class HabitatTab extends ReportTab
name: 'Habitat'
className: 'habitat'
template: templates.habitat
dependencies: [
'BarbudaHabitat'
'MarxanAnalysis'
]
paramName: 'Habitats'
timeout: 120000
heading: "Habitat Representation"
render: () ->
depName = @dependencies[0]
data = @recordSet(depName, @paramName).toArray()
context =
sketch: @model.forTemplate()
sketchClass: @sketchClass.forTemplate()
attributes: @model.getAttributes()
admin: @project.isAdmin window.user
habitats: data
heading: @heading
marxanAnalyses: _.map(@recordSet("MarxanAnalysis", "MarxanAnalysis")
.toArray(), (f) -> f.NAME)
@$el.html @template.render(context, templates)
@enableLayerTogglers(@$el)
@$('.chosen').chosen({disable_search_threshold: 10, width:'400px'})
@$('.chosen').change () =>
_.defer @renderMarxanAnalysis
@renderMarxanAnalysis()
renderMarxanAnalysis: () =>
if window.d3
name = @$('.chosen').val()
try
#hook up the checkboxes for marxan scenario names
nodeMap = {
"1":"PI:KEY:<KEY>END_PI"
"2":"PI:KEY:<KEY>END_PI"
"3":"PI:KEY:<KEY>END_PI"
"4":"PI:KEY:<KEY>END_PI"
"5":"PI:KEY:<KEY>END_PI"
"6":"PI:KEY:<KEY>END_PI"
"7":"PI:KEY:<KEY>END_PI"
"8":"533de20aa498867c56c6cbb3"
}
scenarioName = name.substring(0,1)
nodeId = nodeMap[scenarioName]
toc = window.app.getToc()
view = toc.getChildViewById(nodeId)
node = view.model
isVisible = node.get('visible')
@$('.marxan-node').attr('data-toggle-node', nodeId)
@$('.marxan-node').data('tocItem', view)
@$('.marxan-node').attr('checked', isVisible)
@$('.marxan-node').attr('data-visible', isVisible)
@$('.marxan-node').text('show \'Scenario '+scenarioName+'\' marxan layer')
catch e
console.log("error", e)
records = @recordSet("MarxanAnalysis", "MarxanAnalysis").toArray()
quantile_range = {"Q0":"very low", "Q20": "low","Q40": "mid","Q60": "high","Q80": "very high"}
data = _.find records, (record) -> record.NAME is name
histo = data.HISTO.slice(1, data.HISTO.length - 1).split(/\s/)
histo = _.filter histo, (s) -> s.length > 0
histo = _.map histo, (val) ->
parseInt(val)
quantiles = _.filter(_.keys(data), (key) -> key.indexOf('Q') is 0)
for q, i in quantiles
if parseFloat(data[q]) > parseFloat(data.SCORE) or i is quantiles.length - 1
max_q = quantiles[i]
min_q = quantiles[i - 1] or "Q0" # quantiles[i]
quantile_desc = quantile_range[min_q]
break
@$('.scenarioResults').html """
<a href="http://www.uq.edu.au/marxan/" target="_blank" >Marxan</a> is conservation planning software that provides decision support for a range of conservation planning problems.
In this analysis, the goal is to maximize the amount of habitat conserved. The score for a 200 square meter planning unit is the number of times it is selected in 100 runs,
with higher scores indicating greater conservation value. The average Marxan score for this zone is <strong>#{data.SCORE}</strong>, placing it in
the <strong>#{quantile_desc}</strong> quantile range <strong>(#{min_q.replace('Q', '')}% - #{max_q.replace('Q', '')}%)</strong>
for this region. The graph below shows the distribution of scores for all planning units within this project.
"""
@$('.scenarioDescription').html data.MARX_DESC
domain = _.map quantiles, (q) -> data[q]
domain.push 100
domain.unshift 0
color = d3.scale.linear()
.domain(domain)
.range(["#47ae43", "#6c0", "#ee0", "#eb4", "#ecbb89", "#eeaba0"].reverse())
quantiles = _.map quantiles, (key) ->
max = parseFloat(data[key])
min = parseFloat(data[quantiles[_.indexOf(quantiles, key) - 1]] or 0)
{
range: "#{parseInt(key.replace('Q', '')) - 20}-#{key.replace('Q', '')}%"
name: key
start: min
end: max
bg: color((max + min) / 2)
}
@$('.viz').html('')
el = @$('.viz')[0]
x = d3.scale.linear()
.domain([0, 100])
.range([0, 400])
# Histogram
margin =
top: 5
right: 20
bottom: 30
left: 45
width = 400 - margin.left - margin.right
height = 300 - margin.top - margin.bottom
x = d3.scale.linear()
.domain([0, 100])
.range([0, width])
y = d3.scale.linear()
.range([height, 0])
.domain([0, d3.max(histo)])
xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
yAxis = d3.svg.axis()
.scale(y)
.orient("left")
svg = d3.select(@$('.viz')[0]).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(#{margin.left}, #{margin.top})")
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0,#{height})")
.call(xAxis)
.append("text")
.attr("x", width / 2)
.attr("dy", "3em")
.style("text-anchor", "middle")
.text("Score")
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Number of Planning Units")
svg.selectAll(".bar")
.data(histo)
.enter().append("rect")
.attr("class", "bar")
.attr("x", (d, i) -> x(i))
.attr("width", (width / 100))
.attr("y", (d) -> y(d))
.attr("height", (d) -> height - y(d))
.style 'fill', (d, i) ->
q = _.find quantiles, (q) ->
i >= q.start and i <= q.end
q?.bg or "steelblue"
svg.selectAll(".score")
.data([Math.round(data.SCORE)])
.enter().append("text")
.attr("class", "score")
.attr("x", (d) -> (x(d) - 8 )+ 'px')
.attr("y", (d) -> (y(histo[d]) - 10) + 'px')
.text("▼")
svg.selectAll(".scoreText")
.data([Math.round(data.SCORE)])
.enter().append("text")
.attr("class", "scoreText")
.attr("x", (d) -> (x(d) - 6 )+ 'px')
.attr("y", (d) -> (y(histo[d]) - 30) + 'px')
.text((d) -> d)
@$('.viz').append '<div class="legends"></div>'
for quantile in quantiles
@$('.viz .legends').append """
<div class="legend"><span style="background-color:#{quantile.bg};"> </span>#{quantile.range}</div>
"""
@$('.viz').append '<br style="clear:both;">'
module.exports = HabitatTab |
[
{
"context": "new Vue(\n el: \"#demo\"\n data:\n firstName: 'none'\n lastName: 'ti'\n computed:\n fullName: ->\n",
"end": 51,
"score": 0.9990883469581604,
"start": 47,
"tag": "NAME",
"value": "none"
},
{
"context": "emo\"\n data:\n firstName: 'none'\n lastName: 'ti'\n computed:\n fullName: ->\n return this.l",
"end": 70,
"score": 0.9991362690925598,
"start": 68,
"tag": "NAME",
"value": "ti"
}
] | app/scripts/main.coffee | yoshihara/self-vue-app-base | 0 | new Vue(
el: "#demo"
data:
firstName: 'none'
lastName: 'ti'
computed:
fullName: ->
return this.lastName + ' ' + this.firstName
)
| 98417 | new Vue(
el: "#demo"
data:
firstName: '<NAME>'
lastName: '<NAME>'
computed:
fullName: ->
return this.lastName + ' ' + this.firstName
)
| true | new Vue(
el: "#demo"
data:
firstName: 'PI:NAME:<NAME>END_PI'
lastName: 'PI:NAME:<NAME>END_PI'
computed:
fullName: ->
return this.lastName + ' ' + this.firstName
)
|
[
{
"context": "3\n username: 'user'\n password: 'password'\n\n beforeEach ->\n sinon.stub mong",
"end": 1363,
"score": 0.9994503855705261,
"start": 1355,
"tag": "PASSWORD",
"value": "password"
}
] | test/server/common/dal/mongo.coffee | valueflowquality/gi-util-update | 0 | path = require 'path'
sinon = require 'sinon'
expect = require('chai').expect
proxyquire = require 'proxyquire'
dir = path.normalize __dirname + '../../../../../server'
module.exports = () ->
describe 'mongo', ->
mongo = null
mongooseStub =
connect: ->
connection:
on: ->
model: ->
Schema: ->
stubs =
'mongoose': mongooseStub
'mongoose-long': sinon.spy()
'../crudModelFactory': 'crudModelFactoryStub'
beforeEach ->
mongo = proxyquire(dir + '/common/dal/mongo', stubs)
it 'requires mongoose-long', (done) ->
expect(stubs['mongoose-long'].calledWith(mongooseStub)).to.be.true
done()
describe 'Exports', ->
it 'connect', (done) ->
expect(mongo).to.have.ownProperty 'connect'
expect(mongo.connect).to.be.a 'function'
done()
it 'crudFactory', (done) ->
expect(mongo).to.have.ownProperty 'crudFactory'
done()
it 'modelFactory', (done) ->
expect(mongo).to.have.ownProperty 'modelFactory'
done()
it 'schemaFactory', (done) ->
expect(mongo).to.have.ownProperty 'schemaFactory'
done()
describe 'connect (conf) -> void', ->
conf =
name: 'somedb'
host: 'someHost'
port: 123
username: 'user'
password: 'password'
beforeEach ->
sinon.stub mongooseStub, 'connect'
afterEach ->
mongooseStub.connect.restore()
it 'connects server given in conf.host', (done) ->
mongo.connect conf
expect(mongooseStub.connect.calledWith(conf.host)
, 'connected to wrong host').to.be.true
done()
it 'connects to db given in conf.name', (done) ->
mongo.connect conf
expect(mongooseStub.connect.calledWith(
sinon.match.any, conf.name
), 'connected to wrong db').to.be.true
done()
it 'connects to port given in conf.port', (done) ->
mongo.connect conf
expect(mongooseStub.connect.calledWith(
sinon.match.any, sinon.match.any, conf.port
), 'connected to wrong port').to.be.true
done()
it 'passes username and password as options', (done) ->
opts =
user: conf.username
pass: conf.password
mongo.connect conf
expect(mongooseStub.connect.calledWith(
sinon.match.any, sinon.match.any, sinon.match.any, opts
), 'did not pass login credentials').to.be.true
done()
it 'returns nothing', (done) ->
mongooseStub.connect.returns 'a connection object'
res = mongo.connect conf
expect(res).to.not.exist
done()
describe 'crudFactory', ->
it 'returns the common.crudModelFactory', (done) ->
expect(mongo.crudFactory).to.equal 'crudModelFactoryStub'
done()
describe 'modelFactory (def) -> model', ->
def = {}
beforeEach ->
def =
name: 'a model'
schema: 'a schema'
sinon.stub mongooseStub, 'model'
afterEach ->
mongooseStub.model.restore()
it 'configures mongoose model using def.name'
, (done) ->
mongo.modelFactory def
expect(mongooseStub.model.calledWith(def.name)
, 'mongoose model created with wrong name').to.be.true
done()
it 'configures mongoose model using def.schema'
, (done) ->
mongo.modelFactory def
expect(mongooseStub.model.calledWithExactly(def.name, def.schema)
, 'mongoose model created with wrong schema').to.be.true
done()
it 'overrides collection name with def.options.collectionName'
, (done) ->
def.options =
collectionName: 'bob'
mongo.modelFactory def
expect(mongooseStub.model.calledWithExactly(
def.name, def.schema, 'bob'
), 'mongoose model created with wrong collectionName').to.be.true
done()
it 'returns the mongoose model', (done) ->
mongooseStub.model.returns 'a mongoose model'
res = mongo.modelFactory def
expect(res).to.equal 'a mongoose model'
def.options =
collectionName: 'jack'
res2 = mongo.modelFactory def
expect(res2).to.equal 'a mongoose model'
done()
describe 'schemaFactory (def) -> schema', ->
def = {}
beforeEach ->
def =
name: 'a model'
schemaDefinition: 'a defintion'
sinon.stub mongooseStub, 'Schema'
mongooseStub.Schema.returns {a: 'mongoose schema stub'}
afterEach ->
mongooseStub.Schema.restore()
it 'returns new Schema with given definition', (done) ->
res = mongo.schemaFactory def
expect(mongooseStub.Schema.calledOnce
, 'schema not called exactly once').to.be.true
expect(mongooseStub.Schema.calledWithNew()
, 'schema not called with new').to.be.true
expect(mongooseStub.Schema.calledWithExactly(def.schemaDefinition)
, 'schema not called with correct definition').to.be.true
expect(res).to.deep.equal {a: 'mongoose schema stub'}
done()
it 'passes options to mongoose Schema constructor', (done) ->
def.options = 'schema options'
res = mongo.schemaFactory def
expect(mongooseStub.Schema.calledOnce
, 'schema not called exactly once').to.be.true
expect(mongooseStub.Schema.calledWithNew()
, 'schema not called with new').to.be.true
expect(mongooseStub.Schema.calledWithExactly(
def.schemaDefinition, def.options
), 'schema not called with correct options').to.be.true
expect(res).to.deep.equal {a: 'mongoose schema stub'}
done()
| 42663 | path = require 'path'
sinon = require 'sinon'
expect = require('chai').expect
proxyquire = require 'proxyquire'
dir = path.normalize __dirname + '../../../../../server'
module.exports = () ->
describe 'mongo', ->
mongo = null
mongooseStub =
connect: ->
connection:
on: ->
model: ->
Schema: ->
stubs =
'mongoose': mongooseStub
'mongoose-long': sinon.spy()
'../crudModelFactory': 'crudModelFactoryStub'
beforeEach ->
mongo = proxyquire(dir + '/common/dal/mongo', stubs)
it 'requires mongoose-long', (done) ->
expect(stubs['mongoose-long'].calledWith(mongooseStub)).to.be.true
done()
describe 'Exports', ->
it 'connect', (done) ->
expect(mongo).to.have.ownProperty 'connect'
expect(mongo.connect).to.be.a 'function'
done()
it 'crudFactory', (done) ->
expect(mongo).to.have.ownProperty 'crudFactory'
done()
it 'modelFactory', (done) ->
expect(mongo).to.have.ownProperty 'modelFactory'
done()
it 'schemaFactory', (done) ->
expect(mongo).to.have.ownProperty 'schemaFactory'
done()
describe 'connect (conf) -> void', ->
conf =
name: 'somedb'
host: 'someHost'
port: 123
username: 'user'
password: '<PASSWORD>'
beforeEach ->
sinon.stub mongooseStub, 'connect'
afterEach ->
mongooseStub.connect.restore()
it 'connects server given in conf.host', (done) ->
mongo.connect conf
expect(mongooseStub.connect.calledWith(conf.host)
, 'connected to wrong host').to.be.true
done()
it 'connects to db given in conf.name', (done) ->
mongo.connect conf
expect(mongooseStub.connect.calledWith(
sinon.match.any, conf.name
), 'connected to wrong db').to.be.true
done()
it 'connects to port given in conf.port', (done) ->
mongo.connect conf
expect(mongooseStub.connect.calledWith(
sinon.match.any, sinon.match.any, conf.port
), 'connected to wrong port').to.be.true
done()
it 'passes username and password as options', (done) ->
opts =
user: conf.username
pass: conf.password
mongo.connect conf
expect(mongooseStub.connect.calledWith(
sinon.match.any, sinon.match.any, sinon.match.any, opts
), 'did not pass login credentials').to.be.true
done()
it 'returns nothing', (done) ->
mongooseStub.connect.returns 'a connection object'
res = mongo.connect conf
expect(res).to.not.exist
done()
describe 'crudFactory', ->
it 'returns the common.crudModelFactory', (done) ->
expect(mongo.crudFactory).to.equal 'crudModelFactoryStub'
done()
describe 'modelFactory (def) -> model', ->
def = {}
beforeEach ->
def =
name: 'a model'
schema: 'a schema'
sinon.stub mongooseStub, 'model'
afterEach ->
mongooseStub.model.restore()
it 'configures mongoose model using def.name'
, (done) ->
mongo.modelFactory def
expect(mongooseStub.model.calledWith(def.name)
, 'mongoose model created with wrong name').to.be.true
done()
it 'configures mongoose model using def.schema'
, (done) ->
mongo.modelFactory def
expect(mongooseStub.model.calledWithExactly(def.name, def.schema)
, 'mongoose model created with wrong schema').to.be.true
done()
it 'overrides collection name with def.options.collectionName'
, (done) ->
def.options =
collectionName: 'bob'
mongo.modelFactory def
expect(mongooseStub.model.calledWithExactly(
def.name, def.schema, 'bob'
), 'mongoose model created with wrong collectionName').to.be.true
done()
it 'returns the mongoose model', (done) ->
mongooseStub.model.returns 'a mongoose model'
res = mongo.modelFactory def
expect(res).to.equal 'a mongoose model'
def.options =
collectionName: 'jack'
res2 = mongo.modelFactory def
expect(res2).to.equal 'a mongoose model'
done()
describe 'schemaFactory (def) -> schema', ->
def = {}
beforeEach ->
def =
name: 'a model'
schemaDefinition: 'a defintion'
sinon.stub mongooseStub, 'Schema'
mongooseStub.Schema.returns {a: 'mongoose schema stub'}
afterEach ->
mongooseStub.Schema.restore()
it 'returns new Schema with given definition', (done) ->
res = mongo.schemaFactory def
expect(mongooseStub.Schema.calledOnce
, 'schema not called exactly once').to.be.true
expect(mongooseStub.Schema.calledWithNew()
, 'schema not called with new').to.be.true
expect(mongooseStub.Schema.calledWithExactly(def.schemaDefinition)
, 'schema not called with correct definition').to.be.true
expect(res).to.deep.equal {a: 'mongoose schema stub'}
done()
it 'passes options to mongoose Schema constructor', (done) ->
def.options = 'schema options'
res = mongo.schemaFactory def
expect(mongooseStub.Schema.calledOnce
, 'schema not called exactly once').to.be.true
expect(mongooseStub.Schema.calledWithNew()
, 'schema not called with new').to.be.true
expect(mongooseStub.Schema.calledWithExactly(
def.schemaDefinition, def.options
), 'schema not called with correct options').to.be.true
expect(res).to.deep.equal {a: 'mongoose schema stub'}
done()
| true | path = require 'path'
sinon = require 'sinon'
expect = require('chai').expect
proxyquire = require 'proxyquire'
dir = path.normalize __dirname + '../../../../../server'
module.exports = () ->
describe 'mongo', ->
mongo = null
mongooseStub =
connect: ->
connection:
on: ->
model: ->
Schema: ->
stubs =
'mongoose': mongooseStub
'mongoose-long': sinon.spy()
'../crudModelFactory': 'crudModelFactoryStub'
beforeEach ->
mongo = proxyquire(dir + '/common/dal/mongo', stubs)
it 'requires mongoose-long', (done) ->
expect(stubs['mongoose-long'].calledWith(mongooseStub)).to.be.true
done()
describe 'Exports', ->
it 'connect', (done) ->
expect(mongo).to.have.ownProperty 'connect'
expect(mongo.connect).to.be.a 'function'
done()
it 'crudFactory', (done) ->
expect(mongo).to.have.ownProperty 'crudFactory'
done()
it 'modelFactory', (done) ->
expect(mongo).to.have.ownProperty 'modelFactory'
done()
it 'schemaFactory', (done) ->
expect(mongo).to.have.ownProperty 'schemaFactory'
done()
describe 'connect (conf) -> void', ->
conf =
name: 'somedb'
host: 'someHost'
port: 123
username: 'user'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
beforeEach ->
sinon.stub mongooseStub, 'connect'
afterEach ->
mongooseStub.connect.restore()
it 'connects server given in conf.host', (done) ->
mongo.connect conf
expect(mongooseStub.connect.calledWith(conf.host)
, 'connected to wrong host').to.be.true
done()
it 'connects to db given in conf.name', (done) ->
mongo.connect conf
expect(mongooseStub.connect.calledWith(
sinon.match.any, conf.name
), 'connected to wrong db').to.be.true
done()
it 'connects to port given in conf.port', (done) ->
mongo.connect conf
expect(mongooseStub.connect.calledWith(
sinon.match.any, sinon.match.any, conf.port
), 'connected to wrong port').to.be.true
done()
it 'passes username and password as options', (done) ->
opts =
user: conf.username
pass: conf.password
mongo.connect conf
expect(mongooseStub.connect.calledWith(
sinon.match.any, sinon.match.any, sinon.match.any, opts
), 'did not pass login credentials').to.be.true
done()
it 'returns nothing', (done) ->
mongooseStub.connect.returns 'a connection object'
res = mongo.connect conf
expect(res).to.not.exist
done()
describe 'crudFactory', ->
it 'returns the common.crudModelFactory', (done) ->
expect(mongo.crudFactory).to.equal 'crudModelFactoryStub'
done()
describe 'modelFactory (def) -> model', ->
def = {}
beforeEach ->
def =
name: 'a model'
schema: 'a schema'
sinon.stub mongooseStub, 'model'
afterEach ->
mongooseStub.model.restore()
it 'configures mongoose model using def.name'
, (done) ->
mongo.modelFactory def
expect(mongooseStub.model.calledWith(def.name)
, 'mongoose model created with wrong name').to.be.true
done()
it 'configures mongoose model using def.schema'
, (done) ->
mongo.modelFactory def
expect(mongooseStub.model.calledWithExactly(def.name, def.schema)
, 'mongoose model created with wrong schema').to.be.true
done()
it 'overrides collection name with def.options.collectionName'
, (done) ->
def.options =
collectionName: 'bob'
mongo.modelFactory def
expect(mongooseStub.model.calledWithExactly(
def.name, def.schema, 'bob'
), 'mongoose model created with wrong collectionName').to.be.true
done()
it 'returns the mongoose model', (done) ->
mongooseStub.model.returns 'a mongoose model'
res = mongo.modelFactory def
expect(res).to.equal 'a mongoose model'
def.options =
collectionName: 'jack'
res2 = mongo.modelFactory def
expect(res2).to.equal 'a mongoose model'
done()
describe 'schemaFactory (def) -> schema', ->
def = {}
beforeEach ->
def =
name: 'a model'
schemaDefinition: 'a defintion'
sinon.stub mongooseStub, 'Schema'
mongooseStub.Schema.returns {a: 'mongoose schema stub'}
afterEach ->
mongooseStub.Schema.restore()
it 'returns new Schema with given definition', (done) ->
res = mongo.schemaFactory def
expect(mongooseStub.Schema.calledOnce
, 'schema not called exactly once').to.be.true
expect(mongooseStub.Schema.calledWithNew()
, 'schema not called with new').to.be.true
expect(mongooseStub.Schema.calledWithExactly(def.schemaDefinition)
, 'schema not called with correct definition').to.be.true
expect(res).to.deep.equal {a: 'mongoose schema stub'}
done()
it 'passes options to mongoose Schema constructor', (done) ->
def.options = 'schema options'
res = mongo.schemaFactory def
expect(mongooseStub.Schema.calledOnce
, 'schema not called exactly once').to.be.true
expect(mongooseStub.Schema.calledWithNew()
, 'schema not called with new').to.be.true
expect(mongooseStub.Schema.calledWithExactly(
def.schemaDefinition, def.options
), 'schema not called with correct options').to.be.true
expect(res).to.deep.equal {a: 'mongoose schema stub'}
done()
|
[
{
"context": "key: 'comments'\npatterns: [\n {\n name: 'comment.md'\n begin",
"end": 14,
"score": 0.9872282147407532,
"start": 6,
"tag": "KEY",
"value": "comments"
}
] | grammars/repositories/inlines/comments.cson | doc22940/language-markdown | 138 | key: 'comments'
patterns: [
{
name: 'comment.md'
begin: '(<!(?:-{2,}))'
end: '((?:-{2,})>)'
captures:
1: name: 'punctuation.md'
3: name: 'punctuation.md'
}
]
| 203945 | key: '<KEY>'
patterns: [
{
name: 'comment.md'
begin: '(<!(?:-{2,}))'
end: '((?:-{2,})>)'
captures:
1: name: 'punctuation.md'
3: name: 'punctuation.md'
}
]
| true | key: 'PI:KEY:<KEY>END_PI'
patterns: [
{
name: 'comment.md'
begin: '(<!(?:-{2,}))'
end: '((?:-{2,})>)'
captures:
1: name: 'punctuation.md'
3: name: 'punctuation.md'
}
]
|
[
{
"context": "'use strict'\n#\n# Ethan Mick\n# 2015\n#\n#\nEventEmitter = require('events').Event",
"end": 27,
"score": 0.9996671080589294,
"start": 17,
"tag": "NAME",
"value": "Ethan Mick"
}
] | lib/models/scheduler.coffee | ethanmick/future-server | 0 | 'use strict'
#
# Ethan Mick
# 2015
#
#
EventEmitter = require('events').EventEmitter
PriorityQueue = require 'priorityqueuejs'
_100_MILLISECONDS = 100
_3_MINUTES = 180000
log = require '../helpers/log'
Task = require './task'
class Scheduler extends EventEmitter
constructor: ->
super()
@queue = new PriorityQueue (a, b)->
b.time - a.time
start: ->
@timer = setInterval(@tick.bind(this), _100_MILLISECONDS)
@dbTimer = setInterval(@readDB.bind(this), _3_MINUTES)
tick: ->
# log.info 'ticking...'
unless @queue.isEmpty()
while not @queue.isEmpty() and @queue.peek().hasOccured(30)
task = @queue.deq()
@emit 'task', task
readDB: ->
log.info 'reading db...'
Task.soon().then (tasks)=>
@queue.enq(t) for t in tasks
stop: ->
clearInterval(@timer)
@timer = null
module.exports = Scheduler
| 158954 | 'use strict'
#
# <NAME>
# 2015
#
#
EventEmitter = require('events').EventEmitter
PriorityQueue = require 'priorityqueuejs'
_100_MILLISECONDS = 100
_3_MINUTES = 180000
log = require '../helpers/log'
Task = require './task'
class Scheduler extends EventEmitter
constructor: ->
super()
@queue = new PriorityQueue (a, b)->
b.time - a.time
start: ->
@timer = setInterval(@tick.bind(this), _100_MILLISECONDS)
@dbTimer = setInterval(@readDB.bind(this), _3_MINUTES)
tick: ->
# log.info 'ticking...'
unless @queue.isEmpty()
while not @queue.isEmpty() and @queue.peek().hasOccured(30)
task = @queue.deq()
@emit 'task', task
readDB: ->
log.info 'reading db...'
Task.soon().then (tasks)=>
@queue.enq(t) for t in tasks
stop: ->
clearInterval(@timer)
@timer = null
module.exports = Scheduler
| true | 'use strict'
#
# PI:NAME:<NAME>END_PI
# 2015
#
#
EventEmitter = require('events').EventEmitter
PriorityQueue = require 'priorityqueuejs'
_100_MILLISECONDS = 100
_3_MINUTES = 180000
log = require '../helpers/log'
Task = require './task'
class Scheduler extends EventEmitter
constructor: ->
super()
@queue = new PriorityQueue (a, b)->
b.time - a.time
start: ->
@timer = setInterval(@tick.bind(this), _100_MILLISECONDS)
@dbTimer = setInterval(@readDB.bind(this), _3_MINUTES)
tick: ->
# log.info 'ticking...'
unless @queue.isEmpty()
while not @queue.isEmpty() and @queue.peek().hasOccured(30)
task = @queue.deq()
@emit 'task', task
readDB: ->
log.info 'reading db...'
Task.soon().then (tasks)=>
@queue.enq(t) for t in tasks
stop: ->
clearInterval(@timer)
@timer = null
module.exports = Scheduler
|
[
{
"context": "fo.info\n\nFramer.Info =\n\ttitle: \"Rocket\"\n\tauthor: \"Tony\"\n\ttwitter: \"TonyJing\"\n\tdescription: \"Rocket Launc",
"end": 152,
"score": 0.9778214693069458,
"start": 148,
"tag": "NAME",
"value": "Tony"
},
{
"context": "nfo =\n\ttitle: \"Rocket\"\n\tauthor: \"Tony\"\n\ttwitter: \"TonyJing\"\n\tdescription: \"Rocket Launch Animation\"\n\n\n# Var\n",
"end": 173,
"score": 0.9994357824325562,
"start": 165,
"tag": "USERNAME",
"value": "TonyJing"
}
] | 52rocket.framer/app.coffee | gremjua-forks/100daysofframer | 26 | # Project Info
# This info is presented in a widget when you share.
# http://framerjs.com/docs/#info.info
Framer.Info =
title: "Rocket"
author: "Tony"
twitter: "TonyJing"
description: "Rocket Launch Animation"
# Var
gray = "#ebebeb"
red = "ee5656"
launchTime = 2
flameYBase = 0.1
flameXBase = 1.7
launched = false
nearGround = true
# Elements
sky = new BackgroundLayer
style:
backgroundImage: """linear-gradient(to bottom,
#470DBA 1%,
#5CAFF2 33%,
#FFFFFF 52%)"""
horizon = new Layer
width: 500, y: Align.center(95)
x: Align.center, height: 200, clip: true
borderRadius: "50%", backgroundColor: ""
land = new Layer
x: Align.center, y: -100, width: 400, height: 200
backgroundColor: "white", parent: horizon
rocket = new Layer
width: 50, height: 155, x: Align.center, y: Align.center
clip: true, backgroundColor: ""
finLeft = new Layer
width: 15, height: 100, rotation: 45, parent: rocket
x: -20, y: 40, backgroundColor: red
finRight = new Layer
width: 15, height: 100, rotation: -45, parent: rocket
x: 55, y: 40, backgroundColor: red
nosecone = new Layer
size: 40, rotation: 45, parent: rocket, x: Align.center,
y: 10, borderRadius: "0 100%", backgroundColor: gray
airframe = new Layer
width: 24, height: 50, parent: rocket
x: Align.center, y: 30, backgroundColor: gray
finCenter = new Layer
width: 2, height: 32, parent: rocket
x: Align.center, y: 58, backgroundColor: red
viewWindow = new Layer
size: 12, borderRadius: "50%", parent: rocket, y: 30
x: Align.center, backgroundColor: "#3396ec"
borderColor: "#fff", borderWidth: 2
# Animations
fireAnimation = new Animation
layer: rocket
properties: y: Align.center(-60)
time: launchTime
curve: "ease-in"
flyAnimation = new Animation
layer: rocket, properties: y: -400
time: launchTime * 0.6
curve: "ease-in"
rocketShakeA = new Animation
layer: rocket
properties: x: Align.center(-1)
time: 0.05
rocketShakeB = new Animation
layer: rocket
properties: x: Align.center(1)
time: 0.05
# Functions
launch = ->
launched = true
fireAnimation.start()
fireAnimation.on(Events.AnimationEnd, flyAnimation.start)
fireAnimation.onAnimationEnd ->
nearGround = false
flyAnimation.onAnimationEnd ->
launched = false
Utils.delay 0.5, ->
restart()
shake = ->
rocketShakeA.start()
rocketShakeA.on(Events.AnimationEnd, rocketShakeB.start)
rocketShakeB.on(Events.AnimationEnd, rocketShakeA.start)
Utils. interval 0.1, ->
if launched
flameYBase += 0.032
flameXBase -= 0.01
flame = new Layer
width: 30, height: 80, borderRadius: "50%", parent: rocket
backgroundColor: Utils.randomChoice(["#F18F0F",
"#F1A20F","#F1B50F"])
scale: 0, originY: 0
flame.center()
flame.y = 75
flame.placeBehind airframe
flame.animate
properties:
scale: 1, scaleY: flameYBase, scaleX: flameXBase
time: 0.3
flame.animate
delay: 0.2, time: 0.1, properties: opacity: 0
flame.onAnimationEnd -> @destroy()
else
flameYBase = 0.1
flameXBase = 1.7
randomPos = -> Utils.randomNumber -125, 80
smoke = ->
for i in [0..Utils.randomChoice([10,11,12])]
cloud = new Layer
size: Utils.randomNumber(50, 80)
borderRadius: "50%", opacity: 0.8, scale: 0
style:
background: """radial-gradient(ellipse at center,
rgba(255,255,255,0) 0%,
rgba(215,215,210,1) 100%)"""
cloud.center()
if i <= 9
cloud.placeBehind(rocket)
cloud.animate
delay: launchTime / 5
properties:
scale: 2
x: rocket.midX + randomPos()
y: rocket.midY + 15 + randomPos() / 3.2
curve: "ease-out"
time: launchTime * 1.8
cloud.animate
delay: launchTime / 1.5
properties: opacity: 0
time: launchTime * 1.8
cloud.onAnimationEnd -> @destroy()
restart = ->
rocket.y = Align.center
rocket.props =
y: Align.center, scale: 0
rocket.animate
properties:
scale: 1, rotationX: 0
time: 0.6
curve: "ease-in-out"
rocketShakeA.stop()
rocketShakeB.stop()
# Events
rocket.onClick ->
launch()
shake()
smoke()
restart()
Events.wrap(window).addEventListener "resize", ->
rocket.center()
horizon.centerX()
horizon.centerY(95) | 25605 | # Project Info
# This info is presented in a widget when you share.
# http://framerjs.com/docs/#info.info
Framer.Info =
title: "Rocket"
author: "<NAME>"
twitter: "TonyJing"
description: "Rocket Launch Animation"
# Var
gray = "#ebebeb"
red = "ee5656"
launchTime = 2
flameYBase = 0.1
flameXBase = 1.7
launched = false
nearGround = true
# Elements
sky = new BackgroundLayer
style:
backgroundImage: """linear-gradient(to bottom,
#470DBA 1%,
#5CAFF2 33%,
#FFFFFF 52%)"""
horizon = new Layer
width: 500, y: Align.center(95)
x: Align.center, height: 200, clip: true
borderRadius: "50%", backgroundColor: ""
land = new Layer
x: Align.center, y: -100, width: 400, height: 200
backgroundColor: "white", parent: horizon
rocket = new Layer
width: 50, height: 155, x: Align.center, y: Align.center
clip: true, backgroundColor: ""
finLeft = new Layer
width: 15, height: 100, rotation: 45, parent: rocket
x: -20, y: 40, backgroundColor: red
finRight = new Layer
width: 15, height: 100, rotation: -45, parent: rocket
x: 55, y: 40, backgroundColor: red
nosecone = new Layer
size: 40, rotation: 45, parent: rocket, x: Align.center,
y: 10, borderRadius: "0 100%", backgroundColor: gray
airframe = new Layer
width: 24, height: 50, parent: rocket
x: Align.center, y: 30, backgroundColor: gray
finCenter = new Layer
width: 2, height: 32, parent: rocket
x: Align.center, y: 58, backgroundColor: red
viewWindow = new Layer
size: 12, borderRadius: "50%", parent: rocket, y: 30
x: Align.center, backgroundColor: "#3396ec"
borderColor: "#fff", borderWidth: 2
# Animations
fireAnimation = new Animation
layer: rocket
properties: y: Align.center(-60)
time: launchTime
curve: "ease-in"
flyAnimation = new Animation
layer: rocket, properties: y: -400
time: launchTime * 0.6
curve: "ease-in"
rocketShakeA = new Animation
layer: rocket
properties: x: Align.center(-1)
time: 0.05
rocketShakeB = new Animation
layer: rocket
properties: x: Align.center(1)
time: 0.05
# Functions
launch = ->
launched = true
fireAnimation.start()
fireAnimation.on(Events.AnimationEnd, flyAnimation.start)
fireAnimation.onAnimationEnd ->
nearGround = false
flyAnimation.onAnimationEnd ->
launched = false
Utils.delay 0.5, ->
restart()
shake = ->
rocketShakeA.start()
rocketShakeA.on(Events.AnimationEnd, rocketShakeB.start)
rocketShakeB.on(Events.AnimationEnd, rocketShakeA.start)
Utils. interval 0.1, ->
if launched
flameYBase += 0.032
flameXBase -= 0.01
flame = new Layer
width: 30, height: 80, borderRadius: "50%", parent: rocket
backgroundColor: Utils.randomChoice(["#F18F0F",
"#F1A20F","#F1B50F"])
scale: 0, originY: 0
flame.center()
flame.y = 75
flame.placeBehind airframe
flame.animate
properties:
scale: 1, scaleY: flameYBase, scaleX: flameXBase
time: 0.3
flame.animate
delay: 0.2, time: 0.1, properties: opacity: 0
flame.onAnimationEnd -> @destroy()
else
flameYBase = 0.1
flameXBase = 1.7
randomPos = -> Utils.randomNumber -125, 80
smoke = ->
for i in [0..Utils.randomChoice([10,11,12])]
cloud = new Layer
size: Utils.randomNumber(50, 80)
borderRadius: "50%", opacity: 0.8, scale: 0
style:
background: """radial-gradient(ellipse at center,
rgba(255,255,255,0) 0%,
rgba(215,215,210,1) 100%)"""
cloud.center()
if i <= 9
cloud.placeBehind(rocket)
cloud.animate
delay: launchTime / 5
properties:
scale: 2
x: rocket.midX + randomPos()
y: rocket.midY + 15 + randomPos() / 3.2
curve: "ease-out"
time: launchTime * 1.8
cloud.animate
delay: launchTime / 1.5
properties: opacity: 0
time: launchTime * 1.8
cloud.onAnimationEnd -> @destroy()
restart = ->
rocket.y = Align.center
rocket.props =
y: Align.center, scale: 0
rocket.animate
properties:
scale: 1, rotationX: 0
time: 0.6
curve: "ease-in-out"
rocketShakeA.stop()
rocketShakeB.stop()
# Events
rocket.onClick ->
launch()
shake()
smoke()
restart()
Events.wrap(window).addEventListener "resize", ->
rocket.center()
horizon.centerX()
horizon.centerY(95) | true | # Project Info
# This info is presented in a widget when you share.
# http://framerjs.com/docs/#info.info
Framer.Info =
title: "Rocket"
author: "PI:NAME:<NAME>END_PI"
twitter: "TonyJing"
description: "Rocket Launch Animation"
# Var
gray = "#ebebeb"
red = "ee5656"
launchTime = 2
flameYBase = 0.1
flameXBase = 1.7
launched = false
nearGround = true
# Elements
sky = new BackgroundLayer
style:
backgroundImage: """linear-gradient(to bottom,
#470DBA 1%,
#5CAFF2 33%,
#FFFFFF 52%)"""
horizon = new Layer
width: 500, y: Align.center(95)
x: Align.center, height: 200, clip: true
borderRadius: "50%", backgroundColor: ""
land = new Layer
x: Align.center, y: -100, width: 400, height: 200
backgroundColor: "white", parent: horizon
rocket = new Layer
width: 50, height: 155, x: Align.center, y: Align.center
clip: true, backgroundColor: ""
finLeft = new Layer
width: 15, height: 100, rotation: 45, parent: rocket
x: -20, y: 40, backgroundColor: red
finRight = new Layer
width: 15, height: 100, rotation: -45, parent: rocket
x: 55, y: 40, backgroundColor: red
nosecone = new Layer
size: 40, rotation: 45, parent: rocket, x: Align.center,
y: 10, borderRadius: "0 100%", backgroundColor: gray
airframe = new Layer
width: 24, height: 50, parent: rocket
x: Align.center, y: 30, backgroundColor: gray
finCenter = new Layer
width: 2, height: 32, parent: rocket
x: Align.center, y: 58, backgroundColor: red
viewWindow = new Layer
size: 12, borderRadius: "50%", parent: rocket, y: 30
x: Align.center, backgroundColor: "#3396ec"
borderColor: "#fff", borderWidth: 2
# Animations
fireAnimation = new Animation
layer: rocket
properties: y: Align.center(-60)
time: launchTime
curve: "ease-in"
flyAnimation = new Animation
layer: rocket, properties: y: -400
time: launchTime * 0.6
curve: "ease-in"
rocketShakeA = new Animation
layer: rocket
properties: x: Align.center(-1)
time: 0.05
rocketShakeB = new Animation
layer: rocket
properties: x: Align.center(1)
time: 0.05
# Functions
launch = ->
launched = true
fireAnimation.start()
fireAnimation.on(Events.AnimationEnd, flyAnimation.start)
fireAnimation.onAnimationEnd ->
nearGround = false
flyAnimation.onAnimationEnd ->
launched = false
Utils.delay 0.5, ->
restart()
shake = ->
rocketShakeA.start()
rocketShakeA.on(Events.AnimationEnd, rocketShakeB.start)
rocketShakeB.on(Events.AnimationEnd, rocketShakeA.start)
Utils. interval 0.1, ->
if launched
flameYBase += 0.032
flameXBase -= 0.01
flame = new Layer
width: 30, height: 80, borderRadius: "50%", parent: rocket
backgroundColor: Utils.randomChoice(["#F18F0F",
"#F1A20F","#F1B50F"])
scale: 0, originY: 0
flame.center()
flame.y = 75
flame.placeBehind airframe
flame.animate
properties:
scale: 1, scaleY: flameYBase, scaleX: flameXBase
time: 0.3
flame.animate
delay: 0.2, time: 0.1, properties: opacity: 0
flame.onAnimationEnd -> @destroy()
else
flameYBase = 0.1
flameXBase = 1.7
randomPos = -> Utils.randomNumber -125, 80
smoke = ->
for i in [0..Utils.randomChoice([10,11,12])]
cloud = new Layer
size: Utils.randomNumber(50, 80)
borderRadius: "50%", opacity: 0.8, scale: 0
style:
background: """radial-gradient(ellipse at center,
rgba(255,255,255,0) 0%,
rgba(215,215,210,1) 100%)"""
cloud.center()
if i <= 9
cloud.placeBehind(rocket)
cloud.animate
delay: launchTime / 5
properties:
scale: 2
x: rocket.midX + randomPos()
y: rocket.midY + 15 + randomPos() / 3.2
curve: "ease-out"
time: launchTime * 1.8
cloud.animate
delay: launchTime / 1.5
properties: opacity: 0
time: launchTime * 1.8
cloud.onAnimationEnd -> @destroy()
restart = ->
rocket.y = Align.center
rocket.props =
y: Align.center, scale: 0
rocket.animate
properties:
scale: 1, rotationX: 0
time: 0.6
curve: "ease-in-out"
rocketShakeA.stop()
rocketShakeB.stop()
# Events
rocket.onClick ->
launch()
shake()
smoke()
restart()
Events.wrap(window).addEventListener "resize", ->
rocket.center()
horizon.centerX()
horizon.centerY(95) |
[
{
"context": "\r\n },\r\n {\r\n \"name\": \"FIFA 2014\",\r\n \"level\": 15\r\n },\r\n ",
"end": 395,
"score": 0.761618435382843,
"start": 387,
"tag": "NAME",
"value": "FIFA 201"
},
{
"context": "\r\n },\r\n {\r\n \"name\": \"DOTA 2\",\r\n \"level\": 5\r\n },\r\n ",
"end": 479,
"score": 0.6845418214797974,
"start": 473,
"tag": "NAME",
"value": "DOTA 2"
}
] | mock/data/example.data.coffee | unDemian/protractor-mock | 6 | module.exports = () ->
angular.module("MockedGames", []).run ['Mock', (Mock) ->
# Endpoint Configuration
################################################################
Mock.add 'games',
url: '/games'
response:
data: [
{
"name": "Starcraft II",
"level": 30
},
{
"name": "FIFA 2014",
"level": 15
},
{
"name": "DOTA 2",
"level": 5
},
]
# Custom messages
success:
deleted:
code: 200
content: 'Delete Successful'
headers: []
error:
notFound:
code: 404,
content: 'Not found'
headers: []
Mock.add 'consoles',
url: '/consoles'
response:
data: {
"1": "Xbox One",
"2": "PS4",
}
]
return | 194417 | module.exports = () ->
angular.module("MockedGames", []).run ['Mock', (Mock) ->
# Endpoint Configuration
################################################################
Mock.add 'games',
url: '/games'
response:
data: [
{
"name": "Starcraft II",
"level": 30
},
{
"name": "<NAME>4",
"level": 15
},
{
"name": "<NAME>",
"level": 5
},
]
# Custom messages
success:
deleted:
code: 200
content: 'Delete Successful'
headers: []
error:
notFound:
code: 404,
content: 'Not found'
headers: []
Mock.add 'consoles',
url: '/consoles'
response:
data: {
"1": "Xbox One",
"2": "PS4",
}
]
return | true | module.exports = () ->
angular.module("MockedGames", []).run ['Mock', (Mock) ->
# Endpoint Configuration
################################################################
Mock.add 'games',
url: '/games'
response:
data: [
{
"name": "Starcraft II",
"level": 30
},
{
"name": "PI:NAME:<NAME>END_PI4",
"level": 15
},
{
"name": "PI:NAME:<NAME>END_PI",
"level": 5
},
]
# Custom messages
success:
deleted:
code: 200
content: 'Delete Successful'
headers: []
error:
notFound:
code: 404,
content: 'Not found'
headers: []
Mock.add 'consoles',
url: '/consoles'
response:
data: {
"1": "Xbox One",
"2": "PS4",
}
]
return |
[
{
"context": "\n $scope.user =\n email: ''\n password: null\n passwordRepeat: null\n type: 'advertise",
"end": 293,
"score": 0.9989346265792847,
"start": 289,
"tag": "PASSWORD",
"value": "null"
},
{
"context": "ail: ''\n password: null\n passwordRepeat: null\n type: 'advertiser'\n $scope.isPublisher =",
"end": 320,
"score": 0.9983938336372375,
"start": 316,
"tag": "PASSWORD",
"value": "null"
},
{
"context": " plainPassword:\n first: $scope.user.password\n second: $scope.user.passwordRepeat\n ",
"end": 1033,
"score": 0.7208653688430786,
"start": 1020,
"tag": "PASSWORD",
"value": "user.password"
},
{
"context": ".password\n second: $scope.user.passwordRepeat\n type: $scope.user.type\n # Reset th",
"end": 1080,
"score": 0.648829996585846,
"start": 1074,
"tag": "PASSWORD",
"value": "Repeat"
}
] | src/Vifeed/UserBundle/Resources/assets/js/controllers/signup-ctrl.coffee | bzis/zomba | 0 | angular.module('userApp').controller 'SignupCtrl', [
'$scope', '$window', '$routeParams', 'security', 'ErrorProcessor', 'ProgressBar',
($scope, $window, $routeParams, security, ErrorProcessor, ProgressBar) ->
$scope.errorList = []
$scope.user =
email: ''
password: null
passwordRepeat: null
type: 'advertiser'
$scope.isPublisher = false
if $routeParams.userType? and $routeParams.userType is 'publisher'
$scope.user.type = $routeParams.userType
$scope.isPublisher = true
# Click on the tab for advertiser
$scope.setUserAsAdvertiser = ->
$scope.user.type = 'advertiser'
$scope.isPublisher = false
# Click on the tab for publisher
$scope.setUserAsPublisher = ->
$scope.user.type = 'publisher'
$scope.isPublisher = true
# Sign in button handler
$scope.signup = ->
ProgressBar.start()
userData =
registration:
email: $scope.user.email
plainPassword:
first: $scope.user.password
second: $scope.user.passwordRepeat
type: $scope.user.type
# Reset the error messages
$scope.errorList = []
security.signup(userData).then -> $window.location = '/'
.catch (response) ->
$scope.errorList = ErrorProcessor.toList response.data.errors
.finally( -> ProgressBar.stop())
# Click on the "Enter" link below the submit button
$scope.showLoginForm = -> security.showLogin()
]
| 84459 | angular.module('userApp').controller 'SignupCtrl', [
'$scope', '$window', '$routeParams', 'security', 'ErrorProcessor', 'ProgressBar',
($scope, $window, $routeParams, security, ErrorProcessor, ProgressBar) ->
$scope.errorList = []
$scope.user =
email: ''
password: <PASSWORD>
passwordRepeat: <PASSWORD>
type: 'advertiser'
$scope.isPublisher = false
if $routeParams.userType? and $routeParams.userType is 'publisher'
$scope.user.type = $routeParams.userType
$scope.isPublisher = true
# Click on the tab for advertiser
$scope.setUserAsAdvertiser = ->
$scope.user.type = 'advertiser'
$scope.isPublisher = false
# Click on the tab for publisher
$scope.setUserAsPublisher = ->
$scope.user.type = 'publisher'
$scope.isPublisher = true
# Sign in button handler
$scope.signup = ->
ProgressBar.start()
userData =
registration:
email: $scope.user.email
plainPassword:
first: $scope.<PASSWORD>
second: $scope.user.password<PASSWORD>
type: $scope.user.type
# Reset the error messages
$scope.errorList = []
security.signup(userData).then -> $window.location = '/'
.catch (response) ->
$scope.errorList = ErrorProcessor.toList response.data.errors
.finally( -> ProgressBar.stop())
# Click on the "Enter" link below the submit button
$scope.showLoginForm = -> security.showLogin()
]
| true | angular.module('userApp').controller 'SignupCtrl', [
'$scope', '$window', '$routeParams', 'security', 'ErrorProcessor', 'ProgressBar',
($scope, $window, $routeParams, security, ErrorProcessor, ProgressBar) ->
$scope.errorList = []
$scope.user =
email: ''
password: PI:PASSWORD:<PASSWORD>END_PI
passwordRepeat: PI:PASSWORD:<PASSWORD>END_PI
type: 'advertiser'
$scope.isPublisher = false
if $routeParams.userType? and $routeParams.userType is 'publisher'
$scope.user.type = $routeParams.userType
$scope.isPublisher = true
# Click on the tab for advertiser
$scope.setUserAsAdvertiser = ->
$scope.user.type = 'advertiser'
$scope.isPublisher = false
# Click on the tab for publisher
$scope.setUserAsPublisher = ->
$scope.user.type = 'publisher'
$scope.isPublisher = true
# Sign in button handler
$scope.signup = ->
ProgressBar.start()
userData =
registration:
email: $scope.user.email
plainPassword:
first: $scope.PI:PASSWORD:<PASSWORD>END_PI
second: $scope.user.passwordPI:PASSWORD:<PASSWORD>END_PI
type: $scope.user.type
# Reset the error messages
$scope.errorList = []
security.signup(userData).then -> $window.location = '/'
.catch (response) ->
$scope.errorList = ErrorProcessor.toList response.data.errors
.finally( -> ProgressBar.stop())
# Click on the "Enter" link below the submit button
$scope.showLoginForm = -> security.showLogin()
]
|
[
{
"context": "PlayerConnection: (pc)->\n\n # Why the following, Michael??\n # @pingTimestamp = @pingTimestamp - 5*1000\n",
"end": 41179,
"score": 0.991003155708313,
"start": 41172,
"tag": "NAME",
"value": "Michael"
},
{
"context": "rs to run on the same network\n if username is \"iPad Simulator\"\n username = \"#{username}-#{Hy.Utils.Math.ra",
"end": 44446,
"score": 0.9015507102012634,
"start": 44432,
"tag": "USERNAME",
"value": "iPad Simulator"
},
{
"context": " if username is \"iPad Simulator\"\n username = \"#{username}-#{Hy.Utils.Math.random(10000)}\"\n\n @tag = esca",
"end": 44476,
"score": 0.6820160150527954,
"start": 44465,
"tag": "USERNAME",
"value": "\"#{username"
}
] | app-src/player_network.coffee | hyperbotic/crowdgame-trivially | 0 | # TODO
# Factor out Message, MessageQueue so that these can be used for HTTP as well, if necessary
# Figure out how to stop HTTP Service
# Figure out how to close a socket associated with an HTTP user that has been removed
# Abstract various message types, refactor used of "messageInfo"
#
#
# message = <connection><data>
#
# <connection> = <core_connection> [<bonjour_connection> | <http_connection>]
# <core_connection> = tag:
# <bonjour_connection> = dest:value + ??
#
# ==================================================================================================================
# Abstracts all player network interactions. A single instance is created, running in its own thread,
# when the application is initialized, via the .js file "player_network_stub.js", which is attached to a
# standalone window (and therefore runs in its own thread).
#
# The main app communicates with this instance via the "PlayerNetworkProxy" class; PlayerNetworkProxy" and "PlayerNetwork"
# fire/listen for events across the thread boundaries.
#
#
# Manages an instance of Bonjour network service, HTTP nework service for players, etc.
#
# Responds to these global events:
# "playerNetwork_Stop" {}
# "playerNetwork_Pause" {}
# "playerNetwork_Resumed" {}
# "playerNetwork_SendSingle" {connectionIndex, op, data}
# "playerNetwork_SendAll" {op, data}
#
# Fires these global events
#
# "playerNetwork_Ready" {httpPort}
# "playerNetwork_Error" {error, restartNetwork}
# "playerNetwork_MessageReceived" {playerConnectionIndex, op, data}
# "playerNetwork_AddPlayer" {playerConnectionIndex, playerLabel}
# "playerNetwork_RemovePlayer" {playerConnectionIndex}
# "playerNetwork_PlayerStatusChange" {playerConnectionIndex, status}
# "playerNetwork_ServiceStatusChange" {serviceStatus}
#
class PlayerNetwork
@kKindHTTP = 1
@kKindBonjour = 2
# ----------------------------------------------------------------------------------------------------------------
# Methods below are "private" or "protected", used only by this class and friends
# ----------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------
constructor: ()->
this.init()
this.initHandlers()
this
# ----------------------------------------------------------------------------------------------------------------
init: ()->
@receivedMessageProcessors = []
@sentMessageProcessors = []
this.startServices()
PlayerConnection.start(this)
ActivityMonitor.start(this)
this
# ----------------------------------------------------------------------------------------------------------------
startServices: ()->
@services = []
s1 = {kind: PlayerNetwork.kKindHTTP}
s2 = {kind: PlayerNetwork.kKindBonjour}
@services.push s1
# @services.push s2 # No bonjour discovery for V2
@serviceWatchdog = new ServiceStartupWatchdog(this)
s1.service = (new HTTPPlayerService(this)).start()
# s2.service = (new BonjourService(this)).start()
this
# ----------------------------------------------------------------------------------------------------------------
# After a "stop", can not restart the same instance. Must start over again with a new instance
#
stop: ()->
for s in @services
s.service?.stop()
@serviceWatchdog?.stop()
ActivityMonitor.stop()
PlayerConnection.stop()
this
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
@serviceWatchdog?.pause()
for s in @services
s.service?.pause()
ActivityMonitor.pause()
PlayerConnection.pause()
this
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
@serviceWatchdog?.resumed()
for s in @services
s.service?.resumed()
PlayerConnection.resumed()
ActivityMonitor.resumed()
this
# ----------------------------------------------------------------------------------------------------------------
initHandlers: ()->
Ti.App.addEventListener("playerNetwork_Stop",
(e)=>
this.stop()
null)
Ti.App.addEventListener("playerNetwork_Pause",
(e)=>
this.pause()
null)
Ti.App.addEventListener("playerNetwork_Resumed",
(e)=>
this.resumed()
null)
Ti.App.addEventListener("playerNetwork_SendSingle",
(e)=>
this.sendSingle(e.connectionIndex, e.op, e.data)
null)
Ti.App.addEventListener("playerNetwork_SendAll",
(e)=>
this.sendAll(e.op, e.data)
null)
this
# ----------------------------------------------------------------------------------------------------------------
setServiceReady: (service)->
@serviceWatchdog?.serviceCheckin(service)
# ----------------------------------------------------------------------------------------------------------------
sendSingle: (connectionIndex, op, data)->
playerConnection = PlayerConnection.findByIndex(connectionIndex)
# We use an anonymous object, "messageInfo", to group together message-related info, which
# allows message processors to rewrite the data as necesssary before it's sent off.
# TODO: consider abstracting messages into a hierarchy of sorts, to keep this a little
# more sane.
message = {op:op, data:data}
messageInfo = {playerConnection:playerConnection, message:message, handled:false}
messageInfo = this.doSentMessageProcessors(messageInfo)
if messageInfo.playerConnection?
service = messageInfo.playerConnection.getService()
if service?
# Hy.Trace.debug "PlayerNetwork::sendSingle (op=#{messageInfo.message.op} #{messageInfo.playerConnection.dumpStr()})"
service.sendSingle(messageInfo.playerConnection, messageInfo.message.op, messageInfo.message.data)
else
Hy.Trace.debug "PlayerNetwork::sendSingle (ERROR NO SERVICE for #{connectionIndex})"
else
Hy.Trace.debug "PlayerNetwork::sendSingle (ERROR CANT FIND PlayerConnection for #{connectionIndex})"
this
# ----------------------------------------------------------------------------------------------------------------
sendAll: (op, data)->
Hy.Trace.debug "PlayerNetwork::sendAll (op=#{op})"
message = {op:op, data:data}
messageInfo = {message:message, handled:false}
messageInfo = this.doSentMessageProcessors(messageInfo)
for s in @services
s.service?.sendAll(messageInfo.message.op, messageInfo.message.data)
this
# ----------------------------------------------------------------------------------------------------------------
doReady: ()->
httpPlayerService = this.findService(PlayerNetwork.kKindHTTP)
if httpPlayerService?
port = httpPlayerService.service.getPort()
Ti.App.fireEvent("playerNetwork_Ready", {httpPort:port})
# ----------------------------------------------------------------------------------------------------------------
doError: (error, restartNetwork=false)->
Hy.Trace.debug "PlayerNetwork::doError (ERROR /#{error}/ restartNetwork=#{restartNetwork})"
Ti.App.fireEvent("playerNetwork_Error", {error:error, restartNetwork:restartNetwork})
this
# ----------------------------------------------------------------------------------------------------------------
doMessageReceived: (playerConnectionIndex, op, data)->
Hy.Trace.debug "PlayerNetwork::doMessageReceived (op=#{op} data=#{data})"
Ti.App.fireEvent("playerNetwork_MessageReceived", {playerConnectionIndex:playerConnectionIndex, op:op, data:data})
this
# ----------------------------------------------------------------------------------------------------------------
doAddPlayer: (playerConnectionIndex, playerLabel, majorVersion, minorVersion)->
Hy.Trace.debug "PlayerNetwork::doAddPlayer (##{playerConnectionIndex}/#{playerLabel})"
Ti.App.fireEvent("playerNetwork_AddPlayer", {playerConnectionIndex:playerConnectionIndex, playerLabel:playerLabel, majorVersion:majorVersion, minorVersion:minorVersion})
this
# ----------------------------------------------------------------------------------------------------------------
doRemovePlayer: (playerConnectionIndex)->
Ti.App.fireEvent("playerNetwork_RemovePlayer", {playerConnectionIndex:playerConnectionIndex})
this
# ----------------------------------------------------------------------------------------------------------------
doPlayerStatusChange: (playerConnectionIndex, status)->
Ti.App.fireEvent("playerNetwork_PlayerStatusChange", {playerConnectionIndex:playerConnectionIndex, status:status})
this
# ----------------------------------------------------------------------------------------------------------------
doServiceStatusChange: (serviceStatus)->
Ti.App.fireEvent("playerNetwork_ServiceStatusChange", {serviceStatus: serviceStatus})
this
# ----------------------------------------------------------------------------------------------------------------
getServices: ()->
@services
# ----------------------------------------------------------------------------------------------------------------
findService: (kind)->
_.detect(@services, (s)=>s.kind is kind)
# ----------------------------------------------------------------------------------------------------------------
findServiceByConnection: (connection)->
this.findService(connection.kind)
# ----------------------------------------------------------------------------------------------------------------
addReceivedMessageProcessor: (fn)->
@receivedMessageProcessors.push fn
# ----------------------------------------------------------------------------------------------------------------
addSentMessageProcessor: (fn)->
@sentMessageProcessors.push fn
# ----------------------------------------------------------------------------------------------------------------
doMessageProcessors: (list, messageInfo)->
for fn in list
messageInfo = fn(this, messageInfo)
messageInfo
# ----------------------------------------------------------------------------------------------------------------
doReceivedMessageProcessors: (messageInfo)->
this.doMessageProcessors(@receivedMessageProcessors, messageInfo)
# ----------------------------------------------------------------------------------------------------------------
doSentMessageProcessors: (messageInfo)->
this.doMessageProcessors(@sentMessageProcessors, messageInfo)
# ----------------------------------------------------------------------------------------------------------------
messageReceived: (connection, message)->
playerConnection = PlayerConnection.findByConnection(connection)
# Hy.Trace.debug "PlayerNetwork::messageReceived (/#{message.op}/ from #{if playerConnection? then playerConnection.dumpStr() else connection.kind})"
# We use an anonymous object, "messageInfo", to group together message-related info, which
# allows message processors to rewrite the data as necesssary before it's sent off.
# TODO: consider abstracting messages into a hierarchy of sorts, to keep this a little
# more sane.
messageInfo = {connection:connection, playerConnection:playerConnection, message:message, handled:false}
messageInfo = this.doReceivedMessageProcessors(messageInfo)
if not messageInfo.handled
if messageInfo.playerConnection?
this.doMessageReceived(messageInfo.playerConnection.getIndex(), messageInfo.message.op, messageInfo.message.data)
else
this.doError("Unhandled message Received from unknown player (op=#{messageInfo.message.op}")
this
# ==================================================================================================================
class ServiceStartupWatchdog
kServiceStartupTimeout = 15 * 1000
# ----------------------------------------------------------------------------------------------------------------
constructor: (@networkManager)->
this.initState()
this.setTimer()
this
# ----------------------------------------------------------------------------------------------------------------
initState: ()->
@paused = false
@ready = false
@failed = false
this.clearReadyState()
this.clearTimer()
this
# ----------------------------------------------------------------------------------------------------------------
clearTimer: ()->
if @timer?
@timer.clear()
@timer = null
this
# ----------------------------------------------------------------------------------------------------------------
clearReadyState: ()->
for s in @networkManager.getServices()
s.ready = false
this
# ----------------------------------------------------------------------------------------------------------------
setTimer: ()->
this.clearTimer()
@timer = Hy.Utils.Deferral.create(kServiceStartupTimeout, ()=>this.timerExpired())
this
# ----------------------------------------------------------------------------------------------------------------
timerExpired: ()->
snr = this.servicesNotReady()
if _.size(snr) is 0
@ready = true # Should never get here
else
@failed = true
failedServices = ""
for s in snr
failedServices += "#{s.kind} "
@networkManager.doError("Player network services did not start in time: #{failedServices}", true)
this
# ----------------------------------------------------------------------------------------------------------------
servicesNotReady: ()->
_.select(@networkManager.getServices(), (s)=>not s.ready)
# ----------------------------------------------------------------------------------------------------------------
serviceCheckin: (service)->
s = @networkManager.findService(service.getKind())
if s?
s.ready = true
snr = this.servicesNotReady()
Hy.Trace.debug "ServiceStartupWatchdog::serviceCheckin (service=#{service.getKind()} # not ready = #{_.size(snr)})"
if _.size(snr) is 0
@ready = true
this.clearTimer()
@networkManager.doReady()
this
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
this.clearTimer()
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
this.clearTimer()
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
this.initState()
this.setTimer()
# ==================================================================================================================
# Abstract superclass representing what we need to keep track of a player's connection to the app.
#
# PlayerConnection
# HTTPPlayerConnection
# BonjourPlayerConnection
class PlayerConnection
gInstanceCount = 0
gInstances = []
@kStatusActive = 1
@kStatusInactive = 2
@kStatusDisconnected = 3 # when a remote has disconnected... we allow some time to reconnect
# ----------------------------------------------------------------------------------------------------------------
@start: (networkManager)->
gInstances = []
gInstanceCount = 0
networkManager.addReceivedMessageProcessor(PlayerConnection.processReceivedMessage)
networkManager.addSentMessageProcessor(PlayerConnection.processSentMessage)
# ----------------------------------------------------------------------------------------------------------------
@stop: ()->
for pc in PlayerConnection.getPlayerConnections()
pc.stop()
gInstances = []
null
# ----------------------------------------------------------------------------------------------------------------
@pause: ()->
for pc in PlayerConnection.getPlayerConnections()
pc.pause()
null
# ----------------------------------------------------------------------------------------------------------------
@resumed: ()->
for pc in PlayerConnection.getPlayerConnections()
pc.resumed()
# ----------------------------------------------------------------------------------------------------------------
@processReceivedMessage: (networkManager, messageInfo)->
# Hy.Trace.debug "PlayerConnection::processReceivedMessage (#{messageInfo.message.op})"
switch messageInfo.message.op
when "suspend" # HTTP clients don't send this
messageInfo.handled = true
if messageInfo.playerConnection?
Hy.Trace.debug "PlayerConnection::processReceivedMessage (suspend #{messageInfo.playerConnection.dumpStr()})"
messageInfo.playerConnection.deactivate(true)
when "resumed" # HTTP clients don't send this
messageInfo.handled = true
if messageInfo.playerConnection?
Hy.Trace.debug "PlayerConnection::processReceivedMessage (resumed #{messageInfo.playerConnection.dumpStr()})"
when "join"
messageInfo.handled = true
messageInfo = PlayerConnection.join(networkManager, messageInfo)
messageInfo
# ----------------------------------------------------------------------------------------------------------------
@processSentMessage: (networkManager, messageInfo)->
Hy.Trace.debug "PlayerConnection::processSentMessage (#{messageInfo.message.op})"
switch messageInfo.message.op
when "welcome"
messageInfo.handled = true
if messageInfo.playerConnection? and messageInfo.playerConnection.tagIsGenerated()
# We add in the tag, which we generated and which is assigned to some clients, such as those connected via HTTP.
# Other clients (Bonjour) tell us their tags when they send a join message (and so this is redundant).
# This is a legacy situation.
messageInfo.message.data.assignedTag = messageInfo.playerConnection.getTag()
messageInfo
# ----------------------------------------------------------------------------------------------------------------
@join: (networkManager, messageInfo)->
if not messageInfo.playerConnection?
# Is this a request from a player we've already seen? Check the tag
tag = messageInfo.message.tag
if tag?
messageInfo.playerConnection = PlayerConnection.findByTag(tag)
if messageInfo.playerConnection?
# An existing player may be rejoining over a different socket, etc.
PlayerConnection.swap(messageInfo.playerConnection, messageInfo.connection)
else
messageInfo.playerConnection = PlayerConnection.create(networkManager, messageInfo.connection, messageInfo.message.data)
# We always send a "welcome" when we receive a join
if messageInfo.playerConnection?
networkManager.doAddPlayer(messageInfo.playerConnection.getIndex(), messageInfo.playerConnection.getLabel(), messageInfo.playerConnection.getMajorVersion(), messageInfo.playerConnection.getMinorVersion())
messageInfo
# ----------------------------------------------------------------------------------------------------------------
# If an existing player connects over a new socket. We want to keep the higher-level player state while swapping
# out the specifics of the connection.
#
@swap: (playerConnection, newConnection)->
# Tell the current remote to go away
playerConnection.getService().sendSingle(playerConnection, "ejected", {reason:"You connected in another browser window"}, false)
# Swap in our new connection info, the higher-level app code won't know the difference
playerConnection.resetConnection(newConnection)
# Will result in the console app doing a reactivate, and then sending a welcome. A little wierd.
playerConnection.activate()
this
# ----------------------------------------------------------------------------------------------------------------
@create: (networkManager, connection, data)->
playerConnection = null
t = null
switch connection.kind
when PlayerNetwork.kKindHTTP
t = HTTPPlayerConnection
when PlayerNetwork.kKindBonjour
t = BonjourPlayerConnection
if t?
playerConnection = t.create(networkManager, connection, data)
playerConnection
# ----------------------------------------------------------------------------------------------------------------
@getPlayerConnections: ()->
gInstances
# ----------------------------------------------------------------------------------------------------------------
@numPlayerConnections: ()->
_.size(gInstances)
# ----------------------------------------------------------------------------------------------------------------
@findByConnection: (connection)->
_.detect(PlayerConnection.getPlayerConnections(), (pc)=>pc.compare(connection))
# ----------------------------------------------------------------------------------------------------------------
@findByIndex: (index)->
_.detect(PlayerConnection.getPlayerConnections(), (pc)=>pc.getIndex() is index)
# ----------------------------------------------------------------------------------------------------------------
@findByTag: (tag)->
_.detect(PlayerConnection.getPlayerConnections(), (pc)=>pc.getTag() is tag)
# ----------------------------------------------------------------------------------------------------------------
@getActivePlayerConnections: ()->
_.select(PlayerConnection.getPlayerConnections(), (pc)->pc.isActive())
# ----------------------------------------------------------------------------------------------------------------
@getActivePlayersByServiceKind: (kind)->
_.select(PlayerConnection.getPlayerConnections(), (pc)->(pc.isActive()) and (pc.getKind() is kind))
# ----------------------------------------------------------------------------------------------------------------
# Does some basic checks before we allow a new remote player to join
#
@preAddPlayer: (networkManager, connection, data)->
status = true
# Check version
status = status and PlayerConnection.checkPlayerVersion(networkManager, connection, data)
# Are we at player limit?
status = status and PlayerConnection.makeRoomForPlayer(networkManager, connection, data)
status
# ----------------------------------------------------------------------------------------------------------------
@makeRoomForPlayer: (networkManager, connection, data)->
status = true
if PlayerConnection.numPlayerConnections() >= Hy.Config.kMaxRemotePlayers
Hy.Trace.debug "PlayerConnection::makeRoomForPlayer (count=#{PlayerConnection.numPlayerConnections()} limit=#{Hy.Config.kMaxRemotePlayers})"
toRemove = []
for p in PlayerConnection.getPlayerConnections()
if !p.isActive()
toRemove.push p
for p in toRemove
Hy.Trace.debug "PlayerConnection::makeRoomForPlayer (Removing player: #{p.dumpStr()}, count=#{PlayerConnection.numPlayerConnections()})"
p.remove("You appear to be inactive,<br>so we are making room for another player")
if PlayerConnection.numPlayerConnections() >= Hy.Config.kMaxRemotePlayers
Hy.Trace.debug "PlayerConnection::makeRoomForPlayer (TOO MANY PLAYERS #{connection} Count=#{PlayerConnection.numPlayerConnections()})"
s = networkManager.findServiceByConnection(connection)
if s?
reason = "Too many remote players!<br>(Maximum is #{Hy.Config.kMaxRemotePlayers})"
s.service.sendSingle_(connection, "joinDenied", {reason: reason}, PlayerConnection.getLabelFromMessage(data), false)
status = false
return status
# ----------------------------------------------------------------------------------------------------------------
@checkPlayerVersion: (networkManager, connection, data)->
majorVersion = data.majorVersion
minorVersion = data.minorVersion
status = true
if !majorVersion? or (majorVersion < Hy.Config.Version.Remote.kMinRemoteMajorVersion)
Hy.Trace.debug "PlayerConnection::checkPlayerVersion (WRONG VERSION #{connection} Looking for #{Hy.Config.Version.Remote.kMinRemoteMajorVersion} Remote is version #{majorVersion}.#{minorVersion})"
s = networkManager.findServiceByConnection(connection)
if s?
s.service.sendSingle_(connection,"joinDenied", {reason: 'Update Required! Please visit the AppStore to update this app!'}, PlayerConnection.getLabelFromMessage(data))
status = false
return status
# ----------------------------------------------------------------------------------------------------------------
@getLabelFromMessage: (data)->
unescape(data.label)
# ----------------------------------------------------------------------------------------------------------------
constructor: (@networkManager, connection, data, @requiresActivityMonitor)->
gInstances.push this
@majorVersion = data.majorVersion
@minorVersion = data.minorVersion
@label = PlayerConnection.getLabelFromMessage(data)
@index = ++gInstanceCount
this.setConnection(connection)
Hy.Trace.debug "PlayerConnection::constructor (##{@index} label=/#{@label}/ tag=/#{@tag}/ count=#{_.size(gInstances)})"
if @requiresActivityMonitor
ActivityMonitor.addPlayerConnection(this)
this.activate()
this
# ----------------------------------------------------------------------------------------------------------------
getIndex: ()-> @index
# ----------------------------------------------------------------------------------------------------------------
getNetworkManager: ()-> @networkManager
# ----------------------------------------------------------------------------------------------------------------
getMajorVersion: ()-> @majorVersion
# ----------------------------------------------------------------------------------------------------------------
getMinorVersion: ()-> @minorVersion
# ----------------------------------------------------------------------------------------------------------------
checkVersion: (majorVersion, minorVersion=null)->
status = false
if @majorVersion >= majorVersion
if minorVersion?
if @minorVersion >= minorVersion
status = true
else
status = true
status
# ----------------------------------------------------------------------------------------------------------------
setConnection: (connection)->
@tag = connection.tag
@generatedTag = not @tag?
if @generatedTag
this.createTag()
this
# ----------------------------------------------------------------------------------------------------------------
resetConnection: (connection)->
# ----------------------------------------------------------------------------------------------------------------
getConnection: ()-> null
# ----------------------------------------------------------------------------------------------------------------
getTag: (tag)-> @tag
# ----------------------------------------------------------------------------------------------------------------
tagIsGenerated: ()-> @generatedTag
# ----------------------------------------------------------------------------------------------------------------
createTag: ()->
@generatedTag = true
found = true
while found
tag = Hy.Utils.UUID.generate()
found = PlayerConnection.findByTag(tag)?
Hy.Trace.debug "PlayerConnection::createTag (tag=#{tag})"
@tag = tag
# ----------------------------------------------------------------------------------------------------------------
getLabel: ()-> @label
# ----------------------------------------------------------------------------------------------------------------
compare: (connection)->
this.getKind() is connection.kind
# ----------------------------------------------------------------------------------------------------------------
getService: ()->
service = null
s = this.getNetworkManager().findService(this.getKind())
if s?
service = s.service
service
# ----------------------------------------------------------------------------------------------------------------
getKind: ()-> null
# ----------------------------------------------------------------------------------------------------------------
getStatus: ()-> @status
# ----------------------------------------------------------------------------------------------------------------
getStatusString: ()->
s = switch this.getStatus()
when PlayerConnection.kStatusActive
"active"
when PlayerConnection.kStatusInactive
"inactive"
when PlayerConnection.kStatusDisconnected
"disconnected"
else
"???"
s
# ----------------------------------------------------------------------------------------------------------------
setStatus: (newStatus)->
if newStatus isnt @status
@status = newStatus
s = switch @status
when PlayerConnection.kStatusActive
true
when PlayerConnection.kStatusInactive, PlayerConnection.kStatusDisconnected
false
else
false
this.getNetworkManager().doPlayerStatusChange(this.getIndex(), s)
@status
# ----------------------------------------------------------------------------------------------------------------
isActive: ()->
@status is PlayerConnection.kStatusActive
# ----------------------------------------------------------------------------------------------------------------
activate: ()->
this.setStatus(PlayerConnection.kStatusActive)
# ----------------------------------------------------------------------------------------------------------------
reactivate: ()->
this.activate()
# ----------------------------------------------------------------------------------------------------------------
# If "disconnected", means that the socket as closed or something similar
#
deactivate: (disconnected = false)->
this.setStatus(if disconnected then PlayerConnection.kStatusDisconnected else PlayerConnection.kStatusInactive)
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
this.deactivate()
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
# ----------------------------------------------------------------------------------------------------------------
remove: (warn=null)->
Hy.Trace.debug "PlayerConnection::remove (Removing #{this.dumpStr()} warn=#{warn})"
if @requiresActivityMonitor
ActivityMonitor.removePlayerConnection(this)
if warn?
service = this.getService()
if service?
service.sendSingle(this, "ejected", {reason:warn}, false)
gInstances = _.without(gInstances, this)
this.getService().doneWithPlayerConnection(this)
this.getNetworkManager().doRemovePlayer(this.getIndex())
null
# ----------------------------------------------------------------------------------------------------------------
dumpStr: ()->
"#{this.constructor.name}: ##{this.getIndex()} #{this.getLabel()} #{this.getStatusString()} #{this.getTag()}"
# ==================================================================================================================
class HTTPPlayerConnection extends PlayerConnection
# ----------------------------------------------------------------------------------------------------------------
@create: (networkManager, connection, data)->
if PlayerConnection.preAddPlayer(networkManager, connection, data)
new HTTPPlayerConnection(networkManager, connection, data)
else
null
# ----------------------------------------------------------------------------------------------------------------
constructor: (networkManager, connection, data)->
Hy.Trace.debug "HTTPPlayerConnection::constructor (ENTER)"
super networkManager, connection, data, true
Hy.Trace.debug "HTTPPlayerConnection::constructor (EXIT)"
this
# ----------------------------------------------------------------------------------------------------------------
setConnection: (connection)->
super
@socketID = connection.socketID
this
# ----------------------------------------------------------------------------------------------------------------
resetConnection: (connection)->
super
if connection.socketID isnt @socketID
@socketID = connection.socketID
this
# ----------------------------------------------------------------------------------------------------------------
getConnection: ()-> {kind:this.getKind(), socketID:@socketID}
# ----------------------------------------------------------------------------------------------------------------
getKind: ()-> PlayerNetwork.kKindHTTP
# ----------------------------------------------------------------------------------------------------------------
compare: (connection)->
result = super and (@socketID is connection.socketID)
result
# ----------------------------------------------------------------------------------------------------------------
dumpStr: ()->
super + " socketID=#{@socketID}"
# ==================================================================================================================
class BonjourPlayerConnection extends PlayerConnection
# ----------------------------------------------------------------------------------------------------------------
@create: (networkManager, connection, data)->
if PlayerConnection.preAddPlayer(networkManager, connection, data)
new BonjourPlayerConnection(networkManager, connection, data)
else
null
# ----------------------------------------------------------------------------------------------------------------
constructor: (networkManager, connection, data)->
Hy.Trace.debug "BonjourPlayerConnection::constructor"
# Should do a version check on the remote; if less than iOS 4, requires activityMonitor
super networkManager, connection, data, true
this
# ----------------------------------------------------------------------------------------------------------------
getConnection: ()-> {kind:this.getKind(), tag:@tag}
# ----------------------------------------------------------------------------------------------------------------
getKind: ()-> PlayerNetwork.kKindBonjour
# ----------------------------------------------------------------------------------------------------------------
compare:(connection)->
result = super and (@tag is connection.tag)
result
# ----------------------------------------------------------------------------------------------------------------
dumpStr: ()->
super
# ==================================================================================================================
class ActivityMonitor
gInstance = null
# ----------------------------------------------------------------------------------------------------------------
@start: (networkManager)->
if gInstance?
gInstance.stop()
new ActivityMonitor(networkManager)
# ----------------------------------------------------------------------------------------------------------------
@stop: ()->
if gInstance
gInstance.stop()
gInstance = null
null
# ----------------------------------------------------------------------------------------------------------------
@pause: ()->
if gInstance
gInstance.pause()
null
# ----------------------------------------------------------------------------------------------------------------
@resumed: ()->
if gInstance
gInstance.resumed()
null
# ----------------------------------------------------------------------------------------------------------------
@getTime: ()->
(new Date()).getTime()
# ----------------------------------------------------------------------------------------------------------------
@processReceivedMessage: (networkManager, messageInfo)->
if gInstance?
messageInfo = gInstance.processReceivedMessage(networkManager, messageInfo)
messageInfo
# ----------------------------------------------------------------------------------------------------------------
@addPlayerConnection: (pc)->
if gInstance?
gInstance.addPlayerConnection(pc)
null
# ----------------------------------------------------------------------------------------------------------------
@removePlayerConnection: (pc)->
if gInstance?
gInstance.removePlayerConnection(pc)
null
# ----------------------------------------------------------------------------------------------------------------
constructor: (@networkManager)->
# Hy.Trace.debug "ActivityMonitor::constructor"
gInstance = this
@playerConnections = []
@networkManager.addReceivedMessageProcessor(ActivityMonitor.processReceivedMessage)
this.startTimer()
this
# ----------------------------------------------------------------------------------------------------------------
startTimer: ()->
fnTick = ()=>this.tick()
@interval = setInterval(fnTick, Hy.Config.PlayerNetwork.ActivityMonitor.kCheckInterval)
# ----------------------------------------------------------------------------------------------------------------
clearTimer: ()->
if @interval?
clearInterval(@interval)
@interval = null
this
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
Hy.Trace.debug "ActivityMonitor::stop"
this.clearTimer()
@playerConnections = []
this
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
Hy.Trace.debug "ActivityMonitor::pause"
this.clearTimer()
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
Hy.Trace.debug "ActivityMonitor::resumed"
this.startTimer()
# ----------------------------------------------------------------------------------------------------------------
processReceivedMessage: (networkManager, messageInfo)->
# Hy.Trace.debug "ActivityMonitor::processReceivedMessage (#{messageInfo.op})"
if messageInfo.playerConnection?
p = this.updatePlayerConnection(messageInfo.playerConnection)
switch messageInfo.message.op
when "ping"
p.lastPing = messageInfo.message.data.pingCount
service = messageInfo.playerConnection.getService()
if service?
service.sendSingle(messageInfo.playerConnection, "ack", {pingCount:messageInfo.message.data.pingCount}, false)
messageInfo.handled = true
messageInfo
# ----------------------------------------------------------------------------------------------------------------
addPlayerConnection: (pc)->
if not this.updatePlayerConnection(pc)?
@playerConnections.push {playerConnection: pc, pingTimestamp:ActivityMonitor.getTime(), lastPing:null}
Hy.Trace.debug "ActivityMonitor::addPlayerConnection (size=#{_.size(@playerConnections)} Added:#{pc.dumpStr()})"
pc
# ----------------------------------------------------------------------------------------------------------------
updatePlayerConnection: (pc)->
p = _.detect(@playerConnections, (c)=>c.playerConnection is pc)
if p?
timeNow = ActivityMonitor.getTime()
Hy.Trace.debug "ActivityMonitor::updatePlayerConnection (Updated #{pc.dumpStr()} last heard from=#{timeNow-p.pingTimestamp} lastPing=#{p.lastPing})"
p.pingTimestamp = timeNow
pc.reactivate()
p
# ----------------------------------------------------------------------------------------------------------------
removePlayerConnection: (pc)->
# Why the following, Michael??
# @pingTimestamp = @pingTimestamp - 5*1000
@playerConnections = _.reject(@playerConnections, (p)=>p.playerConnection is pc)
# ----------------------------------------------------------------------------------------------------------------
tick: ()->
Hy.Trace.debug "ActivityMonitor::tick (#connections=#{_.size(@playerConnections)})"
for pc in @playerConnections
this.checkActivity(pc.playerConnection, pc.pingTimestamp, pc.lastPing)
null
# ----------------------------------------------------------------------------------------------------------------
checkActivity: (pc, pingTimestamp, lastPing)->
# this mechanism appears to be needed mostly for iPod 1Gs or perhaps anything else not running iOS 4+, and which
# don't send a "suspend" to the console when the button is pushed
fnTestActive = (pc, timeNow, pingTimestamp)->
((timeNow - pingTimestamp) <= Hy.Config.PlayerNetwork.ActivityMonitor.kThresholdActive)
fnTestAlive = (pc, timeNow, pingTimestamp)->
((timeNow - pingTimestamp) <= Hy.Config.PlayerNetwork.ActivityMonitor.kThresholdAlive)
timeNow = ActivityMonitor.getTime()
debugString = "#{pc.dumpStr()} last heard from=#{timeNow-pingTimestamp} lastPing=#{lastPing}"
if fnTestAlive(pc, timeNow, pingTimestamp)
switch pc.getStatus()
when PlayerConnection.kStatusActive
if not fnTestActive(pc, timeNow, pingTimestamp)
Hy.Trace.debug "PlayerConnection::checkActivity (Deactivating formerly active player #{debugString})"
pc.deactivate()
when PlayerConnection.kStatusInactive
if fnTestActive(pc, timeNow, pingTimestamp)
Hy.Trace.debug "PlayerConnection::checkActivity (Reactivating formerly inactive player #{debugString})"
pc.reactivate()
when PlayerConnection.Disconnected
# We do nothing here. If the player manages to reconnect, the join code will handle that
null
else
Hy.Trace.debug "ActivityMonitor::checkActivity (Removing #{debugString})"
pc.remove("You appear to be inactive")
# if !fnTestAlive(pc, timeNow, pingTimestamp)
# Hy.Trace.debug "ActivityMonitor::checkActivity (Removing #{pc.dumpStr()} #{timeNow-pingTimestamp})"
# pc.remove("You appear to be inactive")
# else if pc.isActive() and !fnTestActive(pc, timeNow, pingTimestamp)
# Hy.Trace.debug "PlayerConnection::checkActivity (Deactivating player #{pc.dumpStr()} #{timeNow-pingTimestamp})"
# pc.deactivate()
# else if !player.isActive() and fnTestActive(player)
# this.playerReactivate player
this
# ==================================================================================================================
# Abstract superclass for all player network types
# Each instance of a subtype of this type is managed by PlayerNetwork
#
# PlayerNetworkService
# HTTPPlayerService
# BonjourService
#
class PlayerNetworkService
# ----------------------------------------------------------------------------------------------------------------
constructor: (@networkManager)->
username = Ti.Platform.username
# to allow two simulators to run on the same network
if username is "iPad Simulator"
username = "#{username}-#{Hy.Utils.Math.random(10000)}"
@tag = escape username
this
# ----------------------------------------------------------------------------------------------------------------
start: ()->
Hy.Trace.debug "PlayerNetworkService::start"
this
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
Hy.Trace.debug "PlayerNetworkService::stop"
this
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
Hy.Trace.debug "PlayerNetworkService::pause"
this
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
Hy.Trace.debug "PlayerNetworkService::resumed"
this
# ----------------------------------------------------------------------------------------------------------------
getKind: ()-> null
# ----------------------------------------------------------------------------------------------------------------
setReady: ()->
Hy.Trace.debug "PlayerNetworkService::setReady (service=#{this.getKind()})"
@networkManager.setServiceReady(this)
# ----------------------------------------------------------------------------------------------------------------
getActivePlayers: ()->
PlayerConnection.getActivePlayersByServiceKind(this.getKind())
# ----------------------------------------------------------------------------------------------------------------
sendSingle_: (connection, op, data, label, requireAck=true)->
Hy.Trace.debug "PlayerNetworkService::sendSingle (#{this.constructor.name} op=#{op} label=#{label})"
# ----------------------------------------------------------------------------------------------------------------
sendSingle: (playerConnection, op, data, requireAck=true)->
this.sendSingle_(playerConnection.getConnection(), op, data, playerConnection.getLabel(), requireAck)
# ----------------------------------------------------------------------------------------------------------------
sendAll: (op, data, requireAck=true)->
Hy.Trace.debug "PlayerNetworkService::sendAll (#{this.constructor.name} op=#{op})"
# ----------------------------------------------------------------------------------------------------------------
doneWithPlayerConnection: (playerConnection)->
# ==================================================================================================================
class HTTPPlayerService extends PlayerNetworkService
# ----------------------------------------------------------------------------------------------------------------
constructor: (networkManager)->
super networkManager
this
# ----------------------------------------------------------------------------------------------------------------
getKind: ()-> PlayerNetwork.kKindHTTP
# ----------------------------------------------------------------------------------------------------------------
getPort: ()->
port = null
if @httpServer?
port = @httpServer.getPort()
port
# ----------------------------------------------------------------------------------------------------------------
start: ()->
Hy.Trace.debug "HTTPPlayerService::start"
fnServerReady = (server)=>this.setReady()
fnSocketOpened = (server, socketID)=> # Rely on clients to send 'join'
Hy.Trace.debug "HTTPPlayerService::fnSocketOpened (socket=#{socketID})"
null
fnSocketClosed = (server, socketID)=>
Hy.Trace.debug "HTTPPlayerService::fnSocketClosed (socket=#{socketID})"
pc = PlayerConnection.findByConnection({kind:this.getKind(), socketID:socketID})
# pc?.remove()
pc?.deactivate(true) # if the user refreshes the browser window, the socket is closed. Let's try to preserve the user's app state across that refresh
null
fnMessageReceived = (server, socketID, messageText)=>this.messageReceived(socketID, messageText)
fnServiceStatusChange = (status, domain, type_, name)=>this.serviceStatusChange(status, domain, type_, name)
@httpServer = Hy.Network.HTTPServerProxy.create(fnServerReady, fnSocketOpened, fnSocketClosed, fnMessageReceived, fnServiceStatusChange, Hy.Config.PlayerNetwork.HTTPServerRunsInOwnThread)
super
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
Hy.Trace.debug "HTTPPlayerService::stop"
@httpServer?.stop() # ?? for some reason, this doesn't work (error in the trivnet module at runtime)
@httpServer = null
super
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
Hy.Trace.debug "HTTPPlayerService::pause"
super
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
Hy.Trace.debug "HTTPPlayerService::resumed (#active=#{_.size(this.getActivePlayers())})"
# If we have resumed and the connections are still connected, then do nothing. Otherwise, restart
if _.size(this.getActivePlayers()) is 0
@httpServer?.restart()
this.setReady()
super
# ----------------------------------------------------------------------------------------------------------------
messageReceived: (socketID, messageText)->
try
message = JSON.parse messageText
catch e
@networkManager.doError("Error parsing HTTP message /#{messageText}/")
return null
@networkManager.messageReceived({kind:this.getKind(), socketID:socketID}, message)
null
# ----------------------------------------------------------------------------------------------------------------
serviceStatusChange: (status, domain, type_, name)->
Hy.Trace.debug "HTTPPlayerService::serviceStatusChange (#{status} #{domain} #{type_} #{name})"
serviceStatus = {}
switch status
when "bonjourPublishSuccess", "bonjourPublishFailure"
serviceStatus.bonjourPublish = {status: status, domain: domain, type_: type_, name: name}
@networkManager.doServiceStatusChange(serviceStatus)
this
# ----------------------------------------------------------------------------------------------------------------
getServiceStatus: ()-> @serviceStatus
# ----------------------------------------------------------------------------------------------------------------
sendSingle_: (connection, op, data, label, requireAck=true)->
# requireAck is not implemented
super
try
message = JSON.stringify src: @tag, op: op, data: data
@httpServer.sendMessage(connection.socketID, message)
catch e
@networkManager.doError("Error encoding HTTP message (connection=#{connection.socketID} op=#{op} tag=#{@tag} data=#{@data})")
this
# ----------------------------------------------------------------------------------------------------------------
sendAll: (op, data, requireAck=true)->
super
for p in this.getActivePlayers()
this.sendSingle(p, op, data, requireAck)
this
# ----------------------------------------------------------------------------------------------------------------
doneWithPlayerConnection: (playerConnection)->
super
# Should figure out a way to close the socket associated with this connection
# ==================================================================================================================
class BonjourService extends PlayerNetworkService
# ----------------------------------------------------------------------------------------------------------------
constructor: (networkManager)->
super networkManager
Hy.Trace.debug "BonjourService::constructor"
this
# ----------------------------------------------------------------------------------------------------------------
getKind: ()-> PlayerNetwork.kKindBonjour
# ----------------------------------------------------------------------------------------------------------------
startBonjourNetwork: ()->
this.openSocket()
this.publishService()
this
# ----------------------------------------------------------------------------------------------------------------
stopBonjourNetwork: ()->
if @localService?
@localService.stop()
@localService = null
if @socket?
if @socket.isValid
@socket.close()
@socket = null
this
# ----------------------------------------------------------------------------------------------------------------
start: ()->
Hy.Trace.debug "BonjourService::start"
this.startBonjourNetwork()
@messageQueue = MessageQueue.create(@networkManager, this)
this.setReady()
super
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
Hy.Trace.debug "BonjourService::stop"
this.stopBonjourNetwork()
@messageQueue.stop()
super
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
Hy.Trace.debug "BonjourService::pause"
this.stop()
super
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
Hy.Trace.debug "BonjourService::resumed"
this.start()
super
# ----------------------------------------------------------------------------------------------------------------
dumpSocket: ()->
(Hy.Trace.debug "socket.#{prop} => #{val}") for prop, val of @socket
Hy.Trace.debug "socket.isValid => #{@socket.isValid}"
Hy.Trace.debug "socket.mode => #{@socket.mode}"
Hy.Trace.debug "socket.port => #{@socket.port}"
Hy.Trace.debug "socket.hostName => #{@socket.hostName}"
# ----------------------------------------------------------------------------------------------------------------
openSocket: ()->
Hy.Trace.debug "BonjourService::openSocket"
@socket = Ti.Network.createTCPSocket(hostName:Hy.Config.Bonjour.hostName, mode:Hy.Config.Bonjour.mode, port:Hy.Config.Bonjour.port)
fnRead = (evt)=>
this.messageReceived(evt)
null
@socket.addEventListener 'read', fnRead
# @socket.stripTerminator = true
fnReadError = (evt)=>
@networkManager.doError("Bonjour READ ERROR (code=#{evt.code}/#{evt.error}/#{evt.type})")
null
@socket.addEventListener 'readError', fnReadError
fnWriteError = (evt)=>
@networkManager.doError("Bonjour WRITE ERROR (code=#{evt.code}/#{evt.error}/#{evt.type})")
null
@socket.addEventListener 'writeError', fnWriteError
@socket.listen()
# ----------------------------------------------------------------------------------------------------------------
publishService: ()->
Hy.Trace.debug "BonjourService::publishService"
@localService = Ti.Network.createBonjourService name:@tag, type:Hy.Config.Bonjour.serviceType, domain:Hy.Config.Bonjour.domain
try
@localService.publish @socket
catch error
@networkManager.doError("Bonjour Open Error", true)
this
# ----------------------------------------------------------------------------------------------------------------
parseForMultiple: (text)->
level = 0
results = []
out = ""
for c in text
if c.charCodeAt(0) is 0
null
else
switch c
when '{'
level++
when '}'
level--
out += c
if level is 0
results.push out
out = ""
return results
# ----------------------------------------------------------------------------------------------------------------
messageReceived: (evt)->
text = "UNKNOWN"
text = evt.data.text
# Hy.Trace.debug "BonjourService::messageReceived (length=#{text.length} last=#{text.charCodeAt(text.length-1)})"
# "suddenly", started seeing null bytes at the end of these strings, and multiple messages at the same time - 2011-08-12
if text.charCodeAt(text.length-1) isnt 125 # 125=}
text = text.substring(0, text.length-1)
results = this.parseForMultiple(text)
for r in results
try
message = JSON.parse r
catch e
@networkManager.doError("Error parsing Bonjour message /#{text}/")
return null
if (message.dest is 0) or (message.dest isnt @tag)
null
else
Hy.Trace.debug "BonjourService::messageReceived (message=#{r})"
@networkManager.messageReceived({kind:this.getKind(), tag:message.src}, message)
null
# ----------------------------------------------------------------------------------------------------------------
sendSingle_: (connection, op, data, label, requireAck=true)->
super
message = new Message(@tag, op, data, requireAck, false)
message.addDest(connection.tag, label)
this.sendMessage message
# ----------------------------------------------------------------------------------------------------------------
sendAll: (op, data, requireAck=true)->
super op, data
# Hy.Trace.info "BonjourService::sendMultipleClients(op=#{op} data=#{JSON.stringify(data)})"
players = this.getActivePlayers()
if _.size(players) isnt 0
message = new Message(@tag, op, data, requireAck, true)
for player in players
message.addDest(player.getConnection().tag, player.label)
this.sendMessage(message)
this
# ----------------------------------------------------------------------------------------------------------------
sendMessage: (message)->
# Hy.Trace.info "BonjourService::sendMessage (#{message.dump()})"
message.send(@socket)
if message.requireAck
@messageQueue.insert(message)
this
# ==================================================================================================================
class Message
messageCount = 0
# ----------------------------------------------------------------------------------------------------------------
constructor: (@src, @op, @data, @requireAck, @isBroadcast)->
messageCount++
@id = messageCount
@dests = []
@createTime = (new Date()).getTime()
@sendCount = 0
@sentTime = null
@broadcastPartiallyAckd = false # set true if we receive at least one response to a broadcast
this
# ----------------------------------------------------------------------------------------------------------------
addDest: (tag, label)->
@dests.push {tag: tag, label: label, ack: false, ackCount: 0}
# ----------------------------------------------------------------------------------------------------------------
getPacket: (tag)->
try
p = JSON.stringify m: @id, count: @sendCount, src: @src, dest: tag, op: @op, data: @data
catch e
Hy.Trace.info "Message::getPacket (ERROR could not encode packet data=#{@data})"
p = ""
p
# ----------------------------------------------------------------------------------------------------------------
getPacket2: (isBroadcast=false)->
tags = []
if not isBroadcast
for d in @dests
tags.push d.tag
try
p = JSON.stringify m: @id, count: @sendCount, src: @src, dest: tags, op: @op, data: @data
# Hy.Trace.info "Message::getPacket (packet=#{p})"
catch e
Hy.Trace.info "Message::getPacket (ERROR could not encode packet data=#{@data})"
p = ""
p
# ----------------------------------------------------------------------------------------------------------------
send: (socket)->
# Hy.Trace.info "Message:send (ENTER #{this.dump()})"
@sentTime = (new Date().getTime())
@sendCount++
dest = null
if 1 # Trying to reduce network traffic by making it possible for a message to target multiple clients
if @isBroadcast and not @broadcastPartiallyAckd
socket.write this.getPacket2(true)
Hy.Trace.info "Message:send (Broadcast #{this.dump()})"
else
socket.write this.getPacket2()
Hy.Trace.info "Message:send (Direct #{this.dump()})"
else
if @isBroadcast and not @broadcastPartiallyAckd
socket.write this.getPacket(0)
Hy.Trace.info "Message:send (Broadcast #{this.dump()})"
else
for dest in @dests
Hy.Trace.info "Message:send (Direct to #{dest.label} #{this.dump()})"
socket.write this.getPacket(dest.tag)
# Hy.Trace.info "Message:send (EXIT #{this.dump()})"
# ----------------------------------------------------------------------------------------------------------------
hasDest: (tag)->
for dest in @dests
if dest.tag is tag
return dest
return null
# ----------------------------------------------------------------------------------------------------------------
setAck: (tag, messageCount)->
ackdBefore = false
ackCount = 0
if @isBroadcast
@broadcastPartiallyAckd = true
dest = this.hasDest tag
if dest?
if dest.ack
ackdBefore = true
else
@ack = (new Date()).getTime()
dest.ack = true
dest.ackCount = messageCount
ackCount = dest.ackCount
# Hy.Trace.info "Message:setAck (#{if ackdBefore then "NOT THE FIRST TIME" else ""} label=#{dest.label} message=#{@id} op=#{@op} createTime=#{this.dumpCreateTime()} sendCount=#{@sendCount} ackCount=#{dest.ackCount})"
else
Hy.Trace.info "Message:setAck (Unexpected Ack: tag=#{tag} message=#{@id})"
ackCount
# ----------------------------------------------------------------------------------------------------------------
removeAckdDests: ()->
if @dests.length>0
newDests = _.reject @dests, (d)=>d.ack
@dests = newDests
return @dests.length > 0
# ----------------------------------------------------------------------------------------------------------------
removeDest: (tag)->
if @dests.length>0
newDests = _.reject @dests, (d)=>d.tag is tag
@dests = newDests
return @dests.length > 0
# ----------------------------------------------------------------------------------------------------------------
removeDests: ()->
@dests= {}
this
# ----------------------------------------------------------------------------------------------------------------
removeDestsInCommon: (message)->
# Hy.Trace.info "Message:removeDestInCommon (ENTER)"
if @dests.length is 0 or message.dests.length is 0
return
newDests = []
for d in @dests
if _.detect(message, (d1)=>d1.tag is d.tag)?
Hy.Trace.info "Message:removeDestsInCommon (Message=#{message.id} in common with #{@id}: Removing #{d.label})"
else
newDests.push d
@dests = newDests
this
# ----------------------------------------------------------------------------------------------------------------
hasOutstandingDests: ()->
@dests.length > 0
# ----------------------------------------------------------------------------------------------------------------
getNumDests: ()->
@dests.length
# ----------------------------------------------------------------------------------------------------------------
dumpCreateTime: ()->
now = (new Date()).getTime()
if @createTime? then ("#{now-this.createTime} milliseconds ago") else "(NO CREATE TIME)"
# ----------------------------------------------------------------------------------------------------------------
dumpSentTime: ()->
now = (new Date()).getTime()
if @sentTime? then ("#{now-@sentTime} milliseconds ago") else "NOT SENT"
# ----------------------------------------------------------------------------------------------------------------
dump: ()->
output = "Message=#{@id} op=#{@op} Broadcast=#{@isBroadcast}/#{@broadcastPartiallyAckd} create=#{this.dumpCreateTime()} AckRequired=#{if @requireAck then 'Yes' else 'No'} sent=#{this.dumpSentTime()} sendCount=#{@sendCount} #dests=#{@dests.length} "
count = 0
for dest in @dests
count++
a = if dest.ack then "ACKd" else "NOT ACKd"
output += "/##{count}: label=#{dest.label} ack=#{a} ackCount=#{dest.ackCount}/ "
output
# ==================================================================================================================
class MessageQueue
gInstance = null
kMessageDeliveryThreshold = 1500
kMaxSendAttempts = 5
# ----------------------------------------------------------------------------------------------------------------
@create: (networkManager, networkService)->
new MessageQueue(networkManager, networkService)
# ----------------------------------------------------------------------------------------------------------------
@processReceivedMessage: (networkManager, messageInfo)->
# Hy.Trace.debug "MessageQueue::processReceivedMessage (#{messageInfo.message.op})"
switch messageInfo.message.op
when "ack2"
messageInfo.handled = true
if messageInfo.playerConnection?
if gInstance?
gInstance.ackReceived(messageInfo.message.data.m, messageInfo.message.data.count, messageInfo.connection.tag)
messageInfo
# ----------------------------------------------------------------------------------------------------------------
constructor: (@networkManager, @networkService)->
# Hy.Trace.info "MessageQueue::constructor"
gInstance = this
@messages = []
@networkManager.addReceivedMessageProcessor(MessageQueue.processReceivedMessage)
this.initStats()
f = ()=>if @messages.length > 0 then this.check()
@interval = null
@interval = setInterval f, kMessageDeliveryThreshold
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
# Hy.Trace.debug "MessageQueue::stop"
clearInterval @interval if @interval?
@interval = null
@messages = []
this.initStats()
# ----------------------------------------------------------------------------------------------------------------
initStats: ()->
# Note that we count each destination in a broadcast as a separate message
@numberOfSentMessages = 0 # Total number of messages sent with "ack required" set
@numberOfResentMessages = 0 # Total number of messages sent more than once
@numberOfAckdMessages = 0 # Total number of messages ack'd
@numberOfAckdOnFirstSendMessages = 0 # Total number of messages ack'd after first send
@totalFirstSendAckdTime = 0 # For all messages ack'd after first send, sum of time between send and ack
@numberOfAckdOnRetryMessages = 0 # Total number of messages ack'd after one or more retries
@totalRetryTime = 0 # For all messages sent more than once, sum of time between send and ack
@numberOfFailedMessages = 0 # Total number of messages we've given up trying to resend
# ----------------------------------------------------------------------------------------------------------------
dumpStats: ()->
stat = "Sent/Ackd/Resent/Failed=#{@numberOfSentMessages}/#{@numberOfAckdMessages}/#{@numberOfResentMessages}/#{@numberOfFailedMessages} "
stat += "1st Send Ackd=#{@numberOfAckdOnFirstSendMessages} Ave=#{@totalFirstSendAckdTime/@numberOfAckdOnFirstSendMessages} secs "
stat += "Ackd after Retry=#{@numberOfAckdOnRetryMessages} Ave=#{@totalRetryTime/@numberOfAckdOnRetryMessages} secs"
stat
# ----------------------------------------------------------------------------------------------------------------
dump: ()->
for message in @messages
Hy.Trace.info "MessageQueue::dump (#{message.dump()})"
this
# ----------------------------------------------------------------------------------------------------------------
insert: (message)->
# Hy.Trace.info "MessageQueue::insert"
# Broadcast messages trump all previous messages, except 'welcome'
if message.isBroadcast and not message.broadcastPartiallyAckd
m = _.select @messages, (m)=>m.op is 'welcome'
# Hy.Trace.info "MessageQueue::insert (Broadcast inserted, was #{@messages.length} now #{m.length})"
@messages = m
else
for m in @messages
m.removeDestsInCommon message
@messages.push message
@numberOfSentMessages += message.getNumDests()
# Hy.Trace.info "MessageQueue::insert (EXIT)"
this
# ----------------------------------------------------------------------------------------------------------------
ackReceived: (messageId, messageCount, tag)->
for message in @messages
if message.id is messageId
ackCount = message.setAck(tag, messageCount)
t = message.ack - message.createTime
if ackCount is 1
@numberOfAckdOnFirstSendMessages++
@totalFirstSendAckdTime += t
else
@numberOfAckdOnRetryMessages++
@totalRetryTime += t
@numberOfAckdMessages++
return
this
# ----------------------------------------------------------------------------------------------------------------
check: ()->
# Hy.Trace.debug "MessageQueue::check (ENTERING number of messages=#{@messages.length} #{this.dumpStats()})"
timeNow = (new Date()).getTime()
messagesToCheckLater = []
messagesToResendNow = []
for message in @messages
# First, remove all clients that have ackd this message
if message.removeAckdDests()
# Then, remove all destinations representing clients that aren't active
for p in @networkService.getActivePlayers()
if !p.isActive()
message.removeDest p.tag
# If there are still outstanding destinations, then have we reached the resend limit?
if message.hasOutstandingDests()
if message.sendCount is kMaxSendAttempts
Hy.Trace.debug "MessageQueue::check (Message - too many retries: #{message.dump()})"
@numberOfFailedMessages += message.getNumDests()
else
# Decide whether to resend now or later
t = message.sentTime
if t?
if (timeNow - t) > kMessageDeliveryThreshold
messagesToResendNow.push message
else
messagesToCheckLater.push message
else
Hy.Trace.debug "MessageQueue::check (Message not sent! #{message.dump()})"
messagesToCheckLater.push message
@messages = []
@messages = messagesToCheckLater
for message in messagesToResendNow #should be safe to iterate while appending
Hy.Trace.debug "MessageQueue::check (Resending message: #{message.dump()})"
@numberOfResentMessages += message.getNumDests()
@networkService.sendMessage message
# Hy.Trace.debug "MessageQueue::check (EXITING number of messages=#{@messages.length})"
# this.dump()
# ==================================================================================================================
# assign to global namespace:
if not Hy.Network?
Hy.Network = {}
Hy.Network.PlayerNetwork = PlayerNetwork
| 6450 | # TODO
# Factor out Message, MessageQueue so that these can be used for HTTP as well, if necessary
# Figure out how to stop HTTP Service
# Figure out how to close a socket associated with an HTTP user that has been removed
# Abstract various message types, refactor used of "messageInfo"
#
#
# message = <connection><data>
#
# <connection> = <core_connection> [<bonjour_connection> | <http_connection>]
# <core_connection> = tag:
# <bonjour_connection> = dest:value + ??
#
# ==================================================================================================================
# Abstracts all player network interactions. A single instance is created, running in its own thread,
# when the application is initialized, via the .js file "player_network_stub.js", which is attached to a
# standalone window (and therefore runs in its own thread).
#
# The main app communicates with this instance via the "PlayerNetworkProxy" class; PlayerNetworkProxy" and "PlayerNetwork"
# fire/listen for events across the thread boundaries.
#
#
# Manages an instance of Bonjour network service, HTTP nework service for players, etc.
#
# Responds to these global events:
# "playerNetwork_Stop" {}
# "playerNetwork_Pause" {}
# "playerNetwork_Resumed" {}
# "playerNetwork_SendSingle" {connectionIndex, op, data}
# "playerNetwork_SendAll" {op, data}
#
# Fires these global events
#
# "playerNetwork_Ready" {httpPort}
# "playerNetwork_Error" {error, restartNetwork}
# "playerNetwork_MessageReceived" {playerConnectionIndex, op, data}
# "playerNetwork_AddPlayer" {playerConnectionIndex, playerLabel}
# "playerNetwork_RemovePlayer" {playerConnectionIndex}
# "playerNetwork_PlayerStatusChange" {playerConnectionIndex, status}
# "playerNetwork_ServiceStatusChange" {serviceStatus}
#
class PlayerNetwork
@kKindHTTP = 1
@kKindBonjour = 2
# ----------------------------------------------------------------------------------------------------------------
# Methods below are "private" or "protected", used only by this class and friends
# ----------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------
constructor: ()->
this.init()
this.initHandlers()
this
# ----------------------------------------------------------------------------------------------------------------
init: ()->
@receivedMessageProcessors = []
@sentMessageProcessors = []
this.startServices()
PlayerConnection.start(this)
ActivityMonitor.start(this)
this
# ----------------------------------------------------------------------------------------------------------------
startServices: ()->
@services = []
s1 = {kind: PlayerNetwork.kKindHTTP}
s2 = {kind: PlayerNetwork.kKindBonjour}
@services.push s1
# @services.push s2 # No bonjour discovery for V2
@serviceWatchdog = new ServiceStartupWatchdog(this)
s1.service = (new HTTPPlayerService(this)).start()
# s2.service = (new BonjourService(this)).start()
this
# ----------------------------------------------------------------------------------------------------------------
# After a "stop", can not restart the same instance. Must start over again with a new instance
#
stop: ()->
for s in @services
s.service?.stop()
@serviceWatchdog?.stop()
ActivityMonitor.stop()
PlayerConnection.stop()
this
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
@serviceWatchdog?.pause()
for s in @services
s.service?.pause()
ActivityMonitor.pause()
PlayerConnection.pause()
this
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
@serviceWatchdog?.resumed()
for s in @services
s.service?.resumed()
PlayerConnection.resumed()
ActivityMonitor.resumed()
this
# ----------------------------------------------------------------------------------------------------------------
initHandlers: ()->
Ti.App.addEventListener("playerNetwork_Stop",
(e)=>
this.stop()
null)
Ti.App.addEventListener("playerNetwork_Pause",
(e)=>
this.pause()
null)
Ti.App.addEventListener("playerNetwork_Resumed",
(e)=>
this.resumed()
null)
Ti.App.addEventListener("playerNetwork_SendSingle",
(e)=>
this.sendSingle(e.connectionIndex, e.op, e.data)
null)
Ti.App.addEventListener("playerNetwork_SendAll",
(e)=>
this.sendAll(e.op, e.data)
null)
this
# ----------------------------------------------------------------------------------------------------------------
setServiceReady: (service)->
@serviceWatchdog?.serviceCheckin(service)
# ----------------------------------------------------------------------------------------------------------------
sendSingle: (connectionIndex, op, data)->
playerConnection = PlayerConnection.findByIndex(connectionIndex)
# We use an anonymous object, "messageInfo", to group together message-related info, which
# allows message processors to rewrite the data as necesssary before it's sent off.
# TODO: consider abstracting messages into a hierarchy of sorts, to keep this a little
# more sane.
message = {op:op, data:data}
messageInfo = {playerConnection:playerConnection, message:message, handled:false}
messageInfo = this.doSentMessageProcessors(messageInfo)
if messageInfo.playerConnection?
service = messageInfo.playerConnection.getService()
if service?
# Hy.Trace.debug "PlayerNetwork::sendSingle (op=#{messageInfo.message.op} #{messageInfo.playerConnection.dumpStr()})"
service.sendSingle(messageInfo.playerConnection, messageInfo.message.op, messageInfo.message.data)
else
Hy.Trace.debug "PlayerNetwork::sendSingle (ERROR NO SERVICE for #{connectionIndex})"
else
Hy.Trace.debug "PlayerNetwork::sendSingle (ERROR CANT FIND PlayerConnection for #{connectionIndex})"
this
# ----------------------------------------------------------------------------------------------------------------
sendAll: (op, data)->
Hy.Trace.debug "PlayerNetwork::sendAll (op=#{op})"
message = {op:op, data:data}
messageInfo = {message:message, handled:false}
messageInfo = this.doSentMessageProcessors(messageInfo)
for s in @services
s.service?.sendAll(messageInfo.message.op, messageInfo.message.data)
this
# ----------------------------------------------------------------------------------------------------------------
doReady: ()->
httpPlayerService = this.findService(PlayerNetwork.kKindHTTP)
if httpPlayerService?
port = httpPlayerService.service.getPort()
Ti.App.fireEvent("playerNetwork_Ready", {httpPort:port})
# ----------------------------------------------------------------------------------------------------------------
doError: (error, restartNetwork=false)->
Hy.Trace.debug "PlayerNetwork::doError (ERROR /#{error}/ restartNetwork=#{restartNetwork})"
Ti.App.fireEvent("playerNetwork_Error", {error:error, restartNetwork:restartNetwork})
this
# ----------------------------------------------------------------------------------------------------------------
doMessageReceived: (playerConnectionIndex, op, data)->
Hy.Trace.debug "PlayerNetwork::doMessageReceived (op=#{op} data=#{data})"
Ti.App.fireEvent("playerNetwork_MessageReceived", {playerConnectionIndex:playerConnectionIndex, op:op, data:data})
this
# ----------------------------------------------------------------------------------------------------------------
doAddPlayer: (playerConnectionIndex, playerLabel, majorVersion, minorVersion)->
Hy.Trace.debug "PlayerNetwork::doAddPlayer (##{playerConnectionIndex}/#{playerLabel})"
Ti.App.fireEvent("playerNetwork_AddPlayer", {playerConnectionIndex:playerConnectionIndex, playerLabel:playerLabel, majorVersion:majorVersion, minorVersion:minorVersion})
this
# ----------------------------------------------------------------------------------------------------------------
doRemovePlayer: (playerConnectionIndex)->
Ti.App.fireEvent("playerNetwork_RemovePlayer", {playerConnectionIndex:playerConnectionIndex})
this
# ----------------------------------------------------------------------------------------------------------------
doPlayerStatusChange: (playerConnectionIndex, status)->
Ti.App.fireEvent("playerNetwork_PlayerStatusChange", {playerConnectionIndex:playerConnectionIndex, status:status})
this
# ----------------------------------------------------------------------------------------------------------------
doServiceStatusChange: (serviceStatus)->
Ti.App.fireEvent("playerNetwork_ServiceStatusChange", {serviceStatus: serviceStatus})
this
# ----------------------------------------------------------------------------------------------------------------
getServices: ()->
@services
# ----------------------------------------------------------------------------------------------------------------
findService: (kind)->
_.detect(@services, (s)=>s.kind is kind)
# ----------------------------------------------------------------------------------------------------------------
findServiceByConnection: (connection)->
this.findService(connection.kind)
# ----------------------------------------------------------------------------------------------------------------
addReceivedMessageProcessor: (fn)->
@receivedMessageProcessors.push fn
# ----------------------------------------------------------------------------------------------------------------
addSentMessageProcessor: (fn)->
@sentMessageProcessors.push fn
# ----------------------------------------------------------------------------------------------------------------
doMessageProcessors: (list, messageInfo)->
for fn in list
messageInfo = fn(this, messageInfo)
messageInfo
# ----------------------------------------------------------------------------------------------------------------
doReceivedMessageProcessors: (messageInfo)->
this.doMessageProcessors(@receivedMessageProcessors, messageInfo)
# ----------------------------------------------------------------------------------------------------------------
doSentMessageProcessors: (messageInfo)->
this.doMessageProcessors(@sentMessageProcessors, messageInfo)
# ----------------------------------------------------------------------------------------------------------------
messageReceived: (connection, message)->
playerConnection = PlayerConnection.findByConnection(connection)
# Hy.Trace.debug "PlayerNetwork::messageReceived (/#{message.op}/ from #{if playerConnection? then playerConnection.dumpStr() else connection.kind})"
# We use an anonymous object, "messageInfo", to group together message-related info, which
# allows message processors to rewrite the data as necesssary before it's sent off.
# TODO: consider abstracting messages into a hierarchy of sorts, to keep this a little
# more sane.
messageInfo = {connection:connection, playerConnection:playerConnection, message:message, handled:false}
messageInfo = this.doReceivedMessageProcessors(messageInfo)
if not messageInfo.handled
if messageInfo.playerConnection?
this.doMessageReceived(messageInfo.playerConnection.getIndex(), messageInfo.message.op, messageInfo.message.data)
else
this.doError("Unhandled message Received from unknown player (op=#{messageInfo.message.op}")
this
# ==================================================================================================================
class ServiceStartupWatchdog
kServiceStartupTimeout = 15 * 1000
# ----------------------------------------------------------------------------------------------------------------
constructor: (@networkManager)->
this.initState()
this.setTimer()
this
# ----------------------------------------------------------------------------------------------------------------
initState: ()->
@paused = false
@ready = false
@failed = false
this.clearReadyState()
this.clearTimer()
this
# ----------------------------------------------------------------------------------------------------------------
clearTimer: ()->
if @timer?
@timer.clear()
@timer = null
this
# ----------------------------------------------------------------------------------------------------------------
clearReadyState: ()->
for s in @networkManager.getServices()
s.ready = false
this
# ----------------------------------------------------------------------------------------------------------------
setTimer: ()->
this.clearTimer()
@timer = Hy.Utils.Deferral.create(kServiceStartupTimeout, ()=>this.timerExpired())
this
# ----------------------------------------------------------------------------------------------------------------
timerExpired: ()->
snr = this.servicesNotReady()
if _.size(snr) is 0
@ready = true # Should never get here
else
@failed = true
failedServices = ""
for s in snr
failedServices += "#{s.kind} "
@networkManager.doError("Player network services did not start in time: #{failedServices}", true)
this
# ----------------------------------------------------------------------------------------------------------------
servicesNotReady: ()->
_.select(@networkManager.getServices(), (s)=>not s.ready)
# ----------------------------------------------------------------------------------------------------------------
serviceCheckin: (service)->
s = @networkManager.findService(service.getKind())
if s?
s.ready = true
snr = this.servicesNotReady()
Hy.Trace.debug "ServiceStartupWatchdog::serviceCheckin (service=#{service.getKind()} # not ready = #{_.size(snr)})"
if _.size(snr) is 0
@ready = true
this.clearTimer()
@networkManager.doReady()
this
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
this.clearTimer()
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
this.clearTimer()
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
this.initState()
this.setTimer()
# ==================================================================================================================
# Abstract superclass representing what we need to keep track of a player's connection to the app.
#
# PlayerConnection
# HTTPPlayerConnection
# BonjourPlayerConnection
class PlayerConnection
gInstanceCount = 0
gInstances = []
@kStatusActive = 1
@kStatusInactive = 2
@kStatusDisconnected = 3 # when a remote has disconnected... we allow some time to reconnect
# ----------------------------------------------------------------------------------------------------------------
@start: (networkManager)->
gInstances = []
gInstanceCount = 0
networkManager.addReceivedMessageProcessor(PlayerConnection.processReceivedMessage)
networkManager.addSentMessageProcessor(PlayerConnection.processSentMessage)
# ----------------------------------------------------------------------------------------------------------------
@stop: ()->
for pc in PlayerConnection.getPlayerConnections()
pc.stop()
gInstances = []
null
# ----------------------------------------------------------------------------------------------------------------
@pause: ()->
for pc in PlayerConnection.getPlayerConnections()
pc.pause()
null
# ----------------------------------------------------------------------------------------------------------------
@resumed: ()->
for pc in PlayerConnection.getPlayerConnections()
pc.resumed()
# ----------------------------------------------------------------------------------------------------------------
@processReceivedMessage: (networkManager, messageInfo)->
# Hy.Trace.debug "PlayerConnection::processReceivedMessage (#{messageInfo.message.op})"
switch messageInfo.message.op
when "suspend" # HTTP clients don't send this
messageInfo.handled = true
if messageInfo.playerConnection?
Hy.Trace.debug "PlayerConnection::processReceivedMessage (suspend #{messageInfo.playerConnection.dumpStr()})"
messageInfo.playerConnection.deactivate(true)
when "resumed" # HTTP clients don't send this
messageInfo.handled = true
if messageInfo.playerConnection?
Hy.Trace.debug "PlayerConnection::processReceivedMessage (resumed #{messageInfo.playerConnection.dumpStr()})"
when "join"
messageInfo.handled = true
messageInfo = PlayerConnection.join(networkManager, messageInfo)
messageInfo
# ----------------------------------------------------------------------------------------------------------------
@processSentMessage: (networkManager, messageInfo)->
Hy.Trace.debug "PlayerConnection::processSentMessage (#{messageInfo.message.op})"
switch messageInfo.message.op
when "welcome"
messageInfo.handled = true
if messageInfo.playerConnection? and messageInfo.playerConnection.tagIsGenerated()
# We add in the tag, which we generated and which is assigned to some clients, such as those connected via HTTP.
# Other clients (Bonjour) tell us their tags when they send a join message (and so this is redundant).
# This is a legacy situation.
messageInfo.message.data.assignedTag = messageInfo.playerConnection.getTag()
messageInfo
# ----------------------------------------------------------------------------------------------------------------
@join: (networkManager, messageInfo)->
if not messageInfo.playerConnection?
# Is this a request from a player we've already seen? Check the tag
tag = messageInfo.message.tag
if tag?
messageInfo.playerConnection = PlayerConnection.findByTag(tag)
if messageInfo.playerConnection?
# An existing player may be rejoining over a different socket, etc.
PlayerConnection.swap(messageInfo.playerConnection, messageInfo.connection)
else
messageInfo.playerConnection = PlayerConnection.create(networkManager, messageInfo.connection, messageInfo.message.data)
# We always send a "welcome" when we receive a join
if messageInfo.playerConnection?
networkManager.doAddPlayer(messageInfo.playerConnection.getIndex(), messageInfo.playerConnection.getLabel(), messageInfo.playerConnection.getMajorVersion(), messageInfo.playerConnection.getMinorVersion())
messageInfo
# ----------------------------------------------------------------------------------------------------------------
# If an existing player connects over a new socket. We want to keep the higher-level player state while swapping
# out the specifics of the connection.
#
@swap: (playerConnection, newConnection)->
# Tell the current remote to go away
playerConnection.getService().sendSingle(playerConnection, "ejected", {reason:"You connected in another browser window"}, false)
# Swap in our new connection info, the higher-level app code won't know the difference
playerConnection.resetConnection(newConnection)
# Will result in the console app doing a reactivate, and then sending a welcome. A little wierd.
playerConnection.activate()
this
# ----------------------------------------------------------------------------------------------------------------
@create: (networkManager, connection, data)->
playerConnection = null
t = null
switch connection.kind
when PlayerNetwork.kKindHTTP
t = HTTPPlayerConnection
when PlayerNetwork.kKindBonjour
t = BonjourPlayerConnection
if t?
playerConnection = t.create(networkManager, connection, data)
playerConnection
# ----------------------------------------------------------------------------------------------------------------
@getPlayerConnections: ()->
gInstances
# ----------------------------------------------------------------------------------------------------------------
@numPlayerConnections: ()->
_.size(gInstances)
# ----------------------------------------------------------------------------------------------------------------
@findByConnection: (connection)->
_.detect(PlayerConnection.getPlayerConnections(), (pc)=>pc.compare(connection))
# ----------------------------------------------------------------------------------------------------------------
@findByIndex: (index)->
_.detect(PlayerConnection.getPlayerConnections(), (pc)=>pc.getIndex() is index)
# ----------------------------------------------------------------------------------------------------------------
@findByTag: (tag)->
_.detect(PlayerConnection.getPlayerConnections(), (pc)=>pc.getTag() is tag)
# ----------------------------------------------------------------------------------------------------------------
@getActivePlayerConnections: ()->
_.select(PlayerConnection.getPlayerConnections(), (pc)->pc.isActive())
# ----------------------------------------------------------------------------------------------------------------
@getActivePlayersByServiceKind: (kind)->
_.select(PlayerConnection.getPlayerConnections(), (pc)->(pc.isActive()) and (pc.getKind() is kind))
# ----------------------------------------------------------------------------------------------------------------
# Does some basic checks before we allow a new remote player to join
#
@preAddPlayer: (networkManager, connection, data)->
status = true
# Check version
status = status and PlayerConnection.checkPlayerVersion(networkManager, connection, data)
# Are we at player limit?
status = status and PlayerConnection.makeRoomForPlayer(networkManager, connection, data)
status
# ----------------------------------------------------------------------------------------------------------------
@makeRoomForPlayer: (networkManager, connection, data)->
status = true
if PlayerConnection.numPlayerConnections() >= Hy.Config.kMaxRemotePlayers
Hy.Trace.debug "PlayerConnection::makeRoomForPlayer (count=#{PlayerConnection.numPlayerConnections()} limit=#{Hy.Config.kMaxRemotePlayers})"
toRemove = []
for p in PlayerConnection.getPlayerConnections()
if !p.isActive()
toRemove.push p
for p in toRemove
Hy.Trace.debug "PlayerConnection::makeRoomForPlayer (Removing player: #{p.dumpStr()}, count=#{PlayerConnection.numPlayerConnections()})"
p.remove("You appear to be inactive,<br>so we are making room for another player")
if PlayerConnection.numPlayerConnections() >= Hy.Config.kMaxRemotePlayers
Hy.Trace.debug "PlayerConnection::makeRoomForPlayer (TOO MANY PLAYERS #{connection} Count=#{PlayerConnection.numPlayerConnections()})"
s = networkManager.findServiceByConnection(connection)
if s?
reason = "Too many remote players!<br>(Maximum is #{Hy.Config.kMaxRemotePlayers})"
s.service.sendSingle_(connection, "joinDenied", {reason: reason}, PlayerConnection.getLabelFromMessage(data), false)
status = false
return status
# ----------------------------------------------------------------------------------------------------------------
@checkPlayerVersion: (networkManager, connection, data)->
majorVersion = data.majorVersion
minorVersion = data.minorVersion
status = true
if !majorVersion? or (majorVersion < Hy.Config.Version.Remote.kMinRemoteMajorVersion)
Hy.Trace.debug "PlayerConnection::checkPlayerVersion (WRONG VERSION #{connection} Looking for #{Hy.Config.Version.Remote.kMinRemoteMajorVersion} Remote is version #{majorVersion}.#{minorVersion})"
s = networkManager.findServiceByConnection(connection)
if s?
s.service.sendSingle_(connection,"joinDenied", {reason: 'Update Required! Please visit the AppStore to update this app!'}, PlayerConnection.getLabelFromMessage(data))
status = false
return status
# ----------------------------------------------------------------------------------------------------------------
@getLabelFromMessage: (data)->
unescape(data.label)
# ----------------------------------------------------------------------------------------------------------------
constructor: (@networkManager, connection, data, @requiresActivityMonitor)->
gInstances.push this
@majorVersion = data.majorVersion
@minorVersion = data.minorVersion
@label = PlayerConnection.getLabelFromMessage(data)
@index = ++gInstanceCount
this.setConnection(connection)
Hy.Trace.debug "PlayerConnection::constructor (##{@index} label=/#{@label}/ tag=/#{@tag}/ count=#{_.size(gInstances)})"
if @requiresActivityMonitor
ActivityMonitor.addPlayerConnection(this)
this.activate()
this
# ----------------------------------------------------------------------------------------------------------------
getIndex: ()-> @index
# ----------------------------------------------------------------------------------------------------------------
getNetworkManager: ()-> @networkManager
# ----------------------------------------------------------------------------------------------------------------
getMajorVersion: ()-> @majorVersion
# ----------------------------------------------------------------------------------------------------------------
getMinorVersion: ()-> @minorVersion
# ----------------------------------------------------------------------------------------------------------------
checkVersion: (majorVersion, minorVersion=null)->
status = false
if @majorVersion >= majorVersion
if minorVersion?
if @minorVersion >= minorVersion
status = true
else
status = true
status
# ----------------------------------------------------------------------------------------------------------------
setConnection: (connection)->
@tag = connection.tag
@generatedTag = not @tag?
if @generatedTag
this.createTag()
this
# ----------------------------------------------------------------------------------------------------------------
resetConnection: (connection)->
# ----------------------------------------------------------------------------------------------------------------
getConnection: ()-> null
# ----------------------------------------------------------------------------------------------------------------
getTag: (tag)-> @tag
# ----------------------------------------------------------------------------------------------------------------
tagIsGenerated: ()-> @generatedTag
# ----------------------------------------------------------------------------------------------------------------
createTag: ()->
@generatedTag = true
found = true
while found
tag = Hy.Utils.UUID.generate()
found = PlayerConnection.findByTag(tag)?
Hy.Trace.debug "PlayerConnection::createTag (tag=#{tag})"
@tag = tag
# ----------------------------------------------------------------------------------------------------------------
getLabel: ()-> @label
# ----------------------------------------------------------------------------------------------------------------
compare: (connection)->
this.getKind() is connection.kind
# ----------------------------------------------------------------------------------------------------------------
getService: ()->
service = null
s = this.getNetworkManager().findService(this.getKind())
if s?
service = s.service
service
# ----------------------------------------------------------------------------------------------------------------
getKind: ()-> null
# ----------------------------------------------------------------------------------------------------------------
getStatus: ()-> @status
# ----------------------------------------------------------------------------------------------------------------
getStatusString: ()->
s = switch this.getStatus()
when PlayerConnection.kStatusActive
"active"
when PlayerConnection.kStatusInactive
"inactive"
when PlayerConnection.kStatusDisconnected
"disconnected"
else
"???"
s
# ----------------------------------------------------------------------------------------------------------------
setStatus: (newStatus)->
if newStatus isnt @status
@status = newStatus
s = switch @status
when PlayerConnection.kStatusActive
true
when PlayerConnection.kStatusInactive, PlayerConnection.kStatusDisconnected
false
else
false
this.getNetworkManager().doPlayerStatusChange(this.getIndex(), s)
@status
# ----------------------------------------------------------------------------------------------------------------
isActive: ()->
@status is PlayerConnection.kStatusActive
# ----------------------------------------------------------------------------------------------------------------
activate: ()->
this.setStatus(PlayerConnection.kStatusActive)
# ----------------------------------------------------------------------------------------------------------------
reactivate: ()->
this.activate()
# ----------------------------------------------------------------------------------------------------------------
# If "disconnected", means that the socket as closed or something similar
#
deactivate: (disconnected = false)->
this.setStatus(if disconnected then PlayerConnection.kStatusDisconnected else PlayerConnection.kStatusInactive)
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
this.deactivate()
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
# ----------------------------------------------------------------------------------------------------------------
remove: (warn=null)->
Hy.Trace.debug "PlayerConnection::remove (Removing #{this.dumpStr()} warn=#{warn})"
if @requiresActivityMonitor
ActivityMonitor.removePlayerConnection(this)
if warn?
service = this.getService()
if service?
service.sendSingle(this, "ejected", {reason:warn}, false)
gInstances = _.without(gInstances, this)
this.getService().doneWithPlayerConnection(this)
this.getNetworkManager().doRemovePlayer(this.getIndex())
null
# ----------------------------------------------------------------------------------------------------------------
dumpStr: ()->
"#{this.constructor.name}: ##{this.getIndex()} #{this.getLabel()} #{this.getStatusString()} #{this.getTag()}"
# ==================================================================================================================
class HTTPPlayerConnection extends PlayerConnection
# ----------------------------------------------------------------------------------------------------------------
@create: (networkManager, connection, data)->
if PlayerConnection.preAddPlayer(networkManager, connection, data)
new HTTPPlayerConnection(networkManager, connection, data)
else
null
# ----------------------------------------------------------------------------------------------------------------
constructor: (networkManager, connection, data)->
Hy.Trace.debug "HTTPPlayerConnection::constructor (ENTER)"
super networkManager, connection, data, true
Hy.Trace.debug "HTTPPlayerConnection::constructor (EXIT)"
this
# ----------------------------------------------------------------------------------------------------------------
setConnection: (connection)->
super
@socketID = connection.socketID
this
# ----------------------------------------------------------------------------------------------------------------
resetConnection: (connection)->
super
if connection.socketID isnt @socketID
@socketID = connection.socketID
this
# ----------------------------------------------------------------------------------------------------------------
getConnection: ()-> {kind:this.getKind(), socketID:@socketID}
# ----------------------------------------------------------------------------------------------------------------
getKind: ()-> PlayerNetwork.kKindHTTP
# ----------------------------------------------------------------------------------------------------------------
compare: (connection)->
result = super and (@socketID is connection.socketID)
result
# ----------------------------------------------------------------------------------------------------------------
dumpStr: ()->
super + " socketID=#{@socketID}"
# ==================================================================================================================
class BonjourPlayerConnection extends PlayerConnection
# ----------------------------------------------------------------------------------------------------------------
@create: (networkManager, connection, data)->
if PlayerConnection.preAddPlayer(networkManager, connection, data)
new BonjourPlayerConnection(networkManager, connection, data)
else
null
# ----------------------------------------------------------------------------------------------------------------
constructor: (networkManager, connection, data)->
Hy.Trace.debug "BonjourPlayerConnection::constructor"
# Should do a version check on the remote; if less than iOS 4, requires activityMonitor
super networkManager, connection, data, true
this
# ----------------------------------------------------------------------------------------------------------------
getConnection: ()-> {kind:this.getKind(), tag:@tag}
# ----------------------------------------------------------------------------------------------------------------
getKind: ()-> PlayerNetwork.kKindBonjour
# ----------------------------------------------------------------------------------------------------------------
compare:(connection)->
result = super and (@tag is connection.tag)
result
# ----------------------------------------------------------------------------------------------------------------
dumpStr: ()->
super
# ==================================================================================================================
class ActivityMonitor
gInstance = null
# ----------------------------------------------------------------------------------------------------------------
@start: (networkManager)->
if gInstance?
gInstance.stop()
new ActivityMonitor(networkManager)
# ----------------------------------------------------------------------------------------------------------------
@stop: ()->
if gInstance
gInstance.stop()
gInstance = null
null
# ----------------------------------------------------------------------------------------------------------------
@pause: ()->
if gInstance
gInstance.pause()
null
# ----------------------------------------------------------------------------------------------------------------
@resumed: ()->
if gInstance
gInstance.resumed()
null
# ----------------------------------------------------------------------------------------------------------------
@getTime: ()->
(new Date()).getTime()
# ----------------------------------------------------------------------------------------------------------------
@processReceivedMessage: (networkManager, messageInfo)->
if gInstance?
messageInfo = gInstance.processReceivedMessage(networkManager, messageInfo)
messageInfo
# ----------------------------------------------------------------------------------------------------------------
@addPlayerConnection: (pc)->
if gInstance?
gInstance.addPlayerConnection(pc)
null
# ----------------------------------------------------------------------------------------------------------------
@removePlayerConnection: (pc)->
if gInstance?
gInstance.removePlayerConnection(pc)
null
# ----------------------------------------------------------------------------------------------------------------
constructor: (@networkManager)->
# Hy.Trace.debug "ActivityMonitor::constructor"
gInstance = this
@playerConnections = []
@networkManager.addReceivedMessageProcessor(ActivityMonitor.processReceivedMessage)
this.startTimer()
this
# ----------------------------------------------------------------------------------------------------------------
startTimer: ()->
fnTick = ()=>this.tick()
@interval = setInterval(fnTick, Hy.Config.PlayerNetwork.ActivityMonitor.kCheckInterval)
# ----------------------------------------------------------------------------------------------------------------
clearTimer: ()->
if @interval?
clearInterval(@interval)
@interval = null
this
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
Hy.Trace.debug "ActivityMonitor::stop"
this.clearTimer()
@playerConnections = []
this
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
Hy.Trace.debug "ActivityMonitor::pause"
this.clearTimer()
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
Hy.Trace.debug "ActivityMonitor::resumed"
this.startTimer()
# ----------------------------------------------------------------------------------------------------------------
processReceivedMessage: (networkManager, messageInfo)->
# Hy.Trace.debug "ActivityMonitor::processReceivedMessage (#{messageInfo.op})"
if messageInfo.playerConnection?
p = this.updatePlayerConnection(messageInfo.playerConnection)
switch messageInfo.message.op
when "ping"
p.lastPing = messageInfo.message.data.pingCount
service = messageInfo.playerConnection.getService()
if service?
service.sendSingle(messageInfo.playerConnection, "ack", {pingCount:messageInfo.message.data.pingCount}, false)
messageInfo.handled = true
messageInfo
# ----------------------------------------------------------------------------------------------------------------
addPlayerConnection: (pc)->
if not this.updatePlayerConnection(pc)?
@playerConnections.push {playerConnection: pc, pingTimestamp:ActivityMonitor.getTime(), lastPing:null}
Hy.Trace.debug "ActivityMonitor::addPlayerConnection (size=#{_.size(@playerConnections)} Added:#{pc.dumpStr()})"
pc
# ----------------------------------------------------------------------------------------------------------------
updatePlayerConnection: (pc)->
p = _.detect(@playerConnections, (c)=>c.playerConnection is pc)
if p?
timeNow = ActivityMonitor.getTime()
Hy.Trace.debug "ActivityMonitor::updatePlayerConnection (Updated #{pc.dumpStr()} last heard from=#{timeNow-p.pingTimestamp} lastPing=#{p.lastPing})"
p.pingTimestamp = timeNow
pc.reactivate()
p
# ----------------------------------------------------------------------------------------------------------------
removePlayerConnection: (pc)->
# Why the following, <NAME>??
# @pingTimestamp = @pingTimestamp - 5*1000
@playerConnections = _.reject(@playerConnections, (p)=>p.playerConnection is pc)
# ----------------------------------------------------------------------------------------------------------------
tick: ()->
Hy.Trace.debug "ActivityMonitor::tick (#connections=#{_.size(@playerConnections)})"
for pc in @playerConnections
this.checkActivity(pc.playerConnection, pc.pingTimestamp, pc.lastPing)
null
# ----------------------------------------------------------------------------------------------------------------
checkActivity: (pc, pingTimestamp, lastPing)->
# this mechanism appears to be needed mostly for iPod 1Gs or perhaps anything else not running iOS 4+, and which
# don't send a "suspend" to the console when the button is pushed
fnTestActive = (pc, timeNow, pingTimestamp)->
((timeNow - pingTimestamp) <= Hy.Config.PlayerNetwork.ActivityMonitor.kThresholdActive)
fnTestAlive = (pc, timeNow, pingTimestamp)->
((timeNow - pingTimestamp) <= Hy.Config.PlayerNetwork.ActivityMonitor.kThresholdAlive)
timeNow = ActivityMonitor.getTime()
debugString = "#{pc.dumpStr()} last heard from=#{timeNow-pingTimestamp} lastPing=#{lastPing}"
if fnTestAlive(pc, timeNow, pingTimestamp)
switch pc.getStatus()
when PlayerConnection.kStatusActive
if not fnTestActive(pc, timeNow, pingTimestamp)
Hy.Trace.debug "PlayerConnection::checkActivity (Deactivating formerly active player #{debugString})"
pc.deactivate()
when PlayerConnection.kStatusInactive
if fnTestActive(pc, timeNow, pingTimestamp)
Hy.Trace.debug "PlayerConnection::checkActivity (Reactivating formerly inactive player #{debugString})"
pc.reactivate()
when PlayerConnection.Disconnected
# We do nothing here. If the player manages to reconnect, the join code will handle that
null
else
Hy.Trace.debug "ActivityMonitor::checkActivity (Removing #{debugString})"
pc.remove("You appear to be inactive")
# if !fnTestAlive(pc, timeNow, pingTimestamp)
# Hy.Trace.debug "ActivityMonitor::checkActivity (Removing #{pc.dumpStr()} #{timeNow-pingTimestamp})"
# pc.remove("You appear to be inactive")
# else if pc.isActive() and !fnTestActive(pc, timeNow, pingTimestamp)
# Hy.Trace.debug "PlayerConnection::checkActivity (Deactivating player #{pc.dumpStr()} #{timeNow-pingTimestamp})"
# pc.deactivate()
# else if !player.isActive() and fnTestActive(player)
# this.playerReactivate player
this
# ==================================================================================================================
# Abstract superclass for all player network types
# Each instance of a subtype of this type is managed by PlayerNetwork
#
# PlayerNetworkService
# HTTPPlayerService
# BonjourService
#
class PlayerNetworkService
# ----------------------------------------------------------------------------------------------------------------
constructor: (@networkManager)->
username = Ti.Platform.username
# to allow two simulators to run on the same network
if username is "iPad Simulator"
username = "#{username}-#{Hy.Utils.Math.random(10000)}"
@tag = escape username
this
# ----------------------------------------------------------------------------------------------------------------
start: ()->
Hy.Trace.debug "PlayerNetworkService::start"
this
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
Hy.Trace.debug "PlayerNetworkService::stop"
this
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
Hy.Trace.debug "PlayerNetworkService::pause"
this
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
Hy.Trace.debug "PlayerNetworkService::resumed"
this
# ----------------------------------------------------------------------------------------------------------------
getKind: ()-> null
# ----------------------------------------------------------------------------------------------------------------
setReady: ()->
Hy.Trace.debug "PlayerNetworkService::setReady (service=#{this.getKind()})"
@networkManager.setServiceReady(this)
# ----------------------------------------------------------------------------------------------------------------
getActivePlayers: ()->
PlayerConnection.getActivePlayersByServiceKind(this.getKind())
# ----------------------------------------------------------------------------------------------------------------
sendSingle_: (connection, op, data, label, requireAck=true)->
Hy.Trace.debug "PlayerNetworkService::sendSingle (#{this.constructor.name} op=#{op} label=#{label})"
# ----------------------------------------------------------------------------------------------------------------
sendSingle: (playerConnection, op, data, requireAck=true)->
this.sendSingle_(playerConnection.getConnection(), op, data, playerConnection.getLabel(), requireAck)
# ----------------------------------------------------------------------------------------------------------------
sendAll: (op, data, requireAck=true)->
Hy.Trace.debug "PlayerNetworkService::sendAll (#{this.constructor.name} op=#{op})"
# ----------------------------------------------------------------------------------------------------------------
doneWithPlayerConnection: (playerConnection)->
# ==================================================================================================================
class HTTPPlayerService extends PlayerNetworkService
# ----------------------------------------------------------------------------------------------------------------
constructor: (networkManager)->
super networkManager
this
# ----------------------------------------------------------------------------------------------------------------
getKind: ()-> PlayerNetwork.kKindHTTP
# ----------------------------------------------------------------------------------------------------------------
getPort: ()->
port = null
if @httpServer?
port = @httpServer.getPort()
port
# ----------------------------------------------------------------------------------------------------------------
start: ()->
Hy.Trace.debug "HTTPPlayerService::start"
fnServerReady = (server)=>this.setReady()
fnSocketOpened = (server, socketID)=> # Rely on clients to send 'join'
Hy.Trace.debug "HTTPPlayerService::fnSocketOpened (socket=#{socketID})"
null
fnSocketClosed = (server, socketID)=>
Hy.Trace.debug "HTTPPlayerService::fnSocketClosed (socket=#{socketID})"
pc = PlayerConnection.findByConnection({kind:this.getKind(), socketID:socketID})
# pc?.remove()
pc?.deactivate(true) # if the user refreshes the browser window, the socket is closed. Let's try to preserve the user's app state across that refresh
null
fnMessageReceived = (server, socketID, messageText)=>this.messageReceived(socketID, messageText)
fnServiceStatusChange = (status, domain, type_, name)=>this.serviceStatusChange(status, domain, type_, name)
@httpServer = Hy.Network.HTTPServerProxy.create(fnServerReady, fnSocketOpened, fnSocketClosed, fnMessageReceived, fnServiceStatusChange, Hy.Config.PlayerNetwork.HTTPServerRunsInOwnThread)
super
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
Hy.Trace.debug "HTTPPlayerService::stop"
@httpServer?.stop() # ?? for some reason, this doesn't work (error in the trivnet module at runtime)
@httpServer = null
super
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
Hy.Trace.debug "HTTPPlayerService::pause"
super
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
Hy.Trace.debug "HTTPPlayerService::resumed (#active=#{_.size(this.getActivePlayers())})"
# If we have resumed and the connections are still connected, then do nothing. Otherwise, restart
if _.size(this.getActivePlayers()) is 0
@httpServer?.restart()
this.setReady()
super
# ----------------------------------------------------------------------------------------------------------------
messageReceived: (socketID, messageText)->
try
message = JSON.parse messageText
catch e
@networkManager.doError("Error parsing HTTP message /#{messageText}/")
return null
@networkManager.messageReceived({kind:this.getKind(), socketID:socketID}, message)
null
# ----------------------------------------------------------------------------------------------------------------
serviceStatusChange: (status, domain, type_, name)->
Hy.Trace.debug "HTTPPlayerService::serviceStatusChange (#{status} #{domain} #{type_} #{name})"
serviceStatus = {}
switch status
when "bonjourPublishSuccess", "bonjourPublishFailure"
serviceStatus.bonjourPublish = {status: status, domain: domain, type_: type_, name: name}
@networkManager.doServiceStatusChange(serviceStatus)
this
# ----------------------------------------------------------------------------------------------------------------
getServiceStatus: ()-> @serviceStatus
# ----------------------------------------------------------------------------------------------------------------
sendSingle_: (connection, op, data, label, requireAck=true)->
# requireAck is not implemented
super
try
message = JSON.stringify src: @tag, op: op, data: data
@httpServer.sendMessage(connection.socketID, message)
catch e
@networkManager.doError("Error encoding HTTP message (connection=#{connection.socketID} op=#{op} tag=#{@tag} data=#{@data})")
this
# ----------------------------------------------------------------------------------------------------------------
sendAll: (op, data, requireAck=true)->
super
for p in this.getActivePlayers()
this.sendSingle(p, op, data, requireAck)
this
# ----------------------------------------------------------------------------------------------------------------
doneWithPlayerConnection: (playerConnection)->
super
# Should figure out a way to close the socket associated with this connection
# ==================================================================================================================
class BonjourService extends PlayerNetworkService
# ----------------------------------------------------------------------------------------------------------------
constructor: (networkManager)->
super networkManager
Hy.Trace.debug "BonjourService::constructor"
this
# ----------------------------------------------------------------------------------------------------------------
getKind: ()-> PlayerNetwork.kKindBonjour
# ----------------------------------------------------------------------------------------------------------------
startBonjourNetwork: ()->
this.openSocket()
this.publishService()
this
# ----------------------------------------------------------------------------------------------------------------
stopBonjourNetwork: ()->
if @localService?
@localService.stop()
@localService = null
if @socket?
if @socket.isValid
@socket.close()
@socket = null
this
# ----------------------------------------------------------------------------------------------------------------
start: ()->
Hy.Trace.debug "BonjourService::start"
this.startBonjourNetwork()
@messageQueue = MessageQueue.create(@networkManager, this)
this.setReady()
super
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
Hy.Trace.debug "BonjourService::stop"
this.stopBonjourNetwork()
@messageQueue.stop()
super
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
Hy.Trace.debug "BonjourService::pause"
this.stop()
super
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
Hy.Trace.debug "BonjourService::resumed"
this.start()
super
# ----------------------------------------------------------------------------------------------------------------
dumpSocket: ()->
(Hy.Trace.debug "socket.#{prop} => #{val}") for prop, val of @socket
Hy.Trace.debug "socket.isValid => #{@socket.isValid}"
Hy.Trace.debug "socket.mode => #{@socket.mode}"
Hy.Trace.debug "socket.port => #{@socket.port}"
Hy.Trace.debug "socket.hostName => #{@socket.hostName}"
# ----------------------------------------------------------------------------------------------------------------
openSocket: ()->
Hy.Trace.debug "BonjourService::openSocket"
@socket = Ti.Network.createTCPSocket(hostName:Hy.Config.Bonjour.hostName, mode:Hy.Config.Bonjour.mode, port:Hy.Config.Bonjour.port)
fnRead = (evt)=>
this.messageReceived(evt)
null
@socket.addEventListener 'read', fnRead
# @socket.stripTerminator = true
fnReadError = (evt)=>
@networkManager.doError("Bonjour READ ERROR (code=#{evt.code}/#{evt.error}/#{evt.type})")
null
@socket.addEventListener 'readError', fnReadError
fnWriteError = (evt)=>
@networkManager.doError("Bonjour WRITE ERROR (code=#{evt.code}/#{evt.error}/#{evt.type})")
null
@socket.addEventListener 'writeError', fnWriteError
@socket.listen()
# ----------------------------------------------------------------------------------------------------------------
publishService: ()->
Hy.Trace.debug "BonjourService::publishService"
@localService = Ti.Network.createBonjourService name:@tag, type:Hy.Config.Bonjour.serviceType, domain:Hy.Config.Bonjour.domain
try
@localService.publish @socket
catch error
@networkManager.doError("Bonjour Open Error", true)
this
# ----------------------------------------------------------------------------------------------------------------
parseForMultiple: (text)->
level = 0
results = []
out = ""
for c in text
if c.charCodeAt(0) is 0
null
else
switch c
when '{'
level++
when '}'
level--
out += c
if level is 0
results.push out
out = ""
return results
# ----------------------------------------------------------------------------------------------------------------
messageReceived: (evt)->
text = "UNKNOWN"
text = evt.data.text
# Hy.Trace.debug "BonjourService::messageReceived (length=#{text.length} last=#{text.charCodeAt(text.length-1)})"
# "suddenly", started seeing null bytes at the end of these strings, and multiple messages at the same time - 2011-08-12
if text.charCodeAt(text.length-1) isnt 125 # 125=}
text = text.substring(0, text.length-1)
results = this.parseForMultiple(text)
for r in results
try
message = JSON.parse r
catch e
@networkManager.doError("Error parsing Bonjour message /#{text}/")
return null
if (message.dest is 0) or (message.dest isnt @tag)
null
else
Hy.Trace.debug "BonjourService::messageReceived (message=#{r})"
@networkManager.messageReceived({kind:this.getKind(), tag:message.src}, message)
null
# ----------------------------------------------------------------------------------------------------------------
sendSingle_: (connection, op, data, label, requireAck=true)->
super
message = new Message(@tag, op, data, requireAck, false)
message.addDest(connection.tag, label)
this.sendMessage message
# ----------------------------------------------------------------------------------------------------------------
sendAll: (op, data, requireAck=true)->
super op, data
# Hy.Trace.info "BonjourService::sendMultipleClients(op=#{op} data=#{JSON.stringify(data)})"
players = this.getActivePlayers()
if _.size(players) isnt 0
message = new Message(@tag, op, data, requireAck, true)
for player in players
message.addDest(player.getConnection().tag, player.label)
this.sendMessage(message)
this
# ----------------------------------------------------------------------------------------------------------------
sendMessage: (message)->
# Hy.Trace.info "BonjourService::sendMessage (#{message.dump()})"
message.send(@socket)
if message.requireAck
@messageQueue.insert(message)
this
# ==================================================================================================================
class Message
messageCount = 0
# ----------------------------------------------------------------------------------------------------------------
constructor: (@src, @op, @data, @requireAck, @isBroadcast)->
messageCount++
@id = messageCount
@dests = []
@createTime = (new Date()).getTime()
@sendCount = 0
@sentTime = null
@broadcastPartiallyAckd = false # set true if we receive at least one response to a broadcast
this
# ----------------------------------------------------------------------------------------------------------------
addDest: (tag, label)->
@dests.push {tag: tag, label: label, ack: false, ackCount: 0}
# ----------------------------------------------------------------------------------------------------------------
getPacket: (tag)->
try
p = JSON.stringify m: @id, count: @sendCount, src: @src, dest: tag, op: @op, data: @data
catch e
Hy.Trace.info "Message::getPacket (ERROR could not encode packet data=#{@data})"
p = ""
p
# ----------------------------------------------------------------------------------------------------------------
getPacket2: (isBroadcast=false)->
tags = []
if not isBroadcast
for d in @dests
tags.push d.tag
try
p = JSON.stringify m: @id, count: @sendCount, src: @src, dest: tags, op: @op, data: @data
# Hy.Trace.info "Message::getPacket (packet=#{p})"
catch e
Hy.Trace.info "Message::getPacket (ERROR could not encode packet data=#{@data})"
p = ""
p
# ----------------------------------------------------------------------------------------------------------------
send: (socket)->
# Hy.Trace.info "Message:send (ENTER #{this.dump()})"
@sentTime = (new Date().getTime())
@sendCount++
dest = null
if 1 # Trying to reduce network traffic by making it possible for a message to target multiple clients
if @isBroadcast and not @broadcastPartiallyAckd
socket.write this.getPacket2(true)
Hy.Trace.info "Message:send (Broadcast #{this.dump()})"
else
socket.write this.getPacket2()
Hy.Trace.info "Message:send (Direct #{this.dump()})"
else
if @isBroadcast and not @broadcastPartiallyAckd
socket.write this.getPacket(0)
Hy.Trace.info "Message:send (Broadcast #{this.dump()})"
else
for dest in @dests
Hy.Trace.info "Message:send (Direct to #{dest.label} #{this.dump()})"
socket.write this.getPacket(dest.tag)
# Hy.Trace.info "Message:send (EXIT #{this.dump()})"
# ----------------------------------------------------------------------------------------------------------------
hasDest: (tag)->
for dest in @dests
if dest.tag is tag
return dest
return null
# ----------------------------------------------------------------------------------------------------------------
setAck: (tag, messageCount)->
ackdBefore = false
ackCount = 0
if @isBroadcast
@broadcastPartiallyAckd = true
dest = this.hasDest tag
if dest?
if dest.ack
ackdBefore = true
else
@ack = (new Date()).getTime()
dest.ack = true
dest.ackCount = messageCount
ackCount = dest.ackCount
# Hy.Trace.info "Message:setAck (#{if ackdBefore then "NOT THE FIRST TIME" else ""} label=#{dest.label} message=#{@id} op=#{@op} createTime=#{this.dumpCreateTime()} sendCount=#{@sendCount} ackCount=#{dest.ackCount})"
else
Hy.Trace.info "Message:setAck (Unexpected Ack: tag=#{tag} message=#{@id})"
ackCount
# ----------------------------------------------------------------------------------------------------------------
removeAckdDests: ()->
if @dests.length>0
newDests = _.reject @dests, (d)=>d.ack
@dests = newDests
return @dests.length > 0
# ----------------------------------------------------------------------------------------------------------------
removeDest: (tag)->
if @dests.length>0
newDests = _.reject @dests, (d)=>d.tag is tag
@dests = newDests
return @dests.length > 0
# ----------------------------------------------------------------------------------------------------------------
removeDests: ()->
@dests= {}
this
# ----------------------------------------------------------------------------------------------------------------
removeDestsInCommon: (message)->
# Hy.Trace.info "Message:removeDestInCommon (ENTER)"
if @dests.length is 0 or message.dests.length is 0
return
newDests = []
for d in @dests
if _.detect(message, (d1)=>d1.tag is d.tag)?
Hy.Trace.info "Message:removeDestsInCommon (Message=#{message.id} in common with #{@id}: Removing #{d.label})"
else
newDests.push d
@dests = newDests
this
# ----------------------------------------------------------------------------------------------------------------
hasOutstandingDests: ()->
@dests.length > 0
# ----------------------------------------------------------------------------------------------------------------
getNumDests: ()->
@dests.length
# ----------------------------------------------------------------------------------------------------------------
dumpCreateTime: ()->
now = (new Date()).getTime()
if @createTime? then ("#{now-this.createTime} milliseconds ago") else "(NO CREATE TIME)"
# ----------------------------------------------------------------------------------------------------------------
dumpSentTime: ()->
now = (new Date()).getTime()
if @sentTime? then ("#{now-@sentTime} milliseconds ago") else "NOT SENT"
# ----------------------------------------------------------------------------------------------------------------
dump: ()->
output = "Message=#{@id} op=#{@op} Broadcast=#{@isBroadcast}/#{@broadcastPartiallyAckd} create=#{this.dumpCreateTime()} AckRequired=#{if @requireAck then 'Yes' else 'No'} sent=#{this.dumpSentTime()} sendCount=#{@sendCount} #dests=#{@dests.length} "
count = 0
for dest in @dests
count++
a = if dest.ack then "ACKd" else "NOT ACKd"
output += "/##{count}: label=#{dest.label} ack=#{a} ackCount=#{dest.ackCount}/ "
output
# ==================================================================================================================
class MessageQueue
gInstance = null
kMessageDeliveryThreshold = 1500
kMaxSendAttempts = 5
# ----------------------------------------------------------------------------------------------------------------
@create: (networkManager, networkService)->
new MessageQueue(networkManager, networkService)
# ----------------------------------------------------------------------------------------------------------------
@processReceivedMessage: (networkManager, messageInfo)->
# Hy.Trace.debug "MessageQueue::processReceivedMessage (#{messageInfo.message.op})"
switch messageInfo.message.op
when "ack2"
messageInfo.handled = true
if messageInfo.playerConnection?
if gInstance?
gInstance.ackReceived(messageInfo.message.data.m, messageInfo.message.data.count, messageInfo.connection.tag)
messageInfo
# ----------------------------------------------------------------------------------------------------------------
constructor: (@networkManager, @networkService)->
# Hy.Trace.info "MessageQueue::constructor"
gInstance = this
@messages = []
@networkManager.addReceivedMessageProcessor(MessageQueue.processReceivedMessage)
this.initStats()
f = ()=>if @messages.length > 0 then this.check()
@interval = null
@interval = setInterval f, kMessageDeliveryThreshold
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
# Hy.Trace.debug "MessageQueue::stop"
clearInterval @interval if @interval?
@interval = null
@messages = []
this.initStats()
# ----------------------------------------------------------------------------------------------------------------
initStats: ()->
# Note that we count each destination in a broadcast as a separate message
@numberOfSentMessages = 0 # Total number of messages sent with "ack required" set
@numberOfResentMessages = 0 # Total number of messages sent more than once
@numberOfAckdMessages = 0 # Total number of messages ack'd
@numberOfAckdOnFirstSendMessages = 0 # Total number of messages ack'd after first send
@totalFirstSendAckdTime = 0 # For all messages ack'd after first send, sum of time between send and ack
@numberOfAckdOnRetryMessages = 0 # Total number of messages ack'd after one or more retries
@totalRetryTime = 0 # For all messages sent more than once, sum of time between send and ack
@numberOfFailedMessages = 0 # Total number of messages we've given up trying to resend
# ----------------------------------------------------------------------------------------------------------------
dumpStats: ()->
stat = "Sent/Ackd/Resent/Failed=#{@numberOfSentMessages}/#{@numberOfAckdMessages}/#{@numberOfResentMessages}/#{@numberOfFailedMessages} "
stat += "1st Send Ackd=#{@numberOfAckdOnFirstSendMessages} Ave=#{@totalFirstSendAckdTime/@numberOfAckdOnFirstSendMessages} secs "
stat += "Ackd after Retry=#{@numberOfAckdOnRetryMessages} Ave=#{@totalRetryTime/@numberOfAckdOnRetryMessages} secs"
stat
# ----------------------------------------------------------------------------------------------------------------
dump: ()->
for message in @messages
Hy.Trace.info "MessageQueue::dump (#{message.dump()})"
this
# ----------------------------------------------------------------------------------------------------------------
insert: (message)->
# Hy.Trace.info "MessageQueue::insert"
# Broadcast messages trump all previous messages, except 'welcome'
if message.isBroadcast and not message.broadcastPartiallyAckd
m = _.select @messages, (m)=>m.op is 'welcome'
# Hy.Trace.info "MessageQueue::insert (Broadcast inserted, was #{@messages.length} now #{m.length})"
@messages = m
else
for m in @messages
m.removeDestsInCommon message
@messages.push message
@numberOfSentMessages += message.getNumDests()
# Hy.Trace.info "MessageQueue::insert (EXIT)"
this
# ----------------------------------------------------------------------------------------------------------------
ackReceived: (messageId, messageCount, tag)->
for message in @messages
if message.id is messageId
ackCount = message.setAck(tag, messageCount)
t = message.ack - message.createTime
if ackCount is 1
@numberOfAckdOnFirstSendMessages++
@totalFirstSendAckdTime += t
else
@numberOfAckdOnRetryMessages++
@totalRetryTime += t
@numberOfAckdMessages++
return
this
# ----------------------------------------------------------------------------------------------------------------
check: ()->
# Hy.Trace.debug "MessageQueue::check (ENTERING number of messages=#{@messages.length} #{this.dumpStats()})"
timeNow = (new Date()).getTime()
messagesToCheckLater = []
messagesToResendNow = []
for message in @messages
# First, remove all clients that have ackd this message
if message.removeAckdDests()
# Then, remove all destinations representing clients that aren't active
for p in @networkService.getActivePlayers()
if !p.isActive()
message.removeDest p.tag
# If there are still outstanding destinations, then have we reached the resend limit?
if message.hasOutstandingDests()
if message.sendCount is kMaxSendAttempts
Hy.Trace.debug "MessageQueue::check (Message - too many retries: #{message.dump()})"
@numberOfFailedMessages += message.getNumDests()
else
# Decide whether to resend now or later
t = message.sentTime
if t?
if (timeNow - t) > kMessageDeliveryThreshold
messagesToResendNow.push message
else
messagesToCheckLater.push message
else
Hy.Trace.debug "MessageQueue::check (Message not sent! #{message.dump()})"
messagesToCheckLater.push message
@messages = []
@messages = messagesToCheckLater
for message in messagesToResendNow #should be safe to iterate while appending
Hy.Trace.debug "MessageQueue::check (Resending message: #{message.dump()})"
@numberOfResentMessages += message.getNumDests()
@networkService.sendMessage message
# Hy.Trace.debug "MessageQueue::check (EXITING number of messages=#{@messages.length})"
# this.dump()
# ==================================================================================================================
# assign to global namespace:
if not Hy.Network?
Hy.Network = {}
Hy.Network.PlayerNetwork = PlayerNetwork
| true | # TODO
# Factor out Message, MessageQueue so that these can be used for HTTP as well, if necessary
# Figure out how to stop HTTP Service
# Figure out how to close a socket associated with an HTTP user that has been removed
# Abstract various message types, refactor used of "messageInfo"
#
#
# message = <connection><data>
#
# <connection> = <core_connection> [<bonjour_connection> | <http_connection>]
# <core_connection> = tag:
# <bonjour_connection> = dest:value + ??
#
# ==================================================================================================================
# Abstracts all player network interactions. A single instance is created, running in its own thread,
# when the application is initialized, via the .js file "player_network_stub.js", which is attached to a
# standalone window (and therefore runs in its own thread).
#
# The main app communicates with this instance via the "PlayerNetworkProxy" class; PlayerNetworkProxy" and "PlayerNetwork"
# fire/listen for events across the thread boundaries.
#
#
# Manages an instance of Bonjour network service, HTTP nework service for players, etc.
#
# Responds to these global events:
# "playerNetwork_Stop" {}
# "playerNetwork_Pause" {}
# "playerNetwork_Resumed" {}
# "playerNetwork_SendSingle" {connectionIndex, op, data}
# "playerNetwork_SendAll" {op, data}
#
# Fires these global events
#
# "playerNetwork_Ready" {httpPort}
# "playerNetwork_Error" {error, restartNetwork}
# "playerNetwork_MessageReceived" {playerConnectionIndex, op, data}
# "playerNetwork_AddPlayer" {playerConnectionIndex, playerLabel}
# "playerNetwork_RemovePlayer" {playerConnectionIndex}
# "playerNetwork_PlayerStatusChange" {playerConnectionIndex, status}
# "playerNetwork_ServiceStatusChange" {serviceStatus}
#
class PlayerNetwork
@kKindHTTP = 1
@kKindBonjour = 2
# ----------------------------------------------------------------------------------------------------------------
# Methods below are "private" or "protected", used only by this class and friends
# ----------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------
constructor: ()->
this.init()
this.initHandlers()
this
# ----------------------------------------------------------------------------------------------------------------
init: ()->
@receivedMessageProcessors = []
@sentMessageProcessors = []
this.startServices()
PlayerConnection.start(this)
ActivityMonitor.start(this)
this
# ----------------------------------------------------------------------------------------------------------------
startServices: ()->
@services = []
s1 = {kind: PlayerNetwork.kKindHTTP}
s2 = {kind: PlayerNetwork.kKindBonjour}
@services.push s1
# @services.push s2 # No bonjour discovery for V2
@serviceWatchdog = new ServiceStartupWatchdog(this)
s1.service = (new HTTPPlayerService(this)).start()
# s2.service = (new BonjourService(this)).start()
this
# ----------------------------------------------------------------------------------------------------------------
# After a "stop", can not restart the same instance. Must start over again with a new instance
#
stop: ()->
for s in @services
s.service?.stop()
@serviceWatchdog?.stop()
ActivityMonitor.stop()
PlayerConnection.stop()
this
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
@serviceWatchdog?.pause()
for s in @services
s.service?.pause()
ActivityMonitor.pause()
PlayerConnection.pause()
this
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
@serviceWatchdog?.resumed()
for s in @services
s.service?.resumed()
PlayerConnection.resumed()
ActivityMonitor.resumed()
this
# ----------------------------------------------------------------------------------------------------------------
initHandlers: ()->
Ti.App.addEventListener("playerNetwork_Stop",
(e)=>
this.stop()
null)
Ti.App.addEventListener("playerNetwork_Pause",
(e)=>
this.pause()
null)
Ti.App.addEventListener("playerNetwork_Resumed",
(e)=>
this.resumed()
null)
Ti.App.addEventListener("playerNetwork_SendSingle",
(e)=>
this.sendSingle(e.connectionIndex, e.op, e.data)
null)
Ti.App.addEventListener("playerNetwork_SendAll",
(e)=>
this.sendAll(e.op, e.data)
null)
this
# ----------------------------------------------------------------------------------------------------------------
setServiceReady: (service)->
@serviceWatchdog?.serviceCheckin(service)
# ----------------------------------------------------------------------------------------------------------------
sendSingle: (connectionIndex, op, data)->
playerConnection = PlayerConnection.findByIndex(connectionIndex)
# We use an anonymous object, "messageInfo", to group together message-related info, which
# allows message processors to rewrite the data as necesssary before it's sent off.
# TODO: consider abstracting messages into a hierarchy of sorts, to keep this a little
# more sane.
message = {op:op, data:data}
messageInfo = {playerConnection:playerConnection, message:message, handled:false}
messageInfo = this.doSentMessageProcessors(messageInfo)
if messageInfo.playerConnection?
service = messageInfo.playerConnection.getService()
if service?
# Hy.Trace.debug "PlayerNetwork::sendSingle (op=#{messageInfo.message.op} #{messageInfo.playerConnection.dumpStr()})"
service.sendSingle(messageInfo.playerConnection, messageInfo.message.op, messageInfo.message.data)
else
Hy.Trace.debug "PlayerNetwork::sendSingle (ERROR NO SERVICE for #{connectionIndex})"
else
Hy.Trace.debug "PlayerNetwork::sendSingle (ERROR CANT FIND PlayerConnection for #{connectionIndex})"
this
# ----------------------------------------------------------------------------------------------------------------
sendAll: (op, data)->
Hy.Trace.debug "PlayerNetwork::sendAll (op=#{op})"
message = {op:op, data:data}
messageInfo = {message:message, handled:false}
messageInfo = this.doSentMessageProcessors(messageInfo)
for s in @services
s.service?.sendAll(messageInfo.message.op, messageInfo.message.data)
this
# ----------------------------------------------------------------------------------------------------------------
doReady: ()->
httpPlayerService = this.findService(PlayerNetwork.kKindHTTP)
if httpPlayerService?
port = httpPlayerService.service.getPort()
Ti.App.fireEvent("playerNetwork_Ready", {httpPort:port})
# ----------------------------------------------------------------------------------------------------------------
doError: (error, restartNetwork=false)->
Hy.Trace.debug "PlayerNetwork::doError (ERROR /#{error}/ restartNetwork=#{restartNetwork})"
Ti.App.fireEvent("playerNetwork_Error", {error:error, restartNetwork:restartNetwork})
this
# ----------------------------------------------------------------------------------------------------------------
doMessageReceived: (playerConnectionIndex, op, data)->
Hy.Trace.debug "PlayerNetwork::doMessageReceived (op=#{op} data=#{data})"
Ti.App.fireEvent("playerNetwork_MessageReceived", {playerConnectionIndex:playerConnectionIndex, op:op, data:data})
this
# ----------------------------------------------------------------------------------------------------------------
doAddPlayer: (playerConnectionIndex, playerLabel, majorVersion, minorVersion)->
Hy.Trace.debug "PlayerNetwork::doAddPlayer (##{playerConnectionIndex}/#{playerLabel})"
Ti.App.fireEvent("playerNetwork_AddPlayer", {playerConnectionIndex:playerConnectionIndex, playerLabel:playerLabel, majorVersion:majorVersion, minorVersion:minorVersion})
this
# ----------------------------------------------------------------------------------------------------------------
doRemovePlayer: (playerConnectionIndex)->
Ti.App.fireEvent("playerNetwork_RemovePlayer", {playerConnectionIndex:playerConnectionIndex})
this
# ----------------------------------------------------------------------------------------------------------------
doPlayerStatusChange: (playerConnectionIndex, status)->
Ti.App.fireEvent("playerNetwork_PlayerStatusChange", {playerConnectionIndex:playerConnectionIndex, status:status})
this
# ----------------------------------------------------------------------------------------------------------------
doServiceStatusChange: (serviceStatus)->
Ti.App.fireEvent("playerNetwork_ServiceStatusChange", {serviceStatus: serviceStatus})
this
# ----------------------------------------------------------------------------------------------------------------
getServices: ()->
@services
# ----------------------------------------------------------------------------------------------------------------
findService: (kind)->
_.detect(@services, (s)=>s.kind is kind)
# ----------------------------------------------------------------------------------------------------------------
findServiceByConnection: (connection)->
this.findService(connection.kind)
# ----------------------------------------------------------------------------------------------------------------
addReceivedMessageProcessor: (fn)->
@receivedMessageProcessors.push fn
# ----------------------------------------------------------------------------------------------------------------
addSentMessageProcessor: (fn)->
@sentMessageProcessors.push fn
# ----------------------------------------------------------------------------------------------------------------
doMessageProcessors: (list, messageInfo)->
for fn in list
messageInfo = fn(this, messageInfo)
messageInfo
# ----------------------------------------------------------------------------------------------------------------
doReceivedMessageProcessors: (messageInfo)->
this.doMessageProcessors(@receivedMessageProcessors, messageInfo)
# ----------------------------------------------------------------------------------------------------------------
doSentMessageProcessors: (messageInfo)->
this.doMessageProcessors(@sentMessageProcessors, messageInfo)
# ----------------------------------------------------------------------------------------------------------------
messageReceived: (connection, message)->
playerConnection = PlayerConnection.findByConnection(connection)
# Hy.Trace.debug "PlayerNetwork::messageReceived (/#{message.op}/ from #{if playerConnection? then playerConnection.dumpStr() else connection.kind})"
# We use an anonymous object, "messageInfo", to group together message-related info, which
# allows message processors to rewrite the data as necesssary before it's sent off.
# TODO: consider abstracting messages into a hierarchy of sorts, to keep this a little
# more sane.
messageInfo = {connection:connection, playerConnection:playerConnection, message:message, handled:false}
messageInfo = this.doReceivedMessageProcessors(messageInfo)
if not messageInfo.handled
if messageInfo.playerConnection?
this.doMessageReceived(messageInfo.playerConnection.getIndex(), messageInfo.message.op, messageInfo.message.data)
else
this.doError("Unhandled message Received from unknown player (op=#{messageInfo.message.op}")
this
# ==================================================================================================================
class ServiceStartupWatchdog
kServiceStartupTimeout = 15 * 1000
# ----------------------------------------------------------------------------------------------------------------
constructor: (@networkManager)->
this.initState()
this.setTimer()
this
# ----------------------------------------------------------------------------------------------------------------
initState: ()->
@paused = false
@ready = false
@failed = false
this.clearReadyState()
this.clearTimer()
this
# ----------------------------------------------------------------------------------------------------------------
clearTimer: ()->
if @timer?
@timer.clear()
@timer = null
this
# ----------------------------------------------------------------------------------------------------------------
clearReadyState: ()->
for s in @networkManager.getServices()
s.ready = false
this
# ----------------------------------------------------------------------------------------------------------------
setTimer: ()->
this.clearTimer()
@timer = Hy.Utils.Deferral.create(kServiceStartupTimeout, ()=>this.timerExpired())
this
# ----------------------------------------------------------------------------------------------------------------
timerExpired: ()->
snr = this.servicesNotReady()
if _.size(snr) is 0
@ready = true # Should never get here
else
@failed = true
failedServices = ""
for s in snr
failedServices += "#{s.kind} "
@networkManager.doError("Player network services did not start in time: #{failedServices}", true)
this
# ----------------------------------------------------------------------------------------------------------------
servicesNotReady: ()->
_.select(@networkManager.getServices(), (s)=>not s.ready)
# ----------------------------------------------------------------------------------------------------------------
serviceCheckin: (service)->
s = @networkManager.findService(service.getKind())
if s?
s.ready = true
snr = this.servicesNotReady()
Hy.Trace.debug "ServiceStartupWatchdog::serviceCheckin (service=#{service.getKind()} # not ready = #{_.size(snr)})"
if _.size(snr) is 0
@ready = true
this.clearTimer()
@networkManager.doReady()
this
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
this.clearTimer()
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
this.clearTimer()
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
this.initState()
this.setTimer()
# ==================================================================================================================
# Abstract superclass representing what we need to keep track of a player's connection to the app.
#
# PlayerConnection
# HTTPPlayerConnection
# BonjourPlayerConnection
class PlayerConnection
gInstanceCount = 0
gInstances = []
@kStatusActive = 1
@kStatusInactive = 2
@kStatusDisconnected = 3 # when a remote has disconnected... we allow some time to reconnect
# ----------------------------------------------------------------------------------------------------------------
@start: (networkManager)->
gInstances = []
gInstanceCount = 0
networkManager.addReceivedMessageProcessor(PlayerConnection.processReceivedMessage)
networkManager.addSentMessageProcessor(PlayerConnection.processSentMessage)
# ----------------------------------------------------------------------------------------------------------------
@stop: ()->
for pc in PlayerConnection.getPlayerConnections()
pc.stop()
gInstances = []
null
# ----------------------------------------------------------------------------------------------------------------
@pause: ()->
for pc in PlayerConnection.getPlayerConnections()
pc.pause()
null
# ----------------------------------------------------------------------------------------------------------------
@resumed: ()->
for pc in PlayerConnection.getPlayerConnections()
pc.resumed()
# ----------------------------------------------------------------------------------------------------------------
@processReceivedMessage: (networkManager, messageInfo)->
# Hy.Trace.debug "PlayerConnection::processReceivedMessage (#{messageInfo.message.op})"
switch messageInfo.message.op
when "suspend" # HTTP clients don't send this
messageInfo.handled = true
if messageInfo.playerConnection?
Hy.Trace.debug "PlayerConnection::processReceivedMessage (suspend #{messageInfo.playerConnection.dumpStr()})"
messageInfo.playerConnection.deactivate(true)
when "resumed" # HTTP clients don't send this
messageInfo.handled = true
if messageInfo.playerConnection?
Hy.Trace.debug "PlayerConnection::processReceivedMessage (resumed #{messageInfo.playerConnection.dumpStr()})"
when "join"
messageInfo.handled = true
messageInfo = PlayerConnection.join(networkManager, messageInfo)
messageInfo
# ----------------------------------------------------------------------------------------------------------------
@processSentMessage: (networkManager, messageInfo)->
Hy.Trace.debug "PlayerConnection::processSentMessage (#{messageInfo.message.op})"
switch messageInfo.message.op
when "welcome"
messageInfo.handled = true
if messageInfo.playerConnection? and messageInfo.playerConnection.tagIsGenerated()
# We add in the tag, which we generated and which is assigned to some clients, such as those connected via HTTP.
# Other clients (Bonjour) tell us their tags when they send a join message (and so this is redundant).
# This is a legacy situation.
messageInfo.message.data.assignedTag = messageInfo.playerConnection.getTag()
messageInfo
# ----------------------------------------------------------------------------------------------------------------
@join: (networkManager, messageInfo)->
if not messageInfo.playerConnection?
# Is this a request from a player we've already seen? Check the tag
tag = messageInfo.message.tag
if tag?
messageInfo.playerConnection = PlayerConnection.findByTag(tag)
if messageInfo.playerConnection?
# An existing player may be rejoining over a different socket, etc.
PlayerConnection.swap(messageInfo.playerConnection, messageInfo.connection)
else
messageInfo.playerConnection = PlayerConnection.create(networkManager, messageInfo.connection, messageInfo.message.data)
# We always send a "welcome" when we receive a join
if messageInfo.playerConnection?
networkManager.doAddPlayer(messageInfo.playerConnection.getIndex(), messageInfo.playerConnection.getLabel(), messageInfo.playerConnection.getMajorVersion(), messageInfo.playerConnection.getMinorVersion())
messageInfo
# ----------------------------------------------------------------------------------------------------------------
# If an existing player connects over a new socket. We want to keep the higher-level player state while swapping
# out the specifics of the connection.
#
@swap: (playerConnection, newConnection)->
# Tell the current remote to go away
playerConnection.getService().sendSingle(playerConnection, "ejected", {reason:"You connected in another browser window"}, false)
# Swap in our new connection info, the higher-level app code won't know the difference
playerConnection.resetConnection(newConnection)
# Will result in the console app doing a reactivate, and then sending a welcome. A little wierd.
playerConnection.activate()
this
# ----------------------------------------------------------------------------------------------------------------
@create: (networkManager, connection, data)->
playerConnection = null
t = null
switch connection.kind
when PlayerNetwork.kKindHTTP
t = HTTPPlayerConnection
when PlayerNetwork.kKindBonjour
t = BonjourPlayerConnection
if t?
playerConnection = t.create(networkManager, connection, data)
playerConnection
# ----------------------------------------------------------------------------------------------------------------
@getPlayerConnections: ()->
gInstances
# ----------------------------------------------------------------------------------------------------------------
@numPlayerConnections: ()->
_.size(gInstances)
# ----------------------------------------------------------------------------------------------------------------
@findByConnection: (connection)->
_.detect(PlayerConnection.getPlayerConnections(), (pc)=>pc.compare(connection))
# ----------------------------------------------------------------------------------------------------------------
@findByIndex: (index)->
_.detect(PlayerConnection.getPlayerConnections(), (pc)=>pc.getIndex() is index)
# ----------------------------------------------------------------------------------------------------------------
@findByTag: (tag)->
_.detect(PlayerConnection.getPlayerConnections(), (pc)=>pc.getTag() is tag)
# ----------------------------------------------------------------------------------------------------------------
@getActivePlayerConnections: ()->
_.select(PlayerConnection.getPlayerConnections(), (pc)->pc.isActive())
# ----------------------------------------------------------------------------------------------------------------
@getActivePlayersByServiceKind: (kind)->
_.select(PlayerConnection.getPlayerConnections(), (pc)->(pc.isActive()) and (pc.getKind() is kind))
# ----------------------------------------------------------------------------------------------------------------
# Does some basic checks before we allow a new remote player to join
#
@preAddPlayer: (networkManager, connection, data)->
status = true
# Check version
status = status and PlayerConnection.checkPlayerVersion(networkManager, connection, data)
# Are we at player limit?
status = status and PlayerConnection.makeRoomForPlayer(networkManager, connection, data)
status
# ----------------------------------------------------------------------------------------------------------------
@makeRoomForPlayer: (networkManager, connection, data)->
status = true
if PlayerConnection.numPlayerConnections() >= Hy.Config.kMaxRemotePlayers
Hy.Trace.debug "PlayerConnection::makeRoomForPlayer (count=#{PlayerConnection.numPlayerConnections()} limit=#{Hy.Config.kMaxRemotePlayers})"
toRemove = []
for p in PlayerConnection.getPlayerConnections()
if !p.isActive()
toRemove.push p
for p in toRemove
Hy.Trace.debug "PlayerConnection::makeRoomForPlayer (Removing player: #{p.dumpStr()}, count=#{PlayerConnection.numPlayerConnections()})"
p.remove("You appear to be inactive,<br>so we are making room for another player")
if PlayerConnection.numPlayerConnections() >= Hy.Config.kMaxRemotePlayers
Hy.Trace.debug "PlayerConnection::makeRoomForPlayer (TOO MANY PLAYERS #{connection} Count=#{PlayerConnection.numPlayerConnections()})"
s = networkManager.findServiceByConnection(connection)
if s?
reason = "Too many remote players!<br>(Maximum is #{Hy.Config.kMaxRemotePlayers})"
s.service.sendSingle_(connection, "joinDenied", {reason: reason}, PlayerConnection.getLabelFromMessage(data), false)
status = false
return status
# ----------------------------------------------------------------------------------------------------------------
@checkPlayerVersion: (networkManager, connection, data)->
majorVersion = data.majorVersion
minorVersion = data.minorVersion
status = true
if !majorVersion? or (majorVersion < Hy.Config.Version.Remote.kMinRemoteMajorVersion)
Hy.Trace.debug "PlayerConnection::checkPlayerVersion (WRONG VERSION #{connection} Looking for #{Hy.Config.Version.Remote.kMinRemoteMajorVersion} Remote is version #{majorVersion}.#{minorVersion})"
s = networkManager.findServiceByConnection(connection)
if s?
s.service.sendSingle_(connection,"joinDenied", {reason: 'Update Required! Please visit the AppStore to update this app!'}, PlayerConnection.getLabelFromMessage(data))
status = false
return status
# ----------------------------------------------------------------------------------------------------------------
@getLabelFromMessage: (data)->
unescape(data.label)
# ----------------------------------------------------------------------------------------------------------------
constructor: (@networkManager, connection, data, @requiresActivityMonitor)->
gInstances.push this
@majorVersion = data.majorVersion
@minorVersion = data.minorVersion
@label = PlayerConnection.getLabelFromMessage(data)
@index = ++gInstanceCount
this.setConnection(connection)
Hy.Trace.debug "PlayerConnection::constructor (##{@index} label=/#{@label}/ tag=/#{@tag}/ count=#{_.size(gInstances)})"
if @requiresActivityMonitor
ActivityMonitor.addPlayerConnection(this)
this.activate()
this
# ----------------------------------------------------------------------------------------------------------------
getIndex: ()-> @index
# ----------------------------------------------------------------------------------------------------------------
getNetworkManager: ()-> @networkManager
# ----------------------------------------------------------------------------------------------------------------
getMajorVersion: ()-> @majorVersion
# ----------------------------------------------------------------------------------------------------------------
getMinorVersion: ()-> @minorVersion
# ----------------------------------------------------------------------------------------------------------------
checkVersion: (majorVersion, minorVersion=null)->
status = false
if @majorVersion >= majorVersion
if minorVersion?
if @minorVersion >= minorVersion
status = true
else
status = true
status
# ----------------------------------------------------------------------------------------------------------------
setConnection: (connection)->
@tag = connection.tag
@generatedTag = not @tag?
if @generatedTag
this.createTag()
this
# ----------------------------------------------------------------------------------------------------------------
resetConnection: (connection)->
# ----------------------------------------------------------------------------------------------------------------
getConnection: ()-> null
# ----------------------------------------------------------------------------------------------------------------
getTag: (tag)-> @tag
# ----------------------------------------------------------------------------------------------------------------
tagIsGenerated: ()-> @generatedTag
# ----------------------------------------------------------------------------------------------------------------
createTag: ()->
@generatedTag = true
found = true
while found
tag = Hy.Utils.UUID.generate()
found = PlayerConnection.findByTag(tag)?
Hy.Trace.debug "PlayerConnection::createTag (tag=#{tag})"
@tag = tag
# ----------------------------------------------------------------------------------------------------------------
getLabel: ()-> @label
# ----------------------------------------------------------------------------------------------------------------
compare: (connection)->
this.getKind() is connection.kind
# ----------------------------------------------------------------------------------------------------------------
getService: ()->
service = null
s = this.getNetworkManager().findService(this.getKind())
if s?
service = s.service
service
# ----------------------------------------------------------------------------------------------------------------
getKind: ()-> null
# ----------------------------------------------------------------------------------------------------------------
getStatus: ()-> @status
# ----------------------------------------------------------------------------------------------------------------
getStatusString: ()->
s = switch this.getStatus()
when PlayerConnection.kStatusActive
"active"
when PlayerConnection.kStatusInactive
"inactive"
when PlayerConnection.kStatusDisconnected
"disconnected"
else
"???"
s
# ----------------------------------------------------------------------------------------------------------------
setStatus: (newStatus)->
if newStatus isnt @status
@status = newStatus
s = switch @status
when PlayerConnection.kStatusActive
true
when PlayerConnection.kStatusInactive, PlayerConnection.kStatusDisconnected
false
else
false
this.getNetworkManager().doPlayerStatusChange(this.getIndex(), s)
@status
# ----------------------------------------------------------------------------------------------------------------
isActive: ()->
@status is PlayerConnection.kStatusActive
# ----------------------------------------------------------------------------------------------------------------
activate: ()->
this.setStatus(PlayerConnection.kStatusActive)
# ----------------------------------------------------------------------------------------------------------------
reactivate: ()->
this.activate()
# ----------------------------------------------------------------------------------------------------------------
# If "disconnected", means that the socket as closed or something similar
#
deactivate: (disconnected = false)->
this.setStatus(if disconnected then PlayerConnection.kStatusDisconnected else PlayerConnection.kStatusInactive)
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
this.deactivate()
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
# ----------------------------------------------------------------------------------------------------------------
remove: (warn=null)->
Hy.Trace.debug "PlayerConnection::remove (Removing #{this.dumpStr()} warn=#{warn})"
if @requiresActivityMonitor
ActivityMonitor.removePlayerConnection(this)
if warn?
service = this.getService()
if service?
service.sendSingle(this, "ejected", {reason:warn}, false)
gInstances = _.without(gInstances, this)
this.getService().doneWithPlayerConnection(this)
this.getNetworkManager().doRemovePlayer(this.getIndex())
null
# ----------------------------------------------------------------------------------------------------------------
dumpStr: ()->
"#{this.constructor.name}: ##{this.getIndex()} #{this.getLabel()} #{this.getStatusString()} #{this.getTag()}"
# ==================================================================================================================
class HTTPPlayerConnection extends PlayerConnection
# ----------------------------------------------------------------------------------------------------------------
@create: (networkManager, connection, data)->
if PlayerConnection.preAddPlayer(networkManager, connection, data)
new HTTPPlayerConnection(networkManager, connection, data)
else
null
# ----------------------------------------------------------------------------------------------------------------
constructor: (networkManager, connection, data)->
Hy.Trace.debug "HTTPPlayerConnection::constructor (ENTER)"
super networkManager, connection, data, true
Hy.Trace.debug "HTTPPlayerConnection::constructor (EXIT)"
this
# ----------------------------------------------------------------------------------------------------------------
setConnection: (connection)->
super
@socketID = connection.socketID
this
# ----------------------------------------------------------------------------------------------------------------
resetConnection: (connection)->
super
if connection.socketID isnt @socketID
@socketID = connection.socketID
this
# ----------------------------------------------------------------------------------------------------------------
getConnection: ()-> {kind:this.getKind(), socketID:@socketID}
# ----------------------------------------------------------------------------------------------------------------
getKind: ()-> PlayerNetwork.kKindHTTP
# ----------------------------------------------------------------------------------------------------------------
compare: (connection)->
result = super and (@socketID is connection.socketID)
result
# ----------------------------------------------------------------------------------------------------------------
dumpStr: ()->
super + " socketID=#{@socketID}"
# ==================================================================================================================
class BonjourPlayerConnection extends PlayerConnection
# ----------------------------------------------------------------------------------------------------------------
@create: (networkManager, connection, data)->
if PlayerConnection.preAddPlayer(networkManager, connection, data)
new BonjourPlayerConnection(networkManager, connection, data)
else
null
# ----------------------------------------------------------------------------------------------------------------
constructor: (networkManager, connection, data)->
Hy.Trace.debug "BonjourPlayerConnection::constructor"
# Should do a version check on the remote; if less than iOS 4, requires activityMonitor
super networkManager, connection, data, true
this
# ----------------------------------------------------------------------------------------------------------------
getConnection: ()-> {kind:this.getKind(), tag:@tag}
# ----------------------------------------------------------------------------------------------------------------
getKind: ()-> PlayerNetwork.kKindBonjour
# ----------------------------------------------------------------------------------------------------------------
compare:(connection)->
result = super and (@tag is connection.tag)
result
# ----------------------------------------------------------------------------------------------------------------
dumpStr: ()->
super
# ==================================================================================================================
class ActivityMonitor
gInstance = null
# ----------------------------------------------------------------------------------------------------------------
@start: (networkManager)->
if gInstance?
gInstance.stop()
new ActivityMonitor(networkManager)
# ----------------------------------------------------------------------------------------------------------------
@stop: ()->
if gInstance
gInstance.stop()
gInstance = null
null
# ----------------------------------------------------------------------------------------------------------------
@pause: ()->
if gInstance
gInstance.pause()
null
# ----------------------------------------------------------------------------------------------------------------
@resumed: ()->
if gInstance
gInstance.resumed()
null
# ----------------------------------------------------------------------------------------------------------------
@getTime: ()->
(new Date()).getTime()
# ----------------------------------------------------------------------------------------------------------------
@processReceivedMessage: (networkManager, messageInfo)->
if gInstance?
messageInfo = gInstance.processReceivedMessage(networkManager, messageInfo)
messageInfo
# ----------------------------------------------------------------------------------------------------------------
@addPlayerConnection: (pc)->
if gInstance?
gInstance.addPlayerConnection(pc)
null
# ----------------------------------------------------------------------------------------------------------------
@removePlayerConnection: (pc)->
if gInstance?
gInstance.removePlayerConnection(pc)
null
# ----------------------------------------------------------------------------------------------------------------
constructor: (@networkManager)->
# Hy.Trace.debug "ActivityMonitor::constructor"
gInstance = this
@playerConnections = []
@networkManager.addReceivedMessageProcessor(ActivityMonitor.processReceivedMessage)
this.startTimer()
this
# ----------------------------------------------------------------------------------------------------------------
startTimer: ()->
fnTick = ()=>this.tick()
@interval = setInterval(fnTick, Hy.Config.PlayerNetwork.ActivityMonitor.kCheckInterval)
# ----------------------------------------------------------------------------------------------------------------
clearTimer: ()->
if @interval?
clearInterval(@interval)
@interval = null
this
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
Hy.Trace.debug "ActivityMonitor::stop"
this.clearTimer()
@playerConnections = []
this
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
Hy.Trace.debug "ActivityMonitor::pause"
this.clearTimer()
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
Hy.Trace.debug "ActivityMonitor::resumed"
this.startTimer()
# ----------------------------------------------------------------------------------------------------------------
processReceivedMessage: (networkManager, messageInfo)->
# Hy.Trace.debug "ActivityMonitor::processReceivedMessage (#{messageInfo.op})"
if messageInfo.playerConnection?
p = this.updatePlayerConnection(messageInfo.playerConnection)
switch messageInfo.message.op
when "ping"
p.lastPing = messageInfo.message.data.pingCount
service = messageInfo.playerConnection.getService()
if service?
service.sendSingle(messageInfo.playerConnection, "ack", {pingCount:messageInfo.message.data.pingCount}, false)
messageInfo.handled = true
messageInfo
# ----------------------------------------------------------------------------------------------------------------
addPlayerConnection: (pc)->
if not this.updatePlayerConnection(pc)?
@playerConnections.push {playerConnection: pc, pingTimestamp:ActivityMonitor.getTime(), lastPing:null}
Hy.Trace.debug "ActivityMonitor::addPlayerConnection (size=#{_.size(@playerConnections)} Added:#{pc.dumpStr()})"
pc
# ----------------------------------------------------------------------------------------------------------------
updatePlayerConnection: (pc)->
p = _.detect(@playerConnections, (c)=>c.playerConnection is pc)
if p?
timeNow = ActivityMonitor.getTime()
Hy.Trace.debug "ActivityMonitor::updatePlayerConnection (Updated #{pc.dumpStr()} last heard from=#{timeNow-p.pingTimestamp} lastPing=#{p.lastPing})"
p.pingTimestamp = timeNow
pc.reactivate()
p
# ----------------------------------------------------------------------------------------------------------------
removePlayerConnection: (pc)->
# Why the following, PI:NAME:<NAME>END_PI??
# @pingTimestamp = @pingTimestamp - 5*1000
@playerConnections = _.reject(@playerConnections, (p)=>p.playerConnection is pc)
# ----------------------------------------------------------------------------------------------------------------
tick: ()->
Hy.Trace.debug "ActivityMonitor::tick (#connections=#{_.size(@playerConnections)})"
for pc in @playerConnections
this.checkActivity(pc.playerConnection, pc.pingTimestamp, pc.lastPing)
null
# ----------------------------------------------------------------------------------------------------------------
checkActivity: (pc, pingTimestamp, lastPing)->
# this mechanism appears to be needed mostly for iPod 1Gs or perhaps anything else not running iOS 4+, and which
# don't send a "suspend" to the console when the button is pushed
fnTestActive = (pc, timeNow, pingTimestamp)->
((timeNow - pingTimestamp) <= Hy.Config.PlayerNetwork.ActivityMonitor.kThresholdActive)
fnTestAlive = (pc, timeNow, pingTimestamp)->
((timeNow - pingTimestamp) <= Hy.Config.PlayerNetwork.ActivityMonitor.kThresholdAlive)
timeNow = ActivityMonitor.getTime()
debugString = "#{pc.dumpStr()} last heard from=#{timeNow-pingTimestamp} lastPing=#{lastPing}"
if fnTestAlive(pc, timeNow, pingTimestamp)
switch pc.getStatus()
when PlayerConnection.kStatusActive
if not fnTestActive(pc, timeNow, pingTimestamp)
Hy.Trace.debug "PlayerConnection::checkActivity (Deactivating formerly active player #{debugString})"
pc.deactivate()
when PlayerConnection.kStatusInactive
if fnTestActive(pc, timeNow, pingTimestamp)
Hy.Trace.debug "PlayerConnection::checkActivity (Reactivating formerly inactive player #{debugString})"
pc.reactivate()
when PlayerConnection.Disconnected
# We do nothing here. If the player manages to reconnect, the join code will handle that
null
else
Hy.Trace.debug "ActivityMonitor::checkActivity (Removing #{debugString})"
pc.remove("You appear to be inactive")
# if !fnTestAlive(pc, timeNow, pingTimestamp)
# Hy.Trace.debug "ActivityMonitor::checkActivity (Removing #{pc.dumpStr()} #{timeNow-pingTimestamp})"
# pc.remove("You appear to be inactive")
# else if pc.isActive() and !fnTestActive(pc, timeNow, pingTimestamp)
# Hy.Trace.debug "PlayerConnection::checkActivity (Deactivating player #{pc.dumpStr()} #{timeNow-pingTimestamp})"
# pc.deactivate()
# else if !player.isActive() and fnTestActive(player)
# this.playerReactivate player
this
# ==================================================================================================================
# Abstract superclass for all player network types
# Each instance of a subtype of this type is managed by PlayerNetwork
#
# PlayerNetworkService
# HTTPPlayerService
# BonjourService
#
class PlayerNetworkService
# ----------------------------------------------------------------------------------------------------------------
constructor: (@networkManager)->
username = Ti.Platform.username
# to allow two simulators to run on the same network
if username is "iPad Simulator"
username = "#{username}-#{Hy.Utils.Math.random(10000)}"
@tag = escape username
this
# ----------------------------------------------------------------------------------------------------------------
start: ()->
Hy.Trace.debug "PlayerNetworkService::start"
this
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
Hy.Trace.debug "PlayerNetworkService::stop"
this
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
Hy.Trace.debug "PlayerNetworkService::pause"
this
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
Hy.Trace.debug "PlayerNetworkService::resumed"
this
# ----------------------------------------------------------------------------------------------------------------
getKind: ()-> null
# ----------------------------------------------------------------------------------------------------------------
setReady: ()->
Hy.Trace.debug "PlayerNetworkService::setReady (service=#{this.getKind()})"
@networkManager.setServiceReady(this)
# ----------------------------------------------------------------------------------------------------------------
getActivePlayers: ()->
PlayerConnection.getActivePlayersByServiceKind(this.getKind())
# ----------------------------------------------------------------------------------------------------------------
sendSingle_: (connection, op, data, label, requireAck=true)->
Hy.Trace.debug "PlayerNetworkService::sendSingle (#{this.constructor.name} op=#{op} label=#{label})"
# ----------------------------------------------------------------------------------------------------------------
sendSingle: (playerConnection, op, data, requireAck=true)->
this.sendSingle_(playerConnection.getConnection(), op, data, playerConnection.getLabel(), requireAck)
# ----------------------------------------------------------------------------------------------------------------
sendAll: (op, data, requireAck=true)->
Hy.Trace.debug "PlayerNetworkService::sendAll (#{this.constructor.name} op=#{op})"
# ----------------------------------------------------------------------------------------------------------------
doneWithPlayerConnection: (playerConnection)->
# ==================================================================================================================
class HTTPPlayerService extends PlayerNetworkService
# ----------------------------------------------------------------------------------------------------------------
constructor: (networkManager)->
super networkManager
this
# ----------------------------------------------------------------------------------------------------------------
getKind: ()-> PlayerNetwork.kKindHTTP
# ----------------------------------------------------------------------------------------------------------------
getPort: ()->
port = null
if @httpServer?
port = @httpServer.getPort()
port
# ----------------------------------------------------------------------------------------------------------------
start: ()->
Hy.Trace.debug "HTTPPlayerService::start"
fnServerReady = (server)=>this.setReady()
fnSocketOpened = (server, socketID)=> # Rely on clients to send 'join'
Hy.Trace.debug "HTTPPlayerService::fnSocketOpened (socket=#{socketID})"
null
fnSocketClosed = (server, socketID)=>
Hy.Trace.debug "HTTPPlayerService::fnSocketClosed (socket=#{socketID})"
pc = PlayerConnection.findByConnection({kind:this.getKind(), socketID:socketID})
# pc?.remove()
pc?.deactivate(true) # if the user refreshes the browser window, the socket is closed. Let's try to preserve the user's app state across that refresh
null
fnMessageReceived = (server, socketID, messageText)=>this.messageReceived(socketID, messageText)
fnServiceStatusChange = (status, domain, type_, name)=>this.serviceStatusChange(status, domain, type_, name)
@httpServer = Hy.Network.HTTPServerProxy.create(fnServerReady, fnSocketOpened, fnSocketClosed, fnMessageReceived, fnServiceStatusChange, Hy.Config.PlayerNetwork.HTTPServerRunsInOwnThread)
super
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
Hy.Trace.debug "HTTPPlayerService::stop"
@httpServer?.stop() # ?? for some reason, this doesn't work (error in the trivnet module at runtime)
@httpServer = null
super
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
Hy.Trace.debug "HTTPPlayerService::pause"
super
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
Hy.Trace.debug "HTTPPlayerService::resumed (#active=#{_.size(this.getActivePlayers())})"
# If we have resumed and the connections are still connected, then do nothing. Otherwise, restart
if _.size(this.getActivePlayers()) is 0
@httpServer?.restart()
this.setReady()
super
# ----------------------------------------------------------------------------------------------------------------
messageReceived: (socketID, messageText)->
try
message = JSON.parse messageText
catch e
@networkManager.doError("Error parsing HTTP message /#{messageText}/")
return null
@networkManager.messageReceived({kind:this.getKind(), socketID:socketID}, message)
null
# ----------------------------------------------------------------------------------------------------------------
serviceStatusChange: (status, domain, type_, name)->
Hy.Trace.debug "HTTPPlayerService::serviceStatusChange (#{status} #{domain} #{type_} #{name})"
serviceStatus = {}
switch status
when "bonjourPublishSuccess", "bonjourPublishFailure"
serviceStatus.bonjourPublish = {status: status, domain: domain, type_: type_, name: name}
@networkManager.doServiceStatusChange(serviceStatus)
this
# ----------------------------------------------------------------------------------------------------------------
getServiceStatus: ()-> @serviceStatus
# ----------------------------------------------------------------------------------------------------------------
sendSingle_: (connection, op, data, label, requireAck=true)->
# requireAck is not implemented
super
try
message = JSON.stringify src: @tag, op: op, data: data
@httpServer.sendMessage(connection.socketID, message)
catch e
@networkManager.doError("Error encoding HTTP message (connection=#{connection.socketID} op=#{op} tag=#{@tag} data=#{@data})")
this
# ----------------------------------------------------------------------------------------------------------------
sendAll: (op, data, requireAck=true)->
super
for p in this.getActivePlayers()
this.sendSingle(p, op, data, requireAck)
this
# ----------------------------------------------------------------------------------------------------------------
doneWithPlayerConnection: (playerConnection)->
super
# Should figure out a way to close the socket associated with this connection
# ==================================================================================================================
class BonjourService extends PlayerNetworkService
# ----------------------------------------------------------------------------------------------------------------
constructor: (networkManager)->
super networkManager
Hy.Trace.debug "BonjourService::constructor"
this
# ----------------------------------------------------------------------------------------------------------------
getKind: ()-> PlayerNetwork.kKindBonjour
# ----------------------------------------------------------------------------------------------------------------
startBonjourNetwork: ()->
this.openSocket()
this.publishService()
this
# ----------------------------------------------------------------------------------------------------------------
stopBonjourNetwork: ()->
if @localService?
@localService.stop()
@localService = null
if @socket?
if @socket.isValid
@socket.close()
@socket = null
this
# ----------------------------------------------------------------------------------------------------------------
start: ()->
Hy.Trace.debug "BonjourService::start"
this.startBonjourNetwork()
@messageQueue = MessageQueue.create(@networkManager, this)
this.setReady()
super
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
Hy.Trace.debug "BonjourService::stop"
this.stopBonjourNetwork()
@messageQueue.stop()
super
# ----------------------------------------------------------------------------------------------------------------
pause: ()->
Hy.Trace.debug "BonjourService::pause"
this.stop()
super
# ----------------------------------------------------------------------------------------------------------------
resumed: ()->
Hy.Trace.debug "BonjourService::resumed"
this.start()
super
# ----------------------------------------------------------------------------------------------------------------
dumpSocket: ()->
(Hy.Trace.debug "socket.#{prop} => #{val}") for prop, val of @socket
Hy.Trace.debug "socket.isValid => #{@socket.isValid}"
Hy.Trace.debug "socket.mode => #{@socket.mode}"
Hy.Trace.debug "socket.port => #{@socket.port}"
Hy.Trace.debug "socket.hostName => #{@socket.hostName}"
# ----------------------------------------------------------------------------------------------------------------
openSocket: ()->
Hy.Trace.debug "BonjourService::openSocket"
@socket = Ti.Network.createTCPSocket(hostName:Hy.Config.Bonjour.hostName, mode:Hy.Config.Bonjour.mode, port:Hy.Config.Bonjour.port)
fnRead = (evt)=>
this.messageReceived(evt)
null
@socket.addEventListener 'read', fnRead
# @socket.stripTerminator = true
fnReadError = (evt)=>
@networkManager.doError("Bonjour READ ERROR (code=#{evt.code}/#{evt.error}/#{evt.type})")
null
@socket.addEventListener 'readError', fnReadError
fnWriteError = (evt)=>
@networkManager.doError("Bonjour WRITE ERROR (code=#{evt.code}/#{evt.error}/#{evt.type})")
null
@socket.addEventListener 'writeError', fnWriteError
@socket.listen()
# ----------------------------------------------------------------------------------------------------------------
publishService: ()->
Hy.Trace.debug "BonjourService::publishService"
@localService = Ti.Network.createBonjourService name:@tag, type:Hy.Config.Bonjour.serviceType, domain:Hy.Config.Bonjour.domain
try
@localService.publish @socket
catch error
@networkManager.doError("Bonjour Open Error", true)
this
# ----------------------------------------------------------------------------------------------------------------
parseForMultiple: (text)->
level = 0
results = []
out = ""
for c in text
if c.charCodeAt(0) is 0
null
else
switch c
when '{'
level++
when '}'
level--
out += c
if level is 0
results.push out
out = ""
return results
# ----------------------------------------------------------------------------------------------------------------
messageReceived: (evt)->
text = "UNKNOWN"
text = evt.data.text
# Hy.Trace.debug "BonjourService::messageReceived (length=#{text.length} last=#{text.charCodeAt(text.length-1)})"
# "suddenly", started seeing null bytes at the end of these strings, and multiple messages at the same time - 2011-08-12
if text.charCodeAt(text.length-1) isnt 125 # 125=}
text = text.substring(0, text.length-1)
results = this.parseForMultiple(text)
for r in results
try
message = JSON.parse r
catch e
@networkManager.doError("Error parsing Bonjour message /#{text}/")
return null
if (message.dest is 0) or (message.dest isnt @tag)
null
else
Hy.Trace.debug "BonjourService::messageReceived (message=#{r})"
@networkManager.messageReceived({kind:this.getKind(), tag:message.src}, message)
null
# ----------------------------------------------------------------------------------------------------------------
sendSingle_: (connection, op, data, label, requireAck=true)->
super
message = new Message(@tag, op, data, requireAck, false)
message.addDest(connection.tag, label)
this.sendMessage message
# ----------------------------------------------------------------------------------------------------------------
sendAll: (op, data, requireAck=true)->
super op, data
# Hy.Trace.info "BonjourService::sendMultipleClients(op=#{op} data=#{JSON.stringify(data)})"
players = this.getActivePlayers()
if _.size(players) isnt 0
message = new Message(@tag, op, data, requireAck, true)
for player in players
message.addDest(player.getConnection().tag, player.label)
this.sendMessage(message)
this
# ----------------------------------------------------------------------------------------------------------------
sendMessage: (message)->
# Hy.Trace.info "BonjourService::sendMessage (#{message.dump()})"
message.send(@socket)
if message.requireAck
@messageQueue.insert(message)
this
# ==================================================================================================================
class Message
messageCount = 0
# ----------------------------------------------------------------------------------------------------------------
constructor: (@src, @op, @data, @requireAck, @isBroadcast)->
messageCount++
@id = messageCount
@dests = []
@createTime = (new Date()).getTime()
@sendCount = 0
@sentTime = null
@broadcastPartiallyAckd = false # set true if we receive at least one response to a broadcast
this
# ----------------------------------------------------------------------------------------------------------------
addDest: (tag, label)->
@dests.push {tag: tag, label: label, ack: false, ackCount: 0}
# ----------------------------------------------------------------------------------------------------------------
getPacket: (tag)->
try
p = JSON.stringify m: @id, count: @sendCount, src: @src, dest: tag, op: @op, data: @data
catch e
Hy.Trace.info "Message::getPacket (ERROR could not encode packet data=#{@data})"
p = ""
p
# ----------------------------------------------------------------------------------------------------------------
getPacket2: (isBroadcast=false)->
tags = []
if not isBroadcast
for d in @dests
tags.push d.tag
try
p = JSON.stringify m: @id, count: @sendCount, src: @src, dest: tags, op: @op, data: @data
# Hy.Trace.info "Message::getPacket (packet=#{p})"
catch e
Hy.Trace.info "Message::getPacket (ERROR could not encode packet data=#{@data})"
p = ""
p
# ----------------------------------------------------------------------------------------------------------------
send: (socket)->
# Hy.Trace.info "Message:send (ENTER #{this.dump()})"
@sentTime = (new Date().getTime())
@sendCount++
dest = null
if 1 # Trying to reduce network traffic by making it possible for a message to target multiple clients
if @isBroadcast and not @broadcastPartiallyAckd
socket.write this.getPacket2(true)
Hy.Trace.info "Message:send (Broadcast #{this.dump()})"
else
socket.write this.getPacket2()
Hy.Trace.info "Message:send (Direct #{this.dump()})"
else
if @isBroadcast and not @broadcastPartiallyAckd
socket.write this.getPacket(0)
Hy.Trace.info "Message:send (Broadcast #{this.dump()})"
else
for dest in @dests
Hy.Trace.info "Message:send (Direct to #{dest.label} #{this.dump()})"
socket.write this.getPacket(dest.tag)
# Hy.Trace.info "Message:send (EXIT #{this.dump()})"
# ----------------------------------------------------------------------------------------------------------------
hasDest: (tag)->
for dest in @dests
if dest.tag is tag
return dest
return null
# ----------------------------------------------------------------------------------------------------------------
setAck: (tag, messageCount)->
ackdBefore = false
ackCount = 0
if @isBroadcast
@broadcastPartiallyAckd = true
dest = this.hasDest tag
if dest?
if dest.ack
ackdBefore = true
else
@ack = (new Date()).getTime()
dest.ack = true
dest.ackCount = messageCount
ackCount = dest.ackCount
# Hy.Trace.info "Message:setAck (#{if ackdBefore then "NOT THE FIRST TIME" else ""} label=#{dest.label} message=#{@id} op=#{@op} createTime=#{this.dumpCreateTime()} sendCount=#{@sendCount} ackCount=#{dest.ackCount})"
else
Hy.Trace.info "Message:setAck (Unexpected Ack: tag=#{tag} message=#{@id})"
ackCount
# ----------------------------------------------------------------------------------------------------------------
removeAckdDests: ()->
if @dests.length>0
newDests = _.reject @dests, (d)=>d.ack
@dests = newDests
return @dests.length > 0
# ----------------------------------------------------------------------------------------------------------------
removeDest: (tag)->
if @dests.length>0
newDests = _.reject @dests, (d)=>d.tag is tag
@dests = newDests
return @dests.length > 0
# ----------------------------------------------------------------------------------------------------------------
removeDests: ()->
@dests= {}
this
# ----------------------------------------------------------------------------------------------------------------
removeDestsInCommon: (message)->
# Hy.Trace.info "Message:removeDestInCommon (ENTER)"
if @dests.length is 0 or message.dests.length is 0
return
newDests = []
for d in @dests
if _.detect(message, (d1)=>d1.tag is d.tag)?
Hy.Trace.info "Message:removeDestsInCommon (Message=#{message.id} in common with #{@id}: Removing #{d.label})"
else
newDests.push d
@dests = newDests
this
# ----------------------------------------------------------------------------------------------------------------
hasOutstandingDests: ()->
@dests.length > 0
# ----------------------------------------------------------------------------------------------------------------
getNumDests: ()->
@dests.length
# ----------------------------------------------------------------------------------------------------------------
dumpCreateTime: ()->
now = (new Date()).getTime()
if @createTime? then ("#{now-this.createTime} milliseconds ago") else "(NO CREATE TIME)"
# ----------------------------------------------------------------------------------------------------------------
dumpSentTime: ()->
now = (new Date()).getTime()
if @sentTime? then ("#{now-@sentTime} milliseconds ago") else "NOT SENT"
# ----------------------------------------------------------------------------------------------------------------
dump: ()->
output = "Message=#{@id} op=#{@op} Broadcast=#{@isBroadcast}/#{@broadcastPartiallyAckd} create=#{this.dumpCreateTime()} AckRequired=#{if @requireAck then 'Yes' else 'No'} sent=#{this.dumpSentTime()} sendCount=#{@sendCount} #dests=#{@dests.length} "
count = 0
for dest in @dests
count++
a = if dest.ack then "ACKd" else "NOT ACKd"
output += "/##{count}: label=#{dest.label} ack=#{a} ackCount=#{dest.ackCount}/ "
output
# ==================================================================================================================
class MessageQueue
gInstance = null
kMessageDeliveryThreshold = 1500
kMaxSendAttempts = 5
# ----------------------------------------------------------------------------------------------------------------
@create: (networkManager, networkService)->
new MessageQueue(networkManager, networkService)
# ----------------------------------------------------------------------------------------------------------------
@processReceivedMessage: (networkManager, messageInfo)->
# Hy.Trace.debug "MessageQueue::processReceivedMessage (#{messageInfo.message.op})"
switch messageInfo.message.op
when "ack2"
messageInfo.handled = true
if messageInfo.playerConnection?
if gInstance?
gInstance.ackReceived(messageInfo.message.data.m, messageInfo.message.data.count, messageInfo.connection.tag)
messageInfo
# ----------------------------------------------------------------------------------------------------------------
constructor: (@networkManager, @networkService)->
# Hy.Trace.info "MessageQueue::constructor"
gInstance = this
@messages = []
@networkManager.addReceivedMessageProcessor(MessageQueue.processReceivedMessage)
this.initStats()
f = ()=>if @messages.length > 0 then this.check()
@interval = null
@interval = setInterval f, kMessageDeliveryThreshold
# ----------------------------------------------------------------------------------------------------------------
stop: ()->
# Hy.Trace.debug "MessageQueue::stop"
clearInterval @interval if @interval?
@interval = null
@messages = []
this.initStats()
# ----------------------------------------------------------------------------------------------------------------
initStats: ()->
# Note that we count each destination in a broadcast as a separate message
@numberOfSentMessages = 0 # Total number of messages sent with "ack required" set
@numberOfResentMessages = 0 # Total number of messages sent more than once
@numberOfAckdMessages = 0 # Total number of messages ack'd
@numberOfAckdOnFirstSendMessages = 0 # Total number of messages ack'd after first send
@totalFirstSendAckdTime = 0 # For all messages ack'd after first send, sum of time between send and ack
@numberOfAckdOnRetryMessages = 0 # Total number of messages ack'd after one or more retries
@totalRetryTime = 0 # For all messages sent more than once, sum of time between send and ack
@numberOfFailedMessages = 0 # Total number of messages we've given up trying to resend
# ----------------------------------------------------------------------------------------------------------------
dumpStats: ()->
stat = "Sent/Ackd/Resent/Failed=#{@numberOfSentMessages}/#{@numberOfAckdMessages}/#{@numberOfResentMessages}/#{@numberOfFailedMessages} "
stat += "1st Send Ackd=#{@numberOfAckdOnFirstSendMessages} Ave=#{@totalFirstSendAckdTime/@numberOfAckdOnFirstSendMessages} secs "
stat += "Ackd after Retry=#{@numberOfAckdOnRetryMessages} Ave=#{@totalRetryTime/@numberOfAckdOnRetryMessages} secs"
stat
# ----------------------------------------------------------------------------------------------------------------
dump: ()->
for message in @messages
Hy.Trace.info "MessageQueue::dump (#{message.dump()})"
this
# ----------------------------------------------------------------------------------------------------------------
insert: (message)->
# Hy.Trace.info "MessageQueue::insert"
# Broadcast messages trump all previous messages, except 'welcome'
if message.isBroadcast and not message.broadcastPartiallyAckd
m = _.select @messages, (m)=>m.op is 'welcome'
# Hy.Trace.info "MessageQueue::insert (Broadcast inserted, was #{@messages.length} now #{m.length})"
@messages = m
else
for m in @messages
m.removeDestsInCommon message
@messages.push message
@numberOfSentMessages += message.getNumDests()
# Hy.Trace.info "MessageQueue::insert (EXIT)"
this
# ----------------------------------------------------------------------------------------------------------------
ackReceived: (messageId, messageCount, tag)->
for message in @messages
if message.id is messageId
ackCount = message.setAck(tag, messageCount)
t = message.ack - message.createTime
if ackCount is 1
@numberOfAckdOnFirstSendMessages++
@totalFirstSendAckdTime += t
else
@numberOfAckdOnRetryMessages++
@totalRetryTime += t
@numberOfAckdMessages++
return
this
# ----------------------------------------------------------------------------------------------------------------
check: ()->
# Hy.Trace.debug "MessageQueue::check (ENTERING number of messages=#{@messages.length} #{this.dumpStats()})"
timeNow = (new Date()).getTime()
messagesToCheckLater = []
messagesToResendNow = []
for message in @messages
# First, remove all clients that have ackd this message
if message.removeAckdDests()
# Then, remove all destinations representing clients that aren't active
for p in @networkService.getActivePlayers()
if !p.isActive()
message.removeDest p.tag
# If there are still outstanding destinations, then have we reached the resend limit?
if message.hasOutstandingDests()
if message.sendCount is kMaxSendAttempts
Hy.Trace.debug "MessageQueue::check (Message - too many retries: #{message.dump()})"
@numberOfFailedMessages += message.getNumDests()
else
# Decide whether to resend now or later
t = message.sentTime
if t?
if (timeNow - t) > kMessageDeliveryThreshold
messagesToResendNow.push message
else
messagesToCheckLater.push message
else
Hy.Trace.debug "MessageQueue::check (Message not sent! #{message.dump()})"
messagesToCheckLater.push message
@messages = []
@messages = messagesToCheckLater
for message in messagesToResendNow #should be safe to iterate while appending
Hy.Trace.debug "MessageQueue::check (Resending message: #{message.dump()})"
@numberOfResentMessages += message.getNumDests()
@networkService.sendMessage message
# Hy.Trace.debug "MessageQueue::check (EXITING number of messages=#{@messages.length})"
# this.dump()
# ==================================================================================================================
# assign to global namespace:
if not Hy.Network?
Hy.Network = {}
Hy.Network.PlayerNetwork = PlayerNetwork
|
[
{
"context": "maintainers - please feel free to <a href=\"mailto:i@fantix.pro\">leave me a message</a> if\n yo",
"end": 2147,
"score": 0.999930202960968,
"start": 2135,
"tag": "EMAIL",
"value": "i@fantix.pro"
}
] | src/scripts/components/pages/aboutme.cjsx | ArchLinux-x32/archlinux-x32.github.io.src | 0 | React = require('react')
GenericContent = require('../modules/generic-content')
module.exports = React.createClass
render: ->
return (
<div className="aboutme">
<GenericContent title="About x32">
In <a href="https://sites.google.com/site/x32abi/">short</a>: A 32-bit psABI for x86-64 with 32-bit pointer size.
<br /><br />
Under x32, there will be new binary libraries for everything, from glibc to your compiled application.
By design, x32 applications are supposed to run as fast - if not faster - as native x86-64 applications,
but consumes less memory. Therefore virtual machines in the cloud with very expensive memory are ideal for x32.
</GenericContent>
<GenericContent title="ArchLinux x32">
I am maintaining some common ArchLinux x32 libraries. Thanks to the community of Debian, Gentoo and more, my packages
so far compile well. They are available on <a href="https://aur.archlinux.org/packages/?SeB=m&K=fantix">AUR</a>,
and <a href="https://wiki.archlinux.org/index.php/Unofficial_user_repositories#archlinuxcn">ArchLinux CN</a> as
pre-compiled packages. Other than AUR, the sources can also be found at <a href="https://github.com/archlinux-x32">
GitHub</a>.
<br /><br />
To get your hands dirty, you'll need 64-bit ArchLinux and a kernel that enables <code>CONFIG_X86_X32</code>,
for example <a href="https://aur.archlinux.org/packages/linux-pf/">linux-pf</a>. Then the easier way is to
install the <code>libx32-*</code> packages from ArchLinux CN repository mentioned above, or you'll need to compile
the world from seeds - I'll explain that part in separate page.
</GenericContent>
<GenericContent title="Contribute">
This project is open for maintainers - please feel free to <a href="mailto:i@fantix.pro">leave me a message</a> if
you want to help.
</GenericContent>
</div>
)
| 46593 | React = require('react')
GenericContent = require('../modules/generic-content')
module.exports = React.createClass
render: ->
return (
<div className="aboutme">
<GenericContent title="About x32">
In <a href="https://sites.google.com/site/x32abi/">short</a>: A 32-bit psABI for x86-64 with 32-bit pointer size.
<br /><br />
Under x32, there will be new binary libraries for everything, from glibc to your compiled application.
By design, x32 applications are supposed to run as fast - if not faster - as native x86-64 applications,
but consumes less memory. Therefore virtual machines in the cloud with very expensive memory are ideal for x32.
</GenericContent>
<GenericContent title="ArchLinux x32">
I am maintaining some common ArchLinux x32 libraries. Thanks to the community of Debian, Gentoo and more, my packages
so far compile well. They are available on <a href="https://aur.archlinux.org/packages/?SeB=m&K=fantix">AUR</a>,
and <a href="https://wiki.archlinux.org/index.php/Unofficial_user_repositories#archlinuxcn">ArchLinux CN</a> as
pre-compiled packages. Other than AUR, the sources can also be found at <a href="https://github.com/archlinux-x32">
GitHub</a>.
<br /><br />
To get your hands dirty, you'll need 64-bit ArchLinux and a kernel that enables <code>CONFIG_X86_X32</code>,
for example <a href="https://aur.archlinux.org/packages/linux-pf/">linux-pf</a>. Then the easier way is to
install the <code>libx32-*</code> packages from ArchLinux CN repository mentioned above, or you'll need to compile
the world from seeds - I'll explain that part in separate page.
</GenericContent>
<GenericContent title="Contribute">
This project is open for maintainers - please feel free to <a href="mailto:<EMAIL>">leave me a message</a> if
you want to help.
</GenericContent>
</div>
)
| true | React = require('react')
GenericContent = require('../modules/generic-content')
module.exports = React.createClass
render: ->
return (
<div className="aboutme">
<GenericContent title="About x32">
In <a href="https://sites.google.com/site/x32abi/">short</a>: A 32-bit psABI for x86-64 with 32-bit pointer size.
<br /><br />
Under x32, there will be new binary libraries for everything, from glibc to your compiled application.
By design, x32 applications are supposed to run as fast - if not faster - as native x86-64 applications,
but consumes less memory. Therefore virtual machines in the cloud with very expensive memory are ideal for x32.
</GenericContent>
<GenericContent title="ArchLinux x32">
I am maintaining some common ArchLinux x32 libraries. Thanks to the community of Debian, Gentoo and more, my packages
so far compile well. They are available on <a href="https://aur.archlinux.org/packages/?SeB=m&K=fantix">AUR</a>,
and <a href="https://wiki.archlinux.org/index.php/Unofficial_user_repositories#archlinuxcn">ArchLinux CN</a> as
pre-compiled packages. Other than AUR, the sources can also be found at <a href="https://github.com/archlinux-x32">
GitHub</a>.
<br /><br />
To get your hands dirty, you'll need 64-bit ArchLinux and a kernel that enables <code>CONFIG_X86_X32</code>,
for example <a href="https://aur.archlinux.org/packages/linux-pf/">linux-pf</a>. Then the easier way is to
install the <code>libx32-*</code> packages from ArchLinux CN repository mentioned above, or you'll need to compile
the world from seeds - I'll explain that part in separate page.
</GenericContent>
<GenericContent title="Contribute">
This project is open for maintainers - please feel free to <a href="mailto:PI:EMAIL:<EMAIL>END_PI">leave me a message</a> if
you want to help.
</GenericContent>
</div>
)
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9976412653923035,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-https-eof-for-eom.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.
# I hate HTTP. One way of terminating an HTTP response is to not send
# a content-length header, not send a transfer-encoding: chunked header,
# and simply terminate the TCP connection. That is identity
# transfer-encoding.
#
# This test is to be sure that the https client is handling this case
# correctly.
unless process.versions.openssl
console.error "Skipping because node compiled without OpenSSL."
process.exit 0
common = require("../common")
assert = require("assert")
tls = require("tls")
https = require("https")
fs = require("fs")
options =
key: fs.readFileSync(common.fixturesDir + "/keys/agent1-key.pem")
cert: fs.readFileSync(common.fixturesDir + "/keys/agent1-cert.pem")
server = tls.Server(options, (socket) ->
console.log "2) Server got request"
socket.write "HTTP/1.1 200 OK\r\n" + "Date: Tue, 15 Feb 2011 22:14:54 GMT\r\n" + "Expires: -1\r\n" + "Cache-Control: private, max-age=0\r\n" + "Set-Cookie: xyz\r\n" + "Set-Cookie: abc\r\n" + "Server: gws\r\n" + "X-XSS-Protection: 1; mode=block\r\n" + "Connection: close\r\n" + "\r\n"
socket.write "hello world\n"
setTimeout (->
socket.end "hello world\n"
console.log "4) Server finished response"
return
), 100
return
)
gotHeaders = false
gotEnd = false
bodyBuffer = ""
server.listen common.PORT, ->
console.log "1) Making Request"
req = https.get(
port: common.PORT
rejectUnauthorized: false
, (res) ->
server.close()
console.log "3) Client got response headers."
assert.equal "gws", res.headers.server
gotHeaders = true
res.setEncoding "utf8"
res.on "data", (s) ->
bodyBuffer += s
return
res.on "end", ->
console.log "5) Client got \"end\" event."
gotEnd = true
return
return
)
return
process.on "exit", ->
assert.ok gotHeaders
assert.ok gotEnd
assert.equal "hello world\nhello world\n", bodyBuffer
return
| 24702 | # 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.
# I hate HTTP. One way of terminating an HTTP response is to not send
# a content-length header, not send a transfer-encoding: chunked header,
# and simply terminate the TCP connection. That is identity
# transfer-encoding.
#
# This test is to be sure that the https client is handling this case
# correctly.
unless process.versions.openssl
console.error "Skipping because node compiled without OpenSSL."
process.exit 0
common = require("../common")
assert = require("assert")
tls = require("tls")
https = require("https")
fs = require("fs")
options =
key: fs.readFileSync(common.fixturesDir + "/keys/agent1-key.pem")
cert: fs.readFileSync(common.fixturesDir + "/keys/agent1-cert.pem")
server = tls.Server(options, (socket) ->
console.log "2) Server got request"
socket.write "HTTP/1.1 200 OK\r\n" + "Date: Tue, 15 Feb 2011 22:14:54 GMT\r\n" + "Expires: -1\r\n" + "Cache-Control: private, max-age=0\r\n" + "Set-Cookie: xyz\r\n" + "Set-Cookie: abc\r\n" + "Server: gws\r\n" + "X-XSS-Protection: 1; mode=block\r\n" + "Connection: close\r\n" + "\r\n"
socket.write "hello world\n"
setTimeout (->
socket.end "hello world\n"
console.log "4) Server finished response"
return
), 100
return
)
gotHeaders = false
gotEnd = false
bodyBuffer = ""
server.listen common.PORT, ->
console.log "1) Making Request"
req = https.get(
port: common.PORT
rejectUnauthorized: false
, (res) ->
server.close()
console.log "3) Client got response headers."
assert.equal "gws", res.headers.server
gotHeaders = true
res.setEncoding "utf8"
res.on "data", (s) ->
bodyBuffer += s
return
res.on "end", ->
console.log "5) Client got \"end\" event."
gotEnd = true
return
return
)
return
process.on "exit", ->
assert.ok gotHeaders
assert.ok gotEnd
assert.equal "hello world\nhello world\n", bodyBuffer
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.
# I hate HTTP. One way of terminating an HTTP response is to not send
# a content-length header, not send a transfer-encoding: chunked header,
# and simply terminate the TCP connection. That is identity
# transfer-encoding.
#
# This test is to be sure that the https client is handling this case
# correctly.
unless process.versions.openssl
console.error "Skipping because node compiled without OpenSSL."
process.exit 0
common = require("../common")
assert = require("assert")
tls = require("tls")
https = require("https")
fs = require("fs")
options =
key: fs.readFileSync(common.fixturesDir + "/keys/agent1-key.pem")
cert: fs.readFileSync(common.fixturesDir + "/keys/agent1-cert.pem")
server = tls.Server(options, (socket) ->
console.log "2) Server got request"
socket.write "HTTP/1.1 200 OK\r\n" + "Date: Tue, 15 Feb 2011 22:14:54 GMT\r\n" + "Expires: -1\r\n" + "Cache-Control: private, max-age=0\r\n" + "Set-Cookie: xyz\r\n" + "Set-Cookie: abc\r\n" + "Server: gws\r\n" + "X-XSS-Protection: 1; mode=block\r\n" + "Connection: close\r\n" + "\r\n"
socket.write "hello world\n"
setTimeout (->
socket.end "hello world\n"
console.log "4) Server finished response"
return
), 100
return
)
gotHeaders = false
gotEnd = false
bodyBuffer = ""
server.listen common.PORT, ->
console.log "1) Making Request"
req = https.get(
port: common.PORT
rejectUnauthorized: false
, (res) ->
server.close()
console.log "3) Client got response headers."
assert.equal "gws", res.headers.server
gotHeaders = true
res.setEncoding "utf8"
res.on "data", (s) ->
bodyBuffer += s
return
res.on "end", ->
console.log "5) Client got \"end\" event."
gotEnd = true
return
return
)
return
process.on "exit", ->
assert.ok gotHeaders
assert.ok gotEnd
assert.equal "hello world\nhello world\n", bodyBuffer
return
|
[
{
"context": "Each ->\n\t\t@fakeUser =\n\t\t\t_id: '12390i'\n\t\t\temail: 'email2@foo.bar'\n\t\t\temails: [\n\t\t\t\t{ email: 'email1@foo.bar', reve",
"end": 427,
"score": 0.9999013543128967,
"start": 413,
"tag": "EMAIL",
"value": "email2@foo.bar"
},
{
"context": "mail: 'email2@foo.bar'\n\t\t\temails: [\n\t\t\t\t{ email: 'email1@foo.bar', reversedHostname: 'rab.oof' }\n\t\t\t\t{ email: 'ema",
"end": 470,
"score": 0.999885618686676,
"start": 456,
"tag": "EMAIL",
"value": "email1@foo.bar"
},
{
"context": "bar', reversedHostname: 'rab.oof' }\n\t\t\t\t{ email: 'email2@foo.bar', reversedHostname: 'rab.oof' }\n\t\t\t]\n\t\t@findOne =",
"end": 531,
"score": 0.9998953342437744,
"start": 517,
"tag": "EMAIL",
"value": "email2@foo.bar"
},
{
"context": "n query\", (done)->\n\t\t\t@UserGetter.getUser email: 'foo@bar.com', {}, (error, user) =>\n\t\t\t\terror.should.exist\n\t\t\t",
"end": 1656,
"score": 0.9998957514762878,
"start": 1645,
"tag": "EMAIL",
"value": "foo@bar.com"
},
{
"context": "etter.getUser = sinon.stub().callsArgWith(2, null, @fakeUser)\n\t\t\tprojection = email: 1, emails: 1\n\t\t\t@UserGett",
"end": 1981,
"score": 0.6672317385673523,
"start": 1972,
"tag": "USERNAME",
"value": "@fakeUser"
},
{
"context": "l: 1, emails: 1\n\t\t\t@UserGetter.getUserFullEmails @fakeUser._id, (error, fullEmails) =>\n\t\t\t\t@UserGetter.g",
"end": 2057,
"score": 0.5911335945129395,
"start": 2053,
"tag": "USERNAME",
"value": "fake"
},
{
"context": "ould.equal true\n\t\t\t\t@UserGetter.getUser.calledWith(@fakeUser._id, projection).should.equal true\n\t\t\t\tdone()\n\n\t\t",
"end": 2183,
"score": 0.6240109801292419,
"start": 2174,
"tag": "USERNAME",
"value": "@fakeUser"
},
{
"context": "etter.getUser = sinon.stub().callsArgWith(2, null, @fakeUser)\n\t\t\t@UserGetter.getUserFullEmails @fakeUser._id, ",
"end": 2342,
"score": 0.8592618107795715,
"start": 2333,
"tag": "USERNAME",
"value": "@fakeUser"
},
{
"context": "ull, @fakeUser)\n\t\t\t@UserGetter.getUserFullEmails @fakeUser._id, (error, fullEmails) =>\n\t\t\t\tassert.deepEqual ",
"end": 2386,
"score": 0.6665136218070984,
"start": 2378,
"tag": "USERNAME",
"value": "fakeUser"
},
{
"context": "\t\t\t\tassert.deepEqual fullEmails, [\n\t\t\t\t\t{ email: 'email1@foo.bar', reversedHostname: 'rab.oof', default: false }\n\t",
"end": 2479,
"score": 0.9995614886283875,
"start": 2465,
"tag": "EMAIL",
"value": "email1@foo.bar"
},
{
"context": "tname: 'rab.oof', default: false }\n\t\t\t\t\t{ email: 'email2@foo.bar', reversedHostname: 'rab.oof', default: true }\n\t\t",
"end": 2557,
"score": 0.9995595812797546,
"start": 2543,
"tag": "EMAIL",
"value": "email2@foo.bar"
},
{
"context": "etter.getUser = sinon.stub().callsArgWith(2, null, @fakeUser)\n\t\t\taffiliationsData = [\n\t\t\t\t{\n\t\t\t\t\temail: 'email",
"end": 2739,
"score": 0.8587238788604736,
"start": 2730,
"tag": "USERNAME",
"value": "@fakeUser"
},
{
"context": "eUser)\n\t\t\taffiliationsData = [\n\t\t\t\t{\n\t\t\t\t\temail: 'email1@foo.bar'\n\t\t\t\t\trole: 'Prof'\n\t\t\t\t\tdepartment: 'Maths'\n\t\t\t\t\t",
"end": 2798,
"score": 0.9998530745506287,
"start": 2784,
"tag": "EMAIL",
"value": "email1@foo.bar"
},
{
"context": "sert.deepEqual fullEmails, [\n\t\t\t\t\t{\n\t\t\t\t\t\temail: 'email1@foo.bar',\n\t\t\t\t\t\treversedHostname: 'rab.oof'\n\t\t\t\t\t\tdefault",
"end": 3146,
"score": 0.9998195171356201,
"start": 3132,
"tag": "EMAIL",
"value": "email1@foo.bar"
},
{
"context": "e: affiliationsData[0].role\n\t\t\t\t\t}\n\t\t\t\t\t{ email: 'email2@foo.bar', reversedHostname: 'rab.oof', default: true }\n\t\t",
"end": 3445,
"score": 0.9998998641967773,
"start": 3431,
"tag": "EMAIL",
"value": "email2@foo.bar"
},
{
"context": "et user when it has no emails field\", (done)->\n\t\t\t@fakeUser =\n\t\t\t\t_id: '12390i'\n\t\t\t\temail: 'email2@foo.bar'\n\t",
"end": 3584,
"score": 0.8904115557670593,
"start": 3575,
"tag": "USERNAME",
"value": "@fakeUser"
},
{
"context": "e)->\n\t\t\t@fakeUser =\n\t\t\t\t_id: '12390i'\n\t\t\t\temail: 'email2@foo.bar'\n\t\t\t@UserGetter.getUser = sinon.stub().callsArgWi",
"end": 3631,
"score": 0.9998977780342102,
"start": 3617,
"tag": "EMAIL",
"value": "email2@foo.bar"
},
{
"context": "etter.getUser = sinon.stub().callsArgWith(2, null, @fakeUser)\n\t\t\tprojection = email: 1, emails: 1\n\t\t\t@UserGett",
"end": 3702,
"score": 0.9691948294639587,
"start": 3693,
"tag": "USERNAME",
"value": "@fakeUser"
},
{
"context": "ail: 1, emails: 1\n\t\t\t@UserGetter.getUserFullEmails @fakeUser._id, (error, fullEmails) =>\n\t\t\t\t@UserGetter.getUs",
"end": 3782,
"score": 0.9254056811332703,
"start": 3773,
"tag": "USERNAME",
"value": "@fakeUser"
},
{
"context": "ould.equal true\n\t\t\t\t@UserGetter.getUser.calledWith(@fakeUser._id, projection).should.equal true\n\t\t\t\tassert.dee",
"end": 3904,
"score": 0.9890190958976746,
"start": 3895,
"tag": "USERNAME",
"value": "@fakeUser"
},
{
"context": " \"query user by main email\", (done)->\n\t\t\temail = 'hello@world.com'\n\t\t\tprojection = emails: 1\n\t\t\t@UserGetter.getUser",
"end": 4092,
"score": 0.9999152421951294,
"start": 4077,
"tag": "EMAIL",
"value": "hello@world.com"
},
{
"context": "\t\tit \"return user if found\", (done)->\n\t\t\temail = 'hello@world.com'\n\t\t\t@UserGetter.getUserByMainEmail email, (error,",
"end": 4373,
"score": 0.9999208450317383,
"start": 4358,
"tag": "EMAIL",
"value": "hello@world.com"
},
{
"context": "email, (error, user) =>\n\t\t\t\tuser.should.deep.equal @fakeUser\n\t\t\t\tdone()\n\n\t\tit \"trim email\", (done)->\n\t\t\temail ",
"end": 4469,
"score": 0.8922954201698303,
"start": 4460,
"tag": "USERNAME",
"value": "@fakeUser"
},
{
"context": "\t\tdone()\n\n\t\tit \"trim email\", (done)->\n\t\t\temail = 'hello@world.com'\n\t\t\t@UserGetter.getUserByMainEmail \" #{email} \", ",
"end": 4537,
"score": 0.9999237060546875,
"start": 4522,
"tag": "EMAIL",
"value": "hello@world.com"
},
{
"context": " \"query user for any email\", (done)->\n\t\t\temail = 'hello@world.com'\n\t\t\texpectedQuery =\n\t\t\t\temails: { $exists: true }",
"end": 4813,
"score": 0.9999219179153442,
"start": 4798,
"tag": "EMAIL",
"value": "hello@world.com"
},
{
"context": "tion).should.equal true\n\t\t\t\tuser.should.deep.equal @fakeUser\n\t\t\t\tdone()\n\n\t\tit \"query contains $exists:true so ",
"end": 5097,
"score": 0.9274594783782959,
"start": 5088,
"tag": "USERNAME",
"value": "@fakeUser"
},
{
"context": "\t@findOne.callsArgWith(2, null, null)\n\t\t\temail = 'hello@world.com'\n\t\t\tprojection = emails: 1\n\t\t\t@UserGetter.getUser",
"end": 5493,
"score": 0.9997593760490417,
"start": 5478,
"tag": "EMAIL",
"value": "hello@world.com"
},
{
"context": "UserGetter.getUserByAnyEmail.callsArgWith(1, null, @fakeUser)\n\t\t\t@UserGetter.ensureUniqueEmailAddress @newEmai",
"end": 6393,
"score": 0.9276793599128723,
"start": 6384,
"tag": "USERNAME",
"value": "@fakeUser"
}
] | test/unit/coffee/User/UserGetterTests.coffee | shyoshyo/web-sharelatex | 1 | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/User/UserGetter"
expect = require("chai").expect
Errors = require "../../../../app/js/Features/Errors/Errors"
describe "UserGetter", ->
beforeEach ->
@fakeUser =
_id: '12390i'
email: 'email2@foo.bar'
emails: [
{ email: 'email1@foo.bar', reversedHostname: 'rab.oof' }
{ email: 'email2@foo.bar', reversedHostname: 'rab.oof' }
]
@findOne = sinon.stub().callsArgWith(2, null, @fakeUser)
@find = sinon.stub().callsArgWith(2, null, [ @fakeUser ])
@Mongo =
db: users:
findOne: @findOne
find: @find
ObjectId: (id) -> return id
settings = apis: { v1: { url: 'v1.url', user: '', pass: '' } }
@getUserAffiliations = sinon.stub().callsArgWith(1, null, [])
@UserGetter = SandboxedModule.require modulePath, requires:
"logger-sharelatex": log:->
"../../infrastructure/mongojs": @Mongo
"metrics-sharelatex": timeAsyncMethod: sinon.stub()
'settings-sharelatex': settings
'../Institutions/InstitutionsAPI':
getUserAffiliations: @getUserAffiliations
"../Errors/Errors": Errors
describe "getUser", ->
it "should get user", (done)->
query = _id: 'foo'
projection = email: 1
@UserGetter.getUser query, projection, (error, user) =>
@findOne.called.should.equal true
@findOne.calledWith(query, projection).should.equal true
user.should.deep.equal @fakeUser
done()
it "should not allow email in query", (done)->
@UserGetter.getUser email: 'foo@bar.com', {}, (error, user) =>
error.should.exist
done()
it "should not allow null query", (done)->
@UserGetter.getUser null, {}, (error, user) =>
error.should.exist
done()
describe "getUserFullEmails", ->
it "should get user", (done)->
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, @fakeUser)
projection = email: 1, emails: 1
@UserGetter.getUserFullEmails @fakeUser._id, (error, fullEmails) =>
@UserGetter.getUser.called.should.equal true
@UserGetter.getUser.calledWith(@fakeUser._id, projection).should.equal true
done()
it "should fetch emails data", (done)->
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, @fakeUser)
@UserGetter.getUserFullEmails @fakeUser._id, (error, fullEmails) =>
assert.deepEqual fullEmails, [
{ email: 'email1@foo.bar', reversedHostname: 'rab.oof', default: false }
{ email: 'email2@foo.bar', reversedHostname: 'rab.oof', default: true }
]
done()
it "should merge affiliation data", (done)->
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, @fakeUser)
affiliationsData = [
{
email: 'email1@foo.bar'
role: 'Prof'
department: 'Maths'
inferred: false
institution: { name: 'University Name', isUniversity: true }
}
]
@getUserAffiliations.callsArgWith(1, null, affiliationsData)
@UserGetter.getUserFullEmails @fakeUser._id, (error, fullEmails) =>
assert.deepEqual fullEmails, [
{
email: 'email1@foo.bar',
reversedHostname: 'rab.oof'
default: false
affiliation:
institution: affiliationsData[0].institution
inferred: affiliationsData[0].inferred
department: affiliationsData[0].department
role: affiliationsData[0].role
}
{ email: 'email2@foo.bar', reversedHostname: 'rab.oof', default: true }
]
done()
it "should get user when it has no emails field", (done)->
@fakeUser =
_id: '12390i'
email: 'email2@foo.bar'
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, @fakeUser)
projection = email: 1, emails: 1
@UserGetter.getUserFullEmails @fakeUser._id, (error, fullEmails) =>
@UserGetter.getUser.called.should.equal true
@UserGetter.getUser.calledWith(@fakeUser._id, projection).should.equal true
assert.deepEqual fullEmails, []
done()
describe "getUserbyMainEmail", ->
it "query user by main email", (done)->
email = 'hello@world.com'
projection = emails: 1
@UserGetter.getUserByMainEmail email, projection, (error, user) =>
@findOne.called.should.equal true
@findOne.calledWith(email: email, projection).should.equal true
done()
it "return user if found", (done)->
email = 'hello@world.com'
@UserGetter.getUserByMainEmail email, (error, user) =>
user.should.deep.equal @fakeUser
done()
it "trim email", (done)->
email = 'hello@world.com'
@UserGetter.getUserByMainEmail " #{email} ", (error, user) =>
@findOne.called.should.equal true
@findOne.calledWith(email: email).should.equal true
done()
describe "getUserByAnyEmail", ->
it "query user for any email", (done)->
email = 'hello@world.com'
expectedQuery =
emails: { $exists: true }
'emails.email': email
projection = emails: 1
@UserGetter.getUserByAnyEmail " #{email} ", projection, (error, user) =>
@findOne.calledWith(expectedQuery, projection).should.equal true
user.should.deep.equal @fakeUser
done()
it "query contains $exists:true so partial index is used", (done)->
expectedQuery =
emails: { $exists: true }
'emails.email': ''
@UserGetter.getUserByAnyEmail '', {}, (error, user) =>
@findOne.calledWith(expectedQuery, {}).should.equal true
done()
it "checks main email as well", (done)->
@findOne.callsArgWith(2, null, null)
email = 'hello@world.com'
projection = emails: 1
@UserGetter.getUserByAnyEmail " #{email} ", projection, (error, user) =>
@findOne.calledTwice.should.equal true
@findOne.calledWith(email: email, projection).should.equal true
done()
describe "getUsersByHostname", ->
it "should find user by hostname", (done)->
hostname = "bar.foo"
expectedQuery =
emails: {$exists: true },
'emails.reversedHostname': hostname.split('').reverse().join('')
projection = emails: 1
@UserGetter.getUsersByHostname hostname, projection, (error, users) =>
@find.calledOnce.should.equal true
@find.calledWith(expectedQuery, projection).should.equal true
done()
describe 'ensureUniqueEmailAddress', ->
beforeEach ->
@UserGetter.getUserByAnyEmail = sinon.stub()
it 'should return error if existing user is found', (done)->
@UserGetter.getUserByAnyEmail.callsArgWith(1, null, @fakeUser)
@UserGetter.ensureUniqueEmailAddress @newEmail, (err)=>
should.exist(err)
expect(err).to.be.an.instanceof(Errors.EmailExistsError)
err.message.should.equal 'alread_exists'
done()
it 'should return null if no user is found', (done)->
@UserGetter.getUserByAnyEmail.callsArgWith(1)
@UserGetter.ensureUniqueEmailAddress @newEmail, (err)=>
should.not.exist(err)
done()
| 225343 | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/User/UserGetter"
expect = require("chai").expect
Errors = require "../../../../app/js/Features/Errors/Errors"
describe "UserGetter", ->
beforeEach ->
@fakeUser =
_id: '12390i'
email: '<EMAIL>'
emails: [
{ email: '<EMAIL>', reversedHostname: 'rab.oof' }
{ email: '<EMAIL>', reversedHostname: 'rab.oof' }
]
@findOne = sinon.stub().callsArgWith(2, null, @fakeUser)
@find = sinon.stub().callsArgWith(2, null, [ @fakeUser ])
@Mongo =
db: users:
findOne: @findOne
find: @find
ObjectId: (id) -> return id
settings = apis: { v1: { url: 'v1.url', user: '', pass: '' } }
@getUserAffiliations = sinon.stub().callsArgWith(1, null, [])
@UserGetter = SandboxedModule.require modulePath, requires:
"logger-sharelatex": log:->
"../../infrastructure/mongojs": @Mongo
"metrics-sharelatex": timeAsyncMethod: sinon.stub()
'settings-sharelatex': settings
'../Institutions/InstitutionsAPI':
getUserAffiliations: @getUserAffiliations
"../Errors/Errors": Errors
describe "getUser", ->
it "should get user", (done)->
query = _id: 'foo'
projection = email: 1
@UserGetter.getUser query, projection, (error, user) =>
@findOne.called.should.equal true
@findOne.calledWith(query, projection).should.equal true
user.should.deep.equal @fakeUser
done()
it "should not allow email in query", (done)->
@UserGetter.getUser email: '<EMAIL>', {}, (error, user) =>
error.should.exist
done()
it "should not allow null query", (done)->
@UserGetter.getUser null, {}, (error, user) =>
error.should.exist
done()
describe "getUserFullEmails", ->
it "should get user", (done)->
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, @fakeUser)
projection = email: 1, emails: 1
@UserGetter.getUserFullEmails @fakeUser._id, (error, fullEmails) =>
@UserGetter.getUser.called.should.equal true
@UserGetter.getUser.calledWith(@fakeUser._id, projection).should.equal true
done()
it "should fetch emails data", (done)->
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, @fakeUser)
@UserGetter.getUserFullEmails @fakeUser._id, (error, fullEmails) =>
assert.deepEqual fullEmails, [
{ email: '<EMAIL>', reversedHostname: 'rab.oof', default: false }
{ email: '<EMAIL>', reversedHostname: 'rab.oof', default: true }
]
done()
it "should merge affiliation data", (done)->
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, @fakeUser)
affiliationsData = [
{
email: '<EMAIL>'
role: 'Prof'
department: 'Maths'
inferred: false
institution: { name: 'University Name', isUniversity: true }
}
]
@getUserAffiliations.callsArgWith(1, null, affiliationsData)
@UserGetter.getUserFullEmails @fakeUser._id, (error, fullEmails) =>
assert.deepEqual fullEmails, [
{
email: '<EMAIL>',
reversedHostname: 'rab.oof'
default: false
affiliation:
institution: affiliationsData[0].institution
inferred: affiliationsData[0].inferred
department: affiliationsData[0].department
role: affiliationsData[0].role
}
{ email: '<EMAIL>', reversedHostname: 'rab.oof', default: true }
]
done()
it "should get user when it has no emails field", (done)->
@fakeUser =
_id: '12390i'
email: '<EMAIL>'
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, @fakeUser)
projection = email: 1, emails: 1
@UserGetter.getUserFullEmails @fakeUser._id, (error, fullEmails) =>
@UserGetter.getUser.called.should.equal true
@UserGetter.getUser.calledWith(@fakeUser._id, projection).should.equal true
assert.deepEqual fullEmails, []
done()
describe "getUserbyMainEmail", ->
it "query user by main email", (done)->
email = '<EMAIL>'
projection = emails: 1
@UserGetter.getUserByMainEmail email, projection, (error, user) =>
@findOne.called.should.equal true
@findOne.calledWith(email: email, projection).should.equal true
done()
it "return user if found", (done)->
email = '<EMAIL>'
@UserGetter.getUserByMainEmail email, (error, user) =>
user.should.deep.equal @fakeUser
done()
it "trim email", (done)->
email = '<EMAIL>'
@UserGetter.getUserByMainEmail " #{email} ", (error, user) =>
@findOne.called.should.equal true
@findOne.calledWith(email: email).should.equal true
done()
describe "getUserByAnyEmail", ->
it "query user for any email", (done)->
email = '<EMAIL>'
expectedQuery =
emails: { $exists: true }
'emails.email': email
projection = emails: 1
@UserGetter.getUserByAnyEmail " #{email} ", projection, (error, user) =>
@findOne.calledWith(expectedQuery, projection).should.equal true
user.should.deep.equal @fakeUser
done()
it "query contains $exists:true so partial index is used", (done)->
expectedQuery =
emails: { $exists: true }
'emails.email': ''
@UserGetter.getUserByAnyEmail '', {}, (error, user) =>
@findOne.calledWith(expectedQuery, {}).should.equal true
done()
it "checks main email as well", (done)->
@findOne.callsArgWith(2, null, null)
email = '<EMAIL>'
projection = emails: 1
@UserGetter.getUserByAnyEmail " #{email} ", projection, (error, user) =>
@findOne.calledTwice.should.equal true
@findOne.calledWith(email: email, projection).should.equal true
done()
describe "getUsersByHostname", ->
it "should find user by hostname", (done)->
hostname = "bar.foo"
expectedQuery =
emails: {$exists: true },
'emails.reversedHostname': hostname.split('').reverse().join('')
projection = emails: 1
@UserGetter.getUsersByHostname hostname, projection, (error, users) =>
@find.calledOnce.should.equal true
@find.calledWith(expectedQuery, projection).should.equal true
done()
describe 'ensureUniqueEmailAddress', ->
beforeEach ->
@UserGetter.getUserByAnyEmail = sinon.stub()
it 'should return error if existing user is found', (done)->
@UserGetter.getUserByAnyEmail.callsArgWith(1, null, @fakeUser)
@UserGetter.ensureUniqueEmailAddress @newEmail, (err)=>
should.exist(err)
expect(err).to.be.an.instanceof(Errors.EmailExistsError)
err.message.should.equal 'alread_exists'
done()
it 'should return null if no user is found', (done)->
@UserGetter.getUserByAnyEmail.callsArgWith(1)
@UserGetter.ensureUniqueEmailAddress @newEmail, (err)=>
should.not.exist(err)
done()
| true | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/User/UserGetter"
expect = require("chai").expect
Errors = require "../../../../app/js/Features/Errors/Errors"
describe "UserGetter", ->
beforeEach ->
@fakeUser =
_id: '12390i'
email: 'PI:EMAIL:<EMAIL>END_PI'
emails: [
{ email: 'PI:EMAIL:<EMAIL>END_PI', reversedHostname: 'rab.oof' }
{ email: 'PI:EMAIL:<EMAIL>END_PI', reversedHostname: 'rab.oof' }
]
@findOne = sinon.stub().callsArgWith(2, null, @fakeUser)
@find = sinon.stub().callsArgWith(2, null, [ @fakeUser ])
@Mongo =
db: users:
findOne: @findOne
find: @find
ObjectId: (id) -> return id
settings = apis: { v1: { url: 'v1.url', user: '', pass: '' } }
@getUserAffiliations = sinon.stub().callsArgWith(1, null, [])
@UserGetter = SandboxedModule.require modulePath, requires:
"logger-sharelatex": log:->
"../../infrastructure/mongojs": @Mongo
"metrics-sharelatex": timeAsyncMethod: sinon.stub()
'settings-sharelatex': settings
'../Institutions/InstitutionsAPI':
getUserAffiliations: @getUserAffiliations
"../Errors/Errors": Errors
describe "getUser", ->
it "should get user", (done)->
query = _id: 'foo'
projection = email: 1
@UserGetter.getUser query, projection, (error, user) =>
@findOne.called.should.equal true
@findOne.calledWith(query, projection).should.equal true
user.should.deep.equal @fakeUser
done()
it "should not allow email in query", (done)->
@UserGetter.getUser email: 'PI:EMAIL:<EMAIL>END_PI', {}, (error, user) =>
error.should.exist
done()
it "should not allow null query", (done)->
@UserGetter.getUser null, {}, (error, user) =>
error.should.exist
done()
describe "getUserFullEmails", ->
it "should get user", (done)->
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, @fakeUser)
projection = email: 1, emails: 1
@UserGetter.getUserFullEmails @fakeUser._id, (error, fullEmails) =>
@UserGetter.getUser.called.should.equal true
@UserGetter.getUser.calledWith(@fakeUser._id, projection).should.equal true
done()
it "should fetch emails data", (done)->
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, @fakeUser)
@UserGetter.getUserFullEmails @fakeUser._id, (error, fullEmails) =>
assert.deepEqual fullEmails, [
{ email: 'PI:EMAIL:<EMAIL>END_PI', reversedHostname: 'rab.oof', default: false }
{ email: 'PI:EMAIL:<EMAIL>END_PI', reversedHostname: 'rab.oof', default: true }
]
done()
it "should merge affiliation data", (done)->
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, @fakeUser)
affiliationsData = [
{
email: 'PI:EMAIL:<EMAIL>END_PI'
role: 'Prof'
department: 'Maths'
inferred: false
institution: { name: 'University Name', isUniversity: true }
}
]
@getUserAffiliations.callsArgWith(1, null, affiliationsData)
@UserGetter.getUserFullEmails @fakeUser._id, (error, fullEmails) =>
assert.deepEqual fullEmails, [
{
email: 'PI:EMAIL:<EMAIL>END_PI',
reversedHostname: 'rab.oof'
default: false
affiliation:
institution: affiliationsData[0].institution
inferred: affiliationsData[0].inferred
department: affiliationsData[0].department
role: affiliationsData[0].role
}
{ email: 'PI:EMAIL:<EMAIL>END_PI', reversedHostname: 'rab.oof', default: true }
]
done()
it "should get user when it has no emails field", (done)->
@fakeUser =
_id: '12390i'
email: 'PI:EMAIL:<EMAIL>END_PI'
@UserGetter.getUser = sinon.stub().callsArgWith(2, null, @fakeUser)
projection = email: 1, emails: 1
@UserGetter.getUserFullEmails @fakeUser._id, (error, fullEmails) =>
@UserGetter.getUser.called.should.equal true
@UserGetter.getUser.calledWith(@fakeUser._id, projection).should.equal true
assert.deepEqual fullEmails, []
done()
describe "getUserbyMainEmail", ->
it "query user by main email", (done)->
email = 'PI:EMAIL:<EMAIL>END_PI'
projection = emails: 1
@UserGetter.getUserByMainEmail email, projection, (error, user) =>
@findOne.called.should.equal true
@findOne.calledWith(email: email, projection).should.equal true
done()
it "return user if found", (done)->
email = 'PI:EMAIL:<EMAIL>END_PI'
@UserGetter.getUserByMainEmail email, (error, user) =>
user.should.deep.equal @fakeUser
done()
it "trim email", (done)->
email = 'PI:EMAIL:<EMAIL>END_PI'
@UserGetter.getUserByMainEmail " #{email} ", (error, user) =>
@findOne.called.should.equal true
@findOne.calledWith(email: email).should.equal true
done()
describe "getUserByAnyEmail", ->
it "query user for any email", (done)->
email = 'PI:EMAIL:<EMAIL>END_PI'
expectedQuery =
emails: { $exists: true }
'emails.email': email
projection = emails: 1
@UserGetter.getUserByAnyEmail " #{email} ", projection, (error, user) =>
@findOne.calledWith(expectedQuery, projection).should.equal true
user.should.deep.equal @fakeUser
done()
it "query contains $exists:true so partial index is used", (done)->
expectedQuery =
emails: { $exists: true }
'emails.email': ''
@UserGetter.getUserByAnyEmail '', {}, (error, user) =>
@findOne.calledWith(expectedQuery, {}).should.equal true
done()
it "checks main email as well", (done)->
@findOne.callsArgWith(2, null, null)
email = 'PI:EMAIL:<EMAIL>END_PI'
projection = emails: 1
@UserGetter.getUserByAnyEmail " #{email} ", projection, (error, user) =>
@findOne.calledTwice.should.equal true
@findOne.calledWith(email: email, projection).should.equal true
done()
describe "getUsersByHostname", ->
it "should find user by hostname", (done)->
hostname = "bar.foo"
expectedQuery =
emails: {$exists: true },
'emails.reversedHostname': hostname.split('').reverse().join('')
projection = emails: 1
@UserGetter.getUsersByHostname hostname, projection, (error, users) =>
@find.calledOnce.should.equal true
@find.calledWith(expectedQuery, projection).should.equal true
done()
describe 'ensureUniqueEmailAddress', ->
beforeEach ->
@UserGetter.getUserByAnyEmail = sinon.stub()
it 'should return error if existing user is found', (done)->
@UserGetter.getUserByAnyEmail.callsArgWith(1, null, @fakeUser)
@UserGetter.ensureUniqueEmailAddress @newEmail, (err)=>
should.exist(err)
expect(err).to.be.an.instanceof(Errors.EmailExistsError)
err.message.should.equal 'alread_exists'
done()
it 'should return null if no user is found', (done)->
@UserGetter.getUserByAnyEmail.callsArgWith(1)
@UserGetter.ensureUniqueEmailAddress @newEmail, (err)=>
should.not.exist(err)
done()
|
[
{
"context": "4-718f-4d41-b348-5b2ef578ad06'\n password_reset: 'a57c6003-5beb-4717-b1f9-8a5b38e08d33'\n share_licenses_joiner: 'b413fc9d-34a0-45aa-90b",
"end": 1582,
"score": 0.9993028044700623,
"start": 1546,
"tag": "PASSWORD",
"value": "a57c6003-5beb-4717-b1f9-8a5b38e08d33"
}
] | server/sendgrid.coffee | IngJuanRuiz/codecombat | 0 | config = require '../server_config'
sendgridAPI = require '@sendgrid/mail'
sendgridAPIKey = config.mail.sendgridAPIKey
log = require 'winston'
Promise = require 'bluebird'
debug = not config.isProduction
module.exports.api =
send: (context) ->
#log.debug('Tried to send email via SendGrid with context: ', JSON.stringify(context, null, ' '))
context.substitutions ?= {}
context.substitutions.email ?= context.to.email # Make sure that {{email}} works in unsubscribe links throughout our templates
Promise.resolve()
if sendgridAPIKey
sendgridAPI.setApiKey(sendgridAPIKey);
module.exports.api = sendgridAPI
module.exports.templates =
coppa_deny_parent_signup: 'cde61ac8-5f60-4fb8-aa35-d409f95d5a91'
share_progress_email: '277b031a-2494-4138-9faa-a11938b86b00'
welcome_email_user: '80ca8690-0bbc-4f3b-9f18-15177a097e7f'
welcome_email_student: '76647674-0208-4650-8dfc-1fd521982cf6'
welcome_email_teacher: '12f68ec3-6d50-4816-8967-2e626c0831e9'
verify_email: '6ee6cb9a-aa3f-4766-9936-260e8aaab378'
ladder_update_email: 'ef2b22dd-f02f-46d8-9ea1-edb3d64696a4' # TODO: template logic needs work, not currently sending
patch_created: '6be4c2c5-d3a5-40f6-a737-8bc152b8d08a'
change_made_notify_watcher: '802ebec8-eebd-4b01-b58e-6997992319ce'
plain_text_email: '6dfd5cbb-428f-4537-91c8-d571b2134b33'
next_steps_email: '34e6400f-7ea3-4c69-a0ff-9485bebb95b9'
course_invite_email: 'd426cfd1-3b70-4ce6-82ea-a3baccb91c06'
subscription_welcome_email: '473f6a34-718f-4d41-b348-5b2ef578ad06'
password_reset: 'a57c6003-5beb-4717-b1f9-8a5b38e08d33'
share_licenses_joiner: 'b413fc9d-34a0-45aa-90b8-f8fa5ea9e1d5'
teacher_signup_instructions: '31b608e9-449e-46ac-9c3c-6c112899cf30'
teacher_game_dev_project_share: 'b9b62cdb-62a8-4e4f-98a2-f9a555e92a1a'
delete_inactive_eu_users: 'a8434f2e-0b59-40a0-bf1a-97678bc09f15'
| 48497 | config = require '../server_config'
sendgridAPI = require '@sendgrid/mail'
sendgridAPIKey = config.mail.sendgridAPIKey
log = require 'winston'
Promise = require 'bluebird'
debug = not config.isProduction
module.exports.api =
send: (context) ->
#log.debug('Tried to send email via SendGrid with context: ', JSON.stringify(context, null, ' '))
context.substitutions ?= {}
context.substitutions.email ?= context.to.email # Make sure that {{email}} works in unsubscribe links throughout our templates
Promise.resolve()
if sendgridAPIKey
sendgridAPI.setApiKey(sendgridAPIKey);
module.exports.api = sendgridAPI
module.exports.templates =
coppa_deny_parent_signup: 'cde61ac8-5f60-4fb8-aa35-d409f95d5a91'
share_progress_email: '277b031a-2494-4138-9faa-a11938b86b00'
welcome_email_user: '80ca8690-0bbc-4f3b-9f18-15177a097e7f'
welcome_email_student: '76647674-0208-4650-8dfc-1fd521982cf6'
welcome_email_teacher: '12f68ec3-6d50-4816-8967-2e626c0831e9'
verify_email: '6ee6cb9a-aa3f-4766-9936-260e8aaab378'
ladder_update_email: 'ef2b22dd-f02f-46d8-9ea1-edb3d64696a4' # TODO: template logic needs work, not currently sending
patch_created: '6be4c2c5-d3a5-40f6-a737-8bc152b8d08a'
change_made_notify_watcher: '802ebec8-eebd-4b01-b58e-6997992319ce'
plain_text_email: '6dfd5cbb-428f-4537-91c8-d571b2134b33'
next_steps_email: '34e6400f-7ea3-4c69-a0ff-9485bebb95b9'
course_invite_email: 'd426cfd1-3b70-4ce6-82ea-a3baccb91c06'
subscription_welcome_email: '473f6a34-718f-4d41-b348-5b2ef578ad06'
password_reset: '<PASSWORD>'
share_licenses_joiner: 'b413fc9d-34a0-45aa-90b8-f8fa5ea9e1d5'
teacher_signup_instructions: '31b608e9-449e-46ac-9c3c-6c112899cf30'
teacher_game_dev_project_share: 'b9b62cdb-62a8-4e4f-98a2-f9a555e92a1a'
delete_inactive_eu_users: 'a8434f2e-0b59-40a0-bf1a-97678bc09f15'
| true | config = require '../server_config'
sendgridAPI = require '@sendgrid/mail'
sendgridAPIKey = config.mail.sendgridAPIKey
log = require 'winston'
Promise = require 'bluebird'
debug = not config.isProduction
module.exports.api =
send: (context) ->
#log.debug('Tried to send email via SendGrid with context: ', JSON.stringify(context, null, ' '))
context.substitutions ?= {}
context.substitutions.email ?= context.to.email # Make sure that {{email}} works in unsubscribe links throughout our templates
Promise.resolve()
if sendgridAPIKey
sendgridAPI.setApiKey(sendgridAPIKey);
module.exports.api = sendgridAPI
module.exports.templates =
coppa_deny_parent_signup: 'cde61ac8-5f60-4fb8-aa35-d409f95d5a91'
share_progress_email: '277b031a-2494-4138-9faa-a11938b86b00'
welcome_email_user: '80ca8690-0bbc-4f3b-9f18-15177a097e7f'
welcome_email_student: '76647674-0208-4650-8dfc-1fd521982cf6'
welcome_email_teacher: '12f68ec3-6d50-4816-8967-2e626c0831e9'
verify_email: '6ee6cb9a-aa3f-4766-9936-260e8aaab378'
ladder_update_email: 'ef2b22dd-f02f-46d8-9ea1-edb3d64696a4' # TODO: template logic needs work, not currently sending
patch_created: '6be4c2c5-d3a5-40f6-a737-8bc152b8d08a'
change_made_notify_watcher: '802ebec8-eebd-4b01-b58e-6997992319ce'
plain_text_email: '6dfd5cbb-428f-4537-91c8-d571b2134b33'
next_steps_email: '34e6400f-7ea3-4c69-a0ff-9485bebb95b9'
course_invite_email: 'd426cfd1-3b70-4ce6-82ea-a3baccb91c06'
subscription_welcome_email: '473f6a34-718f-4d41-b348-5b2ef578ad06'
password_reset: 'PI:PASSWORD:<PASSWORD>END_PI'
share_licenses_joiner: 'b413fc9d-34a0-45aa-90b8-f8fa5ea9e1d5'
teacher_signup_instructions: '31b608e9-449e-46ac-9c3c-6c112899cf30'
teacher_game_dev_project_share: 'b9b62cdb-62a8-4e4f-98a2-f9a555e92a1a'
delete_inactive_eu_users: 'a8434f2e-0b59-40a0-bf1a-97678bc09f15'
|
[
{
"context": "iew Rule to disallow a negated condition\n# @author Alberto Rodríguez\n###\n'use strict'\n\n#------------------------------",
"end": 85,
"score": 0.9998540282249451,
"start": 68,
"tag": "NAME",
"value": "Alberto Rodríguez"
}
] | src/rules/no-negated-condition.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Rule to disallow a negated condition
# @author Alberto Rodríguez
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'disallow negated conditions'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/no-negated-condition'
schema: [
type: 'object'
properties:
requireElse:
type: 'boolean'
additionalProperties: no
]
create: (context) ->
{requireElse} = context.options[0] ? {}
###*
# Determines if a given node is an if-else without a condition on the else
# @param {ASTNode} node The node to check.
# @returns {boolean} True if the node has an else without an if.
# @private
###
hasElseWithoutCondition = (node) ->
node.alternate and node.alternate.type isnt 'IfStatement'
###*
# Determines if a given node is a negated unary expression
# @param {Object} test The test object to check.
# @returns {boolean} True if the node is a negated unary expression.
# @private
###
isNegatedUnaryExpression = (test) ->
test.type is 'UnaryExpression' and test.operator in ['!', 'not']
###*
# Determines if a given node is a negated binary expression
# @param {Test} test The test to check.
# @returns {boolean} True if the node is a negated binary expression.
# @private
###
isNegatedBinaryExpression = (test) ->
test.type is 'BinaryExpression' and test.operator in ['!=', 'isnt']
###*
# Determines if a given node has a negated if expression
# @param {ASTNode} node The node to check.
# @returns {boolean} True if the node has a negated if expression.
# @private
###
isNegatedIf = (node) ->
isNegatedUnaryExpression(node.test) or isNegatedBinaryExpression node.test
checkNode = (node) ->
return unless not requireElse or hasElseWithoutCondition node
if isNegatedIf node
context.report {node, message: 'Unexpected negated condition.'}
IfStatement: checkNode
ConditionalExpression: checkNode
| 62137 | ###*
# @fileoverview Rule to disallow a negated condition
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'disallow negated conditions'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/no-negated-condition'
schema: [
type: 'object'
properties:
requireElse:
type: 'boolean'
additionalProperties: no
]
create: (context) ->
{requireElse} = context.options[0] ? {}
###*
# Determines if a given node is an if-else without a condition on the else
# @param {ASTNode} node The node to check.
# @returns {boolean} True if the node has an else without an if.
# @private
###
hasElseWithoutCondition = (node) ->
node.alternate and node.alternate.type isnt 'IfStatement'
###*
# Determines if a given node is a negated unary expression
# @param {Object} test The test object to check.
# @returns {boolean} True if the node is a negated unary expression.
# @private
###
isNegatedUnaryExpression = (test) ->
test.type is 'UnaryExpression' and test.operator in ['!', 'not']
###*
# Determines if a given node is a negated binary expression
# @param {Test} test The test to check.
# @returns {boolean} True if the node is a negated binary expression.
# @private
###
isNegatedBinaryExpression = (test) ->
test.type is 'BinaryExpression' and test.operator in ['!=', 'isnt']
###*
# Determines if a given node has a negated if expression
# @param {ASTNode} node The node to check.
# @returns {boolean} True if the node has a negated if expression.
# @private
###
isNegatedIf = (node) ->
isNegatedUnaryExpression(node.test) or isNegatedBinaryExpression node.test
checkNode = (node) ->
return unless not requireElse or hasElseWithoutCondition node
if isNegatedIf node
context.report {node, message: 'Unexpected negated condition.'}
IfStatement: checkNode
ConditionalExpression: checkNode
| true | ###*
# @fileoverview Rule to disallow a negated condition
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'disallow negated conditions'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/no-negated-condition'
schema: [
type: 'object'
properties:
requireElse:
type: 'boolean'
additionalProperties: no
]
create: (context) ->
{requireElse} = context.options[0] ? {}
###*
# Determines if a given node is an if-else without a condition on the else
# @param {ASTNode} node The node to check.
# @returns {boolean} True if the node has an else without an if.
# @private
###
hasElseWithoutCondition = (node) ->
node.alternate and node.alternate.type isnt 'IfStatement'
###*
# Determines if a given node is a negated unary expression
# @param {Object} test The test object to check.
# @returns {boolean} True if the node is a negated unary expression.
# @private
###
isNegatedUnaryExpression = (test) ->
test.type is 'UnaryExpression' and test.operator in ['!', 'not']
###*
# Determines if a given node is a negated binary expression
# @param {Test} test The test to check.
# @returns {boolean} True if the node is a negated binary expression.
# @private
###
isNegatedBinaryExpression = (test) ->
test.type is 'BinaryExpression' and test.operator in ['!=', 'isnt']
###*
# Determines if a given node has a negated if expression
# @param {ASTNode} node The node to check.
# @returns {boolean} True if the node has a negated if expression.
# @private
###
isNegatedIf = (node) ->
isNegatedUnaryExpression(node.test) or isNegatedBinaryExpression node.test
checkNode = (node) ->
return unless not requireElse or hasElseWithoutCondition node
if isNegatedIf node
context.report {node, message: 'Unexpected negated condition.'}
IfStatement: checkNode
ConditionalExpression: checkNode
|
[
{
"context": "m('title', $(this).val())\n return\n key = 'post'\n else\n key = /\\w{24}/.exec(window.location)[",
"end": 851,
"score": 0.7906361222267151,
"start": 847,
"tag": "KEY",
"value": "post"
}
] | assets/js/editor.coffee | zhy0216-collection/Gather | 0 | $ ->
names = []
add_name = (ele) ->
name = $(ele).text()
if name not in names
names.push(name)
for a in $('.username')
add_name a
for a in $('.reply_user')
add_name a
$('#content').elastic().atWho '@', {data: names}
$('.reply').click ->
reply = $(this)
floor = reply.data('floor')
user = reply.data('user')
reply_content = $("#content")
new_text = "##{floor} @#{user} "
if reply_content.val().trim().length is 0
new_text += ''
else
new_text = "\n#{new_text}"
reply_content.focus().val reply_content.val() + new_text
return false
if not window.localStorage
return
if $('#title').length != 0
$('#title').val(window.localStorage.getItem('title')).change ->
window.localStorage.setItem('title', $(this).val())
return
key = 'post'
else
key = /\w{24}/.exec(window.location)[0]
if not key
return
$('#content').val(window.localStorage.getItem(key)).change ->
window.localStorage.setItem(key, $(this).val())
return
$('form').submit ->
window.localStorage.setItem('title', '')
window.localStorage.setItem(key, '')
return
| 217269 | $ ->
names = []
add_name = (ele) ->
name = $(ele).text()
if name not in names
names.push(name)
for a in $('.username')
add_name a
for a in $('.reply_user')
add_name a
$('#content').elastic().atWho '@', {data: names}
$('.reply').click ->
reply = $(this)
floor = reply.data('floor')
user = reply.data('user')
reply_content = $("#content")
new_text = "##{floor} @#{user} "
if reply_content.val().trim().length is 0
new_text += ''
else
new_text = "\n#{new_text}"
reply_content.focus().val reply_content.val() + new_text
return false
if not window.localStorage
return
if $('#title').length != 0
$('#title').val(window.localStorage.getItem('title')).change ->
window.localStorage.setItem('title', $(this).val())
return
key = '<KEY>'
else
key = /\w{24}/.exec(window.location)[0]
if not key
return
$('#content').val(window.localStorage.getItem(key)).change ->
window.localStorage.setItem(key, $(this).val())
return
$('form').submit ->
window.localStorage.setItem('title', '')
window.localStorage.setItem(key, '')
return
| true | $ ->
names = []
add_name = (ele) ->
name = $(ele).text()
if name not in names
names.push(name)
for a in $('.username')
add_name a
for a in $('.reply_user')
add_name a
$('#content').elastic().atWho '@', {data: names}
$('.reply').click ->
reply = $(this)
floor = reply.data('floor')
user = reply.data('user')
reply_content = $("#content")
new_text = "##{floor} @#{user} "
if reply_content.val().trim().length is 0
new_text += ''
else
new_text = "\n#{new_text}"
reply_content.focus().val reply_content.val() + new_text
return false
if not window.localStorage
return
if $('#title').length != 0
$('#title').val(window.localStorage.getItem('title')).change ->
window.localStorage.setItem('title', $(this).val())
return
key = 'PI:KEY:<KEY>END_PI'
else
key = /\w{24}/.exec(window.location)[0]
if not key
return
$('#content').val(window.localStorage.getItem(key)).change ->
window.localStorage.setItem(key, $(this).val())
return
$('form').submit ->
window.localStorage.setItem('title', '')
window.localStorage.setItem(key, '')
return
|
[
{
"context": "= grammar.tokenizeLine '{\"Client SB1\": {\"token\": \"abcd1234\"}}'\n expect(tokens[0]).toEqual value: '{', sco",
"end": 579,
"score": 0.8402810096740723,
"start": 571,
"tag": "KEY",
"value": "abcd1234"
}
] | spec/nstba-spec.coffee | caleb531/language-sca | 2 | describe 'NSTBA grammar', ->
grammar = null
beforeEach ->
atom.config.set('core.useTreeSitterParsers', false)
waitsForPromise ->
atom.packages.activatePackage('language-json')
waitsForPromise ->
atom.packages.activatePackage('language-sca')
runs ->
grammar = atom.grammars.grammarForScopeName('source.json.sca.nstba')
it 'parses the grammar', ->
expect(grammar).toBeTruthy()
expect(grammar.scopeName).toBe 'source.json.sca.nstba'
it 'tokenizes JSON', ->
{tokens} = grammar.tokenizeLine '{"Client SB1": {"token": "abcd1234"}}'
expect(tokens[0]).toEqual value: '{', scopes: ['source.json.sca.nstba', 'meta.structure.dictionary.json', 'punctuation.definition.dictionary.begin.json']
expect(tokens[1]).toEqual value: '"', scopes: ['source.json.sca.nstba', 'meta.structure.dictionary.json', 'meta.structure.dictionary.key.json', 'string.quoted.double.json', 'punctuation.definition.string.begin.json']
expect(tokens[12]).toEqual value: '"', scopes: ['source.json.sca.nstba', 'meta.structure.dictionary.json', 'meta.structure.dictionary.value.json', 'meta.structure.dictionary.json', 'meta.structure.dictionary.value.json', 'string.quoted.double.json', 'punctuation.definition.string.begin.json']
| 48097 | describe 'NSTBA grammar', ->
grammar = null
beforeEach ->
atom.config.set('core.useTreeSitterParsers', false)
waitsForPromise ->
atom.packages.activatePackage('language-json')
waitsForPromise ->
atom.packages.activatePackage('language-sca')
runs ->
grammar = atom.grammars.grammarForScopeName('source.json.sca.nstba')
it 'parses the grammar', ->
expect(grammar).toBeTruthy()
expect(grammar.scopeName).toBe 'source.json.sca.nstba'
it 'tokenizes JSON', ->
{tokens} = grammar.tokenizeLine '{"Client SB1": {"token": "<KEY>"}}'
expect(tokens[0]).toEqual value: '{', scopes: ['source.json.sca.nstba', 'meta.structure.dictionary.json', 'punctuation.definition.dictionary.begin.json']
expect(tokens[1]).toEqual value: '"', scopes: ['source.json.sca.nstba', 'meta.structure.dictionary.json', 'meta.structure.dictionary.key.json', 'string.quoted.double.json', 'punctuation.definition.string.begin.json']
expect(tokens[12]).toEqual value: '"', scopes: ['source.json.sca.nstba', 'meta.structure.dictionary.json', 'meta.structure.dictionary.value.json', 'meta.structure.dictionary.json', 'meta.structure.dictionary.value.json', 'string.quoted.double.json', 'punctuation.definition.string.begin.json']
| true | describe 'NSTBA grammar', ->
grammar = null
beforeEach ->
atom.config.set('core.useTreeSitterParsers', false)
waitsForPromise ->
atom.packages.activatePackage('language-json')
waitsForPromise ->
atom.packages.activatePackage('language-sca')
runs ->
grammar = atom.grammars.grammarForScopeName('source.json.sca.nstba')
it 'parses the grammar', ->
expect(grammar).toBeTruthy()
expect(grammar.scopeName).toBe 'source.json.sca.nstba'
it 'tokenizes JSON', ->
{tokens} = grammar.tokenizeLine '{"Client SB1": {"token": "PI:KEY:<KEY>END_PI"}}'
expect(tokens[0]).toEqual value: '{', scopes: ['source.json.sca.nstba', 'meta.structure.dictionary.json', 'punctuation.definition.dictionary.begin.json']
expect(tokens[1]).toEqual value: '"', scopes: ['source.json.sca.nstba', 'meta.structure.dictionary.json', 'meta.structure.dictionary.key.json', 'string.quoted.double.json', 'punctuation.definition.string.begin.json']
expect(tokens[12]).toEqual value: '"', scopes: ['source.json.sca.nstba', 'meta.structure.dictionary.json', 'meta.structure.dictionary.value.json', 'meta.structure.dictionary.json', 'meta.structure.dictionary.value.json', 'string.quoted.double.json', 'punctuation.definition.string.begin.json']
|
[
{
"context": "module.exports =\n michael:\n first_name: \"Michael\"\n last_name: \"Richar",
"end": 26,
"score": 0.813901424407959,
"start": 19,
"tag": "NAME",
"value": "michael"
},
{
"context": "module.exports =\n michael:\n first_name: \"Michael\"\n last_name: \"Richards\"\n short_bio: \"Ruby/J",
"end": 52,
"score": 0.999855637550354,
"start": 45,
"tag": "NAME",
"value": "Michael"
},
{
"context": "ichael:\n first_name: \"Michael\"\n last_name: \"Richards\"\n short_bio: \"Ruby/JavaScript developer. Autho",
"end": 78,
"score": 0.999599814414978,
"start": 70,
"tag": "NAME",
"value": "Richards"
},
{
"context": "ript developer. Author of Rivets.js.\"\n email: \"mike22e@gmail.com\"\n twitter: \"https://twitter.com/mikeric\"\n g",
"end": 174,
"score": 0.9999312162399292,
"start": 157,
"tag": "EMAIL",
"value": "mike22e@gmail.com"
},
{
"context": "e22e@gmail.com\"\n twitter: \"https://twitter.com/mikeric\"\n github: \"http://github.com/mikeric\"\n webs",
"end": 217,
"score": 0.999453067779541,
"start": 210,
"tag": "USERNAME",
"value": "mikeric"
},
{
"context": "itter.com/mikeric\"\n github: \"http://github.com/mikeric\"\n website: \"\"\n mark:\n first_name: \"Mark\"\n ",
"end": 257,
"score": 0.9994094967842102,
"start": 250,
"tag": "USERNAME",
"value": "mikeric"
},
{
"context": "mikeric\"\n website: \"\"\n mark:\n first_name: \"Mark\"\n last_name: \"Johnson\"\n short_bio: \"Web des",
"end": 304,
"score": 0.9998388886451721,
"start": 300,
"tag": "NAME",
"value": "Mark"
},
{
"context": "\"\"\n mark:\n first_name: \"Mark\"\n last_name: \"Johnson\"\n short_bio: \"Web designer, developer and teac",
"end": 329,
"score": 0.9996461868286133,
"start": 322,
"tag": "NAME",
"value": "Johnson"
},
{
"context": "nd teacher. Co-founder of Pathwright\"\n email: \"wmdmark@gmail.com\"\n twitter: \"http://twitter.com/wmdmark\"\n gi",
"end": 439,
"score": 0.9999303221702576,
"start": 422,
"tag": "EMAIL",
"value": "wmdmark@gmail.com"
},
{
"context": "dmark@gmail.com\"\n twitter: \"http://twitter.com/wmdmark\"\n github: \"http://github.com/wmdmark\"\n webs",
"end": 481,
"score": 0.9994476437568665,
"start": 474,
"tag": "USERNAME",
"value": "wmdmark"
},
{
"context": "itter.com/wmdmark\"\n github: \"http://github.com/wmdmark\"\n website: \"http://pathwright.com\"\n mason:\n ",
"end": 521,
"score": 0.9994053840637207,
"start": 514,
"tag": "USERNAME",
"value": "wmdmark"
},
{
"context": "om/wmdmark\"\n website: \"http://pathwright.com\"\n mason:\n first_name: \"Mason\"\n last_name: \"Stew",
"end": 563,
"score": 0.7165508270263672,
"start": 562,
"tag": "NAME",
"value": "m"
},
{
"context": "\"http://pathwright.com\"\n mason:\n first_name: \"Mason\"\n last_name: \"Stewart\"\n short_bio: \"Fronten",
"end": 591,
"score": 0.9996924996376038,
"start": 586,
"tag": "NAME",
"value": "Mason"
},
{
"context": "\n mason:\n first_name: \"Mason\"\n last_name: \"Stewart\"\n short_bio: \"Frontender, JavaScripter, & Lisp",
"end": 616,
"score": 0.99958735704422,
"start": 609,
"tag": "NAME",
"value": "Stewart"
},
{
"context": " \"Frontender, JavaScripter, & Lisper\"\n email: \"mason@theironyard.com\"\n twitter: \"http://twitter.com/masondesu\"\n ",
"end": 703,
"score": 0.9999328851699829,
"start": 682,
"tag": "EMAIL",
"value": "mason@theironyard.com"
},
{
"context": "theironyard.com\"\n twitter: \"http://twitter.com/masondesu\"\n github: \"https://github.com/masondesu\"\n w",
"end": 747,
"score": 0.9996052980422974,
"start": 738,
"tag": "USERNAME",
"value": "masondesu"
},
{
"context": "er.com/masondesu\"\n github: \"https://github.com/masondesu\"\n website: \"\"\n",
"end": 790,
"score": 0.9996291995048523,
"start": 781,
"tag": "USERNAME",
"value": "masondesu"
}
] | app/sample-data.coffee | wmdmark/backbone-rivets-example | 28 | module.exports =
michael:
first_name: "Michael"
last_name: "Richards"
short_bio: "Ruby/JavaScript developer. Author of Rivets.js."
email: "mike22e@gmail.com"
twitter: "https://twitter.com/mikeric"
github: "http://github.com/mikeric"
website: ""
mark:
first_name: "Mark"
last_name: "Johnson"
short_bio: "Web designer, developer and teacher. Co-founder of Pathwright"
email: "wmdmark@gmail.com"
twitter: "http://twitter.com/wmdmark"
github: "http://github.com/wmdmark"
website: "http://pathwright.com"
mason:
first_name: "Mason"
last_name: "Stewart"
short_bio: "Frontender, JavaScripter, & Lisper"
email: "mason@theironyard.com"
twitter: "http://twitter.com/masondesu"
github: "https://github.com/masondesu"
website: ""
| 138229 | module.exports =
<NAME>:
first_name: "<NAME>"
last_name: "<NAME>"
short_bio: "Ruby/JavaScript developer. Author of Rivets.js."
email: "<EMAIL>"
twitter: "https://twitter.com/mikeric"
github: "http://github.com/mikeric"
website: ""
mark:
first_name: "<NAME>"
last_name: "<NAME>"
short_bio: "Web designer, developer and teacher. Co-founder of Pathwright"
email: "<EMAIL>"
twitter: "http://twitter.com/wmdmark"
github: "http://github.com/wmdmark"
website: "http://pathwright.com"
<NAME>ason:
first_name: "<NAME>"
last_name: "<NAME>"
short_bio: "Frontender, JavaScripter, & Lisper"
email: "<EMAIL>"
twitter: "http://twitter.com/masondesu"
github: "https://github.com/masondesu"
website: ""
| true | module.exports =
PI:NAME:<NAME>END_PI:
first_name: "PI:NAME:<NAME>END_PI"
last_name: "PI:NAME:<NAME>END_PI"
short_bio: "Ruby/JavaScript developer. Author of Rivets.js."
email: "PI:EMAIL:<EMAIL>END_PI"
twitter: "https://twitter.com/mikeric"
github: "http://github.com/mikeric"
website: ""
mark:
first_name: "PI:NAME:<NAME>END_PI"
last_name: "PI:NAME:<NAME>END_PI"
short_bio: "Web designer, developer and teacher. Co-founder of Pathwright"
email: "PI:EMAIL:<EMAIL>END_PI"
twitter: "http://twitter.com/wmdmark"
github: "http://github.com/wmdmark"
website: "http://pathwright.com"
PI:NAME:<NAME>END_PIason:
first_name: "PI:NAME:<NAME>END_PI"
last_name: "PI:NAME:<NAME>END_PI"
short_bio: "Frontender, JavaScripter, & Lisper"
email: "PI:EMAIL:<EMAIL>END_PI"
twitter: "http://twitter.com/masondesu"
github: "https://github.com/masondesu"
website: ""
|
[
{
"context": "###*\n * 首页\n * @author vfasky <vfasky@gmail.com>\n###\n'use strict'\n\n{View} = req",
"end": 28,
"score": 0.999345600605011,
"start": 22,
"tag": "USERNAME",
"value": "vfasky"
},
{
"context": "###*\n * 首页\n * @author vfasky <vfasky@gmail.com>\n###\n'use strict'\n\n{View} = require 'mcoreapp'\n\nc",
"end": 46,
"score": 0.9999202489852905,
"start": 30,
"tag": "EMAIL",
"value": "vfasky@gmail.com"
}
] | example/src/home.coffee | vfasky/mcore-weui | 0 | ###*
* 首页
* @author vfasky <vfasky@gmail.com>
###
'use strict'
{View} = require 'mcoreapp'
class Home extends View
run: ->
@render require('../tpl/home.html'),
list: [
{
url: '#/button'
title: '按钮'
desc: '直接调用,没有封装'
}
{
url: '#/cells-radio'
title: '单选列表'
}
{
url: '#/cells-checkbox'
title: '复选列表'
}
{
url: '#/cells-switch'
title: '多选开关'
}
{
url: '#/validator'
title: '表单验证'
}
{
url: '#/toast'
title: 'Toast'
desc: '成功提示,及loading'
}
{
url: '#/dialog'
title: 'Dialog'
desc: 'alert,confirm'
}
{
url: '#/progress-bar'
title: '进度条'
}
{
url: '#/actionSheet'
title: 'ActionSheet'
}
]
module.exports = Home
module.exports.viewName = 'home'
| 25771 | ###*
* 首页
* @author vfasky <<EMAIL>>
###
'use strict'
{View} = require 'mcoreapp'
class Home extends View
run: ->
@render require('../tpl/home.html'),
list: [
{
url: '#/button'
title: '按钮'
desc: '直接调用,没有封装'
}
{
url: '#/cells-radio'
title: '单选列表'
}
{
url: '#/cells-checkbox'
title: '复选列表'
}
{
url: '#/cells-switch'
title: '多选开关'
}
{
url: '#/validator'
title: '表单验证'
}
{
url: '#/toast'
title: 'Toast'
desc: '成功提示,及loading'
}
{
url: '#/dialog'
title: 'Dialog'
desc: 'alert,confirm'
}
{
url: '#/progress-bar'
title: '进度条'
}
{
url: '#/actionSheet'
title: 'ActionSheet'
}
]
module.exports = Home
module.exports.viewName = 'home'
| true | ###*
* 首页
* @author vfasky <PI:EMAIL:<EMAIL>END_PI>
###
'use strict'
{View} = require 'mcoreapp'
class Home extends View
run: ->
@render require('../tpl/home.html'),
list: [
{
url: '#/button'
title: '按钮'
desc: '直接调用,没有封装'
}
{
url: '#/cells-radio'
title: '单选列表'
}
{
url: '#/cells-checkbox'
title: '复选列表'
}
{
url: '#/cells-switch'
title: '多选开关'
}
{
url: '#/validator'
title: '表单验证'
}
{
url: '#/toast'
title: 'Toast'
desc: '成功提示,及loading'
}
{
url: '#/dialog'
title: 'Dialog'
desc: 'alert,confirm'
}
{
url: '#/progress-bar'
title: '进度条'
}
{
url: '#/actionSheet'
title: 'ActionSheet'
}
]
module.exports = Home
module.exports.viewName = 'home'
|
[
{
"context": "e} = require 'nylas-exports'\n\nShowImportantKey = 'core.workspace.showImportant'\n\nclass MailImportantIcon extends React.Component",
"end": 256,
"score": 0.9785251021385193,
"start": 228,
"tag": "KEY",
"value": "core.workspace.showImportant"
}
] | packages/client-app/src/components/mail-important-icon.cjsx | cnheider/nylas-mail | 24,369 | _ = require 'underscore'
React = require 'react'
classNames = require 'classnames'
{Actions,
Utils,
Thread,
TaskFactory,
CategoryStore,
FocusedPerspectiveStore,
AccountStore} = require 'nylas-exports'
ShowImportantKey = 'core.workspace.showImportant'
class MailImportantIcon extends React.Component
@displayName: 'MailImportantIcon'
@propTypes:
thread: React.PropTypes.object
showIfAvailableForAnyAccount: React.PropTypes.bool
constructor: (@props) ->
@state = @getState()
getState: (props = @props) =>
category = null
visible = false
if props.showIfAvailableForAnyAccount
perspective = FocusedPerspectiveStore.current()
for accountId in perspective.accountIds
account = AccountStore.accountForId(accountId)
accountImportant = CategoryStore.getStandardCategory(account, 'important')
if accountImportant
visible = true
if accountId is props.thread.accountId
category = accountImportant
break if visible and category
else
category = CategoryStore.getStandardCategory(props.thread.accountId, 'important')
visible = category?
isImportant = category and _.findWhere(props.thread.categories, {id: category.id})?
{visible, category, isImportant}
componentDidMount: =>
@unsubscribe = FocusedPerspectiveStore.listen =>
@setState(@getState())
@subscription = NylasEnv.config.onDidChange ShowImportantKey, =>
@setState(@getState())
componentWillReceiveProps: (nextProps) =>
@setState(@getState(nextProps))
componentWillUnmount: =>
@unsubscribe?()
@subscription?.dispose()
shouldComponentUpdate: (nextProps, nextState) =>
not _.isEqual(nextState, @state)
render: =>
return false unless @state.visible
classes = classNames
'mail-important-icon': true
'enabled': @state.category?
'active': @state.isImportant
if not @state.category
title = "No important folder / label"
else if @state.isImportant
title = "Mark as unimportant"
else
title = "Mark as important"
<div className={classes}}
title={title}
onClick={@_onToggleImportant}></div>
_onToggleImportant: (event) =>
{category} = @state
if category
isImportant = _.findWhere(@props.thread.categories, {id: category.id})?
threads = [@props.thread]
source = "Important Icon"
if !isImportant
Actions.applyCategoryToThreads({threads, categoryToApply: category, source})
else
Actions.removeCategoryFromThreads({threads, categoryToRemove: category, source})
# Don't trigger the thread row click
event.stopPropagation()
module.exports = MailImportantIcon
| 146928 | _ = require 'underscore'
React = require 'react'
classNames = require 'classnames'
{Actions,
Utils,
Thread,
TaskFactory,
CategoryStore,
FocusedPerspectiveStore,
AccountStore} = require 'nylas-exports'
ShowImportantKey = '<KEY>'
class MailImportantIcon extends React.Component
@displayName: 'MailImportantIcon'
@propTypes:
thread: React.PropTypes.object
showIfAvailableForAnyAccount: React.PropTypes.bool
constructor: (@props) ->
@state = @getState()
getState: (props = @props) =>
category = null
visible = false
if props.showIfAvailableForAnyAccount
perspective = FocusedPerspectiveStore.current()
for accountId in perspective.accountIds
account = AccountStore.accountForId(accountId)
accountImportant = CategoryStore.getStandardCategory(account, 'important')
if accountImportant
visible = true
if accountId is props.thread.accountId
category = accountImportant
break if visible and category
else
category = CategoryStore.getStandardCategory(props.thread.accountId, 'important')
visible = category?
isImportant = category and _.findWhere(props.thread.categories, {id: category.id})?
{visible, category, isImportant}
componentDidMount: =>
@unsubscribe = FocusedPerspectiveStore.listen =>
@setState(@getState())
@subscription = NylasEnv.config.onDidChange ShowImportantKey, =>
@setState(@getState())
componentWillReceiveProps: (nextProps) =>
@setState(@getState(nextProps))
componentWillUnmount: =>
@unsubscribe?()
@subscription?.dispose()
shouldComponentUpdate: (nextProps, nextState) =>
not _.isEqual(nextState, @state)
render: =>
return false unless @state.visible
classes = classNames
'mail-important-icon': true
'enabled': @state.category?
'active': @state.isImportant
if not @state.category
title = "No important folder / label"
else if @state.isImportant
title = "Mark as unimportant"
else
title = "Mark as important"
<div className={classes}}
title={title}
onClick={@_onToggleImportant}></div>
_onToggleImportant: (event) =>
{category} = @state
if category
isImportant = _.findWhere(@props.thread.categories, {id: category.id})?
threads = [@props.thread]
source = "Important Icon"
if !isImportant
Actions.applyCategoryToThreads({threads, categoryToApply: category, source})
else
Actions.removeCategoryFromThreads({threads, categoryToRemove: category, source})
# Don't trigger the thread row click
event.stopPropagation()
module.exports = MailImportantIcon
| true | _ = require 'underscore'
React = require 'react'
classNames = require 'classnames'
{Actions,
Utils,
Thread,
TaskFactory,
CategoryStore,
FocusedPerspectiveStore,
AccountStore} = require 'nylas-exports'
ShowImportantKey = 'PI:KEY:<KEY>END_PI'
class MailImportantIcon extends React.Component
@displayName: 'MailImportantIcon'
@propTypes:
thread: React.PropTypes.object
showIfAvailableForAnyAccount: React.PropTypes.bool
constructor: (@props) ->
@state = @getState()
getState: (props = @props) =>
category = null
visible = false
if props.showIfAvailableForAnyAccount
perspective = FocusedPerspectiveStore.current()
for accountId in perspective.accountIds
account = AccountStore.accountForId(accountId)
accountImportant = CategoryStore.getStandardCategory(account, 'important')
if accountImportant
visible = true
if accountId is props.thread.accountId
category = accountImportant
break if visible and category
else
category = CategoryStore.getStandardCategory(props.thread.accountId, 'important')
visible = category?
isImportant = category and _.findWhere(props.thread.categories, {id: category.id})?
{visible, category, isImportant}
componentDidMount: =>
@unsubscribe = FocusedPerspectiveStore.listen =>
@setState(@getState())
@subscription = NylasEnv.config.onDidChange ShowImportantKey, =>
@setState(@getState())
componentWillReceiveProps: (nextProps) =>
@setState(@getState(nextProps))
componentWillUnmount: =>
@unsubscribe?()
@subscription?.dispose()
shouldComponentUpdate: (nextProps, nextState) =>
not _.isEqual(nextState, @state)
render: =>
return false unless @state.visible
classes = classNames
'mail-important-icon': true
'enabled': @state.category?
'active': @state.isImportant
if not @state.category
title = "No important folder / label"
else if @state.isImportant
title = "Mark as unimportant"
else
title = "Mark as important"
<div className={classes}}
title={title}
onClick={@_onToggleImportant}></div>
_onToggleImportant: (event) =>
{category} = @state
if category
isImportant = _.findWhere(@props.thread.categories, {id: category.id})?
threads = [@props.thread]
source = "Important Icon"
if !isImportant
Actions.applyCategoryToThreads({threads, categoryToApply: category, source})
else
Actions.removeCategoryFromThreads({threads, categoryToRemove: category, source})
# Don't trigger the thread row click
event.stopPropagation()
module.exports = MailImportantIcon
|
[
{
"context": "ess type == \"manyToOne\"\n foreign_key = \"#{key}_id\" unless foreign_key\n @attributes[foreign_key",
"end": 467,
"score": 0.9817367792129517,
"start": 465,
"tag": "KEY",
"value": "id"
},
{
"context": "\"integer\"\n )\n\n save: ->\n data = {}\n data[@_name] = {}\n @_.each(_.keys(@attributes), (key) =>\n ",
"end": 578,
"score": 0.8919251561164856,
"start": 572,
"tag": "USERNAME",
"value": "@_name"
},
{
"context": "_.each(_.keys(@attributes), (key) =>\n data[@_name][key] = @[key]\n )\n if @id\n @store(@_na",
"end": 644,
"score": 0.521992027759552,
"start": 640,
"tag": "USERNAME",
"value": "name"
},
{
"context": "ame][key] = @[key]\n )\n if @id\n @store(@_name).update(@id, data).then (record) =>\n @_set",
"end": 696,
"score": 0.8778678774833679,
"start": 692,
"tag": "USERNAME",
"value": "name"
},
{
"context": "@_afterSave()\n record\n else\n @store(@_name).create(data).then (record) =>\n @_setPrope",
"end": 830,
"score": 0.8638968467712402,
"start": 824,
"tag": "USERNAME",
"value": "@_name"
},
{
"context": "$isDestroyed = true\n @_willDestroy()\n @store(@_name).destroy(@id).then =>\n @_afterDestroy()\n\n r",
"end": 1209,
"score": 0.7859434485435486,
"start": 1203,
"tag": "USERNAME",
"value": "@_name"
},
{
"context": "n unless type == \"manyToOne\"\n foreign_key = \"#{relation}_id\" unless foreign_key\n return if @[relation] && ",
"end": 1607,
"score": 0.9377216696739197,
"start": 1595,
"tag": "KEY",
"value": "relation}_id"
}
] | src/javascripts/models/base.coffee | NprApp/npr | 0 | class Base
constructor: (data) ->
@_setProperties(data)
@store = angular.injector(["npr.app"]).get("Store")
@_ = angular.injector(["npr.app"]).get("_")
# @_rootScope = angular.injector(["npr.app"]).get("$rootScope")
# @_timeout = angular.injector(["npr.app"]).get("$timeout")
@_.each(_.keys(@attributes), (key) =>
[type, foreign_key] = @attributes[key].split(":")
return unless type == "manyToOne"
foreign_key = "#{key}_id" unless foreign_key
@attributes[foreign_key] = "integer"
)
save: ->
data = {}
data[@_name] = {}
@_.each(_.keys(@attributes), (key) =>
data[@_name][key] = @[key]
)
if @id
@store(@_name).update(@id, data).then (record) =>
@_setProperties(record)
@_afterSave()
record
else
@store(@_name).create(data).then (record) =>
@_setProperties(record.data)
@_afterSave()
record
reload: ->
@store(@_name).get(@id, true)
return
_setProperties: (data) ->
angular.extend(@, data)
@_originalData = data
_restore: ->
angular.extend(@, @_originalData)
destroy: ->
@$isDestroyed = true
@_willDestroy()
@store(@_name).destroy(@id).then =>
@_afterDestroy()
reject: ->
@_restore()
isNew: ->
!@id
_willDestroy: ->
_afterSave: ->
return
_afterDestriy: ->
return
_calculateRelationForBaseModel: (relation) ->
return unless @attributes[relation]
[type, foreign_key] = @attributes[relation].split(":")
return unless type == "manyToOne"
foreign_key = "#{relation}_id" unless foreign_key
return if @[relation] && @[relation].id == @[foreign_key]
@[relation] = @store(relation).get(@[foreign_key])
foreign_key
angular.module("npr.app")
.factory "BaseModel", ["Store", "_", "$rootScope", "$timeout", (Store, _, $rootScope, $timeout) ->
console.log 'adad'
Base
]
.directive "bindRelation", ["$parse", "$compile", ($parse, $compile) ->
restrict: 'E'
link: (scope, element, attributes) ->
{ key, render } = attributes
keys = key.split(".")
_.each(keys, (value, index) ->
binding = keys.slice(0, index).join(".")
if foreign_key = $parse(binding)(scope)?._calculateRelationForBaseModel?(value)
scope.$watch("#{binding}.#{foreign_key}", () ->
$parse(binding)(scope)?._calculateRelationForBaseModel?(value)
)
)
if render
element.html("{{#{key}}}")
$compile(element.contents())(scope)
]
| 1338 | class Base
constructor: (data) ->
@_setProperties(data)
@store = angular.injector(["npr.app"]).get("Store")
@_ = angular.injector(["npr.app"]).get("_")
# @_rootScope = angular.injector(["npr.app"]).get("$rootScope")
# @_timeout = angular.injector(["npr.app"]).get("$timeout")
@_.each(_.keys(@attributes), (key) =>
[type, foreign_key] = @attributes[key].split(":")
return unless type == "manyToOne"
foreign_key = "#{key}_<KEY>" unless foreign_key
@attributes[foreign_key] = "integer"
)
save: ->
data = {}
data[@_name] = {}
@_.each(_.keys(@attributes), (key) =>
data[@_name][key] = @[key]
)
if @id
@store(@_name).update(@id, data).then (record) =>
@_setProperties(record)
@_afterSave()
record
else
@store(@_name).create(data).then (record) =>
@_setProperties(record.data)
@_afterSave()
record
reload: ->
@store(@_name).get(@id, true)
return
_setProperties: (data) ->
angular.extend(@, data)
@_originalData = data
_restore: ->
angular.extend(@, @_originalData)
destroy: ->
@$isDestroyed = true
@_willDestroy()
@store(@_name).destroy(@id).then =>
@_afterDestroy()
reject: ->
@_restore()
isNew: ->
!@id
_willDestroy: ->
_afterSave: ->
return
_afterDestriy: ->
return
_calculateRelationForBaseModel: (relation) ->
return unless @attributes[relation]
[type, foreign_key] = @attributes[relation].split(":")
return unless type == "manyToOne"
foreign_key = "#{<KEY>" unless foreign_key
return if @[relation] && @[relation].id == @[foreign_key]
@[relation] = @store(relation).get(@[foreign_key])
foreign_key
angular.module("npr.app")
.factory "BaseModel", ["Store", "_", "$rootScope", "$timeout", (Store, _, $rootScope, $timeout) ->
console.log 'adad'
Base
]
.directive "bindRelation", ["$parse", "$compile", ($parse, $compile) ->
restrict: 'E'
link: (scope, element, attributes) ->
{ key, render } = attributes
keys = key.split(".")
_.each(keys, (value, index) ->
binding = keys.slice(0, index).join(".")
if foreign_key = $parse(binding)(scope)?._calculateRelationForBaseModel?(value)
scope.$watch("#{binding}.#{foreign_key}", () ->
$parse(binding)(scope)?._calculateRelationForBaseModel?(value)
)
)
if render
element.html("{{#{key}}}")
$compile(element.contents())(scope)
]
| true | class Base
constructor: (data) ->
@_setProperties(data)
@store = angular.injector(["npr.app"]).get("Store")
@_ = angular.injector(["npr.app"]).get("_")
# @_rootScope = angular.injector(["npr.app"]).get("$rootScope")
# @_timeout = angular.injector(["npr.app"]).get("$timeout")
@_.each(_.keys(@attributes), (key) =>
[type, foreign_key] = @attributes[key].split(":")
return unless type == "manyToOne"
foreign_key = "#{key}_PI:KEY:<KEY>END_PI" unless foreign_key
@attributes[foreign_key] = "integer"
)
save: ->
data = {}
data[@_name] = {}
@_.each(_.keys(@attributes), (key) =>
data[@_name][key] = @[key]
)
if @id
@store(@_name).update(@id, data).then (record) =>
@_setProperties(record)
@_afterSave()
record
else
@store(@_name).create(data).then (record) =>
@_setProperties(record.data)
@_afterSave()
record
reload: ->
@store(@_name).get(@id, true)
return
_setProperties: (data) ->
angular.extend(@, data)
@_originalData = data
_restore: ->
angular.extend(@, @_originalData)
destroy: ->
@$isDestroyed = true
@_willDestroy()
@store(@_name).destroy(@id).then =>
@_afterDestroy()
reject: ->
@_restore()
isNew: ->
!@id
_willDestroy: ->
_afterSave: ->
return
_afterDestriy: ->
return
_calculateRelationForBaseModel: (relation) ->
return unless @attributes[relation]
[type, foreign_key] = @attributes[relation].split(":")
return unless type == "manyToOne"
foreign_key = "#{PI:KEY:<KEY>END_PI" unless foreign_key
return if @[relation] && @[relation].id == @[foreign_key]
@[relation] = @store(relation).get(@[foreign_key])
foreign_key
angular.module("npr.app")
.factory "BaseModel", ["Store", "_", "$rootScope", "$timeout", (Store, _, $rootScope, $timeout) ->
console.log 'adad'
Base
]
.directive "bindRelation", ["$parse", "$compile", ($parse, $compile) ->
restrict: 'E'
link: (scope, element, attributes) ->
{ key, render } = attributes
keys = key.split(".")
_.each(keys, (value, index) ->
binding = keys.slice(0, index).join(".")
if foreign_key = $parse(binding)(scope)?._calculateRelationForBaseModel?(value)
scope.$watch("#{binding}.#{foreign_key}", () ->
$parse(binding)(scope)?._calculateRelationForBaseModel?(value)
)
)
if render
element.html("{{#{key}}}")
$compile(element.contents())(scope)
]
|
[
{
"context": "##\n#\n# Copyright 2014 Netflix, Inc.\n#\n# Licensed under the Apache Licen",
"end": 26,
"score": 0.9487088322639465,
"start": 23,
"tag": "NAME",
"value": "Net"
}
] | web-ui/public/coffee/apps/application.coffee | krishnachaitanyareddy/inviso | 162 | ##
#
# Copyright 2014 Netflix, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##
class @Application
constructor: (args) ->
normalize: (data) ->
data.start= Number.MAX_VALUE
data.stop= Number.MIN_VALUE
data.longest= Number.MIN_VALUE
for entry in data.entries
if entry.start < 1000 or entry.stop < 1000 then continue
data.start = Math.min(entry.start, data.start)
data.stop = Math.max(entry.stop, data.stop)
data.longest = Math.max(entry.stop - entry.start, data.longest)
data.duration = data.stop - data.start
for entry in data.entries
if entry.start < 1000 or entry.stop < 1000 then continue
entry.start -= data.start
entry.stop -= data.start
return data
| 92044 | ##
#
# Copyright 2014 <NAME>flix, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##
class @Application
constructor: (args) ->
normalize: (data) ->
data.start= Number.MAX_VALUE
data.stop= Number.MIN_VALUE
data.longest= Number.MIN_VALUE
for entry in data.entries
if entry.start < 1000 or entry.stop < 1000 then continue
data.start = Math.min(entry.start, data.start)
data.stop = Math.max(entry.stop, data.stop)
data.longest = Math.max(entry.stop - entry.start, data.longest)
data.duration = data.stop - data.start
for entry in data.entries
if entry.start < 1000 or entry.stop < 1000 then continue
entry.start -= data.start
entry.stop -= data.start
return data
| true | ##
#
# Copyright 2014 PI:NAME:<NAME>END_PIflix, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##
class @Application
constructor: (args) ->
normalize: (data) ->
data.start= Number.MAX_VALUE
data.stop= Number.MIN_VALUE
data.longest= Number.MIN_VALUE
for entry in data.entries
if entry.start < 1000 or entry.stop < 1000 then continue
data.start = Math.min(entry.start, data.start)
data.stop = Math.max(entry.stop, data.stop)
data.longest = Math.max(entry.stop - entry.start, data.longest)
data.duration = data.stop - data.start
for entry in data.entries
if entry.start < 1000 or entry.stop < 1000 then continue
entry.start -= data.start
entry.stop -= data.start
return data
|
[
{
"context": "a.user.enable connection: ipa,\n username: 'test_user_enable'\n , ({config: {uid}}) ->\n uid.should.",
"end": 363,
"score": 0.9991549253463745,
"start": 347,
"tag": "USERNAME",
"value": "test_user_enable"
},
{
"context": " sn: 'Disable'\n mail: [\n 'test_user_enable@nikita.js.org'\n ]\n nsaccountlock: true\n ",
"end": 1176,
"score": 0.9999263882637024,
"start": 1146,
"tag": "EMAIL",
"value": "test_user_enable@nikita.js.org"
},
{
"context": " sn: 'Disable'\n mail: [\n 'test_user_enable@nikita.js.org'\n ]\n nsaccountlock: true\n ",
"end": 1758,
"score": 0.9999268651008606,
"start": 1728,
"tag": "EMAIL",
"value": "test_user_enable@nikita.js.org"
},
{
"context": "t @ipa.user.enable connection: ipa,\n uid: 'test_user_enable_inactive'\n {$status} = await @ipa.user",
"end": 1872,
"score": 0.7288156151771545,
"start": 1862,
"tag": "USERNAME",
"value": "test_user_"
},
{
"context": "t @ipa.user.enable connection: ipa,\n uid: 'test_user_enable_inactive'\n $status.should.be.false()\n",
"end": 1970,
"score": 0.6625660061836243,
"start": 1961,
"tag": "USERNAME",
"value": "test_user"
}
] | packages/ipa/test/user/enable.coffee | shivaylamba/meilisearch-gatsby-plugin-guide | 0 |
nikita = require '@nikitajs/core/lib'
{tags, config, ipa} = require '../test'
they = require('mocha-they')(config)
return unless tags.ipa
describe 'ipa.user.enable', ->
describe 'schema', ->
they 'use `username` as alias for `uid`', ({ssh}) ->
nikita
$ssh: ssh
.ipa.user.enable connection: ipa,
username: 'test_user_enable'
, ({config: {uid}}) ->
uid.should.eql 'test_user_enable'
describe 'action', ->
they 'enable a missing user', ({ssh}) ->
nikita
$ssh: ssh
, ->
@ipa.user.enable connection: ipa,
uid: 'test_user_enable_missing'
.should.be.rejectedWith
code: 4001
message: 'test_user_enable_missing: user not found'
they 'enable an active user', ({ssh}) ->
nikita
$ssh: ssh
, ->
await @ipa.user.del connection: ipa,
$relax: true
uid: 'test_user_enable_active'
await @ipa.user connection: ipa,
uid: 'test_user_enable_active'
attributes:
givenname: 'User'
sn: 'Disable'
mail: [
'test_user_enable@nikita.js.org'
]
nsaccountlock: true
{$status} = await @ipa.user.enable connection: ipa,
uid: 'test_user_enable_active'
$status.should.be.true()
they 'enable an inactive user', ({ssh}) ->
nikita
$ssh: ssh
, ->
await @ipa.user.del connection: ipa,
$relax: true
uid: 'test_user_enable_inactive'
await @ipa.user connection: ipa,
uid: 'test_user_enable_inactive'
attributes:
givenname: 'User'
sn: 'Disable'
mail: [
'test_user_enable@nikita.js.org'
]
nsaccountlock: true
await @ipa.user.enable connection: ipa,
uid: 'test_user_enable_inactive'
{$status} = await @ipa.user.enable connection: ipa,
uid: 'test_user_enable_inactive'
$status.should.be.false()
| 134936 |
nikita = require '@nikitajs/core/lib'
{tags, config, ipa} = require '../test'
they = require('mocha-they')(config)
return unless tags.ipa
describe 'ipa.user.enable', ->
describe 'schema', ->
they 'use `username` as alias for `uid`', ({ssh}) ->
nikita
$ssh: ssh
.ipa.user.enable connection: ipa,
username: 'test_user_enable'
, ({config: {uid}}) ->
uid.should.eql 'test_user_enable'
describe 'action', ->
they 'enable a missing user', ({ssh}) ->
nikita
$ssh: ssh
, ->
@ipa.user.enable connection: ipa,
uid: 'test_user_enable_missing'
.should.be.rejectedWith
code: 4001
message: 'test_user_enable_missing: user not found'
they 'enable an active user', ({ssh}) ->
nikita
$ssh: ssh
, ->
await @ipa.user.del connection: ipa,
$relax: true
uid: 'test_user_enable_active'
await @ipa.user connection: ipa,
uid: 'test_user_enable_active'
attributes:
givenname: 'User'
sn: 'Disable'
mail: [
'<EMAIL>'
]
nsaccountlock: true
{$status} = await @ipa.user.enable connection: ipa,
uid: 'test_user_enable_active'
$status.should.be.true()
they 'enable an inactive user', ({ssh}) ->
nikita
$ssh: ssh
, ->
await @ipa.user.del connection: ipa,
$relax: true
uid: 'test_user_enable_inactive'
await @ipa.user connection: ipa,
uid: 'test_user_enable_inactive'
attributes:
givenname: 'User'
sn: 'Disable'
mail: [
'<EMAIL>'
]
nsaccountlock: true
await @ipa.user.enable connection: ipa,
uid: 'test_user_enable_inactive'
{$status} = await @ipa.user.enable connection: ipa,
uid: 'test_user_enable_inactive'
$status.should.be.false()
| true |
nikita = require '@nikitajs/core/lib'
{tags, config, ipa} = require '../test'
they = require('mocha-they')(config)
return unless tags.ipa
describe 'ipa.user.enable', ->
describe 'schema', ->
they 'use `username` as alias for `uid`', ({ssh}) ->
nikita
$ssh: ssh
.ipa.user.enable connection: ipa,
username: 'test_user_enable'
, ({config: {uid}}) ->
uid.should.eql 'test_user_enable'
describe 'action', ->
they 'enable a missing user', ({ssh}) ->
nikita
$ssh: ssh
, ->
@ipa.user.enable connection: ipa,
uid: 'test_user_enable_missing'
.should.be.rejectedWith
code: 4001
message: 'test_user_enable_missing: user not found'
they 'enable an active user', ({ssh}) ->
nikita
$ssh: ssh
, ->
await @ipa.user.del connection: ipa,
$relax: true
uid: 'test_user_enable_active'
await @ipa.user connection: ipa,
uid: 'test_user_enable_active'
attributes:
givenname: 'User'
sn: 'Disable'
mail: [
'PI:EMAIL:<EMAIL>END_PI'
]
nsaccountlock: true
{$status} = await @ipa.user.enable connection: ipa,
uid: 'test_user_enable_active'
$status.should.be.true()
they 'enable an inactive user', ({ssh}) ->
nikita
$ssh: ssh
, ->
await @ipa.user.del connection: ipa,
$relax: true
uid: 'test_user_enable_inactive'
await @ipa.user connection: ipa,
uid: 'test_user_enable_inactive'
attributes:
givenname: 'User'
sn: 'Disable'
mail: [
'PI:EMAIL:<EMAIL>END_PI'
]
nsaccountlock: true
await @ipa.user.enable connection: ipa,
uid: 'test_user_enable_inactive'
{$status} = await @ipa.user.enable connection: ipa,
uid: 'test_user_enable_inactive'
$status.should.be.false()
|
[
{
"context": ">\n it \"unpacks signals\", ->\n name = new Slot(\"John\")\n outer = new Slot(name)\n vals = []\n\n u",
"end": 240,
"score": 0.998354434967041,
"start": 236,
"tag": "NAME",
"value": "John"
},
{
"context": "\n vals.push val\n assert.deepEqual vals, [\"John\"]\n\n name.set \"Mary\"\n assert.deepEqual vals,",
"end": 394,
"score": 0.99949049949646,
"start": 390,
"tag": "NAME",
"value": "John"
},
{
"context": " assert.deepEqual vals, [\"John\"]\n\n name.set \"Mary\"\n assert.deepEqual vals, [\"John\", \"Mary\"]\n\n ",
"end": 416,
"score": 0.9997642636299133,
"start": 412,
"tag": "NAME",
"value": "Mary"
},
{
"context": "\n name.set \"Mary\"\n assert.deepEqual vals, [\"John\", \"Mary\"]\n\n unsubscribe()\n\n it \"doesn't send ",
"end": 451,
"score": 0.9995371103286743,
"start": 447,
"tag": "NAME",
"value": "John"
},
{
"context": "e.set \"Mary\"\n assert.deepEqual vals, [\"John\", \"Mary\"]\n\n unsubscribe()\n\n it \"doesn't send values f",
"end": 459,
"score": 0.9997830986976624,
"start": 455,
"tag": "NAME",
"value": "Mary"
},
{
"context": "s for old inner signals\", ->\n name = new Slot(\"John\")\n age = new Slot(30)\n outer = new Slot(nam",
"end": 560,
"score": 0.9983248114585876,
"start": 556,
"tag": "NAME",
"value": "John"
},
{
"context": "\n vals.push val\n assert.deepEqual vals, [\"John\"]\n\n outer.set age\n assert.deepEqual vals, [",
"end": 737,
"score": 0.9995408058166504,
"start": 733,
"tag": "NAME",
"value": "John"
},
{
"context": "]\n\n outer.set age\n assert.deepEqual vals, [\"John\", 30]\n\n name.set \"Mary\"\n assert.deepEqual v",
"end": 792,
"score": 0.9995959401130676,
"start": 788,
"tag": "NAME",
"value": "John"
},
{
"context": "ssert.deepEqual vals, [\"John\", 30]\n\n name.set \"Mary\"\n assert.deepEqual vals, [\"John\", 30]\n unsu",
"end": 818,
"score": 0.9996106624603271,
"start": 814,
"tag": "NAME",
"value": "Mary"
},
{
"context": "\n name.set \"Mary\"\n assert.deepEqual vals, [\"John\", 30]\n unsubscribe()\n\n it \"doesn't leak signa",
"end": 853,
"score": 0.9995657801628113,
"start": 849,
"tag": "NAME",
"value": "John"
}
] | test/methods/latest.coffee | trello/hearsay | 5 | latest = require 'hearsay/methods/latest'
Emitter = require 'hearsay/emitter'
Slot = require 'hearsay/slot'
defer = require 'util/defer'
{ assert } = require 'chai'
describe "latest", ->
it "unpacks signals", ->
name = new Slot("John")
outer = new Slot(name)
vals = []
unsubscribe = latest.call(outer).subscribe (val) ->
vals.push val
assert.deepEqual vals, ["John"]
name.set "Mary"
assert.deepEqual vals, ["John", "Mary"]
unsubscribe()
it "doesn't send values for old inner signals", ->
name = new Slot("John")
age = new Slot(30)
outer = new Slot(name)
vals = []
unsubscribe = latest.call(outer).subscribe (val) ->
vals.push val
assert.deepEqual vals, ["John"]
outer.set age
assert.deepEqual vals, ["John", 30]
name.set "Mary"
assert.deepEqual vals, ["John", 30]
unsubscribe()
it "doesn't leak signals", ->
disposed1 = false
disposed2 = false
disposed3 = false
disposed4 = false
disposedOuter = false
signal1 = new Slot(1).addDisposer -> disposed1 = true
outerSlot = new Slot(signal1)
outerSignal = latest.call(outerSlot).addDisposer -> disposedOuter = true
vals = []
unsubscribe = outerSignal.subscribe (val) -> vals.push val
assert.deepEqual vals, [1]
ensureAll = -> assert(!disposed1 && !disposed2 && !disposed3 && !disposed4 && !disposedOuter, "ensureAll")
ensureAllButOne = -> assert(disposed1 && !disposed2 && !disposed3 && !disposed4 && !disposedOuter, "ensureAllButOne")
ensureAll()
defer()
.tap ->
ensureAll()
signal1.set 10
assert.deepEqual vals, [1, 10], "wrong values"
defer()
.tap ->
ensureAll()
outerSlot.set(new Slot(2).addDisposer -> disposed2 = true)
assert.deepEqual vals, [1, 10, 2], "wrong values"
ensureAll()
defer()
.tap ->
ensureAllButOne()
outerSlot.set(new Slot(3).addDisposer -> disposed3 = true)
assert.deepEqual vals, [1, 10, 2, 3], "wrong values"
ensureAllButOne()
outerSlot.set(new Slot(4).addDisposer -> disposed4 = true)
assert.deepEqual vals, [1, 10, 2, 3, 4], "wrong values"
ensureAllButOne()
defer()
.tap ->
assert(disposed1 && disposed2 && disposed3 && !disposed4 && !disposedOuter)
assert.deepEqual vals, [1, 10, 2, 3, 4], "wrong values"
outerSlot.get().set(40)
assert.deepEqual vals, [1, 10, 2, 3, 4, 40], "wrong values"
unsubscribe()
defer()
.tap ->
assert disposed1
assert disposed2
assert disposed3
assert disposed4
assert disposedOuter
| 220118 | latest = require 'hearsay/methods/latest'
Emitter = require 'hearsay/emitter'
Slot = require 'hearsay/slot'
defer = require 'util/defer'
{ assert } = require 'chai'
describe "latest", ->
it "unpacks signals", ->
name = new Slot("<NAME>")
outer = new Slot(name)
vals = []
unsubscribe = latest.call(outer).subscribe (val) ->
vals.push val
assert.deepEqual vals, ["<NAME>"]
name.set "<NAME>"
assert.deepEqual vals, ["<NAME>", "<NAME>"]
unsubscribe()
it "doesn't send values for old inner signals", ->
name = new Slot("<NAME>")
age = new Slot(30)
outer = new Slot(name)
vals = []
unsubscribe = latest.call(outer).subscribe (val) ->
vals.push val
assert.deepEqual vals, ["<NAME>"]
outer.set age
assert.deepEqual vals, ["<NAME>", 30]
name.set "<NAME>"
assert.deepEqual vals, ["<NAME>", 30]
unsubscribe()
it "doesn't leak signals", ->
disposed1 = false
disposed2 = false
disposed3 = false
disposed4 = false
disposedOuter = false
signal1 = new Slot(1).addDisposer -> disposed1 = true
outerSlot = new Slot(signal1)
outerSignal = latest.call(outerSlot).addDisposer -> disposedOuter = true
vals = []
unsubscribe = outerSignal.subscribe (val) -> vals.push val
assert.deepEqual vals, [1]
ensureAll = -> assert(!disposed1 && !disposed2 && !disposed3 && !disposed4 && !disposedOuter, "ensureAll")
ensureAllButOne = -> assert(disposed1 && !disposed2 && !disposed3 && !disposed4 && !disposedOuter, "ensureAllButOne")
ensureAll()
defer()
.tap ->
ensureAll()
signal1.set 10
assert.deepEqual vals, [1, 10], "wrong values"
defer()
.tap ->
ensureAll()
outerSlot.set(new Slot(2).addDisposer -> disposed2 = true)
assert.deepEqual vals, [1, 10, 2], "wrong values"
ensureAll()
defer()
.tap ->
ensureAllButOne()
outerSlot.set(new Slot(3).addDisposer -> disposed3 = true)
assert.deepEqual vals, [1, 10, 2, 3], "wrong values"
ensureAllButOne()
outerSlot.set(new Slot(4).addDisposer -> disposed4 = true)
assert.deepEqual vals, [1, 10, 2, 3, 4], "wrong values"
ensureAllButOne()
defer()
.tap ->
assert(disposed1 && disposed2 && disposed3 && !disposed4 && !disposedOuter)
assert.deepEqual vals, [1, 10, 2, 3, 4], "wrong values"
outerSlot.get().set(40)
assert.deepEqual vals, [1, 10, 2, 3, 4, 40], "wrong values"
unsubscribe()
defer()
.tap ->
assert disposed1
assert disposed2
assert disposed3
assert disposed4
assert disposedOuter
| true | latest = require 'hearsay/methods/latest'
Emitter = require 'hearsay/emitter'
Slot = require 'hearsay/slot'
defer = require 'util/defer'
{ assert } = require 'chai'
describe "latest", ->
it "unpacks signals", ->
name = new Slot("PI:NAME:<NAME>END_PI")
outer = new Slot(name)
vals = []
unsubscribe = latest.call(outer).subscribe (val) ->
vals.push val
assert.deepEqual vals, ["PI:NAME:<NAME>END_PI"]
name.set "PI:NAME:<NAME>END_PI"
assert.deepEqual vals, ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]
unsubscribe()
it "doesn't send values for old inner signals", ->
name = new Slot("PI:NAME:<NAME>END_PI")
age = new Slot(30)
outer = new Slot(name)
vals = []
unsubscribe = latest.call(outer).subscribe (val) ->
vals.push val
assert.deepEqual vals, ["PI:NAME:<NAME>END_PI"]
outer.set age
assert.deepEqual vals, ["PI:NAME:<NAME>END_PI", 30]
name.set "PI:NAME:<NAME>END_PI"
assert.deepEqual vals, ["PI:NAME:<NAME>END_PI", 30]
unsubscribe()
it "doesn't leak signals", ->
disposed1 = false
disposed2 = false
disposed3 = false
disposed4 = false
disposedOuter = false
signal1 = new Slot(1).addDisposer -> disposed1 = true
outerSlot = new Slot(signal1)
outerSignal = latest.call(outerSlot).addDisposer -> disposedOuter = true
vals = []
unsubscribe = outerSignal.subscribe (val) -> vals.push val
assert.deepEqual vals, [1]
ensureAll = -> assert(!disposed1 && !disposed2 && !disposed3 && !disposed4 && !disposedOuter, "ensureAll")
ensureAllButOne = -> assert(disposed1 && !disposed2 && !disposed3 && !disposed4 && !disposedOuter, "ensureAllButOne")
ensureAll()
defer()
.tap ->
ensureAll()
signal1.set 10
assert.deepEqual vals, [1, 10], "wrong values"
defer()
.tap ->
ensureAll()
outerSlot.set(new Slot(2).addDisposer -> disposed2 = true)
assert.deepEqual vals, [1, 10, 2], "wrong values"
ensureAll()
defer()
.tap ->
ensureAllButOne()
outerSlot.set(new Slot(3).addDisposer -> disposed3 = true)
assert.deepEqual vals, [1, 10, 2, 3], "wrong values"
ensureAllButOne()
outerSlot.set(new Slot(4).addDisposer -> disposed4 = true)
assert.deepEqual vals, [1, 10, 2, 3, 4], "wrong values"
ensureAllButOne()
defer()
.tap ->
assert(disposed1 && disposed2 && disposed3 && !disposed4 && !disposedOuter)
assert.deepEqual vals, [1, 10, 2, 3, 4], "wrong values"
outerSlot.get().set(40)
assert.deepEqual vals, [1, 10, 2, 3, 4, 40], "wrong values"
unsubscribe()
defer()
.tap ->
assert disposed1
assert disposed2
assert disposed3
assert disposed4
assert disposedOuter
|
[
{
"context": " HTTP POST request to create a checklist.\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n###\r\nclass CreateAircraftC",
"end": 158,
"score": 0.9998100996017456,
"start": 146,
"tag": "NAME",
"value": "Nathan Klick"
}
] | Workspace/QRef/NodeServer/src/specification/request/ajax/CreateAircraftChecklistAjaxRequest.coffee | qrefdev/qref | 0 | AjaxRequest = require('../../../serialization/AjaxRequest')
###
Object sent as the body of an HTTP POST request to create a checklist.
@author Nathan Klick
@copyright QRef 2012
###
class CreateAircraftChecklistAjaxRequest extends AjaxRequest
###
@property [ObjectId] (Required) The manufacturer that this checklist is built against.
@see AircraftManufacturerSchemaInternal
###
manufacturer:
type: ObjectId
ref: 'aircraft.manufacturers'
required: true
###
@property [ObjectId] (Required) The model that this checklist is built against.
@see AircraftModelSchemaInternal
###
model:
type: ObjectId
ref: 'aircraft.models'
required: true
###
@property [Number] (Optional) The order in which this checklist should appear relative to the other checklists.
###
index:
type: Number
required: false
default: null
###
@property [String] (Optional) The tail number for a list which has been customized to a specific plane.
###
tailNumber:
type: String
required: false
default: null
###
@property [ObjectId] (Optional) The user which owns this customized version of the checklist.
@see UserSchemaInternal
###
user:
type: ObjectId
ref: 'users'
required: false
default: null
###
@property [Number] (Optional) The version number of this checklist.
###
version:
type: Number
required: true
default: 1
###
@property [String] (Optional) A server-based relative path to the product icon. This path should be relative to the server root.
###
productIcon:
type: String
required: false
###
@property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of preflight sections.
###
preflight:
type: [AircraftChecklistSectionSchema]
required: false
###
@property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of takeoff sections.
###
takeoff:
type: [AircraftChecklistSectionSchema]
required: false
###
@property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of landing sections.
###
landing:
type: [AircraftChecklistSectionSchema]
required: false
###
@property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of emergency sections.
###
emergencies:
type: [AircraftChecklistSectionSchema]
required: false
###
@property [Boolean] (Optional) A true/false value indicating whether this record has been deleted. Required for soft-delete support.
###
isDeleted:
type: Boolean
required: true
default: false
module.exports = CreateAircraftChecklistAjaxRequest | 51939 | AjaxRequest = require('../../../serialization/AjaxRequest')
###
Object sent as the body of an HTTP POST request to create a checklist.
@author <NAME>
@copyright QRef 2012
###
class CreateAircraftChecklistAjaxRequest extends AjaxRequest
###
@property [ObjectId] (Required) The manufacturer that this checklist is built against.
@see AircraftManufacturerSchemaInternal
###
manufacturer:
type: ObjectId
ref: 'aircraft.manufacturers'
required: true
###
@property [ObjectId] (Required) The model that this checklist is built against.
@see AircraftModelSchemaInternal
###
model:
type: ObjectId
ref: 'aircraft.models'
required: true
###
@property [Number] (Optional) The order in which this checklist should appear relative to the other checklists.
###
index:
type: Number
required: false
default: null
###
@property [String] (Optional) The tail number for a list which has been customized to a specific plane.
###
tailNumber:
type: String
required: false
default: null
###
@property [ObjectId] (Optional) The user which owns this customized version of the checklist.
@see UserSchemaInternal
###
user:
type: ObjectId
ref: 'users'
required: false
default: null
###
@property [Number] (Optional) The version number of this checklist.
###
version:
type: Number
required: true
default: 1
###
@property [String] (Optional) A server-based relative path to the product icon. This path should be relative to the server root.
###
productIcon:
type: String
required: false
###
@property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of preflight sections.
###
preflight:
type: [AircraftChecklistSectionSchema]
required: false
###
@property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of takeoff sections.
###
takeoff:
type: [AircraftChecklistSectionSchema]
required: false
###
@property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of landing sections.
###
landing:
type: [AircraftChecklistSectionSchema]
required: false
###
@property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of emergency sections.
###
emergencies:
type: [AircraftChecklistSectionSchema]
required: false
###
@property [Boolean] (Optional) A true/false value indicating whether this record has been deleted. Required for soft-delete support.
###
isDeleted:
type: Boolean
required: true
default: false
module.exports = CreateAircraftChecklistAjaxRequest | true | AjaxRequest = require('../../../serialization/AjaxRequest')
###
Object sent as the body of an HTTP POST request to create a checklist.
@author PI:NAME:<NAME>END_PI
@copyright QRef 2012
###
class CreateAircraftChecklistAjaxRequest extends AjaxRequest
###
@property [ObjectId] (Required) The manufacturer that this checklist is built against.
@see AircraftManufacturerSchemaInternal
###
manufacturer:
type: ObjectId
ref: 'aircraft.manufacturers'
required: true
###
@property [ObjectId] (Required) The model that this checklist is built against.
@see AircraftModelSchemaInternal
###
model:
type: ObjectId
ref: 'aircraft.models'
required: true
###
@property [Number] (Optional) The order in which this checklist should appear relative to the other checklists.
###
index:
type: Number
required: false
default: null
###
@property [String] (Optional) The tail number for a list which has been customized to a specific plane.
###
tailNumber:
type: String
required: false
default: null
###
@property [ObjectId] (Optional) The user which owns this customized version of the checklist.
@see UserSchemaInternal
###
user:
type: ObjectId
ref: 'users'
required: false
default: null
###
@property [Number] (Optional) The version number of this checklist.
###
version:
type: Number
required: true
default: 1
###
@property [String] (Optional) A server-based relative path to the product icon. This path should be relative to the server root.
###
productIcon:
type: String
required: false
###
@property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of preflight sections.
###
preflight:
type: [AircraftChecklistSectionSchema]
required: false
###
@property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of takeoff sections.
###
takeoff:
type: [AircraftChecklistSectionSchema]
required: false
###
@property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of landing sections.
###
landing:
type: [AircraftChecklistSectionSchema]
required: false
###
@property [Array<AircraftChecklistSectionSchemaInternal>] (Optional) The array of emergency sections.
###
emergencies:
type: [AircraftChecklistSectionSchema]
required: false
###
@property [Boolean] (Optional) A true/false value indicating whether this record has been deleted. Required for soft-delete support.
###
isDeleted:
type: Boolean
required: true
default: false
module.exports = CreateAircraftChecklistAjaxRequest |
[
{
"context": " <a href=\"#\"><i class=\"fa fa-envelope\"></i>support@company.com</a>\n </li>\n <",
"end": 9194,
"score": 0.9998334646224976,
"start": 9175,
"tag": "EMAIL",
"value": "support@company.com"
},
{
"context": "put type=\"text\" class=\"form-control\" placeholder=\"Name\" aria-label=\"Name\" aria-describedby=\"basic-addon1",
"end": 14854,
"score": 0.5375888347625732,
"start": 14850,
"tag": "NAME",
"value": "Name"
},
{
"context": "put type=\"text\" class=\"form-control\" placeholder=\"Password\" aria-label=\"Password\" aria-describedby=\"basic-ad",
"end": 15692,
"score": 0.811486542224884,
"start": 15684,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": "put type=\"text\" class=\"form-control\" placeholder=\"Password confirmation\" aria-label=\"Password confirmation\" ",
"end": 16114,
"score": 0.6302074790000916,
"start": 16106,
"tag": "PASSWORD",
"value": "Password"
}
] | snippets/snippets.cson | bhavana05/bootstrap-snippets-atom | 1 |
# html and erb
'.text.html.basic , .text.html.erb':
'bootstrap media':
'prefix': 'media'
'body': """
<div class="media">
<div class="media-left">
$1
</div>
<div class="media-body">
$2
</div>
<div class="media-right">
$3
</div>
</div>
"""
'card with image and text':
'prefix': 'card'
'body': """
<div class="card">
<img src="$1" alt="$2">
<div class="card-body">
<h5 class="card-title">$3</h5>
<p class="card-text">$4</p>
<div class="text-warning">
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
</div>
<a href="#" class="btn btn-primary pull-right">$5</a>
</div>
</div>
"""
'accordion with plus and minus icons':
'prefix': 'accordion'
'body': """
<!-- required bootstrap js and fontawesome -->
<!-- add 'accordion' snippet in css -->
<div id="accordion" class="accordion">
<div class="card mb-0">
<div class="card-header collapsed" data-toggle="collapse" href="#collapseOne">
<a class="card-title">$1</a>
</div>
<div id="collapseOne" class="card-body collapse" data-parent="#accordion" >
<p>$2</p>
</div>
<div class="card-header collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">
<a class="card-title">$3</a>
</div>
<div id="collapseTwo" class="card-body collapse" data-parent="#accordion" >
<p>$4</p>
</div>
<div class="card-header collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseThree">
<a class="card-title">$5</a>
</div>
<div id="collapseThree" class="collapse" data-parent="#accordion" >
<div class="card-body">$6</div>
</div>
</div>
</div>
"""
'header with top fixed':
'prefix': 'header-t-f'
'body': """
<!-- required bootstrap js -->
<nav class="navbar navbar-expand-md navbar-light fixed-top bg-light">
<div class="container">
<a class="navbar-brand" href="#">
<img src="$1" alt="$2", height="34">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">$3</a>
</li>
</ul>
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">$4</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">$5</a>
</li>
<li class="nav-item">
<button class="btn btn-outline-primary my-2 my-sm-0 ml-2" type="submit">Login/ Signup</button>
</li>
</ul>
</div>
</div>
</nav>
"""
'dynamic tab pills':
'prefix': 'tabs'
'body': """
<!-- required bootstrap js -->
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item">
<a class="nav-link active" data-toggle="tab" href="#home">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" data-toggle="tab" href="#menu1">Menu 1</a>
</li>
<li class="nav-item">
<a class="nav-link" data-toggle="tab" href="#menu2">Menu 2</a>
</li>
</ul>
<div class="tab-content">
<div id="home" class="container tab-pane active">
<p>$1</p>
</div>
<div id="menu1" class="container tab-pane fade">
<p>$2</p>
</div>
<div id="menu2" class="container tab-pane fade">
<p>$3</p>
</div>
</div>
"""
'table with responsive':
'prefix': 'table-r'
'body': """
<table class="table table-striped table-responsive">
<thead>
<tr>
<th>$1</th>
<th>$2</th>
</tr>
</thead>
<tbody>
<tr>
<td>$3</td>
<td>$4</td>
</tr>
<tr>
<td>$5</td>
<td>$6</td>
</tr>
<tr>
<td>$7</td>
<td>$8</td>
</tr>
</tbody>
</table>
"""
'carousel with indicators,controls and captions':
'prefix': 'carousel-slider'
'body': """
<!-- required bootstrap js -->
<!-- add 'carousel-slider' snippet in css -->
<div id="demo" class="carousel slide" data-ride="carousel">
<ul class="carousel-indicators">
<li data-target="#demo" data-slide-to="0" class="active"></li>
<li data-target="#demo" data-slide-to="1"></li>
<li data-target="#demo" data-slide-to="2"></li>
</ul>
<div class="carousel-inner">
<div class="carousel-item active">
<img src="$1" alt="">
<div class="carousel-caption">
<h3>$2Title</h3>
<p>$3Caption</p>
</div>
</div>
<div class="carousel-item">
<img src="$4" alt="">
<div class="carousel-caption">
<h3>$5Title</h3>
<p>$6Caption</p>
</div>
</div>
<div class="carousel-item">
<img src="$7" alt="">
<div class="carousel-caption">
<h3>$8Title</h3>
<p>$9Caption</p>
</div>
</div>
</div>
<a class="carousel-control-prev" href="#demo" data-slide="prev">
<span class="carousel-control-prev-icon"></span>
</a>
<a class="carousel-control-next" href="#demo" data-slide="next">
<span class="carousel-control-next-icon"></span>
</a>
</div>
"""
'timeline with responsive':
'prefix': 'timeline-r'
'body': """
<!-- required FontAwesome -->
<!-- add 'timeline-r' snippet in css -->
<ul class="timeline">
<li>
<div class="timeline-badge"><i class="fa fa-user"></i></div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">title</h4>
</div>
<div class="timeline-body">
<p>caption</p>
</div>
</div>
</li>
<li class="timeline-inverted">
<div class="timeline-badge"><i class="fa fa-home"></i></div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">title</h4>
</div>
<div class="timeline-body">
<p>caption</p>
</div>
</div>
</li>
<li>
<div class="timeline-badge"><i class="fa fa-user"></i></div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">title</h4>
</div>
<div class="timeline-body">
<p>caption</p>
</div>
</div>
</li>
<li class="timeline-inverted">
<div class="timeline-badge"><i class="fa fa-home"></i></div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">title</h4>
</div>
<div class="timeline-body">
<p>caption</p>
</div>
</div>
</li>
</ul>
"""
'Basic footer':
'prefix': 'footer'
'body': """
<!-- add 'footer' snippet in css -->
<div class="footer-v1 bg-img">
<div class="footer no-margin">
<div class="container">
<div class="row">
<div class="col-md-3">
<div class="headline"><p>Exams</p></div>
<ul class="list-unstyled link-list">
<li><a href="#">Exam 1</a></li>
<li><a href="#">Exam 2 </a></li>
<li><a href="#">Exam 3</a></li>
</ul>
</div>
<div class="col-md-3">
<div class="headline"><p>Resources</p></div>
<ul class="list-unstyled link-list">
<li><a href="#">Blog</a></li>
</ul>
</div>
<div class="col-md-3">
<div class="headline"><p>Support</p></div>
<address>
<ul class="list-unstyled link-list">
<li><a href="#">Contact Us</a></li>
<li>
<a href="#"><i class="fa fa-envelope"></i>support@company.com</a>
</li>
</ul>
</address>
</div>
<div class="col-md-3">
<div class="headline"><p>Company</p></div>
<ul class="list-unstyled link-list">
<li><a href="#">About Us</a></li>
<li> <a href="#">Privacy Policy</a></li>
<li><a href="#">Terms of Use</a></li>
<li><a href="#">FAQs</a></li>
<li><a href="#">Cancellation/Rescheduling policy</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
"""
'Flip card on hover':
'prefix': 'flip-card'
'body': """
<!-- add 'flip-card' snippet in css -->
<div class="flip-card">
<div class="flip-card-inner">
<div class="flip-card-front">
<img src="$1" alt="Avatar" style="width:200px;height:200px;">
</div>
<div class="flip-card-back">
<h1>$2</h1>
<p>$3</p>
<p>$4</p>
</div>
</div>
</div>
"""
'sticky sidebar collapse to icons with responsive':
'prefix': 'sidebar-icons'
'body': """
<!-- required fontawesome -->
<!-- add 'sidebar-icons' snippet in css -->
<!-- add 'sidebar-icons' snippet in js -->
<div class="container">
<div class="row">
<div id="wrapper">
<div id="sidebar-wrapper">
<ul class="sidebar-nav" style="margin-left:0;">
<li class="sidebar-brand">
<a href="#menu-toggle" id="menu-toggle" style="margin-top:10px;float:right;" >
<i class="fa fa-bars " style="font-size:20px !Important;" aria-hidden="true" aria-hidden="true"></i>
</a>
</li>
<li>
<a href="#"><i class="fa fa-sort-alpha-asc " aria-hidden="true"> </i> <span style="margin-left:10px;">Section</span> </a>
</li>
<li>
<a href="#"> <i class="fa fa-play-circle-o " aria-hidden="true"> </i> <span style="margin-left:10px;"> Section</span> </a>
</li>
<li>
<a href="#"> <i class="fa fa-puzzle-piece" aria-hidden="true"> </i> <span style="margin-left:10px;"> Section</span> </a>
</li>
<li>
<a href="#"> <i class="fa fa-font" aria-hidden="true"> </i> <span style="margin-left:10px;"> Section</span> </a>
</li>
<li>
<a href="#"><i class="fa fa-info-circle " aria-hidden="true"> </i> <span style="margin-left:10px;">Section </span> </a>
</li>
<li>
<a href="#"> <i class="fa fa-comment-o" aria-hidden="true"> </i> <span style="margin-left:10px;"> Section</span> </a>
</li>
</ul>
</div>
</div>
</div>
<p>Some text</p>
</div>
"""
'basic login/signup form using modal':
'prefix': 'login-signup'
'body': """
<!-- required bootstrap js -->
<button type="submit" name="commit" class="btn btn-outline-primary btn-sm" data-toggle="modal" data-target="#login">
Login/Signup
</button>
<div class="modal fade" id="login" role="dialog">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Login</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">
<i class="fa fa-envelope"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="Email" aria-label="Email" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">
<i class="fa fa-lock"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="Password" aria-label="Password" aria-describedby="basic-addon1">
</div>
<button type="submit" name="commit" class="btn btn-primary btn-lg btn-block">
<span>Login <i class="fa fa-sign-in"></i></span>
</button>
<div class="text-center">
<a class="" href="" data-dismiss="modal" data-toggle="modal" data-target="#signup">Signup</a>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="signup" role="dialog">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Signup</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">
<i class="fa fa-user"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="Name" aria-label="Name" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">
<i class="fa fa-envelope"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="Email" aria-label="Email" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">
<i class="fa fa-lock"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="Password" aria-label="Password" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">
<i class="fa fa-lock"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="Password confirmation" aria-label="Password confirmation" aria-describedby="basic-addon1">
</div>
<button type="submit" name="commit" class="btn btn-primary btn-lg btn-block">
<span>Signup <i class="fa fa-sign-in"></i></span>
</button>
<div class="text-center">
<a class="" href="" data-dismiss="modal" data-toggle="modal" data-target="#login">Login</a>
</div>
</div>
</div>
</div>
</div>
"""
# js
'.source.js':
'Console log':
'prefix': 'log'
'body': 'console.log($1)'
'sticky sidebar collapse to icons with responsive':
'prefix': 'sidebar-icons'
'body': """
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
"""
# css
'.source.css':
'accordion with plus and minus icons':
'prefix': 'accordion'
'body': """
.accordion .card-header:after {
font-family: 'FontAwesome';
content: "\f068";
float: right;
}
.accordion .card-header.collapsed:after {
/* symbol for "collapsed" panels */
content: "\f067";
}
"""
'carousel with indicators,controls and captions':
'prefix': 'carousel-slider'
'body': """
.carousel-inner img {
width: 100%;
height: 100%;
}
"""
'timeline with responsive':
'prefix': 'timeline-r'
'body': """
.timeline {
list-style: none;
padding: 20px 0 20px;
position: relative;
}
.timeline:before {
top: 0;
bottom: 0;
position: absolute;
content: " ";
width: 3px;
background-color: #eeeeee;
left: 50%;
margin-left: -1.5px;
}
.timeline > li {
margin-bottom: 20px;
position: relative;
}
.timeline > li:before,
.timeline > li:after {
content: " ";
display: table;
}
.timeline > li:after {
clear: both;
}
.timeline > li:before,
.timeline > li:after {
content: " ";
display: table;
}
.timeline > li:after {
clear: both;
}
.timeline > li > .timeline-panel {
width: 46%;
float: left;
border: 1px solid #d4d4d4;
border-radius: 2px;
padding: 20px;
position: relative;
-webkit-box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);
box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);
}
.timeline > li > .timeline-panel:before {
position: absolute;
top: 26px;
right: -15px;
display: inline-block;
border-top: 15px solid transparent;
border-left: 15px solid #ccc;
border-right: 0 solid #ccc;
border-bottom: 15px solid transparent;
content: " ";
}
.timeline > li > .timeline-panel:after {
position: absolute;
top: 27px;
right: -14px;
display: inline-block;
border-top: 14px solid transparent;
border-left: 14px solid #fff;
border-right: 0 solid #fff;
border-bottom: 14px solid transparent;
content: " ";
}
.timeline > li > .timeline-badge {
color: #fff;
width: 50px;
height: 50px;
line-height: 50px;
font-size: 1.4em;
text-align: center;
position: absolute;
top: 16px;
left: 50%;
margin-left: -25px;
background-color: #999999;
z-index: 100;
border-top-right-radius: 50%;
border-top-left-radius: 50%;
border-bottom-right-radius: 50%;
border-bottom-left-radius: 50%;
}
.timeline > li.timeline-inverted > .timeline-panel {
float: right;
}
.timeline > li.timeline-inverted > .timeline-panel:before {
border-left-width: 0;
border-right-width: 15px;
left: -15px;
right: auto;
}
.timeline > li.timeline-inverted > .timeline-panel:after {
border-left-width: 0;
border-right-width: 14px;
left: -14px;
right: auto;
}
@media (max-width: 767px) {
ul.timeline:before {
left: 40px;
}
ul.timeline > li > .timeline-panel {
width: calc(100% - 90px);
width: -moz-calc(100% - 90px);
width: -webkit-calc(100% - 90px);
}
ul.timeline > li > .timeline-badge {
left: 15px;
margin-left: 0;
top: 16px;
}
ul.timeline > li > .timeline-panel {
float: right;
}
ul.timeline > li > .timeline-panel:before {
border-left-width: 0;
border-right-width: 15px;
left: -15px;
right: auto;
}
ul.timeline > li > .timeline-panel:after {
border-left-width: 0;
border-right-width: 14px;
left: -14px;
right: auto;
}
}
"""
'Basic footer':
'prefix': 'footer'
'body': """
.footer-v1.bg-img {
background-color: black;
background-repeat: repeat;
}
.headline {
display: block;
margin: 10px 0 25px 0;
border-bottom: 1px dotted #e4e9f0;
color: white;
font-size: 20px;
}
.headline p {
margin: 0 0 -2px 0;
padding-bottom: 5px;
display: inline-block;
border-bottom: 2px solid #7e57c2;
}
.link-list > li{
padding: 7px 0px;
}
.link-list > li > a , .link-list > li> i{
color:#eee;
font-size: 16px;
}
"""
'Flip card on hover':
'prefix': 'flip-card'
'body': """
.flip-card {
background-color: transparent;
width: 200px;
height: 200px;
perspective: 1000px;
}
.flip-card-inner {
position: relative;
width: 100%;
height: 100%;
text-align: center;
transition: transform 0.6s;
transform-style: preserve-3d;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
}
.flip-card:hover .flip-card-inner {
transform: rotateY(180deg);
}
.flip-card-front, .flip-card-back {
position: absolute;
width: 100%;
height: 100%;
backface-visibility: hidden;
}
.flip-card-front {
background-color: #bbb;
color: black;
z-index: 2;
}
.flip-card-back {
background-color: #2980b9;
color: white;
transform: rotateY(180deg);
z-index: 1;
}
"""
'sticky sidebar collapse to icons with responsive':
'prefix': 'sidebar-icons'
'body': """
#wrapper {
padding-left: 0;
-webkit-transition: all 0.6s ease;
-moz-transition: all 0.6s ease;
-o-transition: all 0.6s ease;
transition: all 0.6s ease;
}
#wrapper.toggled {
padding-left: 200px;
}
#sidebar-wrapper {
z-index: 1000;
position: fixed;
left: 250px;
width: 0;
height: 100%;
margin-left: -250px;
overflow-y: auto;
background-color:#312A25 !Important;
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
transition: all 0.5s ease;
}
#wrapper.toggled #sidebar-wrapper {
width: 0;
}
#page-content-wrapper {
width: 100%;
position: absolute;
padding: 10px;
}
#wrapper.toggled #page-content-wrapper {
position: absolute;
margin-left:-250px;
}
.sidebar-nav {
position: absolute;
top: 0;
right:15px;
width: 200px;
margin: 0;
padding: 0;
list-style: none;
}
.sidebar-nav li {
text-indent: 20px;
line-height: 40px;
}
.sidebar-nav li a {
display: block;
text-decoration: none;
color: #999999;
}
.sidebar-nav li a:hover {
text-decoration: none;
color: #fff;
background: #312A25;
}
.sidebar-nav li a:active,
.sidebar-nav li a:focus {
text-decoration: none;
}
.sidebar-nav > .sidebar-brand {
height: 60px;
font-size: 18px;
}
.sidebar-nav > .sidebar-brand a {
color: #999999;
}
.sidebar-nav > .sidebar-brand a:hover {
color: #fff;
background: none;
}
@media(min-width:768px) {
#wrapper {
padding-left: 220px;
}
#wrapper.toggled {
padding-left: 0;
}
#sidebar-wrapper {
width: 200px;
}
#wrapper.toggled #sidebar-wrapper {
width: 40px;
}
#wrapper.toggled span {
visibility:hidden;
}
#wrapper.toggled i {
float:right;
}
#page-content-wrapper {
padding: 20px;
position: relative;
}
#wrapper.toggled #page-content-wrapper {
position: relative;
margin-right: 0;
}
}
@media(max-width:414px) {
#wrapper.toggled #page-content-wrapper {
position: absolute;
margin-right:60px;
}
#wrapper.toggled {
padding-right: 60px;
}
#wrapper {
padding-left: 20px;
}
#wrapper.toggled {
padding-left: 0;
}
#sidebar-wrapper {
width: 50px;
}
#wrapper.toggled #sidebar-wrapper {
width: 140px;
}
#wrapper.toggled span {
visibility:visible;
position:relative;
left:70px;
bottom:13px;
}
#wrapper span {
visibility:hidden;
}
#wrapper.toggled i {
float:right;
}
#wrapper i {
float:right;
}
#page-content-wrapper {
padding: 5px;
position: relative;
}
#wrapper.toggled #page-content-wrapper {
position: relative;
margin-right: 0;
}
}
"""
| 36403 |
# html and erb
'.text.html.basic , .text.html.erb':
'bootstrap media':
'prefix': 'media'
'body': """
<div class="media">
<div class="media-left">
$1
</div>
<div class="media-body">
$2
</div>
<div class="media-right">
$3
</div>
</div>
"""
'card with image and text':
'prefix': 'card'
'body': """
<div class="card">
<img src="$1" alt="$2">
<div class="card-body">
<h5 class="card-title">$3</h5>
<p class="card-text">$4</p>
<div class="text-warning">
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
</div>
<a href="#" class="btn btn-primary pull-right">$5</a>
</div>
</div>
"""
'accordion with plus and minus icons':
'prefix': 'accordion'
'body': """
<!-- required bootstrap js and fontawesome -->
<!-- add 'accordion' snippet in css -->
<div id="accordion" class="accordion">
<div class="card mb-0">
<div class="card-header collapsed" data-toggle="collapse" href="#collapseOne">
<a class="card-title">$1</a>
</div>
<div id="collapseOne" class="card-body collapse" data-parent="#accordion" >
<p>$2</p>
</div>
<div class="card-header collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">
<a class="card-title">$3</a>
</div>
<div id="collapseTwo" class="card-body collapse" data-parent="#accordion" >
<p>$4</p>
</div>
<div class="card-header collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseThree">
<a class="card-title">$5</a>
</div>
<div id="collapseThree" class="collapse" data-parent="#accordion" >
<div class="card-body">$6</div>
</div>
</div>
</div>
"""
'header with top fixed':
'prefix': 'header-t-f'
'body': """
<!-- required bootstrap js -->
<nav class="navbar navbar-expand-md navbar-light fixed-top bg-light">
<div class="container">
<a class="navbar-brand" href="#">
<img src="$1" alt="$2", height="34">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">$3</a>
</li>
</ul>
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">$4</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">$5</a>
</li>
<li class="nav-item">
<button class="btn btn-outline-primary my-2 my-sm-0 ml-2" type="submit">Login/ Signup</button>
</li>
</ul>
</div>
</div>
</nav>
"""
'dynamic tab pills':
'prefix': 'tabs'
'body': """
<!-- required bootstrap js -->
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item">
<a class="nav-link active" data-toggle="tab" href="#home">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" data-toggle="tab" href="#menu1">Menu 1</a>
</li>
<li class="nav-item">
<a class="nav-link" data-toggle="tab" href="#menu2">Menu 2</a>
</li>
</ul>
<div class="tab-content">
<div id="home" class="container tab-pane active">
<p>$1</p>
</div>
<div id="menu1" class="container tab-pane fade">
<p>$2</p>
</div>
<div id="menu2" class="container tab-pane fade">
<p>$3</p>
</div>
</div>
"""
'table with responsive':
'prefix': 'table-r'
'body': """
<table class="table table-striped table-responsive">
<thead>
<tr>
<th>$1</th>
<th>$2</th>
</tr>
</thead>
<tbody>
<tr>
<td>$3</td>
<td>$4</td>
</tr>
<tr>
<td>$5</td>
<td>$6</td>
</tr>
<tr>
<td>$7</td>
<td>$8</td>
</tr>
</tbody>
</table>
"""
'carousel with indicators,controls and captions':
'prefix': 'carousel-slider'
'body': """
<!-- required bootstrap js -->
<!-- add 'carousel-slider' snippet in css -->
<div id="demo" class="carousel slide" data-ride="carousel">
<ul class="carousel-indicators">
<li data-target="#demo" data-slide-to="0" class="active"></li>
<li data-target="#demo" data-slide-to="1"></li>
<li data-target="#demo" data-slide-to="2"></li>
</ul>
<div class="carousel-inner">
<div class="carousel-item active">
<img src="$1" alt="">
<div class="carousel-caption">
<h3>$2Title</h3>
<p>$3Caption</p>
</div>
</div>
<div class="carousel-item">
<img src="$4" alt="">
<div class="carousel-caption">
<h3>$5Title</h3>
<p>$6Caption</p>
</div>
</div>
<div class="carousel-item">
<img src="$7" alt="">
<div class="carousel-caption">
<h3>$8Title</h3>
<p>$9Caption</p>
</div>
</div>
</div>
<a class="carousel-control-prev" href="#demo" data-slide="prev">
<span class="carousel-control-prev-icon"></span>
</a>
<a class="carousel-control-next" href="#demo" data-slide="next">
<span class="carousel-control-next-icon"></span>
</a>
</div>
"""
'timeline with responsive':
'prefix': 'timeline-r'
'body': """
<!-- required FontAwesome -->
<!-- add 'timeline-r' snippet in css -->
<ul class="timeline">
<li>
<div class="timeline-badge"><i class="fa fa-user"></i></div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">title</h4>
</div>
<div class="timeline-body">
<p>caption</p>
</div>
</div>
</li>
<li class="timeline-inverted">
<div class="timeline-badge"><i class="fa fa-home"></i></div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">title</h4>
</div>
<div class="timeline-body">
<p>caption</p>
</div>
</div>
</li>
<li>
<div class="timeline-badge"><i class="fa fa-user"></i></div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">title</h4>
</div>
<div class="timeline-body">
<p>caption</p>
</div>
</div>
</li>
<li class="timeline-inverted">
<div class="timeline-badge"><i class="fa fa-home"></i></div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">title</h4>
</div>
<div class="timeline-body">
<p>caption</p>
</div>
</div>
</li>
</ul>
"""
'Basic footer':
'prefix': 'footer'
'body': """
<!-- add 'footer' snippet in css -->
<div class="footer-v1 bg-img">
<div class="footer no-margin">
<div class="container">
<div class="row">
<div class="col-md-3">
<div class="headline"><p>Exams</p></div>
<ul class="list-unstyled link-list">
<li><a href="#">Exam 1</a></li>
<li><a href="#">Exam 2 </a></li>
<li><a href="#">Exam 3</a></li>
</ul>
</div>
<div class="col-md-3">
<div class="headline"><p>Resources</p></div>
<ul class="list-unstyled link-list">
<li><a href="#">Blog</a></li>
</ul>
</div>
<div class="col-md-3">
<div class="headline"><p>Support</p></div>
<address>
<ul class="list-unstyled link-list">
<li><a href="#">Contact Us</a></li>
<li>
<a href="#"><i class="fa fa-envelope"></i><EMAIL></a>
</li>
</ul>
</address>
</div>
<div class="col-md-3">
<div class="headline"><p>Company</p></div>
<ul class="list-unstyled link-list">
<li><a href="#">About Us</a></li>
<li> <a href="#">Privacy Policy</a></li>
<li><a href="#">Terms of Use</a></li>
<li><a href="#">FAQs</a></li>
<li><a href="#">Cancellation/Rescheduling policy</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
"""
'Flip card on hover':
'prefix': 'flip-card'
'body': """
<!-- add 'flip-card' snippet in css -->
<div class="flip-card">
<div class="flip-card-inner">
<div class="flip-card-front">
<img src="$1" alt="Avatar" style="width:200px;height:200px;">
</div>
<div class="flip-card-back">
<h1>$2</h1>
<p>$3</p>
<p>$4</p>
</div>
</div>
</div>
"""
'sticky sidebar collapse to icons with responsive':
'prefix': 'sidebar-icons'
'body': """
<!-- required fontawesome -->
<!-- add 'sidebar-icons' snippet in css -->
<!-- add 'sidebar-icons' snippet in js -->
<div class="container">
<div class="row">
<div id="wrapper">
<div id="sidebar-wrapper">
<ul class="sidebar-nav" style="margin-left:0;">
<li class="sidebar-brand">
<a href="#menu-toggle" id="menu-toggle" style="margin-top:10px;float:right;" >
<i class="fa fa-bars " style="font-size:20px !Important;" aria-hidden="true" aria-hidden="true"></i>
</a>
</li>
<li>
<a href="#"><i class="fa fa-sort-alpha-asc " aria-hidden="true"> </i> <span style="margin-left:10px;">Section</span> </a>
</li>
<li>
<a href="#"> <i class="fa fa-play-circle-o " aria-hidden="true"> </i> <span style="margin-left:10px;"> Section</span> </a>
</li>
<li>
<a href="#"> <i class="fa fa-puzzle-piece" aria-hidden="true"> </i> <span style="margin-left:10px;"> Section</span> </a>
</li>
<li>
<a href="#"> <i class="fa fa-font" aria-hidden="true"> </i> <span style="margin-left:10px;"> Section</span> </a>
</li>
<li>
<a href="#"><i class="fa fa-info-circle " aria-hidden="true"> </i> <span style="margin-left:10px;">Section </span> </a>
</li>
<li>
<a href="#"> <i class="fa fa-comment-o" aria-hidden="true"> </i> <span style="margin-left:10px;"> Section</span> </a>
</li>
</ul>
</div>
</div>
</div>
<p>Some text</p>
</div>
"""
'basic login/signup form using modal':
'prefix': 'login-signup'
'body': """
<!-- required bootstrap js -->
<button type="submit" name="commit" class="btn btn-outline-primary btn-sm" data-toggle="modal" data-target="#login">
Login/Signup
</button>
<div class="modal fade" id="login" role="dialog">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Login</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">
<i class="fa fa-envelope"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="Email" aria-label="Email" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">
<i class="fa fa-lock"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="Password" aria-label="Password" aria-describedby="basic-addon1">
</div>
<button type="submit" name="commit" class="btn btn-primary btn-lg btn-block">
<span>Login <i class="fa fa-sign-in"></i></span>
</button>
<div class="text-center">
<a class="" href="" data-dismiss="modal" data-toggle="modal" data-target="#signup">Signup</a>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="signup" role="dialog">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Signup</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">
<i class="fa fa-user"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="<NAME>" aria-label="Name" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">
<i class="fa fa-envelope"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="Email" aria-label="Email" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">
<i class="fa fa-lock"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="<PASSWORD>" aria-label="Password" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">
<i class="fa fa-lock"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="<PASSWORD> confirmation" aria-label="Password confirmation" aria-describedby="basic-addon1">
</div>
<button type="submit" name="commit" class="btn btn-primary btn-lg btn-block">
<span>Signup <i class="fa fa-sign-in"></i></span>
</button>
<div class="text-center">
<a class="" href="" data-dismiss="modal" data-toggle="modal" data-target="#login">Login</a>
</div>
</div>
</div>
</div>
</div>
"""
# js
'.source.js':
'Console log':
'prefix': 'log'
'body': 'console.log($1)'
'sticky sidebar collapse to icons with responsive':
'prefix': 'sidebar-icons'
'body': """
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
"""
# css
'.source.css':
'accordion with plus and minus icons':
'prefix': 'accordion'
'body': """
.accordion .card-header:after {
font-family: 'FontAwesome';
content: "\f068";
float: right;
}
.accordion .card-header.collapsed:after {
/* symbol for "collapsed" panels */
content: "\f067";
}
"""
'carousel with indicators,controls and captions':
'prefix': 'carousel-slider'
'body': """
.carousel-inner img {
width: 100%;
height: 100%;
}
"""
'timeline with responsive':
'prefix': 'timeline-r'
'body': """
.timeline {
list-style: none;
padding: 20px 0 20px;
position: relative;
}
.timeline:before {
top: 0;
bottom: 0;
position: absolute;
content: " ";
width: 3px;
background-color: #eeeeee;
left: 50%;
margin-left: -1.5px;
}
.timeline > li {
margin-bottom: 20px;
position: relative;
}
.timeline > li:before,
.timeline > li:after {
content: " ";
display: table;
}
.timeline > li:after {
clear: both;
}
.timeline > li:before,
.timeline > li:after {
content: " ";
display: table;
}
.timeline > li:after {
clear: both;
}
.timeline > li > .timeline-panel {
width: 46%;
float: left;
border: 1px solid #d4d4d4;
border-radius: 2px;
padding: 20px;
position: relative;
-webkit-box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);
box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);
}
.timeline > li > .timeline-panel:before {
position: absolute;
top: 26px;
right: -15px;
display: inline-block;
border-top: 15px solid transparent;
border-left: 15px solid #ccc;
border-right: 0 solid #ccc;
border-bottom: 15px solid transparent;
content: " ";
}
.timeline > li > .timeline-panel:after {
position: absolute;
top: 27px;
right: -14px;
display: inline-block;
border-top: 14px solid transparent;
border-left: 14px solid #fff;
border-right: 0 solid #fff;
border-bottom: 14px solid transparent;
content: " ";
}
.timeline > li > .timeline-badge {
color: #fff;
width: 50px;
height: 50px;
line-height: 50px;
font-size: 1.4em;
text-align: center;
position: absolute;
top: 16px;
left: 50%;
margin-left: -25px;
background-color: #999999;
z-index: 100;
border-top-right-radius: 50%;
border-top-left-radius: 50%;
border-bottom-right-radius: 50%;
border-bottom-left-radius: 50%;
}
.timeline > li.timeline-inverted > .timeline-panel {
float: right;
}
.timeline > li.timeline-inverted > .timeline-panel:before {
border-left-width: 0;
border-right-width: 15px;
left: -15px;
right: auto;
}
.timeline > li.timeline-inverted > .timeline-panel:after {
border-left-width: 0;
border-right-width: 14px;
left: -14px;
right: auto;
}
@media (max-width: 767px) {
ul.timeline:before {
left: 40px;
}
ul.timeline > li > .timeline-panel {
width: calc(100% - 90px);
width: -moz-calc(100% - 90px);
width: -webkit-calc(100% - 90px);
}
ul.timeline > li > .timeline-badge {
left: 15px;
margin-left: 0;
top: 16px;
}
ul.timeline > li > .timeline-panel {
float: right;
}
ul.timeline > li > .timeline-panel:before {
border-left-width: 0;
border-right-width: 15px;
left: -15px;
right: auto;
}
ul.timeline > li > .timeline-panel:after {
border-left-width: 0;
border-right-width: 14px;
left: -14px;
right: auto;
}
}
"""
'Basic footer':
'prefix': 'footer'
'body': """
.footer-v1.bg-img {
background-color: black;
background-repeat: repeat;
}
.headline {
display: block;
margin: 10px 0 25px 0;
border-bottom: 1px dotted #e4e9f0;
color: white;
font-size: 20px;
}
.headline p {
margin: 0 0 -2px 0;
padding-bottom: 5px;
display: inline-block;
border-bottom: 2px solid #7e57c2;
}
.link-list > li{
padding: 7px 0px;
}
.link-list > li > a , .link-list > li> i{
color:#eee;
font-size: 16px;
}
"""
'Flip card on hover':
'prefix': 'flip-card'
'body': """
.flip-card {
background-color: transparent;
width: 200px;
height: 200px;
perspective: 1000px;
}
.flip-card-inner {
position: relative;
width: 100%;
height: 100%;
text-align: center;
transition: transform 0.6s;
transform-style: preserve-3d;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
}
.flip-card:hover .flip-card-inner {
transform: rotateY(180deg);
}
.flip-card-front, .flip-card-back {
position: absolute;
width: 100%;
height: 100%;
backface-visibility: hidden;
}
.flip-card-front {
background-color: #bbb;
color: black;
z-index: 2;
}
.flip-card-back {
background-color: #2980b9;
color: white;
transform: rotateY(180deg);
z-index: 1;
}
"""
'sticky sidebar collapse to icons with responsive':
'prefix': 'sidebar-icons'
'body': """
#wrapper {
padding-left: 0;
-webkit-transition: all 0.6s ease;
-moz-transition: all 0.6s ease;
-o-transition: all 0.6s ease;
transition: all 0.6s ease;
}
#wrapper.toggled {
padding-left: 200px;
}
#sidebar-wrapper {
z-index: 1000;
position: fixed;
left: 250px;
width: 0;
height: 100%;
margin-left: -250px;
overflow-y: auto;
background-color:#312A25 !Important;
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
transition: all 0.5s ease;
}
#wrapper.toggled #sidebar-wrapper {
width: 0;
}
#page-content-wrapper {
width: 100%;
position: absolute;
padding: 10px;
}
#wrapper.toggled #page-content-wrapper {
position: absolute;
margin-left:-250px;
}
.sidebar-nav {
position: absolute;
top: 0;
right:15px;
width: 200px;
margin: 0;
padding: 0;
list-style: none;
}
.sidebar-nav li {
text-indent: 20px;
line-height: 40px;
}
.sidebar-nav li a {
display: block;
text-decoration: none;
color: #999999;
}
.sidebar-nav li a:hover {
text-decoration: none;
color: #fff;
background: #312A25;
}
.sidebar-nav li a:active,
.sidebar-nav li a:focus {
text-decoration: none;
}
.sidebar-nav > .sidebar-brand {
height: 60px;
font-size: 18px;
}
.sidebar-nav > .sidebar-brand a {
color: #999999;
}
.sidebar-nav > .sidebar-brand a:hover {
color: #fff;
background: none;
}
@media(min-width:768px) {
#wrapper {
padding-left: 220px;
}
#wrapper.toggled {
padding-left: 0;
}
#sidebar-wrapper {
width: 200px;
}
#wrapper.toggled #sidebar-wrapper {
width: 40px;
}
#wrapper.toggled span {
visibility:hidden;
}
#wrapper.toggled i {
float:right;
}
#page-content-wrapper {
padding: 20px;
position: relative;
}
#wrapper.toggled #page-content-wrapper {
position: relative;
margin-right: 0;
}
}
@media(max-width:414px) {
#wrapper.toggled #page-content-wrapper {
position: absolute;
margin-right:60px;
}
#wrapper.toggled {
padding-right: 60px;
}
#wrapper {
padding-left: 20px;
}
#wrapper.toggled {
padding-left: 0;
}
#sidebar-wrapper {
width: 50px;
}
#wrapper.toggled #sidebar-wrapper {
width: 140px;
}
#wrapper.toggled span {
visibility:visible;
position:relative;
left:70px;
bottom:13px;
}
#wrapper span {
visibility:hidden;
}
#wrapper.toggled i {
float:right;
}
#wrapper i {
float:right;
}
#page-content-wrapper {
padding: 5px;
position: relative;
}
#wrapper.toggled #page-content-wrapper {
position: relative;
margin-right: 0;
}
}
"""
| true |
# html and erb
'.text.html.basic , .text.html.erb':
'bootstrap media':
'prefix': 'media'
'body': """
<div class="media">
<div class="media-left">
$1
</div>
<div class="media-body">
$2
</div>
<div class="media-right">
$3
</div>
</div>
"""
'card with image and text':
'prefix': 'card'
'body': """
<div class="card">
<img src="$1" alt="$2">
<div class="card-body">
<h5 class="card-title">$3</h5>
<p class="card-text">$4</p>
<div class="text-warning">
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
</div>
<a href="#" class="btn btn-primary pull-right">$5</a>
</div>
</div>
"""
'accordion with plus and minus icons':
'prefix': 'accordion'
'body': """
<!-- required bootstrap js and fontawesome -->
<!-- add 'accordion' snippet in css -->
<div id="accordion" class="accordion">
<div class="card mb-0">
<div class="card-header collapsed" data-toggle="collapse" href="#collapseOne">
<a class="card-title">$1</a>
</div>
<div id="collapseOne" class="card-body collapse" data-parent="#accordion" >
<p>$2</p>
</div>
<div class="card-header collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">
<a class="card-title">$3</a>
</div>
<div id="collapseTwo" class="card-body collapse" data-parent="#accordion" >
<p>$4</p>
</div>
<div class="card-header collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseThree">
<a class="card-title">$5</a>
</div>
<div id="collapseThree" class="collapse" data-parent="#accordion" >
<div class="card-body">$6</div>
</div>
</div>
</div>
"""
'header with top fixed':
'prefix': 'header-t-f'
'body': """
<!-- required bootstrap js -->
<nav class="navbar navbar-expand-md navbar-light fixed-top bg-light">
<div class="container">
<a class="navbar-brand" href="#">
<img src="$1" alt="$2", height="34">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">$3</a>
</li>
</ul>
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">$4</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">$5</a>
</li>
<li class="nav-item">
<button class="btn btn-outline-primary my-2 my-sm-0 ml-2" type="submit">Login/ Signup</button>
</li>
</ul>
</div>
</div>
</nav>
"""
'dynamic tab pills':
'prefix': 'tabs'
'body': """
<!-- required bootstrap js -->
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item">
<a class="nav-link active" data-toggle="tab" href="#home">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" data-toggle="tab" href="#menu1">Menu 1</a>
</li>
<li class="nav-item">
<a class="nav-link" data-toggle="tab" href="#menu2">Menu 2</a>
</li>
</ul>
<div class="tab-content">
<div id="home" class="container tab-pane active">
<p>$1</p>
</div>
<div id="menu1" class="container tab-pane fade">
<p>$2</p>
</div>
<div id="menu2" class="container tab-pane fade">
<p>$3</p>
</div>
</div>
"""
'table with responsive':
'prefix': 'table-r'
'body': """
<table class="table table-striped table-responsive">
<thead>
<tr>
<th>$1</th>
<th>$2</th>
</tr>
</thead>
<tbody>
<tr>
<td>$3</td>
<td>$4</td>
</tr>
<tr>
<td>$5</td>
<td>$6</td>
</tr>
<tr>
<td>$7</td>
<td>$8</td>
</tr>
</tbody>
</table>
"""
'carousel with indicators,controls and captions':
'prefix': 'carousel-slider'
'body': """
<!-- required bootstrap js -->
<!-- add 'carousel-slider' snippet in css -->
<div id="demo" class="carousel slide" data-ride="carousel">
<ul class="carousel-indicators">
<li data-target="#demo" data-slide-to="0" class="active"></li>
<li data-target="#demo" data-slide-to="1"></li>
<li data-target="#demo" data-slide-to="2"></li>
</ul>
<div class="carousel-inner">
<div class="carousel-item active">
<img src="$1" alt="">
<div class="carousel-caption">
<h3>$2Title</h3>
<p>$3Caption</p>
</div>
</div>
<div class="carousel-item">
<img src="$4" alt="">
<div class="carousel-caption">
<h3>$5Title</h3>
<p>$6Caption</p>
</div>
</div>
<div class="carousel-item">
<img src="$7" alt="">
<div class="carousel-caption">
<h3>$8Title</h3>
<p>$9Caption</p>
</div>
</div>
</div>
<a class="carousel-control-prev" href="#demo" data-slide="prev">
<span class="carousel-control-prev-icon"></span>
</a>
<a class="carousel-control-next" href="#demo" data-slide="next">
<span class="carousel-control-next-icon"></span>
</a>
</div>
"""
'timeline with responsive':
'prefix': 'timeline-r'
'body': """
<!-- required FontAwesome -->
<!-- add 'timeline-r' snippet in css -->
<ul class="timeline">
<li>
<div class="timeline-badge"><i class="fa fa-user"></i></div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">title</h4>
</div>
<div class="timeline-body">
<p>caption</p>
</div>
</div>
</li>
<li class="timeline-inverted">
<div class="timeline-badge"><i class="fa fa-home"></i></div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">title</h4>
</div>
<div class="timeline-body">
<p>caption</p>
</div>
</div>
</li>
<li>
<div class="timeline-badge"><i class="fa fa-user"></i></div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">title</h4>
</div>
<div class="timeline-body">
<p>caption</p>
</div>
</div>
</li>
<li class="timeline-inverted">
<div class="timeline-badge"><i class="fa fa-home"></i></div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">title</h4>
</div>
<div class="timeline-body">
<p>caption</p>
</div>
</div>
</li>
</ul>
"""
'Basic footer':
'prefix': 'footer'
'body': """
<!-- add 'footer' snippet in css -->
<div class="footer-v1 bg-img">
<div class="footer no-margin">
<div class="container">
<div class="row">
<div class="col-md-3">
<div class="headline"><p>Exams</p></div>
<ul class="list-unstyled link-list">
<li><a href="#">Exam 1</a></li>
<li><a href="#">Exam 2 </a></li>
<li><a href="#">Exam 3</a></li>
</ul>
</div>
<div class="col-md-3">
<div class="headline"><p>Resources</p></div>
<ul class="list-unstyled link-list">
<li><a href="#">Blog</a></li>
</ul>
</div>
<div class="col-md-3">
<div class="headline"><p>Support</p></div>
<address>
<ul class="list-unstyled link-list">
<li><a href="#">Contact Us</a></li>
<li>
<a href="#"><i class="fa fa-envelope"></i>PI:EMAIL:<EMAIL>END_PI</a>
</li>
</ul>
</address>
</div>
<div class="col-md-3">
<div class="headline"><p>Company</p></div>
<ul class="list-unstyled link-list">
<li><a href="#">About Us</a></li>
<li> <a href="#">Privacy Policy</a></li>
<li><a href="#">Terms of Use</a></li>
<li><a href="#">FAQs</a></li>
<li><a href="#">Cancellation/Rescheduling policy</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
"""
'Flip card on hover':
'prefix': 'flip-card'
'body': """
<!-- add 'flip-card' snippet in css -->
<div class="flip-card">
<div class="flip-card-inner">
<div class="flip-card-front">
<img src="$1" alt="Avatar" style="width:200px;height:200px;">
</div>
<div class="flip-card-back">
<h1>$2</h1>
<p>$3</p>
<p>$4</p>
</div>
</div>
</div>
"""
'sticky sidebar collapse to icons with responsive':
'prefix': 'sidebar-icons'
'body': """
<!-- required fontawesome -->
<!-- add 'sidebar-icons' snippet in css -->
<!-- add 'sidebar-icons' snippet in js -->
<div class="container">
<div class="row">
<div id="wrapper">
<div id="sidebar-wrapper">
<ul class="sidebar-nav" style="margin-left:0;">
<li class="sidebar-brand">
<a href="#menu-toggle" id="menu-toggle" style="margin-top:10px;float:right;" >
<i class="fa fa-bars " style="font-size:20px !Important;" aria-hidden="true" aria-hidden="true"></i>
</a>
</li>
<li>
<a href="#"><i class="fa fa-sort-alpha-asc " aria-hidden="true"> </i> <span style="margin-left:10px;">Section</span> </a>
</li>
<li>
<a href="#"> <i class="fa fa-play-circle-o " aria-hidden="true"> </i> <span style="margin-left:10px;"> Section</span> </a>
</li>
<li>
<a href="#"> <i class="fa fa-puzzle-piece" aria-hidden="true"> </i> <span style="margin-left:10px;"> Section</span> </a>
</li>
<li>
<a href="#"> <i class="fa fa-font" aria-hidden="true"> </i> <span style="margin-left:10px;"> Section</span> </a>
</li>
<li>
<a href="#"><i class="fa fa-info-circle " aria-hidden="true"> </i> <span style="margin-left:10px;">Section </span> </a>
</li>
<li>
<a href="#"> <i class="fa fa-comment-o" aria-hidden="true"> </i> <span style="margin-left:10px;"> Section</span> </a>
</li>
</ul>
</div>
</div>
</div>
<p>Some text</p>
</div>
"""
'basic login/signup form using modal':
'prefix': 'login-signup'
'body': """
<!-- required bootstrap js -->
<button type="submit" name="commit" class="btn btn-outline-primary btn-sm" data-toggle="modal" data-target="#login">
Login/Signup
</button>
<div class="modal fade" id="login" role="dialog">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Login</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">
<i class="fa fa-envelope"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="Email" aria-label="Email" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">
<i class="fa fa-lock"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="Password" aria-label="Password" aria-describedby="basic-addon1">
</div>
<button type="submit" name="commit" class="btn btn-primary btn-lg btn-block">
<span>Login <i class="fa fa-sign-in"></i></span>
</button>
<div class="text-center">
<a class="" href="" data-dismiss="modal" data-toggle="modal" data-target="#signup">Signup</a>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="signup" role="dialog">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Signup</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">
<i class="fa fa-user"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="PI:NAME:<NAME>END_PI" aria-label="Name" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">
<i class="fa fa-envelope"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="Email" aria-label="Email" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">
<i class="fa fa-lock"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="PI:PASSWORD:<PASSWORD>END_PI" aria-label="Password" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-sm">
<i class="fa fa-lock"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="PI:PASSWORD:<PASSWORD>END_PI confirmation" aria-label="Password confirmation" aria-describedby="basic-addon1">
</div>
<button type="submit" name="commit" class="btn btn-primary btn-lg btn-block">
<span>Signup <i class="fa fa-sign-in"></i></span>
</button>
<div class="text-center">
<a class="" href="" data-dismiss="modal" data-toggle="modal" data-target="#login">Login</a>
</div>
</div>
</div>
</div>
</div>
"""
# js
'.source.js':
'Console log':
'prefix': 'log'
'body': 'console.log($1)'
'sticky sidebar collapse to icons with responsive':
'prefix': 'sidebar-icons'
'body': """
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
"""
# css
'.source.css':
'accordion with plus and minus icons':
'prefix': 'accordion'
'body': """
.accordion .card-header:after {
font-family: 'FontAwesome';
content: "\f068";
float: right;
}
.accordion .card-header.collapsed:after {
/* symbol for "collapsed" panels */
content: "\f067";
}
"""
'carousel with indicators,controls and captions':
'prefix': 'carousel-slider'
'body': """
.carousel-inner img {
width: 100%;
height: 100%;
}
"""
'timeline with responsive':
'prefix': 'timeline-r'
'body': """
.timeline {
list-style: none;
padding: 20px 0 20px;
position: relative;
}
.timeline:before {
top: 0;
bottom: 0;
position: absolute;
content: " ";
width: 3px;
background-color: #eeeeee;
left: 50%;
margin-left: -1.5px;
}
.timeline > li {
margin-bottom: 20px;
position: relative;
}
.timeline > li:before,
.timeline > li:after {
content: " ";
display: table;
}
.timeline > li:after {
clear: both;
}
.timeline > li:before,
.timeline > li:after {
content: " ";
display: table;
}
.timeline > li:after {
clear: both;
}
.timeline > li > .timeline-panel {
width: 46%;
float: left;
border: 1px solid #d4d4d4;
border-radius: 2px;
padding: 20px;
position: relative;
-webkit-box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);
box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);
}
.timeline > li > .timeline-panel:before {
position: absolute;
top: 26px;
right: -15px;
display: inline-block;
border-top: 15px solid transparent;
border-left: 15px solid #ccc;
border-right: 0 solid #ccc;
border-bottom: 15px solid transparent;
content: " ";
}
.timeline > li > .timeline-panel:after {
position: absolute;
top: 27px;
right: -14px;
display: inline-block;
border-top: 14px solid transparent;
border-left: 14px solid #fff;
border-right: 0 solid #fff;
border-bottom: 14px solid transparent;
content: " ";
}
.timeline > li > .timeline-badge {
color: #fff;
width: 50px;
height: 50px;
line-height: 50px;
font-size: 1.4em;
text-align: center;
position: absolute;
top: 16px;
left: 50%;
margin-left: -25px;
background-color: #999999;
z-index: 100;
border-top-right-radius: 50%;
border-top-left-radius: 50%;
border-bottom-right-radius: 50%;
border-bottom-left-radius: 50%;
}
.timeline > li.timeline-inverted > .timeline-panel {
float: right;
}
.timeline > li.timeline-inverted > .timeline-panel:before {
border-left-width: 0;
border-right-width: 15px;
left: -15px;
right: auto;
}
.timeline > li.timeline-inverted > .timeline-panel:after {
border-left-width: 0;
border-right-width: 14px;
left: -14px;
right: auto;
}
@media (max-width: 767px) {
ul.timeline:before {
left: 40px;
}
ul.timeline > li > .timeline-panel {
width: calc(100% - 90px);
width: -moz-calc(100% - 90px);
width: -webkit-calc(100% - 90px);
}
ul.timeline > li > .timeline-badge {
left: 15px;
margin-left: 0;
top: 16px;
}
ul.timeline > li > .timeline-panel {
float: right;
}
ul.timeline > li > .timeline-panel:before {
border-left-width: 0;
border-right-width: 15px;
left: -15px;
right: auto;
}
ul.timeline > li > .timeline-panel:after {
border-left-width: 0;
border-right-width: 14px;
left: -14px;
right: auto;
}
}
"""
'Basic footer':
'prefix': 'footer'
'body': """
.footer-v1.bg-img {
background-color: black;
background-repeat: repeat;
}
.headline {
display: block;
margin: 10px 0 25px 0;
border-bottom: 1px dotted #e4e9f0;
color: white;
font-size: 20px;
}
.headline p {
margin: 0 0 -2px 0;
padding-bottom: 5px;
display: inline-block;
border-bottom: 2px solid #7e57c2;
}
.link-list > li{
padding: 7px 0px;
}
.link-list > li > a , .link-list > li> i{
color:#eee;
font-size: 16px;
}
"""
'Flip card on hover':
'prefix': 'flip-card'
'body': """
.flip-card {
background-color: transparent;
width: 200px;
height: 200px;
perspective: 1000px;
}
.flip-card-inner {
position: relative;
width: 100%;
height: 100%;
text-align: center;
transition: transform 0.6s;
transform-style: preserve-3d;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
}
.flip-card:hover .flip-card-inner {
transform: rotateY(180deg);
}
.flip-card-front, .flip-card-back {
position: absolute;
width: 100%;
height: 100%;
backface-visibility: hidden;
}
.flip-card-front {
background-color: #bbb;
color: black;
z-index: 2;
}
.flip-card-back {
background-color: #2980b9;
color: white;
transform: rotateY(180deg);
z-index: 1;
}
"""
'sticky sidebar collapse to icons with responsive':
'prefix': 'sidebar-icons'
'body': """
#wrapper {
padding-left: 0;
-webkit-transition: all 0.6s ease;
-moz-transition: all 0.6s ease;
-o-transition: all 0.6s ease;
transition: all 0.6s ease;
}
#wrapper.toggled {
padding-left: 200px;
}
#sidebar-wrapper {
z-index: 1000;
position: fixed;
left: 250px;
width: 0;
height: 100%;
margin-left: -250px;
overflow-y: auto;
background-color:#312A25 !Important;
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
transition: all 0.5s ease;
}
#wrapper.toggled #sidebar-wrapper {
width: 0;
}
#page-content-wrapper {
width: 100%;
position: absolute;
padding: 10px;
}
#wrapper.toggled #page-content-wrapper {
position: absolute;
margin-left:-250px;
}
.sidebar-nav {
position: absolute;
top: 0;
right:15px;
width: 200px;
margin: 0;
padding: 0;
list-style: none;
}
.sidebar-nav li {
text-indent: 20px;
line-height: 40px;
}
.sidebar-nav li a {
display: block;
text-decoration: none;
color: #999999;
}
.sidebar-nav li a:hover {
text-decoration: none;
color: #fff;
background: #312A25;
}
.sidebar-nav li a:active,
.sidebar-nav li a:focus {
text-decoration: none;
}
.sidebar-nav > .sidebar-brand {
height: 60px;
font-size: 18px;
}
.sidebar-nav > .sidebar-brand a {
color: #999999;
}
.sidebar-nav > .sidebar-brand a:hover {
color: #fff;
background: none;
}
@media(min-width:768px) {
#wrapper {
padding-left: 220px;
}
#wrapper.toggled {
padding-left: 0;
}
#sidebar-wrapper {
width: 200px;
}
#wrapper.toggled #sidebar-wrapper {
width: 40px;
}
#wrapper.toggled span {
visibility:hidden;
}
#wrapper.toggled i {
float:right;
}
#page-content-wrapper {
padding: 20px;
position: relative;
}
#wrapper.toggled #page-content-wrapper {
position: relative;
margin-right: 0;
}
}
@media(max-width:414px) {
#wrapper.toggled #page-content-wrapper {
position: absolute;
margin-right:60px;
}
#wrapper.toggled {
padding-right: 60px;
}
#wrapper {
padding-left: 20px;
}
#wrapper.toggled {
padding-left: 0;
}
#sidebar-wrapper {
width: 50px;
}
#wrapper.toggled #sidebar-wrapper {
width: 140px;
}
#wrapper.toggled span {
visibility:visible;
position:relative;
left:70px;
bottom:13px;
}
#wrapper span {
visibility:hidden;
}
#wrapper.toggled i {
float:right;
}
#wrapper i {
float:right;
}
#page-content-wrapper {
padding: 5px;
position: relative;
}
#wrapper.toggled #page-content-wrapper {
position: relative;
margin-right: 0;
}
}
"""
|
[
{
"context": "assword'\n username: document.getElementById('username').value.trim(),\n password: document.getEleme",
"end": 3267,
"score": 0.998362123966217,
"start": 3259,
"tag": "USERNAME",
"value": "username"
},
{
"context": ".trim(),\n password: document.getElementById('password').value,\n scope: 'public read_citizen_info c",
"end": 3333,
"score": 0.8159562349319458,
"start": 3325,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "rd_confirmation: document.getElementById('registerPassword').value,\n subscribe_to_newsletter: if subs",
"end": 5234,
"score": 0.5139479637145996,
"start": 5226,
"tag": "PASSWORD",
"value": "Password"
}
] | src/auth.coffee | Schine/StarMade-Launcher | 7 | 'use strict'
REGISTRY_TOKEN_URL = 'https://registry.star-made.org/oauth/token'
REGISTRY_REGISTER_URL = 'https://registry.star-made.org/api/v1/users.json'
electron = require('electron')
request = require('request')
ipc = electron.ipcRenderer
remote = electron.remote
util = require('./util')
log = require('./log-helpers')
close = document.getElementById 'close'
uplinkLink = document.getElementById 'uplinkLink'
guestLink = document.getElementById 'guestLink'
uplinkForm = document.getElementById 'uplink'
uplinkSubmit = document.getElementById 'uplinkSubmit'
status = document.getElementById 'status'
statusGuest = document.getElementById 'statusGuest'
rememberMe = false
rememberMeLabel = document.getElementById 'rememberMeLabel'
rememberMeBox = document.getElementById 'rememberMe'
registerLink = document.getElementById 'registerLink'
guestForm = document.getElementById 'guest'
registerForm = document.getElementById 'register'
registerBack = document.getElementById 'registerBack'
registerSubmit = document.getElementById 'registerSubmit'
registerSubmitBg = document.getElementById 'registerSubmitBg'
registerStatus = document.getElementById 'registerStatus'
subscribe = true
subscribeLabel = document.getElementById 'subscribeLabel'
subscribeBox = document.getElementById 'subscribe'
licensesLink = document.getElementById 'licensesLink'
originalWidth = window.innerWidth
originalHeight = window.innerHeight
util.setupExternalLinks()
close.addEventListener 'click', ->
remote.app.quit()
if localStorage.getItem('playerName')?
# Set username and player name to last used player name
playerName = localStorage.getItem 'playerName'
document.getElementById('username').value = playerName
document.getElementById('playerName').value = playerName
showGuest = ->
uplinkForm.style.display = 'none'
guestForm.style.display = 'block'
showRegister = ->
close.style.display = 'none'
uplinkForm.style.display = 'none'
guestForm.style.display = 'none'
registerForm.style.display = 'block'
# TODO: May need to account the height offset used in OS X
remote.getCurrentWindow().setSize(window.innerWidth, 508)
remote.getCurrentWindow().center()
exitRegister = ->
close.style.display = 'inline'
uplinkForm.style.display = 'block'
guestForm.style.display = 'none'
registerForm.style.display = 'none'
remote.getCurrentWindow().setSize(originalWidth, originalHeight)
remote.getCurrentWindow().center()
switch localStorage.getItem('authGoto')
when 'guest'
showGuest()
when 'register'
showRegister()
localStorage.removeItem('authGoto')
rememberMe = util.parseBoolean localStorage.getItem 'rememberMe'
rememberMeBox.innerHTML = '✓' if rememberMe
uplinkLink.addEventListener 'click', (event) ->
event.preventDefault()
uplinkForm.style.display = 'block'
guestForm.style.display = 'none'
guestLink.addEventListener 'click', (event) ->
event.preventDefault()
showGuest()
doLogin = (event) ->
event.preventDefault()
unless navigator.onLine
status.innerHTML = 'You are not connected to the Internet.'
return
status.innerHTML = 'Logging in...'
request.post REGISTRY_TOKEN_URL,
form:
grant_type: 'password'
username: document.getElementById('username').value.trim(),
password: document.getElementById('password').value,
scope: 'public read_citizen_info client'
(err, res, body) ->
body = JSON.parse body
if !err && res.statusCode == 200
log.entry "Logged in as #{document.getElementById('username').value.trim()}"
ipc.send 'finish-auth', body
else if res.statusCode == 401
log.entry "Invalid login credentials"
status.innerHTML = 'Invalid credentials.'
else
log.entry "Unable to log in (#{res.statusCode})"
status.innerHTML = 'Unable to login, please try later.'
uplinkForm.addEventListener 'submit', doLogin
uplinkSubmit.addEventListener 'click', doLogin
toggleRememberMe = ->
rememberMe = !rememberMe
localStorage.setItem 'rememberMe', rememberMe
if rememberMe
rememberMeBox.innerHTML = '✓'
else
rememberMeBox.innerHTML = ' '
rememberMeLabel.addEventListener 'click', toggleRememberMe
rememberMeBox.addEventListener 'click', toggleRememberMe
registerLink.addEventListener 'click', showRegister
doGuest = (event) ->
event.preventDefault()
playerName = document.getElementById('playerName').value.trim()
unless !!playerName && playerName.length >= 3
statusGuest.innerHTML = "Invalid username"
return
log.entry "Guest login: #{playerName}"
ipc.send 'finish-auth',
playerName: playerName
guestForm.addEventListener 'submit', doGuest
guestSubmit.addEventListener 'click', doGuest
doRegister = (event) ->
event.preventDefault()
registerStatus.innerHTML = 'Registering...'
username = document.getElementById('registerUsername').value
request.post REGISTRY_REGISTER_URL,
form:
user:
username: document.getElementById('registerUsername').value,
email: document.getElementById('registerEmail').value,
password: document.getElementById('registerPassword').value,
password_confirmation: document.getElementById('registerPassword').value,
subscribe_to_newsletter: if subscribe then '1' else '0'
(err, res, body) ->
body = JSON.parse body
if !err && (res.statusCode == 200 || res.statusCode == 201)
registerStatus.innerHTML = ''
log.entry "Registered new account"
status.innerHTML = 'Registered! Please confirm your email.'
document.getElementById('username').value = username
exitRegister()
else if res.statusCode == 422
field = Object.keys(body.errors)[0]
error = body.errors[field][0]
field = field.substring(0, 1).toUpperCase() + field.substring(1, field.length)
log.error "Error registering account"
log.indent.entry "#{field} #{error}"
registerStatus.innerHTML = "#{field} #{error}"
else
log.warning "Unable to register account (#{res.statusCode})"
registerStatus.innerHTML = 'Unable to register, please try later.'
registerForm.addEventListener 'submit', doRegister
registerSubmit.addEventListener 'click', doRegister
registerBack.addEventListener 'click', (event) ->
event.preventDefault()
exitRegister()
registerSubmit.addEventListener 'mouseenter', ->
registerSubmitBg.className = 'hover'
registerSubmit.addEventListener 'mouseleave', ->
registerSubmitBg.className = ''
toggleSubscribe = ->
subscribe = !subscribe
if subscribe
subscribeBox.innerHTML = '✓'
else
subscribeBox.innerHTML = ' '
subscribeLabel.addEventListener 'click', toggleSubscribe
subscribeBox.addEventListener 'click', toggleSubscribe
licensesLink.addEventListener 'click', (event) ->
event.preventDefault()
ipc.send 'open-licenses'
| 198453 | 'use strict'
REGISTRY_TOKEN_URL = 'https://registry.star-made.org/oauth/token'
REGISTRY_REGISTER_URL = 'https://registry.star-made.org/api/v1/users.json'
electron = require('electron')
request = require('request')
ipc = electron.ipcRenderer
remote = electron.remote
util = require('./util')
log = require('./log-helpers')
close = document.getElementById 'close'
uplinkLink = document.getElementById 'uplinkLink'
guestLink = document.getElementById 'guestLink'
uplinkForm = document.getElementById 'uplink'
uplinkSubmit = document.getElementById 'uplinkSubmit'
status = document.getElementById 'status'
statusGuest = document.getElementById 'statusGuest'
rememberMe = false
rememberMeLabel = document.getElementById 'rememberMeLabel'
rememberMeBox = document.getElementById 'rememberMe'
registerLink = document.getElementById 'registerLink'
guestForm = document.getElementById 'guest'
registerForm = document.getElementById 'register'
registerBack = document.getElementById 'registerBack'
registerSubmit = document.getElementById 'registerSubmit'
registerSubmitBg = document.getElementById 'registerSubmitBg'
registerStatus = document.getElementById 'registerStatus'
subscribe = true
subscribeLabel = document.getElementById 'subscribeLabel'
subscribeBox = document.getElementById 'subscribe'
licensesLink = document.getElementById 'licensesLink'
originalWidth = window.innerWidth
originalHeight = window.innerHeight
util.setupExternalLinks()
close.addEventListener 'click', ->
remote.app.quit()
if localStorage.getItem('playerName')?
# Set username and player name to last used player name
playerName = localStorage.getItem 'playerName'
document.getElementById('username').value = playerName
document.getElementById('playerName').value = playerName
showGuest = ->
uplinkForm.style.display = 'none'
guestForm.style.display = 'block'
showRegister = ->
close.style.display = 'none'
uplinkForm.style.display = 'none'
guestForm.style.display = 'none'
registerForm.style.display = 'block'
# TODO: May need to account the height offset used in OS X
remote.getCurrentWindow().setSize(window.innerWidth, 508)
remote.getCurrentWindow().center()
exitRegister = ->
close.style.display = 'inline'
uplinkForm.style.display = 'block'
guestForm.style.display = 'none'
registerForm.style.display = 'none'
remote.getCurrentWindow().setSize(originalWidth, originalHeight)
remote.getCurrentWindow().center()
switch localStorage.getItem('authGoto')
when 'guest'
showGuest()
when 'register'
showRegister()
localStorage.removeItem('authGoto')
rememberMe = util.parseBoolean localStorage.getItem 'rememberMe'
rememberMeBox.innerHTML = '✓' if rememberMe
uplinkLink.addEventListener 'click', (event) ->
event.preventDefault()
uplinkForm.style.display = 'block'
guestForm.style.display = 'none'
guestLink.addEventListener 'click', (event) ->
event.preventDefault()
showGuest()
doLogin = (event) ->
event.preventDefault()
unless navigator.onLine
status.innerHTML = 'You are not connected to the Internet.'
return
status.innerHTML = 'Logging in...'
request.post REGISTRY_TOKEN_URL,
form:
grant_type: 'password'
username: document.getElementById('username').value.trim(),
password: document.getElementById('<PASSWORD>').value,
scope: 'public read_citizen_info client'
(err, res, body) ->
body = JSON.parse body
if !err && res.statusCode == 200
log.entry "Logged in as #{document.getElementById('username').value.trim()}"
ipc.send 'finish-auth', body
else if res.statusCode == 401
log.entry "Invalid login credentials"
status.innerHTML = 'Invalid credentials.'
else
log.entry "Unable to log in (#{res.statusCode})"
status.innerHTML = 'Unable to login, please try later.'
uplinkForm.addEventListener 'submit', doLogin
uplinkSubmit.addEventListener 'click', doLogin
toggleRememberMe = ->
rememberMe = !rememberMe
localStorage.setItem 'rememberMe', rememberMe
if rememberMe
rememberMeBox.innerHTML = '✓'
else
rememberMeBox.innerHTML = ' '
rememberMeLabel.addEventListener 'click', toggleRememberMe
rememberMeBox.addEventListener 'click', toggleRememberMe
registerLink.addEventListener 'click', showRegister
doGuest = (event) ->
event.preventDefault()
playerName = document.getElementById('playerName').value.trim()
unless !!playerName && playerName.length >= 3
statusGuest.innerHTML = "Invalid username"
return
log.entry "Guest login: #{playerName}"
ipc.send 'finish-auth',
playerName: playerName
guestForm.addEventListener 'submit', doGuest
guestSubmit.addEventListener 'click', doGuest
doRegister = (event) ->
event.preventDefault()
registerStatus.innerHTML = 'Registering...'
username = document.getElementById('registerUsername').value
request.post REGISTRY_REGISTER_URL,
form:
user:
username: document.getElementById('registerUsername').value,
email: document.getElementById('registerEmail').value,
password: document.getElementById('registerPassword').value,
password_confirmation: document.getElementById('register<PASSWORD>').value,
subscribe_to_newsletter: if subscribe then '1' else '0'
(err, res, body) ->
body = JSON.parse body
if !err && (res.statusCode == 200 || res.statusCode == 201)
registerStatus.innerHTML = ''
log.entry "Registered new account"
status.innerHTML = 'Registered! Please confirm your email.'
document.getElementById('username').value = username
exitRegister()
else if res.statusCode == 422
field = Object.keys(body.errors)[0]
error = body.errors[field][0]
field = field.substring(0, 1).toUpperCase() + field.substring(1, field.length)
log.error "Error registering account"
log.indent.entry "#{field} #{error}"
registerStatus.innerHTML = "#{field} #{error}"
else
log.warning "Unable to register account (#{res.statusCode})"
registerStatus.innerHTML = 'Unable to register, please try later.'
registerForm.addEventListener 'submit', doRegister
registerSubmit.addEventListener 'click', doRegister
registerBack.addEventListener 'click', (event) ->
event.preventDefault()
exitRegister()
registerSubmit.addEventListener 'mouseenter', ->
registerSubmitBg.className = 'hover'
registerSubmit.addEventListener 'mouseleave', ->
registerSubmitBg.className = ''
toggleSubscribe = ->
subscribe = !subscribe
if subscribe
subscribeBox.innerHTML = '✓'
else
subscribeBox.innerHTML = ' '
subscribeLabel.addEventListener 'click', toggleSubscribe
subscribeBox.addEventListener 'click', toggleSubscribe
licensesLink.addEventListener 'click', (event) ->
event.preventDefault()
ipc.send 'open-licenses'
| true | 'use strict'
REGISTRY_TOKEN_URL = 'https://registry.star-made.org/oauth/token'
REGISTRY_REGISTER_URL = 'https://registry.star-made.org/api/v1/users.json'
electron = require('electron')
request = require('request')
ipc = electron.ipcRenderer
remote = electron.remote
util = require('./util')
log = require('./log-helpers')
close = document.getElementById 'close'
uplinkLink = document.getElementById 'uplinkLink'
guestLink = document.getElementById 'guestLink'
uplinkForm = document.getElementById 'uplink'
uplinkSubmit = document.getElementById 'uplinkSubmit'
status = document.getElementById 'status'
statusGuest = document.getElementById 'statusGuest'
rememberMe = false
rememberMeLabel = document.getElementById 'rememberMeLabel'
rememberMeBox = document.getElementById 'rememberMe'
registerLink = document.getElementById 'registerLink'
guestForm = document.getElementById 'guest'
registerForm = document.getElementById 'register'
registerBack = document.getElementById 'registerBack'
registerSubmit = document.getElementById 'registerSubmit'
registerSubmitBg = document.getElementById 'registerSubmitBg'
registerStatus = document.getElementById 'registerStatus'
subscribe = true
subscribeLabel = document.getElementById 'subscribeLabel'
subscribeBox = document.getElementById 'subscribe'
licensesLink = document.getElementById 'licensesLink'
originalWidth = window.innerWidth
originalHeight = window.innerHeight
util.setupExternalLinks()
close.addEventListener 'click', ->
remote.app.quit()
if localStorage.getItem('playerName')?
# Set username and player name to last used player name
playerName = localStorage.getItem 'playerName'
document.getElementById('username').value = playerName
document.getElementById('playerName').value = playerName
showGuest = ->
uplinkForm.style.display = 'none'
guestForm.style.display = 'block'
showRegister = ->
close.style.display = 'none'
uplinkForm.style.display = 'none'
guestForm.style.display = 'none'
registerForm.style.display = 'block'
# TODO: May need to account the height offset used in OS X
remote.getCurrentWindow().setSize(window.innerWidth, 508)
remote.getCurrentWindow().center()
exitRegister = ->
close.style.display = 'inline'
uplinkForm.style.display = 'block'
guestForm.style.display = 'none'
registerForm.style.display = 'none'
remote.getCurrentWindow().setSize(originalWidth, originalHeight)
remote.getCurrentWindow().center()
switch localStorage.getItem('authGoto')
when 'guest'
showGuest()
when 'register'
showRegister()
localStorage.removeItem('authGoto')
rememberMe = util.parseBoolean localStorage.getItem 'rememberMe'
rememberMeBox.innerHTML = '✓' if rememberMe
uplinkLink.addEventListener 'click', (event) ->
event.preventDefault()
uplinkForm.style.display = 'block'
guestForm.style.display = 'none'
guestLink.addEventListener 'click', (event) ->
event.preventDefault()
showGuest()
doLogin = (event) ->
event.preventDefault()
unless navigator.onLine
status.innerHTML = 'You are not connected to the Internet.'
return
status.innerHTML = 'Logging in...'
request.post REGISTRY_TOKEN_URL,
form:
grant_type: 'password'
username: document.getElementById('username').value.trim(),
password: document.getElementById('PI:PASSWORD:<PASSWORD>END_PI').value,
scope: 'public read_citizen_info client'
(err, res, body) ->
body = JSON.parse body
if !err && res.statusCode == 200
log.entry "Logged in as #{document.getElementById('username').value.trim()}"
ipc.send 'finish-auth', body
else if res.statusCode == 401
log.entry "Invalid login credentials"
status.innerHTML = 'Invalid credentials.'
else
log.entry "Unable to log in (#{res.statusCode})"
status.innerHTML = 'Unable to login, please try later.'
uplinkForm.addEventListener 'submit', doLogin
uplinkSubmit.addEventListener 'click', doLogin
toggleRememberMe = ->
rememberMe = !rememberMe
localStorage.setItem 'rememberMe', rememberMe
if rememberMe
rememberMeBox.innerHTML = '✓'
else
rememberMeBox.innerHTML = ' '
rememberMeLabel.addEventListener 'click', toggleRememberMe
rememberMeBox.addEventListener 'click', toggleRememberMe
registerLink.addEventListener 'click', showRegister
doGuest = (event) ->
event.preventDefault()
playerName = document.getElementById('playerName').value.trim()
unless !!playerName && playerName.length >= 3
statusGuest.innerHTML = "Invalid username"
return
log.entry "Guest login: #{playerName}"
ipc.send 'finish-auth',
playerName: playerName
guestForm.addEventListener 'submit', doGuest
guestSubmit.addEventListener 'click', doGuest
doRegister = (event) ->
event.preventDefault()
registerStatus.innerHTML = 'Registering...'
username = document.getElementById('registerUsername').value
request.post REGISTRY_REGISTER_URL,
form:
user:
username: document.getElementById('registerUsername').value,
email: document.getElementById('registerEmail').value,
password: document.getElementById('registerPassword').value,
password_confirmation: document.getElementById('registerPI:PASSWORD:<PASSWORD>END_PI').value,
subscribe_to_newsletter: if subscribe then '1' else '0'
(err, res, body) ->
body = JSON.parse body
if !err && (res.statusCode == 200 || res.statusCode == 201)
registerStatus.innerHTML = ''
log.entry "Registered new account"
status.innerHTML = 'Registered! Please confirm your email.'
document.getElementById('username').value = username
exitRegister()
else if res.statusCode == 422
field = Object.keys(body.errors)[0]
error = body.errors[field][0]
field = field.substring(0, 1).toUpperCase() + field.substring(1, field.length)
log.error "Error registering account"
log.indent.entry "#{field} #{error}"
registerStatus.innerHTML = "#{field} #{error}"
else
log.warning "Unable to register account (#{res.statusCode})"
registerStatus.innerHTML = 'Unable to register, please try later.'
registerForm.addEventListener 'submit', doRegister
registerSubmit.addEventListener 'click', doRegister
registerBack.addEventListener 'click', (event) ->
event.preventDefault()
exitRegister()
registerSubmit.addEventListener 'mouseenter', ->
registerSubmitBg.className = 'hover'
registerSubmit.addEventListener 'mouseleave', ->
registerSubmitBg.className = ''
toggleSubscribe = ->
subscribe = !subscribe
if subscribe
subscribeBox.innerHTML = '✓'
else
subscribeBox.innerHTML = ' '
subscribeLabel.addEventListener 'click', toggleSubscribe
subscribeBox.addEventListener 'click', toggleSubscribe
licensesLink.addEventListener 'click', (event) ->
event.preventDefault()
ipc.send 'open-licenses'
|
[
{
"context": "tics'\nanalytics = new GoogleAnalytics\n account: 'UA-1224199-59'\n domain: 'floatingforests.org'\n\n$(\".readymade-c",
"end": 1683,
"score": 0.9992968440055847,
"start": 1670,
"tag": "KEY",
"value": "UA-1224199-59"
}
] | overrides.coffee | zooniverse/floatingforests | 1 | translate = require "t7e"
enUs = require './translations/en-us'
translate.load enUs
LanguageManager = require 'zooniverse/lib/language-manager'
languageManager = new LanguageManager
translations:
en: label: 'English', strings: enUs
es: label: 'Español', strings: './translations/es.json'
pl: label: 'Polski', strings: './translations/pl.json'
'zh-tw': label: '繁體中文', strings: './translations/zh-tw.json'
languageManager.on 'change-language', (e, code, strings) ->
translate.load strings
translate.refresh()
Footer = require 'zooniverse/controllers/footer'
MainNav = require './pages/main-nav'
SecondarySubNav = require './pages/sub-nav'
HomeStats = require './pages/home-stats'
project = require "zooniverse-readymade/current-project"
ProfileOverrides = require "./zooniverse/profile"
AboutNav = new SecondarySubNav "about"
EducationNav = new SecondarySubNav "education"
TeamNav = new SecondarySubNav "team"
MainNav.addNavLinks()
MainNav.translateReadymadeLinks('classify', 'profile', 'about', 'education', 'team')
footer = new Footer
project.header.el.append("<meta name='viewport' content='width=600, user-scalable=no'>
<link rel='shortcut icon' href='favicon.ico' type='image/x-icon'>")
footer.el.appendTo $("<div id='footer-container'></div>").insertAfter(".stack-of-pages")
creditElement = document.createElement 'div'
creditElement.className = 'image-credit'
creditElement.innerHTML = translate 'span', 'site.backgroundImageCredit'
$('#footer-container').append creditElement
ProfileOverrides.init()
GoogleAnalytics = require 'zooniverse/lib/google-analytics'
analytics = new GoogleAnalytics
account: 'UA-1224199-59'
domain: 'floatingforests.org'
$(".readymade-call-to-action").html translate 'site.callToAction'
ClassifyEvents = require "./classify/events"
HomeStats.init()
| 139345 | translate = require "t7e"
enUs = require './translations/en-us'
translate.load enUs
LanguageManager = require 'zooniverse/lib/language-manager'
languageManager = new LanguageManager
translations:
en: label: 'English', strings: enUs
es: label: 'Español', strings: './translations/es.json'
pl: label: 'Polski', strings: './translations/pl.json'
'zh-tw': label: '繁體中文', strings: './translations/zh-tw.json'
languageManager.on 'change-language', (e, code, strings) ->
translate.load strings
translate.refresh()
Footer = require 'zooniverse/controllers/footer'
MainNav = require './pages/main-nav'
SecondarySubNav = require './pages/sub-nav'
HomeStats = require './pages/home-stats'
project = require "zooniverse-readymade/current-project"
ProfileOverrides = require "./zooniverse/profile"
AboutNav = new SecondarySubNav "about"
EducationNav = new SecondarySubNav "education"
TeamNav = new SecondarySubNav "team"
MainNav.addNavLinks()
MainNav.translateReadymadeLinks('classify', 'profile', 'about', 'education', 'team')
footer = new Footer
project.header.el.append("<meta name='viewport' content='width=600, user-scalable=no'>
<link rel='shortcut icon' href='favicon.ico' type='image/x-icon'>")
footer.el.appendTo $("<div id='footer-container'></div>").insertAfter(".stack-of-pages")
creditElement = document.createElement 'div'
creditElement.className = 'image-credit'
creditElement.innerHTML = translate 'span', 'site.backgroundImageCredit'
$('#footer-container').append creditElement
ProfileOverrides.init()
GoogleAnalytics = require 'zooniverse/lib/google-analytics'
analytics = new GoogleAnalytics
account: '<KEY>'
domain: 'floatingforests.org'
$(".readymade-call-to-action").html translate 'site.callToAction'
ClassifyEvents = require "./classify/events"
HomeStats.init()
| true | translate = require "t7e"
enUs = require './translations/en-us'
translate.load enUs
LanguageManager = require 'zooniverse/lib/language-manager'
languageManager = new LanguageManager
translations:
en: label: 'English', strings: enUs
es: label: 'Español', strings: './translations/es.json'
pl: label: 'Polski', strings: './translations/pl.json'
'zh-tw': label: '繁體中文', strings: './translations/zh-tw.json'
languageManager.on 'change-language', (e, code, strings) ->
translate.load strings
translate.refresh()
Footer = require 'zooniverse/controllers/footer'
MainNav = require './pages/main-nav'
SecondarySubNav = require './pages/sub-nav'
HomeStats = require './pages/home-stats'
project = require "zooniverse-readymade/current-project"
ProfileOverrides = require "./zooniverse/profile"
AboutNav = new SecondarySubNav "about"
EducationNav = new SecondarySubNav "education"
TeamNav = new SecondarySubNav "team"
MainNav.addNavLinks()
MainNav.translateReadymadeLinks('classify', 'profile', 'about', 'education', 'team')
footer = new Footer
project.header.el.append("<meta name='viewport' content='width=600, user-scalable=no'>
<link rel='shortcut icon' href='favicon.ico' type='image/x-icon'>")
footer.el.appendTo $("<div id='footer-container'></div>").insertAfter(".stack-of-pages")
creditElement = document.createElement 'div'
creditElement.className = 'image-credit'
creditElement.innerHTML = translate 'span', 'site.backgroundImageCredit'
$('#footer-container').append creditElement
ProfileOverrides.init()
GoogleAnalytics = require 'zooniverse/lib/google-analytics'
analytics = new GoogleAnalytics
account: 'PI:KEY:<KEY>END_PI'
domain: 'floatingforests.org'
$(".readymade-call-to-action").html translate 'site.callToAction'
ClassifyEvents = require "./classify/events"
HomeStats.init()
|
[
{
"context": "date gameid, {$push: players: {id: playerid, name: name, score: 0}}\n removePlayer: ({playerid, gameid}",
"end": 454,
"score": 0.8318675756454468,
"start": 450,
"tag": "NAME",
"value": "name"
}
] | komodo/play.coffee | KamikazeKumquatsLLC/komodo | 1 | Router.route "/play/:shortid", ->
@wait Meteor.subscribe "quizPlay", @params.shortid
if @ready()
@layout ""
Session.set "gameid", LiveGames.findOne(shortid: @params.shortid)._id
@render "play", data: -> LiveGames.findOne shortid: @params.shortid
else
@render "loading"
Meteor.methods
addPlayer: ({playerid, gameid, name}) ->
LiveGames.update gameid, {$push: players: {id: playerid, name: name, score: 0}}
removePlayer: ({playerid, gameid}) ->
LiveGames.update gameid, {$pull: {players: id: playerid}}
getPlayer: ({playerid, gameid}) ->
_.findWhere LiveGames.findOne(gameid).players, id: playerid
answer: ({playerid, gameid, answer}) ->
game = LiveGames.findOne(gameid)
{allowLateAnswers, revealed, timer, players, quiz, question} = game
if revealed and not allowLateAnswers
throw new Meteor.Error("too-late", "Tried to answer a question that was already revealed!")
modifier = $push: {}, $set: {}
modifier.$push["answers.#{question}"] = {id: playerid, answer: answer}
unless @isSimulation
quiz = Quizzes.findOne(quiz)
question = quiz.questions[question]
if _.isNumber(question.correctAnswer)
if question.correctAnswer is answer
i = (i for val, i in players when val.id is playerid)[0]
value = if _.isNumber(question.value) then question.value else 1000
timeScale = 1
if _.isNumber(question.time)
timeScale = timer / question.time
modifier.$set["players.#{i}.tmpscore"] = Math.floor(value * timeScale)
LiveGames.update gameid, modifier
unanswer: ({playerid, gameid}) ->
game = LiveGames.findOne(gameid)
{allowLateAnswers, revealed, question, players} = game
if revealed and not allowLateAnswers
throw new Meteor.Error("too-late", "Tried to un-answer a question that was already revealed!")
modifier = $pull: {}, $set: {}
modifier.$pull["answers.#{question}"] = {id: playerid}
unless @isSimulation
i = (i for val, i in players when val.id is playerid)[0]
modifier.$set["players.#{i}.tmpscore"] = 0
LiveGames.update gameid, modifier
getAnswer: ({playerid, gameid, question}) ->
game = LiveGames.findOne(gameid)
question = game.question unless _.isNumber question
list = game.answers?[question]
criterion = ({id}) -> playerid is id
filtered = _.filter(list, criterion)
filtered[0]
getAnswers: ({playerid, gameid}) ->
list = LiveGames.findOne(gameid).answers
_.map(list, (list) -> _.findWhere(list, id: playerid)?.answer)
if Meteor.isClient
getGame = -> LiveGames.findOne Session.get "gameid"
getQuiz = -> {questions: getGame().questionData}
makeProxy = (attr) -> ->
if Template.currentData()[attr]?
Template.currentData()[attr]
else
Quizzes.findOne(Template.currentData().quiz)[attr]
updateMyInfo = ->
Meteor.call "getPlayer",
playerid: Session.get("playerid")
gameid: Session.get("gameid")
, (error, me) ->
if error?
console.log error
Session.set "playername", me?.name
Session.set "score", me?.score
Meteor.call "getAnswer",
playerid: Session.get("playerid")
gameid: Session.get("gameid")
, (error, answer) ->
if error?
console.log error
Session.set "answer", answer
Template.play.rendered = ->
Meteor.setInterval updateMyInfo, 1000
Template.registerHelper "playername", -> Session.get("playername")
Template.fancycountdown.rendered = ->
Session.set "answer"
Template.play.helpers
currentQuestion: -> getQuiz().questions[getGame().question]
answered: -> _.isObject Session.get "answer"
didntAnswer: -> not getGame().allowLateAnswers and getGame().revealed
Template.enterplayername.helpers
name: makeProxy "name"
oldnames: -> JSON.parse localStorage.getItem "oldnames"
Template.enterplayername.events
'click #generate': (evt) ->
index = Math.floor(Math.random() * SAMPLE_NAMES.length)
$("#playername").val(SAMPLE_NAMES[index])
"keyup #playername": (evt) ->
if evt.keyCode is 13
$("#accept").click()
'click #accept': (evt) ->
localStorage.setItem "oldnames", JSON.stringify _.compact _.union [$("#playername").val()], JSON.parse localStorage.getItem "oldnames"
Session.setDefault("playerid", Math.random())
Session.set("playername", $("#playername").val())
Meteor.call "removePlayer",
gameid: Session.get("gameid")
playerid: Session.get("playerid")
Meteor.apply "addPlayer", [
gameid: Session.get("gameid")
playerid: Session.get("playerid")
name: $("#playername").val()
], {wait: yes}
window.addEventListener "beforeunload", ->
Meteor.call "removePlayer",
gameid: Session.get("gameid")
playerid: Session.get("playerid")
Session.set "playername"
'click .oldname': (evt) ->
$("#playername").val(evt.currentTarget.innerText)
Template.play.events
'click #reset': (evt) ->
Session.set "playername"
Meteor.call "removePlayer",
gameid: Session.get("gameid")
playerid: Session.get("playerid")
Template.reviewAnswer.helpers
canUnanswer: ->
{allowLateAnswers, revealed} = getGame()
allowLateAnswers or not revealed
Template.reviewAnswer.events
"click #unanswer": (evt) ->
Session.set "answer"
Meteor.call "unanswer",
playerid: Session.get("playerid")
gameid: Session.get "gameid"
Template.question.helpers
timer: -> getGame().timer
Template.question.events
"click .answer": (evt) ->
selectedAnswer = evt.currentTarget.dataset.original
answerList = Template.currentData().answers
answer = answerList.indexOf(selectedAnswer)
Meteor.call "answer",
playerid: Session.get("playerid")
gameid: Session.get("gameid")
answer: answer
Session.set "answer", answer
no
updateCorrect = ->
correctAnswers = _(getQuiz().questions).pluck("correctAnswer")
Meteor.call "getAnswers",
playerid: Session.get("playerid")
gameid: Session.get("gameid")
, (error, myAnswers) ->
correctAndMyAnswers = _.zip(correctAnswers, myAnswers)
wasCorrect = ([correct, mine]) -> mine? and correct? and correct is mine
correctAnswersIHad = _.filter(correctAndMyAnswers, wasCorrect)
Session.set "correct", correctAnswersIHad.length
getTotal = -> _(getQuiz().questions).chain().pluck("correctAnswer").filter(_.isNumber).value().length
Template.results.rendered = ->
updateCorrect()
updateMyInfo()
Template.results.helpers
correct: -> Session.get "correct"
total: getTotal
pct: -> Math.round(10000*Session.get("correct")/getTotal())/100
score: -> Session.get "score"
| 137045 | Router.route "/play/:shortid", ->
@wait Meteor.subscribe "quizPlay", @params.shortid
if @ready()
@layout ""
Session.set "gameid", LiveGames.findOne(shortid: @params.shortid)._id
@render "play", data: -> LiveGames.findOne shortid: @params.shortid
else
@render "loading"
Meteor.methods
addPlayer: ({playerid, gameid, name}) ->
LiveGames.update gameid, {$push: players: {id: playerid, name: <NAME>, score: 0}}
removePlayer: ({playerid, gameid}) ->
LiveGames.update gameid, {$pull: {players: id: playerid}}
getPlayer: ({playerid, gameid}) ->
_.findWhere LiveGames.findOne(gameid).players, id: playerid
answer: ({playerid, gameid, answer}) ->
game = LiveGames.findOne(gameid)
{allowLateAnswers, revealed, timer, players, quiz, question} = game
if revealed and not allowLateAnswers
throw new Meteor.Error("too-late", "Tried to answer a question that was already revealed!")
modifier = $push: {}, $set: {}
modifier.$push["answers.#{question}"] = {id: playerid, answer: answer}
unless @isSimulation
quiz = Quizzes.findOne(quiz)
question = quiz.questions[question]
if _.isNumber(question.correctAnswer)
if question.correctAnswer is answer
i = (i for val, i in players when val.id is playerid)[0]
value = if _.isNumber(question.value) then question.value else 1000
timeScale = 1
if _.isNumber(question.time)
timeScale = timer / question.time
modifier.$set["players.#{i}.tmpscore"] = Math.floor(value * timeScale)
LiveGames.update gameid, modifier
unanswer: ({playerid, gameid}) ->
game = LiveGames.findOne(gameid)
{allowLateAnswers, revealed, question, players} = game
if revealed and not allowLateAnswers
throw new Meteor.Error("too-late", "Tried to un-answer a question that was already revealed!")
modifier = $pull: {}, $set: {}
modifier.$pull["answers.#{question}"] = {id: playerid}
unless @isSimulation
i = (i for val, i in players when val.id is playerid)[0]
modifier.$set["players.#{i}.tmpscore"] = 0
LiveGames.update gameid, modifier
getAnswer: ({playerid, gameid, question}) ->
game = LiveGames.findOne(gameid)
question = game.question unless _.isNumber question
list = game.answers?[question]
criterion = ({id}) -> playerid is id
filtered = _.filter(list, criterion)
filtered[0]
getAnswers: ({playerid, gameid}) ->
list = LiveGames.findOne(gameid).answers
_.map(list, (list) -> _.findWhere(list, id: playerid)?.answer)
if Meteor.isClient
getGame = -> LiveGames.findOne Session.get "gameid"
getQuiz = -> {questions: getGame().questionData}
makeProxy = (attr) -> ->
if Template.currentData()[attr]?
Template.currentData()[attr]
else
Quizzes.findOne(Template.currentData().quiz)[attr]
updateMyInfo = ->
Meteor.call "getPlayer",
playerid: Session.get("playerid")
gameid: Session.get("gameid")
, (error, me) ->
if error?
console.log error
Session.set "playername", me?.name
Session.set "score", me?.score
Meteor.call "getAnswer",
playerid: Session.get("playerid")
gameid: Session.get("gameid")
, (error, answer) ->
if error?
console.log error
Session.set "answer", answer
Template.play.rendered = ->
Meteor.setInterval updateMyInfo, 1000
Template.registerHelper "playername", -> Session.get("playername")
Template.fancycountdown.rendered = ->
Session.set "answer"
Template.play.helpers
currentQuestion: -> getQuiz().questions[getGame().question]
answered: -> _.isObject Session.get "answer"
didntAnswer: -> not getGame().allowLateAnswers and getGame().revealed
Template.enterplayername.helpers
name: makeProxy "name"
oldnames: -> JSON.parse localStorage.getItem "oldnames"
Template.enterplayername.events
'click #generate': (evt) ->
index = Math.floor(Math.random() * SAMPLE_NAMES.length)
$("#playername").val(SAMPLE_NAMES[index])
"keyup #playername": (evt) ->
if evt.keyCode is 13
$("#accept").click()
'click #accept': (evt) ->
localStorage.setItem "oldnames", JSON.stringify _.compact _.union [$("#playername").val()], JSON.parse localStorage.getItem "oldnames"
Session.setDefault("playerid", Math.random())
Session.set("playername", $("#playername").val())
Meteor.call "removePlayer",
gameid: Session.get("gameid")
playerid: Session.get("playerid")
Meteor.apply "addPlayer", [
gameid: Session.get("gameid")
playerid: Session.get("playerid")
name: $("#playername").val()
], {wait: yes}
window.addEventListener "beforeunload", ->
Meteor.call "removePlayer",
gameid: Session.get("gameid")
playerid: Session.get("playerid")
Session.set "playername"
'click .oldname': (evt) ->
$("#playername").val(evt.currentTarget.innerText)
Template.play.events
'click #reset': (evt) ->
Session.set "playername"
Meteor.call "removePlayer",
gameid: Session.get("gameid")
playerid: Session.get("playerid")
Template.reviewAnswer.helpers
canUnanswer: ->
{allowLateAnswers, revealed} = getGame()
allowLateAnswers or not revealed
Template.reviewAnswer.events
"click #unanswer": (evt) ->
Session.set "answer"
Meteor.call "unanswer",
playerid: Session.get("playerid")
gameid: Session.get "gameid"
Template.question.helpers
timer: -> getGame().timer
Template.question.events
"click .answer": (evt) ->
selectedAnswer = evt.currentTarget.dataset.original
answerList = Template.currentData().answers
answer = answerList.indexOf(selectedAnswer)
Meteor.call "answer",
playerid: Session.get("playerid")
gameid: Session.get("gameid")
answer: answer
Session.set "answer", answer
no
updateCorrect = ->
correctAnswers = _(getQuiz().questions).pluck("correctAnswer")
Meteor.call "getAnswers",
playerid: Session.get("playerid")
gameid: Session.get("gameid")
, (error, myAnswers) ->
correctAndMyAnswers = _.zip(correctAnswers, myAnswers)
wasCorrect = ([correct, mine]) -> mine? and correct? and correct is mine
correctAnswersIHad = _.filter(correctAndMyAnswers, wasCorrect)
Session.set "correct", correctAnswersIHad.length
getTotal = -> _(getQuiz().questions).chain().pluck("correctAnswer").filter(_.isNumber).value().length
Template.results.rendered = ->
updateCorrect()
updateMyInfo()
Template.results.helpers
correct: -> Session.get "correct"
total: getTotal
pct: -> Math.round(10000*Session.get("correct")/getTotal())/100
score: -> Session.get "score"
| true | Router.route "/play/:shortid", ->
@wait Meteor.subscribe "quizPlay", @params.shortid
if @ready()
@layout ""
Session.set "gameid", LiveGames.findOne(shortid: @params.shortid)._id
@render "play", data: -> LiveGames.findOne shortid: @params.shortid
else
@render "loading"
Meteor.methods
addPlayer: ({playerid, gameid, name}) ->
LiveGames.update gameid, {$push: players: {id: playerid, name: PI:NAME:<NAME>END_PI, score: 0}}
removePlayer: ({playerid, gameid}) ->
LiveGames.update gameid, {$pull: {players: id: playerid}}
getPlayer: ({playerid, gameid}) ->
_.findWhere LiveGames.findOne(gameid).players, id: playerid
answer: ({playerid, gameid, answer}) ->
game = LiveGames.findOne(gameid)
{allowLateAnswers, revealed, timer, players, quiz, question} = game
if revealed and not allowLateAnswers
throw new Meteor.Error("too-late", "Tried to answer a question that was already revealed!")
modifier = $push: {}, $set: {}
modifier.$push["answers.#{question}"] = {id: playerid, answer: answer}
unless @isSimulation
quiz = Quizzes.findOne(quiz)
question = quiz.questions[question]
if _.isNumber(question.correctAnswer)
if question.correctAnswer is answer
i = (i for val, i in players when val.id is playerid)[0]
value = if _.isNumber(question.value) then question.value else 1000
timeScale = 1
if _.isNumber(question.time)
timeScale = timer / question.time
modifier.$set["players.#{i}.tmpscore"] = Math.floor(value * timeScale)
LiveGames.update gameid, modifier
unanswer: ({playerid, gameid}) ->
game = LiveGames.findOne(gameid)
{allowLateAnswers, revealed, question, players} = game
if revealed and not allowLateAnswers
throw new Meteor.Error("too-late", "Tried to un-answer a question that was already revealed!")
modifier = $pull: {}, $set: {}
modifier.$pull["answers.#{question}"] = {id: playerid}
unless @isSimulation
i = (i for val, i in players when val.id is playerid)[0]
modifier.$set["players.#{i}.tmpscore"] = 0
LiveGames.update gameid, modifier
getAnswer: ({playerid, gameid, question}) ->
game = LiveGames.findOne(gameid)
question = game.question unless _.isNumber question
list = game.answers?[question]
criterion = ({id}) -> playerid is id
filtered = _.filter(list, criterion)
filtered[0]
getAnswers: ({playerid, gameid}) ->
list = LiveGames.findOne(gameid).answers
_.map(list, (list) -> _.findWhere(list, id: playerid)?.answer)
if Meteor.isClient
getGame = -> LiveGames.findOne Session.get "gameid"
getQuiz = -> {questions: getGame().questionData}
makeProxy = (attr) -> ->
if Template.currentData()[attr]?
Template.currentData()[attr]
else
Quizzes.findOne(Template.currentData().quiz)[attr]
updateMyInfo = ->
Meteor.call "getPlayer",
playerid: Session.get("playerid")
gameid: Session.get("gameid")
, (error, me) ->
if error?
console.log error
Session.set "playername", me?.name
Session.set "score", me?.score
Meteor.call "getAnswer",
playerid: Session.get("playerid")
gameid: Session.get("gameid")
, (error, answer) ->
if error?
console.log error
Session.set "answer", answer
Template.play.rendered = ->
Meteor.setInterval updateMyInfo, 1000
Template.registerHelper "playername", -> Session.get("playername")
Template.fancycountdown.rendered = ->
Session.set "answer"
Template.play.helpers
currentQuestion: -> getQuiz().questions[getGame().question]
answered: -> _.isObject Session.get "answer"
didntAnswer: -> not getGame().allowLateAnswers and getGame().revealed
Template.enterplayername.helpers
name: makeProxy "name"
oldnames: -> JSON.parse localStorage.getItem "oldnames"
Template.enterplayername.events
'click #generate': (evt) ->
index = Math.floor(Math.random() * SAMPLE_NAMES.length)
$("#playername").val(SAMPLE_NAMES[index])
"keyup #playername": (evt) ->
if evt.keyCode is 13
$("#accept").click()
'click #accept': (evt) ->
localStorage.setItem "oldnames", JSON.stringify _.compact _.union [$("#playername").val()], JSON.parse localStorage.getItem "oldnames"
Session.setDefault("playerid", Math.random())
Session.set("playername", $("#playername").val())
Meteor.call "removePlayer",
gameid: Session.get("gameid")
playerid: Session.get("playerid")
Meteor.apply "addPlayer", [
gameid: Session.get("gameid")
playerid: Session.get("playerid")
name: $("#playername").val()
], {wait: yes}
window.addEventListener "beforeunload", ->
Meteor.call "removePlayer",
gameid: Session.get("gameid")
playerid: Session.get("playerid")
Session.set "playername"
'click .oldname': (evt) ->
$("#playername").val(evt.currentTarget.innerText)
Template.play.events
'click #reset': (evt) ->
Session.set "playername"
Meteor.call "removePlayer",
gameid: Session.get("gameid")
playerid: Session.get("playerid")
Template.reviewAnswer.helpers
canUnanswer: ->
{allowLateAnswers, revealed} = getGame()
allowLateAnswers or not revealed
Template.reviewAnswer.events
"click #unanswer": (evt) ->
Session.set "answer"
Meteor.call "unanswer",
playerid: Session.get("playerid")
gameid: Session.get "gameid"
Template.question.helpers
timer: -> getGame().timer
Template.question.events
"click .answer": (evt) ->
selectedAnswer = evt.currentTarget.dataset.original
answerList = Template.currentData().answers
answer = answerList.indexOf(selectedAnswer)
Meteor.call "answer",
playerid: Session.get("playerid")
gameid: Session.get("gameid")
answer: answer
Session.set "answer", answer
no
updateCorrect = ->
correctAnswers = _(getQuiz().questions).pluck("correctAnswer")
Meteor.call "getAnswers",
playerid: Session.get("playerid")
gameid: Session.get("gameid")
, (error, myAnswers) ->
correctAndMyAnswers = _.zip(correctAnswers, myAnswers)
wasCorrect = ([correct, mine]) -> mine? and correct? and correct is mine
correctAnswersIHad = _.filter(correctAndMyAnswers, wasCorrect)
Session.set "correct", correctAnswersIHad.length
getTotal = -> _(getQuiz().questions).chain().pluck("correctAnswer").filter(_.isNumber).value().length
Template.results.rendered = ->
updateCorrect()
updateMyInfo()
Template.results.helpers
correct: -> Session.get "correct"
total: getTotal
pct: -> Math.round(10000*Session.get("correct")/getTotal())/100
score: -> Session.get "score"
|
[
{
"context": " when 'uglify-js' then key = 'jsParametersForUglifyJS2'\n when 'yui-js' th",
"end": 2006,
"score": 0.5540145039558411,
"start": 1996,
"tag": "KEY",
"value": "Parameters"
},
{
"context": "S2'\n when 'yui-js' then key = 'jsParametersForYUI'\n\n return @options[key]\n\n\n getMin",
"end": 2078,
"score": 0.593329668045044,
"start": 2066,
"tag": "KEY",
"value": "jsParameters"
}
] | atom-minify/lib/minifier-options-parser.coffee | raintao/Atom_packages | 34 | module.exports =
class AtomMinifyMinifierOptionsParser
parse: (contentType, options, inlineParameters) ->
@contentType = contentType
@options = options
@inlineParameters = inlineParameters
optionsStr = @getMinifierOptionsStr()
regex = /(?:([\w-\.]+)(?:\s*=\s*(?:(?:'(.*?)')|(?:"(.*?)")|([^ ]+)))?)*/g
options = []
while (match = regex.exec(optionsStr)) != null
if match.index == regex.lastIndex
regex.lastIndex++
if match[1] != undefined
key = match[1].trim()
value = if match[2] then match[2] else if match[3] then match[3] else match[4]
options[key] = @parseValue(value)
return options
getMinifierOptionsStr: () ->
options = @getGlobalMinifierOptions()
inlineParameterOptionsStr = @getMinifierOptionsFromInlineParameter()
if typeof inlineParameterOptionsStr is 'string' and inlineParameterOptionsStr.length > 0
# Check if first character is a plus ("+"), so it means that parameters for minifier
# has to be combined
if inlineParameterOptionsStr[0] is '+'
options += inlineParameterOptionsStr.substr(1)
# ... else we replace the global minifier options
else
options = inlineParameterOptionsStr
return options
getGlobalMinifierOptions: () =>
switch @contentType
when 'css'
switch @options.cssMinifier
when 'clean-css' then key = 'cssParametersForCleanCSS'
when 'csso' then key = 'cssParametersForCSSO'
when 'sqwish' then key = 'cssParametersForSqwish'
when 'yui-css' then key = 'cssParametersForYUI'
when 'js'
switch @options.jsMinifier
when 'gcc' then key = 'jsParametersForGCC'
when 'uglify-js' then key = 'jsParametersForUglifyJS2'
when 'yui-js' then key = 'jsParametersForYUI'
return @options[key]
getMinifierOptionsFromInlineParameter: ()=>
options = undefined
if typeof @inlineParameters.minifierOptions is 'string' and @inlineParameters.minifierOptions.length > 0
options = @inlineParameters.minifierOptions
else if typeof @inlineParameters.options is 'string' and @inlineParameters.options.length > 0
options = @inlineParameters.options
return options
parseValue: (value) ->
# undefined is a special value that means, that the key is defined, but no value
if value is undefined
return true
value = value.trim()
if value in [true, 'true', 'yes']
return true
if value in [false, 'false', 'no']
return false
if isFinite(value)
if value.indexOf('.') > -1
return parseFloat(value)
else
return parseInt(value)
# TODO: Extend for array and objects?
return value
| 160334 | module.exports =
class AtomMinifyMinifierOptionsParser
parse: (contentType, options, inlineParameters) ->
@contentType = contentType
@options = options
@inlineParameters = inlineParameters
optionsStr = @getMinifierOptionsStr()
regex = /(?:([\w-\.]+)(?:\s*=\s*(?:(?:'(.*?)')|(?:"(.*?)")|([^ ]+)))?)*/g
options = []
while (match = regex.exec(optionsStr)) != null
if match.index == regex.lastIndex
regex.lastIndex++
if match[1] != undefined
key = match[1].trim()
value = if match[2] then match[2] else if match[3] then match[3] else match[4]
options[key] = @parseValue(value)
return options
getMinifierOptionsStr: () ->
options = @getGlobalMinifierOptions()
inlineParameterOptionsStr = @getMinifierOptionsFromInlineParameter()
if typeof inlineParameterOptionsStr is 'string' and inlineParameterOptionsStr.length > 0
# Check if first character is a plus ("+"), so it means that parameters for minifier
# has to be combined
if inlineParameterOptionsStr[0] is '+'
options += inlineParameterOptionsStr.substr(1)
# ... else we replace the global minifier options
else
options = inlineParameterOptionsStr
return options
getGlobalMinifierOptions: () =>
switch @contentType
when 'css'
switch @options.cssMinifier
when 'clean-css' then key = 'cssParametersForCleanCSS'
when 'csso' then key = 'cssParametersForCSSO'
when 'sqwish' then key = 'cssParametersForSqwish'
when 'yui-css' then key = 'cssParametersForYUI'
when 'js'
switch @options.jsMinifier
when 'gcc' then key = 'jsParametersForGCC'
when 'uglify-js' then key = 'js<KEY>ForUglifyJS2'
when 'yui-js' then key = '<KEY>ForYUI'
return @options[key]
getMinifierOptionsFromInlineParameter: ()=>
options = undefined
if typeof @inlineParameters.minifierOptions is 'string' and @inlineParameters.minifierOptions.length > 0
options = @inlineParameters.minifierOptions
else if typeof @inlineParameters.options is 'string' and @inlineParameters.options.length > 0
options = @inlineParameters.options
return options
parseValue: (value) ->
# undefined is a special value that means, that the key is defined, but no value
if value is undefined
return true
value = value.trim()
if value in [true, 'true', 'yes']
return true
if value in [false, 'false', 'no']
return false
if isFinite(value)
if value.indexOf('.') > -1
return parseFloat(value)
else
return parseInt(value)
# TODO: Extend for array and objects?
return value
| true | module.exports =
class AtomMinifyMinifierOptionsParser
parse: (contentType, options, inlineParameters) ->
@contentType = contentType
@options = options
@inlineParameters = inlineParameters
optionsStr = @getMinifierOptionsStr()
regex = /(?:([\w-\.]+)(?:\s*=\s*(?:(?:'(.*?)')|(?:"(.*?)")|([^ ]+)))?)*/g
options = []
while (match = regex.exec(optionsStr)) != null
if match.index == regex.lastIndex
regex.lastIndex++
if match[1] != undefined
key = match[1].trim()
value = if match[2] then match[2] else if match[3] then match[3] else match[4]
options[key] = @parseValue(value)
return options
getMinifierOptionsStr: () ->
options = @getGlobalMinifierOptions()
inlineParameterOptionsStr = @getMinifierOptionsFromInlineParameter()
if typeof inlineParameterOptionsStr is 'string' and inlineParameterOptionsStr.length > 0
# Check if first character is a plus ("+"), so it means that parameters for minifier
# has to be combined
if inlineParameterOptionsStr[0] is '+'
options += inlineParameterOptionsStr.substr(1)
# ... else we replace the global minifier options
else
options = inlineParameterOptionsStr
return options
getGlobalMinifierOptions: () =>
switch @contentType
when 'css'
switch @options.cssMinifier
when 'clean-css' then key = 'cssParametersForCleanCSS'
when 'csso' then key = 'cssParametersForCSSO'
when 'sqwish' then key = 'cssParametersForSqwish'
when 'yui-css' then key = 'cssParametersForYUI'
when 'js'
switch @options.jsMinifier
when 'gcc' then key = 'jsParametersForGCC'
when 'uglify-js' then key = 'jsPI:KEY:<KEY>END_PIForUglifyJS2'
when 'yui-js' then key = 'PI:KEY:<KEY>END_PIForYUI'
return @options[key]
getMinifierOptionsFromInlineParameter: ()=>
options = undefined
if typeof @inlineParameters.minifierOptions is 'string' and @inlineParameters.minifierOptions.length > 0
options = @inlineParameters.minifierOptions
else if typeof @inlineParameters.options is 'string' and @inlineParameters.options.length > 0
options = @inlineParameters.options
return options
parseValue: (value) ->
# undefined is a special value that means, that the key is defined, but no value
if value is undefined
return true
value = value.trim()
if value in [true, 'true', 'yes']
return true
if value in [false, 'false', 'no']
return false
if isFinite(value)
if value.indexOf('.') > -1
return parseFloat(value)
else
return parseInt(value)
# TODO: Extend for array and objects?
return value
|
[
{
"context": "@getAvatarUrlFromUsername = (username) ->\n\tkey = \"avatar_random_#{username}\"\n\trandom = Session.keys[key] or 0\n\tif not username",
"end": 76,
"score": 0.9989919662475586,
"start": 50,
"tag": "KEY",
"value": "avatar_random_#{username}\""
},
{
"context": "\n\n@updateAvatarOfUsername = (username) ->\n\tkey = \"avatar_random_#{username}\"\n\tSession.set key, Math.round(Math.random() * 1000",
"end": 283,
"score": 0.9982810616493225,
"start": 257,
"tag": "KEY",
"value": "avatar_random_#{username}\""
},
{
"context": "me\n\n\t\t$(room.dom).find(\".message[data-username='#{username}'] .avatar-image\").css('background-image', \"url(#",
"end": 475,
"score": 0.9085618257522583,
"start": 467,
"tag": "USERNAME",
"value": "username"
}
] | packages/rocketchat-livechat/app/client/lib/fromApp/avatar.coffee | Cosecha/rocket-chat-stable | 2 | @getAvatarUrlFromUsername = (username) ->
key = "avatar_random_#{username}"
random = Session.keys[key] or 0
if not username?
return
return "#{Meteor.absoluteUrl()}avatar/#{username}.jpg?_dc=#{random}"
@updateAvatarOfUsername = (username) ->
key = "avatar_random_#{username}"
Session.set key, Math.round(Math.random() * 1000)
for key, room of RoomManager.openedRooms
url = getAvatarUrlFromUsername username
$(room.dom).find(".message[data-username='#{username}'] .avatar-image").css('background-image', "url(#{url})");
return true
| 163975 | @getAvatarUrlFromUsername = (username) ->
key = "<KEY>
random = Session.keys[key] or 0
if not username?
return
return "#{Meteor.absoluteUrl()}avatar/#{username}.jpg?_dc=#{random}"
@updateAvatarOfUsername = (username) ->
key = "<KEY>
Session.set key, Math.round(Math.random() * 1000)
for key, room of RoomManager.openedRooms
url = getAvatarUrlFromUsername username
$(room.dom).find(".message[data-username='#{username}'] .avatar-image").css('background-image', "url(#{url})");
return true
| true | @getAvatarUrlFromUsername = (username) ->
key = "PI:KEY:<KEY>END_PI
random = Session.keys[key] or 0
if not username?
return
return "#{Meteor.absoluteUrl()}avatar/#{username}.jpg?_dc=#{random}"
@updateAvatarOfUsername = (username) ->
key = "PI:KEY:<KEY>END_PI
Session.set key, Math.round(Math.random() * 1000)
for key, room of RoomManager.openedRooms
url = getAvatarUrlFromUsername username
$(room.dom).find(".message[data-username='#{username}'] .avatar-image").css('background-image', "url(#{url})");
return true
|
[
{
"context": "table.setAverageLogged(0)\n @user = new User('Aaron Sky', 'aaronsky', true, timetable)\n @projectName",
"end": 883,
"score": 0.9998140931129456,
"start": 874,
"tag": "NAME",
"value": "Aaron Sky"
},
{
"context": "ageLogged(0)\n @user = new User('Aaron Sky', 'aaronsky', true, timetable)\n @projectName = 'producti",
"end": 895,
"score": 0.9993536472320557,
"start": 887,
"tag": "USERNAME",
"value": "aaronsky"
},
{
"context": "uments (title-case)', ->\n punch = Punch.parse @user, 'In', 'in'\n expect(punch).to.have.property ",
"end": 1925,
"score": 0.7400690317153931,
"start": 1920,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "uments (title-case)', ->\n punch = Punch.parse @user, 'Out', 'out'\n expect(punch).to.have.propert",
"end": 2254,
"score": 0.6384316682815552,
"start": 2249,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "an existing project', ->\n punch = Punch.parse @user, \"in ##{@projectName}\", 'in'\n expect(punch).",
"end": 2617,
"score": 0.8212571144104004,
"start": 2612,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "o existing projects', ->\n punch = Punch.parse @user,\n \"out ##{@projectName} ",
"end": 3039,
"score": 0.6019175052642822,
"start": 3034,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "out a period marker', ->\n punch = Punch.parse @user, 'in 9:15', 'in'\n expect(punch).to.have.prop",
"end": 3764,
"score": 0.9843454360961914,
"start": 3759,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "nd no space between', ->\n punch = Punch.parse @user, 'in 9:15pm', 'in'\n expect(punch).to.have.pr",
"end": 4485,
"score": 0.990863561630249,
"start": 4480,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "ith a period marker', ->\n punch = Punch.parse @user, 'in 9:15 pm', 'in'\n expect(punch).to.have.p",
"end": 4931,
"score": 0.9882588386535645,
"start": 4926,
"tag": "USERNAME",
"value": "@user"
},
{
"context": " 'in at a full date', ->\n punch = Punch.parse @user, 'in 4pm 4/22/2016', 'in'\n expect(punch).to.",
"end": 5362,
"score": 0.9952500462532043,
"start": 5357,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "t minutes yesterday', ->\n punch = Punch.parse @user, 'out 7pm yesterday', 'out'\n expect(punch).t",
"end": 5888,
"score": 0.9961907267570496,
"start": 5883,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "an existing project', ->\n punch = Punch.parse @user, \"in 17:00 ##{@projectName}\", 'in'\n expect(p",
"end": 6454,
"score": 0.9799942970275879,
"start": 6449,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "time block to punch', ->\n punch = Punch.parse @user, '1.5 hours'\n expect(punch).to.have.property",
"end": 6993,
"score": 0.9795335531234741,
"start": 6988,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "h time block on day', ->\n punch = Punch.parse @user, '15 hours on 4/22'\n expect(punch).to.have.p",
"end": 7360,
"score": 0.9784342050552368,
"start": 7355,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "time block to punch', ->\n punch = Punch.parse @user, '.5 hours'\n expect(punch).to.have.property ",
"end": 7804,
"score": 0.963327169418335,
"start": 7799,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "time block to punch', ->\n punch = Punch.parse @user, '0.5 hours'\n expect(punch).to.have.property",
"end": 8173,
"score": 0.9984400272369385,
"start": 8168,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "time block to punch', ->\n punch = Punch.parse @user, '0.5 hour'\n expect(punch).to.have.property ",
"end": 8543,
"score": 0.9984499216079712,
"start": 8538,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "time block to punch', ->\n punch = Punch.parse @user, '1 hour'\n expect(punch).to.have.property 'm",
"end": 8912,
"score": 0.9985198974609375,
"start": 8907,
"tag": "USERNAME",
"value": "@user"
},
{
"context": " yesterday\\'s punch', ->\n punch = Punch.parse @user, '2 hours yesterday'\n expect(punch).to.have.",
"end": 9290,
"score": 0.9983720183372498,
"start": 9285,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "an existing project\", ->\n punch = Punch.parse @user, \"3.25 hours tuesday ##{@projectName}\"\n expe",
"end": 9723,
"score": 0.9930029511451721,
"start": 9718,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "g today as vacation', ->\n punch = Punch.parse @user, 'vacation today', 'vacation'\n expect(punch)",
"end": 10200,
"score": 0.9908015727996826,
"start": 10195,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "lf of today as sick', ->\n punch = Punch.parse @user, 'sick half-day', 'sick'\n expect(punch).to.h",
"end": 10575,
"score": 0.9915295839309692,
"start": 10570,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "sterday as vacation', ->\n punch = Punch.parse @user,\n 'vacation half-day yes",
"end": 10949,
"score": 0.9890638589859009,
"start": 10944,
"tag": "USERNAME",
"value": "@user"
},
{
"context": " date range as sick', ->\n punch = Punch.parse @user, 'sick Jul 6-8', 'sick'\n expect(punch).t",
"end": 11382,
"score": 0.7341625094413757,
"start": 11382,
"tag": "USERNAME",
"value": ""
},
{
"context": "e range as vacation', ->\n punch = Punch.parse @user, 'vacation 1/28 - 2/4', 'vacation'\n expe",
"end": 11850,
"score": 0.6416233777999878,
"start": 11850,
"tag": "USERNAME",
"value": ""
},
{
"context": "table.setAverageLogged(0)\n @user = new User('Aaron Sky', 'aaronsky', true, timetable)\n it 'should mod",
"end": 12804,
"score": 0.9991087317466736,
"start": 12795,
"tag": "NAME",
"value": "Aaron Sky"
},
{
"context": "ageLogged(0)\n @user = new User('Aaron Sky', 'aaronsky', true, timetable)\n it 'should modify the punc",
"end": 12816,
"score": 0.9993950724601746,
"start": 12808,
"tag": "USERNAME",
"value": "aaronsky"
},
{
"context": " timetable.setAverageLogged(0)\n name = 'Aaron Sky'\n @user = new User(name, 'aaronsky', true, t",
"end": 13985,
"score": 0.9996017813682556,
"start": 13976,
"tag": "NAME",
"value": "Aaron Sky"
},
{
"context": " name = 'Aaron Sky'\n @user = new User(name, 'aaronsky', true, timetable)\n it 'should return a raw ob",
"end": 14025,
"score": 0.9995779395103455,
"start": 14017,
"tag": "USERNAME",
"value": "aaronsky"
},
{
"context": "table.setAverageLogged(0)\n @user = new User('Aaron Sky', 'aaronsky', true, timetable)\n it 'should not",
"end": 15030,
"score": 0.9995427131652832,
"start": 15021,
"tag": "NAME",
"value": "Aaron Sky"
},
{
"context": "ageLogged(0)\n @user = new User('Aaron Sky', 'aaronsky', true, timetable)\n it 'should not assign a ro",
"end": 15042,
"score": 0.9986271262168884,
"start": 15034,
"tag": "USERNAME",
"value": "aaronsky"
},
{
"context": "table.setAverageLogged(0)\n @user = new User('Aaron Sky', 'aaronsky', true, timetable)\n it 'should ret",
"end": 16009,
"score": 0.999006986618042,
"start": 16000,
"tag": "NAME",
"value": "Aaron Sky"
},
{
"context": "ageLogged(0)\n @user = new User('Aaron Sky', 'aaronsky', true, timetable)\n it 'should return a failur",
"end": 16021,
"score": 0.9986701011657715,
"start": 16013,
"tag": "USERNAME",
"value": "aaronsky"
},
{
"context": "in punch', ->\n @user.punches.push(Punch.parse(@user, 'in', 'in'))\n punch = Punch.parse @user, 'i",
"end": 16153,
"score": 0.9782646894454956,
"start": 16148,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "arse(@user, 'in', 'in'))\n punch = Punch.parse @user, 'in', 'in'\n expect(punch.isValid(@user)).to",
"end": 16199,
"score": 0.9180055856704712,
"start": 16194,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "parse @user, 'in', 'in'\n expect(punch.isValid(@user)).to.be.instanceof.String\n it 'should return a",
"end": 16244,
"score": 0.9837337732315063,
"start": 16239,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "nch dated yesterday', ->\n punch = Punch.parse @user, 'in yesterday', 'in'\n expect(punch.isValid(",
"end": 16378,
"score": 0.9492346048355103,
"start": 16373,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "r, 'in yesterday', 'in'\n expect(punch.isValid(@user)).to.be.instanceof.String\n it 'should return a",
"end": 16433,
"score": 0.9920112490653992,
"start": 16428,
"tag": "USERNAME",
"value": "@user"
},
{
"context": " @user.salary = false\n punch = Punch.parse @user, 'unpaid 9:50-10:00', 'unpaid'\n expect(punch",
"end": 16606,
"score": 0.9793571829795837,
"start": 16601,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "d 9:50-10:00', 'unpaid'\n expect(punch.isValid(@user)).to.be.instanceof.String\n it 'should return a",
"end": 16670,
"score": 0.9887045621871948,
"start": 16665,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "etable.setVacation(5, 2)\n punch = Punch.parse @user, 'vacation today', 'vacation'\n expect(punch.",
"end": 16870,
"score": 0.9839605093002319,
"start": 16865,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "tion today', 'vacation'\n expect(punch.isValid(@user)).to.be.instanceof.String\n it 'should return a",
"end": 16933,
"score": 0.9925440549850464,
"start": 16928,
"tag": "USERNAME",
"value": "@user"
},
{
"context": ".timetable.setSick(5, 2)\n punch = Punch.parse @user, 'sick today', 'sick'\n expect(punch.isValid(",
"end": 17121,
"score": 0.981231689453125,
"start": 17116,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "r, 'sick today', 'sick'\n expect(punch.isValid(@user)).to.be.instanceof.String\n it 'should return a",
"end": 17176,
"score": 0.994050145149231,
"start": 17171,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "n\\'t divisible by 4', ->\n punch = Punch.parse @user, 'vacation 9:50-10:00', 'vacation'\n expect(p",
"end": 17338,
"score": 0.9890602827072144,
"start": 17333,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "9:50-10:00', 'vacation'\n expect(punch.isValid(@user)).to.be.instanceof.String\n punch = Punch.par",
"end": 17406,
"score": 0.9954838752746582,
"start": 17401,
"tag": "USERNAME",
"value": "@user"
},
{
"context": ".to.be.instanceof.String\n punch = Punch.parse @user, 'sick 9:50-10:00', 'sick'\n expect(punch.isV",
"end": 17464,
"score": 0.979084312915802,
"start": 17459,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "ick 9:50-10:00', 'sick'\n expect(punch.isValid(@user)).to.be.instanceof.String\n punch = Punch.par",
"end": 17524,
"score": 0.9941033124923706,
"start": 17519,
"tag": "USERNAME",
"value": "@user"
},
{
"context": ".to.be.instanceof.String\n punch = Punch.parse @user, 'unpaid 9:50-10:00', 'unpaid'\n expect(punch",
"end": 17582,
"score": 0.9699832201004028,
"start": 17577,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "d 9:50-10:00', 'unpaid'\n expect(punch.isValid(@user)).to.be.instanceof.String\n it 'should return a",
"end": 17646,
"score": 0.9988709688186646,
"start": 17641,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "d older than 7 days', ->\n punch = Punch.parse @user, 'in Jul 6-8', 'in'\n expect(punch.isValid(@u",
"end": 17786,
"score": 0.9986406564712524,
"start": 17781,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "ser, 'in Jul 6-8', 'in'\n expect(punch.isValid(@user)).to.be.instanceof.String\n it 'should return t",
"end": 17839,
"score": 0.9988484382629395,
"start": 17834,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "e for a valid punch', ->\n punch = Punch.parse @user, 'in', 'in'\n expect(punch.isValid(@user)).to",
"end": 17947,
"score": 0.9986170530319214,
"start": 17942,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "parse @user, 'in', 'in'\n expect(punch.isValid(@user)).to.be.true\n",
"end": 17992,
"score": 0.9990353584289551,
"start": 17987,
"tag": "USERNAME",
"value": "@user"
}
] | tests/models/test_punch.coffee | fangamer/ibizan | 0 |
moment = require 'moment'
expect = require('chai').expect
Organization = require('../../src/models/organization').get('test')
MockSheet = require '../mocks/mock_sheet.js'
Organization.spreadsheet.sheet = MockSheet
Project = require '../../src/models/project'
{ User, Timetable } = require '../../src/models/user'
Punch = require '../../src/models/punch'
Organization.projects = [
new Project('#production'),
new Project('#camp-fangamer')
]
describe 'Punch', ->
describe '#parse(user, command, mode)', ->
beforeEach ->
start = moment({day: 3, hour: 7})
end = moment({day: 3, hour: 18})
timetable = new Timetable(start, end, moment.tz.zone('America/New_York'))
timetable.setVacation(13, 0)
timetable.setSick(5, 0)
timetable.setUnpaid(0)
timetable.setLogged(0)
timetable.setAverageLogged(0)
@user = new User('Aaron Sky', 'aaronsky', true, timetable)
@projectName = 'production'
@alternateProject = 'camp-fangamer'
it 'should return if user and command are not defined', ->
expect(Punch.parse(null, 'a dumb command')).to.be.undefined
expect(Punch.parse(@user, null)).to.be.undefined
it 'in without arguments', ->
punch = Punch.parse @user, 'in', 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
it 'out without arguments', ->
punch = Punch.parse @user, 'out', 'out'
expect(punch).to.have.property 'mode', 'out'
expect(punch).to.have.deep.property 'times[0]'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in without arguments (title-case)', ->
punch = Punch.parse @user, 'In', 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
it 'out without arguments (title-case)', ->
punch = Punch.parse @user, 'Out', 'out'
expect(punch).to.have.property 'mode', 'out'
expect(punch).to.have.deep.property 'times[0]'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in with an existing project', ->
punch = Punch.parse @user, "in ##{@projectName}", 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch).to.have.deep.property 'projects[0]'
expect(punch).to.have.deep.property 'projects[0].name', @projectName
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'out with two existing projects', ->
punch = Punch.parse @user,
"out ##{@projectName} ##{@alternateProject}",
'out'
expect(punch).to.have.property 'mode', 'out'
expect(punch).to.have.deep.property 'times[0]'
expect(punch).to.have.deep.property 'projects[0]'
expect(punch).to.have.deep.property 'projects[0].name',
@projectName
expect(punch).to.have.deep.property 'projects[1]'
expect(punch).to.have.deep.property 'projects[1].name',
@alternateProject
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in at a time without a period marker', ->
punch = Punch.parse @user, 'in 9:15', 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
now = moment()
amPm = now.format('A')
expectedTime = moment("9:15 #{amPm}", 'h:mm A')
if expectedTime.isAfter now
if expectedTime.diff(now, 'hours', true) > 6
expectedTime.subtract(12, 'hours')
expect(punch.times[0].format('hh:mm:ss A')).to.equal expectedTime.format('hh:mm:ss A')
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in at a time with a period marker and no space between', ->
punch = Punch.parse @user, 'in 9:15pm', 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch.times[0].format('hh:mm:ss A')).to.equal "09:15:00 PM"
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in at a time with a period marker', ->
punch = Punch.parse @user, 'in 9:15 pm', 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch.times[0].format('hh:mm:ss A')).to.equal "09:15:00 PM"
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in at a full date', ->
punch = Punch.parse @user, 'in 4pm 4/22/2016', 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch.times[0].format('MM/DD/YYYY')).to.equal "04/22/2016"
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
expect(punch.date.format('MM/DD/YYYY')).to.equal "04/22/2016"
it 'out at a time without minutes yesterday', ->
punch = Punch.parse @user, 'out 7pm yesterday', 'out'
expect(punch).to.have.property 'mode', 'out'
expect(punch).to.have.deep.property 'times[0]'
yesterday = moment().subtract(1, 'days')
expect(punch.times[0].format('MM/DD/YYYY hh:mm:ss A'))
.to.equal "#{yesterday.format('MM/DD/YYYY')} 07:00:00 PM"
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in at a 24-hour time and an existing project', ->
punch = Punch.parse @user, "in 17:00 ##{@projectName}", 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch.times[0].format('hh:mm:ss A')).to.equal "05:00:00 PM"
expect(punch).to.have.deep.property 'projects[0]'
expect(punch).to.have.deep.property 'projects[0].name',
@projectName
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'append time block to punch', ->
punch = Punch.parse @user, '1.5 hours'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 1.5
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'punch time block on day', ->
punch = Punch.parse @user, '15 hours on 4/22'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 15
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
expect(punch.date.format('MM/DD/YYYY')).to.equal "04/22/2016"
it 'append time block to punch', ->
punch = Punch.parse @user, '.5 hours'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 0.5
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'append time block to punch', ->
punch = Punch.parse @user, '0.5 hours'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 0.5
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'append time block to punch', ->
punch = Punch.parse @user, '0.5 hour'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 0.5
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'append time block to punch', ->
punch = Punch.parse @user, '1 hour'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 1
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'append time block to yesterday\'s punch', ->
punch = Punch.parse @user, '2 hours yesterday'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 2
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it "append time block to Tuesday\'s punch
and assign it to an existing project", ->
punch = Punch.parse @user, "3.25 hours tuesday ##{@projectName}"
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 3.25
expect(punch).to.have.deep.property 'projects[0]'
expect(punch).to.have.deep.property 'projects[0].name',
@projectName
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'flag today as vacation', ->
punch = Punch.parse @user, 'vacation today', 'vacation'
expect(punch).to.have.property 'mode', 'vacation'
expect(punch).to.have.property 'times'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'flag half of today as sick', ->
punch = Punch.parse @user, 'sick half-day', 'sick'
expect(punch).to.have.property 'mode', 'sick'
expect(punch).to.have.property 'times'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'flag half of yesterday as vacation', ->
punch = Punch.parse @user,
'vacation half-day yesterday',
'vacation'
expect(punch).to.have.property 'mode', 'vacation'
expect(punch).to.have.property 'times'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'flag a date range as sick', ->
punch = Punch.parse @user, 'sick Jul 6-8', 'sick'
expect(punch).to.have.property 'mode', 'sick'
expect(punch).to.have.property 'times'
expect(punch).to.have.deep.property 'times.length', 2
expect(punch.elapsed).to.equal 33
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'flag a date range as vacation', ->
punch = Punch.parse @user, 'vacation 1/28 - 2/4', 'vacation'
expect(punch).to.have.property 'mode', 'vacation'
expect(punch).to.have.property 'times'
expect(punch).to.have.deep.property 'times.length', 2
expect(punch.elapsed).to.equal 72
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
describe '#out(punch)', ->
beforeEach ->
zone = 'America/New_York'
now = moment.tz zone
start = moment.tz({year: now.year(), month: now.month(), day: now.date(), hour: 7}, zone)
end = moment.tz({year: now.year(), month: now.month(), day: now.date(), hour: 18}, zone)
timetable = new Timetable(start, end, zone)
timetable.setVacation(13, 0)
timetable.setSick(5, 0)
timetable.setUnpaid(0)
timetable.setLogged(0)
timetable.setAverageLogged(0)
@user = new User('Aaron Sky', 'aaronsky', true, timetable)
it 'should modify the punch to an out punch', ->
[start, end] = @user.activeHours()
punch = Punch.parse @user,
"in #{start.format('hh:mma')} #production", 'in'
outPunch = Punch.parse @user,
"out #{end.format('hh:mma')} #camp-fangamer", 'out'
punch.out outPunch
expect(punch.times).to.have.lengthOf 2
expect(punch.times[0].format()).to.equal start.format()
expect(punch.times[1].format()).to.equal end.format()
expect(punch.projects).to.have.lengthOf 2
expect(punch).to.have.deep.property 'projects[0].name',
'production'
expect(punch).to.have.deep.property 'projects[1].name',
'camp-fangamer'
describe '#toRawRow(name)', ->
beforeEach ->
start = moment({day: 3, hour: 7})
end = moment({day: 3, hour: 18})
timetable = new Timetable(start, end, moment.tz.zone('America/New_York'))
timetable.setVacation(13, 0)
timetable.setSick(5, 0)
timetable.setUnpaid(0)
timetable.setLogged(0)
timetable.setAverageLogged(0)
name = 'Aaron Sky'
@user = new User(name, 'aaronsky', true, timetable)
it 'should return a raw object for use with Sheet', ->
punch = Punch.parse @user, 'in', 'in'
raw = punch.toRawRow @user.name
expect(raw).to.exist
it 'should return a raw object for an in punch', ->
punch = Punch.parse @user, 'in', 'in'
raw = punch.toRawRow @user.name
expect(raw).to.exist
it 'should return a raw object for an out punch', ->
punch = Punch.parse @user, 'in 9:00am', 'in'
outPunch = Punch.parse @user, 'out 10:30am', 'out'
punch.out outPunch
raw = punch.toRawRow @user.name
expect(raw).to.exist
describe '#assignRow', ->
beforeEach ->
start = moment({day: 3, hour: 7})
end = moment({day: 3, hour: 18})
timetable = new Timetable(start, end, moment.tz.zone('America/New_York'))
timetable.setVacation(13, 0)
timetable.setSick(5, 0)
timetable.setUnpaid(0)
timetable.setLogged(0)
timetable.setAverageLogged(0)
@user = new User('Aaron Sky', 'aaronsky', true, timetable)
it 'should not assign a row if no parameter is passed', ->
punch = Punch.parse @user, 'in', 'in'
punch.assignRow()
expect(punch.row).to.not.exist
it 'should not assign a row if an invalid row is passed', ->
punch = Punch.parse @user, 'in', 'in'
punch.assignRow({})
expect(punch.row).to.not.exist
it 'should assign a row if a row is passed in', ->
punch = Punch.parse @user, 'in', 'in'
punch.assignRow({
save: () -> ,
del: () ->
})
expect(punch.row).to.exist
describe '#isValid(user)', ->
beforeEach ->
start = moment({day: 3, hour: 7})
end = moment({day: 3, hour: 18})
timetable = new Timetable(start, end, moment.tz.zone('America/New_York'))
timetable.setVacation(13, 0)
timetable.setSick(5, 0)
timetable.setUnpaid(0)
timetable.setLogged(0)
timetable.setAverageLogged(0)
@user = new User('Aaron Sky', 'aaronsky', true, timetable)
it 'should return a failure reason for a repetitive in punch', ->
@user.punches.push(Punch.parse(@user, 'in', 'in'))
punch = Punch.parse @user, 'in', 'in'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return a failure reason for an in punch dated yesterday', ->
punch = Punch.parse @user, 'in yesterday', 'in'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return a failure reason for an non-salary user punching unpaid time', ->
@user.salary = false
punch = Punch.parse @user, 'unpaid 9:50-10:00', 'unpaid'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return a failure reason for a vacation punch that exceeds available vacation time', ->
@user.timetable.setVacation(5, 2)
punch = Punch.parse @user, 'vacation today', 'vacation'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return a failure reason for a sick punch that exceeds available sick time', ->
@user.timetable.setSick(5, 2)
punch = Punch.parse @user, 'sick today', 'sick'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return a failure reason for a vacation/sick/unpaid punch that isn\'t divisible by 4', ->
punch = Punch.parse @user, 'vacation 9:50-10:00', 'vacation'
expect(punch.isValid(@user)).to.be.instanceof.String
punch = Punch.parse @user, 'sick 9:50-10:00', 'sick'
expect(punch.isValid(@user)).to.be.instanceof.String
punch = Punch.parse @user, 'unpaid 9:50-10:00', 'unpaid'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return a failure reason for any punch dated older than 7 days', ->
punch = Punch.parse @user, 'in Jul 6-8', 'in'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return true for a valid punch', ->
punch = Punch.parse @user, 'in', 'in'
expect(punch.isValid(@user)).to.be.true
| 153182 |
moment = require 'moment'
expect = require('chai').expect
Organization = require('../../src/models/organization').get('test')
MockSheet = require '../mocks/mock_sheet.js'
Organization.spreadsheet.sheet = MockSheet
Project = require '../../src/models/project'
{ User, Timetable } = require '../../src/models/user'
Punch = require '../../src/models/punch'
Organization.projects = [
new Project('#production'),
new Project('#camp-fangamer')
]
describe 'Punch', ->
describe '#parse(user, command, mode)', ->
beforeEach ->
start = moment({day: 3, hour: 7})
end = moment({day: 3, hour: 18})
timetable = new Timetable(start, end, moment.tz.zone('America/New_York'))
timetable.setVacation(13, 0)
timetable.setSick(5, 0)
timetable.setUnpaid(0)
timetable.setLogged(0)
timetable.setAverageLogged(0)
@user = new User('<NAME>', 'aaronsky', true, timetable)
@projectName = 'production'
@alternateProject = 'camp-fangamer'
it 'should return if user and command are not defined', ->
expect(Punch.parse(null, 'a dumb command')).to.be.undefined
expect(Punch.parse(@user, null)).to.be.undefined
it 'in without arguments', ->
punch = Punch.parse @user, 'in', 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
it 'out without arguments', ->
punch = Punch.parse @user, 'out', 'out'
expect(punch).to.have.property 'mode', 'out'
expect(punch).to.have.deep.property 'times[0]'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in without arguments (title-case)', ->
punch = Punch.parse @user, 'In', 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
it 'out without arguments (title-case)', ->
punch = Punch.parse @user, 'Out', 'out'
expect(punch).to.have.property 'mode', 'out'
expect(punch).to.have.deep.property 'times[0]'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in with an existing project', ->
punch = Punch.parse @user, "in ##{@projectName}", 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch).to.have.deep.property 'projects[0]'
expect(punch).to.have.deep.property 'projects[0].name', @projectName
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'out with two existing projects', ->
punch = Punch.parse @user,
"out ##{@projectName} ##{@alternateProject}",
'out'
expect(punch).to.have.property 'mode', 'out'
expect(punch).to.have.deep.property 'times[0]'
expect(punch).to.have.deep.property 'projects[0]'
expect(punch).to.have.deep.property 'projects[0].name',
@projectName
expect(punch).to.have.deep.property 'projects[1]'
expect(punch).to.have.deep.property 'projects[1].name',
@alternateProject
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in at a time without a period marker', ->
punch = Punch.parse @user, 'in 9:15', 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
now = moment()
amPm = now.format('A')
expectedTime = moment("9:15 #{amPm}", 'h:mm A')
if expectedTime.isAfter now
if expectedTime.diff(now, 'hours', true) > 6
expectedTime.subtract(12, 'hours')
expect(punch.times[0].format('hh:mm:ss A')).to.equal expectedTime.format('hh:mm:ss A')
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in at a time with a period marker and no space between', ->
punch = Punch.parse @user, 'in 9:15pm', 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch.times[0].format('hh:mm:ss A')).to.equal "09:15:00 PM"
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in at a time with a period marker', ->
punch = Punch.parse @user, 'in 9:15 pm', 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch.times[0].format('hh:mm:ss A')).to.equal "09:15:00 PM"
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in at a full date', ->
punch = Punch.parse @user, 'in 4pm 4/22/2016', 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch.times[0].format('MM/DD/YYYY')).to.equal "04/22/2016"
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
expect(punch.date.format('MM/DD/YYYY')).to.equal "04/22/2016"
it 'out at a time without minutes yesterday', ->
punch = Punch.parse @user, 'out 7pm yesterday', 'out'
expect(punch).to.have.property 'mode', 'out'
expect(punch).to.have.deep.property 'times[0]'
yesterday = moment().subtract(1, 'days')
expect(punch.times[0].format('MM/DD/YYYY hh:mm:ss A'))
.to.equal "#{yesterday.format('MM/DD/YYYY')} 07:00:00 PM"
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in at a 24-hour time and an existing project', ->
punch = Punch.parse @user, "in 17:00 ##{@projectName}", 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch.times[0].format('hh:mm:ss A')).to.equal "05:00:00 PM"
expect(punch).to.have.deep.property 'projects[0]'
expect(punch).to.have.deep.property 'projects[0].name',
@projectName
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'append time block to punch', ->
punch = Punch.parse @user, '1.5 hours'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 1.5
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'punch time block on day', ->
punch = Punch.parse @user, '15 hours on 4/22'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 15
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
expect(punch.date.format('MM/DD/YYYY')).to.equal "04/22/2016"
it 'append time block to punch', ->
punch = Punch.parse @user, '.5 hours'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 0.5
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'append time block to punch', ->
punch = Punch.parse @user, '0.5 hours'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 0.5
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'append time block to punch', ->
punch = Punch.parse @user, '0.5 hour'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 0.5
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'append time block to punch', ->
punch = Punch.parse @user, '1 hour'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 1
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'append time block to yesterday\'s punch', ->
punch = Punch.parse @user, '2 hours yesterday'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 2
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it "append time block to Tuesday\'s punch
and assign it to an existing project", ->
punch = Punch.parse @user, "3.25 hours tuesday ##{@projectName}"
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 3.25
expect(punch).to.have.deep.property 'projects[0]'
expect(punch).to.have.deep.property 'projects[0].name',
@projectName
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'flag today as vacation', ->
punch = Punch.parse @user, 'vacation today', 'vacation'
expect(punch).to.have.property 'mode', 'vacation'
expect(punch).to.have.property 'times'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'flag half of today as sick', ->
punch = Punch.parse @user, 'sick half-day', 'sick'
expect(punch).to.have.property 'mode', 'sick'
expect(punch).to.have.property 'times'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'flag half of yesterday as vacation', ->
punch = Punch.parse @user,
'vacation half-day yesterday',
'vacation'
expect(punch).to.have.property 'mode', 'vacation'
expect(punch).to.have.property 'times'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'flag a date range as sick', ->
punch = Punch.parse @user, 'sick Jul 6-8', 'sick'
expect(punch).to.have.property 'mode', 'sick'
expect(punch).to.have.property 'times'
expect(punch).to.have.deep.property 'times.length', 2
expect(punch.elapsed).to.equal 33
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'flag a date range as vacation', ->
punch = Punch.parse @user, 'vacation 1/28 - 2/4', 'vacation'
expect(punch).to.have.property 'mode', 'vacation'
expect(punch).to.have.property 'times'
expect(punch).to.have.deep.property 'times.length', 2
expect(punch.elapsed).to.equal 72
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
describe '#out(punch)', ->
beforeEach ->
zone = 'America/New_York'
now = moment.tz zone
start = moment.tz({year: now.year(), month: now.month(), day: now.date(), hour: 7}, zone)
end = moment.tz({year: now.year(), month: now.month(), day: now.date(), hour: 18}, zone)
timetable = new Timetable(start, end, zone)
timetable.setVacation(13, 0)
timetable.setSick(5, 0)
timetable.setUnpaid(0)
timetable.setLogged(0)
timetable.setAverageLogged(0)
@user = new User('<NAME>', 'aaronsky', true, timetable)
it 'should modify the punch to an out punch', ->
[start, end] = @user.activeHours()
punch = Punch.parse @user,
"in #{start.format('hh:mma')} #production", 'in'
outPunch = Punch.parse @user,
"out #{end.format('hh:mma')} #camp-fangamer", 'out'
punch.out outPunch
expect(punch.times).to.have.lengthOf 2
expect(punch.times[0].format()).to.equal start.format()
expect(punch.times[1].format()).to.equal end.format()
expect(punch.projects).to.have.lengthOf 2
expect(punch).to.have.deep.property 'projects[0].name',
'production'
expect(punch).to.have.deep.property 'projects[1].name',
'camp-fangamer'
describe '#toRawRow(name)', ->
beforeEach ->
start = moment({day: 3, hour: 7})
end = moment({day: 3, hour: 18})
timetable = new Timetable(start, end, moment.tz.zone('America/New_York'))
timetable.setVacation(13, 0)
timetable.setSick(5, 0)
timetable.setUnpaid(0)
timetable.setLogged(0)
timetable.setAverageLogged(0)
name = '<NAME>'
@user = new User(name, 'aaronsky', true, timetable)
it 'should return a raw object for use with Sheet', ->
punch = Punch.parse @user, 'in', 'in'
raw = punch.toRawRow @user.name
expect(raw).to.exist
it 'should return a raw object for an in punch', ->
punch = Punch.parse @user, 'in', 'in'
raw = punch.toRawRow @user.name
expect(raw).to.exist
it 'should return a raw object for an out punch', ->
punch = Punch.parse @user, 'in 9:00am', 'in'
outPunch = Punch.parse @user, 'out 10:30am', 'out'
punch.out outPunch
raw = punch.toRawRow @user.name
expect(raw).to.exist
describe '#assignRow', ->
beforeEach ->
start = moment({day: 3, hour: 7})
end = moment({day: 3, hour: 18})
timetable = new Timetable(start, end, moment.tz.zone('America/New_York'))
timetable.setVacation(13, 0)
timetable.setSick(5, 0)
timetable.setUnpaid(0)
timetable.setLogged(0)
timetable.setAverageLogged(0)
@user = new User('<NAME>', 'aaronsky', true, timetable)
it 'should not assign a row if no parameter is passed', ->
punch = Punch.parse @user, 'in', 'in'
punch.assignRow()
expect(punch.row).to.not.exist
it 'should not assign a row if an invalid row is passed', ->
punch = Punch.parse @user, 'in', 'in'
punch.assignRow({})
expect(punch.row).to.not.exist
it 'should assign a row if a row is passed in', ->
punch = Punch.parse @user, 'in', 'in'
punch.assignRow({
save: () -> ,
del: () ->
})
expect(punch.row).to.exist
describe '#isValid(user)', ->
beforeEach ->
start = moment({day: 3, hour: 7})
end = moment({day: 3, hour: 18})
timetable = new Timetable(start, end, moment.tz.zone('America/New_York'))
timetable.setVacation(13, 0)
timetable.setSick(5, 0)
timetable.setUnpaid(0)
timetable.setLogged(0)
timetable.setAverageLogged(0)
@user = new User('<NAME>', 'aaronsky', true, timetable)
it 'should return a failure reason for a repetitive in punch', ->
@user.punches.push(Punch.parse(@user, 'in', 'in'))
punch = Punch.parse @user, 'in', 'in'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return a failure reason for an in punch dated yesterday', ->
punch = Punch.parse @user, 'in yesterday', 'in'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return a failure reason for an non-salary user punching unpaid time', ->
@user.salary = false
punch = Punch.parse @user, 'unpaid 9:50-10:00', 'unpaid'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return a failure reason for a vacation punch that exceeds available vacation time', ->
@user.timetable.setVacation(5, 2)
punch = Punch.parse @user, 'vacation today', 'vacation'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return a failure reason for a sick punch that exceeds available sick time', ->
@user.timetable.setSick(5, 2)
punch = Punch.parse @user, 'sick today', 'sick'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return a failure reason for a vacation/sick/unpaid punch that isn\'t divisible by 4', ->
punch = Punch.parse @user, 'vacation 9:50-10:00', 'vacation'
expect(punch.isValid(@user)).to.be.instanceof.String
punch = Punch.parse @user, 'sick 9:50-10:00', 'sick'
expect(punch.isValid(@user)).to.be.instanceof.String
punch = Punch.parse @user, 'unpaid 9:50-10:00', 'unpaid'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return a failure reason for any punch dated older than 7 days', ->
punch = Punch.parse @user, 'in Jul 6-8', 'in'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return true for a valid punch', ->
punch = Punch.parse @user, 'in', 'in'
expect(punch.isValid(@user)).to.be.true
| true |
moment = require 'moment'
expect = require('chai').expect
Organization = require('../../src/models/organization').get('test')
MockSheet = require '../mocks/mock_sheet.js'
Organization.spreadsheet.sheet = MockSheet
Project = require '../../src/models/project'
{ User, Timetable } = require '../../src/models/user'
Punch = require '../../src/models/punch'
Organization.projects = [
new Project('#production'),
new Project('#camp-fangamer')
]
describe 'Punch', ->
describe '#parse(user, command, mode)', ->
beforeEach ->
start = moment({day: 3, hour: 7})
end = moment({day: 3, hour: 18})
timetable = new Timetable(start, end, moment.tz.zone('America/New_York'))
timetable.setVacation(13, 0)
timetable.setSick(5, 0)
timetable.setUnpaid(0)
timetable.setLogged(0)
timetable.setAverageLogged(0)
@user = new User('PI:NAME:<NAME>END_PI', 'aaronsky', true, timetable)
@projectName = 'production'
@alternateProject = 'camp-fangamer'
it 'should return if user and command are not defined', ->
expect(Punch.parse(null, 'a dumb command')).to.be.undefined
expect(Punch.parse(@user, null)).to.be.undefined
it 'in without arguments', ->
punch = Punch.parse @user, 'in', 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
it 'out without arguments', ->
punch = Punch.parse @user, 'out', 'out'
expect(punch).to.have.property 'mode', 'out'
expect(punch).to.have.deep.property 'times[0]'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in without arguments (title-case)', ->
punch = Punch.parse @user, 'In', 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
it 'out without arguments (title-case)', ->
punch = Punch.parse @user, 'Out', 'out'
expect(punch).to.have.property 'mode', 'out'
expect(punch).to.have.deep.property 'times[0]'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in with an existing project', ->
punch = Punch.parse @user, "in ##{@projectName}", 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch).to.have.deep.property 'projects[0]'
expect(punch).to.have.deep.property 'projects[0].name', @projectName
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'out with two existing projects', ->
punch = Punch.parse @user,
"out ##{@projectName} ##{@alternateProject}",
'out'
expect(punch).to.have.property 'mode', 'out'
expect(punch).to.have.deep.property 'times[0]'
expect(punch).to.have.deep.property 'projects[0]'
expect(punch).to.have.deep.property 'projects[0].name',
@projectName
expect(punch).to.have.deep.property 'projects[1]'
expect(punch).to.have.deep.property 'projects[1].name',
@alternateProject
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in at a time without a period marker', ->
punch = Punch.parse @user, 'in 9:15', 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
now = moment()
amPm = now.format('A')
expectedTime = moment("9:15 #{amPm}", 'h:mm A')
if expectedTime.isAfter now
if expectedTime.diff(now, 'hours', true) > 6
expectedTime.subtract(12, 'hours')
expect(punch.times[0].format('hh:mm:ss A')).to.equal expectedTime.format('hh:mm:ss A')
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in at a time with a period marker and no space between', ->
punch = Punch.parse @user, 'in 9:15pm', 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch.times[0].format('hh:mm:ss A')).to.equal "09:15:00 PM"
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in at a time with a period marker', ->
punch = Punch.parse @user, 'in 9:15 pm', 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch.times[0].format('hh:mm:ss A')).to.equal "09:15:00 PM"
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in at a full date', ->
punch = Punch.parse @user, 'in 4pm 4/22/2016', 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch.times[0].format('MM/DD/YYYY')).to.equal "04/22/2016"
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
expect(punch.date.format('MM/DD/YYYY')).to.equal "04/22/2016"
it 'out at a time without minutes yesterday', ->
punch = Punch.parse @user, 'out 7pm yesterday', 'out'
expect(punch).to.have.property 'mode', 'out'
expect(punch).to.have.deep.property 'times[0]'
yesterday = moment().subtract(1, 'days')
expect(punch.times[0].format('MM/DD/YYYY hh:mm:ss A'))
.to.equal "#{yesterday.format('MM/DD/YYYY')} 07:00:00 PM"
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'in at a 24-hour time and an existing project', ->
punch = Punch.parse @user, "in 17:00 ##{@projectName}", 'in'
expect(punch).to.have.property 'mode', 'in'
expect(punch).to.have.deep.property 'times[0]'
expect(punch.times[0].format('hh:mm:ss A')).to.equal "05:00:00 PM"
expect(punch).to.have.deep.property 'projects[0]'
expect(punch).to.have.deep.property 'projects[0].name',
@projectName
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'append time block to punch', ->
punch = Punch.parse @user, '1.5 hours'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 1.5
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'punch time block on day', ->
punch = Punch.parse @user, '15 hours on 4/22'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 15
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
expect(punch.date.format('MM/DD/YYYY')).to.equal "04/22/2016"
it 'append time block to punch', ->
punch = Punch.parse @user, '.5 hours'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 0.5
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'append time block to punch', ->
punch = Punch.parse @user, '0.5 hours'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 0.5
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'append time block to punch', ->
punch = Punch.parse @user, '0.5 hour'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 0.5
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'append time block to punch', ->
punch = Punch.parse @user, '1 hour'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 1
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'append time block to yesterday\'s punch', ->
punch = Punch.parse @user, '2 hours yesterday'
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 2
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it "append time block to Tuesday\'s punch
and assign it to an existing project", ->
punch = Punch.parse @user, "3.25 hours tuesday ##{@projectName}"
expect(punch).to.have.property 'mode', 'none'
expect(punch).to.have.deep.property 'times.block', 3.25
expect(punch).to.have.deep.property 'projects[0]'
expect(punch).to.have.deep.property 'projects[0].name',
@projectName
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'flag today as vacation', ->
punch = Punch.parse @user, 'vacation today', 'vacation'
expect(punch).to.have.property 'mode', 'vacation'
expect(punch).to.have.property 'times'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'flag half of today as sick', ->
punch = Punch.parse @user, 'sick half-day', 'sick'
expect(punch).to.have.property 'mode', 'sick'
expect(punch).to.have.property 'times'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'flag half of yesterday as vacation', ->
punch = Punch.parse @user,
'vacation half-day yesterday',
'vacation'
expect(punch).to.have.property 'mode', 'vacation'
expect(punch).to.have.property 'times'
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'flag a date range as sick', ->
punch = Punch.parse @user, 'sick Jul 6-8', 'sick'
expect(punch).to.have.property 'mode', 'sick'
expect(punch).to.have.property 'times'
expect(punch).to.have.deep.property 'times.length', 2
expect(punch.elapsed).to.equal 33
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
it 'flag a date range as vacation', ->
punch = Punch.parse @user, 'vacation 1/28 - 2/4', 'vacation'
expect(punch).to.have.property 'mode', 'vacation'
expect(punch).to.have.property 'times'
expect(punch).to.have.deep.property 'times.length', 2
expect(punch.elapsed).to.equal 72
expect(punch).to.have.property 'projects'
expect(punch.projects).to.be.empty
expect(punch).to.have.property 'notes'
expect(punch.notes).to.be.empty
describe '#out(punch)', ->
beforeEach ->
zone = 'America/New_York'
now = moment.tz zone
start = moment.tz({year: now.year(), month: now.month(), day: now.date(), hour: 7}, zone)
end = moment.tz({year: now.year(), month: now.month(), day: now.date(), hour: 18}, zone)
timetable = new Timetable(start, end, zone)
timetable.setVacation(13, 0)
timetable.setSick(5, 0)
timetable.setUnpaid(0)
timetable.setLogged(0)
timetable.setAverageLogged(0)
@user = new User('PI:NAME:<NAME>END_PI', 'aaronsky', true, timetable)
it 'should modify the punch to an out punch', ->
[start, end] = @user.activeHours()
punch = Punch.parse @user,
"in #{start.format('hh:mma')} #production", 'in'
outPunch = Punch.parse @user,
"out #{end.format('hh:mma')} #camp-fangamer", 'out'
punch.out outPunch
expect(punch.times).to.have.lengthOf 2
expect(punch.times[0].format()).to.equal start.format()
expect(punch.times[1].format()).to.equal end.format()
expect(punch.projects).to.have.lengthOf 2
expect(punch).to.have.deep.property 'projects[0].name',
'production'
expect(punch).to.have.deep.property 'projects[1].name',
'camp-fangamer'
describe '#toRawRow(name)', ->
beforeEach ->
start = moment({day: 3, hour: 7})
end = moment({day: 3, hour: 18})
timetable = new Timetable(start, end, moment.tz.zone('America/New_York'))
timetable.setVacation(13, 0)
timetable.setSick(5, 0)
timetable.setUnpaid(0)
timetable.setLogged(0)
timetable.setAverageLogged(0)
name = 'PI:NAME:<NAME>END_PI'
@user = new User(name, 'aaronsky', true, timetable)
it 'should return a raw object for use with Sheet', ->
punch = Punch.parse @user, 'in', 'in'
raw = punch.toRawRow @user.name
expect(raw).to.exist
it 'should return a raw object for an in punch', ->
punch = Punch.parse @user, 'in', 'in'
raw = punch.toRawRow @user.name
expect(raw).to.exist
it 'should return a raw object for an out punch', ->
punch = Punch.parse @user, 'in 9:00am', 'in'
outPunch = Punch.parse @user, 'out 10:30am', 'out'
punch.out outPunch
raw = punch.toRawRow @user.name
expect(raw).to.exist
describe '#assignRow', ->
beforeEach ->
start = moment({day: 3, hour: 7})
end = moment({day: 3, hour: 18})
timetable = new Timetable(start, end, moment.tz.zone('America/New_York'))
timetable.setVacation(13, 0)
timetable.setSick(5, 0)
timetable.setUnpaid(0)
timetable.setLogged(0)
timetable.setAverageLogged(0)
@user = new User('PI:NAME:<NAME>END_PI', 'aaronsky', true, timetable)
it 'should not assign a row if no parameter is passed', ->
punch = Punch.parse @user, 'in', 'in'
punch.assignRow()
expect(punch.row).to.not.exist
it 'should not assign a row if an invalid row is passed', ->
punch = Punch.parse @user, 'in', 'in'
punch.assignRow({})
expect(punch.row).to.not.exist
it 'should assign a row if a row is passed in', ->
punch = Punch.parse @user, 'in', 'in'
punch.assignRow({
save: () -> ,
del: () ->
})
expect(punch.row).to.exist
describe '#isValid(user)', ->
beforeEach ->
start = moment({day: 3, hour: 7})
end = moment({day: 3, hour: 18})
timetable = new Timetable(start, end, moment.tz.zone('America/New_York'))
timetable.setVacation(13, 0)
timetable.setSick(5, 0)
timetable.setUnpaid(0)
timetable.setLogged(0)
timetable.setAverageLogged(0)
@user = new User('PI:NAME:<NAME>END_PI', 'aaronsky', true, timetable)
it 'should return a failure reason for a repetitive in punch', ->
@user.punches.push(Punch.parse(@user, 'in', 'in'))
punch = Punch.parse @user, 'in', 'in'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return a failure reason for an in punch dated yesterday', ->
punch = Punch.parse @user, 'in yesterday', 'in'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return a failure reason for an non-salary user punching unpaid time', ->
@user.salary = false
punch = Punch.parse @user, 'unpaid 9:50-10:00', 'unpaid'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return a failure reason for a vacation punch that exceeds available vacation time', ->
@user.timetable.setVacation(5, 2)
punch = Punch.parse @user, 'vacation today', 'vacation'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return a failure reason for a sick punch that exceeds available sick time', ->
@user.timetable.setSick(5, 2)
punch = Punch.parse @user, 'sick today', 'sick'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return a failure reason for a vacation/sick/unpaid punch that isn\'t divisible by 4', ->
punch = Punch.parse @user, 'vacation 9:50-10:00', 'vacation'
expect(punch.isValid(@user)).to.be.instanceof.String
punch = Punch.parse @user, 'sick 9:50-10:00', 'sick'
expect(punch.isValid(@user)).to.be.instanceof.String
punch = Punch.parse @user, 'unpaid 9:50-10:00', 'unpaid'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return a failure reason for any punch dated older than 7 days', ->
punch = Punch.parse @user, 'in Jul 6-8', 'in'
expect(punch.isValid(@user)).to.be.instanceof.String
it 'should return true for a valid punch', ->
punch = Punch.parse @user, 'in', 'in'
expect(punch.isValid(@user)).to.be.true
|
[
{
"context": " runs ->\n findView.findEditor.setText 'kitten'\n editorView.trigger 'find-and-replace:sho",
"end": 1951,
"score": 0.9709285497665405,
"start": 1945,
"tag": "NAME",
"value": "kitten"
},
{
"context": "osition([2,0])\n findView.findEditor.setText 'notinthefilebro'\n findView.findEditor.focus()\n\n findVie",
"end": 10686,
"score": 0.6514767408370972,
"start": 10671,
"tag": "USERNAME",
"value": "notinthefilebro"
}
] | spec/find-view-spec.coffee | abe33/find-and-replace | 1 | _ = require 'underscore-plus'
{$, EditorView, WorkspaceView} = require 'atom'
path = require 'path'
describe 'FindView', ->
[editorView, editor, findView, activationPromise] = []
beforeEach ->
spyOn(atom, 'beep')
atom.workspaceView = new WorkspaceView()
atom.project.setPath(path.join(__dirname, 'fixtures'))
waitsForPromise ->
atom.workspace.open('sample.js')
runs ->
atom.workspaceView.attachToDom()
editorView = atom.workspaceView.getActiveView()
editor = editorView.getEditor()
activationPromise = atom.packages.activatePackage("find-and-replace").then ({mainModule}) ->
mainModule.createFindView()
{findView} = mainModule
describe "when find-and-replace:show is triggered", ->
it "attaches FindView to the root view", ->
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
expect(atom.workspaceView.find('.find-and-replace')).toExist()
it "populates the findEditor with selection when there is a selection", ->
editor.setSelectedBufferRange([[2, 8], [2, 13]])
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
expect(atom.workspaceView.find('.find-and-replace')).toExist()
expect(findView.findEditor.getText()).toBe('items')
findView.findEditor.setText('')
editor.setSelectedBufferRange([[2, 14], [2, 20]])
editorView.trigger 'find-and-replace:show'
expect(atom.workspaceView.find('.find-and-replace')).toExist()
expect(findView.findEditor.getText()).toBe('length')
it "does not change the findEditor text when there is no selection", ->
editor.setSelectedBufferRange([[2, 8], [2, 8]])
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
findView.findEditor.setText 'kitten'
editorView.trigger 'find-and-replace:show'
expect(findView.findEditor.getText()).toBe('kitten')
it "does not change the findEditor text when there is a multiline selection", ->
editor.setSelectedBufferRange([[2, 8], [3, 12]])
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
expect(atom.workspaceView.find('.find-and-replace')).toExist()
expect(findView.findEditor.getText()).toBe('')
describe "when find-and-replace:toggle is triggered", ->
it "toggles the visibility of the FindView", ->
atom.workspaceView.trigger 'find-and-replace:toggle'
waitsForPromise ->
activationPromise
runs ->
expect(atom.workspaceView.find('.find-and-replace')).toExist()
atom.workspaceView.trigger 'find-and-replace:toggle'
expect(atom.workspaceView.find('.find-and-replace')).not.toExist()
describe "when FindView's replace editor is visible", ->
it "keeps the replace editor visible when find-and-replace:show is triggered", ->
editorView.trigger 'find-and-replace:show-replace'
waitsForPromise ->
activationPromise
runs ->
editorView.trigger 'find-and-replace:show'
expect(findView.replaceEditor).toBeVisible()
describe "core:cancel", ->
beforeEach ->
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
findView.findEditor.setText 'items'
findView.findEditor.trigger 'core:confirm'
findView.focus()
describe "when core:cancel is triggered on the find view", ->
it "detaches from the workspace view", ->
$(document.activeElement).trigger 'core:cancel'
expect(atom.workspaceView.find('.find-and-replace')).not.toExist()
it "removes highlighted matches", ->
findResultsView = editorView.find('.search-results')
$(document.activeElement).trigger 'core:cancel'
expect(findResultsView.parent()).not.toExist()
describe "when core:cancel is triggered on an empty pane", ->
it "detaches from the workspace view", ->
atom.workspaceView.getActivePaneView().focus()
$(atom.workspaceView.getActivePaneView()).trigger 'core:cancel'
expect(atom.workspaceView.find('.find-and-replace')).not.toExist()
describe "when core:cancel is triggered on an editor", ->
it "detaches from the workspace view", ->
waitsForPromise ->
atom.workspace.open()
runs ->
$(atom.workspaceView.getActiveView().hiddenInput).trigger 'core:cancel'
expect(atom.workspaceView.find('.find-and-replace')).not.toExist()
describe "when core:cancel is triggered on a mini editor", ->
it "leaves the find view attached", ->
editorView = new EditorView(mini: true)
atom.workspaceView.appendToTop(editorView)
editorView.focus()
$(editorView.hiddenInput).trigger 'core:cancel'
expect(atom.workspaceView.find('.find-and-replace')).toExist()
describe "serialization", ->
it "serializes find and replace history", ->
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
findView.findEditor.setText("items")
findView.replaceEditor.setText("cat")
findView.replaceAll()
findView.findEditor.setText("sort")
findView.replaceEditor.setText("dog")
findView.replaceNext()
findView.findEditor.setText("shift")
findView.replaceEditor.setText("ok")
findView.findNext(false)
atom.packages.deactivatePackage("find-and-replace")
activationPromise = atom.packages.activatePackage("find-and-replace").then ({mainModule}) ->
mainModule.createFindView()
{findView} = mainModule
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
findView.findEditor.trigger('core:move-up')
expect(findView.findEditor.getText()).toBe 'shift'
findView.findEditor.trigger('core:move-up')
expect(findView.findEditor.getText()).toBe 'sort'
findView.findEditor.trigger('core:move-up')
expect(findView.findEditor.getText()).toBe 'items'
findView.replaceEditor.trigger('core:move-up')
expect(findView.replaceEditor.getText()).toBe 'dog'
findView.replaceEditor.trigger('core:move-up')
expect(findView.replaceEditor.getText()).toBe 'cat'
it "serializes find options ", ->
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
expect(findView.caseOptionButton).not.toHaveClass 'selected'
expect(findView.regexOptionButton).not.toHaveClass 'selected'
expect(findView.selectionOptionButton).not.toHaveClass 'selected'
findView.caseOptionButton.click()
findView.regexOptionButton.click()
findView.selectionOptionButton.click()
expect(findView.caseOptionButton).toHaveClass 'selected'
expect(findView.regexOptionButton).toHaveClass 'selected'
expect(findView.selectionOptionButton).toHaveClass 'selected'
atom.packages.deactivatePackage("find-and-replace")
activationPromise = atom.packages.activatePackage("find-and-replace").then ({mainModule}) ->
mainModule.createFindView()
{findView} = mainModule
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
expect(findView.caseOptionButton).toHaveClass 'selected'
expect(findView.regexOptionButton).toHaveClass 'selected'
expect(findView.selectionOptionButton).toHaveClass 'selected'
describe "finding", ->
beforeEach ->
atom.config.set('find-and-replace.focusEditorAfterSearch', false)
editor.setCursorBufferPosition([2,0])
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
findView.findEditor.setText 'items'
findView.findEditor.trigger 'core:confirm'
describe "when the find string contains an escaped char", ->
beforeEach ->
editor.setText("\t\n\\t\\\\")
editor.setCursorBufferPosition([0,0])
describe "when regex seach is enabled", ->
beforeEach ->
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
it "finds a backslash", ->
findView.findEditor.setText('\\\\')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[1, 0], [1, 1]]
it "finds a newline", ->
findView.findEditor.setText('\\n')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[0, 1], [1, 0]]
it "finds a tab character", ->
findView.findEditor.setText('\\t')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[0, 0], [0, 1]]
describe "when regex seach is disabled", ->
it "finds the literal backslash t", ->
findView.findEditor.setText('\\t')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[1, 0], [1, 2]]
it "finds a backslash", ->
findView.findEditor.setText('\\')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[1, 0], [1, 1]]
it "finds two backslashes", ->
findView.findEditor.setText('\\\\')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[1, 2], [1, 4]]
it "doesn't find when escaped", ->
findView.findEditor.setText('\\\\t')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[0, 0], [0, 0]]
describe "when focusEditorAfterSearch is set", ->
beforeEach ->
atom.config.set('find-and-replace.focusEditorAfterSearch', true)
findView.findEditor.trigger 'core:confirm'
it "selects the first match following the cursor and correctly focuses the editor", ->
expect(findView.resultCounter.text()).toEqual('3 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[2, 34], [2, 39]]
expect(editorView).toHaveFocus()
it "doesn't change the selection, beeps if there are no matches and keeps focus on the find view", ->
editor.setCursorBufferPosition([2,0])
findView.findEditor.setText 'notinthefilebro'
findView.findEditor.focus()
findView.findEditor.trigger 'core:confirm'
expect(editor.getCursorBufferPosition()).toEqual [2,0]
expect(atom.beep).toHaveBeenCalled()
expect(findView).toHaveFocus()
expect(findView.descriptionLabel.text()).toEqual "No results found for 'notinthefilebro'"
describe "updating the descriptionLabel", ->
it "properly updates the info message", ->
findView.findEditor.setText 'item'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel.text()).toEqual "6 results found for 'item'"
findView.findEditor.setText 'notinthefilenope'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel.text()).toEqual "No results found for 'notinthefilenope'"
findView.findEditor.setText 'item'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel.text()).toEqual "6 results found for 'item'"
findView.findEditor.setText ''
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel.text()).toContain "Find in Current Buffer"
describe "when there is a find-error", ->
beforeEach ->
editor.setCursorBufferPosition([2,0])
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
it "displays the error", ->
findView.findEditor.setText 'i[t'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel).toHaveClass 'text-error'
expect(findView.descriptionLabel.text()).toContain 'Invalid regular expression'
it "will be reset when there is no longer an error", ->
findView.findEditor.setText 'i[t'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel).toHaveClass 'text-error'
findView.findEditor.setText ''
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel).not.toHaveClass 'text-error'
expect(findView.descriptionLabel.text()).toContain "Find in Current Buffer"
findView.findEditor.setText 'item'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel).not.toHaveClass 'text-error'
expect(findView.descriptionLabel.text()).toContain "6 results"
it "selects the first match following the cursor", ->
expect(findView.resultCounter.text()).toEqual('2 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[2, 8], [2, 13]]
findView.findEditor.trigger 'core:confirm'
expect(findView.resultCounter.text()).toEqual('3 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[2, 34], [2, 39]]
expect(findView.findEditor).toHaveFocus()
it "selects the next match when the next match button is pressed", ->
findView.nextButton.click()
expect(findView.resultCounter.text()).toEqual('3 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[2, 34], [2, 39]]
it "selects the next match when the 'find-and-replace:find-next' event is triggered and correctly focuses the editor", ->
expect(findView).toHaveFocus()
editorView.trigger('find-and-replace:find-next')
expect(findView.resultCounter.text()).toEqual('3 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[2, 34], [2, 39]]
expect(editorView).toHaveFocus()
it "selects the previous match before the cursor when the 'find-and-replace:show-previous' event is triggered", ->
expect(findView.resultCounter.text()).toEqual('2 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[2, 8], [2, 13]]
findView.findEditor.trigger 'find-and-replace:show-previous'
expect(findView.resultCounter.text()).toEqual('1 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[1, 22], [1, 27]]
expect(findView.findEditor).toHaveFocus()
it "will re-run search if 'find-and-replace:find-next' is triggered after changing the findEditor's text", ->
findView.findEditor.setText 'sort'
findView.findEditor.trigger 'find-and-replace:find-next'
expect(findView.resultCounter.text()).toEqual('3 of 5')
expect(editor.getSelectedBufferRange()).toEqual [[8, 11], [8, 15]]
it "'find-and-replace:find-next' adds to the findEditor's history", ->
findView.findEditor.setText 'sort'
findView.findEditor.trigger 'find-and-replace:find-next'
expect(findView.resultCounter.text()).toEqual('3 of 5')
findView.findEditor.setText 'nope'
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'sort'
it "selects the previous match when the previous match button is pressed", ->
findView.previousButton.click()
expect(findView.resultCounter.text()).toEqual('1 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[1, 27], [1, 22]]
it "selects the previous match when the 'find-and-replace:find-previous' event is triggered and correctly focuses the editor", ->
expect(findView).toHaveFocus()
editorView.trigger('find-and-replace:find-previous')
expect(findView.resultCounter.text()).toEqual('1 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[1, 27], [1, 22]]
expect(editorView).toHaveFocus()
it "will re-run search if 'find-and-replace:find-previous' is triggered after changing the findEditor's text", ->
findView.findEditor.setText 'sort'
findView.findEditor.trigger 'find-and-replace:find-previous'
expect(findView.resultCounter.text()).toEqual('2 of 5')
expect(editor.getSelectedBufferRange()).toEqual [[1, 6], [1, 10]]
it "replaces results counter with number of results found when user moves the cursor", ->
editor.moveCursorDown()
expect(findView.resultCounter.text()).toBe '6 found'
it "replaces results counter x of y text when user selects a marked range", ->
editor.moveCursorDown()
editor.setSelectedBufferRange([[2, 34], [2, 39]])
expect(findView.resultCounter.text()).toEqual('3 of 6')
it "places the selected text into the find editor when find-and-replace:set-find-pattern is triggered", ->
editor.setSelectedBufferRange([[1,6],[1,10]])
atom.workspaceView.trigger 'find-and-replace:use-selection-as-find-pattern'
expect(findView.findEditor.getText()).toBe 'sort'
expect(editor.getSelectedBufferRange()).toEqual [[1,6],[1,10]]
atom.workspaceView.trigger 'find-and-replace:find-next'
expect(editor.getSelectedBufferRange()).toEqual [[8,11],[8,15]]
it "does not highlight the found text when the find view is hidden", ->
findView.findEditor.trigger 'core:cancel'
findView.findEditor.trigger 'find-and-replace:find-next'
findResultsView = editorView.find('.search-results')
expect(findResultsView.parent()).not.toExist()
describe "when the active pane item changes", ->
beforeEach ->
editor.setSelectedBufferRange([[0, 0], [0, 0]])
describe "when a new edit session is activated", ->
it "reruns the search on the new edit session", ->
waitsForPromise ->
atom.workspace.open('sample.coffee')
runs ->
editor = atom.workspace.getActivePaneItem()
expect(findView.resultCounter.text()).toEqual('7 found')
expect(editor.getSelectedBufferRange()).toEqual [[0, 0], [0, 0]]
it "initially highlights the found text in the new edit session", ->
expect(editorView.find('.highlight.find-result')).toHaveLength 6
waitsForPromise ->
atom.workspace.open('sample.coffee')
runs ->
# old editor has no more results
expect(editorView.find('.highlight.find-result')).toHaveLength 0
# new one has 7 results
expect(atom.workspaceView.getActiveView().find('.highlight.find-result')).toHaveLength 7
it "highlights the found text in the new edit session when find next is triggered", ->
waitsForPromise ->
atom.workspace.open('sample.coffee')
runs ->
findView.findEditor.trigger 'find-and-replace:find-next'
expect(atom.workspaceView.getActiveView().find('.highlight.find-result')).toHaveLength 6
expect(atom.workspaceView.getActiveView().find('.highlight.current-result')).toHaveLength 1
describe "when all active pane items are closed", ->
it "updates the result count", ->
editorView.trigger 'core:close'
expect(findView.resultCounter.text()).toEqual('no results')
describe "when the active pane item is not an edit session", ->
[anotherOpener] = []
beforeEach ->
anotherOpener = (pathToOpen, options) -> $('another')
atom.workspace.registerOpener(anotherOpener)
afterEach ->
atom.workspace.unregisterOpener(anotherOpener)
it "updates the result view", ->
waitsForPromise ->
atom.workspace.open "another"
runs ->
expect(findView.resultCounter.text()).toEqual('no results')
it "removes all highlights", ->
findResultsView = editorView.find('.search-results')
waitsForPromise ->
atom.workspace.open "another"
runs ->
expect(findResultsView.children()).toHaveLength 0
describe "when a new edit session is activated on a different pane", ->
it "initially highlights all the sample.js results", ->
expect(editorView.find('.find-result')).toHaveLength 6
it "reruns the search on the new editSession", ->
newEditor = null
waitsForPromise ->
atom.project.open('sample.coffee').then (o) -> newEditor = o
runs ->
newEditorView = editorView.getPane().splitRight(newEditor).activeView
expect(findView.resultCounter.text()).toEqual('7 found')
expect(newEditorView.getEditor().getSelectedBufferRange()).toEqual [[0, 0], [0, 0]]
findView.findEditor.trigger 'find-and-replace:find-next'
expect(findView.resultCounter.text()).toEqual('1 of 7')
expect(newEditorView.getEditor().getSelectedBufferRange()).toEqual [[1, 9], [1, 14]]
it "highlights the found text in the new edit session (and removes the highlights from the other)", ->
[newEditor, newEditorView] = []
waitsForPromise ->
atom.project.open('sample.coffee').then (o) -> newEditor = o
runs ->
newEditorView = editorView.getPane().splitRight(newEditor)
runs ->
# old editor has no more results
expect(editorView.find('.find-result')).toHaveLength 0
# new one has 7 results
expect(newEditorView.find('.find-result')).toHaveLength 7
it "will still highlight results after the split pane has been destroyed", ->
[newEditor, newEditorView] = []
waitsForPromise ->
atom.project.open('sample.coffee').then (o) -> newEditor = o
runs ->
newEditorView = editorView.getPane().splitRight(newEditor)
expect(newEditorView.find('.find-result')).toHaveLength 7
newEditorView.focus()
newEditorView.trigger('core:close')
editorView.focus()
runs ->
expect(editorView.find('.find-result')).toHaveLength 6
describe "when the buffer contents change", ->
it "re-runs the search", ->
findResultsView = editorView.find('.search-results')
editor.setSelectedBufferRange([[1, 26], [1, 27]])
editor.insertText("")
window.advanceClock(1000)
expect(findView.resultCounter.text()).toEqual('5 found')
editor.insertText("s")
window.advanceClock(1000)
expect(findView.resultCounter.text()).toEqual('6 found')
it "does not beep if no matches were found", ->
editor.setCursorBufferPosition([2,0])
findView.findEditor.setText 'notinthefilebro'
findView.findEditor.trigger 'core:confirm'
atom.beep.reset()
editor.insertText("blah blah")
expect(atom.beep).not.toHaveBeenCalled()
describe "when finding within a selection", ->
beforeEach ->
editor.setSelectedBufferRange [[2, 0], [4, 0]]
it "toggles find within a selction via and event and only finds matches within the selection", ->
findView.findEditor.setText 'items'
findView.findEditor.trigger 'find-and-replace:toggle-selection-option'
expect(editor.getSelectedBufferRange()).toEqual [[2, 8], [2, 13]]
expect(findView.resultCounter.text()).toEqual('1 of 3')
it "toggles find within a selction via and button and only finds matches within the selection", ->
findView.findEditor.setText 'items'
findView.selectionOptionButton.click()
expect(editor.getSelectedBufferRange()).toEqual [[2, 8], [2, 13]]
expect(findView.resultCounter.text()).toEqual('1 of 3')
describe "when regex is toggled", ->
it "toggles regex via an event and finds text matching the pattern", ->
editor.setCursorBufferPosition([2,0])
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
findView.findEditor.setText 'i[t]em+s'
expect(editor.getSelectedBufferRange()).toEqual [[2, 8], [2, 13]]
it "toggles regex via a button and finds text matching the pattern", ->
editor.setCursorBufferPosition([2,0])
findView.regexOptionButton.click()
findView.findEditor.setText 'i[t]em+s'
expect(editor.getSelectedBufferRange()).toEqual [[2, 8], [2, 13]]
it "re-runs the search using the new find text when toggled", ->
editor.setCursorBufferPosition([1,0])
findView.findEditor.setText 's(o)rt'
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
expect(editor.getSelectedBufferRange()).toEqual [[1, 6], [1, 10]]
describe "when an invalid regex is entered", ->
it "displays an error", ->
editor.setCursorBufferPosition([2,0])
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
findView.findEditor.setText 'i[t'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel).toHaveClass 'text-error'
describe "when case sensitivity is toggled", ->
beforeEach ->
editor.setText "-----\nwords\nWORDs\n"
editor.setCursorBufferPosition([0,0])
it "toggles case sensitivity via an event and finds text matching the pattern", ->
findView.findEditor.setText 'WORDs'
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[1, 0], [1, 5]]
editor.setCursorBufferPosition([0,0])
findView.findEditor.trigger 'find-and-replace:toggle-case-option'
expect(editor.getSelectedBufferRange()).toEqual [[2, 0], [2, 5]]
it "toggles case sensitivity via a button and finds text matching the pattern", ->
findView.findEditor.setText 'WORDs'
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[1, 0], [1, 5]]
editor.setCursorBufferPosition([0,0])
findView.caseOptionButton.click()
expect(editor.getSelectedBufferRange()).toEqual [[2, 0], [2, 5]]
describe "highlighting search results", ->
resultPosition = (result) ->
{top: result.children()[0].style.top, left: result.children()[0].style.left}
it "only highlights matches", ->
expect(editorView.find('.find-result')).toHaveLength 5
findView.findEditor.setText 'notinthefilebro'
findView.findEditor.trigger 'core:confirm'
runs ->
expect(editorView.find('.find-result')).toHaveLength 0
it "adds a class to the current match indicating it is the current match", ->
position = (result) ->
{top: result.children()[0].style.top, left: result.children()[0].style.left}
firstResult = editorView.find('.current-result')
firstPosition = resultPosition(firstResult)
expect(firstResult).toHaveLength 1
expect(editorView.find('.find-result')).toHaveLength 5
findView.findEditor.trigger 'core:confirm'
findView.findEditor.trigger 'core:confirm'
nextResult = editorView.find('.current-result')
nextPosition = resultPosition(nextResult)
expect(nextResult).toHaveLength 1
expect(nextPosition).not.toEqual firstPosition
findView.findEditor.trigger 'find-and-replace:find-previous'
findView.findEditor.trigger 'find-and-replace:find-previous'
originalResult = editorView.find('.current-result')
originalPosition = resultPosition(originalResult)
expect(originalResult).toHaveLength 1
expect(originalPosition).toEqual firstPosition
it "adds a class to the result when the current selection equals the result's range", ->
originalResult = editorView.find('.current-result')
originalPosition = resultPosition(originalResult)
expect(originalResult).toHaveLength 1
editor.setSelectedBufferRange([[5, 16], [5, 20]])
expect(editorView.find('.current-result')).toHaveLength 0
editor.setSelectedBufferRange([[5, 16], [5, 21]])
newResult = editorView.find('.current-result')
newPosition = resultPosition(newResult)
expect(newResult).toHaveLength 1
expect(newPosition).not.toBe originalPosition
describe "when user types in the find editor", ->
advance = ->
advanceClock(findView.findEditor.getEditor().getBuffer().stoppedChangingDelay + 1)
beforeEach ->
findView.findEditor.focus()
it "updates the search results", ->
expect(findView.descriptionLabel.text()).toContain "6 results"
findView.findEditor.setText 'why do I need these 2 lines? The editor does not trigger contents-modified without them'
advance()
findView.findEditor.setText ''
advance()
expect(findView.descriptionLabel.text()).toContain "Find in Current Buffer"
expect(findView).toHaveFocus()
findView.findEditor.setText 'sort'
advance()
expect(findView.descriptionLabel.text()).toContain "5 results"
expect(findView).toHaveFocus()
findView.findEditor.setText 'items'
advance()
expect(findView.descriptionLabel.text()).toContain "6 results"
expect(findView).toHaveFocus()
describe "when another find is called", ->
previousMarkers = null
beforeEach ->
previousMarkers = _.clone(editor.getMarkers())
it "clears existing markers for another search", ->
findView.findEditor.setText('notinthefile')
findView.findEditor.trigger 'core:confirm'
expect(editor.getMarkers().length).toEqual 1
it "clears existing markers for an empty search", ->
findView.findEditor.setText('')
findView.findEditor.trigger 'core:confirm'
expect(editor.getMarkers().length).toEqual 1
describe "replacing", ->
beforeEach ->
editor.setCursorBufferPosition([2,0])
editorView.trigger 'find-and-replace:show-replace'
waitsForPromise ->
activationPromise
runs ->
findView.findEditor.setText('items')
findView.replaceEditor.setText('cats')
describe "when the replacement string contains an escaped char", ->
describe "when the regex option is chosen", ->
beforeEach ->
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
it "inserts tabs and newlines", ->
findView.replaceEditor.setText('\\t\\n')
findView.replaceEditor.trigger 'core:confirm'
expect(editor.getText()).toMatch(/\t\n/)
it "doesn't insert a escaped char if there are multiple backslashs in front of the char", ->
findView.replaceEditor.setText('\\\\t\\\t')
findView.replaceEditor.trigger 'core:confirm'
expect(editor.getText()).toMatch(/\\t\\\t/)
describe "when in normal mode", ->
it "inserts backslach n and t", ->
findView.replaceEditor.setText('\\t\\n')
findView.replaceEditor.trigger 'core:confirm'
expect(editor.getText()).toMatch(/\\t\\n/)
it "inserts carriage returns", ->
textWithCarriageReturns = editor.getText().replace(/\n/g, "\r")
editor.setText(textWithCarriageReturns)
findView.replaceEditor.setText('\\t\\r')
findView.replaceEditor.trigger 'core:confirm'
expect(editor.getText()).toMatch(/\\t\\r/)
describe "replace next", ->
describe "when core:confirm is triggered", ->
it "replaces the match after the cursor and selects the next match", ->
findView.replaceEditor.trigger 'core:confirm'
expect(findView.resultCounter.text()).toEqual('2 of 5')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return items;"
expect(editor.getSelectedBufferRange()).toEqual [[2, 33], [2, 38]]
it "replaceEditor maintains focus after core:confirm is run", ->
findView.replaceEditor.focus()
findView.replaceEditor.trigger 'core:confirm'
expect(findView.replaceEditor).toHaveFocus()
it "replaces the _current_ match and selects the next match", ->
findView.findEditor.trigger 'core:confirm'
editor.setSelectedBufferRange([[2, 8], [2, 13]])
expect(findView.resultCounter.text()).toEqual('2 of 6')
findView.replaceEditor.trigger 'core:confirm'
expect(findView.resultCounter.text()).toEqual('2 of 5')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return items;"
expect(editor.getSelectedBufferRange()).toEqual [[2, 33], [2, 38]]
findView.replaceEditor.trigger 'core:confirm'
expect(findView.resultCounter.text()).toEqual('2 of 4')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return cats;"
expect(editor.getSelectedBufferRange()).toEqual [[3, 16], [3, 21]]
describe "when the replace next button is pressed", ->
it "replaces the match after the cursor and selects the next match", ->
$('.find-and-replace .btn-next').click()
expect(findView.resultCounter.text()).toEqual('2 of 5')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return items;"
expect(editor.getSelectedBufferRange()).toEqual [[2, 33], [2, 38]]
describe "when the 'find-and-replace:replace-next' event is triggered", ->
it "replaces the match after the cursor and selects the next match", ->
editorView.trigger 'find-and-replace:replace-next'
expect(findView.resultCounter.text()).toEqual('2 of 5')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return items;"
expect(editor.getSelectedBufferRange()).toEqual [[2, 33], [2, 38]]
describe "replace previous", ->
describe "when button is clicked", ->
it "replaces the match after the cursor and selects the previous match", ->
findView.findEditor.trigger 'core:confirm'
findView.replacePreviousButton.click()
expect(findView.resultCounter.text()).toEqual('1 of 5')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return items;"
expect(editor.getSelectedBufferRange()).toEqual [[1, 22], [1, 27]]
describe "when command is triggered", ->
it "replaces the match after the cursor and selects the previous match", ->
findView.findEditor.trigger 'core:confirm'
findView.trigger 'find-and-replace:replace-previous'
expect(findView.resultCounter.text()).toEqual('1 of 5')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return items;"
expect(editor.getSelectedBufferRange()).toEqual [[1, 22], [1, 27]]
describe "replace all", ->
describe "when the replace all button is pressed", ->
it "replaces all matched text", ->
$('.find-and-replace .btn-all').click()
expect(findView.resultCounter.text()).toEqual('no results')
expect(editor.getText()).not.toMatch /items/
expect(editor.getText().match(/\bcats\b/g)).toHaveLength 6
expect(editor.getSelectedBufferRange()).toEqual [[2, 0], [2, 0]]
it "all changes are undoable in one transaction", ->
$('.find-and-replace .btn-all').click()
editor.undo()
expect(editor.getText()).not.toMatch /\bcats\b/g
describe "when the 'find-and-replace:replace-all' event is triggered", ->
it "replaces all matched text", ->
editorView.trigger 'find-and-replace:replace-all'
expect(findView.resultCounter.text()).toEqual('no results')
expect(editor.getText()).not.toMatch /items/
expect(editor.getText().match(/\bcats\b/g)).toHaveLength 6
expect(editor.getSelectedBufferRange()).toEqual [[2, 0], [2, 0]]
describe "replacement patterns", ->
describe "when the regex option is true", ->
it "replaces $1, $2, etc... with substring matches", ->
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
findView.findEditor.setText('(items)([\\.;])')
findView.replaceEditor.setText('$2$1')
editorView.trigger 'find-and-replace:replace-all'
expect(editor.getText()).toMatch /;items/
expect(editor.getText()).toMatch /\.items/
describe "when the regex option is false", ->
it "replaces the matches with without any regex subsitions", ->
findView.findEditor.setText('items')
findView.replaceEditor.setText('$&cats')
editorView.trigger 'find-and-replace:replace-all'
expect(editor.getText()).not.toMatch /items/
expect(editor.getText().match(/\$&cats\b/g)).toHaveLength 6
describe "history", ->
beforeEach ->
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
describe "when there is no history", ->
it "retains unsearched text", ->
text = 'something I want to search for but havent yet'
findView.findEditor.setText(text)
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual ''
findView.findEditor.trigger 'core:move-down'
expect(findView.findEditor.getText()).toEqual text
describe "when there is history", ->
[oneRange, twoRange, threeRange] = []
beforeEach ->
editorView.trigger 'find-and-replace:show'
editor.setText("zero\none\ntwo\nthree\n")
findView.findEditor.setText('one')
findView.findEditor.trigger 'core:confirm'
findView.findEditor.setText('two')
findView.findEditor.trigger 'core:confirm'
findView.findEditor.setText('three')
findView.findEditor.trigger 'core:confirm'
it "can navigate the entire history stack", ->
expect(findView.findEditor.getText()).toEqual 'three'
findView.findEditor.trigger 'core:move-down'
expect(findView.findEditor.getText()).toEqual ''
findView.findEditor.trigger 'core:move-down'
expect(findView.findEditor.getText()).toEqual ''
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'three'
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'two'
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'one'
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'one'
findView.findEditor.trigger 'core:move-down'
expect(findView.findEditor.getText()).toEqual 'two'
it "retains the current unsearched text", ->
text = 'something I want to search for but havent yet'
findView.findEditor.setText(text)
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'three'
findView.findEditor.trigger 'core:move-down'
expect(findView.findEditor.getText()).toEqual text
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'three'
findView.findEditor.trigger 'core:move-down'
findView.findEditor.trigger 'core:confirm'
findView.findEditor.trigger 'core:move-down'
expect(findView.findEditor.getText()).toEqual ''
it "adds confirmed patterns to the history", ->
findView.findEditor.setText("cool stuff")
findView.findEditor.trigger 'core:confirm'
findView.findEditor.setText("cooler stuff")
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'cool stuff'
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'three'
describe "when user types in the find editor", ->
advance = ->
advanceClock(findView.findEditor.getEditor().getBuffer().stoppedChangingDelay + 1)
beforeEach ->
findView.findEditor.focus()
it "does not add live searches to the history", ->
expect(findView.descriptionLabel.text()).toContain "1 result"
# I really do not understand why this are necessary...
findView.findEditor.setText 'FIXME: necessary search for some reason??'
advance()
findView.findEditor.setText 'nope'
advance()
expect(findView.descriptionLabel.text()).toContain 'nope'
findView.findEditor.setText 'zero'
advance()
expect(findView.descriptionLabel.text()).toContain "zero"
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'three'
| 52761 | _ = require 'underscore-plus'
{$, EditorView, WorkspaceView} = require 'atom'
path = require 'path'
describe 'FindView', ->
[editorView, editor, findView, activationPromise] = []
beforeEach ->
spyOn(atom, 'beep')
atom.workspaceView = new WorkspaceView()
atom.project.setPath(path.join(__dirname, 'fixtures'))
waitsForPromise ->
atom.workspace.open('sample.js')
runs ->
atom.workspaceView.attachToDom()
editorView = atom.workspaceView.getActiveView()
editor = editorView.getEditor()
activationPromise = atom.packages.activatePackage("find-and-replace").then ({mainModule}) ->
mainModule.createFindView()
{findView} = mainModule
describe "when find-and-replace:show is triggered", ->
it "attaches FindView to the root view", ->
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
expect(atom.workspaceView.find('.find-and-replace')).toExist()
it "populates the findEditor with selection when there is a selection", ->
editor.setSelectedBufferRange([[2, 8], [2, 13]])
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
expect(atom.workspaceView.find('.find-and-replace')).toExist()
expect(findView.findEditor.getText()).toBe('items')
findView.findEditor.setText('')
editor.setSelectedBufferRange([[2, 14], [2, 20]])
editorView.trigger 'find-and-replace:show'
expect(atom.workspaceView.find('.find-and-replace')).toExist()
expect(findView.findEditor.getText()).toBe('length')
it "does not change the findEditor text when there is no selection", ->
editor.setSelectedBufferRange([[2, 8], [2, 8]])
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
findView.findEditor.setText '<NAME>'
editorView.trigger 'find-and-replace:show'
expect(findView.findEditor.getText()).toBe('kitten')
it "does not change the findEditor text when there is a multiline selection", ->
editor.setSelectedBufferRange([[2, 8], [3, 12]])
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
expect(atom.workspaceView.find('.find-and-replace')).toExist()
expect(findView.findEditor.getText()).toBe('')
describe "when find-and-replace:toggle is triggered", ->
it "toggles the visibility of the FindView", ->
atom.workspaceView.trigger 'find-and-replace:toggle'
waitsForPromise ->
activationPromise
runs ->
expect(atom.workspaceView.find('.find-and-replace')).toExist()
atom.workspaceView.trigger 'find-and-replace:toggle'
expect(atom.workspaceView.find('.find-and-replace')).not.toExist()
describe "when FindView's replace editor is visible", ->
it "keeps the replace editor visible when find-and-replace:show is triggered", ->
editorView.trigger 'find-and-replace:show-replace'
waitsForPromise ->
activationPromise
runs ->
editorView.trigger 'find-and-replace:show'
expect(findView.replaceEditor).toBeVisible()
describe "core:cancel", ->
beforeEach ->
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
findView.findEditor.setText 'items'
findView.findEditor.trigger 'core:confirm'
findView.focus()
describe "when core:cancel is triggered on the find view", ->
it "detaches from the workspace view", ->
$(document.activeElement).trigger 'core:cancel'
expect(atom.workspaceView.find('.find-and-replace')).not.toExist()
it "removes highlighted matches", ->
findResultsView = editorView.find('.search-results')
$(document.activeElement).trigger 'core:cancel'
expect(findResultsView.parent()).not.toExist()
describe "when core:cancel is triggered on an empty pane", ->
it "detaches from the workspace view", ->
atom.workspaceView.getActivePaneView().focus()
$(atom.workspaceView.getActivePaneView()).trigger 'core:cancel'
expect(atom.workspaceView.find('.find-and-replace')).not.toExist()
describe "when core:cancel is triggered on an editor", ->
it "detaches from the workspace view", ->
waitsForPromise ->
atom.workspace.open()
runs ->
$(atom.workspaceView.getActiveView().hiddenInput).trigger 'core:cancel'
expect(atom.workspaceView.find('.find-and-replace')).not.toExist()
describe "when core:cancel is triggered on a mini editor", ->
it "leaves the find view attached", ->
editorView = new EditorView(mini: true)
atom.workspaceView.appendToTop(editorView)
editorView.focus()
$(editorView.hiddenInput).trigger 'core:cancel'
expect(atom.workspaceView.find('.find-and-replace')).toExist()
describe "serialization", ->
it "serializes find and replace history", ->
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
findView.findEditor.setText("items")
findView.replaceEditor.setText("cat")
findView.replaceAll()
findView.findEditor.setText("sort")
findView.replaceEditor.setText("dog")
findView.replaceNext()
findView.findEditor.setText("shift")
findView.replaceEditor.setText("ok")
findView.findNext(false)
atom.packages.deactivatePackage("find-and-replace")
activationPromise = atom.packages.activatePackage("find-and-replace").then ({mainModule}) ->
mainModule.createFindView()
{findView} = mainModule
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
findView.findEditor.trigger('core:move-up')
expect(findView.findEditor.getText()).toBe 'shift'
findView.findEditor.trigger('core:move-up')
expect(findView.findEditor.getText()).toBe 'sort'
findView.findEditor.trigger('core:move-up')
expect(findView.findEditor.getText()).toBe 'items'
findView.replaceEditor.trigger('core:move-up')
expect(findView.replaceEditor.getText()).toBe 'dog'
findView.replaceEditor.trigger('core:move-up')
expect(findView.replaceEditor.getText()).toBe 'cat'
it "serializes find options ", ->
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
expect(findView.caseOptionButton).not.toHaveClass 'selected'
expect(findView.regexOptionButton).not.toHaveClass 'selected'
expect(findView.selectionOptionButton).not.toHaveClass 'selected'
findView.caseOptionButton.click()
findView.regexOptionButton.click()
findView.selectionOptionButton.click()
expect(findView.caseOptionButton).toHaveClass 'selected'
expect(findView.regexOptionButton).toHaveClass 'selected'
expect(findView.selectionOptionButton).toHaveClass 'selected'
atom.packages.deactivatePackage("find-and-replace")
activationPromise = atom.packages.activatePackage("find-and-replace").then ({mainModule}) ->
mainModule.createFindView()
{findView} = mainModule
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
expect(findView.caseOptionButton).toHaveClass 'selected'
expect(findView.regexOptionButton).toHaveClass 'selected'
expect(findView.selectionOptionButton).toHaveClass 'selected'
describe "finding", ->
beforeEach ->
atom.config.set('find-and-replace.focusEditorAfterSearch', false)
editor.setCursorBufferPosition([2,0])
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
findView.findEditor.setText 'items'
findView.findEditor.trigger 'core:confirm'
describe "when the find string contains an escaped char", ->
beforeEach ->
editor.setText("\t\n\\t\\\\")
editor.setCursorBufferPosition([0,0])
describe "when regex seach is enabled", ->
beforeEach ->
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
it "finds a backslash", ->
findView.findEditor.setText('\\\\')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[1, 0], [1, 1]]
it "finds a newline", ->
findView.findEditor.setText('\\n')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[0, 1], [1, 0]]
it "finds a tab character", ->
findView.findEditor.setText('\\t')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[0, 0], [0, 1]]
describe "when regex seach is disabled", ->
it "finds the literal backslash t", ->
findView.findEditor.setText('\\t')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[1, 0], [1, 2]]
it "finds a backslash", ->
findView.findEditor.setText('\\')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[1, 0], [1, 1]]
it "finds two backslashes", ->
findView.findEditor.setText('\\\\')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[1, 2], [1, 4]]
it "doesn't find when escaped", ->
findView.findEditor.setText('\\\\t')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[0, 0], [0, 0]]
describe "when focusEditorAfterSearch is set", ->
beforeEach ->
atom.config.set('find-and-replace.focusEditorAfterSearch', true)
findView.findEditor.trigger 'core:confirm'
it "selects the first match following the cursor and correctly focuses the editor", ->
expect(findView.resultCounter.text()).toEqual('3 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[2, 34], [2, 39]]
expect(editorView).toHaveFocus()
it "doesn't change the selection, beeps if there are no matches and keeps focus on the find view", ->
editor.setCursorBufferPosition([2,0])
findView.findEditor.setText 'notinthefilebro'
findView.findEditor.focus()
findView.findEditor.trigger 'core:confirm'
expect(editor.getCursorBufferPosition()).toEqual [2,0]
expect(atom.beep).toHaveBeenCalled()
expect(findView).toHaveFocus()
expect(findView.descriptionLabel.text()).toEqual "No results found for 'notinthefilebro'"
describe "updating the descriptionLabel", ->
it "properly updates the info message", ->
findView.findEditor.setText 'item'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel.text()).toEqual "6 results found for 'item'"
findView.findEditor.setText 'notinthefilenope'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel.text()).toEqual "No results found for 'notinthefilenope'"
findView.findEditor.setText 'item'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel.text()).toEqual "6 results found for 'item'"
findView.findEditor.setText ''
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel.text()).toContain "Find in Current Buffer"
describe "when there is a find-error", ->
beforeEach ->
editor.setCursorBufferPosition([2,0])
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
it "displays the error", ->
findView.findEditor.setText 'i[t'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel).toHaveClass 'text-error'
expect(findView.descriptionLabel.text()).toContain 'Invalid regular expression'
it "will be reset when there is no longer an error", ->
findView.findEditor.setText 'i[t'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel).toHaveClass 'text-error'
findView.findEditor.setText ''
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel).not.toHaveClass 'text-error'
expect(findView.descriptionLabel.text()).toContain "Find in Current Buffer"
findView.findEditor.setText 'item'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel).not.toHaveClass 'text-error'
expect(findView.descriptionLabel.text()).toContain "6 results"
it "selects the first match following the cursor", ->
expect(findView.resultCounter.text()).toEqual('2 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[2, 8], [2, 13]]
findView.findEditor.trigger 'core:confirm'
expect(findView.resultCounter.text()).toEqual('3 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[2, 34], [2, 39]]
expect(findView.findEditor).toHaveFocus()
it "selects the next match when the next match button is pressed", ->
findView.nextButton.click()
expect(findView.resultCounter.text()).toEqual('3 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[2, 34], [2, 39]]
it "selects the next match when the 'find-and-replace:find-next' event is triggered and correctly focuses the editor", ->
expect(findView).toHaveFocus()
editorView.trigger('find-and-replace:find-next')
expect(findView.resultCounter.text()).toEqual('3 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[2, 34], [2, 39]]
expect(editorView).toHaveFocus()
it "selects the previous match before the cursor when the 'find-and-replace:show-previous' event is triggered", ->
expect(findView.resultCounter.text()).toEqual('2 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[2, 8], [2, 13]]
findView.findEditor.trigger 'find-and-replace:show-previous'
expect(findView.resultCounter.text()).toEqual('1 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[1, 22], [1, 27]]
expect(findView.findEditor).toHaveFocus()
it "will re-run search if 'find-and-replace:find-next' is triggered after changing the findEditor's text", ->
findView.findEditor.setText 'sort'
findView.findEditor.trigger 'find-and-replace:find-next'
expect(findView.resultCounter.text()).toEqual('3 of 5')
expect(editor.getSelectedBufferRange()).toEqual [[8, 11], [8, 15]]
it "'find-and-replace:find-next' adds to the findEditor's history", ->
findView.findEditor.setText 'sort'
findView.findEditor.trigger 'find-and-replace:find-next'
expect(findView.resultCounter.text()).toEqual('3 of 5')
findView.findEditor.setText 'nope'
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'sort'
it "selects the previous match when the previous match button is pressed", ->
findView.previousButton.click()
expect(findView.resultCounter.text()).toEqual('1 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[1, 27], [1, 22]]
it "selects the previous match when the 'find-and-replace:find-previous' event is triggered and correctly focuses the editor", ->
expect(findView).toHaveFocus()
editorView.trigger('find-and-replace:find-previous')
expect(findView.resultCounter.text()).toEqual('1 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[1, 27], [1, 22]]
expect(editorView).toHaveFocus()
it "will re-run search if 'find-and-replace:find-previous' is triggered after changing the findEditor's text", ->
findView.findEditor.setText 'sort'
findView.findEditor.trigger 'find-and-replace:find-previous'
expect(findView.resultCounter.text()).toEqual('2 of 5')
expect(editor.getSelectedBufferRange()).toEqual [[1, 6], [1, 10]]
it "replaces results counter with number of results found when user moves the cursor", ->
editor.moveCursorDown()
expect(findView.resultCounter.text()).toBe '6 found'
it "replaces results counter x of y text when user selects a marked range", ->
editor.moveCursorDown()
editor.setSelectedBufferRange([[2, 34], [2, 39]])
expect(findView.resultCounter.text()).toEqual('3 of 6')
it "places the selected text into the find editor when find-and-replace:set-find-pattern is triggered", ->
editor.setSelectedBufferRange([[1,6],[1,10]])
atom.workspaceView.trigger 'find-and-replace:use-selection-as-find-pattern'
expect(findView.findEditor.getText()).toBe 'sort'
expect(editor.getSelectedBufferRange()).toEqual [[1,6],[1,10]]
atom.workspaceView.trigger 'find-and-replace:find-next'
expect(editor.getSelectedBufferRange()).toEqual [[8,11],[8,15]]
it "does not highlight the found text when the find view is hidden", ->
findView.findEditor.trigger 'core:cancel'
findView.findEditor.trigger 'find-and-replace:find-next'
findResultsView = editorView.find('.search-results')
expect(findResultsView.parent()).not.toExist()
describe "when the active pane item changes", ->
beforeEach ->
editor.setSelectedBufferRange([[0, 0], [0, 0]])
describe "when a new edit session is activated", ->
it "reruns the search on the new edit session", ->
waitsForPromise ->
atom.workspace.open('sample.coffee')
runs ->
editor = atom.workspace.getActivePaneItem()
expect(findView.resultCounter.text()).toEqual('7 found')
expect(editor.getSelectedBufferRange()).toEqual [[0, 0], [0, 0]]
it "initially highlights the found text in the new edit session", ->
expect(editorView.find('.highlight.find-result')).toHaveLength 6
waitsForPromise ->
atom.workspace.open('sample.coffee')
runs ->
# old editor has no more results
expect(editorView.find('.highlight.find-result')).toHaveLength 0
# new one has 7 results
expect(atom.workspaceView.getActiveView().find('.highlight.find-result')).toHaveLength 7
it "highlights the found text in the new edit session when find next is triggered", ->
waitsForPromise ->
atom.workspace.open('sample.coffee')
runs ->
findView.findEditor.trigger 'find-and-replace:find-next'
expect(atom.workspaceView.getActiveView().find('.highlight.find-result')).toHaveLength 6
expect(atom.workspaceView.getActiveView().find('.highlight.current-result')).toHaveLength 1
describe "when all active pane items are closed", ->
it "updates the result count", ->
editorView.trigger 'core:close'
expect(findView.resultCounter.text()).toEqual('no results')
describe "when the active pane item is not an edit session", ->
[anotherOpener] = []
beforeEach ->
anotherOpener = (pathToOpen, options) -> $('another')
atom.workspace.registerOpener(anotherOpener)
afterEach ->
atom.workspace.unregisterOpener(anotherOpener)
it "updates the result view", ->
waitsForPromise ->
atom.workspace.open "another"
runs ->
expect(findView.resultCounter.text()).toEqual('no results')
it "removes all highlights", ->
findResultsView = editorView.find('.search-results')
waitsForPromise ->
atom.workspace.open "another"
runs ->
expect(findResultsView.children()).toHaveLength 0
describe "when a new edit session is activated on a different pane", ->
it "initially highlights all the sample.js results", ->
expect(editorView.find('.find-result')).toHaveLength 6
it "reruns the search on the new editSession", ->
newEditor = null
waitsForPromise ->
atom.project.open('sample.coffee').then (o) -> newEditor = o
runs ->
newEditorView = editorView.getPane().splitRight(newEditor).activeView
expect(findView.resultCounter.text()).toEqual('7 found')
expect(newEditorView.getEditor().getSelectedBufferRange()).toEqual [[0, 0], [0, 0]]
findView.findEditor.trigger 'find-and-replace:find-next'
expect(findView.resultCounter.text()).toEqual('1 of 7')
expect(newEditorView.getEditor().getSelectedBufferRange()).toEqual [[1, 9], [1, 14]]
it "highlights the found text in the new edit session (and removes the highlights from the other)", ->
[newEditor, newEditorView] = []
waitsForPromise ->
atom.project.open('sample.coffee').then (o) -> newEditor = o
runs ->
newEditorView = editorView.getPane().splitRight(newEditor)
runs ->
# old editor has no more results
expect(editorView.find('.find-result')).toHaveLength 0
# new one has 7 results
expect(newEditorView.find('.find-result')).toHaveLength 7
it "will still highlight results after the split pane has been destroyed", ->
[newEditor, newEditorView] = []
waitsForPromise ->
atom.project.open('sample.coffee').then (o) -> newEditor = o
runs ->
newEditorView = editorView.getPane().splitRight(newEditor)
expect(newEditorView.find('.find-result')).toHaveLength 7
newEditorView.focus()
newEditorView.trigger('core:close')
editorView.focus()
runs ->
expect(editorView.find('.find-result')).toHaveLength 6
describe "when the buffer contents change", ->
it "re-runs the search", ->
findResultsView = editorView.find('.search-results')
editor.setSelectedBufferRange([[1, 26], [1, 27]])
editor.insertText("")
window.advanceClock(1000)
expect(findView.resultCounter.text()).toEqual('5 found')
editor.insertText("s")
window.advanceClock(1000)
expect(findView.resultCounter.text()).toEqual('6 found')
it "does not beep if no matches were found", ->
editor.setCursorBufferPosition([2,0])
findView.findEditor.setText 'notinthefilebro'
findView.findEditor.trigger 'core:confirm'
atom.beep.reset()
editor.insertText("blah blah")
expect(atom.beep).not.toHaveBeenCalled()
describe "when finding within a selection", ->
beforeEach ->
editor.setSelectedBufferRange [[2, 0], [4, 0]]
it "toggles find within a selction via and event and only finds matches within the selection", ->
findView.findEditor.setText 'items'
findView.findEditor.trigger 'find-and-replace:toggle-selection-option'
expect(editor.getSelectedBufferRange()).toEqual [[2, 8], [2, 13]]
expect(findView.resultCounter.text()).toEqual('1 of 3')
it "toggles find within a selction via and button and only finds matches within the selection", ->
findView.findEditor.setText 'items'
findView.selectionOptionButton.click()
expect(editor.getSelectedBufferRange()).toEqual [[2, 8], [2, 13]]
expect(findView.resultCounter.text()).toEqual('1 of 3')
describe "when regex is toggled", ->
it "toggles regex via an event and finds text matching the pattern", ->
editor.setCursorBufferPosition([2,0])
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
findView.findEditor.setText 'i[t]em+s'
expect(editor.getSelectedBufferRange()).toEqual [[2, 8], [2, 13]]
it "toggles regex via a button and finds text matching the pattern", ->
editor.setCursorBufferPosition([2,0])
findView.regexOptionButton.click()
findView.findEditor.setText 'i[t]em+s'
expect(editor.getSelectedBufferRange()).toEqual [[2, 8], [2, 13]]
it "re-runs the search using the new find text when toggled", ->
editor.setCursorBufferPosition([1,0])
findView.findEditor.setText 's(o)rt'
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
expect(editor.getSelectedBufferRange()).toEqual [[1, 6], [1, 10]]
describe "when an invalid regex is entered", ->
it "displays an error", ->
editor.setCursorBufferPosition([2,0])
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
findView.findEditor.setText 'i[t'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel).toHaveClass 'text-error'
describe "when case sensitivity is toggled", ->
beforeEach ->
editor.setText "-----\nwords\nWORDs\n"
editor.setCursorBufferPosition([0,0])
it "toggles case sensitivity via an event and finds text matching the pattern", ->
findView.findEditor.setText 'WORDs'
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[1, 0], [1, 5]]
editor.setCursorBufferPosition([0,0])
findView.findEditor.trigger 'find-and-replace:toggle-case-option'
expect(editor.getSelectedBufferRange()).toEqual [[2, 0], [2, 5]]
it "toggles case sensitivity via a button and finds text matching the pattern", ->
findView.findEditor.setText 'WORDs'
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[1, 0], [1, 5]]
editor.setCursorBufferPosition([0,0])
findView.caseOptionButton.click()
expect(editor.getSelectedBufferRange()).toEqual [[2, 0], [2, 5]]
describe "highlighting search results", ->
resultPosition = (result) ->
{top: result.children()[0].style.top, left: result.children()[0].style.left}
it "only highlights matches", ->
expect(editorView.find('.find-result')).toHaveLength 5
findView.findEditor.setText 'notinthefilebro'
findView.findEditor.trigger 'core:confirm'
runs ->
expect(editorView.find('.find-result')).toHaveLength 0
it "adds a class to the current match indicating it is the current match", ->
position = (result) ->
{top: result.children()[0].style.top, left: result.children()[0].style.left}
firstResult = editorView.find('.current-result')
firstPosition = resultPosition(firstResult)
expect(firstResult).toHaveLength 1
expect(editorView.find('.find-result')).toHaveLength 5
findView.findEditor.trigger 'core:confirm'
findView.findEditor.trigger 'core:confirm'
nextResult = editorView.find('.current-result')
nextPosition = resultPosition(nextResult)
expect(nextResult).toHaveLength 1
expect(nextPosition).not.toEqual firstPosition
findView.findEditor.trigger 'find-and-replace:find-previous'
findView.findEditor.trigger 'find-and-replace:find-previous'
originalResult = editorView.find('.current-result')
originalPosition = resultPosition(originalResult)
expect(originalResult).toHaveLength 1
expect(originalPosition).toEqual firstPosition
it "adds a class to the result when the current selection equals the result's range", ->
originalResult = editorView.find('.current-result')
originalPosition = resultPosition(originalResult)
expect(originalResult).toHaveLength 1
editor.setSelectedBufferRange([[5, 16], [5, 20]])
expect(editorView.find('.current-result')).toHaveLength 0
editor.setSelectedBufferRange([[5, 16], [5, 21]])
newResult = editorView.find('.current-result')
newPosition = resultPosition(newResult)
expect(newResult).toHaveLength 1
expect(newPosition).not.toBe originalPosition
describe "when user types in the find editor", ->
advance = ->
advanceClock(findView.findEditor.getEditor().getBuffer().stoppedChangingDelay + 1)
beforeEach ->
findView.findEditor.focus()
it "updates the search results", ->
expect(findView.descriptionLabel.text()).toContain "6 results"
findView.findEditor.setText 'why do I need these 2 lines? The editor does not trigger contents-modified without them'
advance()
findView.findEditor.setText ''
advance()
expect(findView.descriptionLabel.text()).toContain "Find in Current Buffer"
expect(findView).toHaveFocus()
findView.findEditor.setText 'sort'
advance()
expect(findView.descriptionLabel.text()).toContain "5 results"
expect(findView).toHaveFocus()
findView.findEditor.setText 'items'
advance()
expect(findView.descriptionLabel.text()).toContain "6 results"
expect(findView).toHaveFocus()
describe "when another find is called", ->
previousMarkers = null
beforeEach ->
previousMarkers = _.clone(editor.getMarkers())
it "clears existing markers for another search", ->
findView.findEditor.setText('notinthefile')
findView.findEditor.trigger 'core:confirm'
expect(editor.getMarkers().length).toEqual 1
it "clears existing markers for an empty search", ->
findView.findEditor.setText('')
findView.findEditor.trigger 'core:confirm'
expect(editor.getMarkers().length).toEqual 1
describe "replacing", ->
beforeEach ->
editor.setCursorBufferPosition([2,0])
editorView.trigger 'find-and-replace:show-replace'
waitsForPromise ->
activationPromise
runs ->
findView.findEditor.setText('items')
findView.replaceEditor.setText('cats')
describe "when the replacement string contains an escaped char", ->
describe "when the regex option is chosen", ->
beforeEach ->
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
it "inserts tabs and newlines", ->
findView.replaceEditor.setText('\\t\\n')
findView.replaceEditor.trigger 'core:confirm'
expect(editor.getText()).toMatch(/\t\n/)
it "doesn't insert a escaped char if there are multiple backslashs in front of the char", ->
findView.replaceEditor.setText('\\\\t\\\t')
findView.replaceEditor.trigger 'core:confirm'
expect(editor.getText()).toMatch(/\\t\\\t/)
describe "when in normal mode", ->
it "inserts backslach n and t", ->
findView.replaceEditor.setText('\\t\\n')
findView.replaceEditor.trigger 'core:confirm'
expect(editor.getText()).toMatch(/\\t\\n/)
it "inserts carriage returns", ->
textWithCarriageReturns = editor.getText().replace(/\n/g, "\r")
editor.setText(textWithCarriageReturns)
findView.replaceEditor.setText('\\t\\r')
findView.replaceEditor.trigger 'core:confirm'
expect(editor.getText()).toMatch(/\\t\\r/)
describe "replace next", ->
describe "when core:confirm is triggered", ->
it "replaces the match after the cursor and selects the next match", ->
findView.replaceEditor.trigger 'core:confirm'
expect(findView.resultCounter.text()).toEqual('2 of 5')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return items;"
expect(editor.getSelectedBufferRange()).toEqual [[2, 33], [2, 38]]
it "replaceEditor maintains focus after core:confirm is run", ->
findView.replaceEditor.focus()
findView.replaceEditor.trigger 'core:confirm'
expect(findView.replaceEditor).toHaveFocus()
it "replaces the _current_ match and selects the next match", ->
findView.findEditor.trigger 'core:confirm'
editor.setSelectedBufferRange([[2, 8], [2, 13]])
expect(findView.resultCounter.text()).toEqual('2 of 6')
findView.replaceEditor.trigger 'core:confirm'
expect(findView.resultCounter.text()).toEqual('2 of 5')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return items;"
expect(editor.getSelectedBufferRange()).toEqual [[2, 33], [2, 38]]
findView.replaceEditor.trigger 'core:confirm'
expect(findView.resultCounter.text()).toEqual('2 of 4')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return cats;"
expect(editor.getSelectedBufferRange()).toEqual [[3, 16], [3, 21]]
describe "when the replace next button is pressed", ->
it "replaces the match after the cursor and selects the next match", ->
$('.find-and-replace .btn-next').click()
expect(findView.resultCounter.text()).toEqual('2 of 5')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return items;"
expect(editor.getSelectedBufferRange()).toEqual [[2, 33], [2, 38]]
describe "when the 'find-and-replace:replace-next' event is triggered", ->
it "replaces the match after the cursor and selects the next match", ->
editorView.trigger 'find-and-replace:replace-next'
expect(findView.resultCounter.text()).toEqual('2 of 5')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return items;"
expect(editor.getSelectedBufferRange()).toEqual [[2, 33], [2, 38]]
describe "replace previous", ->
describe "when button is clicked", ->
it "replaces the match after the cursor and selects the previous match", ->
findView.findEditor.trigger 'core:confirm'
findView.replacePreviousButton.click()
expect(findView.resultCounter.text()).toEqual('1 of 5')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return items;"
expect(editor.getSelectedBufferRange()).toEqual [[1, 22], [1, 27]]
describe "when command is triggered", ->
it "replaces the match after the cursor and selects the previous match", ->
findView.findEditor.trigger 'core:confirm'
findView.trigger 'find-and-replace:replace-previous'
expect(findView.resultCounter.text()).toEqual('1 of 5')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return items;"
expect(editor.getSelectedBufferRange()).toEqual [[1, 22], [1, 27]]
describe "replace all", ->
describe "when the replace all button is pressed", ->
it "replaces all matched text", ->
$('.find-and-replace .btn-all').click()
expect(findView.resultCounter.text()).toEqual('no results')
expect(editor.getText()).not.toMatch /items/
expect(editor.getText().match(/\bcats\b/g)).toHaveLength 6
expect(editor.getSelectedBufferRange()).toEqual [[2, 0], [2, 0]]
it "all changes are undoable in one transaction", ->
$('.find-and-replace .btn-all').click()
editor.undo()
expect(editor.getText()).not.toMatch /\bcats\b/g
describe "when the 'find-and-replace:replace-all' event is triggered", ->
it "replaces all matched text", ->
editorView.trigger 'find-and-replace:replace-all'
expect(findView.resultCounter.text()).toEqual('no results')
expect(editor.getText()).not.toMatch /items/
expect(editor.getText().match(/\bcats\b/g)).toHaveLength 6
expect(editor.getSelectedBufferRange()).toEqual [[2, 0], [2, 0]]
describe "replacement patterns", ->
describe "when the regex option is true", ->
it "replaces $1, $2, etc... with substring matches", ->
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
findView.findEditor.setText('(items)([\\.;])')
findView.replaceEditor.setText('$2$1')
editorView.trigger 'find-and-replace:replace-all'
expect(editor.getText()).toMatch /;items/
expect(editor.getText()).toMatch /\.items/
describe "when the regex option is false", ->
it "replaces the matches with without any regex subsitions", ->
findView.findEditor.setText('items')
findView.replaceEditor.setText('$&cats')
editorView.trigger 'find-and-replace:replace-all'
expect(editor.getText()).not.toMatch /items/
expect(editor.getText().match(/\$&cats\b/g)).toHaveLength 6
describe "history", ->
beforeEach ->
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
describe "when there is no history", ->
it "retains unsearched text", ->
text = 'something I want to search for but havent yet'
findView.findEditor.setText(text)
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual ''
findView.findEditor.trigger 'core:move-down'
expect(findView.findEditor.getText()).toEqual text
describe "when there is history", ->
[oneRange, twoRange, threeRange] = []
beforeEach ->
editorView.trigger 'find-and-replace:show'
editor.setText("zero\none\ntwo\nthree\n")
findView.findEditor.setText('one')
findView.findEditor.trigger 'core:confirm'
findView.findEditor.setText('two')
findView.findEditor.trigger 'core:confirm'
findView.findEditor.setText('three')
findView.findEditor.trigger 'core:confirm'
it "can navigate the entire history stack", ->
expect(findView.findEditor.getText()).toEqual 'three'
findView.findEditor.trigger 'core:move-down'
expect(findView.findEditor.getText()).toEqual ''
findView.findEditor.trigger 'core:move-down'
expect(findView.findEditor.getText()).toEqual ''
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'three'
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'two'
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'one'
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'one'
findView.findEditor.trigger 'core:move-down'
expect(findView.findEditor.getText()).toEqual 'two'
it "retains the current unsearched text", ->
text = 'something I want to search for but havent yet'
findView.findEditor.setText(text)
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'three'
findView.findEditor.trigger 'core:move-down'
expect(findView.findEditor.getText()).toEqual text
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'three'
findView.findEditor.trigger 'core:move-down'
findView.findEditor.trigger 'core:confirm'
findView.findEditor.trigger 'core:move-down'
expect(findView.findEditor.getText()).toEqual ''
it "adds confirmed patterns to the history", ->
findView.findEditor.setText("cool stuff")
findView.findEditor.trigger 'core:confirm'
findView.findEditor.setText("cooler stuff")
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'cool stuff'
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'three'
describe "when user types in the find editor", ->
advance = ->
advanceClock(findView.findEditor.getEditor().getBuffer().stoppedChangingDelay + 1)
beforeEach ->
findView.findEditor.focus()
it "does not add live searches to the history", ->
expect(findView.descriptionLabel.text()).toContain "1 result"
# I really do not understand why this are necessary...
findView.findEditor.setText 'FIXME: necessary search for some reason??'
advance()
findView.findEditor.setText 'nope'
advance()
expect(findView.descriptionLabel.text()).toContain 'nope'
findView.findEditor.setText 'zero'
advance()
expect(findView.descriptionLabel.text()).toContain "zero"
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'three'
| true | _ = require 'underscore-plus'
{$, EditorView, WorkspaceView} = require 'atom'
path = require 'path'
describe 'FindView', ->
[editorView, editor, findView, activationPromise] = []
beforeEach ->
spyOn(atom, 'beep')
atom.workspaceView = new WorkspaceView()
atom.project.setPath(path.join(__dirname, 'fixtures'))
waitsForPromise ->
atom.workspace.open('sample.js')
runs ->
atom.workspaceView.attachToDom()
editorView = atom.workspaceView.getActiveView()
editor = editorView.getEditor()
activationPromise = atom.packages.activatePackage("find-and-replace").then ({mainModule}) ->
mainModule.createFindView()
{findView} = mainModule
describe "when find-and-replace:show is triggered", ->
it "attaches FindView to the root view", ->
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
expect(atom.workspaceView.find('.find-and-replace')).toExist()
it "populates the findEditor with selection when there is a selection", ->
editor.setSelectedBufferRange([[2, 8], [2, 13]])
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
expect(atom.workspaceView.find('.find-and-replace')).toExist()
expect(findView.findEditor.getText()).toBe('items')
findView.findEditor.setText('')
editor.setSelectedBufferRange([[2, 14], [2, 20]])
editorView.trigger 'find-and-replace:show'
expect(atom.workspaceView.find('.find-and-replace')).toExist()
expect(findView.findEditor.getText()).toBe('length')
it "does not change the findEditor text when there is no selection", ->
editor.setSelectedBufferRange([[2, 8], [2, 8]])
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
findView.findEditor.setText 'PI:NAME:<NAME>END_PI'
editorView.trigger 'find-and-replace:show'
expect(findView.findEditor.getText()).toBe('kitten')
it "does not change the findEditor text when there is a multiline selection", ->
editor.setSelectedBufferRange([[2, 8], [3, 12]])
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
expect(atom.workspaceView.find('.find-and-replace')).toExist()
expect(findView.findEditor.getText()).toBe('')
describe "when find-and-replace:toggle is triggered", ->
it "toggles the visibility of the FindView", ->
atom.workspaceView.trigger 'find-and-replace:toggle'
waitsForPromise ->
activationPromise
runs ->
expect(atom.workspaceView.find('.find-and-replace')).toExist()
atom.workspaceView.trigger 'find-and-replace:toggle'
expect(atom.workspaceView.find('.find-and-replace')).not.toExist()
describe "when FindView's replace editor is visible", ->
it "keeps the replace editor visible when find-and-replace:show is triggered", ->
editorView.trigger 'find-and-replace:show-replace'
waitsForPromise ->
activationPromise
runs ->
editorView.trigger 'find-and-replace:show'
expect(findView.replaceEditor).toBeVisible()
describe "core:cancel", ->
beforeEach ->
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
findView.findEditor.setText 'items'
findView.findEditor.trigger 'core:confirm'
findView.focus()
describe "when core:cancel is triggered on the find view", ->
it "detaches from the workspace view", ->
$(document.activeElement).trigger 'core:cancel'
expect(atom.workspaceView.find('.find-and-replace')).not.toExist()
it "removes highlighted matches", ->
findResultsView = editorView.find('.search-results')
$(document.activeElement).trigger 'core:cancel'
expect(findResultsView.parent()).not.toExist()
describe "when core:cancel is triggered on an empty pane", ->
it "detaches from the workspace view", ->
atom.workspaceView.getActivePaneView().focus()
$(atom.workspaceView.getActivePaneView()).trigger 'core:cancel'
expect(atom.workspaceView.find('.find-and-replace')).not.toExist()
describe "when core:cancel is triggered on an editor", ->
it "detaches from the workspace view", ->
waitsForPromise ->
atom.workspace.open()
runs ->
$(atom.workspaceView.getActiveView().hiddenInput).trigger 'core:cancel'
expect(atom.workspaceView.find('.find-and-replace')).not.toExist()
describe "when core:cancel is triggered on a mini editor", ->
it "leaves the find view attached", ->
editorView = new EditorView(mini: true)
atom.workspaceView.appendToTop(editorView)
editorView.focus()
$(editorView.hiddenInput).trigger 'core:cancel'
expect(atom.workspaceView.find('.find-and-replace')).toExist()
describe "serialization", ->
it "serializes find and replace history", ->
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
findView.findEditor.setText("items")
findView.replaceEditor.setText("cat")
findView.replaceAll()
findView.findEditor.setText("sort")
findView.replaceEditor.setText("dog")
findView.replaceNext()
findView.findEditor.setText("shift")
findView.replaceEditor.setText("ok")
findView.findNext(false)
atom.packages.deactivatePackage("find-and-replace")
activationPromise = atom.packages.activatePackage("find-and-replace").then ({mainModule}) ->
mainModule.createFindView()
{findView} = mainModule
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
findView.findEditor.trigger('core:move-up')
expect(findView.findEditor.getText()).toBe 'shift'
findView.findEditor.trigger('core:move-up')
expect(findView.findEditor.getText()).toBe 'sort'
findView.findEditor.trigger('core:move-up')
expect(findView.findEditor.getText()).toBe 'items'
findView.replaceEditor.trigger('core:move-up')
expect(findView.replaceEditor.getText()).toBe 'dog'
findView.replaceEditor.trigger('core:move-up')
expect(findView.replaceEditor.getText()).toBe 'cat'
it "serializes find options ", ->
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
expect(findView.caseOptionButton).not.toHaveClass 'selected'
expect(findView.regexOptionButton).not.toHaveClass 'selected'
expect(findView.selectionOptionButton).not.toHaveClass 'selected'
findView.caseOptionButton.click()
findView.regexOptionButton.click()
findView.selectionOptionButton.click()
expect(findView.caseOptionButton).toHaveClass 'selected'
expect(findView.regexOptionButton).toHaveClass 'selected'
expect(findView.selectionOptionButton).toHaveClass 'selected'
atom.packages.deactivatePackage("find-and-replace")
activationPromise = atom.packages.activatePackage("find-and-replace").then ({mainModule}) ->
mainModule.createFindView()
{findView} = mainModule
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
expect(findView.caseOptionButton).toHaveClass 'selected'
expect(findView.regexOptionButton).toHaveClass 'selected'
expect(findView.selectionOptionButton).toHaveClass 'selected'
describe "finding", ->
beforeEach ->
atom.config.set('find-and-replace.focusEditorAfterSearch', false)
editor.setCursorBufferPosition([2,0])
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
runs ->
findView.findEditor.setText 'items'
findView.findEditor.trigger 'core:confirm'
describe "when the find string contains an escaped char", ->
beforeEach ->
editor.setText("\t\n\\t\\\\")
editor.setCursorBufferPosition([0,0])
describe "when regex seach is enabled", ->
beforeEach ->
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
it "finds a backslash", ->
findView.findEditor.setText('\\\\')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[1, 0], [1, 1]]
it "finds a newline", ->
findView.findEditor.setText('\\n')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[0, 1], [1, 0]]
it "finds a tab character", ->
findView.findEditor.setText('\\t')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[0, 0], [0, 1]]
describe "when regex seach is disabled", ->
it "finds the literal backslash t", ->
findView.findEditor.setText('\\t')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[1, 0], [1, 2]]
it "finds a backslash", ->
findView.findEditor.setText('\\')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[1, 0], [1, 1]]
it "finds two backslashes", ->
findView.findEditor.setText('\\\\')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[1, 2], [1, 4]]
it "doesn't find when escaped", ->
findView.findEditor.setText('\\\\t')
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[0, 0], [0, 0]]
describe "when focusEditorAfterSearch is set", ->
beforeEach ->
atom.config.set('find-and-replace.focusEditorAfterSearch', true)
findView.findEditor.trigger 'core:confirm'
it "selects the first match following the cursor and correctly focuses the editor", ->
expect(findView.resultCounter.text()).toEqual('3 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[2, 34], [2, 39]]
expect(editorView).toHaveFocus()
it "doesn't change the selection, beeps if there are no matches and keeps focus on the find view", ->
editor.setCursorBufferPosition([2,0])
findView.findEditor.setText 'notinthefilebro'
findView.findEditor.focus()
findView.findEditor.trigger 'core:confirm'
expect(editor.getCursorBufferPosition()).toEqual [2,0]
expect(atom.beep).toHaveBeenCalled()
expect(findView).toHaveFocus()
expect(findView.descriptionLabel.text()).toEqual "No results found for 'notinthefilebro'"
describe "updating the descriptionLabel", ->
it "properly updates the info message", ->
findView.findEditor.setText 'item'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel.text()).toEqual "6 results found for 'item'"
findView.findEditor.setText 'notinthefilenope'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel.text()).toEqual "No results found for 'notinthefilenope'"
findView.findEditor.setText 'item'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel.text()).toEqual "6 results found for 'item'"
findView.findEditor.setText ''
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel.text()).toContain "Find in Current Buffer"
describe "when there is a find-error", ->
beforeEach ->
editor.setCursorBufferPosition([2,0])
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
it "displays the error", ->
findView.findEditor.setText 'i[t'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel).toHaveClass 'text-error'
expect(findView.descriptionLabel.text()).toContain 'Invalid regular expression'
it "will be reset when there is no longer an error", ->
findView.findEditor.setText 'i[t'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel).toHaveClass 'text-error'
findView.findEditor.setText ''
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel).not.toHaveClass 'text-error'
expect(findView.descriptionLabel.text()).toContain "Find in Current Buffer"
findView.findEditor.setText 'item'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel).not.toHaveClass 'text-error'
expect(findView.descriptionLabel.text()).toContain "6 results"
it "selects the first match following the cursor", ->
expect(findView.resultCounter.text()).toEqual('2 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[2, 8], [2, 13]]
findView.findEditor.trigger 'core:confirm'
expect(findView.resultCounter.text()).toEqual('3 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[2, 34], [2, 39]]
expect(findView.findEditor).toHaveFocus()
it "selects the next match when the next match button is pressed", ->
findView.nextButton.click()
expect(findView.resultCounter.text()).toEqual('3 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[2, 34], [2, 39]]
it "selects the next match when the 'find-and-replace:find-next' event is triggered and correctly focuses the editor", ->
expect(findView).toHaveFocus()
editorView.trigger('find-and-replace:find-next')
expect(findView.resultCounter.text()).toEqual('3 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[2, 34], [2, 39]]
expect(editorView).toHaveFocus()
it "selects the previous match before the cursor when the 'find-and-replace:show-previous' event is triggered", ->
expect(findView.resultCounter.text()).toEqual('2 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[2, 8], [2, 13]]
findView.findEditor.trigger 'find-and-replace:show-previous'
expect(findView.resultCounter.text()).toEqual('1 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[1, 22], [1, 27]]
expect(findView.findEditor).toHaveFocus()
it "will re-run search if 'find-and-replace:find-next' is triggered after changing the findEditor's text", ->
findView.findEditor.setText 'sort'
findView.findEditor.trigger 'find-and-replace:find-next'
expect(findView.resultCounter.text()).toEqual('3 of 5')
expect(editor.getSelectedBufferRange()).toEqual [[8, 11], [8, 15]]
it "'find-and-replace:find-next' adds to the findEditor's history", ->
findView.findEditor.setText 'sort'
findView.findEditor.trigger 'find-and-replace:find-next'
expect(findView.resultCounter.text()).toEqual('3 of 5')
findView.findEditor.setText 'nope'
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'sort'
it "selects the previous match when the previous match button is pressed", ->
findView.previousButton.click()
expect(findView.resultCounter.text()).toEqual('1 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[1, 27], [1, 22]]
it "selects the previous match when the 'find-and-replace:find-previous' event is triggered and correctly focuses the editor", ->
expect(findView).toHaveFocus()
editorView.trigger('find-and-replace:find-previous')
expect(findView.resultCounter.text()).toEqual('1 of 6')
expect(editor.getSelectedBufferRange()).toEqual [[1, 27], [1, 22]]
expect(editorView).toHaveFocus()
it "will re-run search if 'find-and-replace:find-previous' is triggered after changing the findEditor's text", ->
findView.findEditor.setText 'sort'
findView.findEditor.trigger 'find-and-replace:find-previous'
expect(findView.resultCounter.text()).toEqual('2 of 5')
expect(editor.getSelectedBufferRange()).toEqual [[1, 6], [1, 10]]
it "replaces results counter with number of results found when user moves the cursor", ->
editor.moveCursorDown()
expect(findView.resultCounter.text()).toBe '6 found'
it "replaces results counter x of y text when user selects a marked range", ->
editor.moveCursorDown()
editor.setSelectedBufferRange([[2, 34], [2, 39]])
expect(findView.resultCounter.text()).toEqual('3 of 6')
it "places the selected text into the find editor when find-and-replace:set-find-pattern is triggered", ->
editor.setSelectedBufferRange([[1,6],[1,10]])
atom.workspaceView.trigger 'find-and-replace:use-selection-as-find-pattern'
expect(findView.findEditor.getText()).toBe 'sort'
expect(editor.getSelectedBufferRange()).toEqual [[1,6],[1,10]]
atom.workspaceView.trigger 'find-and-replace:find-next'
expect(editor.getSelectedBufferRange()).toEqual [[8,11],[8,15]]
it "does not highlight the found text when the find view is hidden", ->
findView.findEditor.trigger 'core:cancel'
findView.findEditor.trigger 'find-and-replace:find-next'
findResultsView = editorView.find('.search-results')
expect(findResultsView.parent()).not.toExist()
describe "when the active pane item changes", ->
beforeEach ->
editor.setSelectedBufferRange([[0, 0], [0, 0]])
describe "when a new edit session is activated", ->
it "reruns the search on the new edit session", ->
waitsForPromise ->
atom.workspace.open('sample.coffee')
runs ->
editor = atom.workspace.getActivePaneItem()
expect(findView.resultCounter.text()).toEqual('7 found')
expect(editor.getSelectedBufferRange()).toEqual [[0, 0], [0, 0]]
it "initially highlights the found text in the new edit session", ->
expect(editorView.find('.highlight.find-result')).toHaveLength 6
waitsForPromise ->
atom.workspace.open('sample.coffee')
runs ->
# old editor has no more results
expect(editorView.find('.highlight.find-result')).toHaveLength 0
# new one has 7 results
expect(atom.workspaceView.getActiveView().find('.highlight.find-result')).toHaveLength 7
it "highlights the found text in the new edit session when find next is triggered", ->
waitsForPromise ->
atom.workspace.open('sample.coffee')
runs ->
findView.findEditor.trigger 'find-and-replace:find-next'
expect(atom.workspaceView.getActiveView().find('.highlight.find-result')).toHaveLength 6
expect(atom.workspaceView.getActiveView().find('.highlight.current-result')).toHaveLength 1
describe "when all active pane items are closed", ->
it "updates the result count", ->
editorView.trigger 'core:close'
expect(findView.resultCounter.text()).toEqual('no results')
describe "when the active pane item is not an edit session", ->
[anotherOpener] = []
beforeEach ->
anotherOpener = (pathToOpen, options) -> $('another')
atom.workspace.registerOpener(anotherOpener)
afterEach ->
atom.workspace.unregisterOpener(anotherOpener)
it "updates the result view", ->
waitsForPromise ->
atom.workspace.open "another"
runs ->
expect(findView.resultCounter.text()).toEqual('no results')
it "removes all highlights", ->
findResultsView = editorView.find('.search-results')
waitsForPromise ->
atom.workspace.open "another"
runs ->
expect(findResultsView.children()).toHaveLength 0
describe "when a new edit session is activated on a different pane", ->
it "initially highlights all the sample.js results", ->
expect(editorView.find('.find-result')).toHaveLength 6
it "reruns the search on the new editSession", ->
newEditor = null
waitsForPromise ->
atom.project.open('sample.coffee').then (o) -> newEditor = o
runs ->
newEditorView = editorView.getPane().splitRight(newEditor).activeView
expect(findView.resultCounter.text()).toEqual('7 found')
expect(newEditorView.getEditor().getSelectedBufferRange()).toEqual [[0, 0], [0, 0]]
findView.findEditor.trigger 'find-and-replace:find-next'
expect(findView.resultCounter.text()).toEqual('1 of 7')
expect(newEditorView.getEditor().getSelectedBufferRange()).toEqual [[1, 9], [1, 14]]
it "highlights the found text in the new edit session (and removes the highlights from the other)", ->
[newEditor, newEditorView] = []
waitsForPromise ->
atom.project.open('sample.coffee').then (o) -> newEditor = o
runs ->
newEditorView = editorView.getPane().splitRight(newEditor)
runs ->
# old editor has no more results
expect(editorView.find('.find-result')).toHaveLength 0
# new one has 7 results
expect(newEditorView.find('.find-result')).toHaveLength 7
it "will still highlight results after the split pane has been destroyed", ->
[newEditor, newEditorView] = []
waitsForPromise ->
atom.project.open('sample.coffee').then (o) -> newEditor = o
runs ->
newEditorView = editorView.getPane().splitRight(newEditor)
expect(newEditorView.find('.find-result')).toHaveLength 7
newEditorView.focus()
newEditorView.trigger('core:close')
editorView.focus()
runs ->
expect(editorView.find('.find-result')).toHaveLength 6
describe "when the buffer contents change", ->
it "re-runs the search", ->
findResultsView = editorView.find('.search-results')
editor.setSelectedBufferRange([[1, 26], [1, 27]])
editor.insertText("")
window.advanceClock(1000)
expect(findView.resultCounter.text()).toEqual('5 found')
editor.insertText("s")
window.advanceClock(1000)
expect(findView.resultCounter.text()).toEqual('6 found')
it "does not beep if no matches were found", ->
editor.setCursorBufferPosition([2,0])
findView.findEditor.setText 'notinthefilebro'
findView.findEditor.trigger 'core:confirm'
atom.beep.reset()
editor.insertText("blah blah")
expect(atom.beep).not.toHaveBeenCalled()
describe "when finding within a selection", ->
beforeEach ->
editor.setSelectedBufferRange [[2, 0], [4, 0]]
it "toggles find within a selction via and event and only finds matches within the selection", ->
findView.findEditor.setText 'items'
findView.findEditor.trigger 'find-and-replace:toggle-selection-option'
expect(editor.getSelectedBufferRange()).toEqual [[2, 8], [2, 13]]
expect(findView.resultCounter.text()).toEqual('1 of 3')
it "toggles find within a selction via and button and only finds matches within the selection", ->
findView.findEditor.setText 'items'
findView.selectionOptionButton.click()
expect(editor.getSelectedBufferRange()).toEqual [[2, 8], [2, 13]]
expect(findView.resultCounter.text()).toEqual('1 of 3')
describe "when regex is toggled", ->
it "toggles regex via an event and finds text matching the pattern", ->
editor.setCursorBufferPosition([2,0])
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
findView.findEditor.setText 'i[t]em+s'
expect(editor.getSelectedBufferRange()).toEqual [[2, 8], [2, 13]]
it "toggles regex via a button and finds text matching the pattern", ->
editor.setCursorBufferPosition([2,0])
findView.regexOptionButton.click()
findView.findEditor.setText 'i[t]em+s'
expect(editor.getSelectedBufferRange()).toEqual [[2, 8], [2, 13]]
it "re-runs the search using the new find text when toggled", ->
editor.setCursorBufferPosition([1,0])
findView.findEditor.setText 's(o)rt'
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
expect(editor.getSelectedBufferRange()).toEqual [[1, 6], [1, 10]]
describe "when an invalid regex is entered", ->
it "displays an error", ->
editor.setCursorBufferPosition([2,0])
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
findView.findEditor.setText 'i[t'
findView.findEditor.trigger 'core:confirm'
expect(findView.descriptionLabel).toHaveClass 'text-error'
describe "when case sensitivity is toggled", ->
beforeEach ->
editor.setText "-----\nwords\nWORDs\n"
editor.setCursorBufferPosition([0,0])
it "toggles case sensitivity via an event and finds text matching the pattern", ->
findView.findEditor.setText 'WORDs'
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[1, 0], [1, 5]]
editor.setCursorBufferPosition([0,0])
findView.findEditor.trigger 'find-and-replace:toggle-case-option'
expect(editor.getSelectedBufferRange()).toEqual [[2, 0], [2, 5]]
it "toggles case sensitivity via a button and finds text matching the pattern", ->
findView.findEditor.setText 'WORDs'
findView.findEditor.trigger 'core:confirm'
expect(editor.getSelectedBufferRange()).toEqual [[1, 0], [1, 5]]
editor.setCursorBufferPosition([0,0])
findView.caseOptionButton.click()
expect(editor.getSelectedBufferRange()).toEqual [[2, 0], [2, 5]]
describe "highlighting search results", ->
resultPosition = (result) ->
{top: result.children()[0].style.top, left: result.children()[0].style.left}
it "only highlights matches", ->
expect(editorView.find('.find-result')).toHaveLength 5
findView.findEditor.setText 'notinthefilebro'
findView.findEditor.trigger 'core:confirm'
runs ->
expect(editorView.find('.find-result')).toHaveLength 0
it "adds a class to the current match indicating it is the current match", ->
position = (result) ->
{top: result.children()[0].style.top, left: result.children()[0].style.left}
firstResult = editorView.find('.current-result')
firstPosition = resultPosition(firstResult)
expect(firstResult).toHaveLength 1
expect(editorView.find('.find-result')).toHaveLength 5
findView.findEditor.trigger 'core:confirm'
findView.findEditor.trigger 'core:confirm'
nextResult = editorView.find('.current-result')
nextPosition = resultPosition(nextResult)
expect(nextResult).toHaveLength 1
expect(nextPosition).not.toEqual firstPosition
findView.findEditor.trigger 'find-and-replace:find-previous'
findView.findEditor.trigger 'find-and-replace:find-previous'
originalResult = editorView.find('.current-result')
originalPosition = resultPosition(originalResult)
expect(originalResult).toHaveLength 1
expect(originalPosition).toEqual firstPosition
it "adds a class to the result when the current selection equals the result's range", ->
originalResult = editorView.find('.current-result')
originalPosition = resultPosition(originalResult)
expect(originalResult).toHaveLength 1
editor.setSelectedBufferRange([[5, 16], [5, 20]])
expect(editorView.find('.current-result')).toHaveLength 0
editor.setSelectedBufferRange([[5, 16], [5, 21]])
newResult = editorView.find('.current-result')
newPosition = resultPosition(newResult)
expect(newResult).toHaveLength 1
expect(newPosition).not.toBe originalPosition
describe "when user types in the find editor", ->
advance = ->
advanceClock(findView.findEditor.getEditor().getBuffer().stoppedChangingDelay + 1)
beforeEach ->
findView.findEditor.focus()
it "updates the search results", ->
expect(findView.descriptionLabel.text()).toContain "6 results"
findView.findEditor.setText 'why do I need these 2 lines? The editor does not trigger contents-modified without them'
advance()
findView.findEditor.setText ''
advance()
expect(findView.descriptionLabel.text()).toContain "Find in Current Buffer"
expect(findView).toHaveFocus()
findView.findEditor.setText 'sort'
advance()
expect(findView.descriptionLabel.text()).toContain "5 results"
expect(findView).toHaveFocus()
findView.findEditor.setText 'items'
advance()
expect(findView.descriptionLabel.text()).toContain "6 results"
expect(findView).toHaveFocus()
describe "when another find is called", ->
previousMarkers = null
beforeEach ->
previousMarkers = _.clone(editor.getMarkers())
it "clears existing markers for another search", ->
findView.findEditor.setText('notinthefile')
findView.findEditor.trigger 'core:confirm'
expect(editor.getMarkers().length).toEqual 1
it "clears existing markers for an empty search", ->
findView.findEditor.setText('')
findView.findEditor.trigger 'core:confirm'
expect(editor.getMarkers().length).toEqual 1
describe "replacing", ->
beforeEach ->
editor.setCursorBufferPosition([2,0])
editorView.trigger 'find-and-replace:show-replace'
waitsForPromise ->
activationPromise
runs ->
findView.findEditor.setText('items')
findView.replaceEditor.setText('cats')
describe "when the replacement string contains an escaped char", ->
describe "when the regex option is chosen", ->
beforeEach ->
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
it "inserts tabs and newlines", ->
findView.replaceEditor.setText('\\t\\n')
findView.replaceEditor.trigger 'core:confirm'
expect(editor.getText()).toMatch(/\t\n/)
it "doesn't insert a escaped char if there are multiple backslashs in front of the char", ->
findView.replaceEditor.setText('\\\\t\\\t')
findView.replaceEditor.trigger 'core:confirm'
expect(editor.getText()).toMatch(/\\t\\\t/)
describe "when in normal mode", ->
it "inserts backslach n and t", ->
findView.replaceEditor.setText('\\t\\n')
findView.replaceEditor.trigger 'core:confirm'
expect(editor.getText()).toMatch(/\\t\\n/)
it "inserts carriage returns", ->
textWithCarriageReturns = editor.getText().replace(/\n/g, "\r")
editor.setText(textWithCarriageReturns)
findView.replaceEditor.setText('\\t\\r')
findView.replaceEditor.trigger 'core:confirm'
expect(editor.getText()).toMatch(/\\t\\r/)
describe "replace next", ->
describe "when core:confirm is triggered", ->
it "replaces the match after the cursor and selects the next match", ->
findView.replaceEditor.trigger 'core:confirm'
expect(findView.resultCounter.text()).toEqual('2 of 5')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return items;"
expect(editor.getSelectedBufferRange()).toEqual [[2, 33], [2, 38]]
it "replaceEditor maintains focus after core:confirm is run", ->
findView.replaceEditor.focus()
findView.replaceEditor.trigger 'core:confirm'
expect(findView.replaceEditor).toHaveFocus()
it "replaces the _current_ match and selects the next match", ->
findView.findEditor.trigger 'core:confirm'
editor.setSelectedBufferRange([[2, 8], [2, 13]])
expect(findView.resultCounter.text()).toEqual('2 of 6')
findView.replaceEditor.trigger 'core:confirm'
expect(findView.resultCounter.text()).toEqual('2 of 5')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return items;"
expect(editor.getSelectedBufferRange()).toEqual [[2, 33], [2, 38]]
findView.replaceEditor.trigger 'core:confirm'
expect(findView.resultCounter.text()).toEqual('2 of 4')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return cats;"
expect(editor.getSelectedBufferRange()).toEqual [[3, 16], [3, 21]]
describe "when the replace next button is pressed", ->
it "replaces the match after the cursor and selects the next match", ->
$('.find-and-replace .btn-next').click()
expect(findView.resultCounter.text()).toEqual('2 of 5')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return items;"
expect(editor.getSelectedBufferRange()).toEqual [[2, 33], [2, 38]]
describe "when the 'find-and-replace:replace-next' event is triggered", ->
it "replaces the match after the cursor and selects the next match", ->
editorView.trigger 'find-and-replace:replace-next'
expect(findView.resultCounter.text()).toEqual('2 of 5')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return items;"
expect(editor.getSelectedBufferRange()).toEqual [[2, 33], [2, 38]]
describe "replace previous", ->
describe "when button is clicked", ->
it "replaces the match after the cursor and selects the previous match", ->
findView.findEditor.trigger 'core:confirm'
findView.replacePreviousButton.click()
expect(findView.resultCounter.text()).toEqual('1 of 5')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return items;"
expect(editor.getSelectedBufferRange()).toEqual [[1, 22], [1, 27]]
describe "when command is triggered", ->
it "replaces the match after the cursor and selects the previous match", ->
findView.findEditor.trigger 'core:confirm'
findView.trigger 'find-and-replace:replace-previous'
expect(findView.resultCounter.text()).toEqual('1 of 5')
expect(editor.lineForBufferRow(2)).toBe " if (cats.length <= 1) return items;"
expect(editor.getSelectedBufferRange()).toEqual [[1, 22], [1, 27]]
describe "replace all", ->
describe "when the replace all button is pressed", ->
it "replaces all matched text", ->
$('.find-and-replace .btn-all').click()
expect(findView.resultCounter.text()).toEqual('no results')
expect(editor.getText()).not.toMatch /items/
expect(editor.getText().match(/\bcats\b/g)).toHaveLength 6
expect(editor.getSelectedBufferRange()).toEqual [[2, 0], [2, 0]]
it "all changes are undoable in one transaction", ->
$('.find-and-replace .btn-all').click()
editor.undo()
expect(editor.getText()).not.toMatch /\bcats\b/g
describe "when the 'find-and-replace:replace-all' event is triggered", ->
it "replaces all matched text", ->
editorView.trigger 'find-and-replace:replace-all'
expect(findView.resultCounter.text()).toEqual('no results')
expect(editor.getText()).not.toMatch /items/
expect(editor.getText().match(/\bcats\b/g)).toHaveLength 6
expect(editor.getSelectedBufferRange()).toEqual [[2, 0], [2, 0]]
describe "replacement patterns", ->
describe "when the regex option is true", ->
it "replaces $1, $2, etc... with substring matches", ->
findView.findEditor.trigger 'find-and-replace:toggle-regex-option'
findView.findEditor.setText('(items)([\\.;])')
findView.replaceEditor.setText('$2$1')
editorView.trigger 'find-and-replace:replace-all'
expect(editor.getText()).toMatch /;items/
expect(editor.getText()).toMatch /\.items/
describe "when the regex option is false", ->
it "replaces the matches with without any regex subsitions", ->
findView.findEditor.setText('items')
findView.replaceEditor.setText('$&cats')
editorView.trigger 'find-and-replace:replace-all'
expect(editor.getText()).not.toMatch /items/
expect(editor.getText().match(/\$&cats\b/g)).toHaveLength 6
describe "history", ->
beforeEach ->
editorView.trigger 'find-and-replace:show'
waitsForPromise ->
activationPromise
describe "when there is no history", ->
it "retains unsearched text", ->
text = 'something I want to search for but havent yet'
findView.findEditor.setText(text)
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual ''
findView.findEditor.trigger 'core:move-down'
expect(findView.findEditor.getText()).toEqual text
describe "when there is history", ->
[oneRange, twoRange, threeRange] = []
beforeEach ->
editorView.trigger 'find-and-replace:show'
editor.setText("zero\none\ntwo\nthree\n")
findView.findEditor.setText('one')
findView.findEditor.trigger 'core:confirm'
findView.findEditor.setText('two')
findView.findEditor.trigger 'core:confirm'
findView.findEditor.setText('three')
findView.findEditor.trigger 'core:confirm'
it "can navigate the entire history stack", ->
expect(findView.findEditor.getText()).toEqual 'three'
findView.findEditor.trigger 'core:move-down'
expect(findView.findEditor.getText()).toEqual ''
findView.findEditor.trigger 'core:move-down'
expect(findView.findEditor.getText()).toEqual ''
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'three'
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'two'
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'one'
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'one'
findView.findEditor.trigger 'core:move-down'
expect(findView.findEditor.getText()).toEqual 'two'
it "retains the current unsearched text", ->
text = 'something I want to search for but havent yet'
findView.findEditor.setText(text)
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'three'
findView.findEditor.trigger 'core:move-down'
expect(findView.findEditor.getText()).toEqual text
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'three'
findView.findEditor.trigger 'core:move-down'
findView.findEditor.trigger 'core:confirm'
findView.findEditor.trigger 'core:move-down'
expect(findView.findEditor.getText()).toEqual ''
it "adds confirmed patterns to the history", ->
findView.findEditor.setText("cool stuff")
findView.findEditor.trigger 'core:confirm'
findView.findEditor.setText("cooler stuff")
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'cool stuff'
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'three'
describe "when user types in the find editor", ->
advance = ->
advanceClock(findView.findEditor.getEditor().getBuffer().stoppedChangingDelay + 1)
beforeEach ->
findView.findEditor.focus()
it "does not add live searches to the history", ->
expect(findView.descriptionLabel.text()).toContain "1 result"
# I really do not understand why this are necessary...
findView.findEditor.setText 'FIXME: necessary search for some reason??'
advance()
findView.findEditor.setText 'nope'
advance()
expect(findView.descriptionLabel.text()).toContain 'nope'
findView.findEditor.setText 'zero'
advance()
expect(findView.descriptionLabel.text()).toContain "zero"
findView.findEditor.trigger 'core:move-up'
expect(findView.findEditor.getText()).toEqual 'three'
|
[
{
"context": " \"support_letter\": {\n \"first_name\": first_name,\n \"last_name\": last_name,\n ",
"end": 3651,
"score": 0.7786914706230164,
"start": 3641,
"tag": "NAME",
"value": "first_name"
},
{
"context": "\"first_name\": first_name,\n \"last_name\": last_name,\n \"relationship_to_nominee\": relations",
"end": 3687,
"score": 0.8906338810920715,
"start": 3678,
"tag": "NAME",
"value": "last_name"
},
{
"context": "rror_message) ->\n key_selector = \".js-support-letter-\" + question_key.replace(/_/g, \"-\")\n ",
"end": 5120,
"score": 0.8572189807891846,
"start": 5109,
"tag": "KEY",
"value": "js-support-"
},
{
"context": " key_selector = \".js-support-letter-\" + question_key.replace(/_/g, \"-\")\n ",
"end": 5126,
"score": 0.5993695855140686,
"start": 5126,
"tag": "KEY",
"value": ""
}
] | app/assets/javascripts/frontend/custom_questions/support_letters.js.coffee | wowonrails/qae | 2 | window.SupportLetters =
init: ->
$('.js-support-letter-attachment').each (idx, el) ->
SupportLetters.fileupload_init(el)
SupportLetters.save_collection_init()
new_item_init: (el) ->
SupportLetters.clean_up_system_tags(el)
SupportLetters.enable_item_fields_and_controls(el)
SupportLetters.fileupload_init(el.find(".js-support-letter-attachment"))
fileupload_init: (el) ->
$el = $(el)
parent = $el.closest("label")
upload_done = (e, data) ->
SupportLetters.clean_up_system_tags(parent)
if data.result['original_filename']
filename = data.result['original_filename']
else
filename = "File uploaded"
file_title = $("<span class='support-letter-attachment-filename'>" + filename + "</span>")
hidden_input = $("<input class='js-support-letter-attachment-id' type='hidden' name='#{$el.attr("name")}' value='#{data.result['id']}' />")
parent.find(".errors-container").html("")
parent.find(".errors-container").closest("label").removeClass("question-has-errors")
parent.append(file_title)
parent.append(hidden_input)
SupportLetters.autosave()
failed = (error_message) ->
SupportLetters.clean_up_system_tags(parent)
parent.find(".errors-container").html("<li>" + error_message + "</li>")
parent.closest("label").addClass("question-has-errors")
success_or_error = (e, data) ->
errors = data.result.errors
if errors
failed(errors.toString())
else
upload_done(e, data)
$el.fileupload(
url: $el.closest(".list-add").data('attachments-url') + ".json"
forceIframeTransport: true
dataType: 'json'
formData: [
{ name: "authenticity_token", value: $("meta[name='csrf-token']").attr("content") }
]
always: success_or_error
)
clean_up_system_tags: (parent) ->
parent.find("input[type='hidden']").remove()
parent.find(".support-letter-attachment-filename").remove()
enable_item_fields_and_controls: (parent) ->
parent.find(".js-save-collection").removeClass("visuallyhidden")
parent.find(".visible-read-only").hide()
parent.find(".remove-link").removeClass("visuallyhidden")
fields = parent.find("input")
fields.removeClass("read-only")
parent.find(".errors-container").html("")
form_name_prefix = parent.find(".js-system-tag").data("new-hidden-input-name")
letter_id_hidden_input = $("<input class='js-support-entry-id'>").prop('type', 'hidden').
prop('name', form_name_prefix)
parent.append(letter_id_hidden_input)
disable_item_fields_and_controls: (parent) ->
parent.find(".js-save-collection").addClass("visuallyhidden")
parent.find(".visible-read-only").show()
parent.find(".remove-link").addClass("visuallyhidden")
fields = parent.find("input")
fields.addClass("read-only")
save_collection_init: () ->
$(document).on 'click', '.js-save-collection', ->
button = $(this)
parent = $(this).closest("li")
if !button.hasClass("visuallyhidden")
save_url = button.data 'save-collection-url'
first_name = parent.find(".js-support-letter-first-name").val()
last_name = parent.find(".js-support-letter-last-name").val()
email = parent.find(".js-support-letter-email").val()
relationship_to_nominee = parent.find(".js-support-letter-relationship-to-nominee").val()
attachment_id = parent.find(".js-support-letter-attachment-id").val()
data = {
"support_letter": {
"first_name": first_name,
"last_name": last_name,
"relationship_to_nominee": relationship_to_nominee
}
}
if attachment_id
data["support_letter"]["attachment"] = attachment_id
if email
data["support_letter"]["email"] = email
if save_url
$.ajax
url: save_url
type: 'post'
data: data
dataType: 'json'
success: (response) ->
parent.find(".js-support-entry-id").prop('value', response)
parent.find(".errors-container").html("")
parent.find(".errors-container").closest("label").addClass("question-has-errors")
parent.addClass("read-only")
parent.addClass("js-support-letter-received")
parent.find("input[type='text']").each ->
show_el = $(this).closest("label").find(".visible-read-only")
show_el.text($(this).val())
SupportLetters.disable_item_fields_and_controls(parent)
SupportLetters.autosave()
return
error: (response) ->
parent.find(".errors-container").html("")
parent.find(".errors-container").closest("label").removeClass("question-has-errors")
error_message = response.responseText
$.each $.parseJSON(response.responseText), (question_key, error_message) ->
key_selector = ".js-support-letter-" + question_key.replace(/_/g, "-")
field_error_container = parent.find(key_selector).
closest("label").
find(".errors-container")
field_error_container.html("<li>" + error_message[0] + "</li>")
field_error_container.closest("label").addClass("question-has-errors")
button.removeClass("visuallyhidden")
return
autosave: () ->
url = $('form.qae-form').data('autosave-url')
if url
# Setting current_step_id to form as we updating only current section form_data (not whole form)
$("#current_step_id").val($(".js-step-condition.step-current").attr("data-step"))
form_data = $('form.qae-form').serialize()
$.ajax({
url: url
data: form_data
type: 'POST'
dataType: 'json'
})
| 4660 | window.SupportLetters =
init: ->
$('.js-support-letter-attachment').each (idx, el) ->
SupportLetters.fileupload_init(el)
SupportLetters.save_collection_init()
new_item_init: (el) ->
SupportLetters.clean_up_system_tags(el)
SupportLetters.enable_item_fields_and_controls(el)
SupportLetters.fileupload_init(el.find(".js-support-letter-attachment"))
fileupload_init: (el) ->
$el = $(el)
parent = $el.closest("label")
upload_done = (e, data) ->
SupportLetters.clean_up_system_tags(parent)
if data.result['original_filename']
filename = data.result['original_filename']
else
filename = "File uploaded"
file_title = $("<span class='support-letter-attachment-filename'>" + filename + "</span>")
hidden_input = $("<input class='js-support-letter-attachment-id' type='hidden' name='#{$el.attr("name")}' value='#{data.result['id']}' />")
parent.find(".errors-container").html("")
parent.find(".errors-container").closest("label").removeClass("question-has-errors")
parent.append(file_title)
parent.append(hidden_input)
SupportLetters.autosave()
failed = (error_message) ->
SupportLetters.clean_up_system_tags(parent)
parent.find(".errors-container").html("<li>" + error_message + "</li>")
parent.closest("label").addClass("question-has-errors")
success_or_error = (e, data) ->
errors = data.result.errors
if errors
failed(errors.toString())
else
upload_done(e, data)
$el.fileupload(
url: $el.closest(".list-add").data('attachments-url') + ".json"
forceIframeTransport: true
dataType: 'json'
formData: [
{ name: "authenticity_token", value: $("meta[name='csrf-token']").attr("content") }
]
always: success_or_error
)
clean_up_system_tags: (parent) ->
parent.find("input[type='hidden']").remove()
parent.find(".support-letter-attachment-filename").remove()
enable_item_fields_and_controls: (parent) ->
parent.find(".js-save-collection").removeClass("visuallyhidden")
parent.find(".visible-read-only").hide()
parent.find(".remove-link").removeClass("visuallyhidden")
fields = parent.find("input")
fields.removeClass("read-only")
parent.find(".errors-container").html("")
form_name_prefix = parent.find(".js-system-tag").data("new-hidden-input-name")
letter_id_hidden_input = $("<input class='js-support-entry-id'>").prop('type', 'hidden').
prop('name', form_name_prefix)
parent.append(letter_id_hidden_input)
disable_item_fields_and_controls: (parent) ->
parent.find(".js-save-collection").addClass("visuallyhidden")
parent.find(".visible-read-only").show()
parent.find(".remove-link").addClass("visuallyhidden")
fields = parent.find("input")
fields.addClass("read-only")
save_collection_init: () ->
$(document).on 'click', '.js-save-collection', ->
button = $(this)
parent = $(this).closest("li")
if !button.hasClass("visuallyhidden")
save_url = button.data 'save-collection-url'
first_name = parent.find(".js-support-letter-first-name").val()
last_name = parent.find(".js-support-letter-last-name").val()
email = parent.find(".js-support-letter-email").val()
relationship_to_nominee = parent.find(".js-support-letter-relationship-to-nominee").val()
attachment_id = parent.find(".js-support-letter-attachment-id").val()
data = {
"support_letter": {
"first_name": <NAME>,
"last_name": <NAME>,
"relationship_to_nominee": relationship_to_nominee
}
}
if attachment_id
data["support_letter"]["attachment"] = attachment_id
if email
data["support_letter"]["email"] = email
if save_url
$.ajax
url: save_url
type: 'post'
data: data
dataType: 'json'
success: (response) ->
parent.find(".js-support-entry-id").prop('value', response)
parent.find(".errors-container").html("")
parent.find(".errors-container").closest("label").addClass("question-has-errors")
parent.addClass("read-only")
parent.addClass("js-support-letter-received")
parent.find("input[type='text']").each ->
show_el = $(this).closest("label").find(".visible-read-only")
show_el.text($(this).val())
SupportLetters.disable_item_fields_and_controls(parent)
SupportLetters.autosave()
return
error: (response) ->
parent.find(".errors-container").html("")
parent.find(".errors-container").closest("label").removeClass("question-has-errors")
error_message = response.responseText
$.each $.parseJSON(response.responseText), (question_key, error_message) ->
key_selector = ".<KEY>letter<KEY>-" + question_key.replace(/_/g, "-")
field_error_container = parent.find(key_selector).
closest("label").
find(".errors-container")
field_error_container.html("<li>" + error_message[0] + "</li>")
field_error_container.closest("label").addClass("question-has-errors")
button.removeClass("visuallyhidden")
return
autosave: () ->
url = $('form.qae-form').data('autosave-url')
if url
# Setting current_step_id to form as we updating only current section form_data (not whole form)
$("#current_step_id").val($(".js-step-condition.step-current").attr("data-step"))
form_data = $('form.qae-form').serialize()
$.ajax({
url: url
data: form_data
type: 'POST'
dataType: 'json'
})
| true | window.SupportLetters =
init: ->
$('.js-support-letter-attachment').each (idx, el) ->
SupportLetters.fileupload_init(el)
SupportLetters.save_collection_init()
new_item_init: (el) ->
SupportLetters.clean_up_system_tags(el)
SupportLetters.enable_item_fields_and_controls(el)
SupportLetters.fileupload_init(el.find(".js-support-letter-attachment"))
fileupload_init: (el) ->
$el = $(el)
parent = $el.closest("label")
upload_done = (e, data) ->
SupportLetters.clean_up_system_tags(parent)
if data.result['original_filename']
filename = data.result['original_filename']
else
filename = "File uploaded"
file_title = $("<span class='support-letter-attachment-filename'>" + filename + "</span>")
hidden_input = $("<input class='js-support-letter-attachment-id' type='hidden' name='#{$el.attr("name")}' value='#{data.result['id']}' />")
parent.find(".errors-container").html("")
parent.find(".errors-container").closest("label").removeClass("question-has-errors")
parent.append(file_title)
parent.append(hidden_input)
SupportLetters.autosave()
failed = (error_message) ->
SupportLetters.clean_up_system_tags(parent)
parent.find(".errors-container").html("<li>" + error_message + "</li>")
parent.closest("label").addClass("question-has-errors")
success_or_error = (e, data) ->
errors = data.result.errors
if errors
failed(errors.toString())
else
upload_done(e, data)
$el.fileupload(
url: $el.closest(".list-add").data('attachments-url') + ".json"
forceIframeTransport: true
dataType: 'json'
formData: [
{ name: "authenticity_token", value: $("meta[name='csrf-token']").attr("content") }
]
always: success_or_error
)
clean_up_system_tags: (parent) ->
parent.find("input[type='hidden']").remove()
parent.find(".support-letter-attachment-filename").remove()
enable_item_fields_and_controls: (parent) ->
parent.find(".js-save-collection").removeClass("visuallyhidden")
parent.find(".visible-read-only").hide()
parent.find(".remove-link").removeClass("visuallyhidden")
fields = parent.find("input")
fields.removeClass("read-only")
parent.find(".errors-container").html("")
form_name_prefix = parent.find(".js-system-tag").data("new-hidden-input-name")
letter_id_hidden_input = $("<input class='js-support-entry-id'>").prop('type', 'hidden').
prop('name', form_name_prefix)
parent.append(letter_id_hidden_input)
disable_item_fields_and_controls: (parent) ->
parent.find(".js-save-collection").addClass("visuallyhidden")
parent.find(".visible-read-only").show()
parent.find(".remove-link").addClass("visuallyhidden")
fields = parent.find("input")
fields.addClass("read-only")
save_collection_init: () ->
$(document).on 'click', '.js-save-collection', ->
button = $(this)
parent = $(this).closest("li")
if !button.hasClass("visuallyhidden")
save_url = button.data 'save-collection-url'
first_name = parent.find(".js-support-letter-first-name").val()
last_name = parent.find(".js-support-letter-last-name").val()
email = parent.find(".js-support-letter-email").val()
relationship_to_nominee = parent.find(".js-support-letter-relationship-to-nominee").val()
attachment_id = parent.find(".js-support-letter-attachment-id").val()
data = {
"support_letter": {
"first_name": PI:NAME:<NAME>END_PI,
"last_name": PI:NAME:<NAME>END_PI,
"relationship_to_nominee": relationship_to_nominee
}
}
if attachment_id
data["support_letter"]["attachment"] = attachment_id
if email
data["support_letter"]["email"] = email
if save_url
$.ajax
url: save_url
type: 'post'
data: data
dataType: 'json'
success: (response) ->
parent.find(".js-support-entry-id").prop('value', response)
parent.find(".errors-container").html("")
parent.find(".errors-container").closest("label").addClass("question-has-errors")
parent.addClass("read-only")
parent.addClass("js-support-letter-received")
parent.find("input[type='text']").each ->
show_el = $(this).closest("label").find(".visible-read-only")
show_el.text($(this).val())
SupportLetters.disable_item_fields_and_controls(parent)
SupportLetters.autosave()
return
error: (response) ->
parent.find(".errors-container").html("")
parent.find(".errors-container").closest("label").removeClass("question-has-errors")
error_message = response.responseText
$.each $.parseJSON(response.responseText), (question_key, error_message) ->
key_selector = ".PI:KEY:<KEY>END_PIletterPI:KEY:<KEY>END_PI-" + question_key.replace(/_/g, "-")
field_error_container = parent.find(key_selector).
closest("label").
find(".errors-container")
field_error_container.html("<li>" + error_message[0] + "</li>")
field_error_container.closest("label").addClass("question-has-errors")
button.removeClass("visuallyhidden")
return
autosave: () ->
url = $('form.qae-form').data('autosave-url')
if url
# Setting current_step_id to form as we updating only current section form_data (not whole form)
$("#current_step_id").val($(".js-step-condition.step-current").attr("data-step"))
form_data = $('form.qae-form').serialize()
$.ajax({
url: url
data: form_data
type: 'POST'
dataType: 'json'
})
|
[
{
"context": "=new studentModel\n# sno: '123456'\n# sname: '123456'\n# gender: '男'\n# class: '123456'\n# depar",
"end": 501,
"score": 0.79005366563797,
"start": 495,
"tag": "NAME",
"value": "123456"
}
] | test/studentTest.coffee | ycjcl868/StudentInfo | 0 | db = require('../config/database');
mongoose = require 'mongoose'
studentModel = require('../model/Student');
#for i in [20113092..20113122]
# studentEntity = new student
# sno: '' + i
# sname: '' + i
# gender: if Math.random() > 0.5 then '男' else '女'
# class: '2011221'
# department: '软件工程系'
# console.log studentEntity
# studentEntity.save((err)->if err?
# console.log err)
#studentEntity=new studentModel
# sno: '123456'
# sname: '123456'
# gender: '男'
# class: '123456'
# department: '123456'
# birthday: new Date()
#studentEntity.save() | 23469 | db = require('../config/database');
mongoose = require 'mongoose'
studentModel = require('../model/Student');
#for i in [20113092..20113122]
# studentEntity = new student
# sno: '' + i
# sname: '' + i
# gender: if Math.random() > 0.5 then '男' else '女'
# class: '2011221'
# department: '软件工程系'
# console.log studentEntity
# studentEntity.save((err)->if err?
# console.log err)
#studentEntity=new studentModel
# sno: '123456'
# sname: '<NAME>'
# gender: '男'
# class: '123456'
# department: '123456'
# birthday: new Date()
#studentEntity.save() | true | db = require('../config/database');
mongoose = require 'mongoose'
studentModel = require('../model/Student');
#for i in [20113092..20113122]
# studentEntity = new student
# sno: '' + i
# sname: '' + i
# gender: if Math.random() > 0.5 then '男' else '女'
# class: '2011221'
# department: '软件工程系'
# console.log studentEntity
# studentEntity.save((err)->if err?
# console.log err)
#studentEntity=new studentModel
# sno: '123456'
# sname: 'PI:NAME:<NAME>END_PI'
# gender: '男'
# class: '123456'
# department: '123456'
# birthday: new Date()
#studentEntity.save() |
[
{
"context": "ated by the following individuals:\n# Ethernet by Michael Anthony from The Noun Project\n# Wireless by Piotrek Chu",
"end": 361,
"score": 0.9998860359191895,
"start": 346,
"tag": "NAME",
"value": "Michael Anthony"
},
{
"context": "hael Anthony from The Noun Project\n# Wireless by Piotrek Chuchla from The Noun Project\n#\n#------------------------",
"end": 415,
"score": 0.9999012351036072,
"start": 400,
"tag": "NAME",
"value": "Piotrek Chuchla"
}
] | network-info.widget/network-info.widget.coffee | orbitbot/ubersicht-widgets | 0 | #--------------------------------------------------------------------------------------
# Please Read
#--------------------------------------------------------------------------------------
# The images used in this widget are from the Noun Project (http://thenounproject.com).
#
# They were created by the following individuals:
# Ethernet by Michael Anthony from The Noun Project
# Wireless by Piotrek Chuchla from The Noun Project
#
#--------------------------------------------------------------------------------------
# Execute the shell command.
command: "network-info.widget/network_info.sh"
# Set the refresh frequency (milliseconds).
refreshFrequency: 5000
# Render the output.
render: (output) -> """
<div id='services'>
<div id='ethernet' class='service'>
<p class='primaryInfo'></p>
<p class='secondaryInfo'></p>
</div>
<div id='wi-fi' class='service'>
<p class='primaryInfo'></p>
<p class='secondaryInfo'></p>
</div>
</div>
"""
# Update the rendered output.
update: (output, domEl) ->
dom = $(domEl)
# Parse the JSON created by the shell script.
data = JSON.parse output
html = ""
# Loop through the services in the JSON.
for svc in data.service
disabled = svc.ipaddress == ""
el = $('#'+svc.name)
el.find('.primaryInfo').text(svc.ipaddress || 'Not connected')
el.find('.secondaryInfo').text(if !disabled then svc.macaddress else '')
el.toggleClass('disabled', disabled)
# CSS Style
style: """
margin:0
padding:0px
right:48px
bottom: 22px
#wi-fi
background: url(/network-info.widget/images/wi-fi_light.png)
&.disabled
background: url(/network-info.widget/images/wi-fi_disabled.png)
display: none
#ethernet
background: url(/network-info.widget/images/ethernet.png)
&.disabled
background: url(/network-info.widget/images/ethernet_disabled.png)
display: none
#wi-fi, #ethernet, #wi-fi.disabled, #ethernet.disabled
height: 40px
width: 100px
background-position: left 1px
background-repeat: no-repeat
background-size: 32px 32px
.service
padding: 2px 2px 2px 42px
.primaryInfo, .secondaryInfo
font-family: Helvetica Neue
padding:0px
margin:2px
.primaryInfo
font-size: 8pt
font-weight: bold
color: rgba(#fff, 0.5)
.secondaryInfo
font-size: 8pt
color: rgba(#fff, 0.35)
.disabled p
color: rgba(#000, 0.35)
""" | 120650 | #--------------------------------------------------------------------------------------
# Please Read
#--------------------------------------------------------------------------------------
# The images used in this widget are from the Noun Project (http://thenounproject.com).
#
# They were created by the following individuals:
# Ethernet by <NAME> from The Noun Project
# Wireless by <NAME> from The Noun Project
#
#--------------------------------------------------------------------------------------
# Execute the shell command.
command: "network-info.widget/network_info.sh"
# Set the refresh frequency (milliseconds).
refreshFrequency: 5000
# Render the output.
render: (output) -> """
<div id='services'>
<div id='ethernet' class='service'>
<p class='primaryInfo'></p>
<p class='secondaryInfo'></p>
</div>
<div id='wi-fi' class='service'>
<p class='primaryInfo'></p>
<p class='secondaryInfo'></p>
</div>
</div>
"""
# Update the rendered output.
update: (output, domEl) ->
dom = $(domEl)
# Parse the JSON created by the shell script.
data = JSON.parse output
html = ""
# Loop through the services in the JSON.
for svc in data.service
disabled = svc.ipaddress == ""
el = $('#'+svc.name)
el.find('.primaryInfo').text(svc.ipaddress || 'Not connected')
el.find('.secondaryInfo').text(if !disabled then svc.macaddress else '')
el.toggleClass('disabled', disabled)
# CSS Style
style: """
margin:0
padding:0px
right:48px
bottom: 22px
#wi-fi
background: url(/network-info.widget/images/wi-fi_light.png)
&.disabled
background: url(/network-info.widget/images/wi-fi_disabled.png)
display: none
#ethernet
background: url(/network-info.widget/images/ethernet.png)
&.disabled
background: url(/network-info.widget/images/ethernet_disabled.png)
display: none
#wi-fi, #ethernet, #wi-fi.disabled, #ethernet.disabled
height: 40px
width: 100px
background-position: left 1px
background-repeat: no-repeat
background-size: 32px 32px
.service
padding: 2px 2px 2px 42px
.primaryInfo, .secondaryInfo
font-family: Helvetica Neue
padding:0px
margin:2px
.primaryInfo
font-size: 8pt
font-weight: bold
color: rgba(#fff, 0.5)
.secondaryInfo
font-size: 8pt
color: rgba(#fff, 0.35)
.disabled p
color: rgba(#000, 0.35)
""" | true | #--------------------------------------------------------------------------------------
# Please Read
#--------------------------------------------------------------------------------------
# The images used in this widget are from the Noun Project (http://thenounproject.com).
#
# They were created by the following individuals:
# Ethernet by PI:NAME:<NAME>END_PI from The Noun Project
# Wireless by PI:NAME:<NAME>END_PI from The Noun Project
#
#--------------------------------------------------------------------------------------
# Execute the shell command.
command: "network-info.widget/network_info.sh"
# Set the refresh frequency (milliseconds).
refreshFrequency: 5000
# Render the output.
render: (output) -> """
<div id='services'>
<div id='ethernet' class='service'>
<p class='primaryInfo'></p>
<p class='secondaryInfo'></p>
</div>
<div id='wi-fi' class='service'>
<p class='primaryInfo'></p>
<p class='secondaryInfo'></p>
</div>
</div>
"""
# Update the rendered output.
update: (output, domEl) ->
dom = $(domEl)
# Parse the JSON created by the shell script.
data = JSON.parse output
html = ""
# Loop through the services in the JSON.
for svc in data.service
disabled = svc.ipaddress == ""
el = $('#'+svc.name)
el.find('.primaryInfo').text(svc.ipaddress || 'Not connected')
el.find('.secondaryInfo').text(if !disabled then svc.macaddress else '')
el.toggleClass('disabled', disabled)
# CSS Style
style: """
margin:0
padding:0px
right:48px
bottom: 22px
#wi-fi
background: url(/network-info.widget/images/wi-fi_light.png)
&.disabled
background: url(/network-info.widget/images/wi-fi_disabled.png)
display: none
#ethernet
background: url(/network-info.widget/images/ethernet.png)
&.disabled
background: url(/network-info.widget/images/ethernet_disabled.png)
display: none
#wi-fi, #ethernet, #wi-fi.disabled, #ethernet.disabled
height: 40px
width: 100px
background-position: left 1px
background-repeat: no-repeat
background-size: 32px 32px
.service
padding: 2px 2px 2px 42px
.primaryInfo, .secondaryInfo
font-family: Helvetica Neue
padding:0px
margin:2px
.primaryInfo
font-size: 8pt
font-weight: bold
color: rgba(#fff, 0.5)
.secondaryInfo
font-size: 8pt
color: rgba(#fff, 0.35)
.disabled p
color: rgba(#000, 0.35)
""" |
[
{
"context": "abLength: 4\n \"exception-reporting\":\n userId: \"1a71acde-aaec-49ce-a555-e567e98fcbaf\"\n github:\n remoteFetchProtocol: \"ssh\"\n \"lint",
"end": 516,
"score": 0.9746516346931458,
"start": 480,
"tag": "PASSWORD",
"value": "1a71acde-aaec-49ce-a555-e567e98fcbaf"
}
] | config.cson | pgrepds/atom-config | 0 | "*":
Hydrogen:
gateways: '''
[{
"name": "Remote server",
"options": {
"baseUrl": "http://localhost:8888",
}
}]
'''
globalMode: true
languageMappings: "{ \"sagemath\": \"Sage\", \"python\": \"magicpython\" }"
"autocomplete-python":
useKite: false
core:
telemetryConsent: "no"
editor:
fontSize: 18
lineHeight: 1.75
showIndentGuide: true
tabLength: 4
"exception-reporting":
userId: "1a71acde-aaec-49ce-a555-e567e98fcbaf"
github:
remoteFetchProtocol: "ssh"
"linter-flake8":
ignoreErrorCodes: [
"E305"
]
maxLineLength: 200
minimap:
plugins:
"highlight-selected": true
"highlight-selectedDecorationsZIndex": 0
"one-dark-ui":
fontSize: 16
"preview-inline":
previewMode: "all"
"python-autopep8":
formatOnSave: true
welcome:
showOnStartup: false
| 141976 | "*":
Hydrogen:
gateways: '''
[{
"name": "Remote server",
"options": {
"baseUrl": "http://localhost:8888",
}
}]
'''
globalMode: true
languageMappings: "{ \"sagemath\": \"Sage\", \"python\": \"magicpython\" }"
"autocomplete-python":
useKite: false
core:
telemetryConsent: "no"
editor:
fontSize: 18
lineHeight: 1.75
showIndentGuide: true
tabLength: 4
"exception-reporting":
userId: "<PASSWORD>"
github:
remoteFetchProtocol: "ssh"
"linter-flake8":
ignoreErrorCodes: [
"E305"
]
maxLineLength: 200
minimap:
plugins:
"highlight-selected": true
"highlight-selectedDecorationsZIndex": 0
"one-dark-ui":
fontSize: 16
"preview-inline":
previewMode: "all"
"python-autopep8":
formatOnSave: true
welcome:
showOnStartup: false
| true | "*":
Hydrogen:
gateways: '''
[{
"name": "Remote server",
"options": {
"baseUrl": "http://localhost:8888",
}
}]
'''
globalMode: true
languageMappings: "{ \"sagemath\": \"Sage\", \"python\": \"magicpython\" }"
"autocomplete-python":
useKite: false
core:
telemetryConsent: "no"
editor:
fontSize: 18
lineHeight: 1.75
showIndentGuide: true
tabLength: 4
"exception-reporting":
userId: "PI:PASSWORD:<PASSWORD>END_PI"
github:
remoteFetchProtocol: "ssh"
"linter-flake8":
ignoreErrorCodes: [
"E305"
]
maxLineLength: 200
minimap:
plugins:
"highlight-selected": true
"highlight-selectedDecorationsZIndex": 0
"one-dark-ui":
fontSize: 16
"preview-inline":
previewMode: "all"
"python-autopep8":
formatOnSave: true
welcome:
showOnStartup: false
|
[
{
"context": "# Author: Josh Bass\n\nReact = require(\"react\");\nmathjs = require(\"math",
"end": 19,
"score": 0.9998685121536255,
"start": 10,
"tag": "NAME",
"value": "Josh Bass"
},
{
"context": " getInitialState: ->\n @filter_types = [{key: \"first_name\", name: \"First Name\", type: \"text\"}, {key: \"",
"end": 385,
"score": 0.9639043807983398,
"start": 380,
"tag": "NAME",
"value": "first"
},
{
"context": "nitialState: ->\n @filter_types = [{key: \"first_name\", name: \"First Name\", type: \"text\"}, {key: \"middl",
"end": 390,
"score": 0.5241771340370178,
"start": 386,
"tag": "NAME",
"value": "name"
},
{
"context": ">\n @filter_types = [{key: \"first_name\", name: \"First Name\", type: \"text\"}, {key: \"middle_name\", name: \"Midd",
"end": 410,
"score": 0.8044557571411133,
"start": 400,
"tag": "NAME",
"value": "First Name"
},
{
"context": "_name\", name: \"First Name\", type: \"text\"}, {key: \"middle_name\", name: \"Middle Name\", type: \"text\"}, \\\n ",
"end": 441,
"score": 0.9610432386398315,
"start": 435,
"tag": "NAME",
"value": "middle"
},
{
"context": "Name\", type: \"text\"}, {key: \"middle_name\", name: \"Middle Name\", type: \"text\"}, \\\n {key: \"last_name\", ",
"end": 462,
"score": 0.5906233787536621,
"start": 456,
"tag": "NAME",
"value": "Middle"
},
{
"context": "ame: \"Middle Name\", type: \"text\"}, \\\n {key: \"last_name\", name: \"Last Name\", type: \"text\"}, {key: \"a",
"end": 504,
"score": 0.9541233777999878,
"start": 500,
"tag": "NAME",
"value": "last"
},
{
"context": "\"Middle Name\", type: \"text\"}, \\\n {key: \"last_name\", name: \"Last Name\", type: \"text\"}, {key: \"addres",
"end": 509,
"score": 0.6069515943527222,
"start": 505,
"tag": "NAME",
"value": "name"
},
{
"context": " type: \"text\"}, \\\n {key: \"last_name\", name: \"Last Name\", type: \"text\"}, {key: \"address\", name: \"Address\"",
"end": 528,
"score": 0.8378654718399048,
"start": 519,
"tag": "NAME",
"value": "Last Name"
}
] | src/client/components/customers/CustomerView.coffee | jbass86/Aroma | 0 | # Author: Josh Bass
React = require("react");
mathjs = require("mathjs");
CreateCustomer = require("./CustomerCreate.coffee");
CustomerTable = require("./CustomerTable.coffee");
Filters = require("client/components/filters/FiltersView.coffee");
css = require("./res/styles/customers.scss")
module.exports = React.createClass
getInitialState: ->
@filter_types = [{key: "first_name", name: "First Name", type: "text"}, {key: "middle_name", name: "Middle Name", type: "text"}, \
{key: "last_name", name: "Last Name", type: "text"}, {key: "address", name: "Address", type: "text"}, \
{key: "email", name: "Email", type: "text"}, {key: "phone_number", name: "Phone Number", type: "text"}, \
{key: "social_media", name: "Social Media", type: "text"}, {key: "birthday", name: "Birthday", type: "date"}];
{customers: [], filters: {}};
componentDidMount: ->
@updateCustomers();
render: ->
<div className="common-view customer-view">
<div className="section-title">
Customers
</div>
<CreateCustomer customerUpdate={@updateCustomers} />
<Filters filterTypes={@filter_types} applyFilters={@applyFilters} name="customer_filters" />
<CustomerTable customerUpdate={@updateCustomers} items={@state.customers} order_model={@props.order_model} />
</div>
applyFilters: (filters) ->
@setState({filters: filters}, () =>
@updateCustomers();
);
updateCustomers: () ->
$.get("aroma/secure/get_customers", {token: window.sessionStorage.token, filters: @state.filters}, (response) =>
if (response.success)
@setState(customers: response.results);
);
| 191985 | # Author: <NAME>
React = require("react");
mathjs = require("mathjs");
CreateCustomer = require("./CustomerCreate.coffee");
CustomerTable = require("./CustomerTable.coffee");
Filters = require("client/components/filters/FiltersView.coffee");
css = require("./res/styles/customers.scss")
module.exports = React.createClass
getInitialState: ->
@filter_types = [{key: "<NAME>_<NAME>", name: "<NAME>", type: "text"}, {key: "<NAME>_name", name: "<NAME> Name", type: "text"}, \
{key: "<NAME>_<NAME>", name: "<NAME>", type: "text"}, {key: "address", name: "Address", type: "text"}, \
{key: "email", name: "Email", type: "text"}, {key: "phone_number", name: "Phone Number", type: "text"}, \
{key: "social_media", name: "Social Media", type: "text"}, {key: "birthday", name: "Birthday", type: "date"}];
{customers: [], filters: {}};
componentDidMount: ->
@updateCustomers();
render: ->
<div className="common-view customer-view">
<div className="section-title">
Customers
</div>
<CreateCustomer customerUpdate={@updateCustomers} />
<Filters filterTypes={@filter_types} applyFilters={@applyFilters} name="customer_filters" />
<CustomerTable customerUpdate={@updateCustomers} items={@state.customers} order_model={@props.order_model} />
</div>
applyFilters: (filters) ->
@setState({filters: filters}, () =>
@updateCustomers();
);
updateCustomers: () ->
$.get("aroma/secure/get_customers", {token: window.sessionStorage.token, filters: @state.filters}, (response) =>
if (response.success)
@setState(customers: response.results);
);
| true | # Author: PI:NAME:<NAME>END_PI
React = require("react");
mathjs = require("mathjs");
CreateCustomer = require("./CustomerCreate.coffee");
CustomerTable = require("./CustomerTable.coffee");
Filters = require("client/components/filters/FiltersView.coffee");
css = require("./res/styles/customers.scss")
module.exports = React.createClass
getInitialState: ->
@filter_types = [{key: "PI:NAME:<NAME>END_PI_PI:NAME:<NAME>END_PI", name: "PI:NAME:<NAME>END_PI", type: "text"}, {key: "PI:NAME:<NAME>END_PI_name", name: "PI:NAME:<NAME>END_PI Name", type: "text"}, \
{key: "PI:NAME:<NAME>END_PI_PI:NAME:<NAME>END_PI", name: "PI:NAME:<NAME>END_PI", type: "text"}, {key: "address", name: "Address", type: "text"}, \
{key: "email", name: "Email", type: "text"}, {key: "phone_number", name: "Phone Number", type: "text"}, \
{key: "social_media", name: "Social Media", type: "text"}, {key: "birthday", name: "Birthday", type: "date"}];
{customers: [], filters: {}};
componentDidMount: ->
@updateCustomers();
render: ->
<div className="common-view customer-view">
<div className="section-title">
Customers
</div>
<CreateCustomer customerUpdate={@updateCustomers} />
<Filters filterTypes={@filter_types} applyFilters={@applyFilters} name="customer_filters" />
<CustomerTable customerUpdate={@updateCustomers} items={@state.customers} order_model={@props.order_model} />
</div>
applyFilters: (filters) ->
@setState({filters: filters}, () =>
@updateCustomers();
);
updateCustomers: () ->
$.get("aroma/secure/get_customers", {token: window.sessionStorage.token, filters: @state.filters}, (response) =>
if (response.success)
@setState(customers: response.results);
);
|
[
{
"context": "\t\t\t\t@newAccessLevel = 'tokenBased'\n\t\t\t\t@tokens = {readOnly: 'aaa', readAndWrite: '42bbb'}\n\t\t\t\t@ProjectDetail",
"end": 16833,
"score": 0.8922584056854248,
"start": 16825,
"tag": "KEY",
"value": "readOnly"
},
{
"context": "essLevel = 'tokenBased'\n\t\t\t\t@tokens = {readOnly: 'aaa', readAndWrite: '42bbb'}\n\t\t\t\t@ProjectDetailsHandl",
"end": 16839,
"score": 0.9374321699142456,
"start": 16836,
"tag": "KEY",
"value": "aaa"
},
{
"context": "d'\n\t\t\t\t@tokens = {readOnly: 'aaa', readAndWrite: '42bbb'}\n\t\t\t\t@ProjectDetailsHandler.ensureTokensArePrese",
"end": 16862,
"score": 0.9948733448982239,
"start": 16857,
"tag": "KEY",
"value": "42bbb"
}
] | test/unit/coffee/Editor/EditorControllerTests.coffee | davidmehren/web-sharelatex | 0 | SandboxedModule = require('sandboxed-module')
sinon = require('sinon')
require('chai').should()
expect = require("chai").expect
modulePath = require('path').join __dirname, '../../../../app/js/Features/Editor/EditorController'
MockClient = require "../helpers/MockClient"
assert = require('assert')
describe "EditorController", ->
beforeEach ->
@project_id = "test-project-id"
@source = "dropbox"
@doc = _id: @doc_id = "test-doc-id"
@docName = "doc.tex"
@docLines = ["1234","dskl"]
@file = _id: @file_id ="dasdkjk"
@fileName = "file.png"
@fsPath = "/folder/file.png"
@linkedFileData = {provider: 'url'}
@newFile = _id: "new-file-id"
@folder_id = "123ksajdn"
@folder = _id: @folder_id
@folderName = "folder"
@callback = sinon.stub()
@EditorController = SandboxedModule.require modulePath, requires:
'../Project/ProjectEntityUpdateHandler' : @ProjectEntityUpdateHandler = {}
'../Project/ProjectOptionsHandler' : @ProjectOptionsHandler =
setCompiler: sinon.stub().yields()
setSpellCheckLanguage: sinon.stub().yields()
'../Project/ProjectDetailsHandler': @ProjectDetailsHandler =
setProjectDescription: sinon.stub().yields()
renameProject: sinon.stub().yields()
setPublicAccessLevel: sinon.stub().yields()
'../Project/ProjectDeleter' : @ProjectDeleter = {}
'../DocumentUpdater/DocumentUpdaterHandler' : @DocumentUpdaterHandler =
flushDocToMongo: sinon.stub().yields()
setDocument: sinon.stub().yields()
'./EditorRealTimeController':@EditorRealTimeController =
emitToRoom: sinon.stub()
"metrics-sharelatex": @Metrics = inc: sinon.stub()
"logger-sharelatex": @logger =
log: sinon.stub()
err: sinon.stub()
describe 'addDoc', ->
beforeEach ->
@ProjectEntityUpdateHandler.addDoc = sinon.stub().yields(null, @doc, @folder_id)
@EditorController.addDoc @project_id, @folder_id, @docName, @docLines, @source, @user_id, @callback
it 'should add the doc using the project entity handler', ->
@ProjectEntityUpdateHandler.addDoc
.calledWith(@project_id, @folder_id, @docName, @docLines)
.should.equal true
it 'should send the update out to the users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewDoc", @folder_id, @doc, @source)
.should.equal true
it 'calls the callback', ->
@callback.calledWith(null, @doc).should.equal true
describe 'addFile', ->
beforeEach ->
@ProjectEntityUpdateHandler.addFile = sinon.stub().yields(null, @file, @folder_id)
@EditorController.addFile @project_id, @folder_id, @fileName, @fsPath, @linkedFileData, @source, @user_id, @callback
it 'should add the folder using the project entity handler', ->
@ProjectEntityUpdateHandler.addFile
.calledWith(@project_id, @folder_id, @fileName, @fsPath, @linkedFileData, @user_id)
.should.equal true
it 'should send the update of a new folder out to the users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFile", @folder_id, @file, @source, @linkedFileData)
.should.equal true
it 'calls the callback', ->
@callback.calledWith(null, @file).should.equal true
describe 'upsertDoc', ->
beforeEach ->
@ProjectEntityUpdateHandler.upsertDoc = sinon.stub().yields(null, @doc, false)
@EditorController.upsertDoc @project_id, @folder_id, @docName, @docLines, @source, @user_id, @callback
it 'upserts the doc using the project entity handler', ->
@ProjectEntityUpdateHandler.upsertDoc
.calledWith(@project_id, @folder_id, @docName, @docLines, @source)
.should.equal true
it 'returns the doc', ->
@callback.calledWith(null, @doc).should.equal true
describe 'doc does not exist', ->
beforeEach ->
@ProjectEntityUpdateHandler.upsertDoc = sinon.stub().yields(null, @doc, true)
@EditorController.upsertDoc @project_id, @folder_id, @docName, @docLines, @source, @user_id, @callback
it 'sends an update out to users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewDoc", @folder_id, @doc, @source)
.should.equal true
describe 'upsertFile', ->
beforeEach ->
@ProjectEntityUpdateHandler.upsertFile = sinon.stub().yields(null, @newFile, false, @file)
@EditorController.upsertFile @project_id, @folder_id, @fileName, @fsPath, @linkedFileData, @source, @user_id, @callback
it 'upserts the file using the project entity handler', ->
@ProjectEntityUpdateHandler.upsertFile
.calledWith(@project_id, @folder_id, @fileName, @fsPath, @linkedFileData, @user_id)
.should.equal true
it 'returns the file', ->
@callback.calledWith(null, @newFile).should.equal true
describe 'file does not exist', ->
beforeEach ->
@ProjectEntityUpdateHandler.upsertFile = sinon.stub().yields(null, @file, true)
@EditorController.upsertFile @project_id, @folder_id, @fileName, @fsPath, @linkedFileData, @source, @user_id, @callback
it 'should send the update out to users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFile", @folder_id, @file, @source, @linkedFileData)
.should.equal true
describe "upsertDocWithPath", ->
beforeEach ->
@docPath = '/folder/doc'
@ProjectEntityUpdateHandler.upsertDocWithPath = sinon.stub().yields(null, @doc, false, [], @folder)
@EditorController.upsertDocWithPath @project_id, @docPath, @docLines, @source, @user_id, @callback
it 'upserts the doc using the project entity handler', ->
@ProjectEntityUpdateHandler.upsertDocWithPath
.calledWith(@project_id, @docPath, @docLines, @source)
.should.equal true
describe 'doc does not exist', ->
beforeEach ->
@ProjectEntityUpdateHandler.upsertDocWithPath = sinon.stub().yields(null, @doc, true, [], @folder)
@EditorController.upsertDocWithPath @project_id, @docPath, @docLines, @source, @user_id, @callback
it 'should send the update for the doc out to users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewDoc", @folder_id, @doc, @source)
.should.equal true
describe 'folders required for doc do not exist', ->
beforeEach ->
folders = [
@folderA = { _id: 2, parentFolder_id: 1}
@folderB = { _id: 3, parentFolder_id: 2}
]
@ProjectEntityUpdateHandler.upsertDocWithPath = sinon.stub().yields(null, @doc, true, folders, @folderB)
@EditorController.upsertDocWithPath @project_id, @docPath, @docLines, @source, @user_id, @callback
it 'should send the update for each folder to users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFolder", @folderA.parentFolder_id, @folderA)
.should.equal true
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFolder", @folderB.parentFolder_id, @folderB)
.should.equal true
describe "upsertFileWithPath", ->
beforeEach ->
@filePath = '/folder/file'
@ProjectEntityUpdateHandler.upsertFileWithPath = sinon.stub().yields(null, @newFile, false, @file, [], @folder)
@EditorController.upsertFileWithPath @project_id, @filePath, @fsPath, @linkedFileData, @source, @user_id, @callback
it 'upserts the file using the project entity handler', ->
@ProjectEntityUpdateHandler.upsertFileWithPath
.calledWith(@project_id, @filePath, @fsPath, @linkedFileData)
.should.equal true
describe 'file does not exist', ->
beforeEach ->
@ProjectEntityUpdateHandler.upsertFileWithPath = sinon.stub().yields(null, @file, true, undefined, [], @folder)
@EditorController.upsertFileWithPath @project_id, @filePath, @fsPath, @linkedFileData, @source, @user_id, @callback
it 'should send the update for the file out to users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFile", @folder_id, @file, @source, @linkedFileData)
.should.equal true
describe 'folders required for file do not exist', ->
beforeEach ->
folders = [
@folderA = { _id: 2, parentFolder_id: 1}
@folderB = { _id: 3, parentFolder_id: 2}
]
@ProjectEntityUpdateHandler.upsertFileWithPath = sinon.stub().yields(null, @file, true, undefined, folders, @folderB)
@EditorController.upsertFileWithPath @project_id, @filePath, @fsPath, @linkedFileData, @source, @user_id, @callback
it 'should send the update for each folder to users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFolder", @folderA.parentFolder_id, @folderA)
.should.equal true
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFolder", @folderB.parentFolder_id, @folderB)
.should.equal true
describe 'addFolder', ->
beforeEach ->
@EditorController._notifyProjectUsersOfNewFolder = sinon.stub().yields()
@ProjectEntityUpdateHandler.addFolder = sinon.stub().yields(null, @folder, @folder_id)
@EditorController.addFolder @project_id, @folder_id, @folderName, @source, @callback
it 'should add the folder using the project entity handler', ->
@ProjectEntityUpdateHandler.addFolder
.calledWith(@project_id, @folder_id, @folderName)
.should.equal true
it 'should notifyProjectUsersOfNewFolder', ->
@EditorController._notifyProjectUsersOfNewFolder
.calledWith(@project_id, @folder_id, @folder)
it 'should return the folder in the callback', ->
@callback.calledWith(null, @folder).should.equal true
describe 'mkdirp', ->
beforeEach ->
@path = "folder1/folder2"
@folders = [
@folderA = { _id: 2, parentFolder_id: 1}
@folderB = { _id: 3, parentFolder_id: 2}
]
@EditorController._notifyProjectUsersOfNewFolders = sinon.stub().yields()
@ProjectEntityUpdateHandler.mkdirp = sinon.stub().yields(null, @folders, @folder)
@EditorController.mkdirp @project_id, @path, @callback
it 'should create the folder using the project entity handler', ->
@ProjectEntityUpdateHandler.mkdirp
.calledWith(@project_id, @path)
.should.equal true
it 'should notifyProjectUsersOfNewFolder', ->
@EditorController._notifyProjectUsersOfNewFolders
.calledWith(@project_id, @folders)
it 'should return the folder in the callback', ->
@callback.calledWith(null, @folders, @folder).should.equal true
describe 'deleteEntity', ->
beforeEach ->
@entity_id = "entity_id_here"
@type = "doc"
@ProjectEntityUpdateHandler.deleteEntity = sinon.stub().yields()
@EditorController.deleteEntity @project_id, @entity_id, @type, @source, @user_id, @callback
it 'should delete the folder using the project entity handler', ->
@ProjectEntityUpdateHandler.deleteEntity
.calledWith(@project_id, @entity_id, @type, @user_id)
.should.equal.true
it 'notify users an entity has been deleted', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "removeEntity", @entity_id, @source)
.should.equal true
describe "deleteEntityWithPath", ->
beforeEach () ->
@entity_id = "entity_id_here"
@ProjectEntityUpdateHandler.deleteEntityWithPath = sinon.stub().yields(null, @entity_id)
@path = "folder1/folder2"
@EditorController.deleteEntityWithPath @project_id, @path, @source, @user_id, @callback
it 'should delete the folder using the project entity handler', ->
@ProjectEntityUpdateHandler.deleteEntityWithPath
.calledWith(@project_id, @path, @user_id)
.should.equal.true
it 'notify users an entity has been deleted', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "removeEntity", @entity_id, @source)
.should.equal true
describe "notifyUsersProjectHasBeenDeletedOrRenamed", ->
it 'should emmit a message to all users in a project', (done)->
@EditorController.notifyUsersProjectHasBeenDeletedOrRenamed @project_id, (err)=>
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "projectRenamedOrDeletedByExternalSource")
.should.equal true
done()
describe "updateProjectDescription", ->
beforeEach ->
@description = "new description"
@EditorController.updateProjectDescription @project_id, @description, @callback
it "should send the new description to the project details handler", ->
@ProjectDetailsHandler.setProjectDescription.calledWith(@project_id, @description).should.equal true
it "should notify the other clients about the updated description", ->
@EditorRealTimeController.emitToRoom.calledWith(@project_id, "projectDescriptionUpdated", @description).should.equal true
describe "deleteProject", ->
beforeEach ->
@err = "errro"
@ProjectDeleter.deleteProject = sinon.stub().callsArgWith(1, @err)
it "should call the project handler", (done)->
@EditorController.deleteProject @project_id, (err)=>
err.should.equal @err
@ProjectDeleter.deleteProject.calledWith(@project_id).should.equal true
done()
describe "renameEntity", ->
beforeEach (done) ->
@entity_id = "entity_id_here"
@entityType = "doc"
@newName = "bobsfile.tex"
@ProjectEntityUpdateHandler.renameEntity = sinon.stub().yields()
@EditorController.renameEntity @project_id, @entity_id, @entityType, @newName, @user_id, done
it "should call the project handler", ->
@ProjectEntityUpdateHandler.renameEntity
.calledWith(@project_id, @entity_id, @entityType, @newName, @user_id)
.should.equal true
it "should emit the update to the room", ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'reciveEntityRename', @entity_id, @newName)
.should.equal true
describe "moveEntity", ->
beforeEach ->
@entity_id = "entity_id_here"
@entityType = "doc"
@ProjectEntityUpdateHandler.moveEntity = sinon.stub().yields()
@EditorController.moveEntity @project_id, @entity_id, @folder_id, @entityType, @user_id, @callback
it "should call the ProjectEntityUpdateHandler", ->
@ProjectEntityUpdateHandler.moveEntity
.calledWith(@project_id, @entity_id, @folder_id, @entityType, @user_id)
.should.equal true
it "should emit the update to the room", ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'reciveEntityMove', @entity_id, @folder_id)
.should.equal true
it "calls the callback", ->
@callback.called.should.equal true
describe "renameProject", ->
beforeEach ->
@err = "errro"
@newName = "new name here"
@EditorController.renameProject @project_id, @newName, @callback
it "should call the EditorController", ->
@ProjectDetailsHandler.renameProject.calledWith(@project_id, @newName).should.equal true
it "should emit the update to the room", ->
@EditorRealTimeController.emitToRoom.calledWith(@project_id, 'projectNameUpdated', @newName).should.equal true
describe "setCompiler", ->
beforeEach ->
@compiler = "latex"
@EditorController.setCompiler @project_id, @compiler, @callback
it "should send the new compiler and project id to the project options handler", ->
@ProjectOptionsHandler.setCompiler
.calledWith(@project_id, @compiler)
.should.equal true
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "compilerUpdated", @compiler)
.should.equal true
describe "setSpellCheckLanguage", ->
beforeEach ->
@languageCode = "fr"
@EditorController.setSpellCheckLanguage @project_id, @languageCode, @callback
it "should send the new languageCode and project id to the project options handler", ->
@ProjectOptionsHandler.setSpellCheckLanguage
.calledWith(@project_id, @languageCode)
.should.equal true
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "spellCheckLanguageUpdated", @languageCode)
.should.equal true
describe "setPublicAccessLevel", ->
describe 'when setting to private', ->
beforeEach ->
@newAccessLevel = 'private'
@ProjectDetailsHandler.ensureTokensArePresent = sinon.stub().yields(null, @tokens)
@EditorController.setPublicAccessLevel @project_id, @newAccessLevel, @callback
it 'should set the access level', ->
@ProjectDetailsHandler.setPublicAccessLevel
.calledWith(@project_id, @newAccessLevel)
.should.equal true
it 'should broadcast the access level change', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'project:publicAccessLevel:changed')
.should.equal true
it 'should not ensure tokens are present for project', ->
@ProjectDetailsHandler.ensureTokensArePresent
.calledWith(@project_id)
.should.equal false
it 'should not broadcast a token change', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'project:tokens:changed', {tokens: @tokens})
.should.equal false
describe 'when setting to tokenBased', ->
beforeEach ->
@newAccessLevel = 'tokenBased'
@tokens = {readOnly: 'aaa', readAndWrite: '42bbb'}
@ProjectDetailsHandler.ensureTokensArePresent = sinon.stub().yields(null, @tokens)
@EditorController.setPublicAccessLevel @project_id, @newAccessLevel, @callback
it 'should set the access level', ->
@ProjectDetailsHandler.setPublicAccessLevel
.calledWith(@project_id, @newAccessLevel)
.should.equal true
it 'should broadcast the access level change', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'project:publicAccessLevel:changed')
.should.equal true
it 'should ensure tokens are present for project', ->
@ProjectDetailsHandler.ensureTokensArePresent
.calledWith(@project_id)
.should.equal true
it 'should broadcast the token change too', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'project:tokens:changed', {tokens: @tokens})
.should.equal true
describe "setRootDoc", ->
beforeEach ->
@newRootDocID = "21312321321"
@ProjectEntityUpdateHandler.setRootDoc = sinon.stub().yields()
@EditorController.setRootDoc @project_id, @newRootDocID, @callback
it "should call the ProjectEntityUpdateHandler", ->
@ProjectEntityUpdateHandler.setRootDoc
.calledWith(@project_id, @newRootDocID)
.should.equal true
it "should emit the update to the room", ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'rootDocUpdated', @newRootDocID)
.should.equal true
| 37401 | SandboxedModule = require('sandboxed-module')
sinon = require('sinon')
require('chai').should()
expect = require("chai").expect
modulePath = require('path').join __dirname, '../../../../app/js/Features/Editor/EditorController'
MockClient = require "../helpers/MockClient"
assert = require('assert')
describe "EditorController", ->
beforeEach ->
@project_id = "test-project-id"
@source = "dropbox"
@doc = _id: @doc_id = "test-doc-id"
@docName = "doc.tex"
@docLines = ["1234","dskl"]
@file = _id: @file_id ="dasdkjk"
@fileName = "file.png"
@fsPath = "/folder/file.png"
@linkedFileData = {provider: 'url'}
@newFile = _id: "new-file-id"
@folder_id = "123ksajdn"
@folder = _id: @folder_id
@folderName = "folder"
@callback = sinon.stub()
@EditorController = SandboxedModule.require modulePath, requires:
'../Project/ProjectEntityUpdateHandler' : @ProjectEntityUpdateHandler = {}
'../Project/ProjectOptionsHandler' : @ProjectOptionsHandler =
setCompiler: sinon.stub().yields()
setSpellCheckLanguage: sinon.stub().yields()
'../Project/ProjectDetailsHandler': @ProjectDetailsHandler =
setProjectDescription: sinon.stub().yields()
renameProject: sinon.stub().yields()
setPublicAccessLevel: sinon.stub().yields()
'../Project/ProjectDeleter' : @ProjectDeleter = {}
'../DocumentUpdater/DocumentUpdaterHandler' : @DocumentUpdaterHandler =
flushDocToMongo: sinon.stub().yields()
setDocument: sinon.stub().yields()
'./EditorRealTimeController':@EditorRealTimeController =
emitToRoom: sinon.stub()
"metrics-sharelatex": @Metrics = inc: sinon.stub()
"logger-sharelatex": @logger =
log: sinon.stub()
err: sinon.stub()
describe 'addDoc', ->
beforeEach ->
@ProjectEntityUpdateHandler.addDoc = sinon.stub().yields(null, @doc, @folder_id)
@EditorController.addDoc @project_id, @folder_id, @docName, @docLines, @source, @user_id, @callback
it 'should add the doc using the project entity handler', ->
@ProjectEntityUpdateHandler.addDoc
.calledWith(@project_id, @folder_id, @docName, @docLines)
.should.equal true
it 'should send the update out to the users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewDoc", @folder_id, @doc, @source)
.should.equal true
it 'calls the callback', ->
@callback.calledWith(null, @doc).should.equal true
describe 'addFile', ->
beforeEach ->
@ProjectEntityUpdateHandler.addFile = sinon.stub().yields(null, @file, @folder_id)
@EditorController.addFile @project_id, @folder_id, @fileName, @fsPath, @linkedFileData, @source, @user_id, @callback
it 'should add the folder using the project entity handler', ->
@ProjectEntityUpdateHandler.addFile
.calledWith(@project_id, @folder_id, @fileName, @fsPath, @linkedFileData, @user_id)
.should.equal true
it 'should send the update of a new folder out to the users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFile", @folder_id, @file, @source, @linkedFileData)
.should.equal true
it 'calls the callback', ->
@callback.calledWith(null, @file).should.equal true
describe 'upsertDoc', ->
beforeEach ->
@ProjectEntityUpdateHandler.upsertDoc = sinon.stub().yields(null, @doc, false)
@EditorController.upsertDoc @project_id, @folder_id, @docName, @docLines, @source, @user_id, @callback
it 'upserts the doc using the project entity handler', ->
@ProjectEntityUpdateHandler.upsertDoc
.calledWith(@project_id, @folder_id, @docName, @docLines, @source)
.should.equal true
it 'returns the doc', ->
@callback.calledWith(null, @doc).should.equal true
describe 'doc does not exist', ->
beforeEach ->
@ProjectEntityUpdateHandler.upsertDoc = sinon.stub().yields(null, @doc, true)
@EditorController.upsertDoc @project_id, @folder_id, @docName, @docLines, @source, @user_id, @callback
it 'sends an update out to users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewDoc", @folder_id, @doc, @source)
.should.equal true
describe 'upsertFile', ->
beforeEach ->
@ProjectEntityUpdateHandler.upsertFile = sinon.stub().yields(null, @newFile, false, @file)
@EditorController.upsertFile @project_id, @folder_id, @fileName, @fsPath, @linkedFileData, @source, @user_id, @callback
it 'upserts the file using the project entity handler', ->
@ProjectEntityUpdateHandler.upsertFile
.calledWith(@project_id, @folder_id, @fileName, @fsPath, @linkedFileData, @user_id)
.should.equal true
it 'returns the file', ->
@callback.calledWith(null, @newFile).should.equal true
describe 'file does not exist', ->
beforeEach ->
@ProjectEntityUpdateHandler.upsertFile = sinon.stub().yields(null, @file, true)
@EditorController.upsertFile @project_id, @folder_id, @fileName, @fsPath, @linkedFileData, @source, @user_id, @callback
it 'should send the update out to users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFile", @folder_id, @file, @source, @linkedFileData)
.should.equal true
describe "upsertDocWithPath", ->
beforeEach ->
@docPath = '/folder/doc'
@ProjectEntityUpdateHandler.upsertDocWithPath = sinon.stub().yields(null, @doc, false, [], @folder)
@EditorController.upsertDocWithPath @project_id, @docPath, @docLines, @source, @user_id, @callback
it 'upserts the doc using the project entity handler', ->
@ProjectEntityUpdateHandler.upsertDocWithPath
.calledWith(@project_id, @docPath, @docLines, @source)
.should.equal true
describe 'doc does not exist', ->
beforeEach ->
@ProjectEntityUpdateHandler.upsertDocWithPath = sinon.stub().yields(null, @doc, true, [], @folder)
@EditorController.upsertDocWithPath @project_id, @docPath, @docLines, @source, @user_id, @callback
it 'should send the update for the doc out to users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewDoc", @folder_id, @doc, @source)
.should.equal true
describe 'folders required for doc do not exist', ->
beforeEach ->
folders = [
@folderA = { _id: 2, parentFolder_id: 1}
@folderB = { _id: 3, parentFolder_id: 2}
]
@ProjectEntityUpdateHandler.upsertDocWithPath = sinon.stub().yields(null, @doc, true, folders, @folderB)
@EditorController.upsertDocWithPath @project_id, @docPath, @docLines, @source, @user_id, @callback
it 'should send the update for each folder to users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFolder", @folderA.parentFolder_id, @folderA)
.should.equal true
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFolder", @folderB.parentFolder_id, @folderB)
.should.equal true
describe "upsertFileWithPath", ->
beforeEach ->
@filePath = '/folder/file'
@ProjectEntityUpdateHandler.upsertFileWithPath = sinon.stub().yields(null, @newFile, false, @file, [], @folder)
@EditorController.upsertFileWithPath @project_id, @filePath, @fsPath, @linkedFileData, @source, @user_id, @callback
it 'upserts the file using the project entity handler', ->
@ProjectEntityUpdateHandler.upsertFileWithPath
.calledWith(@project_id, @filePath, @fsPath, @linkedFileData)
.should.equal true
describe 'file does not exist', ->
beforeEach ->
@ProjectEntityUpdateHandler.upsertFileWithPath = sinon.stub().yields(null, @file, true, undefined, [], @folder)
@EditorController.upsertFileWithPath @project_id, @filePath, @fsPath, @linkedFileData, @source, @user_id, @callback
it 'should send the update for the file out to users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFile", @folder_id, @file, @source, @linkedFileData)
.should.equal true
describe 'folders required for file do not exist', ->
beforeEach ->
folders = [
@folderA = { _id: 2, parentFolder_id: 1}
@folderB = { _id: 3, parentFolder_id: 2}
]
@ProjectEntityUpdateHandler.upsertFileWithPath = sinon.stub().yields(null, @file, true, undefined, folders, @folderB)
@EditorController.upsertFileWithPath @project_id, @filePath, @fsPath, @linkedFileData, @source, @user_id, @callback
it 'should send the update for each folder to users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFolder", @folderA.parentFolder_id, @folderA)
.should.equal true
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFolder", @folderB.parentFolder_id, @folderB)
.should.equal true
describe 'addFolder', ->
beforeEach ->
@EditorController._notifyProjectUsersOfNewFolder = sinon.stub().yields()
@ProjectEntityUpdateHandler.addFolder = sinon.stub().yields(null, @folder, @folder_id)
@EditorController.addFolder @project_id, @folder_id, @folderName, @source, @callback
it 'should add the folder using the project entity handler', ->
@ProjectEntityUpdateHandler.addFolder
.calledWith(@project_id, @folder_id, @folderName)
.should.equal true
it 'should notifyProjectUsersOfNewFolder', ->
@EditorController._notifyProjectUsersOfNewFolder
.calledWith(@project_id, @folder_id, @folder)
it 'should return the folder in the callback', ->
@callback.calledWith(null, @folder).should.equal true
describe 'mkdirp', ->
beforeEach ->
@path = "folder1/folder2"
@folders = [
@folderA = { _id: 2, parentFolder_id: 1}
@folderB = { _id: 3, parentFolder_id: 2}
]
@EditorController._notifyProjectUsersOfNewFolders = sinon.stub().yields()
@ProjectEntityUpdateHandler.mkdirp = sinon.stub().yields(null, @folders, @folder)
@EditorController.mkdirp @project_id, @path, @callback
it 'should create the folder using the project entity handler', ->
@ProjectEntityUpdateHandler.mkdirp
.calledWith(@project_id, @path)
.should.equal true
it 'should notifyProjectUsersOfNewFolder', ->
@EditorController._notifyProjectUsersOfNewFolders
.calledWith(@project_id, @folders)
it 'should return the folder in the callback', ->
@callback.calledWith(null, @folders, @folder).should.equal true
describe 'deleteEntity', ->
beforeEach ->
@entity_id = "entity_id_here"
@type = "doc"
@ProjectEntityUpdateHandler.deleteEntity = sinon.stub().yields()
@EditorController.deleteEntity @project_id, @entity_id, @type, @source, @user_id, @callback
it 'should delete the folder using the project entity handler', ->
@ProjectEntityUpdateHandler.deleteEntity
.calledWith(@project_id, @entity_id, @type, @user_id)
.should.equal.true
it 'notify users an entity has been deleted', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "removeEntity", @entity_id, @source)
.should.equal true
describe "deleteEntityWithPath", ->
beforeEach () ->
@entity_id = "entity_id_here"
@ProjectEntityUpdateHandler.deleteEntityWithPath = sinon.stub().yields(null, @entity_id)
@path = "folder1/folder2"
@EditorController.deleteEntityWithPath @project_id, @path, @source, @user_id, @callback
it 'should delete the folder using the project entity handler', ->
@ProjectEntityUpdateHandler.deleteEntityWithPath
.calledWith(@project_id, @path, @user_id)
.should.equal.true
it 'notify users an entity has been deleted', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "removeEntity", @entity_id, @source)
.should.equal true
describe "notifyUsersProjectHasBeenDeletedOrRenamed", ->
it 'should emmit a message to all users in a project', (done)->
@EditorController.notifyUsersProjectHasBeenDeletedOrRenamed @project_id, (err)=>
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "projectRenamedOrDeletedByExternalSource")
.should.equal true
done()
describe "updateProjectDescription", ->
beforeEach ->
@description = "new description"
@EditorController.updateProjectDescription @project_id, @description, @callback
it "should send the new description to the project details handler", ->
@ProjectDetailsHandler.setProjectDescription.calledWith(@project_id, @description).should.equal true
it "should notify the other clients about the updated description", ->
@EditorRealTimeController.emitToRoom.calledWith(@project_id, "projectDescriptionUpdated", @description).should.equal true
describe "deleteProject", ->
beforeEach ->
@err = "errro"
@ProjectDeleter.deleteProject = sinon.stub().callsArgWith(1, @err)
it "should call the project handler", (done)->
@EditorController.deleteProject @project_id, (err)=>
err.should.equal @err
@ProjectDeleter.deleteProject.calledWith(@project_id).should.equal true
done()
describe "renameEntity", ->
beforeEach (done) ->
@entity_id = "entity_id_here"
@entityType = "doc"
@newName = "bobsfile.tex"
@ProjectEntityUpdateHandler.renameEntity = sinon.stub().yields()
@EditorController.renameEntity @project_id, @entity_id, @entityType, @newName, @user_id, done
it "should call the project handler", ->
@ProjectEntityUpdateHandler.renameEntity
.calledWith(@project_id, @entity_id, @entityType, @newName, @user_id)
.should.equal true
it "should emit the update to the room", ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'reciveEntityRename', @entity_id, @newName)
.should.equal true
describe "moveEntity", ->
beforeEach ->
@entity_id = "entity_id_here"
@entityType = "doc"
@ProjectEntityUpdateHandler.moveEntity = sinon.stub().yields()
@EditorController.moveEntity @project_id, @entity_id, @folder_id, @entityType, @user_id, @callback
it "should call the ProjectEntityUpdateHandler", ->
@ProjectEntityUpdateHandler.moveEntity
.calledWith(@project_id, @entity_id, @folder_id, @entityType, @user_id)
.should.equal true
it "should emit the update to the room", ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'reciveEntityMove', @entity_id, @folder_id)
.should.equal true
it "calls the callback", ->
@callback.called.should.equal true
describe "renameProject", ->
beforeEach ->
@err = "errro"
@newName = "new name here"
@EditorController.renameProject @project_id, @newName, @callback
it "should call the EditorController", ->
@ProjectDetailsHandler.renameProject.calledWith(@project_id, @newName).should.equal true
it "should emit the update to the room", ->
@EditorRealTimeController.emitToRoom.calledWith(@project_id, 'projectNameUpdated', @newName).should.equal true
describe "setCompiler", ->
beforeEach ->
@compiler = "latex"
@EditorController.setCompiler @project_id, @compiler, @callback
it "should send the new compiler and project id to the project options handler", ->
@ProjectOptionsHandler.setCompiler
.calledWith(@project_id, @compiler)
.should.equal true
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "compilerUpdated", @compiler)
.should.equal true
describe "setSpellCheckLanguage", ->
beforeEach ->
@languageCode = "fr"
@EditorController.setSpellCheckLanguage @project_id, @languageCode, @callback
it "should send the new languageCode and project id to the project options handler", ->
@ProjectOptionsHandler.setSpellCheckLanguage
.calledWith(@project_id, @languageCode)
.should.equal true
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "spellCheckLanguageUpdated", @languageCode)
.should.equal true
describe "setPublicAccessLevel", ->
describe 'when setting to private', ->
beforeEach ->
@newAccessLevel = 'private'
@ProjectDetailsHandler.ensureTokensArePresent = sinon.stub().yields(null, @tokens)
@EditorController.setPublicAccessLevel @project_id, @newAccessLevel, @callback
it 'should set the access level', ->
@ProjectDetailsHandler.setPublicAccessLevel
.calledWith(@project_id, @newAccessLevel)
.should.equal true
it 'should broadcast the access level change', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'project:publicAccessLevel:changed')
.should.equal true
it 'should not ensure tokens are present for project', ->
@ProjectDetailsHandler.ensureTokensArePresent
.calledWith(@project_id)
.should.equal false
it 'should not broadcast a token change', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'project:tokens:changed', {tokens: @tokens})
.should.equal false
describe 'when setting to tokenBased', ->
beforeEach ->
@newAccessLevel = 'tokenBased'
@tokens = {<KEY>: '<KEY>', readAndWrite: '<KEY>'}
@ProjectDetailsHandler.ensureTokensArePresent = sinon.stub().yields(null, @tokens)
@EditorController.setPublicAccessLevel @project_id, @newAccessLevel, @callback
it 'should set the access level', ->
@ProjectDetailsHandler.setPublicAccessLevel
.calledWith(@project_id, @newAccessLevel)
.should.equal true
it 'should broadcast the access level change', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'project:publicAccessLevel:changed')
.should.equal true
it 'should ensure tokens are present for project', ->
@ProjectDetailsHandler.ensureTokensArePresent
.calledWith(@project_id)
.should.equal true
it 'should broadcast the token change too', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'project:tokens:changed', {tokens: @tokens})
.should.equal true
describe "setRootDoc", ->
beforeEach ->
@newRootDocID = "21312321321"
@ProjectEntityUpdateHandler.setRootDoc = sinon.stub().yields()
@EditorController.setRootDoc @project_id, @newRootDocID, @callback
it "should call the ProjectEntityUpdateHandler", ->
@ProjectEntityUpdateHandler.setRootDoc
.calledWith(@project_id, @newRootDocID)
.should.equal true
it "should emit the update to the room", ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'rootDocUpdated', @newRootDocID)
.should.equal true
| true | SandboxedModule = require('sandboxed-module')
sinon = require('sinon')
require('chai').should()
expect = require("chai").expect
modulePath = require('path').join __dirname, '../../../../app/js/Features/Editor/EditorController'
MockClient = require "../helpers/MockClient"
assert = require('assert')
describe "EditorController", ->
beforeEach ->
@project_id = "test-project-id"
@source = "dropbox"
@doc = _id: @doc_id = "test-doc-id"
@docName = "doc.tex"
@docLines = ["1234","dskl"]
@file = _id: @file_id ="dasdkjk"
@fileName = "file.png"
@fsPath = "/folder/file.png"
@linkedFileData = {provider: 'url'}
@newFile = _id: "new-file-id"
@folder_id = "123ksajdn"
@folder = _id: @folder_id
@folderName = "folder"
@callback = sinon.stub()
@EditorController = SandboxedModule.require modulePath, requires:
'../Project/ProjectEntityUpdateHandler' : @ProjectEntityUpdateHandler = {}
'../Project/ProjectOptionsHandler' : @ProjectOptionsHandler =
setCompiler: sinon.stub().yields()
setSpellCheckLanguage: sinon.stub().yields()
'../Project/ProjectDetailsHandler': @ProjectDetailsHandler =
setProjectDescription: sinon.stub().yields()
renameProject: sinon.stub().yields()
setPublicAccessLevel: sinon.stub().yields()
'../Project/ProjectDeleter' : @ProjectDeleter = {}
'../DocumentUpdater/DocumentUpdaterHandler' : @DocumentUpdaterHandler =
flushDocToMongo: sinon.stub().yields()
setDocument: sinon.stub().yields()
'./EditorRealTimeController':@EditorRealTimeController =
emitToRoom: sinon.stub()
"metrics-sharelatex": @Metrics = inc: sinon.stub()
"logger-sharelatex": @logger =
log: sinon.stub()
err: sinon.stub()
describe 'addDoc', ->
beforeEach ->
@ProjectEntityUpdateHandler.addDoc = sinon.stub().yields(null, @doc, @folder_id)
@EditorController.addDoc @project_id, @folder_id, @docName, @docLines, @source, @user_id, @callback
it 'should add the doc using the project entity handler', ->
@ProjectEntityUpdateHandler.addDoc
.calledWith(@project_id, @folder_id, @docName, @docLines)
.should.equal true
it 'should send the update out to the users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewDoc", @folder_id, @doc, @source)
.should.equal true
it 'calls the callback', ->
@callback.calledWith(null, @doc).should.equal true
describe 'addFile', ->
beforeEach ->
@ProjectEntityUpdateHandler.addFile = sinon.stub().yields(null, @file, @folder_id)
@EditorController.addFile @project_id, @folder_id, @fileName, @fsPath, @linkedFileData, @source, @user_id, @callback
it 'should add the folder using the project entity handler', ->
@ProjectEntityUpdateHandler.addFile
.calledWith(@project_id, @folder_id, @fileName, @fsPath, @linkedFileData, @user_id)
.should.equal true
it 'should send the update of a new folder out to the users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFile", @folder_id, @file, @source, @linkedFileData)
.should.equal true
it 'calls the callback', ->
@callback.calledWith(null, @file).should.equal true
describe 'upsertDoc', ->
beforeEach ->
@ProjectEntityUpdateHandler.upsertDoc = sinon.stub().yields(null, @doc, false)
@EditorController.upsertDoc @project_id, @folder_id, @docName, @docLines, @source, @user_id, @callback
it 'upserts the doc using the project entity handler', ->
@ProjectEntityUpdateHandler.upsertDoc
.calledWith(@project_id, @folder_id, @docName, @docLines, @source)
.should.equal true
it 'returns the doc', ->
@callback.calledWith(null, @doc).should.equal true
describe 'doc does not exist', ->
beforeEach ->
@ProjectEntityUpdateHandler.upsertDoc = sinon.stub().yields(null, @doc, true)
@EditorController.upsertDoc @project_id, @folder_id, @docName, @docLines, @source, @user_id, @callback
it 'sends an update out to users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewDoc", @folder_id, @doc, @source)
.should.equal true
describe 'upsertFile', ->
beforeEach ->
@ProjectEntityUpdateHandler.upsertFile = sinon.stub().yields(null, @newFile, false, @file)
@EditorController.upsertFile @project_id, @folder_id, @fileName, @fsPath, @linkedFileData, @source, @user_id, @callback
it 'upserts the file using the project entity handler', ->
@ProjectEntityUpdateHandler.upsertFile
.calledWith(@project_id, @folder_id, @fileName, @fsPath, @linkedFileData, @user_id)
.should.equal true
it 'returns the file', ->
@callback.calledWith(null, @newFile).should.equal true
describe 'file does not exist', ->
beforeEach ->
@ProjectEntityUpdateHandler.upsertFile = sinon.stub().yields(null, @file, true)
@EditorController.upsertFile @project_id, @folder_id, @fileName, @fsPath, @linkedFileData, @source, @user_id, @callback
it 'should send the update out to users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFile", @folder_id, @file, @source, @linkedFileData)
.should.equal true
describe "upsertDocWithPath", ->
beforeEach ->
@docPath = '/folder/doc'
@ProjectEntityUpdateHandler.upsertDocWithPath = sinon.stub().yields(null, @doc, false, [], @folder)
@EditorController.upsertDocWithPath @project_id, @docPath, @docLines, @source, @user_id, @callback
it 'upserts the doc using the project entity handler', ->
@ProjectEntityUpdateHandler.upsertDocWithPath
.calledWith(@project_id, @docPath, @docLines, @source)
.should.equal true
describe 'doc does not exist', ->
beforeEach ->
@ProjectEntityUpdateHandler.upsertDocWithPath = sinon.stub().yields(null, @doc, true, [], @folder)
@EditorController.upsertDocWithPath @project_id, @docPath, @docLines, @source, @user_id, @callback
it 'should send the update for the doc out to users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewDoc", @folder_id, @doc, @source)
.should.equal true
describe 'folders required for doc do not exist', ->
beforeEach ->
folders = [
@folderA = { _id: 2, parentFolder_id: 1}
@folderB = { _id: 3, parentFolder_id: 2}
]
@ProjectEntityUpdateHandler.upsertDocWithPath = sinon.stub().yields(null, @doc, true, folders, @folderB)
@EditorController.upsertDocWithPath @project_id, @docPath, @docLines, @source, @user_id, @callback
it 'should send the update for each folder to users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFolder", @folderA.parentFolder_id, @folderA)
.should.equal true
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFolder", @folderB.parentFolder_id, @folderB)
.should.equal true
describe "upsertFileWithPath", ->
beforeEach ->
@filePath = '/folder/file'
@ProjectEntityUpdateHandler.upsertFileWithPath = sinon.stub().yields(null, @newFile, false, @file, [], @folder)
@EditorController.upsertFileWithPath @project_id, @filePath, @fsPath, @linkedFileData, @source, @user_id, @callback
it 'upserts the file using the project entity handler', ->
@ProjectEntityUpdateHandler.upsertFileWithPath
.calledWith(@project_id, @filePath, @fsPath, @linkedFileData)
.should.equal true
describe 'file does not exist', ->
beforeEach ->
@ProjectEntityUpdateHandler.upsertFileWithPath = sinon.stub().yields(null, @file, true, undefined, [], @folder)
@EditorController.upsertFileWithPath @project_id, @filePath, @fsPath, @linkedFileData, @source, @user_id, @callback
it 'should send the update for the file out to users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFile", @folder_id, @file, @source, @linkedFileData)
.should.equal true
describe 'folders required for file do not exist', ->
beforeEach ->
folders = [
@folderA = { _id: 2, parentFolder_id: 1}
@folderB = { _id: 3, parentFolder_id: 2}
]
@ProjectEntityUpdateHandler.upsertFileWithPath = sinon.stub().yields(null, @file, true, undefined, folders, @folderB)
@EditorController.upsertFileWithPath @project_id, @filePath, @fsPath, @linkedFileData, @source, @user_id, @callback
it 'should send the update for each folder to users in the project', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFolder", @folderA.parentFolder_id, @folderA)
.should.equal true
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "reciveNewFolder", @folderB.parentFolder_id, @folderB)
.should.equal true
describe 'addFolder', ->
beforeEach ->
@EditorController._notifyProjectUsersOfNewFolder = sinon.stub().yields()
@ProjectEntityUpdateHandler.addFolder = sinon.stub().yields(null, @folder, @folder_id)
@EditorController.addFolder @project_id, @folder_id, @folderName, @source, @callback
it 'should add the folder using the project entity handler', ->
@ProjectEntityUpdateHandler.addFolder
.calledWith(@project_id, @folder_id, @folderName)
.should.equal true
it 'should notifyProjectUsersOfNewFolder', ->
@EditorController._notifyProjectUsersOfNewFolder
.calledWith(@project_id, @folder_id, @folder)
it 'should return the folder in the callback', ->
@callback.calledWith(null, @folder).should.equal true
describe 'mkdirp', ->
beforeEach ->
@path = "folder1/folder2"
@folders = [
@folderA = { _id: 2, parentFolder_id: 1}
@folderB = { _id: 3, parentFolder_id: 2}
]
@EditorController._notifyProjectUsersOfNewFolders = sinon.stub().yields()
@ProjectEntityUpdateHandler.mkdirp = sinon.stub().yields(null, @folders, @folder)
@EditorController.mkdirp @project_id, @path, @callback
it 'should create the folder using the project entity handler', ->
@ProjectEntityUpdateHandler.mkdirp
.calledWith(@project_id, @path)
.should.equal true
it 'should notifyProjectUsersOfNewFolder', ->
@EditorController._notifyProjectUsersOfNewFolders
.calledWith(@project_id, @folders)
it 'should return the folder in the callback', ->
@callback.calledWith(null, @folders, @folder).should.equal true
describe 'deleteEntity', ->
beforeEach ->
@entity_id = "entity_id_here"
@type = "doc"
@ProjectEntityUpdateHandler.deleteEntity = sinon.stub().yields()
@EditorController.deleteEntity @project_id, @entity_id, @type, @source, @user_id, @callback
it 'should delete the folder using the project entity handler', ->
@ProjectEntityUpdateHandler.deleteEntity
.calledWith(@project_id, @entity_id, @type, @user_id)
.should.equal.true
it 'notify users an entity has been deleted', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "removeEntity", @entity_id, @source)
.should.equal true
describe "deleteEntityWithPath", ->
beforeEach () ->
@entity_id = "entity_id_here"
@ProjectEntityUpdateHandler.deleteEntityWithPath = sinon.stub().yields(null, @entity_id)
@path = "folder1/folder2"
@EditorController.deleteEntityWithPath @project_id, @path, @source, @user_id, @callback
it 'should delete the folder using the project entity handler', ->
@ProjectEntityUpdateHandler.deleteEntityWithPath
.calledWith(@project_id, @path, @user_id)
.should.equal.true
it 'notify users an entity has been deleted', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "removeEntity", @entity_id, @source)
.should.equal true
describe "notifyUsersProjectHasBeenDeletedOrRenamed", ->
it 'should emmit a message to all users in a project', (done)->
@EditorController.notifyUsersProjectHasBeenDeletedOrRenamed @project_id, (err)=>
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "projectRenamedOrDeletedByExternalSource")
.should.equal true
done()
describe "updateProjectDescription", ->
beforeEach ->
@description = "new description"
@EditorController.updateProjectDescription @project_id, @description, @callback
it "should send the new description to the project details handler", ->
@ProjectDetailsHandler.setProjectDescription.calledWith(@project_id, @description).should.equal true
it "should notify the other clients about the updated description", ->
@EditorRealTimeController.emitToRoom.calledWith(@project_id, "projectDescriptionUpdated", @description).should.equal true
describe "deleteProject", ->
beforeEach ->
@err = "errro"
@ProjectDeleter.deleteProject = sinon.stub().callsArgWith(1, @err)
it "should call the project handler", (done)->
@EditorController.deleteProject @project_id, (err)=>
err.should.equal @err
@ProjectDeleter.deleteProject.calledWith(@project_id).should.equal true
done()
describe "renameEntity", ->
beforeEach (done) ->
@entity_id = "entity_id_here"
@entityType = "doc"
@newName = "bobsfile.tex"
@ProjectEntityUpdateHandler.renameEntity = sinon.stub().yields()
@EditorController.renameEntity @project_id, @entity_id, @entityType, @newName, @user_id, done
it "should call the project handler", ->
@ProjectEntityUpdateHandler.renameEntity
.calledWith(@project_id, @entity_id, @entityType, @newName, @user_id)
.should.equal true
it "should emit the update to the room", ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'reciveEntityRename', @entity_id, @newName)
.should.equal true
describe "moveEntity", ->
beforeEach ->
@entity_id = "entity_id_here"
@entityType = "doc"
@ProjectEntityUpdateHandler.moveEntity = sinon.stub().yields()
@EditorController.moveEntity @project_id, @entity_id, @folder_id, @entityType, @user_id, @callback
it "should call the ProjectEntityUpdateHandler", ->
@ProjectEntityUpdateHandler.moveEntity
.calledWith(@project_id, @entity_id, @folder_id, @entityType, @user_id)
.should.equal true
it "should emit the update to the room", ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'reciveEntityMove', @entity_id, @folder_id)
.should.equal true
it "calls the callback", ->
@callback.called.should.equal true
describe "renameProject", ->
beforeEach ->
@err = "errro"
@newName = "new name here"
@EditorController.renameProject @project_id, @newName, @callback
it "should call the EditorController", ->
@ProjectDetailsHandler.renameProject.calledWith(@project_id, @newName).should.equal true
it "should emit the update to the room", ->
@EditorRealTimeController.emitToRoom.calledWith(@project_id, 'projectNameUpdated', @newName).should.equal true
describe "setCompiler", ->
beforeEach ->
@compiler = "latex"
@EditorController.setCompiler @project_id, @compiler, @callback
it "should send the new compiler and project id to the project options handler", ->
@ProjectOptionsHandler.setCompiler
.calledWith(@project_id, @compiler)
.should.equal true
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "compilerUpdated", @compiler)
.should.equal true
describe "setSpellCheckLanguage", ->
beforeEach ->
@languageCode = "fr"
@EditorController.setSpellCheckLanguage @project_id, @languageCode, @callback
it "should send the new languageCode and project id to the project options handler", ->
@ProjectOptionsHandler.setSpellCheckLanguage
.calledWith(@project_id, @languageCode)
.should.equal true
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, "spellCheckLanguageUpdated", @languageCode)
.should.equal true
describe "setPublicAccessLevel", ->
describe 'when setting to private', ->
beforeEach ->
@newAccessLevel = 'private'
@ProjectDetailsHandler.ensureTokensArePresent = sinon.stub().yields(null, @tokens)
@EditorController.setPublicAccessLevel @project_id, @newAccessLevel, @callback
it 'should set the access level', ->
@ProjectDetailsHandler.setPublicAccessLevel
.calledWith(@project_id, @newAccessLevel)
.should.equal true
it 'should broadcast the access level change', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'project:publicAccessLevel:changed')
.should.equal true
it 'should not ensure tokens are present for project', ->
@ProjectDetailsHandler.ensureTokensArePresent
.calledWith(@project_id)
.should.equal false
it 'should not broadcast a token change', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'project:tokens:changed', {tokens: @tokens})
.should.equal false
describe 'when setting to tokenBased', ->
beforeEach ->
@newAccessLevel = 'tokenBased'
@tokens = {PI:KEY:<KEY>END_PI: 'PI:KEY:<KEY>END_PI', readAndWrite: 'PI:KEY:<KEY>END_PI'}
@ProjectDetailsHandler.ensureTokensArePresent = sinon.stub().yields(null, @tokens)
@EditorController.setPublicAccessLevel @project_id, @newAccessLevel, @callback
it 'should set the access level', ->
@ProjectDetailsHandler.setPublicAccessLevel
.calledWith(@project_id, @newAccessLevel)
.should.equal true
it 'should broadcast the access level change', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'project:publicAccessLevel:changed')
.should.equal true
it 'should ensure tokens are present for project', ->
@ProjectDetailsHandler.ensureTokensArePresent
.calledWith(@project_id)
.should.equal true
it 'should broadcast the token change too', ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'project:tokens:changed', {tokens: @tokens})
.should.equal true
describe "setRootDoc", ->
beforeEach ->
@newRootDocID = "21312321321"
@ProjectEntityUpdateHandler.setRootDoc = sinon.stub().yields()
@EditorController.setRootDoc @project_id, @newRootDocID, @callback
it "should call the ProjectEntityUpdateHandler", ->
@ProjectEntityUpdateHandler.setRootDoc
.calledWith(@project_id, @newRootDocID)
.should.equal true
it "should emit the update to the room", ->
@EditorRealTimeController.emitToRoom
.calledWith(@project_id, 'rootDocUpdated', @newRootDocID)
.should.equal true
|
[
{
"context": "nt true)\n return ''\n else\n whoto = ['help@openaccessbutton.org']\n text = ''\n for k of this.request.bod",
"end": 3440,
"score": 0.9999312162399292,
"start": 3415,
"tag": "EMAIL",
"value": "help@openaccessbutton.org"
},
{
"context": "rm in ['wrong','uninstall']\n whoto.push 'natalia.norori@openaccessbutton.org'\n API.mail.send {\n service: 'openacce",
"end": 4191,
"score": 0.9999276995658875,
"start": 4156,
"tag": "EMAIL",
"value": "natalia.norori@openaccessbutton.org"
},
{
"context": " service: 'openaccessbutton',\n from: 'natalia.norori@openaccessbutton.org',\n to: whoto,\n subject: subject,\n ",
"end": 4302,
"score": 0.999927818775177,
"start": 4267,
"tag": "EMAIL",
"value": "natalia.norori@openaccessbutton.org"
},
{
"context": "ton.profile.profession','roles.openaccessbutton','username']\n rec[f] = API.collection.dot r._so",
"end": 5577,
"score": 0.9993669390678406,
"start": 5569,
"tag": "USERNAME",
"value": "username"
},
{
"context": "date = (email, domain, verify=false) ->\n bad = ['eric@talkwithcustomer.com']\n if typeof email isnt 'string' or email.indexO",
"end": 20585,
"score": 0.9999104142189026,
"start": 20560,
"tag": "EMAIL",
"value": "eric@talkwithcustomer.com"
},
{
"context": " vars.profession ?= 'person'\n vars.fullname ?= 'a user'\n vars.name ?= 'colleague'\n return vars\n\nA",
"end": 23437,
"score": 0.7001383304595947,
"start": 23436,
"tag": "NAME",
"value": "a"
},
{
"context": " vars.profession ?= 'person'\n vars.fullname ?= 'a user'\n vars.name ?= 'colleague'\n return vars\n\nAPI.se",
"end": 23442,
"score": 0.7227092385292053,
"start": 23438,
"tag": "NAME",
"value": "user"
},
{
"context": "rson'\n vars.fullname ?= 'a user'\n vars.name ?= 'colleague'\n return vars\n\nAPI.service.oab.substitute = (con",
"end": 23469,
"score": 0.8544355630874634,
"start": 23460,
"tag": "NAME",
"value": "colleague"
},
{
"context": "troduced this because of issue https://github.com/OAButton/discussion/issues/1257\n # and for example http",
"end": 31298,
"score": 0.9996500611305237,
"start": 31290,
"tag": "USERNAME",
"value": "OAButton"
}
] | noddy/service/v2/api.coffee | oaworks/API | 2 |
import moment from 'moment'
API.service ?= {}
API.service.oab ?= {}
# these are global so can be accessed on other oabutton files
@oab_support = new API.collection {index:"oab",type:"support"}
@oab_catalogue = new API.collection {index:"oab",type:"catalogue"}
@oab_request = new API.collection {index:"oab",type:"request",history:true}
@oab_find = new API.collection {index:"oab",type:"find"}
@oab_ill = new API.collection {index:"oab",type:"ill"}
@oab_permissions = new API.collection {index:"oab",type:"permissions"}
@oab_dnr = new API.collection {index:"oab",type:"oab_dnr"}
API.add 'service/oab',
get: () -> return {data: 'The Open Access Button API.'}
post:
roleRequired:'openaccessbutton.user'
action: () ->
return {data: 'You are authenticated'}
API.add 'service/oab/blacklist',
get: () -> return {data:API.service.oab.blacklist(this.queryParams.url,this.queryParams.stale)}
API.add 'service/oab/templates',
get: () -> return API.service.oab.template(this.queryParams.template,this.queryParams.refresh)
API.add 'service/oab/substitute',
post: () -> return API.service.oab.substitute this.request.body.content,this.request.body.vars,this.request.body.markdown
API.add 'service/oab/mail',
post:
roleRequired:'openaccessbutton.admin'
action: () -> return API.service.oab.mail this.request.body
API.add 'service/oab/validate',
post:
authOptional:true
action: () ->
if this.queryParams.email and (this.queryParams.uid or this.userId) #and (this.queryParams.uid is 'anonymous' or API.accounts.retrieve(this.queryParams.uid ? this.userId))
return API.service.oab.validate this.queryParams.email, this.queryParams.domained, this.queryParams.verify
else
return undefined
API.add 'service/oab/dnr',
get:
authOptional: true
action: () ->
return API.service.oab.dnr() if not this.queryParams.email? and this.user and API.accounts.auth 'openaccessbutton.admin', this.user
d = {}
d.dnr = API.service.oab.dnr this.queryParams.email
if not d.dnr and this.queryParams.user
u = API.accounts.retrieve this.queryParams.user
d.dnr = 'user' if u.emails[0].address is this.queryParams.email
if not d.dnr and this.queryParams.request
r = oab_request.get this.queryParams.request
d.dnr = 'creator' if r.user.email is this.queryParams.email
if not d.dnr
d.dnr = 'supporter' if oab_support.find {rid:this.queryParams.request, email:this.queryParams.email}
if not d.dnr and this.queryParams.validate
d.validation = API.mail.validate this.queryParams.email, API.settings.service?.openaccessbutton?.mail?.pubkey
d.dnr = 'invalid' if not d.validation.is_valid
return d
post: () ->
e = this.queryParams.email ? this.request.body.email
refuse = if not this.queryParams.refuse? or this.queryParams.refuse in ['false',false] then false else true
return if e then API.service.oab.dnr(e,true,refuse) else 400
delete:
roleRequired: 'openaccessbutton.admin'
action: () ->
oab_dnr.remove({email:this.queryParams.email}) if this.queryParams.email
return {}
API.add 'service/oab/bug',
post: () ->
if (this.request.body?.contact? and this.request.body.contact.length) or (this.request.body?.email? and API.service.oab.validate(this.request.body.email) isnt true)
return ''
else
whoto = ['help@openaccessbutton.org']
text = ''
for k of this.request.body
text += k + ': ' + JSON.stringify(this.request.body[k],undefined,2) + '\n\n'
text = API.tdm.clean text
subject = '[OAB forms]'
if this.request.body?.form is 'uninstall' # wrong bug general other
subject += ' Uninstall notice'
else if this.request.body?.form is 'wrong'
subject += ' Wrong article'
else if this.request.body?.form is 'bug'
subject += ' Bug'
else if this.request.body?.form is 'general'
subject += ' General'
else
subject += ' Other'
subject += ' ' + Date.now()
try
if this.request.body?.form in ['wrong','uninstall']
whoto.push 'natalia.norori@openaccessbutton.org'
API.mail.send {
service: 'openaccessbutton',
from: 'natalia.norori@openaccessbutton.org',
to: whoto,
subject: subject,
text: text
}
return {
statusCode: 302,
headers: {
'Content-Type': 'text/plain',
'Location': (if API.settings.dev then 'https://dev.openaccessbutton.org' else 'https://openaccessbutton.org') + '/feedback#defaultthanks'
},
body: 'Location: ' + (if API.settings.dev then 'https://dev.openaccessbutton.org' else 'https://openaccessbutton.org') + '/feedback#defaultthanks'
}
API.add 'service/oab/history', () -> return oab_request.history this
API.add 'service/oab/users',
csv: true
get:
roleRequired:'openaccessbutton.admin'
action: () ->
res = Users.search this.queryParams, {restrict:[{exists:{field:'roles.openaccessbutton'}}]}
recs = []
try
for r in res.hits.hits
if not r._source.email?
r._source.email = r._source.emails[0].address
if this.request.url.split('?')[0].endsWith '.csv'
rec = {}
for f in ['_id','createdAt','created_date','updatedAt','updated_date','email','profile.name','profile.firstname','profile.lastname','service.openaccessbutton.profile.affiliation','service.openaccessbutton.profile.profession','roles.openaccessbutton','username']
rec[f] = API.collection.dot r._source, f
recs.push rec
if recs.length
return recs
else
return res
post:
roleRequired:'openaccessbutton.admin'
action: () ->
res = Users.search this.bodyParams, {restrict:[{exists:{field:'roles.openaccessbutton'}}]}
try
for r in res.hits.hits
if not res.hits.hits[r]._source.email?
res.hits.hits[r]._source.email = res.hits.hits[r]._source.emails[0].address
return res
API.add 'service/oab/redirect', get: () -> return API.service.oab.redirect this.queryParams.url, this.queryParams.refresh?
API.add 'service/oab/status', get: () -> return API.service.oab.status()
API.add 'service/oab/stats', get: () -> return API.service.oab.stats this.queryParams.tool
API.add 'service/oab/stats/emails',
post:
roleRequired:'openaccessbutton.admin'
action: () ->
res = {}
for uid in this.request.body
try res[uid] = API.accounts.retrieve(uid).emails[0].address
return res
API.service.oab.status = () ->
return # simple queries to get basic status - use stats below for more complex feedback
requests: oab_request.count()
stories: oab_request.count undefined, 'story:*'
test: oab_request.count undefined, {test:true}
help: oab_request.count undefined, {status:'help'}
moderate: oab_request.count undefined, {status:'moderate'}
progress: oab_request.count undefined, {status:'progress'}
hold: oab_request.count undefined, {status:'hold'}
refused: oab_request.count undefined, {status:'refused'}
received: oab_request.count undefined, {status:'received'}
supports: oab_support.count()
finds: oab_find.count()
found: oab_find.count undefined, 'url:*'
users: Users.count undefined, {exists:{field:"roles.openaccessbutton"}}
requested: oab_request.count 'user.id', {exists:{field:"user.id"}}
API.service.oab.stats = (tool) ->
tool = undefined if tool? and tool not in ['embedoa','illiad','clio']
q = if tool is 'embedoa' then 'plugin:'+tool else if tool? then 'from:'+tool else undefined
res = status: API.service.oab.status(), requests: {}
if q?
res.status.finds = oab_find.count undefined, q
res.status.found = oab_find.count undefined, q + ' AND url:*'
res.status.stories = oab_request.count undefined, q + ' AND story:*'
twoyearsago = Date.now() - (31536000000*2)
rgs = {requests: {date_histogram: {field: "createdAt", interval: "week"}}}
rgs.requests2yrs = {aggs: {vals: {date_histogram: {field: "createdAt", interval: "week"}}}, filter: {range: {createdAt: {gt: twoyearsago }}}}
rgs.stories2yrs = {aggs: {vals: {date_histogram: {field: "createdAt", interval: "week"}}}, filter: {bool: {must: [{exists: {field: 'story'}}, {range: {createdAt: {gt: twoyearsago }}}]}}}
rgs.received2yrs = {aggs: {vals: {date_histogram: {field: "received.date", interval: "week"}}}, filter: {bool: {must: [{term: {status: 'received'}}, {range: {createdAt: {gt: twoyearsago }}}]}}}
#ra = oab_request.search q, {size: 0, aggregations: rgs}
#res.requests.requests = ra.aggregations.requests.buckets
#res.requests.requests2yrs = ra.aggregations.requests2yrs.vals.buckets
#res.requests.stories2yrs = ra.aggregations.stories2yrs.vals.buckets
#res.requests.received2yrs = ra.aggregations.received2yrs.vals.buckets
# query finds
tmwk = moment().startOf('week').valueOf() # timestamp up to a week ago
tm1 = moment().startOf('month').valueOf() # timestamp at start of the current month
tm3 = moment().subtract(3,'months').valueOf() # timestamp 3 months ago
aggs =
users: {terms: {field: "from.exact", size: 10000}, aggs: {firsts: {terms: {field: "created_date", size: 1, order: {_term: "asc"}}}}}
finds: {date_histogram: {field: "createdAt", interval: "week"}}
emails: {cardinality : {field: "email.exact"}}
tm1: {filter: {range: {createdAt: {gt: tm1}}}, aggs: {tm1v: {cardinality: {field: "email.exact" }}}}
tm3: {filter: {range: {createdAt: {gt: tm3, lte: tm1 }}}, aggs: {tm3v: {cardinality: {field: "email.exact" }}}}
facets =
plugin: { terms: { field: "plugin.exact", size: 500}}
plugin_week: { terms: { field: "plugin.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: tmwk }}}}
plugin_month: { terms: { field: "plugin.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: tm1 }}}}
plugin_threemonth: { terms: { field: "plugin.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: tm3 }}}}
plugin_june18: { terms: { field: "plugin.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: 1527811200000 }}}}
email: { terms: { field: "email.exact", size: 1 } }
embeds: { terms: { field: "embedded.exact", size: 500 } }
from_week: { terms: { field: "from.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: tmwk }}}}
from_month: { terms: { field: "from.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: tm1 }}}}
from_threemonth: { terms: { field: "from.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: tm3 }}}}
from_june18: { terms: { field: "from.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: 1527811200000 }}}}
finds = oab_find.search q, { size: 0, aggs: aggs, facets: facets}
res.find = {total: finds.hits.total, users: {}}
try
for u in finds.aggregations.users.buckets
res.find.users[u.key] = count: u.doc_count, first: u.firsts.buckets[0].key_as_string.split(' ')[0].split('-').reverse().join('/')
try res.find.finds = finds.aggregations.finds.buckets
try res.find.emails = finds.aggregations.emails.value
try res.find.tm1 = finds.aggregations.tm1.tm1v.value
try res.find.tm3 = finds.aggregations.tm3.tm3v.value
try res.find.plugin = finds.facets.plugin.terms
try res.find.plugin_week = finds.facets.plugin_week.terms
try res.find.plugin_month = finds.facets.plugin_month.terms
try res.find.plugin_threemonth = finds.facets.plugin_threemonth.terms
try res.find.plugin_june18 = finds.facets.plugin_june18.terms
try res.find.email = finds.facets.email.terms
try res.find.anonymous = finds.facets.email.missing
try res.find.embeds = finds.facets.embeds.terms
try res.find.from_week = finds.facets.from_week.terms
try res.find.from_month = finds.facets.from_month.terms
try res.find.from_threemonth = finds.facets.from_threemonth.terms
try res.find.from_june18 = finds.facets.from_june18.terms
res.plugins = {api:{all:finds.facets.plugin.missing, week:finds.facets.plugin_week.missing, month:finds.facets.plugin_month.missing, threemonth:finds.facets.plugin_threemonth.missing, june18:finds.facets.plugin_june18.missing}}
wrongpings = {}
if not tool? # get pings
pingcounts = {alltime:{},week:{},month:{},threemonth:{},june18:{}}
for h in pings.search('service:openaccessbutton AND action:*', {newest: false, size: 100000}).hits.hits
hr = h._source
if hr.from and hr.action.toLowerCase() is 'instantill_wrong_article'
wrongpings[hr.from] ?= 0
wrongpings[hr.from] += 1
for nm in _.keys pingcounts
if nm is 'alltime' or (nm is 'week' and hr.createdAt > tmwk) or (nm is 'month' and hr.createdAt > tm1) or (nm is 'threemonth' and hr.createdAt > tm3) or (nm is 'june18' and hr.createdAt > 1527811200000)
pingcounts[nm][hr.action] = (pingcounts[nm][hr.action] ? 0) + 1
sorts = []
for kv of pingcounts.alltime
sp = action: kv
sp[nm] = (pingcounts[nm][kv] ? 0) for nm in _.keys pingcounts
sorts.push sp
res.pings = sorts.sort((a, b) -> return a.alltime - b.alltime)
if not tool? or tool is 'embedoa' # stats on embedoa
eggs = {users: {terms: {field: "from.exact", size: 10000}}}
eggs.users.aggs = {firsts: {terms: {field:"created_date", size: 1, order: {_term: "asc"}}}}
eggs.users.aggs.oa = {filter: {bool: {must: [{exists: {field: "url"}}]}}, aggs: {from: {terms: {field: "from.exact"}}}}
eggs.users.aggs.embeds = {terms: {field: "embedded.exact", size: 100}}
eres = oab_find.search {plugin: 'widget'}, {size: 0, aggs: eggs}
# TODO finish formatting the embedoa results into the necessary stats
res.embedoa = {}
try
for u in eres.aggregations.users.buckets
res.embedoa[u.key] = count: u.doc_count
try res.embedoa[u.key].first = u.firsts.buckets[0].key_as_string.split(' ')[0].split('-').reverse().join('/')
try res.embedoa[u.key].oa = u.oa.doc_count # check this
res.embedoa[u.key].embeds = []
for em in u.embeds.buckets
tk = em.key.split('?')[0].split('#')[0]
res.embedoa[u.key].embeds.push(tk) if tk not in res.embedoa[u.key].embeds
if not tool? # ills and shareyourpapers
iggs = {users: {terms: {field: "from.exact", size: 10000}}}
iggs.users.aggs = {firsts: {terms: {field:"created_date", size: 1, order: {_term: "asc"}}}}
iggs.users.aggs.oa = {filter: {bool: {must: [{exists: {field: "url"}}]}}, aggs: {from: {terms: {field: "from.exact"}}}}
iggs.users.aggs.subs = {filter: {query: {query_string: {query: "ill.subscription.url:*"}}}, aggs: {from: {terms: {field: "from.exact"}}}}
#iggs.users.aggs.wrong = {filter: {term: {wrong: true}}, aggs: {from: {terms: {field: "from.exact"}}}}
iggs.users.aggs.embeds = {terms: {field: "embedded.exact", size: 100}}
illfinds = oab_find.search {plugin: 'instantill'}, {size: 0, aggs: iggs}
res.ill = {}
try
for u in illfinds.aggregations.users.buckets
res.ill[u.key] = count: u.doc_count
try res.ill[u.key].first = u.firsts.buckets[0].key_as_string.split(' ')[0].split('-').reverse().join('/')
try res.ill[u.key].oa = u.oa.doc_count
try res.ill[u.key].subs = u.subs.doc_count
#try res.ill[u.key].wrong = u.wrong.doc_count
try res.ill[u.key].wrong = wrongpings[u.key]
res.ill[u.key].embeds = []
for em in u.embeds.buckets
tk = em.key.split('?')[0].split('#')[0]
res.ill[u.key].embeds.push(tk) if tk not in res.ill[u.key].embeds
igs = {users: {terms: {field: "from.exact", size: 10000}}}
igs.issn = {filter: {query: {query_string: {query: "metadata.title:* AND metadata.journal:* AND metadata.year:* AND metadata.issn:*"}}}, aggs: {users: {terms: {field: "from.exact", size: 10000}}}}
igs.forwarded = {filter: {term: {forwarded: true}}, aggs: {users: {terms: {field: "from.exact", size: 10000}}}}
ills = oab_ill.search undefined, {size: 0, aggs: igs}
try
for u in ills.aggregations.users.buckets
res.ill[u.key] ?= {}
res.ill[u.key].ill = u.doc_count
try res.ill[u.key].withissn = u.doc_count for u in ills.aggregations.issn.users.buckets
try res.ill[u.key].forwarded = u.doc_count for u in ills.aggregations.forwarded.users.buckets
sggs = {users: {terms: {field: "from.exact", size: 10000}}}
sggs.users.aggs = {firsts: {terms: {field:"created_date", size: 1, order: {_term: "asc"}}}}
sggs.users.aggs.embeds = {terms: {field: "embedded.exact", size: 100}}
sypfinds = oab_find.search {plugin: 'shareyourpaper'}, {size: 0, aggs: sggs}
res.syp = {}
try
for u in sypfinds.aggregations.users.buckets
res.syp[u.key] = count: u.doc_count
try res.syp[u.key].first = u.firsts.buckets[0].key_as_string.split(' ')[0].split('-').reverse().join('/')
res.syp[u.key].embeds = []
for em in u.embeds.buckets
tk = em.key.split('?')[0].split('#')[0]
res.syp[u.key].embeds.push(tk) if tk not in res.syp[u.key].embeds
res.syp[u.key].review ?= 0
res.syp[u.key].zenodo ?= 0
res.syp[u.key].redeposit ?= 0
res.syp[u.key].forward ?= 0
res.syp[u.key].dark ?= 0
oab_catalogue.each 'deposit.from.exact:* AND deposit.type.exact:*', (rec) ->
for d in rec.deposit
res.syp[d.from] ?= {}
#if not res.syp[d.from].firstAt or res.syp[d.from].firstAt < d.createdAt
# res.syp[d.from].firstAt = d.createdAt
# res.syp[d.from].first = d.created_date.split(' ')[0].split('-').reverse().join('/')
res.syp[d.from].review ?= 0
res.syp[d.from].zenodo ?= 0
res.syp[d.from].redeposit ?= 0
res.syp[d.from].forward ?= 0
res.syp[d.from].dark ?= 0
res.syp[d.from][d.type] ?= 0
res.syp[d.from][d.type] += 1
return res
API.service.oab.blacklist = (url,stale=360000) ->
API.log msg: 'Checking OAB blacklist', url: url
stale = 0 if stale is false
url = url.toString() if typeof url is 'number'
return false if url? and (url.length < 4 or url.indexOf('.') is -1)
bl = API.use.google.sheets.feed API.settings.service.openaccessbutton?.google?.sheets?.blacklist, stale
blacklist = []
blacklist.push(i.url) for i in bl
if url
if url.indexOf('http') isnt 0 and url.indexOf(' ') isnt -1
return false # sometimes article titles get sent here, no point checking them on the blacklist
else
for b in blacklist
return true if url.indexOf(b) isnt -1
return false
else
return blacklist
API.service.oab.dnr = (email,add,refuse) ->
return oab_dnr.search('*')?.hits?.hits if not email? and not add?
ondnr = oab_dnr.find {email:email}
if add and not ondnr
oab_dnr.insert {email:email}
# also set any requests where this author is the email address to refused - can't use the address!
if refuse
oab_request.each {email:email}, (req) -> API.service.oab.refuse req._id, 'Author DNRd their email address'
else
oab_request.each {email:email}, (req) ->
if req.status in ['help','moderate','progress']
oab_request.update r._id, {email:'',status:'help'}
return ondnr? or add is true
API.service.oab.template = (template,refresh) ->
if refresh or mail_template.count(undefined,{service:'openaccessbutton'}) is 0
mail_template.remove {service:'openaccessbutton'}
ghurl = API.settings.service.openaccessbutton?.templates_url
ghp = ghurl.split('.com/')[1].split('/tree')[0]
m = API.tdm.extract
url:ghurl
matchers:['/href="/' + ghp + '/blob/' + (if API.settings.dev then 'develop' else 'master') + '/emails/(.*?[.].*?)">/gi']
start:'<table class="files'
end:'</table'
fls = []
fls.push(fm.result[1]) for fm in m.matches
flurl = ghurl.replace('github.com','raw.githubusercontent.com').replace('/tree','')
for f in fls
if f isnt 'archive'
content = HTTP.call('GET',flurl + '/' + f).content
API.mail.template undefined,{filename:f,service:'openaccessbutton',content:content}
return API.mail.template {service:'openaccessbutton'}
else if template
return API.mail.template template
else
return API.mail.template {service:'openaccessbutton'}
# run a template refresh on every restart
Meteor.setTimeout (() -> API.service.oab.template(undefined, true) if API.status.ip() not in (API.settings.cluster.ip ? [])), 40000
API.service.oab.validate = (email, domain, verify=false) ->
bad = ['eric@talkwithcustomer.com']
if typeof email isnt 'string' or email.indexOf(',') isnt -1 or email in bad
return false
else if email.indexOf('@openaccessbutton.org') isnt -1 or email.indexOf('@email.ghostinspector.com') isnt -1 #or email in []
return true
else
#v = API.mail.validate email, API.settings.service.openaccessbutton.mail.pubkey
# not using mailgun verification any more, just do the direct simple check of the email
v = {}
if typeof email is 'string' and email.length and email.indexOf(' ') is -1
[n, d] = email.split '@'
if n.length and d.length and d.split('.').length > 1
v = is_valid: true
if v.is_valid and (not verify or v.mailbox_verification in [true,'true'])
if false #domain and domain not in ['qZooaHWRz9NLFNcgR','eZwJ83xp3oZDaec86'] # turning this off for now
iacc = API.accounts.retrieve domain
return 'baddomain' if not iacc?
eml = false #iacc.email ? iacc.emails[0].address # may also later have a config where the allowed domains can be listed but for now just match the domain of the account holder - only in the case where shareyourpaper config exists
dc = false
try
dc = API.service.oab.deposit.config iacc
#eml = dc.adminemail if dc.adminemail? # don't bother defaulting to the admin email
dc.email_domains = dc.email_domains.split(',') if dc.email_domains? and typeof dc.email_domains is 'string'
if dc isnt false and dc.email_domains? and _.isArray(dc.email_domains) and dc.email_domains.length > 0
for ed in dc.email_domains
if email.toLowerCase().indexOf(ed.toLowerCase()) > 0
return true
return 'baddomain'
else
if typeof eml is 'string' and eml.toLowerCase().indexOf(email.split('@')[1].split('.')[0].toLowerCase()) is -1
return 'baddomain'
else
return true
else
return true
else if v.did_you_mean
return v.did_you_mean
else
return false
API.service.oab.vars = (vars) ->
vars = JSON.parse JSON.stringify vars # need this in case a request is passed in as vars and later edited
if vars?.user
u = API.accounts.retrieve vars.user.id
if u
vars.profession = u.service?.openaccessbutton?.profile?.profession ? 'person'
vars.profession = 'person' if vars.profession.toLowerCase() is 'other'
vars.affiliation = u.service?.openaccessbutton?.profile?.affiliation ? ''
vars.userid = vars.user.id
vars.fullname = u?.profile?.name ? ''
if not vars.fullname and u?.profile?.firstname
vars.fullname = u.profile.firstname
vars.fullname += ' ' + u.profile.lastname if u.profile.lastname
vars.username = vars.user.username ? vars.fullname
vars.useremail = vars.user.email
vars.profession ?= 'person'
vars.fullname ?= 'a user'
vars.name ?= 'colleague'
return vars
API.service.oab.substitute = (content,vars,markdown) ->
vars = API.service.oab.vars vars
if API.settings.dev
content = content.replace(/https:\/\/openaccessbutton.org/g,'https://dev.openaccessbutton.org')
content = content.replace(/https:\/\/api.openaccessbutton.org/g,'https://dev.api.cottagelabs.com/service/oab')
return API.mail.substitute content, vars, markdown
API.service.oab.mail = (opts={}) ->
opts.service = 'openaccessbutton'
opts.subject ?= 'Hello from Open Access Button'
opts.from ?= API.settings.service.openaccessbutton?.requests_from
if opts.bcc is 'ALL'
opts.bcc = []
Users.each {"roles.openaccessbutton":"*"}, (user) -> opts.bcc.push user.emails[0].address
return API.mail.send opts
API.service.oab.admin = (rid,action) ->
r = oab_request.get rid
vars = API.service.oab.vars r
usermail
if r.user?.id
u = API.accounts.retrieve r.user.id
usermail = u.emails[0].address
update = {}
requestors = []
requestors.push(usermail) if usermail
oab_support.each {rid:rid}, (s) -> requestors.push(s.email) if s.email and s.email not in requestors
if action is 'reject_upload'
update.status = 'moderate'
API.service.oab.mail({vars:vars,template:{filename:'author_thanks_article_rejection.html'},to:r.email})
else if action is 'successful_upload'
update.status = 'received'
API.service.oab.mail({vars:vars,template:{filename:'requesters_request_success.html'},to:requestors}) if requestors.length
API.service.oab.mail({vars:vars,template:{filename:'author_thanks_article.html'},to:r.email})
else if action is 'send_to_author'
update.status = 'progress'
update.rating = 1 if r.story
API.service.oab.mail({vars:vars,template:{filename:'requesters_request_inprogress.html'},to:requestors}) if requestors.length
if r.type is 'article'
if r.email
if r.story
API.service.oab.mail({vars:vars,template:{filename:'author_request_article_v2.html'},to:r.email})
else
API.service.oab.mail({vars:vars,template:{filename:'author_request_article_v2_nostory.html'},to:r.email})
else if r.email
API.service.oab.mail({vars:vars,template:{filename:'author_request_data_v2.html'},to:r.email})
else if action is 'story_too_bad'
update.status = 'help'
update.rating = 0
API.service.oab.mail({vars:vars,template:{filename:'initiator_poorstory.html'},to:requestors}) if requestors.length
API.service.oab.mail({vars:vars,template:{filename:'author_request_article_v2_nostory.html'},to:r.email}) if r.email
else if action is 'not_a_scholarly_article'
update.status = 'closed'
API.service.oab.mail({vars:vars,template:{filename:'initiator_invalid.html'},to:usermail}) if usermail
else if action is 'dead_author'
update.status = 'closed'
API.service.oab.mail({vars:vars,template:{filename:'requesters_request_failed_authordeath.html'},to:requestors}) if requestors.length
else if action is 'user_testing'
update.test = true
update.status = 'closed'
update.rating = 0 if r.story
API.service.oab.mail({vars:vars,template:{filename:'initiator_testing.html'},to:usermail}) if usermail
else if action is 'broken_link' and usermail
API.service.oab.mail({vars:vars,template:{filename:'initiator_brokenlink.html'},to:usermail})
update.status = 'closed'
else if action is 'remove_submitted_url'
update.status = 'moderate'
update.received = false
else if action is 'article_before_2000'
API.service.oab.mail({vars:vars,template:{filename:'article_before_2000.html'},to:requestors}) if requestors.length
update.status = 'closed'
else if action is 'author_email_not_found'
API.service.oab.mail({vars:vars,template:{filename:'author_email_not_found.html'},to:requestors}) if requestors.length
update.status = 'closed'
else if action is 'link_by_author'
API.service.oab.mail({vars:vars,template:{filename:'authors_thanks_article.html'},to:r.email}) if r.email
API.service.oab.mail({vars:vars,template:{filename:'requestors_request_success_article.html'},to:requestors}) if requestors.length
update.status = 'received'
else if action is 'link_by_admin'
API.service.oab.mail({vars:vars,template:{filename:'requestors_request_success_article.html'},to:requestors}) if requestors.length
update.status = 'received'
oab_request.update(rid,update) if JSON.stringify(update) isnt '{}'
# LIVE: https://docs.google.com/spreadsheets/d/1Te9zcQtBLq2Vx81JUE9R42fjptFGXY6jybXBCt85dcs/edit#gid=0
# Develop: https://docs.google.com/spreadsheets/d/1AaY7hS0D9jtLgVsGO4cJuLn_-CzNQg0yCreC3PP3UU0/edit#gid=0
API.service.oab.redirect = (url,refresh=false) ->
API.log msg: 'Checking OAB open list', url: url
url = API.http.resolve url, refresh # will return undefined if the url doesn't resolve at all
if url
return false if API.service.oab.blacklist(url) is true # ignore anything on the usual URL blacklist
list = API.use.google.sheets.feed API.settings.service.openaccessbutton?.google?.sheets?.redirect, 360000
for listing in list
if listing.redirect and url.replace('http://','').replace('https://','').split('#')[0] is listing.redirect.replace('http://','').replace('https://','').split('#')[0]
# we have an exact alternative for this url
return listing.redirect
else if typeof url is 'string' and url.indexOf(listing.domain.replace('http://','').replace('https://','').split('/')[0]) isnt -1
url = url.replace('http://','https://') if listing.domain.indexOf('https://') is 0
listing.domain = listing.domain.replace('http://','https://') if url.indexOf('https://') is 0
if (listing.fulltext and listing.splash and listing.identifier) or listing.element
source = url
if listing.fulltext
# switch the url by comparing the fulltext and splash examples, and converting the url in the same way
parts = listing.splash.split listing.identifier
if url.indexOf(parts[0]) is 0 # can only successfully replace if the incoming url starts with the same as the start of the splash url
diff = url.replace parts[0], ''
diff = diff.replace(parts[1],'') if parts.length > 1
url = listing.fulltext.replace listing.identifier, diff
else if listing.element and url.indexOf('.pdf') is -1
try
content = API.http.puppeteer url
url = content.toLowerCase().split(listing.element.toLowerCase())[1].split('"')[0].split("'")[0].split('>')[0]
return false if (not url? or url.length < 6 or url is source) and listing.blacklist is "yes"
# fulltext or element can possibly give us a url which then redirects to a login wall
# so we have to check the given url against the whole sheet listing again for the login wall
# so this allows the rest of the listing to be checked before returning - MAKE SURE loginwall fragments are at the end of the sheet
resv = API.http.resolve url # resolve it again to make sure whatever we have now is accessible
url = resv if typeof resv is 'string'
else if listing.loginwall and url.indexOf(listing.loginwall.replace('http://','').replace('https://','')) isnt -1
# this url is on the login wall of the repo in question, so it is no use
return false
else if listing.blacklist is "yes"
return false
if typeof url is 'string'
# some URLs can be confirmed as resolvable but we also hit a captcha response and end up serving that to the user
# we want to avoid that, so when such URLs appear to be found here, just return true instead, which will cause
# us to accept the original URL
# we introduced this because of issue https://github.com/OAButton/discussion/issues/1257
# and for example https://www.tandfonline.com/doi/pdf/10.1080/17521740701702115?needAccess=true
# ends up as https://www.tandfonline.com/action/captchaChallenge?redirectUri=%2Fdoi%2Fpdf%2F10.1080%2F17521740701702115%3FneedAccess%3Dtrue
for avoid in ['captcha','challenge']
return undefined if url.toLowerCase().indexOf(avoid) isnt -1
return url
| 165718 |
import moment from 'moment'
API.service ?= {}
API.service.oab ?= {}
# these are global so can be accessed on other oabutton files
@oab_support = new API.collection {index:"oab",type:"support"}
@oab_catalogue = new API.collection {index:"oab",type:"catalogue"}
@oab_request = new API.collection {index:"oab",type:"request",history:true}
@oab_find = new API.collection {index:"oab",type:"find"}
@oab_ill = new API.collection {index:"oab",type:"ill"}
@oab_permissions = new API.collection {index:"oab",type:"permissions"}
@oab_dnr = new API.collection {index:"oab",type:"oab_dnr"}
API.add 'service/oab',
get: () -> return {data: 'The Open Access Button API.'}
post:
roleRequired:'openaccessbutton.user'
action: () ->
return {data: 'You are authenticated'}
API.add 'service/oab/blacklist',
get: () -> return {data:API.service.oab.blacklist(this.queryParams.url,this.queryParams.stale)}
API.add 'service/oab/templates',
get: () -> return API.service.oab.template(this.queryParams.template,this.queryParams.refresh)
API.add 'service/oab/substitute',
post: () -> return API.service.oab.substitute this.request.body.content,this.request.body.vars,this.request.body.markdown
API.add 'service/oab/mail',
post:
roleRequired:'openaccessbutton.admin'
action: () -> return API.service.oab.mail this.request.body
API.add 'service/oab/validate',
post:
authOptional:true
action: () ->
if this.queryParams.email and (this.queryParams.uid or this.userId) #and (this.queryParams.uid is 'anonymous' or API.accounts.retrieve(this.queryParams.uid ? this.userId))
return API.service.oab.validate this.queryParams.email, this.queryParams.domained, this.queryParams.verify
else
return undefined
API.add 'service/oab/dnr',
get:
authOptional: true
action: () ->
return API.service.oab.dnr() if not this.queryParams.email? and this.user and API.accounts.auth 'openaccessbutton.admin', this.user
d = {}
d.dnr = API.service.oab.dnr this.queryParams.email
if not d.dnr and this.queryParams.user
u = API.accounts.retrieve this.queryParams.user
d.dnr = 'user' if u.emails[0].address is this.queryParams.email
if not d.dnr and this.queryParams.request
r = oab_request.get this.queryParams.request
d.dnr = 'creator' if r.user.email is this.queryParams.email
if not d.dnr
d.dnr = 'supporter' if oab_support.find {rid:this.queryParams.request, email:this.queryParams.email}
if not d.dnr and this.queryParams.validate
d.validation = API.mail.validate this.queryParams.email, API.settings.service?.openaccessbutton?.mail?.pubkey
d.dnr = 'invalid' if not d.validation.is_valid
return d
post: () ->
e = this.queryParams.email ? this.request.body.email
refuse = if not this.queryParams.refuse? or this.queryParams.refuse in ['false',false] then false else true
return if e then API.service.oab.dnr(e,true,refuse) else 400
delete:
roleRequired: 'openaccessbutton.admin'
action: () ->
oab_dnr.remove({email:this.queryParams.email}) if this.queryParams.email
return {}
API.add 'service/oab/bug',
post: () ->
if (this.request.body?.contact? and this.request.body.contact.length) or (this.request.body?.email? and API.service.oab.validate(this.request.body.email) isnt true)
return ''
else
whoto = ['<EMAIL>']
text = ''
for k of this.request.body
text += k + ': ' + JSON.stringify(this.request.body[k],undefined,2) + '\n\n'
text = API.tdm.clean text
subject = '[OAB forms]'
if this.request.body?.form is 'uninstall' # wrong bug general other
subject += ' Uninstall notice'
else if this.request.body?.form is 'wrong'
subject += ' Wrong article'
else if this.request.body?.form is 'bug'
subject += ' Bug'
else if this.request.body?.form is 'general'
subject += ' General'
else
subject += ' Other'
subject += ' ' + Date.now()
try
if this.request.body?.form in ['wrong','uninstall']
whoto.push '<EMAIL>'
API.mail.send {
service: 'openaccessbutton',
from: '<EMAIL>',
to: whoto,
subject: subject,
text: text
}
return {
statusCode: 302,
headers: {
'Content-Type': 'text/plain',
'Location': (if API.settings.dev then 'https://dev.openaccessbutton.org' else 'https://openaccessbutton.org') + '/feedback#defaultthanks'
},
body: 'Location: ' + (if API.settings.dev then 'https://dev.openaccessbutton.org' else 'https://openaccessbutton.org') + '/feedback#defaultthanks'
}
API.add 'service/oab/history', () -> return oab_request.history this
API.add 'service/oab/users',
csv: true
get:
roleRequired:'openaccessbutton.admin'
action: () ->
res = Users.search this.queryParams, {restrict:[{exists:{field:'roles.openaccessbutton'}}]}
recs = []
try
for r in res.hits.hits
if not r._source.email?
r._source.email = r._source.emails[0].address
if this.request.url.split('?')[0].endsWith '.csv'
rec = {}
for f in ['_id','createdAt','created_date','updatedAt','updated_date','email','profile.name','profile.firstname','profile.lastname','service.openaccessbutton.profile.affiliation','service.openaccessbutton.profile.profession','roles.openaccessbutton','username']
rec[f] = API.collection.dot r._source, f
recs.push rec
if recs.length
return recs
else
return res
post:
roleRequired:'openaccessbutton.admin'
action: () ->
res = Users.search this.bodyParams, {restrict:[{exists:{field:'roles.openaccessbutton'}}]}
try
for r in res.hits.hits
if not res.hits.hits[r]._source.email?
res.hits.hits[r]._source.email = res.hits.hits[r]._source.emails[0].address
return res
API.add 'service/oab/redirect', get: () -> return API.service.oab.redirect this.queryParams.url, this.queryParams.refresh?
API.add 'service/oab/status', get: () -> return API.service.oab.status()
API.add 'service/oab/stats', get: () -> return API.service.oab.stats this.queryParams.tool
API.add 'service/oab/stats/emails',
post:
roleRequired:'openaccessbutton.admin'
action: () ->
res = {}
for uid in this.request.body
try res[uid] = API.accounts.retrieve(uid).emails[0].address
return res
API.service.oab.status = () ->
return # simple queries to get basic status - use stats below for more complex feedback
requests: oab_request.count()
stories: oab_request.count undefined, 'story:*'
test: oab_request.count undefined, {test:true}
help: oab_request.count undefined, {status:'help'}
moderate: oab_request.count undefined, {status:'moderate'}
progress: oab_request.count undefined, {status:'progress'}
hold: oab_request.count undefined, {status:'hold'}
refused: oab_request.count undefined, {status:'refused'}
received: oab_request.count undefined, {status:'received'}
supports: oab_support.count()
finds: oab_find.count()
found: oab_find.count undefined, 'url:*'
users: Users.count undefined, {exists:{field:"roles.openaccessbutton"}}
requested: oab_request.count 'user.id', {exists:{field:"user.id"}}
API.service.oab.stats = (tool) ->
tool = undefined if tool? and tool not in ['embedoa','illiad','clio']
q = if tool is 'embedoa' then 'plugin:'+tool else if tool? then 'from:'+tool else undefined
res = status: API.service.oab.status(), requests: {}
if q?
res.status.finds = oab_find.count undefined, q
res.status.found = oab_find.count undefined, q + ' AND url:*'
res.status.stories = oab_request.count undefined, q + ' AND story:*'
twoyearsago = Date.now() - (31536000000*2)
rgs = {requests: {date_histogram: {field: "createdAt", interval: "week"}}}
rgs.requests2yrs = {aggs: {vals: {date_histogram: {field: "createdAt", interval: "week"}}}, filter: {range: {createdAt: {gt: twoyearsago }}}}
rgs.stories2yrs = {aggs: {vals: {date_histogram: {field: "createdAt", interval: "week"}}}, filter: {bool: {must: [{exists: {field: 'story'}}, {range: {createdAt: {gt: twoyearsago }}}]}}}
rgs.received2yrs = {aggs: {vals: {date_histogram: {field: "received.date", interval: "week"}}}, filter: {bool: {must: [{term: {status: 'received'}}, {range: {createdAt: {gt: twoyearsago }}}]}}}
#ra = oab_request.search q, {size: 0, aggregations: rgs}
#res.requests.requests = ra.aggregations.requests.buckets
#res.requests.requests2yrs = ra.aggregations.requests2yrs.vals.buckets
#res.requests.stories2yrs = ra.aggregations.stories2yrs.vals.buckets
#res.requests.received2yrs = ra.aggregations.received2yrs.vals.buckets
# query finds
tmwk = moment().startOf('week').valueOf() # timestamp up to a week ago
tm1 = moment().startOf('month').valueOf() # timestamp at start of the current month
tm3 = moment().subtract(3,'months').valueOf() # timestamp 3 months ago
aggs =
users: {terms: {field: "from.exact", size: 10000}, aggs: {firsts: {terms: {field: "created_date", size: 1, order: {_term: "asc"}}}}}
finds: {date_histogram: {field: "createdAt", interval: "week"}}
emails: {cardinality : {field: "email.exact"}}
tm1: {filter: {range: {createdAt: {gt: tm1}}}, aggs: {tm1v: {cardinality: {field: "email.exact" }}}}
tm3: {filter: {range: {createdAt: {gt: tm3, lte: tm1 }}}, aggs: {tm3v: {cardinality: {field: "email.exact" }}}}
facets =
plugin: { terms: { field: "plugin.exact", size: 500}}
plugin_week: { terms: { field: "plugin.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: tmwk }}}}
plugin_month: { terms: { field: "plugin.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: tm1 }}}}
plugin_threemonth: { terms: { field: "plugin.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: tm3 }}}}
plugin_june18: { terms: { field: "plugin.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: 1527811200000 }}}}
email: { terms: { field: "email.exact", size: 1 } }
embeds: { terms: { field: "embedded.exact", size: 500 } }
from_week: { terms: { field: "from.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: tmwk }}}}
from_month: { terms: { field: "from.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: tm1 }}}}
from_threemonth: { terms: { field: "from.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: tm3 }}}}
from_june18: { terms: { field: "from.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: 1527811200000 }}}}
finds = oab_find.search q, { size: 0, aggs: aggs, facets: facets}
res.find = {total: finds.hits.total, users: {}}
try
for u in finds.aggregations.users.buckets
res.find.users[u.key] = count: u.doc_count, first: u.firsts.buckets[0].key_as_string.split(' ')[0].split('-').reverse().join('/')
try res.find.finds = finds.aggregations.finds.buckets
try res.find.emails = finds.aggregations.emails.value
try res.find.tm1 = finds.aggregations.tm1.tm1v.value
try res.find.tm3 = finds.aggregations.tm3.tm3v.value
try res.find.plugin = finds.facets.plugin.terms
try res.find.plugin_week = finds.facets.plugin_week.terms
try res.find.plugin_month = finds.facets.plugin_month.terms
try res.find.plugin_threemonth = finds.facets.plugin_threemonth.terms
try res.find.plugin_june18 = finds.facets.plugin_june18.terms
try res.find.email = finds.facets.email.terms
try res.find.anonymous = finds.facets.email.missing
try res.find.embeds = finds.facets.embeds.terms
try res.find.from_week = finds.facets.from_week.terms
try res.find.from_month = finds.facets.from_month.terms
try res.find.from_threemonth = finds.facets.from_threemonth.terms
try res.find.from_june18 = finds.facets.from_june18.terms
res.plugins = {api:{all:finds.facets.plugin.missing, week:finds.facets.plugin_week.missing, month:finds.facets.plugin_month.missing, threemonth:finds.facets.plugin_threemonth.missing, june18:finds.facets.plugin_june18.missing}}
wrongpings = {}
if not tool? # get pings
pingcounts = {alltime:{},week:{},month:{},threemonth:{},june18:{}}
for h in pings.search('service:openaccessbutton AND action:*', {newest: false, size: 100000}).hits.hits
hr = h._source
if hr.from and hr.action.toLowerCase() is 'instantill_wrong_article'
wrongpings[hr.from] ?= 0
wrongpings[hr.from] += 1
for nm in _.keys pingcounts
if nm is 'alltime' or (nm is 'week' and hr.createdAt > tmwk) or (nm is 'month' and hr.createdAt > tm1) or (nm is 'threemonth' and hr.createdAt > tm3) or (nm is 'june18' and hr.createdAt > 1527811200000)
pingcounts[nm][hr.action] = (pingcounts[nm][hr.action] ? 0) + 1
sorts = []
for kv of pingcounts.alltime
sp = action: kv
sp[nm] = (pingcounts[nm][kv] ? 0) for nm in _.keys pingcounts
sorts.push sp
res.pings = sorts.sort((a, b) -> return a.alltime - b.alltime)
if not tool? or tool is 'embedoa' # stats on embedoa
eggs = {users: {terms: {field: "from.exact", size: 10000}}}
eggs.users.aggs = {firsts: {terms: {field:"created_date", size: 1, order: {_term: "asc"}}}}
eggs.users.aggs.oa = {filter: {bool: {must: [{exists: {field: "url"}}]}}, aggs: {from: {terms: {field: "from.exact"}}}}
eggs.users.aggs.embeds = {terms: {field: "embedded.exact", size: 100}}
eres = oab_find.search {plugin: 'widget'}, {size: 0, aggs: eggs}
# TODO finish formatting the embedoa results into the necessary stats
res.embedoa = {}
try
for u in eres.aggregations.users.buckets
res.embedoa[u.key] = count: u.doc_count
try res.embedoa[u.key].first = u.firsts.buckets[0].key_as_string.split(' ')[0].split('-').reverse().join('/')
try res.embedoa[u.key].oa = u.oa.doc_count # check this
res.embedoa[u.key].embeds = []
for em in u.embeds.buckets
tk = em.key.split('?')[0].split('#')[0]
res.embedoa[u.key].embeds.push(tk) if tk not in res.embedoa[u.key].embeds
if not tool? # ills and shareyourpapers
iggs = {users: {terms: {field: "from.exact", size: 10000}}}
iggs.users.aggs = {firsts: {terms: {field:"created_date", size: 1, order: {_term: "asc"}}}}
iggs.users.aggs.oa = {filter: {bool: {must: [{exists: {field: "url"}}]}}, aggs: {from: {terms: {field: "from.exact"}}}}
iggs.users.aggs.subs = {filter: {query: {query_string: {query: "ill.subscription.url:*"}}}, aggs: {from: {terms: {field: "from.exact"}}}}
#iggs.users.aggs.wrong = {filter: {term: {wrong: true}}, aggs: {from: {terms: {field: "from.exact"}}}}
iggs.users.aggs.embeds = {terms: {field: "embedded.exact", size: 100}}
illfinds = oab_find.search {plugin: 'instantill'}, {size: 0, aggs: iggs}
res.ill = {}
try
for u in illfinds.aggregations.users.buckets
res.ill[u.key] = count: u.doc_count
try res.ill[u.key].first = u.firsts.buckets[0].key_as_string.split(' ')[0].split('-').reverse().join('/')
try res.ill[u.key].oa = u.oa.doc_count
try res.ill[u.key].subs = u.subs.doc_count
#try res.ill[u.key].wrong = u.wrong.doc_count
try res.ill[u.key].wrong = wrongpings[u.key]
res.ill[u.key].embeds = []
for em in u.embeds.buckets
tk = em.key.split('?')[0].split('#')[0]
res.ill[u.key].embeds.push(tk) if tk not in res.ill[u.key].embeds
igs = {users: {terms: {field: "from.exact", size: 10000}}}
igs.issn = {filter: {query: {query_string: {query: "metadata.title:* AND metadata.journal:* AND metadata.year:* AND metadata.issn:*"}}}, aggs: {users: {terms: {field: "from.exact", size: 10000}}}}
igs.forwarded = {filter: {term: {forwarded: true}}, aggs: {users: {terms: {field: "from.exact", size: 10000}}}}
ills = oab_ill.search undefined, {size: 0, aggs: igs}
try
for u in ills.aggregations.users.buckets
res.ill[u.key] ?= {}
res.ill[u.key].ill = u.doc_count
try res.ill[u.key].withissn = u.doc_count for u in ills.aggregations.issn.users.buckets
try res.ill[u.key].forwarded = u.doc_count for u in ills.aggregations.forwarded.users.buckets
sggs = {users: {terms: {field: "from.exact", size: 10000}}}
sggs.users.aggs = {firsts: {terms: {field:"created_date", size: 1, order: {_term: "asc"}}}}
sggs.users.aggs.embeds = {terms: {field: "embedded.exact", size: 100}}
sypfinds = oab_find.search {plugin: 'shareyourpaper'}, {size: 0, aggs: sggs}
res.syp = {}
try
for u in sypfinds.aggregations.users.buckets
res.syp[u.key] = count: u.doc_count
try res.syp[u.key].first = u.firsts.buckets[0].key_as_string.split(' ')[0].split('-').reverse().join('/')
res.syp[u.key].embeds = []
for em in u.embeds.buckets
tk = em.key.split('?')[0].split('#')[0]
res.syp[u.key].embeds.push(tk) if tk not in res.syp[u.key].embeds
res.syp[u.key].review ?= 0
res.syp[u.key].zenodo ?= 0
res.syp[u.key].redeposit ?= 0
res.syp[u.key].forward ?= 0
res.syp[u.key].dark ?= 0
oab_catalogue.each 'deposit.from.exact:* AND deposit.type.exact:*', (rec) ->
for d in rec.deposit
res.syp[d.from] ?= {}
#if not res.syp[d.from].firstAt or res.syp[d.from].firstAt < d.createdAt
# res.syp[d.from].firstAt = d.createdAt
# res.syp[d.from].first = d.created_date.split(' ')[0].split('-').reverse().join('/')
res.syp[d.from].review ?= 0
res.syp[d.from].zenodo ?= 0
res.syp[d.from].redeposit ?= 0
res.syp[d.from].forward ?= 0
res.syp[d.from].dark ?= 0
res.syp[d.from][d.type] ?= 0
res.syp[d.from][d.type] += 1
return res
API.service.oab.blacklist = (url,stale=360000) ->
API.log msg: 'Checking OAB blacklist', url: url
stale = 0 if stale is false
url = url.toString() if typeof url is 'number'
return false if url? and (url.length < 4 or url.indexOf('.') is -1)
bl = API.use.google.sheets.feed API.settings.service.openaccessbutton?.google?.sheets?.blacklist, stale
blacklist = []
blacklist.push(i.url) for i in bl
if url
if url.indexOf('http') isnt 0 and url.indexOf(' ') isnt -1
return false # sometimes article titles get sent here, no point checking them on the blacklist
else
for b in blacklist
return true if url.indexOf(b) isnt -1
return false
else
return blacklist
API.service.oab.dnr = (email,add,refuse) ->
return oab_dnr.search('*')?.hits?.hits if not email? and not add?
ondnr = oab_dnr.find {email:email}
if add and not ondnr
oab_dnr.insert {email:email}
# also set any requests where this author is the email address to refused - can't use the address!
if refuse
oab_request.each {email:email}, (req) -> API.service.oab.refuse req._id, 'Author DNRd their email address'
else
oab_request.each {email:email}, (req) ->
if req.status in ['help','moderate','progress']
oab_request.update r._id, {email:'',status:'help'}
return ondnr? or add is true
API.service.oab.template = (template,refresh) ->
if refresh or mail_template.count(undefined,{service:'openaccessbutton'}) is 0
mail_template.remove {service:'openaccessbutton'}
ghurl = API.settings.service.openaccessbutton?.templates_url
ghp = ghurl.split('.com/')[1].split('/tree')[0]
m = API.tdm.extract
url:ghurl
matchers:['/href="/' + ghp + '/blob/' + (if API.settings.dev then 'develop' else 'master') + '/emails/(.*?[.].*?)">/gi']
start:'<table class="files'
end:'</table'
fls = []
fls.push(fm.result[1]) for fm in m.matches
flurl = ghurl.replace('github.com','raw.githubusercontent.com').replace('/tree','')
for f in fls
if f isnt 'archive'
content = HTTP.call('GET',flurl + '/' + f).content
API.mail.template undefined,{filename:f,service:'openaccessbutton',content:content}
return API.mail.template {service:'openaccessbutton'}
else if template
return API.mail.template template
else
return API.mail.template {service:'openaccessbutton'}
# run a template refresh on every restart
Meteor.setTimeout (() -> API.service.oab.template(undefined, true) if API.status.ip() not in (API.settings.cluster.ip ? [])), 40000
API.service.oab.validate = (email, domain, verify=false) ->
bad = ['<EMAIL>']
if typeof email isnt 'string' or email.indexOf(',') isnt -1 or email in bad
return false
else if email.indexOf('@openaccessbutton.org') isnt -1 or email.indexOf('@email.ghostinspector.com') isnt -1 #or email in []
return true
else
#v = API.mail.validate email, API.settings.service.openaccessbutton.mail.pubkey
# not using mailgun verification any more, just do the direct simple check of the email
v = {}
if typeof email is 'string' and email.length and email.indexOf(' ') is -1
[n, d] = email.split '@'
if n.length and d.length and d.split('.').length > 1
v = is_valid: true
if v.is_valid and (not verify or v.mailbox_verification in [true,'true'])
if false #domain and domain not in ['qZooaHWRz9NLFNcgR','eZwJ83xp3oZDaec86'] # turning this off for now
iacc = API.accounts.retrieve domain
return 'baddomain' if not iacc?
eml = false #iacc.email ? iacc.emails[0].address # may also later have a config where the allowed domains can be listed but for now just match the domain of the account holder - only in the case where shareyourpaper config exists
dc = false
try
dc = API.service.oab.deposit.config iacc
#eml = dc.adminemail if dc.adminemail? # don't bother defaulting to the admin email
dc.email_domains = dc.email_domains.split(',') if dc.email_domains? and typeof dc.email_domains is 'string'
if dc isnt false and dc.email_domains? and _.isArray(dc.email_domains) and dc.email_domains.length > 0
for ed in dc.email_domains
if email.toLowerCase().indexOf(ed.toLowerCase()) > 0
return true
return 'baddomain'
else
if typeof eml is 'string' and eml.toLowerCase().indexOf(email.split('@')[1].split('.')[0].toLowerCase()) is -1
return 'baddomain'
else
return true
else
return true
else if v.did_you_mean
return v.did_you_mean
else
return false
API.service.oab.vars = (vars) ->
vars = JSON.parse JSON.stringify vars # need this in case a request is passed in as vars and later edited
if vars?.user
u = API.accounts.retrieve vars.user.id
if u
vars.profession = u.service?.openaccessbutton?.profile?.profession ? 'person'
vars.profession = 'person' if vars.profession.toLowerCase() is 'other'
vars.affiliation = u.service?.openaccessbutton?.profile?.affiliation ? ''
vars.userid = vars.user.id
vars.fullname = u?.profile?.name ? ''
if not vars.fullname and u?.profile?.firstname
vars.fullname = u.profile.firstname
vars.fullname += ' ' + u.profile.lastname if u.profile.lastname
vars.username = vars.user.username ? vars.fullname
vars.useremail = vars.user.email
vars.profession ?= 'person'
vars.fullname ?= '<NAME> <NAME>'
vars.name ?= '<NAME>'
return vars
API.service.oab.substitute = (content,vars,markdown) ->
vars = API.service.oab.vars vars
if API.settings.dev
content = content.replace(/https:\/\/openaccessbutton.org/g,'https://dev.openaccessbutton.org')
content = content.replace(/https:\/\/api.openaccessbutton.org/g,'https://dev.api.cottagelabs.com/service/oab')
return API.mail.substitute content, vars, markdown
API.service.oab.mail = (opts={}) ->
opts.service = 'openaccessbutton'
opts.subject ?= 'Hello from Open Access Button'
opts.from ?= API.settings.service.openaccessbutton?.requests_from
if opts.bcc is 'ALL'
opts.bcc = []
Users.each {"roles.openaccessbutton":"*"}, (user) -> opts.bcc.push user.emails[0].address
return API.mail.send opts
API.service.oab.admin = (rid,action) ->
r = oab_request.get rid
vars = API.service.oab.vars r
usermail
if r.user?.id
u = API.accounts.retrieve r.user.id
usermail = u.emails[0].address
update = {}
requestors = []
requestors.push(usermail) if usermail
oab_support.each {rid:rid}, (s) -> requestors.push(s.email) if s.email and s.email not in requestors
if action is 'reject_upload'
update.status = 'moderate'
API.service.oab.mail({vars:vars,template:{filename:'author_thanks_article_rejection.html'},to:r.email})
else if action is 'successful_upload'
update.status = 'received'
API.service.oab.mail({vars:vars,template:{filename:'requesters_request_success.html'},to:requestors}) if requestors.length
API.service.oab.mail({vars:vars,template:{filename:'author_thanks_article.html'},to:r.email})
else if action is 'send_to_author'
update.status = 'progress'
update.rating = 1 if r.story
API.service.oab.mail({vars:vars,template:{filename:'requesters_request_inprogress.html'},to:requestors}) if requestors.length
if r.type is 'article'
if r.email
if r.story
API.service.oab.mail({vars:vars,template:{filename:'author_request_article_v2.html'},to:r.email})
else
API.service.oab.mail({vars:vars,template:{filename:'author_request_article_v2_nostory.html'},to:r.email})
else if r.email
API.service.oab.mail({vars:vars,template:{filename:'author_request_data_v2.html'},to:r.email})
else if action is 'story_too_bad'
update.status = 'help'
update.rating = 0
API.service.oab.mail({vars:vars,template:{filename:'initiator_poorstory.html'},to:requestors}) if requestors.length
API.service.oab.mail({vars:vars,template:{filename:'author_request_article_v2_nostory.html'},to:r.email}) if r.email
else if action is 'not_a_scholarly_article'
update.status = 'closed'
API.service.oab.mail({vars:vars,template:{filename:'initiator_invalid.html'},to:usermail}) if usermail
else if action is 'dead_author'
update.status = 'closed'
API.service.oab.mail({vars:vars,template:{filename:'requesters_request_failed_authordeath.html'},to:requestors}) if requestors.length
else if action is 'user_testing'
update.test = true
update.status = 'closed'
update.rating = 0 if r.story
API.service.oab.mail({vars:vars,template:{filename:'initiator_testing.html'},to:usermail}) if usermail
else if action is 'broken_link' and usermail
API.service.oab.mail({vars:vars,template:{filename:'initiator_brokenlink.html'},to:usermail})
update.status = 'closed'
else if action is 'remove_submitted_url'
update.status = 'moderate'
update.received = false
else if action is 'article_before_2000'
API.service.oab.mail({vars:vars,template:{filename:'article_before_2000.html'},to:requestors}) if requestors.length
update.status = 'closed'
else if action is 'author_email_not_found'
API.service.oab.mail({vars:vars,template:{filename:'author_email_not_found.html'},to:requestors}) if requestors.length
update.status = 'closed'
else if action is 'link_by_author'
API.service.oab.mail({vars:vars,template:{filename:'authors_thanks_article.html'},to:r.email}) if r.email
API.service.oab.mail({vars:vars,template:{filename:'requestors_request_success_article.html'},to:requestors}) if requestors.length
update.status = 'received'
else if action is 'link_by_admin'
API.service.oab.mail({vars:vars,template:{filename:'requestors_request_success_article.html'},to:requestors}) if requestors.length
update.status = 'received'
oab_request.update(rid,update) if JSON.stringify(update) isnt '{}'
# LIVE: https://docs.google.com/spreadsheets/d/1Te9zcQtBLq2Vx81JUE9R42fjptFGXY6jybXBCt85dcs/edit#gid=0
# Develop: https://docs.google.com/spreadsheets/d/1AaY7hS0D9jtLgVsGO4cJuLn_-CzNQg0yCreC3PP3UU0/edit#gid=0
API.service.oab.redirect = (url,refresh=false) ->
API.log msg: 'Checking OAB open list', url: url
url = API.http.resolve url, refresh # will return undefined if the url doesn't resolve at all
if url
return false if API.service.oab.blacklist(url) is true # ignore anything on the usual URL blacklist
list = API.use.google.sheets.feed API.settings.service.openaccessbutton?.google?.sheets?.redirect, 360000
for listing in list
if listing.redirect and url.replace('http://','').replace('https://','').split('#')[0] is listing.redirect.replace('http://','').replace('https://','').split('#')[0]
# we have an exact alternative for this url
return listing.redirect
else if typeof url is 'string' and url.indexOf(listing.domain.replace('http://','').replace('https://','').split('/')[0]) isnt -1
url = url.replace('http://','https://') if listing.domain.indexOf('https://') is 0
listing.domain = listing.domain.replace('http://','https://') if url.indexOf('https://') is 0
if (listing.fulltext and listing.splash and listing.identifier) or listing.element
source = url
if listing.fulltext
# switch the url by comparing the fulltext and splash examples, and converting the url in the same way
parts = listing.splash.split listing.identifier
if url.indexOf(parts[0]) is 0 # can only successfully replace if the incoming url starts with the same as the start of the splash url
diff = url.replace parts[0], ''
diff = diff.replace(parts[1],'') if parts.length > 1
url = listing.fulltext.replace listing.identifier, diff
else if listing.element and url.indexOf('.pdf') is -1
try
content = API.http.puppeteer url
url = content.toLowerCase().split(listing.element.toLowerCase())[1].split('"')[0].split("'")[0].split('>')[0]
return false if (not url? or url.length < 6 or url is source) and listing.blacklist is "yes"
# fulltext or element can possibly give us a url which then redirects to a login wall
# so we have to check the given url against the whole sheet listing again for the login wall
# so this allows the rest of the listing to be checked before returning - MAKE SURE loginwall fragments are at the end of the sheet
resv = API.http.resolve url # resolve it again to make sure whatever we have now is accessible
url = resv if typeof resv is 'string'
else if listing.loginwall and url.indexOf(listing.loginwall.replace('http://','').replace('https://','')) isnt -1
# this url is on the login wall of the repo in question, so it is no use
return false
else if listing.blacklist is "yes"
return false
if typeof url is 'string'
# some URLs can be confirmed as resolvable but we also hit a captcha response and end up serving that to the user
# we want to avoid that, so when such URLs appear to be found here, just return true instead, which will cause
# us to accept the original URL
# we introduced this because of issue https://github.com/OAButton/discussion/issues/1257
# and for example https://www.tandfonline.com/doi/pdf/10.1080/17521740701702115?needAccess=true
# ends up as https://www.tandfonline.com/action/captchaChallenge?redirectUri=%2Fdoi%2Fpdf%2F10.1080%2F17521740701702115%3FneedAccess%3Dtrue
for avoid in ['captcha','challenge']
return undefined if url.toLowerCase().indexOf(avoid) isnt -1
return url
| true |
import moment from 'moment'
API.service ?= {}
API.service.oab ?= {}
# these are global so can be accessed on other oabutton files
@oab_support = new API.collection {index:"oab",type:"support"}
@oab_catalogue = new API.collection {index:"oab",type:"catalogue"}
@oab_request = new API.collection {index:"oab",type:"request",history:true}
@oab_find = new API.collection {index:"oab",type:"find"}
@oab_ill = new API.collection {index:"oab",type:"ill"}
@oab_permissions = new API.collection {index:"oab",type:"permissions"}
@oab_dnr = new API.collection {index:"oab",type:"oab_dnr"}
API.add 'service/oab',
get: () -> return {data: 'The Open Access Button API.'}
post:
roleRequired:'openaccessbutton.user'
action: () ->
return {data: 'You are authenticated'}
API.add 'service/oab/blacklist',
get: () -> return {data:API.service.oab.blacklist(this.queryParams.url,this.queryParams.stale)}
API.add 'service/oab/templates',
get: () -> return API.service.oab.template(this.queryParams.template,this.queryParams.refresh)
API.add 'service/oab/substitute',
post: () -> return API.service.oab.substitute this.request.body.content,this.request.body.vars,this.request.body.markdown
API.add 'service/oab/mail',
post:
roleRequired:'openaccessbutton.admin'
action: () -> return API.service.oab.mail this.request.body
API.add 'service/oab/validate',
post:
authOptional:true
action: () ->
if this.queryParams.email and (this.queryParams.uid or this.userId) #and (this.queryParams.uid is 'anonymous' or API.accounts.retrieve(this.queryParams.uid ? this.userId))
return API.service.oab.validate this.queryParams.email, this.queryParams.domained, this.queryParams.verify
else
return undefined
API.add 'service/oab/dnr',
get:
authOptional: true
action: () ->
return API.service.oab.dnr() if not this.queryParams.email? and this.user and API.accounts.auth 'openaccessbutton.admin', this.user
d = {}
d.dnr = API.service.oab.dnr this.queryParams.email
if not d.dnr and this.queryParams.user
u = API.accounts.retrieve this.queryParams.user
d.dnr = 'user' if u.emails[0].address is this.queryParams.email
if not d.dnr and this.queryParams.request
r = oab_request.get this.queryParams.request
d.dnr = 'creator' if r.user.email is this.queryParams.email
if not d.dnr
d.dnr = 'supporter' if oab_support.find {rid:this.queryParams.request, email:this.queryParams.email}
if not d.dnr and this.queryParams.validate
d.validation = API.mail.validate this.queryParams.email, API.settings.service?.openaccessbutton?.mail?.pubkey
d.dnr = 'invalid' if not d.validation.is_valid
return d
post: () ->
e = this.queryParams.email ? this.request.body.email
refuse = if not this.queryParams.refuse? or this.queryParams.refuse in ['false',false] then false else true
return if e then API.service.oab.dnr(e,true,refuse) else 400
delete:
roleRequired: 'openaccessbutton.admin'
action: () ->
oab_dnr.remove({email:this.queryParams.email}) if this.queryParams.email
return {}
API.add 'service/oab/bug',
post: () ->
if (this.request.body?.contact? and this.request.body.contact.length) or (this.request.body?.email? and API.service.oab.validate(this.request.body.email) isnt true)
return ''
else
whoto = ['PI:EMAIL:<EMAIL>END_PI']
text = ''
for k of this.request.body
text += k + ': ' + JSON.stringify(this.request.body[k],undefined,2) + '\n\n'
text = API.tdm.clean text
subject = '[OAB forms]'
if this.request.body?.form is 'uninstall' # wrong bug general other
subject += ' Uninstall notice'
else if this.request.body?.form is 'wrong'
subject += ' Wrong article'
else if this.request.body?.form is 'bug'
subject += ' Bug'
else if this.request.body?.form is 'general'
subject += ' General'
else
subject += ' Other'
subject += ' ' + Date.now()
try
if this.request.body?.form in ['wrong','uninstall']
whoto.push 'PI:EMAIL:<EMAIL>END_PI'
API.mail.send {
service: 'openaccessbutton',
from: 'PI:EMAIL:<EMAIL>END_PI',
to: whoto,
subject: subject,
text: text
}
return {
statusCode: 302,
headers: {
'Content-Type': 'text/plain',
'Location': (if API.settings.dev then 'https://dev.openaccessbutton.org' else 'https://openaccessbutton.org') + '/feedback#defaultthanks'
},
body: 'Location: ' + (if API.settings.dev then 'https://dev.openaccessbutton.org' else 'https://openaccessbutton.org') + '/feedback#defaultthanks'
}
API.add 'service/oab/history', () -> return oab_request.history this
API.add 'service/oab/users',
csv: true
get:
roleRequired:'openaccessbutton.admin'
action: () ->
res = Users.search this.queryParams, {restrict:[{exists:{field:'roles.openaccessbutton'}}]}
recs = []
try
for r in res.hits.hits
if not r._source.email?
r._source.email = r._source.emails[0].address
if this.request.url.split('?')[0].endsWith '.csv'
rec = {}
for f in ['_id','createdAt','created_date','updatedAt','updated_date','email','profile.name','profile.firstname','profile.lastname','service.openaccessbutton.profile.affiliation','service.openaccessbutton.profile.profession','roles.openaccessbutton','username']
rec[f] = API.collection.dot r._source, f
recs.push rec
if recs.length
return recs
else
return res
post:
roleRequired:'openaccessbutton.admin'
action: () ->
res = Users.search this.bodyParams, {restrict:[{exists:{field:'roles.openaccessbutton'}}]}
try
for r in res.hits.hits
if not res.hits.hits[r]._source.email?
res.hits.hits[r]._source.email = res.hits.hits[r]._source.emails[0].address
return res
API.add 'service/oab/redirect', get: () -> return API.service.oab.redirect this.queryParams.url, this.queryParams.refresh?
API.add 'service/oab/status', get: () -> return API.service.oab.status()
API.add 'service/oab/stats', get: () -> return API.service.oab.stats this.queryParams.tool
API.add 'service/oab/stats/emails',
post:
roleRequired:'openaccessbutton.admin'
action: () ->
res = {}
for uid in this.request.body
try res[uid] = API.accounts.retrieve(uid).emails[0].address
return res
API.service.oab.status = () ->
return # simple queries to get basic status - use stats below for more complex feedback
requests: oab_request.count()
stories: oab_request.count undefined, 'story:*'
test: oab_request.count undefined, {test:true}
help: oab_request.count undefined, {status:'help'}
moderate: oab_request.count undefined, {status:'moderate'}
progress: oab_request.count undefined, {status:'progress'}
hold: oab_request.count undefined, {status:'hold'}
refused: oab_request.count undefined, {status:'refused'}
received: oab_request.count undefined, {status:'received'}
supports: oab_support.count()
finds: oab_find.count()
found: oab_find.count undefined, 'url:*'
users: Users.count undefined, {exists:{field:"roles.openaccessbutton"}}
requested: oab_request.count 'user.id', {exists:{field:"user.id"}}
API.service.oab.stats = (tool) ->
tool = undefined if tool? and tool not in ['embedoa','illiad','clio']
q = if tool is 'embedoa' then 'plugin:'+tool else if tool? then 'from:'+tool else undefined
res = status: API.service.oab.status(), requests: {}
if q?
res.status.finds = oab_find.count undefined, q
res.status.found = oab_find.count undefined, q + ' AND url:*'
res.status.stories = oab_request.count undefined, q + ' AND story:*'
twoyearsago = Date.now() - (31536000000*2)
rgs = {requests: {date_histogram: {field: "createdAt", interval: "week"}}}
rgs.requests2yrs = {aggs: {vals: {date_histogram: {field: "createdAt", interval: "week"}}}, filter: {range: {createdAt: {gt: twoyearsago }}}}
rgs.stories2yrs = {aggs: {vals: {date_histogram: {field: "createdAt", interval: "week"}}}, filter: {bool: {must: [{exists: {field: 'story'}}, {range: {createdAt: {gt: twoyearsago }}}]}}}
rgs.received2yrs = {aggs: {vals: {date_histogram: {field: "received.date", interval: "week"}}}, filter: {bool: {must: [{term: {status: 'received'}}, {range: {createdAt: {gt: twoyearsago }}}]}}}
#ra = oab_request.search q, {size: 0, aggregations: rgs}
#res.requests.requests = ra.aggregations.requests.buckets
#res.requests.requests2yrs = ra.aggregations.requests2yrs.vals.buckets
#res.requests.stories2yrs = ra.aggregations.stories2yrs.vals.buckets
#res.requests.received2yrs = ra.aggregations.received2yrs.vals.buckets
# query finds
tmwk = moment().startOf('week').valueOf() # timestamp up to a week ago
tm1 = moment().startOf('month').valueOf() # timestamp at start of the current month
tm3 = moment().subtract(3,'months').valueOf() # timestamp 3 months ago
aggs =
users: {terms: {field: "from.exact", size: 10000}, aggs: {firsts: {terms: {field: "created_date", size: 1, order: {_term: "asc"}}}}}
finds: {date_histogram: {field: "createdAt", interval: "week"}}
emails: {cardinality : {field: "email.exact"}}
tm1: {filter: {range: {createdAt: {gt: tm1}}}, aggs: {tm1v: {cardinality: {field: "email.exact" }}}}
tm3: {filter: {range: {createdAt: {gt: tm3, lte: tm1 }}}, aggs: {tm3v: {cardinality: {field: "email.exact" }}}}
facets =
plugin: { terms: { field: "plugin.exact", size: 500}}
plugin_week: { terms: { field: "plugin.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: tmwk }}}}
plugin_month: { terms: { field: "plugin.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: tm1 }}}}
plugin_threemonth: { terms: { field: "plugin.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: tm3 }}}}
plugin_june18: { terms: { field: "plugin.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: 1527811200000 }}}}
email: { terms: { field: "email.exact", size: 1 } }
embeds: { terms: { field: "embedded.exact", size: 500 } }
from_week: { terms: { field: "from.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: tmwk }}}}
from_month: { terms: { field: "from.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: tm1 }}}}
from_threemonth: { terms: { field: "from.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: tm3 }}}}
from_june18: { terms: { field: "from.exact", size: 500 }, facet_filter: {range: {createdAt: {gt: 1527811200000 }}}}
finds = oab_find.search q, { size: 0, aggs: aggs, facets: facets}
res.find = {total: finds.hits.total, users: {}}
try
for u in finds.aggregations.users.buckets
res.find.users[u.key] = count: u.doc_count, first: u.firsts.buckets[0].key_as_string.split(' ')[0].split('-').reverse().join('/')
try res.find.finds = finds.aggregations.finds.buckets
try res.find.emails = finds.aggregations.emails.value
try res.find.tm1 = finds.aggregations.tm1.tm1v.value
try res.find.tm3 = finds.aggregations.tm3.tm3v.value
try res.find.plugin = finds.facets.plugin.terms
try res.find.plugin_week = finds.facets.plugin_week.terms
try res.find.plugin_month = finds.facets.plugin_month.terms
try res.find.plugin_threemonth = finds.facets.plugin_threemonth.terms
try res.find.plugin_june18 = finds.facets.plugin_june18.terms
try res.find.email = finds.facets.email.terms
try res.find.anonymous = finds.facets.email.missing
try res.find.embeds = finds.facets.embeds.terms
try res.find.from_week = finds.facets.from_week.terms
try res.find.from_month = finds.facets.from_month.terms
try res.find.from_threemonth = finds.facets.from_threemonth.terms
try res.find.from_june18 = finds.facets.from_june18.terms
res.plugins = {api:{all:finds.facets.plugin.missing, week:finds.facets.plugin_week.missing, month:finds.facets.plugin_month.missing, threemonth:finds.facets.plugin_threemonth.missing, june18:finds.facets.plugin_june18.missing}}
wrongpings = {}
if not tool? # get pings
pingcounts = {alltime:{},week:{},month:{},threemonth:{},june18:{}}
for h in pings.search('service:openaccessbutton AND action:*', {newest: false, size: 100000}).hits.hits
hr = h._source
if hr.from and hr.action.toLowerCase() is 'instantill_wrong_article'
wrongpings[hr.from] ?= 0
wrongpings[hr.from] += 1
for nm in _.keys pingcounts
if nm is 'alltime' or (nm is 'week' and hr.createdAt > tmwk) or (nm is 'month' and hr.createdAt > tm1) or (nm is 'threemonth' and hr.createdAt > tm3) or (nm is 'june18' and hr.createdAt > 1527811200000)
pingcounts[nm][hr.action] = (pingcounts[nm][hr.action] ? 0) + 1
sorts = []
for kv of pingcounts.alltime
sp = action: kv
sp[nm] = (pingcounts[nm][kv] ? 0) for nm in _.keys pingcounts
sorts.push sp
res.pings = sorts.sort((a, b) -> return a.alltime - b.alltime)
if not tool? or tool is 'embedoa' # stats on embedoa
eggs = {users: {terms: {field: "from.exact", size: 10000}}}
eggs.users.aggs = {firsts: {terms: {field:"created_date", size: 1, order: {_term: "asc"}}}}
eggs.users.aggs.oa = {filter: {bool: {must: [{exists: {field: "url"}}]}}, aggs: {from: {terms: {field: "from.exact"}}}}
eggs.users.aggs.embeds = {terms: {field: "embedded.exact", size: 100}}
eres = oab_find.search {plugin: 'widget'}, {size: 0, aggs: eggs}
# TODO finish formatting the embedoa results into the necessary stats
res.embedoa = {}
try
for u in eres.aggregations.users.buckets
res.embedoa[u.key] = count: u.doc_count
try res.embedoa[u.key].first = u.firsts.buckets[0].key_as_string.split(' ')[0].split('-').reverse().join('/')
try res.embedoa[u.key].oa = u.oa.doc_count # check this
res.embedoa[u.key].embeds = []
for em in u.embeds.buckets
tk = em.key.split('?')[0].split('#')[0]
res.embedoa[u.key].embeds.push(tk) if tk not in res.embedoa[u.key].embeds
if not tool? # ills and shareyourpapers
iggs = {users: {terms: {field: "from.exact", size: 10000}}}
iggs.users.aggs = {firsts: {terms: {field:"created_date", size: 1, order: {_term: "asc"}}}}
iggs.users.aggs.oa = {filter: {bool: {must: [{exists: {field: "url"}}]}}, aggs: {from: {terms: {field: "from.exact"}}}}
iggs.users.aggs.subs = {filter: {query: {query_string: {query: "ill.subscription.url:*"}}}, aggs: {from: {terms: {field: "from.exact"}}}}
#iggs.users.aggs.wrong = {filter: {term: {wrong: true}}, aggs: {from: {terms: {field: "from.exact"}}}}
iggs.users.aggs.embeds = {terms: {field: "embedded.exact", size: 100}}
illfinds = oab_find.search {plugin: 'instantill'}, {size: 0, aggs: iggs}
res.ill = {}
try
for u in illfinds.aggregations.users.buckets
res.ill[u.key] = count: u.doc_count
try res.ill[u.key].first = u.firsts.buckets[0].key_as_string.split(' ')[0].split('-').reverse().join('/')
try res.ill[u.key].oa = u.oa.doc_count
try res.ill[u.key].subs = u.subs.doc_count
#try res.ill[u.key].wrong = u.wrong.doc_count
try res.ill[u.key].wrong = wrongpings[u.key]
res.ill[u.key].embeds = []
for em in u.embeds.buckets
tk = em.key.split('?')[0].split('#')[0]
res.ill[u.key].embeds.push(tk) if tk not in res.ill[u.key].embeds
igs = {users: {terms: {field: "from.exact", size: 10000}}}
igs.issn = {filter: {query: {query_string: {query: "metadata.title:* AND metadata.journal:* AND metadata.year:* AND metadata.issn:*"}}}, aggs: {users: {terms: {field: "from.exact", size: 10000}}}}
igs.forwarded = {filter: {term: {forwarded: true}}, aggs: {users: {terms: {field: "from.exact", size: 10000}}}}
ills = oab_ill.search undefined, {size: 0, aggs: igs}
try
for u in ills.aggregations.users.buckets
res.ill[u.key] ?= {}
res.ill[u.key].ill = u.doc_count
try res.ill[u.key].withissn = u.doc_count for u in ills.aggregations.issn.users.buckets
try res.ill[u.key].forwarded = u.doc_count for u in ills.aggregations.forwarded.users.buckets
sggs = {users: {terms: {field: "from.exact", size: 10000}}}
sggs.users.aggs = {firsts: {terms: {field:"created_date", size: 1, order: {_term: "asc"}}}}
sggs.users.aggs.embeds = {terms: {field: "embedded.exact", size: 100}}
sypfinds = oab_find.search {plugin: 'shareyourpaper'}, {size: 0, aggs: sggs}
res.syp = {}
try
for u in sypfinds.aggregations.users.buckets
res.syp[u.key] = count: u.doc_count
try res.syp[u.key].first = u.firsts.buckets[0].key_as_string.split(' ')[0].split('-').reverse().join('/')
res.syp[u.key].embeds = []
for em in u.embeds.buckets
tk = em.key.split('?')[0].split('#')[0]
res.syp[u.key].embeds.push(tk) if tk not in res.syp[u.key].embeds
res.syp[u.key].review ?= 0
res.syp[u.key].zenodo ?= 0
res.syp[u.key].redeposit ?= 0
res.syp[u.key].forward ?= 0
res.syp[u.key].dark ?= 0
oab_catalogue.each 'deposit.from.exact:* AND deposit.type.exact:*', (rec) ->
for d in rec.deposit
res.syp[d.from] ?= {}
#if not res.syp[d.from].firstAt or res.syp[d.from].firstAt < d.createdAt
# res.syp[d.from].firstAt = d.createdAt
# res.syp[d.from].first = d.created_date.split(' ')[0].split('-').reverse().join('/')
res.syp[d.from].review ?= 0
res.syp[d.from].zenodo ?= 0
res.syp[d.from].redeposit ?= 0
res.syp[d.from].forward ?= 0
res.syp[d.from].dark ?= 0
res.syp[d.from][d.type] ?= 0
res.syp[d.from][d.type] += 1
return res
API.service.oab.blacklist = (url,stale=360000) ->
API.log msg: 'Checking OAB blacklist', url: url
stale = 0 if stale is false
url = url.toString() if typeof url is 'number'
return false if url? and (url.length < 4 or url.indexOf('.') is -1)
bl = API.use.google.sheets.feed API.settings.service.openaccessbutton?.google?.sheets?.blacklist, stale
blacklist = []
blacklist.push(i.url) for i in bl
if url
if url.indexOf('http') isnt 0 and url.indexOf(' ') isnt -1
return false # sometimes article titles get sent here, no point checking them on the blacklist
else
for b in blacklist
return true if url.indexOf(b) isnt -1
return false
else
return blacklist
API.service.oab.dnr = (email,add,refuse) ->
return oab_dnr.search('*')?.hits?.hits if not email? and not add?
ondnr = oab_dnr.find {email:email}
if add and not ondnr
oab_dnr.insert {email:email}
# also set any requests where this author is the email address to refused - can't use the address!
if refuse
oab_request.each {email:email}, (req) -> API.service.oab.refuse req._id, 'Author DNRd their email address'
else
oab_request.each {email:email}, (req) ->
if req.status in ['help','moderate','progress']
oab_request.update r._id, {email:'',status:'help'}
return ondnr? or add is true
API.service.oab.template = (template,refresh) ->
if refresh or mail_template.count(undefined,{service:'openaccessbutton'}) is 0
mail_template.remove {service:'openaccessbutton'}
ghurl = API.settings.service.openaccessbutton?.templates_url
ghp = ghurl.split('.com/')[1].split('/tree')[0]
m = API.tdm.extract
url:ghurl
matchers:['/href="/' + ghp + '/blob/' + (if API.settings.dev then 'develop' else 'master') + '/emails/(.*?[.].*?)">/gi']
start:'<table class="files'
end:'</table'
fls = []
fls.push(fm.result[1]) for fm in m.matches
flurl = ghurl.replace('github.com','raw.githubusercontent.com').replace('/tree','')
for f in fls
if f isnt 'archive'
content = HTTP.call('GET',flurl + '/' + f).content
API.mail.template undefined,{filename:f,service:'openaccessbutton',content:content}
return API.mail.template {service:'openaccessbutton'}
else if template
return API.mail.template template
else
return API.mail.template {service:'openaccessbutton'}
# run a template refresh on every restart
Meteor.setTimeout (() -> API.service.oab.template(undefined, true) if API.status.ip() not in (API.settings.cluster.ip ? [])), 40000
API.service.oab.validate = (email, domain, verify=false) ->
bad = ['PI:EMAIL:<EMAIL>END_PI']
if typeof email isnt 'string' or email.indexOf(',') isnt -1 or email in bad
return false
else if email.indexOf('@openaccessbutton.org') isnt -1 or email.indexOf('@email.ghostinspector.com') isnt -1 #or email in []
return true
else
#v = API.mail.validate email, API.settings.service.openaccessbutton.mail.pubkey
# not using mailgun verification any more, just do the direct simple check of the email
v = {}
if typeof email is 'string' and email.length and email.indexOf(' ') is -1
[n, d] = email.split '@'
if n.length and d.length and d.split('.').length > 1
v = is_valid: true
if v.is_valid and (not verify or v.mailbox_verification in [true,'true'])
if false #domain and domain not in ['qZooaHWRz9NLFNcgR','eZwJ83xp3oZDaec86'] # turning this off for now
iacc = API.accounts.retrieve domain
return 'baddomain' if not iacc?
eml = false #iacc.email ? iacc.emails[0].address # may also later have a config where the allowed domains can be listed but for now just match the domain of the account holder - only in the case where shareyourpaper config exists
dc = false
try
dc = API.service.oab.deposit.config iacc
#eml = dc.adminemail if dc.adminemail? # don't bother defaulting to the admin email
dc.email_domains = dc.email_domains.split(',') if dc.email_domains? and typeof dc.email_domains is 'string'
if dc isnt false and dc.email_domains? and _.isArray(dc.email_domains) and dc.email_domains.length > 0
for ed in dc.email_domains
if email.toLowerCase().indexOf(ed.toLowerCase()) > 0
return true
return 'baddomain'
else
if typeof eml is 'string' and eml.toLowerCase().indexOf(email.split('@')[1].split('.')[0].toLowerCase()) is -1
return 'baddomain'
else
return true
else
return true
else if v.did_you_mean
return v.did_you_mean
else
return false
API.service.oab.vars = (vars) ->
vars = JSON.parse JSON.stringify vars # need this in case a request is passed in as vars and later edited
if vars?.user
u = API.accounts.retrieve vars.user.id
if u
vars.profession = u.service?.openaccessbutton?.profile?.profession ? 'person'
vars.profession = 'person' if vars.profession.toLowerCase() is 'other'
vars.affiliation = u.service?.openaccessbutton?.profile?.affiliation ? ''
vars.userid = vars.user.id
vars.fullname = u?.profile?.name ? ''
if not vars.fullname and u?.profile?.firstname
vars.fullname = u.profile.firstname
vars.fullname += ' ' + u.profile.lastname if u.profile.lastname
vars.username = vars.user.username ? vars.fullname
vars.useremail = vars.user.email
vars.profession ?= 'person'
vars.fullname ?= 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI'
vars.name ?= 'PI:NAME:<NAME>END_PI'
return vars
API.service.oab.substitute = (content,vars,markdown) ->
vars = API.service.oab.vars vars
if API.settings.dev
content = content.replace(/https:\/\/openaccessbutton.org/g,'https://dev.openaccessbutton.org')
content = content.replace(/https:\/\/api.openaccessbutton.org/g,'https://dev.api.cottagelabs.com/service/oab')
return API.mail.substitute content, vars, markdown
API.service.oab.mail = (opts={}) ->
opts.service = 'openaccessbutton'
opts.subject ?= 'Hello from Open Access Button'
opts.from ?= API.settings.service.openaccessbutton?.requests_from
if opts.bcc is 'ALL'
opts.bcc = []
Users.each {"roles.openaccessbutton":"*"}, (user) -> opts.bcc.push user.emails[0].address
return API.mail.send opts
API.service.oab.admin = (rid,action) ->
r = oab_request.get rid
vars = API.service.oab.vars r
usermail
if r.user?.id
u = API.accounts.retrieve r.user.id
usermail = u.emails[0].address
update = {}
requestors = []
requestors.push(usermail) if usermail
oab_support.each {rid:rid}, (s) -> requestors.push(s.email) if s.email and s.email not in requestors
if action is 'reject_upload'
update.status = 'moderate'
API.service.oab.mail({vars:vars,template:{filename:'author_thanks_article_rejection.html'},to:r.email})
else if action is 'successful_upload'
update.status = 'received'
API.service.oab.mail({vars:vars,template:{filename:'requesters_request_success.html'},to:requestors}) if requestors.length
API.service.oab.mail({vars:vars,template:{filename:'author_thanks_article.html'},to:r.email})
else if action is 'send_to_author'
update.status = 'progress'
update.rating = 1 if r.story
API.service.oab.mail({vars:vars,template:{filename:'requesters_request_inprogress.html'},to:requestors}) if requestors.length
if r.type is 'article'
if r.email
if r.story
API.service.oab.mail({vars:vars,template:{filename:'author_request_article_v2.html'},to:r.email})
else
API.service.oab.mail({vars:vars,template:{filename:'author_request_article_v2_nostory.html'},to:r.email})
else if r.email
API.service.oab.mail({vars:vars,template:{filename:'author_request_data_v2.html'},to:r.email})
else if action is 'story_too_bad'
update.status = 'help'
update.rating = 0
API.service.oab.mail({vars:vars,template:{filename:'initiator_poorstory.html'},to:requestors}) if requestors.length
API.service.oab.mail({vars:vars,template:{filename:'author_request_article_v2_nostory.html'},to:r.email}) if r.email
else if action is 'not_a_scholarly_article'
update.status = 'closed'
API.service.oab.mail({vars:vars,template:{filename:'initiator_invalid.html'},to:usermail}) if usermail
else if action is 'dead_author'
update.status = 'closed'
API.service.oab.mail({vars:vars,template:{filename:'requesters_request_failed_authordeath.html'},to:requestors}) if requestors.length
else if action is 'user_testing'
update.test = true
update.status = 'closed'
update.rating = 0 if r.story
API.service.oab.mail({vars:vars,template:{filename:'initiator_testing.html'},to:usermail}) if usermail
else if action is 'broken_link' and usermail
API.service.oab.mail({vars:vars,template:{filename:'initiator_brokenlink.html'},to:usermail})
update.status = 'closed'
else if action is 'remove_submitted_url'
update.status = 'moderate'
update.received = false
else if action is 'article_before_2000'
API.service.oab.mail({vars:vars,template:{filename:'article_before_2000.html'},to:requestors}) if requestors.length
update.status = 'closed'
else if action is 'author_email_not_found'
API.service.oab.mail({vars:vars,template:{filename:'author_email_not_found.html'},to:requestors}) if requestors.length
update.status = 'closed'
else if action is 'link_by_author'
API.service.oab.mail({vars:vars,template:{filename:'authors_thanks_article.html'},to:r.email}) if r.email
API.service.oab.mail({vars:vars,template:{filename:'requestors_request_success_article.html'},to:requestors}) if requestors.length
update.status = 'received'
else if action is 'link_by_admin'
API.service.oab.mail({vars:vars,template:{filename:'requestors_request_success_article.html'},to:requestors}) if requestors.length
update.status = 'received'
oab_request.update(rid,update) if JSON.stringify(update) isnt '{}'
# LIVE: https://docs.google.com/spreadsheets/d/1Te9zcQtBLq2Vx81JUE9R42fjptFGXY6jybXBCt85dcs/edit#gid=0
# Develop: https://docs.google.com/spreadsheets/d/1AaY7hS0D9jtLgVsGO4cJuLn_-CzNQg0yCreC3PP3UU0/edit#gid=0
API.service.oab.redirect = (url,refresh=false) ->
API.log msg: 'Checking OAB open list', url: url
url = API.http.resolve url, refresh # will return undefined if the url doesn't resolve at all
if url
return false if API.service.oab.blacklist(url) is true # ignore anything on the usual URL blacklist
list = API.use.google.sheets.feed API.settings.service.openaccessbutton?.google?.sheets?.redirect, 360000
for listing in list
if listing.redirect and url.replace('http://','').replace('https://','').split('#')[0] is listing.redirect.replace('http://','').replace('https://','').split('#')[0]
# we have an exact alternative for this url
return listing.redirect
else if typeof url is 'string' and url.indexOf(listing.domain.replace('http://','').replace('https://','').split('/')[0]) isnt -1
url = url.replace('http://','https://') if listing.domain.indexOf('https://') is 0
listing.domain = listing.domain.replace('http://','https://') if url.indexOf('https://') is 0
if (listing.fulltext and listing.splash and listing.identifier) or listing.element
source = url
if listing.fulltext
# switch the url by comparing the fulltext and splash examples, and converting the url in the same way
parts = listing.splash.split listing.identifier
if url.indexOf(parts[0]) is 0 # can only successfully replace if the incoming url starts with the same as the start of the splash url
diff = url.replace parts[0], ''
diff = diff.replace(parts[1],'') if parts.length > 1
url = listing.fulltext.replace listing.identifier, diff
else if listing.element and url.indexOf('.pdf') is -1
try
content = API.http.puppeteer url
url = content.toLowerCase().split(listing.element.toLowerCase())[1].split('"')[0].split("'")[0].split('>')[0]
return false if (not url? or url.length < 6 or url is source) and listing.blacklist is "yes"
# fulltext or element can possibly give us a url which then redirects to a login wall
# so we have to check the given url against the whole sheet listing again for the login wall
# so this allows the rest of the listing to be checked before returning - MAKE SURE loginwall fragments are at the end of the sheet
resv = API.http.resolve url # resolve it again to make sure whatever we have now is accessible
url = resv if typeof resv is 'string'
else if listing.loginwall and url.indexOf(listing.loginwall.replace('http://','').replace('https://','')) isnt -1
# this url is on the login wall of the repo in question, so it is no use
return false
else if listing.blacklist is "yes"
return false
if typeof url is 'string'
# some URLs can be confirmed as resolvable but we also hit a captcha response and end up serving that to the user
# we want to avoid that, so when such URLs appear to be found here, just return true instead, which will cause
# us to accept the original URL
# we introduced this because of issue https://github.com/OAButton/discussion/issues/1257
# and for example https://www.tandfonline.com/doi/pdf/10.1080/17521740701702115?needAccess=true
# ends up as https://www.tandfonline.com/action/captchaChallenge?redirectUri=%2Fdoi%2Fpdf%2F10.1080%2F17521740701702115%3FneedAccess%3Dtrue
for avoid in ['captcha','challenge']
return undefined if url.toLowerCase().indexOf(avoid) isnt -1
return url
|
[
{
"context": "#\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 - Studionet\n#\n# Permission is hereby granted, free of ",
"end": 55,
"score": 0.5654720067977905,
"start": 53,
"tag": "USERNAME",
"value": "St"
},
{
"context": " The MIT License (MIT)\n#\n# Copyright (c) 2015 - Studionet\n#\n# Permission is hereby granted, free of charge,",
"end": 62,
"score": 0.5034335255622864,
"start": 55,
"tag": "NAME",
"value": "udionet"
}
] | sources/coffee/tags-input.coffee | studio-net/tags-input | 3 | ###
# The MIT License (MIT)
#
# Copyright (c) 2015 - Studionet
#
# 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.
###
window.Tag = class Tag
element : null
options : null
deleted : false
terms : null # Represents the terms container
requestInstances : []
defaultOptions :
tooltip : true
tooltipText : "Right click to delete"
formSeparator : ","
nextTagCodes : [13, 188, 9] # ENTER, COMMA and TAB
autocomplete : null
autofield : "value"
automin : 3
autolimit : 5
placeholder : null
constructor : (@element, @options) ->
that = @
# Construct options
@options = @configureOptions()
# Create the real container of all tags
@container = document.createElement "ul"
placeholder = @createPlaceHolder()
# Insert it just after the @element
@element.parentNode.insertBefore @container, @element.nextSibling
@container.style.position = "relative"
@container.style.left = 0
@container.style.height = "auto"
@container.style.minHeight = @element.offsetHeight + "px"
@container.classList.add "tag-input"
@container.classList.add "container"
# On container click, add a new tag
@container.addEventListener "click", (event) ->
if event.target isnt that.container
return
that.createTag()
@container.addEventListener "DOMNodeInserted", (event) ->
placeholder = document.querySelector ".tag-input > .placeholder"
return if event.target is placeholder
if placeholder and that.container.children.length > 1
placeholder.remove()
return
@container.addEventListener "DOMNodeRemoved", (event) ->
if that.container.childNodes.length - 1 is 0
that.createPlaceHolder()
return
# Prevent from content editable focus on container click
@container.addEventListener "mousedown", (event) ->
if event.target isnt that.container
return
event.preventDefault()
# Get existing values
tags = @element.getAttribute "value"
return if not tags
for tag in tags.split @options.formSeparator
@createTag tag
# Blur the last tag
@container.lastChild.firstChild.blur()
configureOptions : () ->
options = @defaultOptions
if typeof(@options) isnt 'object'
return options
for key, property of @options
if options[key] is 'undefined'
throw "`#{key}` option doesn't exist"
options[key] = property
return options
createPlaceHolder : ->
if @options.placeholder
placeholder = document.createElement "span"
placeholder.innerHTML = @options.placeholder
placeholder.classList.add "placeholder"
@container.appendChild placeholder
return placeholder
return null
createTag : (value) ->
that = @
# Create a container of our tag
tag = document.createElement "li"
tag.classList.add "tag-input"
tag.classList.add "tag"
# Create the content of the new tag
content = document.createElement "span"
content.classList.add "tag-content"
content.contentEditable = true
content.innerHTML = value if value
# Append the content into the tag and the whole into the global
# container
tag.appendChild content
@container.appendChild tag
if @options.tooltip
# Create tooltip
tooltip = document.createElement "span"
tooltip.classList.add "tag-tooltip"
tooltip.innerHTML = @options.tooltipText
tag.appendChild tooltip
# Let's create a focus into the newer tag
@createFocus tag
tag.firstChild.addEventListener "blur", ->
# Remove on empty content
if not @innerHTML
@parentNode.remove()
return
sessionStorage.removeItem "tags-input-autocomplete"
that.fillInput()
# When the user press some keys, we need to prevent from default
# For example, when a user press ENTER key, we don't want the submitting
# form, we just need create a new tag
tag.addEventListener "keydown", (event) ->
# On ENTER key or COMMA key
if event.keyCode in that.options.nextTagCodes
event.preventDefault()
value = sessionStorage.getItem "tags-input-autocomplete"
@firstChild.innerHTML = value if value
# Prevent from multiple creations and suppressions
if @firstChild.innerHTML
that.createTag()
return false
sessionStorage.removeItem "tags-input-autocomplete"
# On content editable change
tag.firstChild.addEventListener "input", (event) ->
min = that.options.automin
sessionStorage.setItem "tags-input-value", @innerHTML
range = window.getSelection().getRangeAt 0
that.clearRequests()
return if not that.options.autocomplete
return if @innerHTML.length < min
return if range.startOffset isnt @innerHTML.length
clearTimeout that.timer
that.requestTerm @parentNode
# Delete a tag on right click on it
tag.addEventListener "contextmenu", (event) ->
@remove()
that.fillInput()
event.preventDefault()
return false
createFocus : (tag) ->
@terms.remove() if @terms
@terms = null
tag.firstChild.focus()
requestTerm : (tag) ->
that = @
value = tag.firstChild.innerHTML
permalink = @options.autocomplete.replace "%search%", value
request = new XMLHttpRequest()
request.open "GET", permalink, true
request.addEventListener "readystatechange", (event) ->
response = event.target
return if response.readyState isnt 4
return if response.status isnt 200
data = JSON.parse response.responseText
terms = that.autocomplete data, value
# Show all terms
that.showTerms terms, tag
request.send null
@requestInstances.push request
clearRequests : ->
# Abort all existing instances of XMLHttpRequest
if @requestInstances.length > 0
for instance in @requestInstances
instance.abort()
@requestInstances.slice @requestInstances.indexOf(instance), 1
searchTerm : (value, search) ->
list = []
for key, term of value
if term instanceof Object
found = @searchTerm term, search
list = list.concat found if found.length
continue if key isnt @options.autofield
list = list.concat term
return list
autocomplete : (values, search) ->
return if not values or not search
terms = []
for key, value of values
continue if value not instanceof Array
terms = terms.concat @searchTerm(value, search)
return terms.slice 0, @options.autolimit
showTerms : (terms, tag) ->
that = @
if not @terms
@terms = document.createElement "div"
@terms.classList.add "tag-input"
@terms.classList.add "terms"
@container.appendChild @terms
# Remove all childs (faster way) if we're on the same tag
while @terms.firstChild
@terms.removeChild @terms.firstChild
for term in terms
node = document.createElement "div"
node.classList.add "tag-input"
node.classList.add "link-term"
node.innerHTML = term
node.addEventListener "click", (event) ->
# Replace tag with new value
tag.firstChild.innerHTML = event.target.innerHTML
# Remove the terms container
that.terms.remove()
that.terms = null
@terms.appendChild node
fillInput : ->
# Fill the given input (element) with tags
tags = @container.childNodes
content = []
for tag in tags
content.push tag.firstChild.innerHTML
@element.setAttribute "value", content.join @options.formSeparator
@guess : (elements, options) ->
# As the class Tag represent an input, we need a guess function to allow
# user fetching multiple inputs
for element in elements
new Tag element, options
| 7155 | ###
# The MIT License (MIT)
#
# Copyright (c) 2015 - St<NAME>
#
# 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.
###
window.Tag = class Tag
element : null
options : null
deleted : false
terms : null # Represents the terms container
requestInstances : []
defaultOptions :
tooltip : true
tooltipText : "Right click to delete"
formSeparator : ","
nextTagCodes : [13, 188, 9] # ENTER, COMMA and TAB
autocomplete : null
autofield : "value"
automin : 3
autolimit : 5
placeholder : null
constructor : (@element, @options) ->
that = @
# Construct options
@options = @configureOptions()
# Create the real container of all tags
@container = document.createElement "ul"
placeholder = @createPlaceHolder()
# Insert it just after the @element
@element.parentNode.insertBefore @container, @element.nextSibling
@container.style.position = "relative"
@container.style.left = 0
@container.style.height = "auto"
@container.style.minHeight = @element.offsetHeight + "px"
@container.classList.add "tag-input"
@container.classList.add "container"
# On container click, add a new tag
@container.addEventListener "click", (event) ->
if event.target isnt that.container
return
that.createTag()
@container.addEventListener "DOMNodeInserted", (event) ->
placeholder = document.querySelector ".tag-input > .placeholder"
return if event.target is placeholder
if placeholder and that.container.children.length > 1
placeholder.remove()
return
@container.addEventListener "DOMNodeRemoved", (event) ->
if that.container.childNodes.length - 1 is 0
that.createPlaceHolder()
return
# Prevent from content editable focus on container click
@container.addEventListener "mousedown", (event) ->
if event.target isnt that.container
return
event.preventDefault()
# Get existing values
tags = @element.getAttribute "value"
return if not tags
for tag in tags.split @options.formSeparator
@createTag tag
# Blur the last tag
@container.lastChild.firstChild.blur()
configureOptions : () ->
options = @defaultOptions
if typeof(@options) isnt 'object'
return options
for key, property of @options
if options[key] is 'undefined'
throw "`#{key}` option doesn't exist"
options[key] = property
return options
createPlaceHolder : ->
if @options.placeholder
placeholder = document.createElement "span"
placeholder.innerHTML = @options.placeholder
placeholder.classList.add "placeholder"
@container.appendChild placeholder
return placeholder
return null
createTag : (value) ->
that = @
# Create a container of our tag
tag = document.createElement "li"
tag.classList.add "tag-input"
tag.classList.add "tag"
# Create the content of the new tag
content = document.createElement "span"
content.classList.add "tag-content"
content.contentEditable = true
content.innerHTML = value if value
# Append the content into the tag and the whole into the global
# container
tag.appendChild content
@container.appendChild tag
if @options.tooltip
# Create tooltip
tooltip = document.createElement "span"
tooltip.classList.add "tag-tooltip"
tooltip.innerHTML = @options.tooltipText
tag.appendChild tooltip
# Let's create a focus into the newer tag
@createFocus tag
tag.firstChild.addEventListener "blur", ->
# Remove on empty content
if not @innerHTML
@parentNode.remove()
return
sessionStorage.removeItem "tags-input-autocomplete"
that.fillInput()
# When the user press some keys, we need to prevent from default
# For example, when a user press ENTER key, we don't want the submitting
# form, we just need create a new tag
tag.addEventListener "keydown", (event) ->
# On ENTER key or COMMA key
if event.keyCode in that.options.nextTagCodes
event.preventDefault()
value = sessionStorage.getItem "tags-input-autocomplete"
@firstChild.innerHTML = value if value
# Prevent from multiple creations and suppressions
if @firstChild.innerHTML
that.createTag()
return false
sessionStorage.removeItem "tags-input-autocomplete"
# On content editable change
tag.firstChild.addEventListener "input", (event) ->
min = that.options.automin
sessionStorage.setItem "tags-input-value", @innerHTML
range = window.getSelection().getRangeAt 0
that.clearRequests()
return if not that.options.autocomplete
return if @innerHTML.length < min
return if range.startOffset isnt @innerHTML.length
clearTimeout that.timer
that.requestTerm @parentNode
# Delete a tag on right click on it
tag.addEventListener "contextmenu", (event) ->
@remove()
that.fillInput()
event.preventDefault()
return false
createFocus : (tag) ->
@terms.remove() if @terms
@terms = null
tag.firstChild.focus()
requestTerm : (tag) ->
that = @
value = tag.firstChild.innerHTML
permalink = @options.autocomplete.replace "%search%", value
request = new XMLHttpRequest()
request.open "GET", permalink, true
request.addEventListener "readystatechange", (event) ->
response = event.target
return if response.readyState isnt 4
return if response.status isnt 200
data = JSON.parse response.responseText
terms = that.autocomplete data, value
# Show all terms
that.showTerms terms, tag
request.send null
@requestInstances.push request
clearRequests : ->
# Abort all existing instances of XMLHttpRequest
if @requestInstances.length > 0
for instance in @requestInstances
instance.abort()
@requestInstances.slice @requestInstances.indexOf(instance), 1
searchTerm : (value, search) ->
list = []
for key, term of value
if term instanceof Object
found = @searchTerm term, search
list = list.concat found if found.length
continue if key isnt @options.autofield
list = list.concat term
return list
autocomplete : (values, search) ->
return if not values or not search
terms = []
for key, value of values
continue if value not instanceof Array
terms = terms.concat @searchTerm(value, search)
return terms.slice 0, @options.autolimit
showTerms : (terms, tag) ->
that = @
if not @terms
@terms = document.createElement "div"
@terms.classList.add "tag-input"
@terms.classList.add "terms"
@container.appendChild @terms
# Remove all childs (faster way) if we're on the same tag
while @terms.firstChild
@terms.removeChild @terms.firstChild
for term in terms
node = document.createElement "div"
node.classList.add "tag-input"
node.classList.add "link-term"
node.innerHTML = term
node.addEventListener "click", (event) ->
# Replace tag with new value
tag.firstChild.innerHTML = event.target.innerHTML
# Remove the terms container
that.terms.remove()
that.terms = null
@terms.appendChild node
fillInput : ->
# Fill the given input (element) with tags
tags = @container.childNodes
content = []
for tag in tags
content.push tag.firstChild.innerHTML
@element.setAttribute "value", content.join @options.formSeparator
@guess : (elements, options) ->
# As the class Tag represent an input, we need a guess function to allow
# user fetching multiple inputs
for element in elements
new Tag element, options
| true | ###
# The MIT License (MIT)
#
# Copyright (c) 2015 - StPI:NAME:<NAME>END_PI
#
# 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.
###
window.Tag = class Tag
element : null
options : null
deleted : false
terms : null # Represents the terms container
requestInstances : []
defaultOptions :
tooltip : true
tooltipText : "Right click to delete"
formSeparator : ","
nextTagCodes : [13, 188, 9] # ENTER, COMMA and TAB
autocomplete : null
autofield : "value"
automin : 3
autolimit : 5
placeholder : null
constructor : (@element, @options) ->
that = @
# Construct options
@options = @configureOptions()
# Create the real container of all tags
@container = document.createElement "ul"
placeholder = @createPlaceHolder()
# Insert it just after the @element
@element.parentNode.insertBefore @container, @element.nextSibling
@container.style.position = "relative"
@container.style.left = 0
@container.style.height = "auto"
@container.style.minHeight = @element.offsetHeight + "px"
@container.classList.add "tag-input"
@container.classList.add "container"
# On container click, add a new tag
@container.addEventListener "click", (event) ->
if event.target isnt that.container
return
that.createTag()
@container.addEventListener "DOMNodeInserted", (event) ->
placeholder = document.querySelector ".tag-input > .placeholder"
return if event.target is placeholder
if placeholder and that.container.children.length > 1
placeholder.remove()
return
@container.addEventListener "DOMNodeRemoved", (event) ->
if that.container.childNodes.length - 1 is 0
that.createPlaceHolder()
return
# Prevent from content editable focus on container click
@container.addEventListener "mousedown", (event) ->
if event.target isnt that.container
return
event.preventDefault()
# Get existing values
tags = @element.getAttribute "value"
return if not tags
for tag in tags.split @options.formSeparator
@createTag tag
# Blur the last tag
@container.lastChild.firstChild.blur()
configureOptions : () ->
options = @defaultOptions
if typeof(@options) isnt 'object'
return options
for key, property of @options
if options[key] is 'undefined'
throw "`#{key}` option doesn't exist"
options[key] = property
return options
createPlaceHolder : ->
if @options.placeholder
placeholder = document.createElement "span"
placeholder.innerHTML = @options.placeholder
placeholder.classList.add "placeholder"
@container.appendChild placeholder
return placeholder
return null
createTag : (value) ->
that = @
# Create a container of our tag
tag = document.createElement "li"
tag.classList.add "tag-input"
tag.classList.add "tag"
# Create the content of the new tag
content = document.createElement "span"
content.classList.add "tag-content"
content.contentEditable = true
content.innerHTML = value if value
# Append the content into the tag and the whole into the global
# container
tag.appendChild content
@container.appendChild tag
if @options.tooltip
# Create tooltip
tooltip = document.createElement "span"
tooltip.classList.add "tag-tooltip"
tooltip.innerHTML = @options.tooltipText
tag.appendChild tooltip
# Let's create a focus into the newer tag
@createFocus tag
tag.firstChild.addEventListener "blur", ->
# Remove on empty content
if not @innerHTML
@parentNode.remove()
return
sessionStorage.removeItem "tags-input-autocomplete"
that.fillInput()
# When the user press some keys, we need to prevent from default
# For example, when a user press ENTER key, we don't want the submitting
# form, we just need create a new tag
tag.addEventListener "keydown", (event) ->
# On ENTER key or COMMA key
if event.keyCode in that.options.nextTagCodes
event.preventDefault()
value = sessionStorage.getItem "tags-input-autocomplete"
@firstChild.innerHTML = value if value
# Prevent from multiple creations and suppressions
if @firstChild.innerHTML
that.createTag()
return false
sessionStorage.removeItem "tags-input-autocomplete"
# On content editable change
tag.firstChild.addEventListener "input", (event) ->
min = that.options.automin
sessionStorage.setItem "tags-input-value", @innerHTML
range = window.getSelection().getRangeAt 0
that.clearRequests()
return if not that.options.autocomplete
return if @innerHTML.length < min
return if range.startOffset isnt @innerHTML.length
clearTimeout that.timer
that.requestTerm @parentNode
# Delete a tag on right click on it
tag.addEventListener "contextmenu", (event) ->
@remove()
that.fillInput()
event.preventDefault()
return false
createFocus : (tag) ->
@terms.remove() if @terms
@terms = null
tag.firstChild.focus()
requestTerm : (tag) ->
that = @
value = tag.firstChild.innerHTML
permalink = @options.autocomplete.replace "%search%", value
request = new XMLHttpRequest()
request.open "GET", permalink, true
request.addEventListener "readystatechange", (event) ->
response = event.target
return if response.readyState isnt 4
return if response.status isnt 200
data = JSON.parse response.responseText
terms = that.autocomplete data, value
# Show all terms
that.showTerms terms, tag
request.send null
@requestInstances.push request
clearRequests : ->
# Abort all existing instances of XMLHttpRequest
if @requestInstances.length > 0
for instance in @requestInstances
instance.abort()
@requestInstances.slice @requestInstances.indexOf(instance), 1
searchTerm : (value, search) ->
list = []
for key, term of value
if term instanceof Object
found = @searchTerm term, search
list = list.concat found if found.length
continue if key isnt @options.autofield
list = list.concat term
return list
autocomplete : (values, search) ->
return if not values or not search
terms = []
for key, value of values
continue if value not instanceof Array
terms = terms.concat @searchTerm(value, search)
return terms.slice 0, @options.autolimit
showTerms : (terms, tag) ->
that = @
if not @terms
@terms = document.createElement "div"
@terms.classList.add "tag-input"
@terms.classList.add "terms"
@container.appendChild @terms
# Remove all childs (faster way) if we're on the same tag
while @terms.firstChild
@terms.removeChild @terms.firstChild
for term in terms
node = document.createElement "div"
node.classList.add "tag-input"
node.classList.add "link-term"
node.innerHTML = term
node.addEventListener "click", (event) ->
# Replace tag with new value
tag.firstChild.innerHTML = event.target.innerHTML
# Remove the terms container
that.terms.remove()
that.terms = null
@terms.appendChild node
fillInput : ->
# Fill the given input (element) with tags
tags = @container.childNodes
content = []
for tag in tags
content.push tag.firstChild.innerHTML
@element.setAttribute "value", content.join @options.formSeparator
@guess : (elements, options) ->
# As the class Tag represent an input, we need a guess function to allow
# user fetching multiple inputs
for element in elements
new Tag element, options
|
[
{
"context": " at Bob and observer whether they\n # propagate to Alice as a remote ref with Bob's peer name (not Bob's p",
"end": 1740,
"score": 0.7694295048713684,
"start": 1735,
"tag": "NAME",
"value": "Alice"
},
{
"context": "r they\n # propagate to Alice as a remote ref with Bob's peer name (not Bob's peer\n # username).\n\n it ",
"end": 1765,
"score": 0.7102288603782654,
"start": 1762,
"tag": "NAME",
"value": "Bob"
},
{
"context": "to Alice as a remote ref with Bob's peer name (not Bob's peer\n # username).\n\n it 'connectRemotes() sta",
"end": 1786,
"score": 0.5140020847320557,
"start": 1783,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ceMain.syncStore.snapshot euid, {\n ownerName: aliceOwner\n synchroName: 'all'\n }\n expect(status)",
"end": 3959,
"score": 0.999294638633728,
"start": 3949,
"tag": "USERNAME",
"value": "aliceOwner"
}
] | packages/nog-sync/nog-sync-peer-sync-tests.coffee | nogproject/nog | 0 | { createTestPeers } = require './nog-sync-peer-tests.coffee'
{ createContentFaker } = require './nog-sync-store-tests.coffee'
NULL_SHA1 = '0000000000000000000000000000000000000000'
describe 'nog-sync', ->
peers = null
euid = null
aliceOwner = null
AliceMain = null
BobMain = null
rndBob = null
contentFaker = null
before ->
peers = createTestPeers()
aliceOwner = peers.aliceOwner
AliceMain = peers.AliceMain
BobMain = peers.BobMain
rndBob = peers.rndBob
AliceMain.ensureSyncUsers()
AliceMain.ensureMainSynchro euid
BobMain.ensureSyncUsers()
BobMain.ensureMainSynchro euid
contentFaker = createContentFaker()
after ->
peers.cleanup()
contentFaker.cleanup()
it 'startMainSynchro() starts interval snapshots', (done) ->
synchros = AliceMain.syncStore.synchros
sel = {owner: aliceOwner, name: 'all'}
fields = {}
fields['refs.branches/master'] = 1
obs = synchros.find(sel, {fields}).observe {
changed: (doc) ->
obs.stop()
AliceMain.stopMainSynchro euid
done()
}
AliceMain.startMainSynchro euid
expectAliceFetchesBob = (done) ->
synchros = AliceMain.syncStore.synchros
sel = {owner: aliceOwner, name: 'all'}
fields = {}
refName = "remotes/#{rndBob}/branches/master"
fields["refs.#{refName}"] = 1
obs = synchros.find(sel, {fields}).observeChanges {
changed: (id, doc) ->
unless (sha = doc.refs?[refName])? and sha != NULL_SHA1
return
obs.stop()
BobMain.stopMainSynchro euid
AliceMain.disconnectRemotes euid
done()
}
# Connect Alice to Bob, then start snapshots at Bob and observer whether they
# propagate to Alice as a remote ref with Bob's peer name (not Bob's peer
# username).
it 'connectRemotes() starts fetching remote', (done) ->
expectAliceFetchesBob done
AliceMain.connectRemotes euid
BobMain.startMainSynchro euid
it 'remote fetches repo updates', (done) ->
@timeout(3000)
contentFaker.insertFakeUsers {users: Meteor.users}
expectAliceFetchesBob ->
# Test that method access has been checked.
expect(peers.bobOpts.checkAccess).to.have.been.calledWith(
null, 'nog-sync/get'
)
# Test that publish access has been checked.
expect(peers.bobOpts.testAccess).to.have.been.calledWith(
null, 'nog-sync/get'
)
done()
BobMain.startMainSynchro euid
contentFaker.createFakeContent {
store: peers.bobOpts.contentStore
}
Meteor._sleepForMs 150
contentFaker.commitFakeContent()
Meteor._sleepForMs 150
contentFaker.commitFakeContent()
Meteor._sleepForMs 150
peers.aliceOpts.checkAccess.reset()
peers.aliceOpts.testAccess.reset()
AliceMain.connectRemotes euid
getAliceRemoteMaster = ->
synchro = AliceMain.syncStore.synchros.findOne { name: 'all' }
return synchro.refs["remotes/#{rndBob}/branches/master"]
# A partial apply could cause inconsistent state. Some repo masters may have
# been updated before apply got interrupted. If a later pull fetched and
# merged before completing the interrupted apply, the master for the
# already-updated repos would not match the base, causing spurious conflicts;
# similarly for snapshots.
it 'interrupted apply blocks fetch and snapshot', ->
BobMain.startMainSynchro euid
contentFaker.createFakeContent {
store: peers.bobOpts.contentStore
}
# Force fake error.
AliceMain.syncStore._testingApplyErrorProb = 1
AliceMain.connectRemotes euid
Meteor._sleepForMs 200
oldRef = getAliceRemoteMaster()
# Trigger change, which is not fetched.
contentFaker.commitFakeContent()
Meteor._sleepForMs 200
expect(getAliceRemoteMaster()).to.be.eql oldRef
# Snapshots are refused with a pending apply.
{ status } = AliceMain.syncStore.snapshot euid, {
ownerName: aliceOwner
synchroName: 'all'
}
expect(status).to.eql 'refused'
# Clear fake error to allow recovery.
AliceMain.syncStore._testingApplyErrorProb = 0
# Trigger pull that skips fetch and restarts apply.
contentFaker.commitFakeContent()
Meteor._sleepForMs 200
# Trigger another pull that fetches, since apply has completed.
contentFaker.commitFakeContent()
Meteor._sleepForMs 500
expect(getAliceRemoteMaster()).to.be.not.eql oldRef
AliceMain.disconnectRemotes euid
BobMain.stopMainSynchro euid
# NULL_SHA1s are ignored during fetch; similar to git fetch, which requires
# an explicit prune before it deletes refs that disappeared at the remote.
it 'remote fetch ignores remote NULL_SHA1 synchro master', ->
oldRef = getAliceRemoteMaster()
$set = {}
$set['refs.branches/master'] = NULL_SHA1
BobMain.syncStore.synchros.update { name: 'all' }, { $set }
AliceMain.connectRemotes euid
Meteor._sleepForMs 200
expect(getAliceRemoteMaster()).to.be.eql oldRef
AliceMain.disconnectRemotes euid
| 104368 | { createTestPeers } = require './nog-sync-peer-tests.coffee'
{ createContentFaker } = require './nog-sync-store-tests.coffee'
NULL_SHA1 = '0000000000000000000000000000000000000000'
describe 'nog-sync', ->
peers = null
euid = null
aliceOwner = null
AliceMain = null
BobMain = null
rndBob = null
contentFaker = null
before ->
peers = createTestPeers()
aliceOwner = peers.aliceOwner
AliceMain = peers.AliceMain
BobMain = peers.BobMain
rndBob = peers.rndBob
AliceMain.ensureSyncUsers()
AliceMain.ensureMainSynchro euid
BobMain.ensureSyncUsers()
BobMain.ensureMainSynchro euid
contentFaker = createContentFaker()
after ->
peers.cleanup()
contentFaker.cleanup()
it 'startMainSynchro() starts interval snapshots', (done) ->
synchros = AliceMain.syncStore.synchros
sel = {owner: aliceOwner, name: 'all'}
fields = {}
fields['refs.branches/master'] = 1
obs = synchros.find(sel, {fields}).observe {
changed: (doc) ->
obs.stop()
AliceMain.stopMainSynchro euid
done()
}
AliceMain.startMainSynchro euid
expectAliceFetchesBob = (done) ->
synchros = AliceMain.syncStore.synchros
sel = {owner: aliceOwner, name: 'all'}
fields = {}
refName = "remotes/#{rndBob}/branches/master"
fields["refs.#{refName}"] = 1
obs = synchros.find(sel, {fields}).observeChanges {
changed: (id, doc) ->
unless (sha = doc.refs?[refName])? and sha != NULL_SHA1
return
obs.stop()
BobMain.stopMainSynchro euid
AliceMain.disconnectRemotes euid
done()
}
# Connect Alice to Bob, then start snapshots at Bob and observer whether they
# propagate to <NAME> as a remote ref with <NAME>'s peer name (not <NAME>'s peer
# username).
it 'connectRemotes() starts fetching remote', (done) ->
expectAliceFetchesBob done
AliceMain.connectRemotes euid
BobMain.startMainSynchro euid
it 'remote fetches repo updates', (done) ->
@timeout(3000)
contentFaker.insertFakeUsers {users: Meteor.users}
expectAliceFetchesBob ->
# Test that method access has been checked.
expect(peers.bobOpts.checkAccess).to.have.been.calledWith(
null, 'nog-sync/get'
)
# Test that publish access has been checked.
expect(peers.bobOpts.testAccess).to.have.been.calledWith(
null, 'nog-sync/get'
)
done()
BobMain.startMainSynchro euid
contentFaker.createFakeContent {
store: peers.bobOpts.contentStore
}
Meteor._sleepForMs 150
contentFaker.commitFakeContent()
Meteor._sleepForMs 150
contentFaker.commitFakeContent()
Meteor._sleepForMs 150
peers.aliceOpts.checkAccess.reset()
peers.aliceOpts.testAccess.reset()
AliceMain.connectRemotes euid
getAliceRemoteMaster = ->
synchro = AliceMain.syncStore.synchros.findOne { name: 'all' }
return synchro.refs["remotes/#{rndBob}/branches/master"]
# A partial apply could cause inconsistent state. Some repo masters may have
# been updated before apply got interrupted. If a later pull fetched and
# merged before completing the interrupted apply, the master for the
# already-updated repos would not match the base, causing spurious conflicts;
# similarly for snapshots.
it 'interrupted apply blocks fetch and snapshot', ->
BobMain.startMainSynchro euid
contentFaker.createFakeContent {
store: peers.bobOpts.contentStore
}
# Force fake error.
AliceMain.syncStore._testingApplyErrorProb = 1
AliceMain.connectRemotes euid
Meteor._sleepForMs 200
oldRef = getAliceRemoteMaster()
# Trigger change, which is not fetched.
contentFaker.commitFakeContent()
Meteor._sleepForMs 200
expect(getAliceRemoteMaster()).to.be.eql oldRef
# Snapshots are refused with a pending apply.
{ status } = AliceMain.syncStore.snapshot euid, {
ownerName: aliceOwner
synchroName: 'all'
}
expect(status).to.eql 'refused'
# Clear fake error to allow recovery.
AliceMain.syncStore._testingApplyErrorProb = 0
# Trigger pull that skips fetch and restarts apply.
contentFaker.commitFakeContent()
Meteor._sleepForMs 200
# Trigger another pull that fetches, since apply has completed.
contentFaker.commitFakeContent()
Meteor._sleepForMs 500
expect(getAliceRemoteMaster()).to.be.not.eql oldRef
AliceMain.disconnectRemotes euid
BobMain.stopMainSynchro euid
# NULL_SHA1s are ignored during fetch; similar to git fetch, which requires
# an explicit prune before it deletes refs that disappeared at the remote.
it 'remote fetch ignores remote NULL_SHA1 synchro master', ->
oldRef = getAliceRemoteMaster()
$set = {}
$set['refs.branches/master'] = NULL_SHA1
BobMain.syncStore.synchros.update { name: 'all' }, { $set }
AliceMain.connectRemotes euid
Meteor._sleepForMs 200
expect(getAliceRemoteMaster()).to.be.eql oldRef
AliceMain.disconnectRemotes euid
| true | { createTestPeers } = require './nog-sync-peer-tests.coffee'
{ createContentFaker } = require './nog-sync-store-tests.coffee'
NULL_SHA1 = '0000000000000000000000000000000000000000'
describe 'nog-sync', ->
peers = null
euid = null
aliceOwner = null
AliceMain = null
BobMain = null
rndBob = null
contentFaker = null
before ->
peers = createTestPeers()
aliceOwner = peers.aliceOwner
AliceMain = peers.AliceMain
BobMain = peers.BobMain
rndBob = peers.rndBob
AliceMain.ensureSyncUsers()
AliceMain.ensureMainSynchro euid
BobMain.ensureSyncUsers()
BobMain.ensureMainSynchro euid
contentFaker = createContentFaker()
after ->
peers.cleanup()
contentFaker.cleanup()
it 'startMainSynchro() starts interval snapshots', (done) ->
synchros = AliceMain.syncStore.synchros
sel = {owner: aliceOwner, name: 'all'}
fields = {}
fields['refs.branches/master'] = 1
obs = synchros.find(sel, {fields}).observe {
changed: (doc) ->
obs.stop()
AliceMain.stopMainSynchro euid
done()
}
AliceMain.startMainSynchro euid
expectAliceFetchesBob = (done) ->
synchros = AliceMain.syncStore.synchros
sel = {owner: aliceOwner, name: 'all'}
fields = {}
refName = "remotes/#{rndBob}/branches/master"
fields["refs.#{refName}"] = 1
obs = synchros.find(sel, {fields}).observeChanges {
changed: (id, doc) ->
unless (sha = doc.refs?[refName])? and sha != NULL_SHA1
return
obs.stop()
BobMain.stopMainSynchro euid
AliceMain.disconnectRemotes euid
done()
}
# Connect Alice to Bob, then start snapshots at Bob and observer whether they
# propagate to PI:NAME:<NAME>END_PI as a remote ref with PI:NAME:<NAME>END_PI's peer name (not PI:NAME:<NAME>END_PI's peer
# username).
it 'connectRemotes() starts fetching remote', (done) ->
expectAliceFetchesBob done
AliceMain.connectRemotes euid
BobMain.startMainSynchro euid
it 'remote fetches repo updates', (done) ->
@timeout(3000)
contentFaker.insertFakeUsers {users: Meteor.users}
expectAliceFetchesBob ->
# Test that method access has been checked.
expect(peers.bobOpts.checkAccess).to.have.been.calledWith(
null, 'nog-sync/get'
)
# Test that publish access has been checked.
expect(peers.bobOpts.testAccess).to.have.been.calledWith(
null, 'nog-sync/get'
)
done()
BobMain.startMainSynchro euid
contentFaker.createFakeContent {
store: peers.bobOpts.contentStore
}
Meteor._sleepForMs 150
contentFaker.commitFakeContent()
Meteor._sleepForMs 150
contentFaker.commitFakeContent()
Meteor._sleepForMs 150
peers.aliceOpts.checkAccess.reset()
peers.aliceOpts.testAccess.reset()
AliceMain.connectRemotes euid
getAliceRemoteMaster = ->
synchro = AliceMain.syncStore.synchros.findOne { name: 'all' }
return synchro.refs["remotes/#{rndBob}/branches/master"]
# A partial apply could cause inconsistent state. Some repo masters may have
# been updated before apply got interrupted. If a later pull fetched and
# merged before completing the interrupted apply, the master for the
# already-updated repos would not match the base, causing spurious conflicts;
# similarly for snapshots.
it 'interrupted apply blocks fetch and snapshot', ->
BobMain.startMainSynchro euid
contentFaker.createFakeContent {
store: peers.bobOpts.contentStore
}
# Force fake error.
AliceMain.syncStore._testingApplyErrorProb = 1
AliceMain.connectRemotes euid
Meteor._sleepForMs 200
oldRef = getAliceRemoteMaster()
# Trigger change, which is not fetched.
contentFaker.commitFakeContent()
Meteor._sleepForMs 200
expect(getAliceRemoteMaster()).to.be.eql oldRef
# Snapshots are refused with a pending apply.
{ status } = AliceMain.syncStore.snapshot euid, {
ownerName: aliceOwner
synchroName: 'all'
}
expect(status).to.eql 'refused'
# Clear fake error to allow recovery.
AliceMain.syncStore._testingApplyErrorProb = 0
# Trigger pull that skips fetch and restarts apply.
contentFaker.commitFakeContent()
Meteor._sleepForMs 200
# Trigger another pull that fetches, since apply has completed.
contentFaker.commitFakeContent()
Meteor._sleepForMs 500
expect(getAliceRemoteMaster()).to.be.not.eql oldRef
AliceMain.disconnectRemotes euid
BobMain.stopMainSynchro euid
# NULL_SHA1s are ignored during fetch; similar to git fetch, which requires
# an explicit prune before it deletes refs that disappeared at the remote.
it 'remote fetch ignores remote NULL_SHA1 synchro master', ->
oldRef = getAliceRemoteMaster()
$set = {}
$set['refs.branches/master'] = NULL_SHA1
BobMain.syncStore.synchros.update { name: 'all' }, { $set }
AliceMain.connectRemotes euid
Meteor._sleepForMs 200
expect(getAliceRemoteMaster()).to.be.eql oldRef
AliceMain.disconnectRemotes euid
|
[
{
"context": ".tooltip()\n\t\t, 500)\n\n\t\t$scope.about = {\n\t\t\tmail: 'joel.dumoulin@hefr.ch'\n\t\t\thomepage: 'http://joel.dumoulin.ch'\n\t\t\tlinked",
"end": 2334,
"score": 0.9999139904975891,
"start": 2313,
"tag": "EMAIL",
"value": "joel.dumoulin@hefr.ch"
},
{
"context": "ulin.ch'\n\t\t\tlinkedIn: 'http://ch.linkedin.com/pub/joël-dumoulin/60/b58/814/'\n\t\t\tscholar: 'https://scholar.google.",
"end": 2429,
"score": 0.8099170327186584,
"start": 2416,
"tag": "USERNAME",
"value": "joël-dumoulin"
},
{
"context": "&oi=ao'\n\t\t\tacademia: 'https://eia-fr.academia.edu/JoëlDumoulin'\n\t\t\tresearchGate: 'https://www.researchgate.net/p",
"end": 2577,
"score": 0.9989250302314758,
"start": 2565,
"tag": "NAME",
"value": "JoëlDumoulin"
},
{
"context": "searchGate: 'https://www.researchgate.net/profile/Joel_Dumoulin'\n\t\t}\n\n\t\tlicenses = {\n\t\t\tMIT: \"MIT License\",\n\t\t\tBS",
"end": 2647,
"score": 0.9277840256690979,
"start": 2634,
"tag": "NAME",
"value": "Joel_Dumoulin"
},
{
"context": "\": \"Swampdragon\",\n\t\t\t\t\t\"url\": \"https://github.com/inaffect-ag/swampdragon-bower\"\n\t\t\t\t\t\"license\": \"Copyright (c)",
"end": 3580,
"score": 0.9980448484420776,
"start": 3569,
"tag": "USERNAME",
"value": "inaffect-ag"
},
{
"context": "dragon-bower\"\n\t\t\t\t\t\"license\": \"Copyright (c) 2014, jonas hagstedt All rights reserved\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"name\": \"B",
"end": 3651,
"score": 0.9998916983604431,
"start": 3637,
"tag": "NAME",
"value": "jonas hagstedt"
},
{
"context": "\": \"Restangular\",\n\t\t\t\t\t\"url\": \"https://github.com/mgonto/restangular\"\n\t\t\t\t\t\"license\": licenses.MIT\n\t\t\t\t},\n",
"end": 4671,
"score": 0.9996623992919922,
"start": 4665,
"tag": "USERNAME",
"value": "mgonto"
},
{
"context": "gular ui router\",\n\t\t\t\t\t\"url\": \"https://github.com/angular-ui/ui-router\"\n\t\t\t\t\t\"license\": licenses.MIT\n\t\t\t\t},\n\t\t",
"end": 4803,
"score": 0.9997037053108215,
"start": 4793,
"tag": "USERNAME",
"value": "angular-ui"
},
{
"context": "\"Angular motion\",\n\t\t\t\t\t\"url\": \"https://github.com/mgcrea/angular-motion\"\n\t\t\t\t\t\"license\": licenses.MIT\n\t\t\t\t",
"end": 5050,
"score": 0.9995337128639221,
"start": 5044,
"tag": "USERNAME",
"value": "mgcrea"
},
{
"context": "lar file upload\",\n\t\t\t\t\t\"url\": \"https://github.com/danialfarid/ng-file-upload\"\n\t\t\t\t\t\"license\": licenses.MIT\n\t\t\t\t",
"end": 5476,
"score": 0.9997715950012207,
"start": 5465,
"tag": "USERNAME",
"value": "danialfarid"
},
{
"context": "Angular spinner\",\n\t\t\t\t\t\"url\": \"https://github.com/urish/angular-spinner\"\n\t\t\t\t\t\"license\": licenses.MIT\n\t\t\t",
"end": 5604,
"score": 0.9996377229690552,
"start": 5599,
"tag": "USERNAME",
"value": "urish"
},
{
"context": "rk.org/\"\n\t\t\t\t\t\"license\": \"Copyright (c) 2011-2015, Tom Christie All rights reserved.\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"name\": \"",
"end": 6182,
"score": 0.9998820424079895,
"start": 6170,
"tag": "NAME",
"value": "Tom Christie"
},
{
"context": "jango enumfield\",\n\t\t\t\t\t\"url\": \"https://github.com/5monkeys/django-enumfield\"\n\t\t\t\t\t\"license\": licenses.MIT\n\t\t",
"end": 6853,
"score": 0.9993867874145508,
"start": 6845,
"tag": "USERNAME",
"value": "5monkeys"
},
{
"context": "Django annoying\",\n\t\t\t\t\t\"url\": \"https://github.com/skorokithakis/django-annoying\"\n\t\t\t\t\t\"license\": licenses.BSD\n\t\t\t",
"end": 6991,
"score": 0.9994775652885437,
"start": 6978,
"tag": "USERNAME",
"value": "skorokithakis"
},
{
"context": "go cors headers\",\n\t\t\t\t\t\"url\": \"https://github.com/ottoyiu/django-cors-headers\"\n\t\t\t\t\t\"license\": licenses.MIT",
"end": 7126,
"score": 0.9983997344970703,
"start": 7119,
"tag": "USERNAME",
"value": "ottoyiu"
},
{
"context": "\"name\": \"Pillow\",\n\t\t\t\t\t\"url\": \"https://github.com/python-pillow/Pillow\"\n\t\t\t\t\t\"license\": \"Standard PIL License\"\n\t\t",
"end": 7367,
"score": 0.9825026988983154,
"start": 7354,
"tag": "USERNAME",
"value": "python-pillow"
},
{
"context": "video converter\",\n\t\t\t\t\t\"url\": \"https://github.com/senko/python-video-converter\"\n\t\t\t\t\t\"license\": \"Not spec",
"end": 7504,
"score": 0.9980909824371338,
"start": 7499,
"tag": "USERNAME",
"value": "senko"
}
] | ers_frontend/app/scripts/home/home.coffee | dumoulinj/erf | 0 | 'use strict'
# app.home Module
#
# @abstract Home controllers
angular
.module 'app.home', []
.config ($stateProvider, $urlRouterProvider) ->
$stateProvider
.state 'home', {
url: '/home',
templateUrl: '/partials/home.html',
controller: 'HomeCtrl'
}
.state 'about', {
url: '/about',
templateUrl: '/partials/about.html',
controller: 'AboutCtrl'
}
.controller 'HomeCtrl',($scope) ->
$scope.features = [
{
"text": "Video datasets management"
"icon": "glyphicon-wrench"
"subFeatures" : [
{
"text": "Create/Update/Delete datasets"
}
{
"text": "Scan video folder for existing videos"
}
{
"text": "Upload videos to the server by drag & drop"
}
{
"text": "Bulk upload videos of a same emotion class"
}
{
"text": "Prepare videos (conversion in a good video format, extract audio)"
}
]
}
{
"text": "Shot boundaries detection"
"icon": "glyphicon-camera"
"subFeatures" : [
{
"text": "Configuration (algorithms, thresholds, ...)"
}
{
"text": "Evaluation against ground truth (csv list of shot boundaries)"
}
{
"text": "Dynamic visualization (linked with the video) of the detected shot boundaries with color feedback to differentiate between true positives, false positives and misses"
}
]
}
{
"text": "Features extraction"
"icon": "glyphicon-tasks"
"subFeatures" : [
{
"text": "Audio and visual features extraction"
}
{
"text": "State of the art audio features extraction, with functionals (mean, min, max, skewness, etc.) "
}
{
"text": "Dynamic visualization (linked with the video) of extracted features visualization"
}
]
}
{
"text": "Emotion modeling"
"icon": "glyphicon-star-empty"
"subFeatures" : [
{
"text": "Arousal modeling, with dynamic visualization linked to the video"
}
{
"text": "Valence modeling (coming soon)"
}
{
"text": "Emotion classification (coming soon)"
}
]
}
]
.controller 'AboutCtrl',($scope, $timeout) ->
# Initialize tooltips on buttons
$timeout(() ->
$('[data-toggle="tooltip"]').tooltip()
, 500)
$scope.about = {
mail: 'joel.dumoulin@hefr.ch'
homepage: 'http://joel.dumoulin.ch'
linkedIn: 'http://ch.linkedin.com/pub/joël-dumoulin/60/b58/814/'
scholar: 'https://scholar.google.ch/citations?user=4qMFFxkAAAAJ&hl=fr&oi=ao'
academia: 'https://eia-fr.academia.edu/JoëlDumoulin'
researchGate: 'https://www.researchgate.net/profile/Joel_Dumoulin'
}
licenses = {
MIT: "MIT License",
BSD: "BSD",
BSD3: "3-clause BSD License",
APACHE2: "Apache License, Version 2.0",
GNU: "GNU Lesser General Public License (LGPL) version 2.1"
}
$scope.usedProjects = {
"frontend": [
{
"name": "Angular JS",
"url": "https://angularjs.org/"
"license": licenses.MIT
},
{
"name": "Jade",
"url": "http://jade-lang.com/"
"license": licenses.MIT
},
{
"name": "CoffeeScript",
"url": "http://coffeescript.org/"
"license": licenses.MIT
}
{
"name": "Brunch.io",
"url": "http://brunch.io/"
"license": licenses.MIT
},
{
"name": "Node.js",
"url": "https://nodejs.org/"
"license": licenses.MIT
},
{
"name": "Bower",
"url": "http://bower.io/"
"license": licenses.MIT
},
{
"name": "Swampdragon",
"url": "https://github.com/inaffect-ag/swampdragon-bower"
"license": "Copyright (c) 2014, jonas hagstedt All rights reserved"
},
{
"name": "Bootstrap",
"url": "http://getbootstrap.com/"
"license": licenses.MIT
},
{
"name": "Bootswatch Paper theme",
"url": "https://bootswatch.com/paper/"
"license": licenses.MIT
},
{
"name": "Fontawesome",
"url": "http://fortawesome.github.io/Font-Awesome/"
"license": licenses.MIT
},
{
"name": "Jquery",
"url": "https://jquery.com/"
"license": licenses.MIT
},
{
"name": "lodash",
"url": "https://lodash.com/"
"license": licenses.MIT
},
{
"name": "D3.js",
"url": "http://d3js.org/"
"license": licenses.BSD
},
{
"name": "nvd3",
"url": "http://nvd3.org/"
"license": licenses.APACHE
},
{
"name": "Angular nvd3 directives",
"url": "https://github.com/angularjs-nvd3-directives/angularjs-nvd3-directives"
"license": licenses.APACHE
},
{
"name": "Restangular",
"url": "https://github.com/mgonto/restangular"
"license": licenses.MIT
},
{
"name": "Angular ui router",
"url": "https://github.com/angular-ui/ui-router"
"license": licenses.MIT
},
{
"name": "AngularStrap",
"url": "http://mgcrea.github.io/angular-strap/"
"license": licenses.MIT
},
{
"name": "Angular motion",
"url": "https://github.com/mgcrea/angular-motion"
"license": licenses.MIT
},
{
"name": "Angular loading bar",
"url": "http://chieffancypants.github.io/angular-loading-bar/"
"license": licenses.MIT
},
{
"name": "Angular smart table",
"url": "http://lorenzofox3.github.io/smart-table-website/"
"license": licenses.MIT
},
{
"name": "Angular file upload",
"url": "https://github.com/danialfarid/ng-file-upload"
"license": licenses.MIT
},
{
"name": "Angular spinner",
"url": "https://github.com/urish/angular-spinner"
"license": licenses.MIT
},
{
"name": "Videogular",
"url": "http://www.videogular.com/"
"license": licenses.MIT
},
{
"name": "Checklist-model",
"url": "http://vitalets.github.io/checklist-model/"
"license": licenses.MIT
}
],
"backend": [
{
"name": "Django",
"url": "https://www.djangoproject.com/"
"license": licenses.BSD3
},
{
"name": "Django Rest Framework",
"url": "http://www.django-rest-framework.org/"
"license": "Copyright (c) 2011-2015, Tom Christie All rights reserved."
},
{
"name": "Swampdragon",
"url": "http://swampdragon.net/"
"license": licenses.BSD
},
{
"name": "OpenCV",
"url": "http://opencv.org/"
"license": licenses.BSD3
},
{
"name": "FFmpeg",
"url": "https://www.ffmpeg.org/"
"license": licenses.GNU
},
{
"name": "OpenSMILE",
"url": "http://www.audeering.com/research/opensmile"
"license": "audEERING Research License Agreement"
},
{
"name": "Numpy",
"url": "http://www.numpy.org/"
"license": licenses.BSD
},
{
"name": "Django enumfield",
"url": "https://github.com/5monkeys/django-enumfield"
"license": licenses.MIT
},
{
"name": "Django annoying",
"url": "https://github.com/skorokithakis/django-annoying"
"license": licenses.BSD
},
{
"name": "Django cors headers",
"url": "https://github.com/ottoyiu/django-cors-headers"
"license": licenses.MIT
},
{
"name": "Celery",
"url": "http://www.celeryproject.org/"
"license": licenses.BSD
},
{
"name": "Pillow",
"url": "https://github.com/python-pillow/Pillow"
"license": "Standard PIL License"
},
{
"name": "Python video converter",
"url": "https://github.com/senko/python-video-converter"
"license": "Not specified"
}
]
} | 140910 | 'use strict'
# app.home Module
#
# @abstract Home controllers
angular
.module 'app.home', []
.config ($stateProvider, $urlRouterProvider) ->
$stateProvider
.state 'home', {
url: '/home',
templateUrl: '/partials/home.html',
controller: 'HomeCtrl'
}
.state 'about', {
url: '/about',
templateUrl: '/partials/about.html',
controller: 'AboutCtrl'
}
.controller 'HomeCtrl',($scope) ->
$scope.features = [
{
"text": "Video datasets management"
"icon": "glyphicon-wrench"
"subFeatures" : [
{
"text": "Create/Update/Delete datasets"
}
{
"text": "Scan video folder for existing videos"
}
{
"text": "Upload videos to the server by drag & drop"
}
{
"text": "Bulk upload videos of a same emotion class"
}
{
"text": "Prepare videos (conversion in a good video format, extract audio)"
}
]
}
{
"text": "Shot boundaries detection"
"icon": "glyphicon-camera"
"subFeatures" : [
{
"text": "Configuration (algorithms, thresholds, ...)"
}
{
"text": "Evaluation against ground truth (csv list of shot boundaries)"
}
{
"text": "Dynamic visualization (linked with the video) of the detected shot boundaries with color feedback to differentiate between true positives, false positives and misses"
}
]
}
{
"text": "Features extraction"
"icon": "glyphicon-tasks"
"subFeatures" : [
{
"text": "Audio and visual features extraction"
}
{
"text": "State of the art audio features extraction, with functionals (mean, min, max, skewness, etc.) "
}
{
"text": "Dynamic visualization (linked with the video) of extracted features visualization"
}
]
}
{
"text": "Emotion modeling"
"icon": "glyphicon-star-empty"
"subFeatures" : [
{
"text": "Arousal modeling, with dynamic visualization linked to the video"
}
{
"text": "Valence modeling (coming soon)"
}
{
"text": "Emotion classification (coming soon)"
}
]
}
]
.controller 'AboutCtrl',($scope, $timeout) ->
# Initialize tooltips on buttons
$timeout(() ->
$('[data-toggle="tooltip"]').tooltip()
, 500)
$scope.about = {
mail: '<EMAIL>'
homepage: 'http://joel.dumoulin.ch'
linkedIn: 'http://ch.linkedin.com/pub/joël-dumoulin/60/b58/814/'
scholar: 'https://scholar.google.ch/citations?user=4qMFFxkAAAAJ&hl=fr&oi=ao'
academia: 'https://eia-fr.academia.edu/<NAME>'
researchGate: 'https://www.researchgate.net/profile/<NAME>'
}
licenses = {
MIT: "MIT License",
BSD: "BSD",
BSD3: "3-clause BSD License",
APACHE2: "Apache License, Version 2.0",
GNU: "GNU Lesser General Public License (LGPL) version 2.1"
}
$scope.usedProjects = {
"frontend": [
{
"name": "Angular JS",
"url": "https://angularjs.org/"
"license": licenses.MIT
},
{
"name": "Jade",
"url": "http://jade-lang.com/"
"license": licenses.MIT
},
{
"name": "CoffeeScript",
"url": "http://coffeescript.org/"
"license": licenses.MIT
}
{
"name": "Brunch.io",
"url": "http://brunch.io/"
"license": licenses.MIT
},
{
"name": "Node.js",
"url": "https://nodejs.org/"
"license": licenses.MIT
},
{
"name": "Bower",
"url": "http://bower.io/"
"license": licenses.MIT
},
{
"name": "Swampdragon",
"url": "https://github.com/inaffect-ag/swampdragon-bower"
"license": "Copyright (c) 2014, <NAME> All rights reserved"
},
{
"name": "Bootstrap",
"url": "http://getbootstrap.com/"
"license": licenses.MIT
},
{
"name": "Bootswatch Paper theme",
"url": "https://bootswatch.com/paper/"
"license": licenses.MIT
},
{
"name": "Fontawesome",
"url": "http://fortawesome.github.io/Font-Awesome/"
"license": licenses.MIT
},
{
"name": "Jquery",
"url": "https://jquery.com/"
"license": licenses.MIT
},
{
"name": "lodash",
"url": "https://lodash.com/"
"license": licenses.MIT
},
{
"name": "D3.js",
"url": "http://d3js.org/"
"license": licenses.BSD
},
{
"name": "nvd3",
"url": "http://nvd3.org/"
"license": licenses.APACHE
},
{
"name": "Angular nvd3 directives",
"url": "https://github.com/angularjs-nvd3-directives/angularjs-nvd3-directives"
"license": licenses.APACHE
},
{
"name": "Restangular",
"url": "https://github.com/mgonto/restangular"
"license": licenses.MIT
},
{
"name": "Angular ui router",
"url": "https://github.com/angular-ui/ui-router"
"license": licenses.MIT
},
{
"name": "AngularStrap",
"url": "http://mgcrea.github.io/angular-strap/"
"license": licenses.MIT
},
{
"name": "Angular motion",
"url": "https://github.com/mgcrea/angular-motion"
"license": licenses.MIT
},
{
"name": "Angular loading bar",
"url": "http://chieffancypants.github.io/angular-loading-bar/"
"license": licenses.MIT
},
{
"name": "Angular smart table",
"url": "http://lorenzofox3.github.io/smart-table-website/"
"license": licenses.MIT
},
{
"name": "Angular file upload",
"url": "https://github.com/danialfarid/ng-file-upload"
"license": licenses.MIT
},
{
"name": "Angular spinner",
"url": "https://github.com/urish/angular-spinner"
"license": licenses.MIT
},
{
"name": "Videogular",
"url": "http://www.videogular.com/"
"license": licenses.MIT
},
{
"name": "Checklist-model",
"url": "http://vitalets.github.io/checklist-model/"
"license": licenses.MIT
}
],
"backend": [
{
"name": "Django",
"url": "https://www.djangoproject.com/"
"license": licenses.BSD3
},
{
"name": "Django Rest Framework",
"url": "http://www.django-rest-framework.org/"
"license": "Copyright (c) 2011-2015, <NAME> All rights reserved."
},
{
"name": "Swampdragon",
"url": "http://swampdragon.net/"
"license": licenses.BSD
},
{
"name": "OpenCV",
"url": "http://opencv.org/"
"license": licenses.BSD3
},
{
"name": "FFmpeg",
"url": "https://www.ffmpeg.org/"
"license": licenses.GNU
},
{
"name": "OpenSMILE",
"url": "http://www.audeering.com/research/opensmile"
"license": "audEERING Research License Agreement"
},
{
"name": "Numpy",
"url": "http://www.numpy.org/"
"license": licenses.BSD
},
{
"name": "Django enumfield",
"url": "https://github.com/5monkeys/django-enumfield"
"license": licenses.MIT
},
{
"name": "Django annoying",
"url": "https://github.com/skorokithakis/django-annoying"
"license": licenses.BSD
},
{
"name": "Django cors headers",
"url": "https://github.com/ottoyiu/django-cors-headers"
"license": licenses.MIT
},
{
"name": "Celery",
"url": "http://www.celeryproject.org/"
"license": licenses.BSD
},
{
"name": "Pillow",
"url": "https://github.com/python-pillow/Pillow"
"license": "Standard PIL License"
},
{
"name": "Python video converter",
"url": "https://github.com/senko/python-video-converter"
"license": "Not specified"
}
]
} | true | 'use strict'
# app.home Module
#
# @abstract Home controllers
angular
.module 'app.home', []
.config ($stateProvider, $urlRouterProvider) ->
$stateProvider
.state 'home', {
url: '/home',
templateUrl: '/partials/home.html',
controller: 'HomeCtrl'
}
.state 'about', {
url: '/about',
templateUrl: '/partials/about.html',
controller: 'AboutCtrl'
}
.controller 'HomeCtrl',($scope) ->
$scope.features = [
{
"text": "Video datasets management"
"icon": "glyphicon-wrench"
"subFeatures" : [
{
"text": "Create/Update/Delete datasets"
}
{
"text": "Scan video folder for existing videos"
}
{
"text": "Upload videos to the server by drag & drop"
}
{
"text": "Bulk upload videos of a same emotion class"
}
{
"text": "Prepare videos (conversion in a good video format, extract audio)"
}
]
}
{
"text": "Shot boundaries detection"
"icon": "glyphicon-camera"
"subFeatures" : [
{
"text": "Configuration (algorithms, thresholds, ...)"
}
{
"text": "Evaluation against ground truth (csv list of shot boundaries)"
}
{
"text": "Dynamic visualization (linked with the video) of the detected shot boundaries with color feedback to differentiate between true positives, false positives and misses"
}
]
}
{
"text": "Features extraction"
"icon": "glyphicon-tasks"
"subFeatures" : [
{
"text": "Audio and visual features extraction"
}
{
"text": "State of the art audio features extraction, with functionals (mean, min, max, skewness, etc.) "
}
{
"text": "Dynamic visualization (linked with the video) of extracted features visualization"
}
]
}
{
"text": "Emotion modeling"
"icon": "glyphicon-star-empty"
"subFeatures" : [
{
"text": "Arousal modeling, with dynamic visualization linked to the video"
}
{
"text": "Valence modeling (coming soon)"
}
{
"text": "Emotion classification (coming soon)"
}
]
}
]
.controller 'AboutCtrl',($scope, $timeout) ->
# Initialize tooltips on buttons
$timeout(() ->
$('[data-toggle="tooltip"]').tooltip()
, 500)
$scope.about = {
mail: 'PI:EMAIL:<EMAIL>END_PI'
homepage: 'http://joel.dumoulin.ch'
linkedIn: 'http://ch.linkedin.com/pub/joël-dumoulin/60/b58/814/'
scholar: 'https://scholar.google.ch/citations?user=4qMFFxkAAAAJ&hl=fr&oi=ao'
academia: 'https://eia-fr.academia.edu/PI:NAME:<NAME>END_PI'
researchGate: 'https://www.researchgate.net/profile/PI:NAME:<NAME>END_PI'
}
licenses = {
MIT: "MIT License",
BSD: "BSD",
BSD3: "3-clause BSD License",
APACHE2: "Apache License, Version 2.0",
GNU: "GNU Lesser General Public License (LGPL) version 2.1"
}
$scope.usedProjects = {
"frontend": [
{
"name": "Angular JS",
"url": "https://angularjs.org/"
"license": licenses.MIT
},
{
"name": "Jade",
"url": "http://jade-lang.com/"
"license": licenses.MIT
},
{
"name": "CoffeeScript",
"url": "http://coffeescript.org/"
"license": licenses.MIT
}
{
"name": "Brunch.io",
"url": "http://brunch.io/"
"license": licenses.MIT
},
{
"name": "Node.js",
"url": "https://nodejs.org/"
"license": licenses.MIT
},
{
"name": "Bower",
"url": "http://bower.io/"
"license": licenses.MIT
},
{
"name": "Swampdragon",
"url": "https://github.com/inaffect-ag/swampdragon-bower"
"license": "Copyright (c) 2014, PI:NAME:<NAME>END_PI All rights reserved"
},
{
"name": "Bootstrap",
"url": "http://getbootstrap.com/"
"license": licenses.MIT
},
{
"name": "Bootswatch Paper theme",
"url": "https://bootswatch.com/paper/"
"license": licenses.MIT
},
{
"name": "Fontawesome",
"url": "http://fortawesome.github.io/Font-Awesome/"
"license": licenses.MIT
},
{
"name": "Jquery",
"url": "https://jquery.com/"
"license": licenses.MIT
},
{
"name": "lodash",
"url": "https://lodash.com/"
"license": licenses.MIT
},
{
"name": "D3.js",
"url": "http://d3js.org/"
"license": licenses.BSD
},
{
"name": "nvd3",
"url": "http://nvd3.org/"
"license": licenses.APACHE
},
{
"name": "Angular nvd3 directives",
"url": "https://github.com/angularjs-nvd3-directives/angularjs-nvd3-directives"
"license": licenses.APACHE
},
{
"name": "Restangular",
"url": "https://github.com/mgonto/restangular"
"license": licenses.MIT
},
{
"name": "Angular ui router",
"url": "https://github.com/angular-ui/ui-router"
"license": licenses.MIT
},
{
"name": "AngularStrap",
"url": "http://mgcrea.github.io/angular-strap/"
"license": licenses.MIT
},
{
"name": "Angular motion",
"url": "https://github.com/mgcrea/angular-motion"
"license": licenses.MIT
},
{
"name": "Angular loading bar",
"url": "http://chieffancypants.github.io/angular-loading-bar/"
"license": licenses.MIT
},
{
"name": "Angular smart table",
"url": "http://lorenzofox3.github.io/smart-table-website/"
"license": licenses.MIT
},
{
"name": "Angular file upload",
"url": "https://github.com/danialfarid/ng-file-upload"
"license": licenses.MIT
},
{
"name": "Angular spinner",
"url": "https://github.com/urish/angular-spinner"
"license": licenses.MIT
},
{
"name": "Videogular",
"url": "http://www.videogular.com/"
"license": licenses.MIT
},
{
"name": "Checklist-model",
"url": "http://vitalets.github.io/checklist-model/"
"license": licenses.MIT
}
],
"backend": [
{
"name": "Django",
"url": "https://www.djangoproject.com/"
"license": licenses.BSD3
},
{
"name": "Django Rest Framework",
"url": "http://www.django-rest-framework.org/"
"license": "Copyright (c) 2011-2015, PI:NAME:<NAME>END_PI All rights reserved."
},
{
"name": "Swampdragon",
"url": "http://swampdragon.net/"
"license": licenses.BSD
},
{
"name": "OpenCV",
"url": "http://opencv.org/"
"license": licenses.BSD3
},
{
"name": "FFmpeg",
"url": "https://www.ffmpeg.org/"
"license": licenses.GNU
},
{
"name": "OpenSMILE",
"url": "http://www.audeering.com/research/opensmile"
"license": "audEERING Research License Agreement"
},
{
"name": "Numpy",
"url": "http://www.numpy.org/"
"license": licenses.BSD
},
{
"name": "Django enumfield",
"url": "https://github.com/5monkeys/django-enumfield"
"license": licenses.MIT
},
{
"name": "Django annoying",
"url": "https://github.com/skorokithakis/django-annoying"
"license": licenses.BSD
},
{
"name": "Django cors headers",
"url": "https://github.com/ottoyiu/django-cors-headers"
"license": licenses.MIT
},
{
"name": "Celery",
"url": "http://www.celeryproject.org/"
"license": licenses.BSD
},
{
"name": "Pillow",
"url": "https://github.com/python-pillow/Pillow"
"license": "Standard PIL License"
},
{
"name": "Python video converter",
"url": "https://github.com/senko/python-video-converter"
"license": "Not specified"
}
]
} |
[
{
"context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ",
"end": 38,
"score": 0.9998860359191895,
"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.9999293088912964,
"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.9998779296875,
"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.9999352693557739,
"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.9998773336410522,
"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.9999345541000366,
"start": 160,
"tag": "EMAIL",
"value": "bameda@dbarragan.com"
}
] | public/taiga-front/app/coffee/modules/auth.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/auth.coffee
###
taiga = @.taiga
debounce = @.taiga.debounce
module = angular.module("taigaAuth", ["taigaResources"])
#############################################################################
## Authentication Service
#############################################################################
class AuthService extends taiga.Service
@.$inject = ["$rootScope",
"$tgStorage",
"$tgModel",
"$tgResources",
"$tgHttp",
"$tgUrls"]
constructor: (@rootscope, @storage, @model, @rs, @http, @urls) ->
super()
getUser: ->
if @rootscope.user
return @rootscope.user
userData = @storage.get("userInfo")
if userData
user = @model.make_model("users", userData)
@rootscope.user = user
return user
return null
setUser: (user) ->
@rootscope.auth = user
@rootscope.$broadcast("i18n:change", user.default_language)
@storage.set("userInfo", user.getAttrs())
@rootscope.user = user
clear: ->
@rootscope.auth = null
@rootscope.user = null
@storage.remove("userInfo")
setToken: (token) ->
@storage.set("token", token)
getToken: ->
return @storage.get("token")
removeToken: ->
@storage.remove("token")
isAuthenticated: ->
if @.getUser() != null
return true
return false
## Http interface
login: (data, type) ->
url = @urls.resolve("auth")
data = _.clone(data, false)
data.type = if type then type else "normal"
@.removeToken()
return @http.post(url, data).then (data, status) =>
user = @model.make_model("users", data.data)
@.setToken(user.auth_token)
@.setUser(user)
return user
logout: ->
@.removeToken()
@.clear()
register: (data, type, existing) ->
url = @urls.resolve("auth-register")
data = _.clone(data, false)
data.type = if type then type else "public"
if type == "private"
data.existing = if existing then existing else false
@.removeToken()
return @http.post(url, data).then (response) =>
user = @model.make_model("users", response.data)
@.setToken(user.auth_token)
@.setUser(user)
return user
getInvitation: (token) ->
return @rs.invitations.get(token)
acceptInvitiationWithNewUser: (data) ->
return @.register(data, "private", false)
acceptInvitiationWithExistingUser: (data) ->
return @.register(data, "private", true)
forgotPassword: (data) ->
url = @urls.resolve("users-password-recovery")
data = _.clone(data, false)
@.removeToken()
return @http.post(url, data)
changePasswordFromRecovery: (data) ->
url = @urls.resolve("users-change-password-from-recovery")
data = _.clone(data, false)
@.removeToken()
return @http.post(url, data)
changeEmail: (data) ->
url = @urls.resolve("users-change-email")
data = _.clone(data, false)
return @http.post(url, data)
cancelAccount: (data) ->
url = @urls.resolve("users-cancel-account")
data = _.clone(data, false)
return @http.post(url, data)
module.service("$tgAuth", AuthService)
#############################################################################
## Login Directive
#############################################################################
# Directive that manages the visualization of public register
# message/link on login page.
PublicRegisterMessageDirective = ($config, $navUrls) ->
template = _.template("""
<p class="login-text">
<span>Not registered yet?</span>
<a href="<%- url %>" tg-nav="register" title="Register"> create your free account here</a>
</p>""")
templateFn = ->
publicRegisterEnabled = $config.get("publicRegisterEnabled")
if not publicRegisterEnabled
return ""
return template({url:$navUrls.resolve("register")})
return {
restrict: "AE"
scope: {}
template: templateFn
}
module.directive("tgPublicRegisterMessage", ["$tgConfig", "$tgNavUrls", PublicRegisterMessageDirective])
LoginDirective = ($auth, $confirm, $location, $config, $routeParams, $navUrls, $events) ->
link = ($scope, $el, $attrs) ->
onSuccess = (response) ->
if $routeParams['next'] and $routeParams['next'] != $navUrls.resolve("login")
nextUrl = $routeParams['next']
else
nextUrl = $navUrls.resolve("home")
$events.setupConnection()
$location.path(nextUrl)
onError = (response) ->
$confirm.notify("light-error", "According to our Oompa Loompas, your username/email
or password are incorrect.") #TODO: i18n
submit = debounce 2000, (event) =>
event.preventDefault()
form = new checksley.Form($el.find("form.login-form"))
if not form.validate()
return
data = {
"username": $el.find("form.login-form input[name=username]").val(),
"password": $el.find("form.login-form input[name=password]").val()
}
promise = $auth.login(data)
return promise.then(onSuccess, onError)
$el.on "submit", "form", submit
$el.on "click", ".submit-button", submit
return {link:link}
module.directive("tgLogin", ["$tgAuth", "$tgConfirm", "$tgLocation", "$tgConfig", "$routeParams",
"$tgNavUrls", "$tgEvents", LoginDirective])
#############################################################################
## Register Directive
#############################################################################
RegisterDirective = ($auth, $confirm, $location, $navUrls, $config, $analytics) ->
link = ($scope, $el, $attrs) ->
if not $config.get("publicRegisterEnabled")
$location.path($navUrls.resolve("not-found"))
$location.replace()
$scope.data = {}
form = $el.find("form").checksley({onlyOneErrorElement: true})
onSuccessSubmit = (response) ->
$analytics.trackEvent("auth", "register", "user registration", 1)
$confirm.notify("success", "Our Oompa Loompas are happy, welcome to Taiga.") #TODO: i18n
$location.path($navUrls.resolve("home"))
onErrorSubmit = (response) ->
if response.data._error_message?
$confirm.notify("light-error", "According to our Oompa Loompas there was an error. #{response.data._error_message}") #TODO: i18n
form.setErrors(response.data)
submit = debounce 2000, (event) =>
event.preventDefault()
if not form.validate()
return
promise = $auth.register($scope.data)
promise.then(onSuccessSubmit, onErrorSubmit)
$el.on "submit", "form", submit
$el.on "click", ".submit-button", submit
return {link:link}
module.directive("tgRegister", ["$tgAuth", "$tgConfirm", "$tgLocation", "$tgNavUrls", "$tgConfig",
"$tgAnalytics", RegisterDirective])
#############################################################################
## Forgot Password Directive
#############################################################################
ForgotPasswordDirective = ($auth, $confirm, $location, $navUrls) ->
link = ($scope, $el, $attrs) ->
$scope.data = {}
form = $el.find("form").checksley()
onSuccessSubmit = (response) ->
$location.path($navUrls.resolve("login"))
$confirm.success("<strong>Check your inbox!</strong><br />
We have sent a mail to<br />
<strong>#{response.data.email}</strong><br />
with the instructions to set a new password") #TODO: i18n
onErrorSubmit = (response) ->
$confirm.notify("light-error", "According to our Oompa Loompas,
your are not registered yet.") #TODO: i18n
submit = debounce 2000, (event) =>
event.preventDefault()
if not form.validate()
return
promise = $auth.forgotPassword($scope.data)
promise.then(onSuccessSubmit, onErrorSubmit)
$el.on "submit", "form", submit
$el.on "click", ".submit-button", submit
return {link:link}
module.directive("tgForgotPassword", ["$tgAuth", "$tgConfirm", "$tgLocation", "$tgNavUrls",
ForgotPasswordDirective])
#############################################################################
## Change Password from Recovery Directive
#############################################################################
ChangePasswordFromRecoveryDirective = ($auth, $confirm, $location, $params, $navUrls) ->
link = ($scope, $el, $attrs) ->
$scope.data = {}
if $params.token?
$scope.tokenInParams = true
$scope.data.token = $params.token
else
$scope.tokenInParams = false
form = $el.find("form").checksley()
onSuccessSubmit = (response) ->
$location.path($navUrls.resolve("login"))
$confirm.success("Our Oompa Loompas saved your new password.<br />
Try to <strong>sign in</strong> with it.") #TODO: i18n
onErrorSubmit = (response) ->
$confirm.notify("light-error", "One of our Oompa Loompas say
'#{response.data._error_message}'.") #TODO: i18n
submit = debounce 2000, (event) =>
event.preventDefault()
if not form.validate()
return
promise = $auth.changePasswordFromRecovery($scope.data)
promise.then(onSuccessSubmit, onErrorSubmit)
$el.on "submit", "form", submit
$el.on "click", ".submit-button", submit
return {link:link}
module.directive("tgChangePasswordFromRecovery", ["$tgAuth", "$tgConfirm", "$tgLocation", "$routeParams",
"$tgNavUrls", ChangePasswordFromRecoveryDirective])
#############################################################################
## Invitation
#############################################################################
InvitationDirective = ($auth, $confirm, $location, $params, $navUrls, $analytics) ->
link = ($scope, $el, $attrs) ->
token = $params.token
promise = $auth.getInvitation(token)
promise.then (invitation) ->
$scope.invitation = invitation
promise.then null, (response) ->
$location.path($navUrls.resolve("login"))
$confirm.success("<strong>Ooops, we have a problem</strong><br />
Our Oompa Loompas can't find your invitation.") #TODO: i18n
# Login form
$scope.dataLogin = {token: token}
loginForm = $el.find("form.login-form").checksley({onlyOneErrorElement: true})
onSuccessSubmitLogin = (response) ->
$analytics.trackEvent("auth", "invitationAccept", "invitation accept with existing user", 1)
$location.path($navUrls.resolve("project", {project: $scope.invitation.project_slug}))
$confirm.notify("success", "You've successfully joined this project",
"Welcome to #{_.escape($scope.invitation.project_name)}")
onErrorSubmitLogin = (response) ->
$confirm.notify("light-error", "According to our Oompa Loompas, your are not registered yet or
typed an invalid password.") #TODO: i18n
submitLogin = debounce 2000, (event) =>
event.preventDefault()
if not loginForm.validate()
return
promise = $auth.acceptInvitiationWithExistingUser($scope.dataLogin)
promise.then(onSuccessSubmitLogin, onErrorSubmitLogin)
$el.on "submit", "form.login-form", submitLogin
$el.on "click", ".button-login", submitLogin
# Register form
$scope.dataRegister = {token: token}
registerForm = $el.find("form.register-form").checksley()
onSuccessSubmitRegister = (response) ->
$analytics.trackEvent("auth", "invitationAccept", "invitation accept with new user", 1)
$location.path($navUrls.resolve("project", {project: $scope.invitation.project_slug}))
$confirm.notify("success", "You've successfully joined this project",
"Welcome to #{_.escape($scope.invitation.project_name)}")
onErrorSubmitRegister = (response) ->
$confirm.notify("light-error", "According to our Oompa Loompas, that
username or email is already in use.") #TODO: i18n
submitRegister = debounce 2000, (event) =>
event.preventDefault()
if not registerForm.validate()
return
promise = $auth.acceptInvitiationWithNewUser($scope.dataRegister)
promise.then(onSuccessSubmitRegister, onErrorSubmitRegister)
$el.on "submit", "form.register-form", submitRegister
$el.on "click", ".button-register", submitRegister
return {link:link}
module.directive("tgInvitation", ["$tgAuth", "$tgConfirm", "$tgLocation", "$routeParams",
"$tgNavUrls", "$tgAnalytics", InvitationDirective])
#############################################################################
## Change Email
#############################################################################
ChangeEmailDirective = ($repo, $model, $auth, $confirm, $location, $params, $navUrls) ->
link = ($scope, $el, $attrs) ->
$scope.data = {}
$scope.data.email_token = $params.email_token
form = $el.find("form").checksley()
onSuccessSubmit = (response) ->
$repo.queryOne("users", $auth.getUser().id).then (data) =>
$auth.setUser(data)
$location.path($navUrls.resolve("home"))
$confirm.success("Our Oompa Loompas updated your email") #TODO: i18n
onErrorSubmit = (response) ->
$confirm.notify("error", "One of our Oompa Loompas says
'#{response.data._error_message}'.") #TODO: i18n
submit = ->
if not form.validate()
return
promise = $auth.changeEmail($scope.data)
promise.then(onSuccessSubmit, onErrorSubmit)
$el.on "submit", (event) ->
event.preventDefault()
submit()
$el.on "click", "a.button-change-email", (event) ->
event.preventDefault()
submit()
return {link:link}
module.directive("tgChangeEmail", ["$tgRepo", "$tgModel", "$tgAuth", "$tgConfirm", "$tgLocation", "$routeParams",
"$tgNavUrls", ChangeEmailDirective])
#############################################################################
## Cancel account
#############################################################################
CancelAccountDirective = ($repo, $model, $auth, $confirm, $location, $params, $navUrls) ->
link = ($scope, $el, $attrs) ->
$scope.data = {}
$scope.data.cancel_token = $params.cancel_token
form = $el.find("form").checksley()
onSuccessSubmit = (response) ->
$auth.logout()
$location.path($navUrls.resolve("home"))
$confirm.success("Our Oompa Loompas removed your account") #TODO: i18n
onErrorSubmit = (response) ->
$confirm.notify("error", "One of our Oompa Loompas says
'#{response.data._error_message}'.") #TODO: i18n
submit = debounce 2000, (event) =>
event.preventDefault()
if not form.validate()
return
promise = $auth.cancelAccount($scope.data)
promise.then(onSuccessSubmit, onErrorSubmit)
$el.on "submit", "form", submit
$el.on "click", ".submit-button", submit
return {link:link}
module.directive("tgCancelAccount", ["$tgRepo", "$tgModel", "$tgAuth", "$tgConfirm", "$tgLocation", "$routeParams",
"$tgNavUrls", CancelAccountDirective])
| 8601 | ###
# 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/auth.coffee
###
taiga = @.taiga
debounce = @.taiga.debounce
module = angular.module("taigaAuth", ["taigaResources"])
#############################################################################
## Authentication Service
#############################################################################
class AuthService extends taiga.Service
@.$inject = ["$rootScope",
"$tgStorage",
"$tgModel",
"$tgResources",
"$tgHttp",
"$tgUrls"]
constructor: (@rootscope, @storage, @model, @rs, @http, @urls) ->
super()
getUser: ->
if @rootscope.user
return @rootscope.user
userData = @storage.get("userInfo")
if userData
user = @model.make_model("users", userData)
@rootscope.user = user
return user
return null
setUser: (user) ->
@rootscope.auth = user
@rootscope.$broadcast("i18n:change", user.default_language)
@storage.set("userInfo", user.getAttrs())
@rootscope.user = user
clear: ->
@rootscope.auth = null
@rootscope.user = null
@storage.remove("userInfo")
setToken: (token) ->
@storage.set("token", token)
getToken: ->
return @storage.get("token")
removeToken: ->
@storage.remove("token")
isAuthenticated: ->
if @.getUser() != null
return true
return false
## Http interface
login: (data, type) ->
url = @urls.resolve("auth")
data = _.clone(data, false)
data.type = if type then type else "normal"
@.removeToken()
return @http.post(url, data).then (data, status) =>
user = @model.make_model("users", data.data)
@.setToken(user.auth_token)
@.setUser(user)
return user
logout: ->
@.removeToken()
@.clear()
register: (data, type, existing) ->
url = @urls.resolve("auth-register")
data = _.clone(data, false)
data.type = if type then type else "public"
if type == "private"
data.existing = if existing then existing else false
@.removeToken()
return @http.post(url, data).then (response) =>
user = @model.make_model("users", response.data)
@.setToken(user.auth_token)
@.setUser(user)
return user
getInvitation: (token) ->
return @rs.invitations.get(token)
acceptInvitiationWithNewUser: (data) ->
return @.register(data, "private", false)
acceptInvitiationWithExistingUser: (data) ->
return @.register(data, "private", true)
forgotPassword: (data) ->
url = @urls.resolve("users-password-recovery")
data = _.clone(data, false)
@.removeToken()
return @http.post(url, data)
changePasswordFromRecovery: (data) ->
url = @urls.resolve("users-change-password-from-recovery")
data = _.clone(data, false)
@.removeToken()
return @http.post(url, data)
changeEmail: (data) ->
url = @urls.resolve("users-change-email")
data = _.clone(data, false)
return @http.post(url, data)
cancelAccount: (data) ->
url = @urls.resolve("users-cancel-account")
data = _.clone(data, false)
return @http.post(url, data)
module.service("$tgAuth", AuthService)
#############################################################################
## Login Directive
#############################################################################
# Directive that manages the visualization of public register
# message/link on login page.
PublicRegisterMessageDirective = ($config, $navUrls) ->
template = _.template("""
<p class="login-text">
<span>Not registered yet?</span>
<a href="<%- url %>" tg-nav="register" title="Register"> create your free account here</a>
</p>""")
templateFn = ->
publicRegisterEnabled = $config.get("publicRegisterEnabled")
if not publicRegisterEnabled
return ""
return template({url:$navUrls.resolve("register")})
return {
restrict: "AE"
scope: {}
template: templateFn
}
module.directive("tgPublicRegisterMessage", ["$tgConfig", "$tgNavUrls", PublicRegisterMessageDirective])
LoginDirective = ($auth, $confirm, $location, $config, $routeParams, $navUrls, $events) ->
link = ($scope, $el, $attrs) ->
onSuccess = (response) ->
if $routeParams['next'] and $routeParams['next'] != $navUrls.resolve("login")
nextUrl = $routeParams['next']
else
nextUrl = $navUrls.resolve("home")
$events.setupConnection()
$location.path(nextUrl)
onError = (response) ->
$confirm.notify("light-error", "According to our Oompa Loompas, your username/email
or password are incorrect.") #TODO: i18n
submit = debounce 2000, (event) =>
event.preventDefault()
form = new checksley.Form($el.find("form.login-form"))
if not form.validate()
return
data = {
"username": $el.find("form.login-form input[name=username]").val(),
"password": $el.find("form.login-form input[name=password]").val()
}
promise = $auth.login(data)
return promise.then(onSuccess, onError)
$el.on "submit", "form", submit
$el.on "click", ".submit-button", submit
return {link:link}
module.directive("tgLogin", ["$tgAuth", "$tgConfirm", "$tgLocation", "$tgConfig", "$routeParams",
"$tgNavUrls", "$tgEvents", LoginDirective])
#############################################################################
## Register Directive
#############################################################################
RegisterDirective = ($auth, $confirm, $location, $navUrls, $config, $analytics) ->
link = ($scope, $el, $attrs) ->
if not $config.get("publicRegisterEnabled")
$location.path($navUrls.resolve("not-found"))
$location.replace()
$scope.data = {}
form = $el.find("form").checksley({onlyOneErrorElement: true})
onSuccessSubmit = (response) ->
$analytics.trackEvent("auth", "register", "user registration", 1)
$confirm.notify("success", "Our Oompa Loompas are happy, welcome to Taiga.") #TODO: i18n
$location.path($navUrls.resolve("home"))
onErrorSubmit = (response) ->
if response.data._error_message?
$confirm.notify("light-error", "According to our Oompa Loompas there was an error. #{response.data._error_message}") #TODO: i18n
form.setErrors(response.data)
submit = debounce 2000, (event) =>
event.preventDefault()
if not form.validate()
return
promise = $auth.register($scope.data)
promise.then(onSuccessSubmit, onErrorSubmit)
$el.on "submit", "form", submit
$el.on "click", ".submit-button", submit
return {link:link}
module.directive("tgRegister", ["$tgAuth", "$tgConfirm", "$tgLocation", "$tgNavUrls", "$tgConfig",
"$tgAnalytics", RegisterDirective])
#############################################################################
## Forgot Password Directive
#############################################################################
ForgotPasswordDirective = ($auth, $confirm, $location, $navUrls) ->
link = ($scope, $el, $attrs) ->
$scope.data = {}
form = $el.find("form").checksley()
onSuccessSubmit = (response) ->
$location.path($navUrls.resolve("login"))
$confirm.success("<strong>Check your inbox!</strong><br />
We have sent a mail to<br />
<strong>#{response.data.email}</strong><br />
with the instructions to set a new password") #TODO: i18n
onErrorSubmit = (response) ->
$confirm.notify("light-error", "According to our Oompa Loompas,
your are not registered yet.") #TODO: i18n
submit = debounce 2000, (event) =>
event.preventDefault()
if not form.validate()
return
promise = $auth.forgotPassword($scope.data)
promise.then(onSuccessSubmit, onErrorSubmit)
$el.on "submit", "form", submit
$el.on "click", ".submit-button", submit
return {link:link}
module.directive("tgForgotPassword", ["$tgAuth", "$tgConfirm", "$tgLocation", "$tgNavUrls",
ForgotPasswordDirective])
#############################################################################
## Change Password from Recovery Directive
#############################################################################
ChangePasswordFromRecoveryDirective = ($auth, $confirm, $location, $params, $navUrls) ->
link = ($scope, $el, $attrs) ->
$scope.data = {}
if $params.token?
$scope.tokenInParams = true
$scope.data.token = $params.token
else
$scope.tokenInParams = false
form = $el.find("form").checksley()
onSuccessSubmit = (response) ->
$location.path($navUrls.resolve("login"))
$confirm.success("Our Oompa Loompas saved your new password.<br />
Try to <strong>sign in</strong> with it.") #TODO: i18n
onErrorSubmit = (response) ->
$confirm.notify("light-error", "One of our Oompa Loompas say
'#{response.data._error_message}'.") #TODO: i18n
submit = debounce 2000, (event) =>
event.preventDefault()
if not form.validate()
return
promise = $auth.changePasswordFromRecovery($scope.data)
promise.then(onSuccessSubmit, onErrorSubmit)
$el.on "submit", "form", submit
$el.on "click", ".submit-button", submit
return {link:link}
module.directive("tgChangePasswordFromRecovery", ["$tgAuth", "$tgConfirm", "$tgLocation", "$routeParams",
"$tgNavUrls", ChangePasswordFromRecoveryDirective])
#############################################################################
## Invitation
#############################################################################
InvitationDirective = ($auth, $confirm, $location, $params, $navUrls, $analytics) ->
link = ($scope, $el, $attrs) ->
token = $params.token
promise = $auth.getInvitation(token)
promise.then (invitation) ->
$scope.invitation = invitation
promise.then null, (response) ->
$location.path($navUrls.resolve("login"))
$confirm.success("<strong>Ooops, we have a problem</strong><br />
Our Oompa Loompas can't find your invitation.") #TODO: i18n
# Login form
$scope.dataLogin = {token: token}
loginForm = $el.find("form.login-form").checksley({onlyOneErrorElement: true})
onSuccessSubmitLogin = (response) ->
$analytics.trackEvent("auth", "invitationAccept", "invitation accept with existing user", 1)
$location.path($navUrls.resolve("project", {project: $scope.invitation.project_slug}))
$confirm.notify("success", "You've successfully joined this project",
"Welcome to #{_.escape($scope.invitation.project_name)}")
onErrorSubmitLogin = (response) ->
$confirm.notify("light-error", "According to our Oompa Loompas, your are not registered yet or
typed an invalid password.") #TODO: i18n
submitLogin = debounce 2000, (event) =>
event.preventDefault()
if not loginForm.validate()
return
promise = $auth.acceptInvitiationWithExistingUser($scope.dataLogin)
promise.then(onSuccessSubmitLogin, onErrorSubmitLogin)
$el.on "submit", "form.login-form", submitLogin
$el.on "click", ".button-login", submitLogin
# Register form
$scope.dataRegister = {token: token}
registerForm = $el.find("form.register-form").checksley()
onSuccessSubmitRegister = (response) ->
$analytics.trackEvent("auth", "invitationAccept", "invitation accept with new user", 1)
$location.path($navUrls.resolve("project", {project: $scope.invitation.project_slug}))
$confirm.notify("success", "You've successfully joined this project",
"Welcome to #{_.escape($scope.invitation.project_name)}")
onErrorSubmitRegister = (response) ->
$confirm.notify("light-error", "According to our Oompa Loompas, that
username or email is already in use.") #TODO: i18n
submitRegister = debounce 2000, (event) =>
event.preventDefault()
if not registerForm.validate()
return
promise = $auth.acceptInvitiationWithNewUser($scope.dataRegister)
promise.then(onSuccessSubmitRegister, onErrorSubmitRegister)
$el.on "submit", "form.register-form", submitRegister
$el.on "click", ".button-register", submitRegister
return {link:link}
module.directive("tgInvitation", ["$tgAuth", "$tgConfirm", "$tgLocation", "$routeParams",
"$tgNavUrls", "$tgAnalytics", InvitationDirective])
#############################################################################
## Change Email
#############################################################################
ChangeEmailDirective = ($repo, $model, $auth, $confirm, $location, $params, $navUrls) ->
link = ($scope, $el, $attrs) ->
$scope.data = {}
$scope.data.email_token = $params.email_token
form = $el.find("form").checksley()
onSuccessSubmit = (response) ->
$repo.queryOne("users", $auth.getUser().id).then (data) =>
$auth.setUser(data)
$location.path($navUrls.resolve("home"))
$confirm.success("Our Oompa Loompas updated your email") #TODO: i18n
onErrorSubmit = (response) ->
$confirm.notify("error", "One of our Oompa Loompas says
'#{response.data._error_message}'.") #TODO: i18n
submit = ->
if not form.validate()
return
promise = $auth.changeEmail($scope.data)
promise.then(onSuccessSubmit, onErrorSubmit)
$el.on "submit", (event) ->
event.preventDefault()
submit()
$el.on "click", "a.button-change-email", (event) ->
event.preventDefault()
submit()
return {link:link}
module.directive("tgChangeEmail", ["$tgRepo", "$tgModel", "$tgAuth", "$tgConfirm", "$tgLocation", "$routeParams",
"$tgNavUrls", ChangeEmailDirective])
#############################################################################
## Cancel account
#############################################################################
CancelAccountDirective = ($repo, $model, $auth, $confirm, $location, $params, $navUrls) ->
link = ($scope, $el, $attrs) ->
$scope.data = {}
$scope.data.cancel_token = $params.cancel_token
form = $el.find("form").checksley()
onSuccessSubmit = (response) ->
$auth.logout()
$location.path($navUrls.resolve("home"))
$confirm.success("Our Oompa Loompas removed your account") #TODO: i18n
onErrorSubmit = (response) ->
$confirm.notify("error", "One of our Oompa Loompas says
'#{response.data._error_message}'.") #TODO: i18n
submit = debounce 2000, (event) =>
event.preventDefault()
if not form.validate()
return
promise = $auth.cancelAccount($scope.data)
promise.then(onSuccessSubmit, onErrorSubmit)
$el.on "submit", "form", submit
$el.on "click", ".submit-button", submit
return {link:link}
module.directive("tgCancelAccount", ["$tgRepo", "$tgModel", "$tgAuth", "$tgConfirm", "$tgLocation", "$routeParams",
"$tgNavUrls", CancelAccountDirective])
| 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/auth.coffee
###
taiga = @.taiga
debounce = @.taiga.debounce
module = angular.module("taigaAuth", ["taigaResources"])
#############################################################################
## Authentication Service
#############################################################################
class AuthService extends taiga.Service
@.$inject = ["$rootScope",
"$tgStorage",
"$tgModel",
"$tgResources",
"$tgHttp",
"$tgUrls"]
constructor: (@rootscope, @storage, @model, @rs, @http, @urls) ->
super()
getUser: ->
if @rootscope.user
return @rootscope.user
userData = @storage.get("userInfo")
if userData
user = @model.make_model("users", userData)
@rootscope.user = user
return user
return null
setUser: (user) ->
@rootscope.auth = user
@rootscope.$broadcast("i18n:change", user.default_language)
@storage.set("userInfo", user.getAttrs())
@rootscope.user = user
clear: ->
@rootscope.auth = null
@rootscope.user = null
@storage.remove("userInfo")
setToken: (token) ->
@storage.set("token", token)
getToken: ->
return @storage.get("token")
removeToken: ->
@storage.remove("token")
isAuthenticated: ->
if @.getUser() != null
return true
return false
## Http interface
login: (data, type) ->
url = @urls.resolve("auth")
data = _.clone(data, false)
data.type = if type then type else "normal"
@.removeToken()
return @http.post(url, data).then (data, status) =>
user = @model.make_model("users", data.data)
@.setToken(user.auth_token)
@.setUser(user)
return user
logout: ->
@.removeToken()
@.clear()
register: (data, type, existing) ->
url = @urls.resolve("auth-register")
data = _.clone(data, false)
data.type = if type then type else "public"
if type == "private"
data.existing = if existing then existing else false
@.removeToken()
return @http.post(url, data).then (response) =>
user = @model.make_model("users", response.data)
@.setToken(user.auth_token)
@.setUser(user)
return user
getInvitation: (token) ->
return @rs.invitations.get(token)
acceptInvitiationWithNewUser: (data) ->
return @.register(data, "private", false)
acceptInvitiationWithExistingUser: (data) ->
return @.register(data, "private", true)
forgotPassword: (data) ->
url = @urls.resolve("users-password-recovery")
data = _.clone(data, false)
@.removeToken()
return @http.post(url, data)
changePasswordFromRecovery: (data) ->
url = @urls.resolve("users-change-password-from-recovery")
data = _.clone(data, false)
@.removeToken()
return @http.post(url, data)
changeEmail: (data) ->
url = @urls.resolve("users-change-email")
data = _.clone(data, false)
return @http.post(url, data)
cancelAccount: (data) ->
url = @urls.resolve("users-cancel-account")
data = _.clone(data, false)
return @http.post(url, data)
module.service("$tgAuth", AuthService)
#############################################################################
## Login Directive
#############################################################################
# Directive that manages the visualization of public register
# message/link on login page.
PublicRegisterMessageDirective = ($config, $navUrls) ->
template = _.template("""
<p class="login-text">
<span>Not registered yet?</span>
<a href="<%- url %>" tg-nav="register" title="Register"> create your free account here</a>
</p>""")
templateFn = ->
publicRegisterEnabled = $config.get("publicRegisterEnabled")
if not publicRegisterEnabled
return ""
return template({url:$navUrls.resolve("register")})
return {
restrict: "AE"
scope: {}
template: templateFn
}
module.directive("tgPublicRegisterMessage", ["$tgConfig", "$tgNavUrls", PublicRegisterMessageDirective])
LoginDirective = ($auth, $confirm, $location, $config, $routeParams, $navUrls, $events) ->
link = ($scope, $el, $attrs) ->
onSuccess = (response) ->
if $routeParams['next'] and $routeParams['next'] != $navUrls.resolve("login")
nextUrl = $routeParams['next']
else
nextUrl = $navUrls.resolve("home")
$events.setupConnection()
$location.path(nextUrl)
onError = (response) ->
$confirm.notify("light-error", "According to our Oompa Loompas, your username/email
or password are incorrect.") #TODO: i18n
submit = debounce 2000, (event) =>
event.preventDefault()
form = new checksley.Form($el.find("form.login-form"))
if not form.validate()
return
data = {
"username": $el.find("form.login-form input[name=username]").val(),
"password": $el.find("form.login-form input[name=password]").val()
}
promise = $auth.login(data)
return promise.then(onSuccess, onError)
$el.on "submit", "form", submit
$el.on "click", ".submit-button", submit
return {link:link}
module.directive("tgLogin", ["$tgAuth", "$tgConfirm", "$tgLocation", "$tgConfig", "$routeParams",
"$tgNavUrls", "$tgEvents", LoginDirective])
#############################################################################
## Register Directive
#############################################################################
RegisterDirective = ($auth, $confirm, $location, $navUrls, $config, $analytics) ->
link = ($scope, $el, $attrs) ->
if not $config.get("publicRegisterEnabled")
$location.path($navUrls.resolve("not-found"))
$location.replace()
$scope.data = {}
form = $el.find("form").checksley({onlyOneErrorElement: true})
onSuccessSubmit = (response) ->
$analytics.trackEvent("auth", "register", "user registration", 1)
$confirm.notify("success", "Our Oompa Loompas are happy, welcome to Taiga.") #TODO: i18n
$location.path($navUrls.resolve("home"))
onErrorSubmit = (response) ->
if response.data._error_message?
$confirm.notify("light-error", "According to our Oompa Loompas there was an error. #{response.data._error_message}") #TODO: i18n
form.setErrors(response.data)
submit = debounce 2000, (event) =>
event.preventDefault()
if not form.validate()
return
promise = $auth.register($scope.data)
promise.then(onSuccessSubmit, onErrorSubmit)
$el.on "submit", "form", submit
$el.on "click", ".submit-button", submit
return {link:link}
module.directive("tgRegister", ["$tgAuth", "$tgConfirm", "$tgLocation", "$tgNavUrls", "$tgConfig",
"$tgAnalytics", RegisterDirective])
#############################################################################
## Forgot Password Directive
#############################################################################
ForgotPasswordDirective = ($auth, $confirm, $location, $navUrls) ->
link = ($scope, $el, $attrs) ->
$scope.data = {}
form = $el.find("form").checksley()
onSuccessSubmit = (response) ->
$location.path($navUrls.resolve("login"))
$confirm.success("<strong>Check your inbox!</strong><br />
We have sent a mail to<br />
<strong>#{response.data.email}</strong><br />
with the instructions to set a new password") #TODO: i18n
onErrorSubmit = (response) ->
$confirm.notify("light-error", "According to our Oompa Loompas,
your are not registered yet.") #TODO: i18n
submit = debounce 2000, (event) =>
event.preventDefault()
if not form.validate()
return
promise = $auth.forgotPassword($scope.data)
promise.then(onSuccessSubmit, onErrorSubmit)
$el.on "submit", "form", submit
$el.on "click", ".submit-button", submit
return {link:link}
module.directive("tgForgotPassword", ["$tgAuth", "$tgConfirm", "$tgLocation", "$tgNavUrls",
ForgotPasswordDirective])
#############################################################################
## Change Password from Recovery Directive
#############################################################################
ChangePasswordFromRecoveryDirective = ($auth, $confirm, $location, $params, $navUrls) ->
link = ($scope, $el, $attrs) ->
$scope.data = {}
if $params.token?
$scope.tokenInParams = true
$scope.data.token = $params.token
else
$scope.tokenInParams = false
form = $el.find("form").checksley()
onSuccessSubmit = (response) ->
$location.path($navUrls.resolve("login"))
$confirm.success("Our Oompa Loompas saved your new password.<br />
Try to <strong>sign in</strong> with it.") #TODO: i18n
onErrorSubmit = (response) ->
$confirm.notify("light-error", "One of our Oompa Loompas say
'#{response.data._error_message}'.") #TODO: i18n
submit = debounce 2000, (event) =>
event.preventDefault()
if not form.validate()
return
promise = $auth.changePasswordFromRecovery($scope.data)
promise.then(onSuccessSubmit, onErrorSubmit)
$el.on "submit", "form", submit
$el.on "click", ".submit-button", submit
return {link:link}
module.directive("tgChangePasswordFromRecovery", ["$tgAuth", "$tgConfirm", "$tgLocation", "$routeParams",
"$tgNavUrls", ChangePasswordFromRecoveryDirective])
#############################################################################
## Invitation
#############################################################################
InvitationDirective = ($auth, $confirm, $location, $params, $navUrls, $analytics) ->
link = ($scope, $el, $attrs) ->
token = $params.token
promise = $auth.getInvitation(token)
promise.then (invitation) ->
$scope.invitation = invitation
promise.then null, (response) ->
$location.path($navUrls.resolve("login"))
$confirm.success("<strong>Ooops, we have a problem</strong><br />
Our Oompa Loompas can't find your invitation.") #TODO: i18n
# Login form
$scope.dataLogin = {token: token}
loginForm = $el.find("form.login-form").checksley({onlyOneErrorElement: true})
onSuccessSubmitLogin = (response) ->
$analytics.trackEvent("auth", "invitationAccept", "invitation accept with existing user", 1)
$location.path($navUrls.resolve("project", {project: $scope.invitation.project_slug}))
$confirm.notify("success", "You've successfully joined this project",
"Welcome to #{_.escape($scope.invitation.project_name)}")
onErrorSubmitLogin = (response) ->
$confirm.notify("light-error", "According to our Oompa Loompas, your are not registered yet or
typed an invalid password.") #TODO: i18n
submitLogin = debounce 2000, (event) =>
event.preventDefault()
if not loginForm.validate()
return
promise = $auth.acceptInvitiationWithExistingUser($scope.dataLogin)
promise.then(onSuccessSubmitLogin, onErrorSubmitLogin)
$el.on "submit", "form.login-form", submitLogin
$el.on "click", ".button-login", submitLogin
# Register form
$scope.dataRegister = {token: token}
registerForm = $el.find("form.register-form").checksley()
onSuccessSubmitRegister = (response) ->
$analytics.trackEvent("auth", "invitationAccept", "invitation accept with new user", 1)
$location.path($navUrls.resolve("project", {project: $scope.invitation.project_slug}))
$confirm.notify("success", "You've successfully joined this project",
"Welcome to #{_.escape($scope.invitation.project_name)}")
onErrorSubmitRegister = (response) ->
$confirm.notify("light-error", "According to our Oompa Loompas, that
username or email is already in use.") #TODO: i18n
submitRegister = debounce 2000, (event) =>
event.preventDefault()
if not registerForm.validate()
return
promise = $auth.acceptInvitiationWithNewUser($scope.dataRegister)
promise.then(onSuccessSubmitRegister, onErrorSubmitRegister)
$el.on "submit", "form.register-form", submitRegister
$el.on "click", ".button-register", submitRegister
return {link:link}
module.directive("tgInvitation", ["$tgAuth", "$tgConfirm", "$tgLocation", "$routeParams",
"$tgNavUrls", "$tgAnalytics", InvitationDirective])
#############################################################################
## Change Email
#############################################################################
ChangeEmailDirective = ($repo, $model, $auth, $confirm, $location, $params, $navUrls) ->
link = ($scope, $el, $attrs) ->
$scope.data = {}
$scope.data.email_token = $params.email_token
form = $el.find("form").checksley()
onSuccessSubmit = (response) ->
$repo.queryOne("users", $auth.getUser().id).then (data) =>
$auth.setUser(data)
$location.path($navUrls.resolve("home"))
$confirm.success("Our Oompa Loompas updated your email") #TODO: i18n
onErrorSubmit = (response) ->
$confirm.notify("error", "One of our Oompa Loompas says
'#{response.data._error_message}'.") #TODO: i18n
submit = ->
if not form.validate()
return
promise = $auth.changeEmail($scope.data)
promise.then(onSuccessSubmit, onErrorSubmit)
$el.on "submit", (event) ->
event.preventDefault()
submit()
$el.on "click", "a.button-change-email", (event) ->
event.preventDefault()
submit()
return {link:link}
module.directive("tgChangeEmail", ["$tgRepo", "$tgModel", "$tgAuth", "$tgConfirm", "$tgLocation", "$routeParams",
"$tgNavUrls", ChangeEmailDirective])
#############################################################################
## Cancel account
#############################################################################
CancelAccountDirective = ($repo, $model, $auth, $confirm, $location, $params, $navUrls) ->
link = ($scope, $el, $attrs) ->
$scope.data = {}
$scope.data.cancel_token = $params.cancel_token
form = $el.find("form").checksley()
onSuccessSubmit = (response) ->
$auth.logout()
$location.path($navUrls.resolve("home"))
$confirm.success("Our Oompa Loompas removed your account") #TODO: i18n
onErrorSubmit = (response) ->
$confirm.notify("error", "One of our Oompa Loompas says
'#{response.data._error_message}'.") #TODO: i18n
submit = debounce 2000, (event) =>
event.preventDefault()
if not form.validate()
return
promise = $auth.cancelAccount($scope.data)
promise.then(onSuccessSubmit, onErrorSubmit)
$el.on "submit", "form", submit
$el.on "click", ".submit-button", submit
return {link:link}
module.directive("tgCancelAccount", ["$tgRepo", "$tgModel", "$tgAuth", "$tgConfirm", "$tgLocation", "$routeParams",
"$tgNavUrls", CancelAccountDirective])
|
[
{
"context": " token: $stateParams.token, pass: $scope.userData.password\n }).then ->\n $scope.processing = ",
"end": 533,
"score": 0.8250743746757507,
"start": 525,
"tag": "PASSWORD",
"value": "password"
}
] | src/controllers/public/reset.coffee | ah450/guclink-auth-www | 0 | angular.module 'guclinkAuth'
.controller 'ResetController', ($scope, AUTH_BASE_URL, $stateParams,
$timeout, $state, $http, authConfigurations) ->
$scope.processing = false
$scope.done = false
$scope.userData = {}
$scope.resetPassword = ->
return if $scope.processing
$scope.processing = true
url = [AUTH_BASE_URL, 'users', "#{$stateParams.id}",
'confirm_reset.json'].join '/'
$http.put(url, {
token: $stateParams.token, pass: $scope.userData.password
}).then ->
$scope.processing = false
$scope.done = true
$timeout ->
$state.go 'public.login'
, 800
.catch (response) ->
if response.status is 404
$scope.processing = false
$scope.error = 'User does not exist'
else if response.status is 422
$scope.processing = false
$scope.error = response.data.message
else if response.status is 420
authConfigurations.then (config) ->
$scope.error = "Token only valid for " +
"#{config.pass_reset_expiration / 60} minutes"
$scope.processing = false
else
$state.go 'public.internal_error'
| 62984 | angular.module 'guclinkAuth'
.controller 'ResetController', ($scope, AUTH_BASE_URL, $stateParams,
$timeout, $state, $http, authConfigurations) ->
$scope.processing = false
$scope.done = false
$scope.userData = {}
$scope.resetPassword = ->
return if $scope.processing
$scope.processing = true
url = [AUTH_BASE_URL, 'users', "#{$stateParams.id}",
'confirm_reset.json'].join '/'
$http.put(url, {
token: $stateParams.token, pass: $scope.userData.<PASSWORD>
}).then ->
$scope.processing = false
$scope.done = true
$timeout ->
$state.go 'public.login'
, 800
.catch (response) ->
if response.status is 404
$scope.processing = false
$scope.error = 'User does not exist'
else if response.status is 422
$scope.processing = false
$scope.error = response.data.message
else if response.status is 420
authConfigurations.then (config) ->
$scope.error = "Token only valid for " +
"#{config.pass_reset_expiration / 60} minutes"
$scope.processing = false
else
$state.go 'public.internal_error'
| true | angular.module 'guclinkAuth'
.controller 'ResetController', ($scope, AUTH_BASE_URL, $stateParams,
$timeout, $state, $http, authConfigurations) ->
$scope.processing = false
$scope.done = false
$scope.userData = {}
$scope.resetPassword = ->
return if $scope.processing
$scope.processing = true
url = [AUTH_BASE_URL, 'users', "#{$stateParams.id}",
'confirm_reset.json'].join '/'
$http.put(url, {
token: $stateParams.token, pass: $scope.userData.PI:PASSWORD:<PASSWORD>END_PI
}).then ->
$scope.processing = false
$scope.done = true
$timeout ->
$state.go 'public.login'
, 800
.catch (response) ->
if response.status is 404
$scope.processing = false
$scope.error = 'User does not exist'
else if response.status is 422
$scope.processing = false
$scope.error = response.data.message
else if response.status is 420
authConfigurations.then (config) ->
$scope.error = "Token only valid for " +
"#{config.pass_reset_expiration / 60} minutes"
$scope.processing = false
else
$state.go 'public.internal_error'
|
[
{
"context": "ror\n contents = {\n name: \"Untitled Note\"\n content: raw.toString()\n",
"end": 4201,
"score": 0.6832018494606018,
"start": 4198,
"tag": "NAME",
"value": "Unt"
}
] | app/controllers/upgrader.coffee | sarthakganguly/notes | 191 | ###############
# If you're reading this code, and you're like
# ERMAGERD, WHY IS THIS IDIOT USING NODE.JS, S`NOT EVEN ASYNC!!11!!
# Well, it's because Spine doesn't work too well when it's async.
# Not sure why, it just loves to run out of memory and crash.
###############
Spine = require 'spine'
marked = require 'marked'
Note = require '../models/note.coffee'
Notebook = require '../models/notebook.coffee'
class window.upgrader extends Spine.Controller
constructor: ->
super
notebookPromise = new $.Deferred()
notePromise = new $.Deferred()
Spine.bind "Notebook:ready", notebookPromise.resolve
Spine.bind "Note:ready", notePromise.resolve
$.when.apply($, [notebookPromise.promise(), notePromise.promise()]).then =>
@upgrade(localStorage.version)
localStorage.version = "2.0"
upgrade: (version) ->
# New install, add default notes
if version is undefined
for notebook in ['Personal', 'Scrap', 'Work']
Notebook.create
name: notebook
attributes: {starred: false}
categories: ["General"]
date: Math.round(new Date()/1000)
# Semi Ajaxed in, rather than hardcoded.
$.getJSON('default.json').done (data) ->
for defaultNote in data
note = Note.create
name: defaultNote.name
excerpt: defaultNote.content.substring(0, 100)
notebook: 'c-2'
category: 'General'
date: Math.round(new Date().getTime()/1000)
note.saveNote defaultNote.content
# For whatever reason, it doesn't reload afterwards?
$("#notebook-all").trigger("click")
else if version is "1.1"
console.log "Upgrading DB"
for note in Note.toJSON()
note = Note.create
name: note.name
starred: false
categories: note.categories
date: note.date
Note.find(note.id).destroy()
$.getJSON('default.json').done (data) ->
for defaultNote in data
note = Note.create
name: defaultNote.name
excerpt: defaultNote.content.substring(0, 100)
notebook: 'c-2'
category: 'General'
date: Math.round(new Date().getTime()/1000)
note.saveNote defaultNote.content
# For whatever reason, it doesn't reload afterwards?
$("#notebook-all").trigger("click")
else if version is "1.0"
path = window.require 'path'
fs = window.require 'fs'
# Make variables. Do checks.
homedir = window.process.env.HOME
# Set up where we're going to store stuff.
if window.process.platform is 'darwin'
storagedir = path.join(homedir, "/Library/Application Support/Springseed/")
else if window.process.platform is 'win32'
storagedir = path.join(process.env.LOCALAPPDATA, "/Springseed/")
else if window.process.platform is 'linux'
storagedir = path.join(homedir, '/.config/Springseed/')
notebookdir = path.join(storagedir, 'Notebooks')
notebooks = {}
files = fs.readdirSync notebookdir
files.forEach (file) =>
if file.substr(16,5) is ".list"
# Read the file, syncronously.
data = fs.readFileSync path.join(notebookdir, file)
console.log data.toString()
# Read the old notebook, create a new spine model
try
oldnotebook = JSON.parse(data)
newNotebook = Notebook.create
name: oldnotebook.name
categories: ["General"]
date: Math.round(new Date()/1000)
# Our mapping array to show the new positions
notebooks[oldnotebook.id] = newNotebook.id
catch error
console.log("there was an error", id)
# Eh, what can we do?
return
# Load the notes from the notebook into the model
files.forEach (file) =>
if file.substr(33,5) is ".note"
raw = fs.readFileSync path.join(notebookdir, file)
try
contents = JSON.parse(raw)
contents.notebook = notebooks[contents.notebook]
catch error
contents = {
name: "Untitled Note"
content: raw.toString()
date: Math.round(new Date()/1000)
notebook: Notebook.all()[0].id
}
note = Note.create
name: contents.name
excerpt: $(marked(contents.content.substring(0,100))).text()
notebook: contents.notebook
category: "General"
date: contents.date
note.saveNote(contents.content)
module.exports = upgrader
| 59016 | ###############
# If you're reading this code, and you're like
# ERMAGERD, WHY IS THIS IDIOT USING NODE.JS, S`NOT EVEN ASYNC!!11!!
# Well, it's because Spine doesn't work too well when it's async.
# Not sure why, it just loves to run out of memory and crash.
###############
Spine = require 'spine'
marked = require 'marked'
Note = require '../models/note.coffee'
Notebook = require '../models/notebook.coffee'
class window.upgrader extends Spine.Controller
constructor: ->
super
notebookPromise = new $.Deferred()
notePromise = new $.Deferred()
Spine.bind "Notebook:ready", notebookPromise.resolve
Spine.bind "Note:ready", notePromise.resolve
$.when.apply($, [notebookPromise.promise(), notePromise.promise()]).then =>
@upgrade(localStorage.version)
localStorage.version = "2.0"
upgrade: (version) ->
# New install, add default notes
if version is undefined
for notebook in ['Personal', 'Scrap', 'Work']
Notebook.create
name: notebook
attributes: {starred: false}
categories: ["General"]
date: Math.round(new Date()/1000)
# Semi Ajaxed in, rather than hardcoded.
$.getJSON('default.json').done (data) ->
for defaultNote in data
note = Note.create
name: defaultNote.name
excerpt: defaultNote.content.substring(0, 100)
notebook: 'c-2'
category: 'General'
date: Math.round(new Date().getTime()/1000)
note.saveNote defaultNote.content
# For whatever reason, it doesn't reload afterwards?
$("#notebook-all").trigger("click")
else if version is "1.1"
console.log "Upgrading DB"
for note in Note.toJSON()
note = Note.create
name: note.name
starred: false
categories: note.categories
date: note.date
Note.find(note.id).destroy()
$.getJSON('default.json').done (data) ->
for defaultNote in data
note = Note.create
name: defaultNote.name
excerpt: defaultNote.content.substring(0, 100)
notebook: 'c-2'
category: 'General'
date: Math.round(new Date().getTime()/1000)
note.saveNote defaultNote.content
# For whatever reason, it doesn't reload afterwards?
$("#notebook-all").trigger("click")
else if version is "1.0"
path = window.require 'path'
fs = window.require 'fs'
# Make variables. Do checks.
homedir = window.process.env.HOME
# Set up where we're going to store stuff.
if window.process.platform is 'darwin'
storagedir = path.join(homedir, "/Library/Application Support/Springseed/")
else if window.process.platform is 'win32'
storagedir = path.join(process.env.LOCALAPPDATA, "/Springseed/")
else if window.process.platform is 'linux'
storagedir = path.join(homedir, '/.config/Springseed/')
notebookdir = path.join(storagedir, 'Notebooks')
notebooks = {}
files = fs.readdirSync notebookdir
files.forEach (file) =>
if file.substr(16,5) is ".list"
# Read the file, syncronously.
data = fs.readFileSync path.join(notebookdir, file)
console.log data.toString()
# Read the old notebook, create a new spine model
try
oldnotebook = JSON.parse(data)
newNotebook = Notebook.create
name: oldnotebook.name
categories: ["General"]
date: Math.round(new Date()/1000)
# Our mapping array to show the new positions
notebooks[oldnotebook.id] = newNotebook.id
catch error
console.log("there was an error", id)
# Eh, what can we do?
return
# Load the notes from the notebook into the model
files.forEach (file) =>
if file.substr(33,5) is ".note"
raw = fs.readFileSync path.join(notebookdir, file)
try
contents = JSON.parse(raw)
contents.notebook = notebooks[contents.notebook]
catch error
contents = {
name: "<NAME>itled Note"
content: raw.toString()
date: Math.round(new Date()/1000)
notebook: Notebook.all()[0].id
}
note = Note.create
name: contents.name
excerpt: $(marked(contents.content.substring(0,100))).text()
notebook: contents.notebook
category: "General"
date: contents.date
note.saveNote(contents.content)
module.exports = upgrader
| true | ###############
# If you're reading this code, and you're like
# ERMAGERD, WHY IS THIS IDIOT USING NODE.JS, S`NOT EVEN ASYNC!!11!!
# Well, it's because Spine doesn't work too well when it's async.
# Not sure why, it just loves to run out of memory and crash.
###############
Spine = require 'spine'
marked = require 'marked'
Note = require '../models/note.coffee'
Notebook = require '../models/notebook.coffee'
class window.upgrader extends Spine.Controller
constructor: ->
super
notebookPromise = new $.Deferred()
notePromise = new $.Deferred()
Spine.bind "Notebook:ready", notebookPromise.resolve
Spine.bind "Note:ready", notePromise.resolve
$.when.apply($, [notebookPromise.promise(), notePromise.promise()]).then =>
@upgrade(localStorage.version)
localStorage.version = "2.0"
upgrade: (version) ->
# New install, add default notes
if version is undefined
for notebook in ['Personal', 'Scrap', 'Work']
Notebook.create
name: notebook
attributes: {starred: false}
categories: ["General"]
date: Math.round(new Date()/1000)
# Semi Ajaxed in, rather than hardcoded.
$.getJSON('default.json').done (data) ->
for defaultNote in data
note = Note.create
name: defaultNote.name
excerpt: defaultNote.content.substring(0, 100)
notebook: 'c-2'
category: 'General'
date: Math.round(new Date().getTime()/1000)
note.saveNote defaultNote.content
# For whatever reason, it doesn't reload afterwards?
$("#notebook-all").trigger("click")
else if version is "1.1"
console.log "Upgrading DB"
for note in Note.toJSON()
note = Note.create
name: note.name
starred: false
categories: note.categories
date: note.date
Note.find(note.id).destroy()
$.getJSON('default.json').done (data) ->
for defaultNote in data
note = Note.create
name: defaultNote.name
excerpt: defaultNote.content.substring(0, 100)
notebook: 'c-2'
category: 'General'
date: Math.round(new Date().getTime()/1000)
note.saveNote defaultNote.content
# For whatever reason, it doesn't reload afterwards?
$("#notebook-all").trigger("click")
else if version is "1.0"
path = window.require 'path'
fs = window.require 'fs'
# Make variables. Do checks.
homedir = window.process.env.HOME
# Set up where we're going to store stuff.
if window.process.platform is 'darwin'
storagedir = path.join(homedir, "/Library/Application Support/Springseed/")
else if window.process.platform is 'win32'
storagedir = path.join(process.env.LOCALAPPDATA, "/Springseed/")
else if window.process.platform is 'linux'
storagedir = path.join(homedir, '/.config/Springseed/')
notebookdir = path.join(storagedir, 'Notebooks')
notebooks = {}
files = fs.readdirSync notebookdir
files.forEach (file) =>
if file.substr(16,5) is ".list"
# Read the file, syncronously.
data = fs.readFileSync path.join(notebookdir, file)
console.log data.toString()
# Read the old notebook, create a new spine model
try
oldnotebook = JSON.parse(data)
newNotebook = Notebook.create
name: oldnotebook.name
categories: ["General"]
date: Math.round(new Date()/1000)
# Our mapping array to show the new positions
notebooks[oldnotebook.id] = newNotebook.id
catch error
console.log("there was an error", id)
# Eh, what can we do?
return
# Load the notes from the notebook into the model
files.forEach (file) =>
if file.substr(33,5) is ".note"
raw = fs.readFileSync path.join(notebookdir, file)
try
contents = JSON.parse(raw)
contents.notebook = notebooks[contents.notebook]
catch error
contents = {
name: "PI:NAME:<NAME>END_PIitled Note"
content: raw.toString()
date: Math.round(new Date()/1000)
notebook: Notebook.all()[0].id
}
note = Note.create
name: contents.name
excerpt: $(marked(contents.content.substring(0,100))).text()
notebook: contents.notebook
category: "General"
date: contents.date
note.saveNote(contents.content)
module.exports = upgrader
|
[
{
"context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Cof",
"end": 23,
"score": 0.9998793005943298,
"start": 13,
"tag": "NAME",
"value": "Mat Groves"
},
{
"context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Coffixi/primitives/G",
"end": 40,
"score": 0.9054906368255615,
"start": 34,
"tag": "USERNAME",
"value": "groves"
},
{
"context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Coffixi/primitives/Graphics', [\n 'C",
"end": 56,
"score": 0.9993705153465271,
"start": 46,
"tag": "USERNAME",
"value": "@Doormat23"
}
] | src/Coffixi/primitives/Graphics.coffee | namuol/Coffixi | 1 | ###*
@author Mat Groves http://matgroves.com/ @Doormat23
###
define 'Coffixi/primitives/Graphics', [
'Coffixi/display/DisplayObjectContainer'
'Coffixi/core/RenderTypes'
], (
DisplayObjectContainer
RenderTypes
) ->
###*
The Graphics class contains a set of methods that you can use to create primitive shapes and lines.
It is important to know that with the webGL renderer only simple polys can be filled at this stage
Complex polys will not be filled. Heres an example of a complex poly: http://www.goodboydigital.com/wp-content/uploads/2013/06/complexPolygon.png
@class Graphics
@extends DisplayObjectContainer
@constructor
###
class Graphics extends DisplayObjectContainer
__renderType: RenderTypes.GRAPHICS
# SOME TYPES:
@POLY: 0
@RECT: 1
@CIRC: 2
@ELIP: 3
constructor: ->
super
@renderable = true
###*
The alpha of the fill of this graphics object
@property fillAlpha
@type Number
###
@fillAlpha = 1
###*
The width of any lines drawn
@property lineWidth
@type Number
###
@lineWidth = 0
###*
The color of any lines drawn
@property lineColor
@type String
###
@lineColor = 'black'
###*
Graphics data
@property graphicsData
@type Array
@private
###
@graphicsData = []
###*
Current path
@property currentPath
@type Object
@private
###
@currentPath = points: []
###*
Specifies a line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method.
@method lineStyle
@param lineWidth {Number} width of the line to draw, will update the object's stored style
@param color {Number} color of the line to draw, will update the object's stored style
@param alpha {Number} alpha of the line to draw, will update the object's stored style
###
lineStyle: (lineWidth, color, alpha) ->
@graphicsData.pop() if @currentPath.points.length is 0
@lineWidth = lineWidth or 0
@lineColor = color or 0
@lineAlpha = (if (alpha is `undefined`) then 1 else alpha)
@currentPath =
lineWidth: @lineWidth
lineColor: @lineColor
lineAlpha: @lineAlpha
fillColor: @fillColor
fillAlpha: @fillAlpha
fill: @filling
points: []
type: Graphics.POLY
@graphicsData.push @currentPath
###*
Moves the current drawing position to (x, y).
@method moveTo
@param x {Number} the X coord to move to
@param y {Number} the Y coord to move to
###
moveTo: (x, y) ->
@graphicsData.pop() if @currentPath.points.length is 0
@currentPath = @currentPath =
lineWidth: @lineWidth
lineColor: @lineColor
lineAlpha: @lineAlpha
fillColor: @fillColor
fillAlpha: @fillAlpha
fill: @filling
points: []
type: Graphics.POLY
@currentPath.points.push x, y
@graphicsData.push @currentPath
###*
Draws a line using the current line style from the current drawing position to (x, y);
the current drawing position is then set to (x, y).
@method lineTo
@param x {Number} the X coord to draw to
@param y {Number} the Y coord to draw to
###
lineTo: (x, y) ->
@currentPath.points.push x, y
@dirty = true
###*
Specifies a simple one-color fill that subsequent calls to other Graphics methods
(such as lineTo() or drawCircle()) use when drawing.
@method beginFill
@param color {uint} the color of the fill
@param alpha {Number} the alpha
###
beginFill: (color, alpha) ->
@filling = true
@fillColor = color or 0
@fillAlpha = alpha ? 1
###*
Applies a fill to the lines and shapes that were added since the last call to the beginFill() method.
@method endFill
###
endFill: ->
@filling = false
@fillColor = null
@fillAlpha = 1
###*
@method drawRect
@param x {Number} The X coord of the top-left of the rectangle
@param y {Number} The Y coord of the top-left of the rectangle
@param width {Number} The width of the rectangle
@param height {Number} The height of the rectangle
###
drawRect: (x, y, width, height) ->
@graphicsData.pop() if @currentPath.points.length is 0
@currentPath =
lineWidth: @lineWidth
lineColor: @lineColor
lineAlpha: @lineAlpha
fillColor: @fillColor
fillAlpha: @fillAlpha
fill: @filling
points: [x, y, width, height]
type: Graphics.RECT
@graphicsData.push @currentPath
@dirty = true
###*
Draws a circle.
@method drawCircle
@param x {Number} The X coord of the center of the circle
@param y {Number} The Y coord of the center of the circle
@param radius {Number} The radius of the circle
###
drawCircle: (x, y, radius) ->
@graphicsData.pop() if @currentPath.points.length is 0
@currentPath =
lineWidth: @lineWidth
lineColor: @lineColor
lineAlpha: @lineAlpha
fillColor: @fillColor
fillAlpha: @fillAlpha
fill: @filling
points: [x, y, radius, radius]
type: Graphics.CIRC
@graphicsData.push @currentPath
@dirty = true
###*
Draws an elipse.
@method drawElipse
@param x {Number}
@param y {Number}
@param width {Number}
@param height {Number}
###
drawElipse: (x, y, width, height) ->
@graphicsData.pop() if @currentPath.points.length is 0
@currentPath =
lineWidth: @lineWidth
lineColor: @lineColor
lineAlpha: @lineAlpha
fillColor: @fillColor
fillAlpha: @fillAlpha
fill: @filling
points: [x, y, width, height]
type: Graphics.ELIP
@graphicsData.push @currentPath
@dirty = true
###*
Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
@method clear
###
clear: ->
@lineWidth = 0
@filling = false
@dirty = true
@clearDirty = true
@graphicsData = []
| 70781 | ###*
@author <NAME> http://matgroves.com/ @Doormat23
###
define 'Coffixi/primitives/Graphics', [
'Coffixi/display/DisplayObjectContainer'
'Coffixi/core/RenderTypes'
], (
DisplayObjectContainer
RenderTypes
) ->
###*
The Graphics class contains a set of methods that you can use to create primitive shapes and lines.
It is important to know that with the webGL renderer only simple polys can be filled at this stage
Complex polys will not be filled. Heres an example of a complex poly: http://www.goodboydigital.com/wp-content/uploads/2013/06/complexPolygon.png
@class Graphics
@extends DisplayObjectContainer
@constructor
###
class Graphics extends DisplayObjectContainer
__renderType: RenderTypes.GRAPHICS
# SOME TYPES:
@POLY: 0
@RECT: 1
@CIRC: 2
@ELIP: 3
constructor: ->
super
@renderable = true
###*
The alpha of the fill of this graphics object
@property fillAlpha
@type Number
###
@fillAlpha = 1
###*
The width of any lines drawn
@property lineWidth
@type Number
###
@lineWidth = 0
###*
The color of any lines drawn
@property lineColor
@type String
###
@lineColor = 'black'
###*
Graphics data
@property graphicsData
@type Array
@private
###
@graphicsData = []
###*
Current path
@property currentPath
@type Object
@private
###
@currentPath = points: []
###*
Specifies a line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method.
@method lineStyle
@param lineWidth {Number} width of the line to draw, will update the object's stored style
@param color {Number} color of the line to draw, will update the object's stored style
@param alpha {Number} alpha of the line to draw, will update the object's stored style
###
lineStyle: (lineWidth, color, alpha) ->
@graphicsData.pop() if @currentPath.points.length is 0
@lineWidth = lineWidth or 0
@lineColor = color or 0
@lineAlpha = (if (alpha is `undefined`) then 1 else alpha)
@currentPath =
lineWidth: @lineWidth
lineColor: @lineColor
lineAlpha: @lineAlpha
fillColor: @fillColor
fillAlpha: @fillAlpha
fill: @filling
points: []
type: Graphics.POLY
@graphicsData.push @currentPath
###*
Moves the current drawing position to (x, y).
@method moveTo
@param x {Number} the X coord to move to
@param y {Number} the Y coord to move to
###
moveTo: (x, y) ->
@graphicsData.pop() if @currentPath.points.length is 0
@currentPath = @currentPath =
lineWidth: @lineWidth
lineColor: @lineColor
lineAlpha: @lineAlpha
fillColor: @fillColor
fillAlpha: @fillAlpha
fill: @filling
points: []
type: Graphics.POLY
@currentPath.points.push x, y
@graphicsData.push @currentPath
###*
Draws a line using the current line style from the current drawing position to (x, y);
the current drawing position is then set to (x, y).
@method lineTo
@param x {Number} the X coord to draw to
@param y {Number} the Y coord to draw to
###
lineTo: (x, y) ->
@currentPath.points.push x, y
@dirty = true
###*
Specifies a simple one-color fill that subsequent calls to other Graphics methods
(such as lineTo() or drawCircle()) use when drawing.
@method beginFill
@param color {uint} the color of the fill
@param alpha {Number} the alpha
###
beginFill: (color, alpha) ->
@filling = true
@fillColor = color or 0
@fillAlpha = alpha ? 1
###*
Applies a fill to the lines and shapes that were added since the last call to the beginFill() method.
@method endFill
###
endFill: ->
@filling = false
@fillColor = null
@fillAlpha = 1
###*
@method drawRect
@param x {Number} The X coord of the top-left of the rectangle
@param y {Number} The Y coord of the top-left of the rectangle
@param width {Number} The width of the rectangle
@param height {Number} The height of the rectangle
###
drawRect: (x, y, width, height) ->
@graphicsData.pop() if @currentPath.points.length is 0
@currentPath =
lineWidth: @lineWidth
lineColor: @lineColor
lineAlpha: @lineAlpha
fillColor: @fillColor
fillAlpha: @fillAlpha
fill: @filling
points: [x, y, width, height]
type: Graphics.RECT
@graphicsData.push @currentPath
@dirty = true
###*
Draws a circle.
@method drawCircle
@param x {Number} The X coord of the center of the circle
@param y {Number} The Y coord of the center of the circle
@param radius {Number} The radius of the circle
###
drawCircle: (x, y, radius) ->
@graphicsData.pop() if @currentPath.points.length is 0
@currentPath =
lineWidth: @lineWidth
lineColor: @lineColor
lineAlpha: @lineAlpha
fillColor: @fillColor
fillAlpha: @fillAlpha
fill: @filling
points: [x, y, radius, radius]
type: Graphics.CIRC
@graphicsData.push @currentPath
@dirty = true
###*
Draws an elipse.
@method drawElipse
@param x {Number}
@param y {Number}
@param width {Number}
@param height {Number}
###
drawElipse: (x, y, width, height) ->
@graphicsData.pop() if @currentPath.points.length is 0
@currentPath =
lineWidth: @lineWidth
lineColor: @lineColor
lineAlpha: @lineAlpha
fillColor: @fillColor
fillAlpha: @fillAlpha
fill: @filling
points: [x, y, width, height]
type: Graphics.ELIP
@graphicsData.push @currentPath
@dirty = true
###*
Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
@method clear
###
clear: ->
@lineWidth = 0
@filling = false
@dirty = true
@clearDirty = true
@graphicsData = []
| true | ###*
@author PI:NAME:<NAME>END_PI http://matgroves.com/ @Doormat23
###
define 'Coffixi/primitives/Graphics', [
'Coffixi/display/DisplayObjectContainer'
'Coffixi/core/RenderTypes'
], (
DisplayObjectContainer
RenderTypes
) ->
###*
The Graphics class contains a set of methods that you can use to create primitive shapes and lines.
It is important to know that with the webGL renderer only simple polys can be filled at this stage
Complex polys will not be filled. Heres an example of a complex poly: http://www.goodboydigital.com/wp-content/uploads/2013/06/complexPolygon.png
@class Graphics
@extends DisplayObjectContainer
@constructor
###
class Graphics extends DisplayObjectContainer
__renderType: RenderTypes.GRAPHICS
# SOME TYPES:
@POLY: 0
@RECT: 1
@CIRC: 2
@ELIP: 3
constructor: ->
super
@renderable = true
###*
The alpha of the fill of this graphics object
@property fillAlpha
@type Number
###
@fillAlpha = 1
###*
The width of any lines drawn
@property lineWidth
@type Number
###
@lineWidth = 0
###*
The color of any lines drawn
@property lineColor
@type String
###
@lineColor = 'black'
###*
Graphics data
@property graphicsData
@type Array
@private
###
@graphicsData = []
###*
Current path
@property currentPath
@type Object
@private
###
@currentPath = points: []
###*
Specifies a line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method.
@method lineStyle
@param lineWidth {Number} width of the line to draw, will update the object's stored style
@param color {Number} color of the line to draw, will update the object's stored style
@param alpha {Number} alpha of the line to draw, will update the object's stored style
###
lineStyle: (lineWidth, color, alpha) ->
@graphicsData.pop() if @currentPath.points.length is 0
@lineWidth = lineWidth or 0
@lineColor = color or 0
@lineAlpha = (if (alpha is `undefined`) then 1 else alpha)
@currentPath =
lineWidth: @lineWidth
lineColor: @lineColor
lineAlpha: @lineAlpha
fillColor: @fillColor
fillAlpha: @fillAlpha
fill: @filling
points: []
type: Graphics.POLY
@graphicsData.push @currentPath
###*
Moves the current drawing position to (x, y).
@method moveTo
@param x {Number} the X coord to move to
@param y {Number} the Y coord to move to
###
moveTo: (x, y) ->
@graphicsData.pop() if @currentPath.points.length is 0
@currentPath = @currentPath =
lineWidth: @lineWidth
lineColor: @lineColor
lineAlpha: @lineAlpha
fillColor: @fillColor
fillAlpha: @fillAlpha
fill: @filling
points: []
type: Graphics.POLY
@currentPath.points.push x, y
@graphicsData.push @currentPath
###*
Draws a line using the current line style from the current drawing position to (x, y);
the current drawing position is then set to (x, y).
@method lineTo
@param x {Number} the X coord to draw to
@param y {Number} the Y coord to draw to
###
lineTo: (x, y) ->
@currentPath.points.push x, y
@dirty = true
###*
Specifies a simple one-color fill that subsequent calls to other Graphics methods
(such as lineTo() or drawCircle()) use when drawing.
@method beginFill
@param color {uint} the color of the fill
@param alpha {Number} the alpha
###
beginFill: (color, alpha) ->
@filling = true
@fillColor = color or 0
@fillAlpha = alpha ? 1
###*
Applies a fill to the lines and shapes that were added since the last call to the beginFill() method.
@method endFill
###
endFill: ->
@filling = false
@fillColor = null
@fillAlpha = 1
###*
@method drawRect
@param x {Number} The X coord of the top-left of the rectangle
@param y {Number} The Y coord of the top-left of the rectangle
@param width {Number} The width of the rectangle
@param height {Number} The height of the rectangle
###
drawRect: (x, y, width, height) ->
@graphicsData.pop() if @currentPath.points.length is 0
@currentPath =
lineWidth: @lineWidth
lineColor: @lineColor
lineAlpha: @lineAlpha
fillColor: @fillColor
fillAlpha: @fillAlpha
fill: @filling
points: [x, y, width, height]
type: Graphics.RECT
@graphicsData.push @currentPath
@dirty = true
###*
Draws a circle.
@method drawCircle
@param x {Number} The X coord of the center of the circle
@param y {Number} The Y coord of the center of the circle
@param radius {Number} The radius of the circle
###
drawCircle: (x, y, radius) ->
@graphicsData.pop() if @currentPath.points.length is 0
@currentPath =
lineWidth: @lineWidth
lineColor: @lineColor
lineAlpha: @lineAlpha
fillColor: @fillColor
fillAlpha: @fillAlpha
fill: @filling
points: [x, y, radius, radius]
type: Graphics.CIRC
@graphicsData.push @currentPath
@dirty = true
###*
Draws an elipse.
@method drawElipse
@param x {Number}
@param y {Number}
@param width {Number}
@param height {Number}
###
drawElipse: (x, y, width, height) ->
@graphicsData.pop() if @currentPath.points.length is 0
@currentPath =
lineWidth: @lineWidth
lineColor: @lineColor
lineAlpha: @lineAlpha
fillColor: @fillColor
fillAlpha: @fillAlpha
fill: @filling
points: [x, y, width, height]
type: Graphics.ELIP
@graphicsData.push @currentPath
@dirty = true
###*
Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
@method clear
###
clear: ->
@lineWidth = 0
@filling = false
@dirty = true
@clearDirty = true
@graphicsData = []
|
[
{
"context": " 'Esquema del caso:'\n 'Eixemplos:'\n 'Dau '\n 'Dada '\n 'Daus '\n 'Dadas '\n ",
"end": 193,
"score": 0.9995157718658447,
"start": 190,
"tag": "NAME",
"value": "Dau"
},
{
"context": "del caso:'\n 'Eixemplos:'\n 'Dau '\n 'Dada '\n 'Daus '\n 'Dadas '\n 'Cuan '\n ",
"end": 207,
"score": 0.9995471239089966,
"start": 203,
"tag": "NAME",
"value": "Dada"
},
{
"context": " 'Eixemplos:'\n 'Dau '\n 'Dada '\n 'Daus '\n 'Dadas '\n 'Cuan '\n 'Alavez '\n ",
"end": 221,
"score": 0.9994723796844482,
"start": 217,
"tag": "NAME",
"value": "Daus"
},
{
"context": "'\n 'Dau '\n 'Dada '\n 'Daus '\n 'Dadas '\n 'Cuan '\n 'Alavez '\n 'Allora '\n ",
"end": 236,
"score": 0.9996370077133179,
"start": 231,
"tag": "NAME",
"value": "Dadas"
},
{
"context": " 'Dada '\n 'Daus '\n 'Dadas '\n 'Cuan '\n 'Alavez '\n 'Allora '\n 'Antonces",
"end": 250,
"score": 0.999620795249939,
"start": 246,
"tag": "NAME",
"value": "Cuan"
},
{
"context": " 'Daus '\n 'Dadas '\n 'Cuan '\n 'Alavez '\n 'Allora '\n 'Antonces '\n 'Pero '",
"end": 266,
"score": 0.9996633529663086,
"start": 260,
"tag": "NAME",
"value": "Alavez"
},
{
"context": " 'Dadas '\n 'Cuan '\n 'Alavez '\n 'Allora '\n 'Antonces '\n 'Pero '\n 'Y '\n ",
"end": 282,
"score": 0.9995682239532471,
"start": 276,
"tag": "NAME",
"value": "Allora"
},
{
"context": " 'Cuan '\n 'Alavez '\n 'Allora '\n 'Antonces '\n 'Pero '\n 'Y '\n 'E '\n ]\n '",
"end": 300,
"score": 0.9987632632255554,
"start": 292,
"tag": "NAME",
"value": "Antonces"
},
{
"context": "Alavez '\n 'Allora '\n 'Antonces '\n 'Pero '\n 'Y '\n 'E '\n ]\n 'increaseIndent",
"end": 314,
"score": 0.9989290237426758,
"start": 310,
"tag": "NAME",
"value": "Pero"
}
] | settings/language-gherkin_an.cson | mackoj/language-gherkin-i18n | 17 | '.text.gherkin.feature.an':
'editor':
'completions': [
'Caracteristica:'
'Antecedents:'
'Eixemplo:'
'Caso:'
'Esquema del caso:'
'Eixemplos:'
'Dau '
'Dada '
'Daus '
'Dadas '
'Cuan '
'Alavez '
'Allora '
'Antonces '
'Pero '
'Y '
'E '
]
'increaseIndentPattern': 'Eixemplo: .*'
'Caso: .*'
'commentStart': '# '
| 97646 | '.text.gherkin.feature.an':
'editor':
'completions': [
'Caracteristica:'
'Antecedents:'
'Eixemplo:'
'Caso:'
'Esquema del caso:'
'Eixemplos:'
'<NAME> '
'<NAME> '
'<NAME> '
'<NAME> '
'<NAME> '
'<NAME> '
'<NAME> '
'<NAME> '
'<NAME> '
'Y '
'E '
]
'increaseIndentPattern': 'Eixemplo: .*'
'Caso: .*'
'commentStart': '# '
| true | '.text.gherkin.feature.an':
'editor':
'completions': [
'Caracteristica:'
'Antecedents:'
'Eixemplo:'
'Caso:'
'Esquema del caso:'
'Eixemplos:'
'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 '
'PI:NAME:<NAME>END_PI '
'PI:NAME:<NAME>END_PI '
'PI:NAME:<NAME>END_PI '
'PI:NAME:<NAME>END_PI '
'Y '
'E '
]
'increaseIndentPattern': 'Eixemplo: .*'
'Caso: .*'
'commentStart': '# '
|
[
{
"context": "###******************************\n* StromBewusst - UDP Simulator\n# *******************************",
"end": 49,
"score": 0.9983446002006531,
"start": 37,
"tag": "NAME",
"value": "StromBewusst"
}
] | server/udp_simulation.coffee | rastapasta/strombewusst | 0 | ###******************************
* StromBewusst - UDP Simulator
# *******************************
###
dgram = require "dgram"
message = new Buffer "\xAA\xBB\xCC\xDD\xEE\xFF\x3C\x01"
client = dgram.createSocket "udp4"
client.send message, 0, message.length, 8888, "localhost", (err, bytes) ->
client.close()
| 204404 | ###******************************
* <NAME> - UDP Simulator
# *******************************
###
dgram = require "dgram"
message = new Buffer "\xAA\xBB\xCC\xDD\xEE\xFF\x3C\x01"
client = dgram.createSocket "udp4"
client.send message, 0, message.length, 8888, "localhost", (err, bytes) ->
client.close()
| true | ###******************************
* PI:NAME:<NAME>END_PI - UDP Simulator
# *******************************
###
dgram = require "dgram"
message = new Buffer "\xAA\xBB\xCC\xDD\xEE\xFF\x3C\x01"
client = dgram.createSocket "udp4"
client.send message, 0, message.length, 8888, "localhost", (err, bytes) ->
client.close()
|
[
{
"context": ", 'success', 4\n \n save: (name, data)->\n key = @generateKey(name)\n if ws then ws.set(key, JSON.stringify(data))\n",
"end": 5110,
"score": 0.8922513127326965,
"start": 5092,
"tag": "KEY",
"value": "@generateKey(name)"
},
{
"context": " @behaviorLoad()\n\n backgroundLoad: ()->\n key = @generateKey(@project_background)\n rtn = ws.get(key)\n console.log",
"end": 5324,
"score": 0.8611283302307129,
"start": 5303,
"tag": "KEY",
"value": "@generateKey(@project"
},
{
"context": "kgroundLoad: ()->\n key = @generateKey(@project_background)\n rtn = ws.get(key)\n console.log '↑', rtn\n ",
"end": 5336,
"score": 0.6507141590118408,
"start": 5325,
"tag": "KEY",
"value": "background)"
},
{
"context": ") \n \n \n\n behaviorLoad: ()->\n key = @generateKey(@behaviors)\n rtn = ws.get(key)\n \n \n ",
"end": 5478,
"score": 0.7078835964202881,
"start": 5469,
"tag": "KEY",
"value": "@generate"
},
{
"context": " \n\n behaviorLoad: ()->\n key = @generateKey(@behaviors)\n rtn = ws.get(key)\n \n \n behaviors = if",
"end": 5492,
"score": 0.5880831480026245,
"start": 5483,
"tag": "USERNAME",
"value": "behaviors"
},
{
"context": "rary .track-full')\n # data:\n # name: \"Stagger\"\n \n playBehavior = (event)-> \n event.",
"end": 6057,
"score": 0.7653216123580933,
"start": 6050,
"tag": "NAME",
"value": "Stagger"
},
{
"context": "ctors: (name, loadFN)->\n scope = this\n key = @generateKey(name)\n rtn = ws.get(key)\n actors = if _.isN",
"end": 6964,
"score": 0.8675100207328796,
"start": 6952,
"tag": "KEY",
"value": "@generateKey"
},
{
"context": "nerateKey: (name)->\n return [fs.getName(), name].join(':')\n \nclass window.Grouper extends ActuatorWi",
"end": 7892,
"score": 0.5766891241073608,
"start": 7888,
"tag": "KEY",
"value": "join"
}
] | src/choreographer/app/assets/javascripts/aesthetic_actuation/levels/Actuator/ActuatorWidgets.js.coffee | Hybrid-Ecologies/a-conversation-with-actuators | 0 | window.SPECIAL_KEYS = [32]
$ ->
$(document).keypress (event) ->
# console.log event
# console.log event.which, Widget.bindings
if Widget.bindings_on
if event.ctrlKey or _.includes window.SPECIAL_KEYS, event.which
console.log "WIDGET ACTIVATED", event.which
event.preventDefault()
_.each Widget.bindings, (func, key)->
if event.which == parseInt(key)
func(event)
class window.Widget
@bindings = {}
@bindings_on = true
@enable: ->
$(".toggle").click ()->
$(this).parent().toggleClass('shrink')
state = $(this).parent().hasClass('shrink')
$(this).parent().find('.trigger').prop("disabled", state)
if state
$(this).find('span').removeClass('glyphicon-collapse-up')
$(this).find('span').addClass('glyphicon-collapse-down')
else
$(this).find('span').removeClass('glyphicon-collapse-down')
$(this).find('span').addClass('glyphicon-collapse-up')
fullscreenToggle = (dom)->
$(dom).toggleClass('fullscreen')
# if $(dom).hasClass('fullscreen')
# $(dom).detach().appendTo('body')
# else
# $(dom).detach().appendTo('#levels')
Widget.bindKeypress 1, (()-> $('event button.toggle').click()), true
Widget.bindKeypress 2, (()-> fullscreenToggle($('event#behaviors'))), true
Widget.bindKeypress 49, (()-> $('event.actuation-design button.toggle').click()), true
Widget.bindKeypress 50, (()-> $('event.signal-design button.toggle').click()), true
Widget.bindKeypress 51, (()-> $('event.composition-design button.toggle').click()), true
Widget.bindKeypress 6, (()-> $('#fullscreen').click()), true
return
@bindKeypress: (key, func, ascii = false)->
if not ascii
key = parseInt(key.charCodeAt(0))
# console.log "Binding", key
Widget.bindings[key] = func;
class window.ActuatorWidgets
constructor: ()->
console.info '✓ Actuation Widgets'
@group = new Grouper
dom: $("#group")
track: $("#actuator-group")
result: $("#group-result")
trigger: $("#group-button.trigger")
clear: $("#group-clear")
bindKey: 7 #G
@saver = new Saver
track: $("#actuator-library .track-full")
trigger: $("#library.actuation-design button.trigger")
bindKey: 19 #S
@async = new AsynchMorph
track: $("#async .track-full")
trigger: $("#async button")
bindKey: 3 #C
slider: $("#async input")
# @comm = new Communicator
# trigger: $('button#live-connect')
# bindKey: 'l'
class window.ActuatorWidget
@resolveTrack: (track)->
_.map track.find('actuator'), (act)-> return am.resolve(act)
resolveTrack: ()->
ActuatorWidget.resolveTrack(@track)
class window.AsynchMorph extends ActuatorWidget
@MIN: 0
@MAX: 1000
constructor: (op)->
# console.log "Async"
scope = this
_.extend this, op
Widget.bindKeypress @bindKey, (()-> scope.trigger.click()), true
@slider.on 'input', (e)->
v = if this.value < AsynchMorph.MIN then AsynchMorph.MIN else this.value
# console.log v
_.each scope.resolveTrack(), (actuator)->
actuator.form = {async_period: parseInt(v)}
class window.Saver extends ActuatorWidget
# ↑ ↓
constructor: (@op)->
console.info '\t✓ Save/Load'
scope = this
Widget.bindKeypress @op.bindKey, (()-> scope.saveActuation()), true
$("#save-behaviors").click ()->
scope.saveActuation()
@project_background = "project_background"
@track = "actuator_group_library"
@stage = "behavior_stage"
@a_library = "a_library"
@ts_library = "ts_library"
@behaviors = "behaviors"
# SAVE BEHAVIORS
@op.trigger.click (event)->
console.info "SAVING..."
scope.saveActuation()
saveBackground: ()->
console.info '↓',
background: ch.getBGColor()
@save @project_background, ch.getBGColor()
saveBehaviors: ()->
behaviors = _.map Behavior.library, (behavior, id)->
behavior.save()
console.info '↓', behaviors.length, "behaviors"
@save @behaviors, behaviors
saveActuation: (e)->
scope = this
scope.saveBackground()
# track_actuators = _.map @op.track.find('actuator'), (actor)-> return am.resolve(actor)
# @saveActors(scope.track, track_actuators)
# stage_actuators = bm.getActors()
# scope.saveActors(scope.stage, stage_actuators)
# signal_tracks = $(".signal-design .track-full").not("#hues")
# signal_tracks = _.map signal_tracks, (track)->
# signals = TimeWidget.resolveTrack(track, '.easing, .default')
# track_id = $(track).parent('event').attr('id')
actuators = am.gatherActuators()
timesignals = tsm.gatherSignals()
@saveActors(scope.a_library, actuators)
console.info '↓', actuators.length, "actuators"
@saveActors(scope.ts_library, timesignals)
console.info '↓', timesignals.length, "signals"
@saveBehaviors()
alertify.notify "<b>SAVED!</b> We won't forget a thing!", 'success', 4
save: (name, data)->
key = @generateKey(name)
if ws then ws.set(key, JSON.stringify(data))
load:()->
scope = this
@backgroundLoad()
@actuatorLoad()
@signalLoad()
@behaviorLoad()
backgroundLoad: ()->
key = @generateKey(@project_background)
rtn = ws.get(key)
console.log '↑', rtn
if rtn
ch.setBGColor(rtn)
behaviorLoad: ()->
key = @generateKey(@behaviors)
rtn = ws.get(key)
behaviors = if _.isNull(rtn) then [] else JSON.parse(rtn)
behaviors = _.map behaviors, (behaviorData, behaviorID)->
# console.log behaviorData
new Behavior
container: $('#behavior-library .track-full')
_load: behaviorData.manager
data: behaviorData.data
console.info '↑', behaviors.length, "behaviors"
# window.current_behavior = behaviors[0]
# window.current_behavior = new Behavior
# container: $('#behavior-library .track-full')
# data:
# name: "Stagger"
playBehavior = (event)->
event.preventDefault()
window.current_behavior.play()
Widget.bindKeypress 32, playBehavior, true
$('#add-stage').click ()->
if window.current_behavior
window.current_behavior.data.manager.addStage()
else
$('#add-behavior').click()
# $('#add-stage').click()
saveActors: (name, actors)->
data = _.map actors, (actor)->
actor.form = {saved: true}
if actor.easing then return null
lib = actor.dom.parents("#actuator-library").length == 1 or actor.dom.parents("#library.signal-design").length == 1
rtn = _.extend actor.form,
file: fs.getName()
library: lib
# parent: actor.dom.parent().data().id
test: ""
return rtn
data = _.compact(data)
@save(name, data)
loadActors: (name, loadFN)->
scope = this
key = @generateKey(name)
rtn = ws.get(key)
actors = if _.isNull(rtn) then [] else JSON.parse(rtn)
_.each actors, (actor)->
loadFN(actor)
console.info '↑', actors.length, name
return actors
signalLoad: ()->
scope = this
scope.loadActors scope.ts_library, (signal)->
dom = TimeSignal.create
clear: false
target: $("#library.signal-design .track-full")
ts = new TimeSignal dom, signal
if not signal.library
ts.dom.addClass('meta').hide()
actuatorLoad: ()->
scope = this
@loadActors @a_library, (actuator)->
ops =
clear: false
target: $("#actuator-library .track-full")
ops = _.extend(ops, actuator)
ops.override = true
dom = ActuatorManager.create ops
# console.log "LOAD", actuator
if not actuator.library
dom.addClass('meta').hide()
generateKey: (name)->
return [fs.getName(), name].join(':')
class window.Grouper extends ActuatorWidget
constructor: (@op)->
scope = this
# console.log "GroupMaker"
Widget.bindKeypress @op.bindKey, (()-> scope.op.trigger.click()), true
@op.dom.hide()
@op.trigger.click (event)->
acts = scope.op.track.find('actuator')
ids = _.chain acts
.map (dom)-> return am.resolve(dom).form.hardware_ids
.flatten()
.uniq()
.sortBy()
.value()
if _.isEmpty(ids) then return
# # ALL HAVE TO BE THE SAME TYPE...
ops = _.extend am.resolve(_.first(acts)).form,
clear: true
target: scope.op.result
hardware_ids: ids
title: ids.join(',')
ActuatorManager.create ops
return
| 180258 | window.SPECIAL_KEYS = [32]
$ ->
$(document).keypress (event) ->
# console.log event
# console.log event.which, Widget.bindings
if Widget.bindings_on
if event.ctrlKey or _.includes window.SPECIAL_KEYS, event.which
console.log "WIDGET ACTIVATED", event.which
event.preventDefault()
_.each Widget.bindings, (func, key)->
if event.which == parseInt(key)
func(event)
class window.Widget
@bindings = {}
@bindings_on = true
@enable: ->
$(".toggle").click ()->
$(this).parent().toggleClass('shrink')
state = $(this).parent().hasClass('shrink')
$(this).parent().find('.trigger').prop("disabled", state)
if state
$(this).find('span').removeClass('glyphicon-collapse-up')
$(this).find('span').addClass('glyphicon-collapse-down')
else
$(this).find('span').removeClass('glyphicon-collapse-down')
$(this).find('span').addClass('glyphicon-collapse-up')
fullscreenToggle = (dom)->
$(dom).toggleClass('fullscreen')
# if $(dom).hasClass('fullscreen')
# $(dom).detach().appendTo('body')
# else
# $(dom).detach().appendTo('#levels')
Widget.bindKeypress 1, (()-> $('event button.toggle').click()), true
Widget.bindKeypress 2, (()-> fullscreenToggle($('event#behaviors'))), true
Widget.bindKeypress 49, (()-> $('event.actuation-design button.toggle').click()), true
Widget.bindKeypress 50, (()-> $('event.signal-design button.toggle').click()), true
Widget.bindKeypress 51, (()-> $('event.composition-design button.toggle').click()), true
Widget.bindKeypress 6, (()-> $('#fullscreen').click()), true
return
@bindKeypress: (key, func, ascii = false)->
if not ascii
key = parseInt(key.charCodeAt(0))
# console.log "Binding", key
Widget.bindings[key] = func;
class window.ActuatorWidgets
constructor: ()->
console.info '✓ Actuation Widgets'
@group = new Grouper
dom: $("#group")
track: $("#actuator-group")
result: $("#group-result")
trigger: $("#group-button.trigger")
clear: $("#group-clear")
bindKey: 7 #G
@saver = new Saver
track: $("#actuator-library .track-full")
trigger: $("#library.actuation-design button.trigger")
bindKey: 19 #S
@async = new AsynchMorph
track: $("#async .track-full")
trigger: $("#async button")
bindKey: 3 #C
slider: $("#async input")
# @comm = new Communicator
# trigger: $('button#live-connect')
# bindKey: 'l'
class window.ActuatorWidget
@resolveTrack: (track)->
_.map track.find('actuator'), (act)-> return am.resolve(act)
resolveTrack: ()->
ActuatorWidget.resolveTrack(@track)
class window.AsynchMorph extends ActuatorWidget
@MIN: 0
@MAX: 1000
constructor: (op)->
# console.log "Async"
scope = this
_.extend this, op
Widget.bindKeypress @bindKey, (()-> scope.trigger.click()), true
@slider.on 'input', (e)->
v = if this.value < AsynchMorph.MIN then AsynchMorph.MIN else this.value
# console.log v
_.each scope.resolveTrack(), (actuator)->
actuator.form = {async_period: parseInt(v)}
class window.Saver extends ActuatorWidget
# ↑ ↓
constructor: (@op)->
console.info '\t✓ Save/Load'
scope = this
Widget.bindKeypress @op.bindKey, (()-> scope.saveActuation()), true
$("#save-behaviors").click ()->
scope.saveActuation()
@project_background = "project_background"
@track = "actuator_group_library"
@stage = "behavior_stage"
@a_library = "a_library"
@ts_library = "ts_library"
@behaviors = "behaviors"
# SAVE BEHAVIORS
@op.trigger.click (event)->
console.info "SAVING..."
scope.saveActuation()
saveBackground: ()->
console.info '↓',
background: ch.getBGColor()
@save @project_background, ch.getBGColor()
saveBehaviors: ()->
behaviors = _.map Behavior.library, (behavior, id)->
behavior.save()
console.info '↓', behaviors.length, "behaviors"
@save @behaviors, behaviors
saveActuation: (e)->
scope = this
scope.saveBackground()
# track_actuators = _.map @op.track.find('actuator'), (actor)-> return am.resolve(actor)
# @saveActors(scope.track, track_actuators)
# stage_actuators = bm.getActors()
# scope.saveActors(scope.stage, stage_actuators)
# signal_tracks = $(".signal-design .track-full").not("#hues")
# signal_tracks = _.map signal_tracks, (track)->
# signals = TimeWidget.resolveTrack(track, '.easing, .default')
# track_id = $(track).parent('event').attr('id')
actuators = am.gatherActuators()
timesignals = tsm.gatherSignals()
@saveActors(scope.a_library, actuators)
console.info '↓', actuators.length, "actuators"
@saveActors(scope.ts_library, timesignals)
console.info '↓', timesignals.length, "signals"
@saveBehaviors()
alertify.notify "<b>SAVED!</b> We won't forget a thing!", 'success', 4
save: (name, data)->
key = <KEY>
if ws then ws.set(key, JSON.stringify(data))
load:()->
scope = this
@backgroundLoad()
@actuatorLoad()
@signalLoad()
@behaviorLoad()
backgroundLoad: ()->
key = <KEY>_<KEY>
rtn = ws.get(key)
console.log '↑', rtn
if rtn
ch.setBGColor(rtn)
behaviorLoad: ()->
key = <KEY>Key(@behaviors)
rtn = ws.get(key)
behaviors = if _.isNull(rtn) then [] else JSON.parse(rtn)
behaviors = _.map behaviors, (behaviorData, behaviorID)->
# console.log behaviorData
new Behavior
container: $('#behavior-library .track-full')
_load: behaviorData.manager
data: behaviorData.data
console.info '↑', behaviors.length, "behaviors"
# window.current_behavior = behaviors[0]
# window.current_behavior = new Behavior
# container: $('#behavior-library .track-full')
# data:
# name: "<NAME>"
playBehavior = (event)->
event.preventDefault()
window.current_behavior.play()
Widget.bindKeypress 32, playBehavior, true
$('#add-stage').click ()->
if window.current_behavior
window.current_behavior.data.manager.addStage()
else
$('#add-behavior').click()
# $('#add-stage').click()
saveActors: (name, actors)->
data = _.map actors, (actor)->
actor.form = {saved: true}
if actor.easing then return null
lib = actor.dom.parents("#actuator-library").length == 1 or actor.dom.parents("#library.signal-design").length == 1
rtn = _.extend actor.form,
file: fs.getName()
library: lib
# parent: actor.dom.parent().data().id
test: ""
return rtn
data = _.compact(data)
@save(name, data)
loadActors: (name, loadFN)->
scope = this
key = <KEY>(name)
rtn = ws.get(key)
actors = if _.isNull(rtn) then [] else JSON.parse(rtn)
_.each actors, (actor)->
loadFN(actor)
console.info '↑', actors.length, name
return actors
signalLoad: ()->
scope = this
scope.loadActors scope.ts_library, (signal)->
dom = TimeSignal.create
clear: false
target: $("#library.signal-design .track-full")
ts = new TimeSignal dom, signal
if not signal.library
ts.dom.addClass('meta').hide()
actuatorLoad: ()->
scope = this
@loadActors @a_library, (actuator)->
ops =
clear: false
target: $("#actuator-library .track-full")
ops = _.extend(ops, actuator)
ops.override = true
dom = ActuatorManager.create ops
# console.log "LOAD", actuator
if not actuator.library
dom.addClass('meta').hide()
generateKey: (name)->
return [fs.getName(), name].<KEY>(':')
class window.Grouper extends ActuatorWidget
constructor: (@op)->
scope = this
# console.log "GroupMaker"
Widget.bindKeypress @op.bindKey, (()-> scope.op.trigger.click()), true
@op.dom.hide()
@op.trigger.click (event)->
acts = scope.op.track.find('actuator')
ids = _.chain acts
.map (dom)-> return am.resolve(dom).form.hardware_ids
.flatten()
.uniq()
.sortBy()
.value()
if _.isEmpty(ids) then return
# # ALL HAVE TO BE THE SAME TYPE...
ops = _.extend am.resolve(_.first(acts)).form,
clear: true
target: scope.op.result
hardware_ids: ids
title: ids.join(',')
ActuatorManager.create ops
return
| true | window.SPECIAL_KEYS = [32]
$ ->
$(document).keypress (event) ->
# console.log event
# console.log event.which, Widget.bindings
if Widget.bindings_on
if event.ctrlKey or _.includes window.SPECIAL_KEYS, event.which
console.log "WIDGET ACTIVATED", event.which
event.preventDefault()
_.each Widget.bindings, (func, key)->
if event.which == parseInt(key)
func(event)
class window.Widget
@bindings = {}
@bindings_on = true
@enable: ->
$(".toggle").click ()->
$(this).parent().toggleClass('shrink')
state = $(this).parent().hasClass('shrink')
$(this).parent().find('.trigger').prop("disabled", state)
if state
$(this).find('span').removeClass('glyphicon-collapse-up')
$(this).find('span').addClass('glyphicon-collapse-down')
else
$(this).find('span').removeClass('glyphicon-collapse-down')
$(this).find('span').addClass('glyphicon-collapse-up')
fullscreenToggle = (dom)->
$(dom).toggleClass('fullscreen')
# if $(dom).hasClass('fullscreen')
# $(dom).detach().appendTo('body')
# else
# $(dom).detach().appendTo('#levels')
Widget.bindKeypress 1, (()-> $('event button.toggle').click()), true
Widget.bindKeypress 2, (()-> fullscreenToggle($('event#behaviors'))), true
Widget.bindKeypress 49, (()-> $('event.actuation-design button.toggle').click()), true
Widget.bindKeypress 50, (()-> $('event.signal-design button.toggle').click()), true
Widget.bindKeypress 51, (()-> $('event.composition-design button.toggle').click()), true
Widget.bindKeypress 6, (()-> $('#fullscreen').click()), true
return
@bindKeypress: (key, func, ascii = false)->
if not ascii
key = parseInt(key.charCodeAt(0))
# console.log "Binding", key
Widget.bindings[key] = func;
class window.ActuatorWidgets
constructor: ()->
console.info '✓ Actuation Widgets'
@group = new Grouper
dom: $("#group")
track: $("#actuator-group")
result: $("#group-result")
trigger: $("#group-button.trigger")
clear: $("#group-clear")
bindKey: 7 #G
@saver = new Saver
track: $("#actuator-library .track-full")
trigger: $("#library.actuation-design button.trigger")
bindKey: 19 #S
@async = new AsynchMorph
track: $("#async .track-full")
trigger: $("#async button")
bindKey: 3 #C
slider: $("#async input")
# @comm = new Communicator
# trigger: $('button#live-connect')
# bindKey: 'l'
class window.ActuatorWidget
@resolveTrack: (track)->
_.map track.find('actuator'), (act)-> return am.resolve(act)
resolveTrack: ()->
ActuatorWidget.resolveTrack(@track)
class window.AsynchMorph extends ActuatorWidget
@MIN: 0
@MAX: 1000
constructor: (op)->
# console.log "Async"
scope = this
_.extend this, op
Widget.bindKeypress @bindKey, (()-> scope.trigger.click()), true
@slider.on 'input', (e)->
v = if this.value < AsynchMorph.MIN then AsynchMorph.MIN else this.value
# console.log v
_.each scope.resolveTrack(), (actuator)->
actuator.form = {async_period: parseInt(v)}
class window.Saver extends ActuatorWidget
# ↑ ↓
constructor: (@op)->
console.info '\t✓ Save/Load'
scope = this
Widget.bindKeypress @op.bindKey, (()-> scope.saveActuation()), true
$("#save-behaviors").click ()->
scope.saveActuation()
@project_background = "project_background"
@track = "actuator_group_library"
@stage = "behavior_stage"
@a_library = "a_library"
@ts_library = "ts_library"
@behaviors = "behaviors"
# SAVE BEHAVIORS
@op.trigger.click (event)->
console.info "SAVING..."
scope.saveActuation()
saveBackground: ()->
console.info '↓',
background: ch.getBGColor()
@save @project_background, ch.getBGColor()
saveBehaviors: ()->
behaviors = _.map Behavior.library, (behavior, id)->
behavior.save()
console.info '↓', behaviors.length, "behaviors"
@save @behaviors, behaviors
saveActuation: (e)->
scope = this
scope.saveBackground()
# track_actuators = _.map @op.track.find('actuator'), (actor)-> return am.resolve(actor)
# @saveActors(scope.track, track_actuators)
# stage_actuators = bm.getActors()
# scope.saveActors(scope.stage, stage_actuators)
# signal_tracks = $(".signal-design .track-full").not("#hues")
# signal_tracks = _.map signal_tracks, (track)->
# signals = TimeWidget.resolveTrack(track, '.easing, .default')
# track_id = $(track).parent('event').attr('id')
actuators = am.gatherActuators()
timesignals = tsm.gatherSignals()
@saveActors(scope.a_library, actuators)
console.info '↓', actuators.length, "actuators"
@saveActors(scope.ts_library, timesignals)
console.info '↓', timesignals.length, "signals"
@saveBehaviors()
alertify.notify "<b>SAVED!</b> We won't forget a thing!", 'success', 4
save: (name, data)->
key = PI:KEY:<KEY>END_PI
if ws then ws.set(key, JSON.stringify(data))
load:()->
scope = this
@backgroundLoad()
@actuatorLoad()
@signalLoad()
@behaviorLoad()
backgroundLoad: ()->
key = PI:KEY:<KEY>END_PI_PI:KEY:<KEY>END_PI
rtn = ws.get(key)
console.log '↑', rtn
if rtn
ch.setBGColor(rtn)
behaviorLoad: ()->
key = PI:KEY:<KEY>END_PIKey(@behaviors)
rtn = ws.get(key)
behaviors = if _.isNull(rtn) then [] else JSON.parse(rtn)
behaviors = _.map behaviors, (behaviorData, behaviorID)->
# console.log behaviorData
new Behavior
container: $('#behavior-library .track-full')
_load: behaviorData.manager
data: behaviorData.data
console.info '↑', behaviors.length, "behaviors"
# window.current_behavior = behaviors[0]
# window.current_behavior = new Behavior
# container: $('#behavior-library .track-full')
# data:
# name: "PI:NAME:<NAME>END_PI"
playBehavior = (event)->
event.preventDefault()
window.current_behavior.play()
Widget.bindKeypress 32, playBehavior, true
$('#add-stage').click ()->
if window.current_behavior
window.current_behavior.data.manager.addStage()
else
$('#add-behavior').click()
# $('#add-stage').click()
saveActors: (name, actors)->
data = _.map actors, (actor)->
actor.form = {saved: true}
if actor.easing then return null
lib = actor.dom.parents("#actuator-library").length == 1 or actor.dom.parents("#library.signal-design").length == 1
rtn = _.extend actor.form,
file: fs.getName()
library: lib
# parent: actor.dom.parent().data().id
test: ""
return rtn
data = _.compact(data)
@save(name, data)
loadActors: (name, loadFN)->
scope = this
key = PI:KEY:<KEY>END_PI(name)
rtn = ws.get(key)
actors = if _.isNull(rtn) then [] else JSON.parse(rtn)
_.each actors, (actor)->
loadFN(actor)
console.info '↑', actors.length, name
return actors
signalLoad: ()->
scope = this
scope.loadActors scope.ts_library, (signal)->
dom = TimeSignal.create
clear: false
target: $("#library.signal-design .track-full")
ts = new TimeSignal dom, signal
if not signal.library
ts.dom.addClass('meta').hide()
actuatorLoad: ()->
scope = this
@loadActors @a_library, (actuator)->
ops =
clear: false
target: $("#actuator-library .track-full")
ops = _.extend(ops, actuator)
ops.override = true
dom = ActuatorManager.create ops
# console.log "LOAD", actuator
if not actuator.library
dom.addClass('meta').hide()
generateKey: (name)->
return [fs.getName(), name].PI:KEY:<KEY>END_PI(':')
class window.Grouper extends ActuatorWidget
constructor: (@op)->
scope = this
# console.log "GroupMaker"
Widget.bindKeypress @op.bindKey, (()-> scope.op.trigger.click()), true
@op.dom.hide()
@op.trigger.click (event)->
acts = scope.op.track.find('actuator')
ids = _.chain acts
.map (dom)-> return am.resolve(dom).form.hardware_ids
.flatten()
.uniq()
.sortBy()
.value()
if _.isEmpty(ids) then return
# # ALL HAVE TO BE THE SAME TYPE...
ops = _.extend am.resolve(_.first(acts)).form,
clear: true
target: scope.op.result
hardware_ids: ids
title: ids.join(',')
ActuatorManager.create ops
return
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999128580093384,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/_components/flag-country.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 * as React from 'react'
import { span } from 'react-dom-factories'
el = React.createElement
bn = 'flag-country'
export FlagCountry = ({country, modifiers}) ->
return null if !country?.code?
blockClass = osu.classWithModifiers(bn, modifiers)
span
className: blockClass
title: country.name
style:
backgroundImage: "url('/images/flags/#{country.code}.png')"
| 13992 | # 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 * as React from 'react'
import { span } from 'react-dom-factories'
el = React.createElement
bn = 'flag-country'
export FlagCountry = ({country, modifiers}) ->
return null if !country?.code?
blockClass = osu.classWithModifiers(bn, modifiers)
span
className: blockClass
title: country.name
style:
backgroundImage: "url('/images/flags/#{country.code}.png')"
| 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 * as React from 'react'
import { span } from 'react-dom-factories'
el = React.createElement
bn = 'flag-country'
export FlagCountry = ({country, modifiers}) ->
return null if !country?.code?
blockClass = osu.classWithModifiers(bn, modifiers)
span
className: blockClass
title: country.name
style:
backgroundImage: "url('/images/flags/#{country.code}.png')"
|
[
{
"context": "place to get drunk with your guildies!\n *\n * @name Tavern\n * @category Buildings\n * @package Guild\n * @cost",
"end": 136,
"score": 0.9660488963127136,
"start": 130,
"tag": "NAME",
"value": "Tavern"
},
{
"context": "Cost = (level) -> level * 50000\n\n f =\n name: \"Barkeep\"\n gid: 13\n type: \"Guild NPC\"\n properties",
"end": 461,
"score": 0.9970996379852295,
"start": 454,
"tag": "NAME",
"value": "Barkeep"
}
] | src/map/guild-buildings/Tavern.coffee | jawsome/IdleLands | 3 |
GuildBuilding = require "../GuildBuilding"
`/**
* The Tavern provides you a place to get drunk with your guildies!
*
* @name Tavern
* @category Buildings
* @package Guild
* @cost {level-up} level*50000
* @size {lg}
*/`
class Tavern extends GuildBuilding
@size = Tavern::size = "lg"
@desc = Tavern::desc = "Upgrade this building to get your guildies drunk!"
@levelupCost = Tavern::levelupCost = (level) -> level * 50000
f =
name: "Barkeep"
gid: 13
type: "Guild NPC"
properties: {}
tiles: [
0, 0, 0, 0, 0, 0, 0,
0, 44, 39, 0, 45, 47, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 44, 44, 0, 44, 0, 0,
0, 46, f, 0, 0, 46, 0,
0, 0, 0, 0, 0, 0, 0
]
module.exports = exports = Tavern | 64758 |
GuildBuilding = require "../GuildBuilding"
`/**
* The Tavern provides you a place to get drunk with your guildies!
*
* @name <NAME>
* @category Buildings
* @package Guild
* @cost {level-up} level*50000
* @size {lg}
*/`
class Tavern extends GuildBuilding
@size = Tavern::size = "lg"
@desc = Tavern::desc = "Upgrade this building to get your guildies drunk!"
@levelupCost = Tavern::levelupCost = (level) -> level * 50000
f =
name: "<NAME>"
gid: 13
type: "Guild NPC"
properties: {}
tiles: [
0, 0, 0, 0, 0, 0, 0,
0, 44, 39, 0, 45, 47, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 44, 44, 0, 44, 0, 0,
0, 46, f, 0, 0, 46, 0,
0, 0, 0, 0, 0, 0, 0
]
module.exports = exports = Tavern | true |
GuildBuilding = require "../GuildBuilding"
`/**
* The Tavern provides you a place to get drunk with your guildies!
*
* @name PI:NAME:<NAME>END_PI
* @category Buildings
* @package Guild
* @cost {level-up} level*50000
* @size {lg}
*/`
class Tavern extends GuildBuilding
@size = Tavern::size = "lg"
@desc = Tavern::desc = "Upgrade this building to get your guildies drunk!"
@levelupCost = Tavern::levelupCost = (level) -> level * 50000
f =
name: "PI:NAME:<NAME>END_PI"
gid: 13
type: "Guild NPC"
properties: {}
tiles: [
0, 0, 0, 0, 0, 0, 0,
0, 44, 39, 0, 45, 47, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 44, 44, 0, 44, 0, 0,
0, 46, f, 0, 0, 46, 0,
0, 0, 0, 0, 0, 0, 0
]
module.exports = exports = Tavern |
[
{
"context": "/:id', ->\n client = _id: @params.id, name:'Bob'\n @format\n 'json': =>\n ",
"end": 902,
"score": 0.9984319806098938,
"start": 899,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ual 1, body._id, '3'\n t.equal 2, body.name, 'Bob'\n c.get '/clients/3', headers:{Accept:'text/ht",
"end": 1300,
"score": 0.9962653517723083,
"start": 1297,
"tag": "NAME",
"value": "Bob"
},
{
"context": ", res) ->\n t.equal 3, res.body, '<div id=\"3\">Bob</div>'\n\n 'default': (t) ->\n t.expect 1,2\n ",
"end": 1413,
"score": 0.9712643027305603,
"start": 1410,
"tag": "NAME",
"value": "Bob"
}
] | tests/more.coffee | zappajs/zappajs | 50 | zappa = require '../src/zappa'
port = 15900
@tests =
'powered by': (t) ->
t.expect 'express handles errors', 'zappa handles successful queries'
t.wait 3000
zapp = zappa port++, ->
@get '/foo', -> 'ok'
c = t.client(zapp.server)
c.get '/', (err, res) ->
t.ok 'express handles errors', res.headers['x-powered-by'].match /^Express/
c.get '/foo', (err, res) ->
t.ok 'zappa handles successful queries', res.headers['x-powered-by'].match /^Zappa/
'silent zappa': (t) ->
t.expect 'silent zappa'
t.wait 3000
zapp = zappa port++, ->
@enable 'silent_zappa'
@get '/', -> 'ok'
c = t.client(zapp.server)
c.get '/', (err, res) ->
t.ok 'silent zappa', res.body is 'ok'
'format': (t) ->
t.expect 1,2,3
t.wait 3000
zapp = zappa port++, ->
@get '/clients/:id', ->
client = _id: @params.id, name:'Bob'
@format
'json': =>
@json client
'html': =>
@render 'index', client
{div} = @teacup
@view index: ->
div id:@_id, => @name
c = t.client(zapp.server)
c.get '/clients/3', headers:{Accept:'application/json'}, (err, res) ->
body = JSON.parse res.body
t.equal 1, body._id, '3'
t.equal 2, body.name, 'Bob'
c.get '/clients/3', headers:{Accept:'text/html'}, (err, res) ->
t.equal 3, res.body, '<div id="3">Bob</div>'
'default': (t) ->
t.expect 1,2
zapp = zappa port++, ->
@get '/text', ->
'goo'
@get '/async', ->
Promise.resolve 'blar'
c = t.client(zapp.server)
c.get '/text', (err, res) ->
t.equal 1, res.body, 'goo'
c.get '/async', (err, res) ->
t.equal 2, res.body, 'blar'
| 128901 | zappa = require '../src/zappa'
port = 15900
@tests =
'powered by': (t) ->
t.expect 'express handles errors', 'zappa handles successful queries'
t.wait 3000
zapp = zappa port++, ->
@get '/foo', -> 'ok'
c = t.client(zapp.server)
c.get '/', (err, res) ->
t.ok 'express handles errors', res.headers['x-powered-by'].match /^Express/
c.get '/foo', (err, res) ->
t.ok 'zappa handles successful queries', res.headers['x-powered-by'].match /^Zappa/
'silent zappa': (t) ->
t.expect 'silent zappa'
t.wait 3000
zapp = zappa port++, ->
@enable 'silent_zappa'
@get '/', -> 'ok'
c = t.client(zapp.server)
c.get '/', (err, res) ->
t.ok 'silent zappa', res.body is 'ok'
'format': (t) ->
t.expect 1,2,3
t.wait 3000
zapp = zappa port++, ->
@get '/clients/:id', ->
client = _id: @params.id, name:'<NAME>'
@format
'json': =>
@json client
'html': =>
@render 'index', client
{div} = @teacup
@view index: ->
div id:@_id, => @name
c = t.client(zapp.server)
c.get '/clients/3', headers:{Accept:'application/json'}, (err, res) ->
body = JSON.parse res.body
t.equal 1, body._id, '3'
t.equal 2, body.name, '<NAME>'
c.get '/clients/3', headers:{Accept:'text/html'}, (err, res) ->
t.equal 3, res.body, '<div id="3"><NAME></div>'
'default': (t) ->
t.expect 1,2
zapp = zappa port++, ->
@get '/text', ->
'goo'
@get '/async', ->
Promise.resolve 'blar'
c = t.client(zapp.server)
c.get '/text', (err, res) ->
t.equal 1, res.body, 'goo'
c.get '/async', (err, res) ->
t.equal 2, res.body, 'blar'
| true | zappa = require '../src/zappa'
port = 15900
@tests =
'powered by': (t) ->
t.expect 'express handles errors', 'zappa handles successful queries'
t.wait 3000
zapp = zappa port++, ->
@get '/foo', -> 'ok'
c = t.client(zapp.server)
c.get '/', (err, res) ->
t.ok 'express handles errors', res.headers['x-powered-by'].match /^Express/
c.get '/foo', (err, res) ->
t.ok 'zappa handles successful queries', res.headers['x-powered-by'].match /^Zappa/
'silent zappa': (t) ->
t.expect 'silent zappa'
t.wait 3000
zapp = zappa port++, ->
@enable 'silent_zappa'
@get '/', -> 'ok'
c = t.client(zapp.server)
c.get '/', (err, res) ->
t.ok 'silent zappa', res.body is 'ok'
'format': (t) ->
t.expect 1,2,3
t.wait 3000
zapp = zappa port++, ->
@get '/clients/:id', ->
client = _id: @params.id, name:'PI:NAME:<NAME>END_PI'
@format
'json': =>
@json client
'html': =>
@render 'index', client
{div} = @teacup
@view index: ->
div id:@_id, => @name
c = t.client(zapp.server)
c.get '/clients/3', headers:{Accept:'application/json'}, (err, res) ->
body = JSON.parse res.body
t.equal 1, body._id, '3'
t.equal 2, body.name, 'PI:NAME:<NAME>END_PI'
c.get '/clients/3', headers:{Accept:'text/html'}, (err, res) ->
t.equal 3, res.body, '<div id="3">PI:NAME:<NAME>END_PI</div>'
'default': (t) ->
t.expect 1,2
zapp = zappa port++, ->
@get '/text', ->
'goo'
@get '/async', ->
Promise.resolve 'blar'
c = t.client(zapp.server)
c.get '/text', (err, res) ->
t.equal 1, res.body, 'goo'
c.get '/async', (err, res) ->
t.equal 2, res.body, 'blar'
|
[
{
"context": "il\n country: req.body.country\n pass: req.body.pass\n }\n data.meta = JSON.parse( req.body['m",
"end": 3462,
"score": 0.9988815188407898,
"start": 3449,
"tag": "PASSWORD",
"value": "req.body.pass"
},
{
"context": "['email']\n user: req.body['user']\n pass: req.body['pass']\n country: req.body['country']\n ",
"end": 4595,
"score": 0.9988982081413269,
"start": 4587,
"tag": "PASSWORD",
"value": "req.body"
},
{
"context": " user: req.body['user']\n pass: req.body['pass']\n country: req.body['country']\n meta: ",
"end": 4601,
"score": 0.9751813411712646,
"start": 4597,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": "reset =\n email: email\n passHash: passH\n res.render 'reset.jade', { \n tit",
"end": 5804,
"score": 0.9740250110626221,
"start": 5799,
"tag": "PASSWORD",
"value": "passH"
}
] | app/server/router.coffee | coderofsalvation/express-api-user-management-signup | 1 |
console.log "registered user signup routings"
module.exports = (app,layout,mongocfg) ->
CT = @CT = require('./modules/country-list')
AM = @AM = {}
EM = @EM = require('./modules/email-dispatcher')
AM = @AM = require('./modules/account-manager.mongo')
AM.init mongocfg
@layout = layout
updateCookieAge = (o,res) ->
res.cookie 'user', o.user, maxAge: 900000
res.cookie 'pass', o.pass, maxAge: 900000
# main login page //
app.get '/', (req, res) ->
# check if the user's credentials are saved in a cookie //
if req.cookies.user == undefined or req.cookies.pass == undefined
res.render 'login.jade', {
title: layout.title.welcome
brand: layout.title.brand
googleanalytics: process.env.GOOGLE_ANALYTICS_TOKEN
}
else
# attempt automatic login //
AM.autoLogin req.cookies.user, req.cookies.pass, (o) ->
if o != null
req.session.user = o
res.redirect '/home'
else
res.render 'login.jade', {
brand: layout.title.brand
title: layout.title.welcome
googleanalytics: process.env.GOOGLE_ANALYTICS_TOKEN
}
return
return
app.post '/', (req, res) ->
AM.manualLogin req.body.user, req.body.pass, (e, o) ->
if !o
res.status(400).send(e)
else
req.session.user = o
if req.body['remember-me'] == 'true'
updateCookieAge o, res
res.status(200).send o
return
return
# update apikey
app.post '/update/apikey', (req, res) ->
# check if the user's credentials are saved in a cookie //
data = {}
response = {msg:"could not update apikey"}
if req.cookies.user == undefined or req.cookies.pass == undefined
response.msg = "session expired, please re-login"
res.end JSON.stringify(response)
else
# attempt automatic login //
AM.autoLogin req.cookies.user, req.cookies.pass, (o) ->
if o == null
response.msg = "could not load user, please re-login"
res.end JSON.stringify(response)
else
req.session.user = o
if req.cookies.user != undefined and req.cookies.pass != undefined
updateCookieAge o, res
d = new Date()
AM.generateApiKey d.getMilliseconds()+d, (apikey) ->
AM.updateApiKey o.user, apikey, (e, o) ->
if e
response.msg = "could not regenerate apikey for user "+o.user +", please try again later"
else
response.msg = "your new apikey is "+apikey
response.apikey = apikey
# update the user's login cookies if they exists //
res.end JSON.stringify(response)
return
return
# logged-in user homepage //
app.get '/home', (req, res) ->
if req.session.user == null
# if user is not logged-in redirect back to login page //
res.redirect '/'
else
res.render 'home.jade',
metaformurl: layout.formurl
menu: layout.menu
brand: layout.title.brand
countries: CT
udata: req.session.user
googleanalytics: process.env.GOOGLE_ANALYTICS_TOKEN
return
app.post '/home', (req, res) ->
if req.body.user != undefined
data = {
user: req.body.user
name: req.body.name
email: req.body.email
country: req.body.country
pass: req.body.pass
}
data.meta = JSON.parse( req.body['meta'] ) if req.params['meta']
console.dir data
AM.updateAccount data, (e, o) ->
if e
res.status(400).send 'error-updating-account'
else
req.session.user = o
# update the user's login cookies if they exists //
if req.cookies.user != undefined and req.cookies.pass != undefined
updateCookieAge o, res
res.status(200).send 'ok'
return
else if req.body['logout'] == 'true'
res.clearCookie 'user'
res.clearCookie 'pass'
req.session.destroy (e) ->
res.status(200).send 'ok'
return
return
# creating new accounts //
app.get '/signup', (req, res) ->
res.render 'signup.jade',
metaformurl: layout.formurl
brand: layout.title.brand
title: 'Signup'
countries: CT
googleanalytics: process.env.GOOGLE_ANALYTICS_TOKEN
return
app.post '/signup', (req, res) ->
console.dir req
AM.addNewAccount {
name: req.body['name']
email: req.body['email']
user: req.body['user']
pass: req.body['pass']
country: req.body['country']
meta: {}
}, (e) ->
if e
res.status(400).send e
else
res.status(200).send 'ok'
return
return
# password reset //
app.post '/lost-password', (req, res) ->
# look up the user's account via their email //
AM.getAccountByEmail req.body['email'], (o) ->
if o
res.status(200).send 'ok'
EM.dispatchResetPasswordLink o, (e, m) ->
# this callback takes a moment to return //
# should add an ajax loader to give user feedback //
if !e
# res.send('ok', 200);
else
res.status(400).send 'email-server-error'
for k of e
console.log 'error : ', k, e[k]
return
else
res.status(400).send 'email-not-found'
return
return
app.get '/reset-password', (req, res) ->
email = req.query['e']
passH = req.query['p']
AM.validateResetLink email, passH, (e) ->
if e != 'ok'
res.redirect '/'
else
# save the user's email in a session instead of sending to the client //
req.session.reset =
email: email
passHash: passH
res.render 'reset.jade', {
title: 'Reset Password', brand: layout.title.brand
googleanalytics: process.env.GOOGLE_ANALYTICS_TOKEN
}
return
return
app.post '/reset-password', (req, res) ->
nPass = req.body['pass']
# retrieve the user's email from the session to lookup their account and reset password //
email = req.session.reset.email
# destory the session immediately after retrieving the stored email //
req.session.destroy()
AM.updatePassword email, nPass, (e, o) ->
if o
res.status(200).send 'ok'
else
res.status(400).send 'unable to update password'
return
return
# view & delete accounts (disabled because of security) //
###
app.get '/print', (req, res) ->
AM.getAllRecords (e, accounts) ->
res.render.jade 'print',
brand: layout.title.brand
title: 'Account List'
accts: accounts
googleanalytics: process.env.GOOGLE_ANALYTICS_TOKEN
return
return
###
app.post '/delete', (req, res) ->
AM.deleteAccount req.body.id, (e, obj) ->
if !e
res.clearCookie 'user'
res.clearCookie 'pass'
req.session.destroy (e) ->
res.status(200).send 'ok'
return
else
res.status(400).send 'record not found'
return
return
app.get '/reset', (req, res) ->
AM.delAllRecords ->
res.redirect '/print'
return
return
#app.get('*', function(req, res) { res.render('404.jade', { title: 'Page Not Found'}); });
this
# ---
# generated by js2coffee 2.0.3
| 186892 |
console.log "registered user signup routings"
module.exports = (app,layout,mongocfg) ->
CT = @CT = require('./modules/country-list')
AM = @AM = {}
EM = @EM = require('./modules/email-dispatcher')
AM = @AM = require('./modules/account-manager.mongo')
AM.init mongocfg
@layout = layout
updateCookieAge = (o,res) ->
res.cookie 'user', o.user, maxAge: 900000
res.cookie 'pass', o.pass, maxAge: 900000
# main login page //
app.get '/', (req, res) ->
# check if the user's credentials are saved in a cookie //
if req.cookies.user == undefined or req.cookies.pass == undefined
res.render 'login.jade', {
title: layout.title.welcome
brand: layout.title.brand
googleanalytics: process.env.GOOGLE_ANALYTICS_TOKEN
}
else
# attempt automatic login //
AM.autoLogin req.cookies.user, req.cookies.pass, (o) ->
if o != null
req.session.user = o
res.redirect '/home'
else
res.render 'login.jade', {
brand: layout.title.brand
title: layout.title.welcome
googleanalytics: process.env.GOOGLE_ANALYTICS_TOKEN
}
return
return
app.post '/', (req, res) ->
AM.manualLogin req.body.user, req.body.pass, (e, o) ->
if !o
res.status(400).send(e)
else
req.session.user = o
if req.body['remember-me'] == 'true'
updateCookieAge o, res
res.status(200).send o
return
return
# update apikey
app.post '/update/apikey', (req, res) ->
# check if the user's credentials are saved in a cookie //
data = {}
response = {msg:"could not update apikey"}
if req.cookies.user == undefined or req.cookies.pass == undefined
response.msg = "session expired, please re-login"
res.end JSON.stringify(response)
else
# attempt automatic login //
AM.autoLogin req.cookies.user, req.cookies.pass, (o) ->
if o == null
response.msg = "could not load user, please re-login"
res.end JSON.stringify(response)
else
req.session.user = o
if req.cookies.user != undefined and req.cookies.pass != undefined
updateCookieAge o, res
d = new Date()
AM.generateApiKey d.getMilliseconds()+d, (apikey) ->
AM.updateApiKey o.user, apikey, (e, o) ->
if e
response.msg = "could not regenerate apikey for user "+o.user +", please try again later"
else
response.msg = "your new apikey is "+apikey
response.apikey = apikey
# update the user's login cookies if they exists //
res.end JSON.stringify(response)
return
return
# logged-in user homepage //
app.get '/home', (req, res) ->
if req.session.user == null
# if user is not logged-in redirect back to login page //
res.redirect '/'
else
res.render 'home.jade',
metaformurl: layout.formurl
menu: layout.menu
brand: layout.title.brand
countries: CT
udata: req.session.user
googleanalytics: process.env.GOOGLE_ANALYTICS_TOKEN
return
app.post '/home', (req, res) ->
if req.body.user != undefined
data = {
user: req.body.user
name: req.body.name
email: req.body.email
country: req.body.country
pass: <PASSWORD>
}
data.meta = JSON.parse( req.body['meta'] ) if req.params['meta']
console.dir data
AM.updateAccount data, (e, o) ->
if e
res.status(400).send 'error-updating-account'
else
req.session.user = o
# update the user's login cookies if they exists //
if req.cookies.user != undefined and req.cookies.pass != undefined
updateCookieAge o, res
res.status(200).send 'ok'
return
else if req.body['logout'] == 'true'
res.clearCookie 'user'
res.clearCookie 'pass'
req.session.destroy (e) ->
res.status(200).send 'ok'
return
return
# creating new accounts //
app.get '/signup', (req, res) ->
res.render 'signup.jade',
metaformurl: layout.formurl
brand: layout.title.brand
title: 'Signup'
countries: CT
googleanalytics: process.env.GOOGLE_ANALYTICS_TOKEN
return
app.post '/signup', (req, res) ->
console.dir req
AM.addNewAccount {
name: req.body['name']
email: req.body['email']
user: req.body['user']
pass: <PASSWORD>['<PASSWORD>']
country: req.body['country']
meta: {}
}, (e) ->
if e
res.status(400).send e
else
res.status(200).send 'ok'
return
return
# password reset //
app.post '/lost-password', (req, res) ->
# look up the user's account via their email //
AM.getAccountByEmail req.body['email'], (o) ->
if o
res.status(200).send 'ok'
EM.dispatchResetPasswordLink o, (e, m) ->
# this callback takes a moment to return //
# should add an ajax loader to give user feedback //
if !e
# res.send('ok', 200);
else
res.status(400).send 'email-server-error'
for k of e
console.log 'error : ', k, e[k]
return
else
res.status(400).send 'email-not-found'
return
return
app.get '/reset-password', (req, res) ->
email = req.query['e']
passH = req.query['p']
AM.validateResetLink email, passH, (e) ->
if e != 'ok'
res.redirect '/'
else
# save the user's email in a session instead of sending to the client //
req.session.reset =
email: email
passHash: <PASSWORD>
res.render 'reset.jade', {
title: 'Reset Password', brand: layout.title.brand
googleanalytics: process.env.GOOGLE_ANALYTICS_TOKEN
}
return
return
app.post '/reset-password', (req, res) ->
nPass = req.body['pass']
# retrieve the user's email from the session to lookup their account and reset password //
email = req.session.reset.email
# destory the session immediately after retrieving the stored email //
req.session.destroy()
AM.updatePassword email, nPass, (e, o) ->
if o
res.status(200).send 'ok'
else
res.status(400).send 'unable to update password'
return
return
# view & delete accounts (disabled because of security) //
###
app.get '/print', (req, res) ->
AM.getAllRecords (e, accounts) ->
res.render.jade 'print',
brand: layout.title.brand
title: 'Account List'
accts: accounts
googleanalytics: process.env.GOOGLE_ANALYTICS_TOKEN
return
return
###
app.post '/delete', (req, res) ->
AM.deleteAccount req.body.id, (e, obj) ->
if !e
res.clearCookie 'user'
res.clearCookie 'pass'
req.session.destroy (e) ->
res.status(200).send 'ok'
return
else
res.status(400).send 'record not found'
return
return
app.get '/reset', (req, res) ->
AM.delAllRecords ->
res.redirect '/print'
return
return
#app.get('*', function(req, res) { res.render('404.jade', { title: 'Page Not Found'}); });
this
# ---
# generated by js2coffee 2.0.3
| true |
console.log "registered user signup routings"
module.exports = (app,layout,mongocfg) ->
CT = @CT = require('./modules/country-list')
AM = @AM = {}
EM = @EM = require('./modules/email-dispatcher')
AM = @AM = require('./modules/account-manager.mongo')
AM.init mongocfg
@layout = layout
updateCookieAge = (o,res) ->
res.cookie 'user', o.user, maxAge: 900000
res.cookie 'pass', o.pass, maxAge: 900000
# main login page //
app.get '/', (req, res) ->
# check if the user's credentials are saved in a cookie //
if req.cookies.user == undefined or req.cookies.pass == undefined
res.render 'login.jade', {
title: layout.title.welcome
brand: layout.title.brand
googleanalytics: process.env.GOOGLE_ANALYTICS_TOKEN
}
else
# attempt automatic login //
AM.autoLogin req.cookies.user, req.cookies.pass, (o) ->
if o != null
req.session.user = o
res.redirect '/home'
else
res.render 'login.jade', {
brand: layout.title.brand
title: layout.title.welcome
googleanalytics: process.env.GOOGLE_ANALYTICS_TOKEN
}
return
return
app.post '/', (req, res) ->
AM.manualLogin req.body.user, req.body.pass, (e, o) ->
if !o
res.status(400).send(e)
else
req.session.user = o
if req.body['remember-me'] == 'true'
updateCookieAge o, res
res.status(200).send o
return
return
# update apikey
app.post '/update/apikey', (req, res) ->
# check if the user's credentials are saved in a cookie //
data = {}
response = {msg:"could not update apikey"}
if req.cookies.user == undefined or req.cookies.pass == undefined
response.msg = "session expired, please re-login"
res.end JSON.stringify(response)
else
# attempt automatic login //
AM.autoLogin req.cookies.user, req.cookies.pass, (o) ->
if o == null
response.msg = "could not load user, please re-login"
res.end JSON.stringify(response)
else
req.session.user = o
if req.cookies.user != undefined and req.cookies.pass != undefined
updateCookieAge o, res
d = new Date()
AM.generateApiKey d.getMilliseconds()+d, (apikey) ->
AM.updateApiKey o.user, apikey, (e, o) ->
if e
response.msg = "could not regenerate apikey for user "+o.user +", please try again later"
else
response.msg = "your new apikey is "+apikey
response.apikey = apikey
# update the user's login cookies if they exists //
res.end JSON.stringify(response)
return
return
# logged-in user homepage //
app.get '/home', (req, res) ->
if req.session.user == null
# if user is not logged-in redirect back to login page //
res.redirect '/'
else
res.render 'home.jade',
metaformurl: layout.formurl
menu: layout.menu
brand: layout.title.brand
countries: CT
udata: req.session.user
googleanalytics: process.env.GOOGLE_ANALYTICS_TOKEN
return
app.post '/home', (req, res) ->
if req.body.user != undefined
data = {
user: req.body.user
name: req.body.name
email: req.body.email
country: req.body.country
pass: PI:PASSWORD:<PASSWORD>END_PI
}
data.meta = JSON.parse( req.body['meta'] ) if req.params['meta']
console.dir data
AM.updateAccount data, (e, o) ->
if e
res.status(400).send 'error-updating-account'
else
req.session.user = o
# update the user's login cookies if they exists //
if req.cookies.user != undefined and req.cookies.pass != undefined
updateCookieAge o, res
res.status(200).send 'ok'
return
else if req.body['logout'] == 'true'
res.clearCookie 'user'
res.clearCookie 'pass'
req.session.destroy (e) ->
res.status(200).send 'ok'
return
return
# creating new accounts //
app.get '/signup', (req, res) ->
res.render 'signup.jade',
metaformurl: layout.formurl
brand: layout.title.brand
title: 'Signup'
countries: CT
googleanalytics: process.env.GOOGLE_ANALYTICS_TOKEN
return
app.post '/signup', (req, res) ->
console.dir req
AM.addNewAccount {
name: req.body['name']
email: req.body['email']
user: req.body['user']
pass: PI:PASSWORD:<PASSWORD>END_PI['PI:PASSWORD:<PASSWORD>END_PI']
country: req.body['country']
meta: {}
}, (e) ->
if e
res.status(400).send e
else
res.status(200).send 'ok'
return
return
# password reset //
app.post '/lost-password', (req, res) ->
# look up the user's account via their email //
AM.getAccountByEmail req.body['email'], (o) ->
if o
res.status(200).send 'ok'
EM.dispatchResetPasswordLink o, (e, m) ->
# this callback takes a moment to return //
# should add an ajax loader to give user feedback //
if !e
# res.send('ok', 200);
else
res.status(400).send 'email-server-error'
for k of e
console.log 'error : ', k, e[k]
return
else
res.status(400).send 'email-not-found'
return
return
app.get '/reset-password', (req, res) ->
email = req.query['e']
passH = req.query['p']
AM.validateResetLink email, passH, (e) ->
if e != 'ok'
res.redirect '/'
else
# save the user's email in a session instead of sending to the client //
req.session.reset =
email: email
passHash: PI:PASSWORD:<PASSWORD>END_PI
res.render 'reset.jade', {
title: 'Reset Password', brand: layout.title.brand
googleanalytics: process.env.GOOGLE_ANALYTICS_TOKEN
}
return
return
app.post '/reset-password', (req, res) ->
nPass = req.body['pass']
# retrieve the user's email from the session to lookup their account and reset password //
email = req.session.reset.email
# destory the session immediately after retrieving the stored email //
req.session.destroy()
AM.updatePassword email, nPass, (e, o) ->
if o
res.status(200).send 'ok'
else
res.status(400).send 'unable to update password'
return
return
# view & delete accounts (disabled because of security) //
###
app.get '/print', (req, res) ->
AM.getAllRecords (e, accounts) ->
res.render.jade 'print',
brand: layout.title.brand
title: 'Account List'
accts: accounts
googleanalytics: process.env.GOOGLE_ANALYTICS_TOKEN
return
return
###
app.post '/delete', (req, res) ->
AM.deleteAccount req.body.id, (e, obj) ->
if !e
res.clearCookie 'user'
res.clearCookie 'pass'
req.session.destroy (e) ->
res.status(200).send 'ok'
return
else
res.status(400).send 'record not found'
return
return
app.get '/reset', (req, res) ->
AM.delAllRecords ->
res.redirect '/print'
return
return
#app.get('*', function(req, res) { res.render('404.jade', { title: 'Page Not Found'}); });
this
# ---
# generated by js2coffee 2.0.3
|
[
{
"context": "an error msg', (assert) ->\n model = \n email: \"foxnewsnetwork@gmail.com\"\n username: \"foxnewsnetwork\"\n\n checker = (mod",
"end": 386,
"score": 0.9999209642410278,
"start": 362,
"tag": "EMAIL",
"value": "foxnewsnetwork@gmail.com"
},
{
"context": " email: \"foxnewsnetwork@gmail.com\"\n username: \"foxnewsnetwork\"\n\n checker = (model) ->\n \"bad model is bad\"\n\n",
"end": 417,
"score": 0.9995673298835754,
"start": 403,
"tag": "USERNAME",
"value": "foxnewsnetwork"
},
{
"context": "kers as well', (assert) ->\n model = \n email: \"foxnewsnetwork@gmail.com\"\n username: \"foxnewsnetwork\"\n\n checker = (mod",
"end": 1124,
"score": 0.9999188780784607,
"start": 1100,
"tag": "EMAIL",
"value": "foxnewsnetwork@gmail.com"
},
{
"context": " email: \"foxnewsnetwork@gmail.com\"\n username: \"foxnewsnetwork\"\n\n checker = (model) ->\n new Ember.RSVP.Promi",
"end": 1155,
"score": 0.999565839767456,
"start": 1141,
"tag": "USERNAME",
"value": "foxnewsnetwork"
},
{
"context": "strings also', (assert) ->\n model = \n email: \"foxnewsnetwork@gmail.com\"\n username: \"foxnewsnetwork\"\n\n checker = (mod",
"end": 1622,
"score": 0.9999202489852905,
"start": 1598,
"tag": "EMAIL",
"value": "foxnewsnetwork@gmail.com"
},
{
"context": " email: \"foxnewsnetwork@gmail.com\"\n username: \"foxnewsnetwork\"\n\n checker = (model) ->\n new Ember.RSVP.Promi",
"end": 1653,
"score": 0.9995679259300232,
"start": 1639,
"tag": "USERNAME",
"value": "foxnewsnetwork"
},
{
"context": "pture errors', (assert) ->\n model = \n email: \"foxnewsnetwork@gmail.com\"\n username: \"foxnewsnetwork\"\n\n checker = (mod",
"end": 2107,
"score": 0.9999181628227234,
"start": 2083,
"tag": "EMAIL",
"value": "foxnewsnetwork@gmail.com"
},
{
"context": " email: \"foxnewsnetwork@gmail.com\"\n username: \"foxnewsnetwork\"\n\n checker = (model) ->\n new Ember.RSVP.Promi",
"end": 2138,
"score": 0.9995205998420715,
"start": 2124,
"tag": "USERNAME",
"value": "foxnewsnetwork"
},
{
"context": "ould be fine', (assert) ->\n model = \n email: \"foxnewsnetwork@gmail.com\"\n\n checker = (model) -> null\n custom \"email\", c",
"end": 2566,
"score": 0.9999176263809204,
"start": 2542,
"tag": "EMAIL",
"value": "foxnewsnetwork@gmail.com"
},
{
"context": "as a promise', (assert) ->\n model = \n email: \"foxnewsnetwork@gmail.com\"\n\n checker = (model) -> \n new Ember.RSVP.Prom",
"end": 2897,
"score": 0.9999154210090637,
"start": 2873,
"tag": "EMAIL",
"value": "foxnewsnetwork@gmail.com"
}
] | tests/unit/validators/custom-test.coffee | foxnewsnetwork/ember-functional-validation | 4 | `import Ember from 'ember'`
`import { module, test } from 'qunit'`
`import custom from 'ember-functional-validation/validators/custom'`
module 'Validators: Custom'
test 'it should exist', (assert) ->
assert.ok custom
assert.equal typeof custom, 'function'
test 'it should error out if the checker returns an error msg', (assert) ->
model =
email: "foxnewsnetwork@gmail.com"
username: "foxnewsnetwork"
checker = (model) ->
"bad model is bad"
custom "email", checker, model
.then ->
assert.ok false, "it should not resolve a bad check"
.catch (errors) ->
assert.equal errors.size, 1
assert.deepEqual errors.get("email"), ["bad model is bad"]
test 'it should properly have the attribute passed in', (assert) ->
model =
donkey: "animal"
checker = (model, attribute) ->
assert.equal attribute, "donkey"
"animal should be donkey"
custom "donkey", checker, model
.catch (errors) ->
assert.deepEqual errors.get("donkey"), ["animal should be donkey"]
test 'it should resolve promise checkers as well', (assert) ->
model =
email: "foxnewsnetwork@gmail.com"
username: "foxnewsnetwork"
checker = (model) ->
new Ember.RSVP.Promise (resolve) ->
Ember.run.later @, ( -> resolve "some error message" ), 75
custom "email", checker, model
.then ->
assert.ok false, "it should not resolve a bad check"
.catch (errors) ->
assert.equal errors.size, 1
assert.deepEqual errors.get("email"), ["some error message"]
test 'it should properly handle rejected strings also', (assert) ->
model =
email: "foxnewsnetwork@gmail.com"
username: "foxnewsnetwork"
checker = (model) ->
new Ember.RSVP.Promise (_, reject) ->
Ember.run.later @, ( -> reject "some error message" ), 75
custom "email", checker, model
.then ->
assert.ok false, "it should not resolve a bad check"
.catch (errors) ->
assert.equal errors.size, 1
assert.deepEqual errors.get("email"), ["some error message"]
test 'it should properly capture errors', (assert) ->
model =
email: "foxnewsnetwork@gmail.com"
username: "foxnewsnetwork"
checker = (model) ->
new Ember.RSVP.Promise ->
throw new Error "dog food is tasty"
custom "email", checker, model
.then ->
assert.ok false, "it should not resolve a bad check"
.catch (errors) ->
assert.equal errors.size, 1
assert.deepEqual errors.get("email"), ["dog food is tasty"]
test 'things that pass validation should be fine', (assert) ->
model =
email: "foxnewsnetwork@gmail.com"
checker = (model) -> null
custom "email", checker, model
.then (checkedModel) ->
assert.equal model, checkedModel
.catch ->
assert.ok false, "it should not have rejected good models"
test 'things that pass validation should be fine even as a promise', (assert) ->
model =
email: "foxnewsnetwork@gmail.com"
checker = (model) ->
new Ember.RSVP.Promise (resolve) ->
Ember.run.later @, resolve, 15
custom "email", checker, model
.then (checkedModel) ->
assert.equal model, checkedModel
.catch ->
assert.ok false, "it should not have rejected good models" | 28515 | `import Ember from 'ember'`
`import { module, test } from 'qunit'`
`import custom from 'ember-functional-validation/validators/custom'`
module 'Validators: Custom'
test 'it should exist', (assert) ->
assert.ok custom
assert.equal typeof custom, 'function'
test 'it should error out if the checker returns an error msg', (assert) ->
model =
email: "<EMAIL>"
username: "foxnewsnetwork"
checker = (model) ->
"bad model is bad"
custom "email", checker, model
.then ->
assert.ok false, "it should not resolve a bad check"
.catch (errors) ->
assert.equal errors.size, 1
assert.deepEqual errors.get("email"), ["bad model is bad"]
test 'it should properly have the attribute passed in', (assert) ->
model =
donkey: "animal"
checker = (model, attribute) ->
assert.equal attribute, "donkey"
"animal should be donkey"
custom "donkey", checker, model
.catch (errors) ->
assert.deepEqual errors.get("donkey"), ["animal should be donkey"]
test 'it should resolve promise checkers as well', (assert) ->
model =
email: "<EMAIL>"
username: "foxnewsnetwork"
checker = (model) ->
new Ember.RSVP.Promise (resolve) ->
Ember.run.later @, ( -> resolve "some error message" ), 75
custom "email", checker, model
.then ->
assert.ok false, "it should not resolve a bad check"
.catch (errors) ->
assert.equal errors.size, 1
assert.deepEqual errors.get("email"), ["some error message"]
test 'it should properly handle rejected strings also', (assert) ->
model =
email: "<EMAIL>"
username: "foxnewsnetwork"
checker = (model) ->
new Ember.RSVP.Promise (_, reject) ->
Ember.run.later @, ( -> reject "some error message" ), 75
custom "email", checker, model
.then ->
assert.ok false, "it should not resolve a bad check"
.catch (errors) ->
assert.equal errors.size, 1
assert.deepEqual errors.get("email"), ["some error message"]
test 'it should properly capture errors', (assert) ->
model =
email: "<EMAIL>"
username: "foxnewsnetwork"
checker = (model) ->
new Ember.RSVP.Promise ->
throw new Error "dog food is tasty"
custom "email", checker, model
.then ->
assert.ok false, "it should not resolve a bad check"
.catch (errors) ->
assert.equal errors.size, 1
assert.deepEqual errors.get("email"), ["dog food is tasty"]
test 'things that pass validation should be fine', (assert) ->
model =
email: "<EMAIL>"
checker = (model) -> null
custom "email", checker, model
.then (checkedModel) ->
assert.equal model, checkedModel
.catch ->
assert.ok false, "it should not have rejected good models"
test 'things that pass validation should be fine even as a promise', (assert) ->
model =
email: "<EMAIL>"
checker = (model) ->
new Ember.RSVP.Promise (resolve) ->
Ember.run.later @, resolve, 15
custom "email", checker, model
.then (checkedModel) ->
assert.equal model, checkedModel
.catch ->
assert.ok false, "it should not have rejected good models" | true | `import Ember from 'ember'`
`import { module, test } from 'qunit'`
`import custom from 'ember-functional-validation/validators/custom'`
module 'Validators: Custom'
test 'it should exist', (assert) ->
assert.ok custom
assert.equal typeof custom, 'function'
test 'it should error out if the checker returns an error msg', (assert) ->
model =
email: "PI:EMAIL:<EMAIL>END_PI"
username: "foxnewsnetwork"
checker = (model) ->
"bad model is bad"
custom "email", checker, model
.then ->
assert.ok false, "it should not resolve a bad check"
.catch (errors) ->
assert.equal errors.size, 1
assert.deepEqual errors.get("email"), ["bad model is bad"]
test 'it should properly have the attribute passed in', (assert) ->
model =
donkey: "animal"
checker = (model, attribute) ->
assert.equal attribute, "donkey"
"animal should be donkey"
custom "donkey", checker, model
.catch (errors) ->
assert.deepEqual errors.get("donkey"), ["animal should be donkey"]
test 'it should resolve promise checkers as well', (assert) ->
model =
email: "PI:EMAIL:<EMAIL>END_PI"
username: "foxnewsnetwork"
checker = (model) ->
new Ember.RSVP.Promise (resolve) ->
Ember.run.later @, ( -> resolve "some error message" ), 75
custom "email", checker, model
.then ->
assert.ok false, "it should not resolve a bad check"
.catch (errors) ->
assert.equal errors.size, 1
assert.deepEqual errors.get("email"), ["some error message"]
test 'it should properly handle rejected strings also', (assert) ->
model =
email: "PI:EMAIL:<EMAIL>END_PI"
username: "foxnewsnetwork"
checker = (model) ->
new Ember.RSVP.Promise (_, reject) ->
Ember.run.later @, ( -> reject "some error message" ), 75
custom "email", checker, model
.then ->
assert.ok false, "it should not resolve a bad check"
.catch (errors) ->
assert.equal errors.size, 1
assert.deepEqual errors.get("email"), ["some error message"]
test 'it should properly capture errors', (assert) ->
model =
email: "PI:EMAIL:<EMAIL>END_PI"
username: "foxnewsnetwork"
checker = (model) ->
new Ember.RSVP.Promise ->
throw new Error "dog food is tasty"
custom "email", checker, model
.then ->
assert.ok false, "it should not resolve a bad check"
.catch (errors) ->
assert.equal errors.size, 1
assert.deepEqual errors.get("email"), ["dog food is tasty"]
test 'things that pass validation should be fine', (assert) ->
model =
email: "PI:EMAIL:<EMAIL>END_PI"
checker = (model) -> null
custom "email", checker, model
.then (checkedModel) ->
assert.equal model, checkedModel
.catch ->
assert.ok false, "it should not have rejected good models"
test 'things that pass validation should be fine even as a promise', (assert) ->
model =
email: "PI:EMAIL:<EMAIL>END_PI"
checker = (model) ->
new Ember.RSVP.Promise (resolve) ->
Ember.run.later @, resolve, 15
custom "email", checker, model
.then (checkedModel) ->
assert.equal model, checkedModel
.catch ->
assert.ok false, "it should not have rejected good models" |
[
{
"context": "###\ngrunt-styledocco\nhttps://github.com/weareinteractive/grunt-styledocco\n\nCopyright (c) 2013 We Are Inter",
"end": 56,
"score": 0.9995620250701904,
"start": 40,
"tag": "USERNAME",
"value": "weareinteractive"
},
{
"context": "reinteractive/grunt-styledocco\n\nCopyright (c) 2013 We Are Interactive\nLicensed under the MIT license.\n###\n\nmodule.expor",
"end": 112,
"score": 0.9951248168945312,
"start": 94,
"tag": "NAME",
"value": "We Are Interactive"
}
] | Gruntfile.coffee | gruntjs-updater/grunt-styledocco | 0 | ###
grunt-styledocco
https://github.com/weareinteractive/grunt-styledocco
Copyright (c) 2013 We Are Interactive
Licensed under the MIT license.
###
module.exports = (grunt) ->
"use strict"
# Project configuration.
grunt.initConfig
pkg: grunt.file.readJSON "package.json"
coffeelint:
files: ["Gruntfile.coffee", "tasks/**/*.coffee", "test/**/*.coffee"]
options:
max_line_length:
value: 200
level: "error"
clean:
test:
src: ["test/tmp/*"]
# Run for unit tests
styledocco:
test:
options:
name: "<%= pkg.name %> v<%= pkg.version %>"
cmd: "node_modules/.bin/styledocco"
files: [
"test/tmp": "test/fixtures"
]
# Unit tests.
mochacov:
options:
bail: true
ui: 'exports'
require: 'coffee-script'
compilers: ['coffee:coffee-script/register']
files: 'test/specs/**/*.coffee'
all:
options:
reporter: 'spec'
# Deployment
bumper:
options:
push: false
createTag: false
tasks: ["default"]
files: ["package.json"]
updateConfigs: ["pkg"]
# Actually load this plugin's task(s).
grunt.loadTasks "tasks"
# Load npm tasks
grunt.loadNpmTasks "grunt-coffeelint"
grunt.loadNpmTasks "grunt-contrib-clean"
grunt.loadNpmTasks "grunt-mocha-cov"
grunt.loadNpmTasks "grunt-bumper"
# Tasks
grunt.registerTask "default", ["coffeelint"]
grunt.registerTask "test", ["default", "clean", "styledocco", "mochacov"]
| 199258 | ###
grunt-styledocco
https://github.com/weareinteractive/grunt-styledocco
Copyright (c) 2013 <NAME>
Licensed under the MIT license.
###
module.exports = (grunt) ->
"use strict"
# Project configuration.
grunt.initConfig
pkg: grunt.file.readJSON "package.json"
coffeelint:
files: ["Gruntfile.coffee", "tasks/**/*.coffee", "test/**/*.coffee"]
options:
max_line_length:
value: 200
level: "error"
clean:
test:
src: ["test/tmp/*"]
# Run for unit tests
styledocco:
test:
options:
name: "<%= pkg.name %> v<%= pkg.version %>"
cmd: "node_modules/.bin/styledocco"
files: [
"test/tmp": "test/fixtures"
]
# Unit tests.
mochacov:
options:
bail: true
ui: 'exports'
require: 'coffee-script'
compilers: ['coffee:coffee-script/register']
files: 'test/specs/**/*.coffee'
all:
options:
reporter: 'spec'
# Deployment
bumper:
options:
push: false
createTag: false
tasks: ["default"]
files: ["package.json"]
updateConfigs: ["pkg"]
# Actually load this plugin's task(s).
grunt.loadTasks "tasks"
# Load npm tasks
grunt.loadNpmTasks "grunt-coffeelint"
grunt.loadNpmTasks "grunt-contrib-clean"
grunt.loadNpmTasks "grunt-mocha-cov"
grunt.loadNpmTasks "grunt-bumper"
# Tasks
grunt.registerTask "default", ["coffeelint"]
grunt.registerTask "test", ["default", "clean", "styledocco", "mochacov"]
| true | ###
grunt-styledocco
https://github.com/weareinteractive/grunt-styledocco
Copyright (c) 2013 PI:NAME:<NAME>END_PI
Licensed under the MIT license.
###
module.exports = (grunt) ->
"use strict"
# Project configuration.
grunt.initConfig
pkg: grunt.file.readJSON "package.json"
coffeelint:
files: ["Gruntfile.coffee", "tasks/**/*.coffee", "test/**/*.coffee"]
options:
max_line_length:
value: 200
level: "error"
clean:
test:
src: ["test/tmp/*"]
# Run for unit tests
styledocco:
test:
options:
name: "<%= pkg.name %> v<%= pkg.version %>"
cmd: "node_modules/.bin/styledocco"
files: [
"test/tmp": "test/fixtures"
]
# Unit tests.
mochacov:
options:
bail: true
ui: 'exports'
require: 'coffee-script'
compilers: ['coffee:coffee-script/register']
files: 'test/specs/**/*.coffee'
all:
options:
reporter: 'spec'
# Deployment
bumper:
options:
push: false
createTag: false
tasks: ["default"]
files: ["package.json"]
updateConfigs: ["pkg"]
# Actually load this plugin's task(s).
grunt.loadTasks "tasks"
# Load npm tasks
grunt.loadNpmTasks "grunt-coffeelint"
grunt.loadNpmTasks "grunt-contrib-clean"
grunt.loadNpmTasks "grunt-mocha-cov"
grunt.loadNpmTasks "grunt-bumper"
# Tasks
grunt.registerTask "default", ["coffeelint"]
grunt.registerTask "test", ["default", "clean", "styledocco", "mochacov"]
|
[
{
"context": "`null` representation for Date flags\nfor key in ['archived', 'protected', 'raised'] # 'deleted' always used nul",
"end": 401,
"score": 0.8440488576889038,
"start": 389,
"tag": "KEY",
"value": "archived', '"
},
{
"context": "sentation for Date flags\nfor key in ['archived', 'protected', 'raised'] # 'deleted' always used null\n for db in",
"end": 414,
"score": 0.7159886360168457,
"start": 401,
"tag": "KEY",
"value": "protected', '"
},
{
"context": " Date flags\nfor key in ['archived', 'protected', 'raised'] # 'deleted' always used null\n for db in [Room",
"end": 420,
"score": 0.683299720287323,
"start": 414,
"tag": "KEY",
"value": "raised"
}
] | server/bootstrap.coffee | mehtank/comingle | 37 | import {Meetings, makeMeetingSecret} from '/lib/meetings'
import {Rooms} from '/lib/rooms'
import {Tabs} from '/lib/tabs'
## Add missing meeting secrets (though still only gettable via database)
Meetings.find
secret: $exists: false
.forEach (room) ->
Meetings.update room._id, $set: secret: makeMeetingSecret()
## Convert `false` to `null` representation for Date flags
for key in ['archived', 'protected', 'raised'] # 'deleted' always used null
for db in [Rooms, Tabs]
db.update
"#{key}": false
,
$set: "#{key}": null
,
multi: true
console.log 'Upgraded database as necessary.'
| 199629 | import {Meetings, makeMeetingSecret} from '/lib/meetings'
import {Rooms} from '/lib/rooms'
import {Tabs} from '/lib/tabs'
## Add missing meeting secrets (though still only gettable via database)
Meetings.find
secret: $exists: false
.forEach (room) ->
Meetings.update room._id, $set: secret: makeMeetingSecret()
## Convert `false` to `null` representation for Date flags
for key in ['<KEY> <KEY> <KEY>'] # 'deleted' always used null
for db in [Rooms, Tabs]
db.update
"#{key}": false
,
$set: "#{key}": null
,
multi: true
console.log 'Upgraded database as necessary.'
| true | import {Meetings, makeMeetingSecret} from '/lib/meetings'
import {Rooms} from '/lib/rooms'
import {Tabs} from '/lib/tabs'
## Add missing meeting secrets (though still only gettable via database)
Meetings.find
secret: $exists: false
.forEach (room) ->
Meetings.update room._id, $set: secret: makeMeetingSecret()
## Convert `false` to `null` representation for Date flags
for key in ['PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI'] # 'deleted' always used null
for db in [Rooms, Tabs]
db.update
"#{key}": false
,
$set: "#{key}": null
,
multi: true
console.log 'Upgraded database as necessary.'
|
[
{
"context": "raph.coffee\n# Library for graph theory functions\n# J. Hassler Thurston\n# Adapted from Mathematica code written in 2010-2",
"end": 73,
"score": 0.9998629093170166,
"start": 54,
"tag": "NAME",
"value": "J. Hassler Thurston"
}
] | graph.js.coffee | jthurst3/computermusic | 0 | # graph.coffee
# Library for graph theory functions
# J. Hassler Thurston
# Adapted from Mathematica code written in 2010-2011
# January 24, 2014
# graphs:
# represented by an object, which has vertex and edge attributes
# the vertices are represented by an array of vertex names
# the edges are represented by a ragged array, where the ith array contains other vertices connected to the ith vertex
# e.g. the graph with edges 1->2, 0->3, 4->1, 1->0 would be represented by the object
# {
# vertices: [1,2,0,3,4],
# edges: [[2,0],[],[3],[],[1]]
# }
# creates a graph with the given edges
class Graph
constructor: (@edges) ->
vertices = (edge[0] for edge in edges if edge[0] not in vertices)
| 57184 | # graph.coffee
# Library for graph theory functions
# <NAME>
# Adapted from Mathematica code written in 2010-2011
# January 24, 2014
# graphs:
# represented by an object, which has vertex and edge attributes
# the vertices are represented by an array of vertex names
# the edges are represented by a ragged array, where the ith array contains other vertices connected to the ith vertex
# e.g. the graph with edges 1->2, 0->3, 4->1, 1->0 would be represented by the object
# {
# vertices: [1,2,0,3,4],
# edges: [[2,0],[],[3],[],[1]]
# }
# creates a graph with the given edges
class Graph
constructor: (@edges) ->
vertices = (edge[0] for edge in edges if edge[0] not in vertices)
| true | # graph.coffee
# Library for graph theory functions
# PI:NAME:<NAME>END_PI
# Adapted from Mathematica code written in 2010-2011
# January 24, 2014
# graphs:
# represented by an object, which has vertex and edge attributes
# the vertices are represented by an array of vertex names
# the edges are represented by a ragged array, where the ith array contains other vertices connected to the ith vertex
# e.g. the graph with edges 1->2, 0->3, 4->1, 1->0 would be represented by the object
# {
# vertices: [1,2,0,3,4],
# edges: [[2,0],[],[3],[],[1]]
# }
# creates a graph with the given edges
class Graph
constructor: (@edges) ->
vertices = (edge[0] for edge in edges if edge[0] not in vertices)
|
[
{
"context": "{{/with}}\n</div>\n\"\"\"\n\t\tvm =\n\t\t\titem: {\n\t\t\t\tname: 'test'\n\t\t\t}\n\t\tko.applyBindings vm\n\n\t\t$('.item').text().",
"end": 1955,
"score": 0.9960554838180542,
"start": 1951,
"tag": "NAME",
"value": "test"
}
] | test/test.coffee | sergeyt/knockout-handlebars | 3 | describe 'ko.handlebars', ->
init = ->
ko.cleanNode document.body
div = $ '#sandbox'
$('<div id="sandbox"></div>').appendTo($('body')) unless div.length
div.html ''
template = (s) ->
init()
$(s).appendTo $('#sandbox')
it 'should replace text nodes', ->
template '<div class="test">before {{value}} after</div>'
vm = {value: 'test'}
ko.applyBindings vm
$('.test').text().should.eql 'before test after'
it 'should replace attribute', ->
template '<input class="test {{cls}}" value="test {{value}}"/>'
vm = {value: 'text', cls: 'error'}
ko.applyBindings vm
e = $ '.test'
e.val().should.eql 'test text'
e.hasClass('error').should.be.ok
e.is('[value]').should.be.false
it 'should replace ko- attribute', ->
template '<input class="test" ko-value="value"/>'
vm = {value: 'test'}
ko.applyBindings vm
e = $ '.test'
e.val().should.eql 'test'
e.attr('data-bind').should.eql 'value:value'
e.is('[ko-value]').should.be.false
it 'should process {{#each expr}}', ->
template """
<div class="test">
{{#each items}}
<span class="item">{{name}}</span>
{{/each}}
</div>
"""
vm =
items: [
{name: 'A'}
{name: 'B'}
{name: 'C'}
]
ko.applyBindings vm
$('.item').length.should.eql 3
$('.item:nth-child(1)').text().should.eql 'A'
$('.item:nth-child(2)').text().should.eql 'B'
$('.item:nth-child(3)').text().should.eql 'C'
it 'should process {{#if expr}}', ->
html = """
<div class="test">
{{#unless valid}}
<span>invalid</span>
{{/unless}}
{{#if valid}}
<span>valid</span>
{{/if}}
</div>
"""
run = (valid) ->
template html
vm = {valid: valid}
ko.applyBindings vm
expected = if valid then "valid" else "invalid"
$('.test').text().trim().should.eql expected
run false
run true
it 'should process {{#with expr}}', ->
template """
<div class="test">
{{#with item}}
<span class="item">{{name}}</span>
{{/with}}
</div>
"""
vm =
item: {
name: 'test'
}
ko.applyBindings vm
$('.item').text().should.eql 'test'
| 115896 | describe 'ko.handlebars', ->
init = ->
ko.cleanNode document.body
div = $ '#sandbox'
$('<div id="sandbox"></div>').appendTo($('body')) unless div.length
div.html ''
template = (s) ->
init()
$(s).appendTo $('#sandbox')
it 'should replace text nodes', ->
template '<div class="test">before {{value}} after</div>'
vm = {value: 'test'}
ko.applyBindings vm
$('.test').text().should.eql 'before test after'
it 'should replace attribute', ->
template '<input class="test {{cls}}" value="test {{value}}"/>'
vm = {value: 'text', cls: 'error'}
ko.applyBindings vm
e = $ '.test'
e.val().should.eql 'test text'
e.hasClass('error').should.be.ok
e.is('[value]').should.be.false
it 'should replace ko- attribute', ->
template '<input class="test" ko-value="value"/>'
vm = {value: 'test'}
ko.applyBindings vm
e = $ '.test'
e.val().should.eql 'test'
e.attr('data-bind').should.eql 'value:value'
e.is('[ko-value]').should.be.false
it 'should process {{#each expr}}', ->
template """
<div class="test">
{{#each items}}
<span class="item">{{name}}</span>
{{/each}}
</div>
"""
vm =
items: [
{name: 'A'}
{name: 'B'}
{name: 'C'}
]
ko.applyBindings vm
$('.item').length.should.eql 3
$('.item:nth-child(1)').text().should.eql 'A'
$('.item:nth-child(2)').text().should.eql 'B'
$('.item:nth-child(3)').text().should.eql 'C'
it 'should process {{#if expr}}', ->
html = """
<div class="test">
{{#unless valid}}
<span>invalid</span>
{{/unless}}
{{#if valid}}
<span>valid</span>
{{/if}}
</div>
"""
run = (valid) ->
template html
vm = {valid: valid}
ko.applyBindings vm
expected = if valid then "valid" else "invalid"
$('.test').text().trim().should.eql expected
run false
run true
it 'should process {{#with expr}}', ->
template """
<div class="test">
{{#with item}}
<span class="item">{{name}}</span>
{{/with}}
</div>
"""
vm =
item: {
name: '<NAME>'
}
ko.applyBindings vm
$('.item').text().should.eql 'test'
| true | describe 'ko.handlebars', ->
init = ->
ko.cleanNode document.body
div = $ '#sandbox'
$('<div id="sandbox"></div>').appendTo($('body')) unless div.length
div.html ''
template = (s) ->
init()
$(s).appendTo $('#sandbox')
it 'should replace text nodes', ->
template '<div class="test">before {{value}} after</div>'
vm = {value: 'test'}
ko.applyBindings vm
$('.test').text().should.eql 'before test after'
it 'should replace attribute', ->
template '<input class="test {{cls}}" value="test {{value}}"/>'
vm = {value: 'text', cls: 'error'}
ko.applyBindings vm
e = $ '.test'
e.val().should.eql 'test text'
e.hasClass('error').should.be.ok
e.is('[value]').should.be.false
it 'should replace ko- attribute', ->
template '<input class="test" ko-value="value"/>'
vm = {value: 'test'}
ko.applyBindings vm
e = $ '.test'
e.val().should.eql 'test'
e.attr('data-bind').should.eql 'value:value'
e.is('[ko-value]').should.be.false
it 'should process {{#each expr}}', ->
template """
<div class="test">
{{#each items}}
<span class="item">{{name}}</span>
{{/each}}
</div>
"""
vm =
items: [
{name: 'A'}
{name: 'B'}
{name: 'C'}
]
ko.applyBindings vm
$('.item').length.should.eql 3
$('.item:nth-child(1)').text().should.eql 'A'
$('.item:nth-child(2)').text().should.eql 'B'
$('.item:nth-child(3)').text().should.eql 'C'
it 'should process {{#if expr}}', ->
html = """
<div class="test">
{{#unless valid}}
<span>invalid</span>
{{/unless}}
{{#if valid}}
<span>valid</span>
{{/if}}
</div>
"""
run = (valid) ->
template html
vm = {valid: valid}
ko.applyBindings vm
expected = if valid then "valid" else "invalid"
$('.test').text().trim().should.eql expected
run false
run true
it 'should process {{#with expr}}', ->
template """
<div class="test">
{{#with item}}
<span class="item">{{name}}</span>
{{/with}}
</div>
"""
vm =
item: {
name: 'PI:NAME:<NAME>END_PI'
}
ko.applyBindings vm
$('.item').text().should.eql 'test'
|
[
{
"context": " JavaScript highligher\n#\n# Copyright (C) 2011-2012 Nikolay Nemshilov\n#\nColorifier.js = Colorifier.javascript = new Cla",
"end": 71,
"score": 0.9998908042907715,
"start": 54,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | src/lang/javascript.coffee | MadRabbit/colorifier | 1 | #
# JavaScript highligher
#
# Copyright (C) 2011-2012 Nikolay Nemshilov
#
Colorifier.js = Colorifier.javascript = new Class Colorifier,
comments: "/* */,//"
keywords: "function,return,for,if,else,while,do,throw,try,catch,instanceof,break,continue"
objects: "var,new,this,self"
booleans: "true,false,null,undefined,typeof"
paint: (text)->
@$super text, (text)->
text.replace /(^|[^a-z0-9_])([a-z0-9_]+)(\s*:)/ig, (m, _1, _2, _3)->
"#{_1}<span class=\"attribute\">#{_2}</span>#{_3}"
| 76040 | #
# JavaScript highligher
#
# Copyright (C) 2011-2012 <NAME>
#
Colorifier.js = Colorifier.javascript = new Class Colorifier,
comments: "/* */,//"
keywords: "function,return,for,if,else,while,do,throw,try,catch,instanceof,break,continue"
objects: "var,new,this,self"
booleans: "true,false,null,undefined,typeof"
paint: (text)->
@$super text, (text)->
text.replace /(^|[^a-z0-9_])([a-z0-9_]+)(\s*:)/ig, (m, _1, _2, _3)->
"#{_1}<span class=\"attribute\">#{_2}</span>#{_3}"
| true | #
# JavaScript highligher
#
# Copyright (C) 2011-2012 PI:NAME:<NAME>END_PI
#
Colorifier.js = Colorifier.javascript = new Class Colorifier,
comments: "/* */,//"
keywords: "function,return,for,if,else,while,do,throw,try,catch,instanceof,break,continue"
objects: "var,new,this,self"
booleans: "true,false,null,undefined,typeof"
paint: (text)->
@$super text, (text)->
text.replace /(^|[^a-z0-9_])([a-z0-9_]+)(\s*:)/ig, (m, _1, _2, _3)->
"#{_1}<span class=\"attribute\">#{_2}</span>#{_3}"
|
[
{
"context": " Looking-Glass\n\n 'Really, now you ask me,' said Alice, very much confused, 'I don't\n think—'\n\n 'T",
"end": 94,
"score": 0.7758482694625854,
"start": 89,
"tag": "NAME",
"value": "Alice"
},
{
"context": "\n 'At any rate I'll never go THERE again!' said Alice as she picked her\n way through the wood. 'It's",
"end": 629,
"score": 0.5456060767173767,
"start": 624,
"tag": "NAME",
"value": "Alice"
},
{
"context": "rm that was linked\n into hers began to tremble. Alice looked up, and there stood the Queen\n in front",
"end": 4280,
"score": 0.7167704105377197,
"start": 4275,
"tag": "NAME",
"value": "Alice"
},
{
"context": " 'Let's go on with the game,' the Queen said to Alice; and Alice was\n too much frightened to say a w",
"end": 4772,
"score": 0.5454222559928894,
"start": 4767,
"tag": "NAME",
"value": "Alice"
},
{
"context": "l the\n players, except the King, the Queen, and Alice, were in custody and\n under sentence of execut",
"end": 5558,
"score": 0.9616289138793945,
"start": 5553,
"tag": "NAME",
"value": "Alice"
},
{
"context": "een.\n\n 'I never saw one, or heard of one,' said Alice.\n\n 'Come on, then,' said the Queen, 'and he sh",
"end": 5910,
"score": 0.7293592691421509,
"start": 5905,
"tag": "NAME",
"value": "Alice"
},
{
"context": "rything about\n her, to pass away the time.\n\n Alice had never been in a court of justice before, but ",
"end": 15348,
"score": 0.960542619228363,
"start": 15343,
"tag": "NAME",
"value": "Alice"
},
{
"context": " becoming.\n\n 'And that's the jury-box,' thought Alice, 'and those twelve creatures,'\n (she was oblig",
"end": 15864,
"score": 0.7594378590583801,
"start": 15859,
"tag": "NAME",
"value": "Alice"
},
{
"context": " very busily on slates. 'What are they\n doing?' Alice whispered to the Gryphon. 'They can't have anythi",
"end": 16390,
"score": 0.6709453463554382,
"start": 16385,
"tag": "NAME",
"value": "Alice"
},
{
"context": "the top of his shrill little voice, the\n name 'Alice!'\n\n\n\n\n ## CHAPTER XII. Alice's Evidence\n\n\n ",
"end": 25623,
"score": 0.879734218120575,
"start": 25618,
"tag": "NAME",
"value": "Alice"
},
{
"context": " CHAPTER XII. Alice's Evidence\n\n\n 'Here!' cried Alice, quite forgetting in the flurry of the moment how",
"end": 25692,
"score": 0.6066675782203674,
"start": 25687,
"tag": "NAME",
"value": "Alice"
},
{
"context": ". Nobody\n moved.\n\n 'Who cares for you?' said Alice, (she had grown to her full size by this\n time",
"end": 34440,
"score": 0.9851450324058533,
"start": 34435,
"tag": "NAME",
"value": "Alice"
},
{
"context": " down from the trees upon her face.\n\n 'Wake up, Alice dear!' said her sister; 'Why, what a long sleep y",
"end": 34913,
"score": 0.9878964424133301,
"start": 34908,
"tag": "NAME",
"value": "Alice"
},
{
"context": "d!'\n\n 'Oh, I've had such a curious dream!' said Alice, and she told her\n sister, as well as she coul",
"end": 35031,
"score": 0.9922694563865662,
"start": 35026,
"tag": "NAME",
"value": "Alice"
},
{
"context": "now run in to your tea; it's getting late.' So\n Alice got up and ran off, thinking while she ran, as we",
"end": 35348,
"score": 0.9420103430747986,
"start": 35343,
"tag": "NAME",
"value": "Alice"
}
] | mingkwai.app/Contents/Resources/app.nw/src/demo-text.coffee | loveencounterflow/mingkwai-app | 0 | module.exports = """
# Through the Looking-Glass
'Really, now you ask me,' said Alice, very much confused, 'I don't
think—'
'Then you shouldn't talk,' said the Hatter.
This piece of rudeness was more than Alice could bear: she got up in
great disgust, and walked off; the Dormouse fell asleep instantly, and
neither of the others took the least notice of her going, though she
looked back once or twice, half hoping that they would call after her:
the last time she saw them, they were trying to put the Dormouse into
the teapot.
'At any rate I'll never go THERE again!' said Alice as she picked her
way through the wood. 'It's the stupidest tea-party I ever was at in all
my life!'
Just as she said this, she noticed that one of the trees had a door
leading right into it. 'That's very curious!' she thought. 'But
everything's curious today. I think I may as well go in at once.' And in
she went.
Once more she found herself in the long hall, and close to the little
glass table. 'Now, I'll manage better this time,' she said to herself,
and began by taking the little golden key, and unlocking the door that
led into the garden. Then she went to work nibbling at the mushroom (she
had kept a piece of it in her pocket) till she was about a foot high:
then she walked down the little passage: and THEN—she found herself at
last in the beautiful garden, among the bright flower-beds and the cool
fountains.
Alice opened the door and found that it led into a small passage, not
much larger than a rat-hole: she knelt down and looked along the passage
into the loveliest garden you ever saw. How she longed to get out of
that dark hall, and wander about among those beds of bright flowers and
those cool fountains, but she could not even get her head through the
doorway; 'and even if my head would go through,' thought poor Alice, 'it
would be of very little use without my shoulders. Oh, how I wish I could
shut up like a telescope! I think I could, if I only knew how to begin.'
For, you see, so many out-of-the-way things had happened lately,
that Alice had begun to think that very few things indeed were really
impossible.
'Only mustard isn't a bird,' Alice remarked.
'Right, as usual,' said the Duchess: 'what a clear way you have of
putting things!'
'It's a mineral, I THINK,' said Alice.
'Of course it is,' said the Duchess, who seemed ready to agree to
everything that Alice said; 'there's a large mustard-mine near here. And
the moral of that is--"The more there is of mine, the less there is of
yours."'
'Oh, I know!' exclaimed Alice, who had not attended to this last remark,
'it's a vegetable. It doesn't look like one, but it is.'
'I quite agree with you,' said the Duchess; 'and the moral of that
is--"Be what you would seem to be"--or if you'd like it put more
simply--*Never imagine yourself not to be otherwise than what it might
appear to others that what you were or might have been was not otherwise
than what you had been would have appeared to them to be otherwise.*'
'I think I should understand that better,' Alice said very politely, 'if
I had it written down: but I can't quite follow it as you say it.'
'That's nothing to what I could say if I chose,' the Duchess replied, in
a pleased tone.
'Pray don't trouble yourself to say it any longer than that,' said
Alice.
'Oh, don't talk about trouble!' said the Duchess. 'I make you a present
of everything I've said as yet.'
'A cheap sort of present!' thought Alice. 'I'm glad they don't give
birthday presents like that!' But she did not venture to say it out
loud.
'Thinking again?' the Duchess asked, with another dig of her sharp
little chin.
'I've a right to think,' said Alice sharply, for she was beginning to
feel a little worried.
'Just about as much right,' said the Duchess, 'as pigs have to fly; and
the m--'
But here, to Alice's great surprise, the Duchess's voice died away, even
in the middle of her favourite word 'moral,' and the arm that was linked
into hers began to tremble. Alice looked up, and there stood the Queen
in front of them, with her arms folded, frowning like a thunderstorm.
'A fine day, your Majesty!' the Duchess began in a low, weak voice.
'Now, I give you fair warning,' shouted the Queen, stamping on the
ground as she spoke; 'either you or your head must be off, and that in
about half no time! Take your choice!'
The Duchess took her choice, and was gone in a moment.
'Let's go on with the game,' the Queen said to Alice; and Alice was
too much frightened to say a word, but slowly followed her back to the
croquet-ground.
The other guests had taken advantage of the Queen's absence, and were
resting in the shade: however, the moment they saw her, they hurried
back to the game, the Queen merely remarking that a moment's delay would
cost them their lives.
All the time they were playing the Queen never left off quarrelling with
the other players, and shouting 'Off with his head!' or 'Off with her
head!' Those whom she sentenced were taken into custody by the soldiers,
who of course had to leave off being arches to do this, so that by
the end of half an hour or so there were no arches left, and all the
players, except the King, the Queen, and Alice, were in custody and
under sentence of execution.
Then the Queen left off, quite out of breath, and said to Alice, 'Have
you seen the Mock Turtle yet?'
'No,' said Alice. 'I don't even know what a Mock Turtle is.'
'It's the thing Mock Turtle Soup is made from,' said the Queen.
'I never saw one, or heard of one,' said Alice.
'Come on, then,' said the Queen, 'and he shall tell you his history,'
As they walked off together, Alice heard the King say in a low voice,
to the company generally, 'You are all pardoned.' 'Come, THAT'S a good
thing!' she said to herself, for she had felt quite unhappy at the
number of executions the Queen had ordered.
They very soon came upon a Gryphon, lying fast asleep in the sun.
(IF you don't know what a Gryphon is, look at the picture.) 'Up, lazy
thing!' said the Queen, 'and take this young lady to see the Mock
Turtle, and to hear his history. I must go back and see after some
executions I have ordered'; and she walked off, leaving Alice alone with
the Gryphon. Alice did not quite like the look of the creature, but on
the whole she thought it would be quite as safe to stay with it as to go
after that savage Queen: so she waited.
The Gryphon sat up and rubbed its eyes: then it watched the Queen till
she was out of sight: then it chuckled. 'What fun!' said the Gryphon,
half to itself, half to Alice.
'What IS the fun?' said Alice.
'Why, SHE,' said the Gryphon. 'It's all her fancy, that: they never
executes nobody, you know. Come on!'
'Everybody says "come on!" here,' thought Alice, as she went slowly
after it: 'I never was so ordered about in all my life, never!'
They had not gone far before they saw the Mock Turtle in the distance,
sitting sad and lonely on a little ledge of rock, and, as they came
nearer, Alice could hear him sighing as if his heart would break. She
pitied him deeply. 'What is his sorrow?' she asked the Gryphon, and the
Gryphon answered, very nearly in the same words as before, 'It's all his
fancy, that: he hasn't got no sorrow, you know. Come on!'
So they went up to the Mock Turtle, who looked at them with large eyes
full of tears, but said nothing.
'This here young lady,' said the Gryphon, 'she wants for to know your
history, she do.'
'I'll tell it her,' said the Mock Turtle in a deep, hollow tone: 'sit
down, both of you, and don't speak a word till I've finished.'
So they sat down, and nobody spoke for some minutes. Alice thought to
herself, 'I don't see how he can EVEN finish, if he doesn't begin.' But
she waited patiently.
'Once,' said the Mock Turtle at last, with a deep sigh, 'I was a real
Turtle.'
These words were followed by a very long silence, broken only by an
occasional exclamation of 'Hjckrrh!' from the Gryphon, and the constant
heavy sobbing of the Mock Turtle. Alice was very nearly getting up and
saying, 'Thank you, sir, for your interesting story,' but she could
not help thinking there MUST be more to come, so she sat still and said
nothing.
'When we were little,' the Mock Turtle went on at last, more calmly,
though still sobbing a little now and then, 'we went to school in the
sea. The master was an old Turtle--we used to call him Tortoise--'
'Why did you call him Tortoise, if he wasn't one?' Alice asked.
'We called him Tortoise because he taught us,' said the Mock Turtle
angrily: 'really you are very dull!'
'You ought to be ashamed of yourself for asking such a simple question,'
added the Gryphon; and then they both sat silent and looked at poor
Alice, who felt ready to sink into the earth. At last the Gryphon said
to the Mock Turtle, 'Drive on, old fellow! Don't be all day about it!'
and he went on in these words:
'Yes, we went to school in the sea, though you mayn't believe it--'
'I never said I didn't!' interrupted Alice.
'You did,' said the Mock Turtle.
'Hold your tongue!' added the Gryphon, before Alice could speak again.
The Mock Turtle went on.
'We had the best of educations--in fact, we went to school every day--'
'I'VE been to a day-school, too,' said Alice; 'you needn't be so proud
as all that.'
'With extras?' asked the Mock Turtle a little anxiously.
'Yes,' said Alice, 'we learned French and music.'
'And washing?' said the Mock Turtle.
'Certainly not!' said Alice indignantly.
'Ah! then yours wasn't a really good school,' said the Mock Turtle in
a tone of great relief. 'Now at OURS they had at the end of the bill,
"French, music, AND WASHING--extra."'
'How the creatures order one about, and make one repeat lessons!'
thought Alice; 'I might as well be at school at once.' However, she
got up, and began to repeat it, but her head was so full of the Lobster
Quadrille, that she hardly knew what she was saying, and the words came
very queer indeed:--
''Tis the voice of the Lobster; I heard him declare,
"You have baked me too brown, I must sugar my hair."
As a duck with its eyelids, so he with his nose
Trims his belt and his buttons, and turns out his toes.'
When the sands are all dry, he is gay as a lark,
And will talk in contemptuous tones of the Shark,
But, when the tide rises and sharks are around,
His voice has a timid and tremulous sound.
'That's different from what I used to say when I was a child,' said the
Gryphon.
'Well, I never heard it before,' said the Mock Turtle; 'but it sounds
uncommon nonsense.'
Alice said nothing; she had sat down with her face in her hands,
wondering if anything would EVER happen in a natural way again.
'I should like to have it explained,' said the Mock Turtle.
'She can't explain it,' said the Gryphon hastily. 'Go on with the next
verse.'
'But about his toes?' the Mock Turtle persisted. 'How COULD he turn them
out with his nose, you know?'
'It's the first position in dancing.' Alice said; but was dreadfully
puzzled by the whole thing, and longed to change the subject.
'Go on with the next verse,' the Gryphon repeated impatiently: 'it
begins "I passed by his garden."'
Alice did not dare to disobey, though she felt sure it would all come
wrong, and she went on in a trembling voice:--
'I passed by his garden, and marked, with one eye,
How the Owl and the Panther were sharing a pie--'
The Panther took pie-crust, and gravy, and meat,
While the Owl had the dish as its share of the treat.
When the pie was all finished, the Owl, as a boon,
Was kindly permitted to pocket the spoon:
While the Panther received knife and fork with a growl,
And concluded the banquet--
'What IS the use of repeating all that stuff,' the Mock Turtle
interrupted, 'if you don't explain it as you go on? It's by far the most
confusing thing I ever heard!'
'Yes, I think you'd better leave off,' said the Gryphon: and Alice was
only too glad to do so.
'Shall we try another figure of the Lobster Quadrille?' the Gryphon went
on. 'Or would you like the Mock Turtle to sing you a song?'
'Oh, a song, please, if the Mock Turtle would be so kind,' Alice
replied, so eagerly that the Gryphon said, in a rather offended tone,
'Hm! No accounting for tastes! Sing her "Turtle Soup," will you, old
fellow?'
The Mock Turtle sighed deeply, and began, in a voice sometimes choked
with sobs, to sing this:--
'Beautiful Soup, so rich and green,
Waiting in a hot tureen!
Who for such dainties would not stoop?
Soup of the evening, beautiful Soup!
Soup of the evening, beautiful Soup!
Beau--ootiful Soo--oop!
Beau--ootiful Soo--oop!
Soo--oop of the e--e--evening,
Beautiful, beautiful Soup!
'Beautiful Soup! Who cares for fish,
Game, or any other dish?
Who would not give all else for two
Pennyworth only of beautiful Soup?
Pennyworth only of beautiful Soup?
Beau--ootiful Soo--oop!
Beau--ootiful Soo--oop!
Soo--oop of the e--e--evening,
Beautiful, beauti--FUL SOUP!'
'Chorus again!' cried the Gryphon, and the Mock Turtle had just begun
to repeat it, when a cry of 'The trial's beginning!' was heard in the
distance.
'Come on!' cried the Gryphon, and, taking Alice by the hand, it hurried
off, without waiting for the end of the song.
'What trial is it?' Alice panted as she ran; but the Gryphon only
answered 'Come on!' and ran the faster, while more and more faintly
came, carried on the breeze that followed them, the melancholy words:--
'Soo--oop of the e--e--evening,
Beautiful, beautiful Soup!'
## CHAPTER XI. Who Stole the Tarts?
The King and Queen of Hearts were seated on their throne when they
arrived, with a great crowd assembled about them--all sorts of little
birds and beasts, as well as the whole pack of cards: the Knave was
standing before them, in chains, with a soldier on each side to guard
him; and near the King was the White Rabbit, with a trumpet in one hand,
and a scroll of parchment in the other. In the very middle of the court
was a table, with a large dish of tarts upon it: they looked so good,
that it made Alice quite hungry to look at them--'I wish they'd get the
trial done,' she thought, 'and hand round the refreshments!' But there
seemed to be no chance of this, so she began looking at everything about
her, to pass away the time.
Alice had never been in a court of justice before, but she had read
about them in books, and she was quite pleased to find that she knew
the name of nearly everything there. 'That's the judge,' she said to
herself, 'because of his great wig.'
The judge, by the way, was the King; and as he wore his crown over the
wig, (look at the frontispiece if you want to see how he did it,) he did
not look at all comfortable, and it was certainly not becoming.
'And that's the jury-box,' thought Alice, 'and those twelve creatures,'
(she was obliged to say 'creatures,' you see, because some of them were
animals, and some were birds,) 'I suppose they are the jurors.' She said
this last word two or three times over to herself, being rather proud of
it: for she thought, and rightly too, that very few little girls of her
age knew the meaning of it at all. However, 'jury-men' would have done
just as well.
The twelve jurors were all writing very busily on slates. 'What are they
doing?' Alice whispered to the Gryphon. 'They can't have anything to put
down yet, before the trial's begun.'
'They're putting down their names,' the Gryphon whispered in reply, 'for
fear they should forget them before the end of the trial.'
'Stupid things!' Alice began in a loud, indignant voice, but she stopped
hastily, for the White Rabbit cried out, 'Silence in the court!' and the
King put on his spectacles and looked anxiously round, to make out who
was talking.
Alice could see, as well as if she were looking over their shoulders,
that all the jurors were writing down 'stupid things!' on their slates,
and she could even make out that one of them didn't know how to spell
'stupid,' and that he had to ask his neighbour to tell him. 'A nice
muddle their slates'll be in before the trial's over!' thought Alice.
One of the jurors had a pencil that squeaked. This of course, Alice
could not stand, and she went round the court and got behind him, and
very soon found an opportunity of taking it away. She did it so quickly
that the poor little juror (it was Bill, the Lizard) could not make out
at all what had become of it; so, after hunting all about for it, he was
obliged to write with one finger for the rest of the day; and this was
of very little use, as it left no mark on the slate.
'Herald, read the accusation!' said the King.
On this the White Rabbit blew three blasts on the trumpet, and then
unrolled the parchment scroll, and read as follows:--
'The Queen of Hearts, she made some tarts,
All on a summer day:
The Knave of Hearts, he stole those tarts,
And took them quite away!'
'Consider your verdict,' the King said to the jury.
'Not yet, not yet!' the Rabbit hastily interrupted. 'There's a great
deal to come before that!'
'Call the first witness,' said the King; and the White Rabbit blew three
blasts on the trumpet, and called out, 'First witness!'
The first witness was the Hatter. He came in with a teacup in one
hand and a piece of bread-and-butter in the other. 'I beg pardon, your
Majesty,' he began, 'for bringing these in: but I hadn't quite finished
my tea when I was sent for.'
'You ought to have finished,' said the King. 'When did you begin?'
The Hatter looked at the March Hare, who had followed him into the
court, arm-in-arm with the Dormouse. 'Fourteenth of March, I think it
was,' he said.
'Fifteenth,' said the March Hare.
'Sixteenth,' added the Dormouse.
'Write that down,' the King said to the jury, and the jury eagerly
wrote down all three dates on their slates, and then added them up, and
reduced the answer to shillings and pence.
'Take off your hat,' the King said to the Hatter.
'It isn't mine,' said the Hatter.
'Stolen!' the King exclaimed, turning to the jury, who instantly made a
memorandum of the fact.
'I keep them to sell,' the Hatter added as an explanation; 'I've none of
my own. I'm a hatter.'
Here the Queen put on her spectacles, and began staring at the Hatter,
who turned pale and fidgeted.
'Give your evidence,' said the King; 'and don't be nervous, or I'll have
you executed on the spot.'
This did not seem to encourage the witness at all: he kept shifting
from one foot to the other, looking uneasily at the Queen, and in
his confusion he bit a large piece out of his teacup instead of the
bread-and-butter.
Just at this moment Alice felt a very curious sensation, which puzzled
her a good deal until she made out what it was: she was beginning to
grow larger again, and she thought at first she would get up and leave
the court; but on second thoughts she decided to remain where she was as
long as there was room for her.
'I wish you wouldn't squeeze so.' said the Dormouse, who was sitting
next to her. 'I can hardly breathe.'
'I can't help it,' said Alice very meekly: 'I'm growing.'
'You've no right to grow here,' said the Dormouse.
'Don't talk nonsense,' said Alice more boldly: 'you know you're growing
too.'
'Yes, but I grow at a reasonable pace,' said the Dormouse: 'not in that
ridiculous fashion.' And he got up very sulkily and crossed over to the
other side of the court.
All this time the Queen had never left off staring at the Hatter, and,
just as the Dormouse crossed the court, she said to one of the officers
of the court, 'Bring me the list of the singers in the last concert!' on
which the wretched Hatter trembled so, that he shook both his shoes off.
'Give your evidence,' the King repeated angrily, 'or I'll have you
executed, whether you're nervous or not.'
'I'm a poor man, your Majesty,' the Hatter began, in a trembling voice,
'--and I hadn't begun my tea--not above a week or so--and what with the
bread-and-butter getting so thin--and the twinkling of the tea--'
'The twinkling of the what?' said the King.
'It began with the tea,' the Hatter replied.
'Of course twinkling begins with a T!' said the King sharply. 'Do you
take me for a dunce? Go on!'
'I'm a poor man,' the Hatter went on, 'and most things twinkled after
that--only the March Hare said--'
'I didn't!' the March Hare interrupted in a great hurry.
'You did!' said the Hatter.
'I deny it!' said the March Hare.
'He denies it,' said the King: 'leave out that part.'
'Well, at any rate, the Dormouse said--' the Hatter went on, looking
anxiously round to see if he would deny it too: but the Dormouse denied
nothing, being fast asleep.
'After that,' continued the Hatter, 'I cut some more bread-and-butter--'
'But what did the Dormouse say?' one of the jury asked.
'That I can't remember,' said the Hatter.
'You MUST remember,' remarked the King, 'or I'll have you executed.'
The miserable Hatter dropped his teacup and bread-and-butter, and went
down on one knee. 'I'm a poor man, your Majesty,' he began.
'You're a very poor speaker,' said the King.
Here one of the guinea-pigs cheered, and was immediately suppressed by
the officers of the court. (As that is rather a hard word, I will just
explain to you how it was done. They had a large canvas bag, which tied
up at the mouth with strings: into this they slipped the guinea-pig,
head first, and then sat upon it.)
'I'm glad I've seen that done,' thought Alice. 'I've so often read
in the newspapers, at the end of trials, "There was some attempts
at applause, which was immediately suppressed by the officers of the
court," and I never understood what it meant till now.'
'If that's all you know about it, you may stand down,' continued the
King.
'I can't go no lower,' said the Hatter: 'I'm on the floor, as it is.'
'Then you may SIT down,' the King replied.
Here the other guinea-pig cheered, and was suppressed.
'Come, that finished the guinea-pigs!' thought Alice. 'Now we shall get
on better.'
'I'd rather finish my tea,' said the Hatter, with an anxious look at the
Queen, who was reading the list of singers.
'You may go,' said the King, and the Hatter hurriedly left the court,
without even waiting to put his shoes on.
'--and just take his head off outside,' the Queen added to one of the
officers: but the Hatter was out of sight before the officer could get
to the door.
'Call the next witness!' said the King.
The next witness was the Duchess's cook. She carried the pepper-box in
her hand, and Alice guessed who it was, even before she got into the
court, by the way the people near the door began sneezing all at once.
'Give your evidence,' said the King.
'Shan't,' said the cook.
The King looked anxiously at the White Rabbit, who said in a low voice,
'Your Majesty must cross-examine THIS witness.'
'Well, if I must, I must,' the King said, with a melancholy air, and,
after folding his arms and frowning at the cook till his eyes were
nearly out of sight, he said in a deep voice, 'What are tarts made of?'
'Pepper, mostly,' said the cook.
'Treacle,' said a sleepy voice behind her.
'Collar that Dormouse,' the Queen shrieked out. 'Behead that Dormouse!
Turn that Dormouse out of court! Suppress him! Pinch him! Off with his
whiskers!'
For some minutes the whole court was in confusion, getting the Dormouse
turned out, and, by the time they had settled down again, the cook had
disappeared.
'Never mind!' said the King, with an air of great relief. 'Call the next
witness.' And he added in an undertone to the Queen, 'Really, my dear,
YOU must cross-examine the next witness. It quite makes my forehead
ache!'
Alice watched the White Rabbit as he fumbled over the list, feeling very
curious to see what the next witness would be like, '--for they haven't
got much evidence YET,' she said to herself. Imagine her surprise, when
the White Rabbit read out, at the top of his shrill little voice, the
name 'Alice!'
## CHAPTER XII. Alice's Evidence
'Here!' cried Alice, quite forgetting in the flurry of the moment how
large she had grown in the last few minutes, and she jumped up in such
a hurry that she tipped over the jury-box with the edge of her skirt,
upsetting all the jurymen on to the heads of the crowd below, and there
they lay sprawling about, reminding her very much of a globe of goldfish
she had accidentally upset the week before.
'Oh, I BEG your pardon!' she exclaimed in a tone of great dismay, and
began picking them up again as quickly as she could, for the accident of
the goldfish kept running in her head, and she had a vague sort of idea
that they must be collected at once and put back into the jury-box, or
they would die.
'The trial cannot proceed,' said the King in a very grave voice, 'until
all the jurymen are back in their proper places--ALL,' he repeated with
great emphasis, looking hard at Alice as he said do.
Alice looked at the jury-box, and saw that, in her haste, she had put
the Lizard in head downwards, and the poor little thing was waving its
tail about in a melancholy way, being quite unable to move. She soon got
it out again, and put it right; 'not that it signifies much,' she said
to herself; 'I should think it would be QUITE as much use in the trial
one way up as the other.'
As soon as the jury had a little recovered from the shock of being
upset, and their slates and pencils had been found and handed back to
them, they set to work very diligently to write out a history of the
accident, all except the Lizard, who seemed too much overcome to do
anything but sit with its mouth open, gazing up into the roof of the
court.
'What do you know about this business?' the King said to Alice.
'Nothing,' said Alice.
'Nothing WHATEVER?' persisted the King.
'Nothing whatever,' said Alice.
'That's very important,' the King said, turning to the jury. They were
just beginning to write this down on their slates, when the White Rabbit
interrupted: 'UNimportant, your Majesty means, of course,' he said in a
very respectful tone, but frowning and making faces at him as he spoke.
'UNimportant, of course, I meant,' the King hastily said, and went on
to himself in an undertone,
'important--unimportant--unimportant--important--' as if he were trying
which word sounded best.
Some of the jury wrote it down 'important,' and some 'unimportant.'
Alice could see this, as she was near enough to look over their slates;
'but it doesn't matter a bit,' she thought to herself.
At this moment the King, who had been for some time busily writing in
his note-book, cackled out 'Silence!' and read out from his book, 'Rule
Forty-two. ALL PERSONS MORE THAN A MILE HIGH TO LEAVE THE COURT.'
Everybody looked at Alice.
'I'M not a mile high,' said Alice.
'You are,' said the King.
'Nearly two miles high,' added the Queen.
'Well, I shan't go, at any rate,' said Alice: 'besides, that's not a
regular rule: you invented it just now.'
'It's the oldest rule in the book,' said the King.
'Then it ought to be Number One,' said Alice.
The King turned pale, and shut his note-book hastily. 'Consider your
verdict,' he said to the jury, in a low, trembling voice.
'There's more evidence to come yet, please your Majesty,' said the White
Rabbit, jumping up in a great hurry; 'this paper has just been picked
up.'
'What's in it?' said the Queen.
'I haven't opened it yet,' said the White Rabbit, 'but it seems to be a
letter, written by the prisoner to--to somebody.'
'It must have been that,' said the King, 'unless it was written to
nobody, which isn't usual, you know.'
'Who is it directed to?' said one of the jurymen.
'It isn't directed at all,' said the White Rabbit; 'in fact, there's
nothing written on the OUTSIDE.' He unfolded the paper as he spoke, and
added 'It isn't a letter, after all: it's a set of verses.'
'Are they in the prisoner's handwriting?' asked another of the jurymen.
'No, they're not,' said the White Rabbit, 'and that's the queerest thing
about it.' (The jury all looked puzzled.)
'He must have imitated somebody else's hand,' said the King. (The jury
all brightened up again.)
'Please your Majesty,' said the Knave, 'I didn't write it, and they
can't prove I did: there's no name signed at the end.'
'If you didn't sign it,' said the King, 'that only makes the matter
worse. You MUST have meant some mischief, or else you'd have signed your
name like an honest man.'
There was a general clapping of hands at this: it was the first really
clever thing the King had said that day.
'That PROVES his guilt,' said the Queen.
'It proves nothing of the sort!' said Alice. 'Why, you don't even know
what they're about!'
'Read them,' said the King.
The White Rabbit put on his spectacles. 'Where shall I begin, please
your Majesty?' he asked.
'Begin at the beginning,' the King said gravely, 'and go on till you
come to the end: then stop.'
These were the verses the White Rabbit read:--
'They told me you had been to her,
And mentioned me to him:
She gave me a good character,
But said I could not swim.
He sent them word I had not gone
(We know it to be true):
If she should push the matter on,
What would become of you?
I gave her one, they gave him two,
You gave us three or more;
They all returned from him to you,
Though they were mine before.
If I or she should chance to be
Involved in this affair,
He trusts to you to set them free,
Exactly as we were.
My notion was that you had been
(Before she had this fit)
An obstacle that came between
Him, and ourselves, and it.
Don't let him know she liked them best,
For this must ever be
A secret, kept from all the rest,
Between yourself and me.'
'That's the most important piece of evidence we've heard yet,' said the
King, rubbing his hands; 'so now let the jury--'
'If any one of them can explain it,' said Alice, (she had grown so large
in the last few minutes that she wasn't a bit afraid of interrupting
him,) 'I'll give him sixpence. _I_ don't believe there's an atom of
meaning in it.'
The jury all wrote down on their slates, 'SHE doesn't believe there's an
atom of meaning in it,' but none of them attempted to explain the paper.
'If there's no meaning in it,' said the King, 'that saves a world of
trouble, you know, as we needn't try to find any. And yet I don't know,'
he went on, spreading out the verses on his knee, and looking at them
with one eye; 'I seem to see some meaning in them, after all. "--SAID
I COULD NOT SWIM--" you can't swim, can you?' he added, turning to the
Knave.
The Knave shook his head sadly. 'Do I look like it?' he said. (Which he
certainly did NOT, being made entirely of cardboard.)
'All right, so far,' said the King, and he went on muttering over
the verses to himself: '"WE KNOW IT TO BE TRUE--" that's the jury, of
course--"I GAVE HER ONE, THEY GAVE HIM TWO--" why, that must be what he
did with the tarts, you know--'
'But, it goes on "THEY ALL RETURNED FROM HIM TO YOU,"' said Alice.
'Why, there they are!' said the King triumphantly, pointing to the tarts
on the table. 'Nothing can be clearer than THAT. Then again--"BEFORE SHE
HAD THIS FIT--" you never had fits, my dear, I think?' he said to the
Queen.
'Never!' said the Queen furiously, throwing an inkstand at the Lizard
as she spoke. (The unfortunate little Bill had left off writing on his
slate with one finger, as he found it made no mark; but he now hastily
began again, using the ink, that was trickling down his face, as long as
it lasted.)
'Then the words don't FIT you,' said the King, looking round the court
with a smile. There was a dead silence.
'It's a pun!' the King added in an offended tone, and everybody laughed,
'Let the jury consider their verdict,' the King said, for about the
twentieth time that day.
'No, no!' said the Queen. 'Sentence first--verdict afterwards.'
'Stuff and nonsense!' said Alice loudly. 'The idea of having the
sentence first!'
'Hold your tongue!' said the Queen, turning purple.
'I won't!' said Alice.
'Off with her head!' the Queen shouted at the top of her voice. Nobody
moved.
'Who cares for you?' said Alice, (she had grown to her full size by this
time.) 'You're nothing but a pack of cards!'
At this the whole pack rose up into the air, and came flying down upon
her: she gave a little scream, half of fright and half of anger, and
tried to beat them off, and found herself lying on the bank, with her
head in the lap of her sister, who was gently brushing away some dead
leaves that had fluttered down from the trees upon her face.
'Wake up, Alice dear!' said her sister; 'Why, what a long sleep you've
had!'
'Oh, I've had such a curious dream!' said Alice, and she told her
sister, as well as she could remember them, all these strange Adventures
of hers that you have just been reading about; and when she had
finished, her sister kissed her, and said, 'It WAS a curious dream,
dear, certainly: but now run in to your tea; it's getting late.' So
Alice got up and ran off, thinking while she ran, as well she might,
what a wonderful dream it had been.
But her sister sat still just as she left her, leaning her head on her
hand, watching the setting sun, and thinking of little Alice and all her
wonderful Adventures, till she too began dreaming after a fashion, and
this was her dream:--
First, she dreamed of little Alice herself, and once again the tiny
hands were clasped upon her knee, and the bright eager eyes were looking
up into hers--she could hear the very tones of her voice, and see that
queer little toss of her head to keep back the wandering hair that
WOULD always get into her eyes--and still as she listened, or seemed to
listen, the whole place around her became alive with the strange creatures
of her little sister's dream.
The long grass rustled at her feet as the White Rabbit hurried by--the
frightened Mouse splashed his way through the neighbouring pool--she
could hear the rattle of the teacups as the March Hare and his friends
shared their never-ending meal, and the shrill voice of the Queen
ordering off her unfortunate guests to execution--once more the pig-baby
was sneezing on the Duchess's knee, while plates and dishes crashed
around it--once more the shriek of the Gryphon, the squeaking of the
Lizard's slate-pencil, and the choking of the suppressed guinea-pigs,
filled the air, mixed up with the distant sobs of the miserable Mock
Turtle.
So she sat on, with closed eyes, and half believed herself in
Wonderland, though she knew she had but to open them again, and all
would change to dull reality--the grass would be only rustling in the
wind, and the pool rippling to the waving of the reeds--the rattling
teacups would change to tinkling sheep-bells, and the Queen's shrill
cries to the voice of the shepherd boy--and the sneeze of the baby, the
shriek of the Gryphon, and all the other queer noises, would change (she
knew) to the confused clamour of the busy farm-yard--while the lowing
of the cattle in the distance would take the place of the Mock Turtle's
heavy sobs.
Lastly, she pictured to herself how this same little sister of hers
would, in the after-time, be herself a grown woman; and how she would
keep, through all her riper years, the simple and loving heart of her
childhood: and how she would gather about her other little children, and
make THEIR eyes bright and eager with many a strange tale, perhaps even
with the dream of Wonderland of long ago: and how she would feel with
all their simple sorrows, and find a pleasure in all their simple joys,
remembering her own child-life, and the happy summer days.
"""
| 63730 | module.exports = """
# Through the Looking-Glass
'Really, now you ask me,' said <NAME>, very much confused, 'I don't
think—'
'Then you shouldn't talk,' said the Hatter.
This piece of rudeness was more than Alice could bear: she got up in
great disgust, and walked off; the Dormouse fell asleep instantly, and
neither of the others took the least notice of her going, though she
looked back once or twice, half hoping that they would call after her:
the last time she saw them, they were trying to put the Dormouse into
the teapot.
'At any rate I'll never go THERE again!' said <NAME> as she picked her
way through the wood. 'It's the stupidest tea-party I ever was at in all
my life!'
Just as she said this, she noticed that one of the trees had a door
leading right into it. 'That's very curious!' she thought. 'But
everything's curious today. I think I may as well go in at once.' And in
she went.
Once more she found herself in the long hall, and close to the little
glass table. 'Now, I'll manage better this time,' she said to herself,
and began by taking the little golden key, and unlocking the door that
led into the garden. Then she went to work nibbling at the mushroom (she
had kept a piece of it in her pocket) till she was about a foot high:
then she walked down the little passage: and THEN—she found herself at
last in the beautiful garden, among the bright flower-beds and the cool
fountains.
Alice opened the door and found that it led into a small passage, not
much larger than a rat-hole: she knelt down and looked along the passage
into the loveliest garden you ever saw. How she longed to get out of
that dark hall, and wander about among those beds of bright flowers and
those cool fountains, but she could not even get her head through the
doorway; 'and even if my head would go through,' thought poor Alice, 'it
would be of very little use without my shoulders. Oh, how I wish I could
shut up like a telescope! I think I could, if I only knew how to begin.'
For, you see, so many out-of-the-way things had happened lately,
that Alice had begun to think that very few things indeed were really
impossible.
'Only mustard isn't a bird,' Alice remarked.
'Right, as usual,' said the Duchess: 'what a clear way you have of
putting things!'
'It's a mineral, I THINK,' said Alice.
'Of course it is,' said the Duchess, who seemed ready to agree to
everything that Alice said; 'there's a large mustard-mine near here. And
the moral of that is--"The more there is of mine, the less there is of
yours."'
'Oh, I know!' exclaimed Alice, who had not attended to this last remark,
'it's a vegetable. It doesn't look like one, but it is.'
'I quite agree with you,' said the Duchess; 'and the moral of that
is--"Be what you would seem to be"--or if you'd like it put more
simply--*Never imagine yourself not to be otherwise than what it might
appear to others that what you were or might have been was not otherwise
than what you had been would have appeared to them to be otherwise.*'
'I think I should understand that better,' Alice said very politely, 'if
I had it written down: but I can't quite follow it as you say it.'
'That's nothing to what I could say if I chose,' the Duchess replied, in
a pleased tone.
'Pray don't trouble yourself to say it any longer than that,' said
Alice.
'Oh, don't talk about trouble!' said the Duchess. 'I make you a present
of everything I've said as yet.'
'A cheap sort of present!' thought Alice. 'I'm glad they don't give
birthday presents like that!' But she did not venture to say it out
loud.
'Thinking again?' the Duchess asked, with another dig of her sharp
little chin.
'I've a right to think,' said Alice sharply, for she was beginning to
feel a little worried.
'Just about as much right,' said the Duchess, 'as pigs have to fly; and
the m--'
But here, to Alice's great surprise, the Duchess's voice died away, even
in the middle of her favourite word 'moral,' and the arm that was linked
into hers began to tremble. <NAME> looked up, and there stood the Queen
in front of them, with her arms folded, frowning like a thunderstorm.
'A fine day, your Majesty!' the Duchess began in a low, weak voice.
'Now, I give you fair warning,' shouted the Queen, stamping on the
ground as she spoke; 'either you or your head must be off, and that in
about half no time! Take your choice!'
The Duchess took her choice, and was gone in a moment.
'Let's go on with the game,' the Queen said to <NAME>; and Alice was
too much frightened to say a word, but slowly followed her back to the
croquet-ground.
The other guests had taken advantage of the Queen's absence, and were
resting in the shade: however, the moment they saw her, they hurried
back to the game, the Queen merely remarking that a moment's delay would
cost them their lives.
All the time they were playing the Queen never left off quarrelling with
the other players, and shouting 'Off with his head!' or 'Off with her
head!' Those whom she sentenced were taken into custody by the soldiers,
who of course had to leave off being arches to do this, so that by
the end of half an hour or so there were no arches left, and all the
players, except the King, the Queen, and <NAME>, were in custody and
under sentence of execution.
Then the Queen left off, quite out of breath, and said to Alice, 'Have
you seen the Mock Turtle yet?'
'No,' said Alice. 'I don't even know what a Mock Turtle is.'
'It's the thing Mock Turtle Soup is made from,' said the Queen.
'I never saw one, or heard of one,' said <NAME>.
'Come on, then,' said the Queen, 'and he shall tell you his history,'
As they walked off together, Alice heard the King say in a low voice,
to the company generally, 'You are all pardoned.' 'Come, THAT'S a good
thing!' she said to herself, for she had felt quite unhappy at the
number of executions the Queen had ordered.
They very soon came upon a Gryphon, lying fast asleep in the sun.
(IF you don't know what a Gryphon is, look at the picture.) 'Up, lazy
thing!' said the Queen, 'and take this young lady to see the Mock
Turtle, and to hear his history. I must go back and see after some
executions I have ordered'; and she walked off, leaving Alice alone with
the Gryphon. Alice did not quite like the look of the creature, but on
the whole she thought it would be quite as safe to stay with it as to go
after that savage Queen: so she waited.
The Gryphon sat up and rubbed its eyes: then it watched the Queen till
she was out of sight: then it chuckled. 'What fun!' said the Gryphon,
half to itself, half to Alice.
'What IS the fun?' said Alice.
'Why, SHE,' said the Gryphon. 'It's all her fancy, that: they never
executes nobody, you know. Come on!'
'Everybody says "come on!" here,' thought Alice, as she went slowly
after it: 'I never was so ordered about in all my life, never!'
They had not gone far before they saw the Mock Turtle in the distance,
sitting sad and lonely on a little ledge of rock, and, as they came
nearer, Alice could hear him sighing as if his heart would break. She
pitied him deeply. 'What is his sorrow?' she asked the Gryphon, and the
Gryphon answered, very nearly in the same words as before, 'It's all his
fancy, that: he hasn't got no sorrow, you know. Come on!'
So they went up to the Mock Turtle, who looked at them with large eyes
full of tears, but said nothing.
'This here young lady,' said the Gryphon, 'she wants for to know your
history, she do.'
'I'll tell it her,' said the Mock Turtle in a deep, hollow tone: 'sit
down, both of you, and don't speak a word till I've finished.'
So they sat down, and nobody spoke for some minutes. Alice thought to
herself, 'I don't see how he can EVEN finish, if he doesn't begin.' But
she waited patiently.
'Once,' said the Mock Turtle at last, with a deep sigh, 'I was a real
Turtle.'
These words were followed by a very long silence, broken only by an
occasional exclamation of 'Hjckrrh!' from the Gryphon, and the constant
heavy sobbing of the Mock Turtle. Alice was very nearly getting up and
saying, 'Thank you, sir, for your interesting story,' but she could
not help thinking there MUST be more to come, so she sat still and said
nothing.
'When we were little,' the Mock Turtle went on at last, more calmly,
though still sobbing a little now and then, 'we went to school in the
sea. The master was an old Turtle--we used to call him Tortoise--'
'Why did you call him Tortoise, if he wasn't one?' Alice asked.
'We called him Tortoise because he taught us,' said the Mock Turtle
angrily: 'really you are very dull!'
'You ought to be ashamed of yourself for asking such a simple question,'
added the Gryphon; and then they both sat silent and looked at poor
Alice, who felt ready to sink into the earth. At last the Gryphon said
to the Mock Turtle, 'Drive on, old fellow! Don't be all day about it!'
and he went on in these words:
'Yes, we went to school in the sea, though you mayn't believe it--'
'I never said I didn't!' interrupted Alice.
'You did,' said the Mock Turtle.
'Hold your tongue!' added the Gryphon, before Alice could speak again.
The Mock Turtle went on.
'We had the best of educations--in fact, we went to school every day--'
'I'VE been to a day-school, too,' said Alice; 'you needn't be so proud
as all that.'
'With extras?' asked the Mock Turtle a little anxiously.
'Yes,' said Alice, 'we learned French and music.'
'And washing?' said the Mock Turtle.
'Certainly not!' said Alice indignantly.
'Ah! then yours wasn't a really good school,' said the Mock Turtle in
a tone of great relief. 'Now at OURS they had at the end of the bill,
"French, music, AND WASHING--extra."'
'How the creatures order one about, and make one repeat lessons!'
thought Alice; 'I might as well be at school at once.' However, she
got up, and began to repeat it, but her head was so full of the Lobster
Quadrille, that she hardly knew what she was saying, and the words came
very queer indeed:--
''Tis the voice of the Lobster; I heard him declare,
"You have baked me too brown, I must sugar my hair."
As a duck with its eyelids, so he with his nose
Trims his belt and his buttons, and turns out his toes.'
When the sands are all dry, he is gay as a lark,
And will talk in contemptuous tones of the Shark,
But, when the tide rises and sharks are around,
His voice has a timid and tremulous sound.
'That's different from what I used to say when I was a child,' said the
Gryphon.
'Well, I never heard it before,' said the Mock Turtle; 'but it sounds
uncommon nonsense.'
Alice said nothing; she had sat down with her face in her hands,
wondering if anything would EVER happen in a natural way again.
'I should like to have it explained,' said the Mock Turtle.
'She can't explain it,' said the Gryphon hastily. 'Go on with the next
verse.'
'But about his toes?' the Mock Turtle persisted. 'How COULD he turn them
out with his nose, you know?'
'It's the first position in dancing.' Alice said; but was dreadfully
puzzled by the whole thing, and longed to change the subject.
'Go on with the next verse,' the Gryphon repeated impatiently: 'it
begins "I passed by his garden."'
Alice did not dare to disobey, though she felt sure it would all come
wrong, and she went on in a trembling voice:--
'I passed by his garden, and marked, with one eye,
How the Owl and the Panther were sharing a pie--'
The Panther took pie-crust, and gravy, and meat,
While the Owl had the dish as its share of the treat.
When the pie was all finished, the Owl, as a boon,
Was kindly permitted to pocket the spoon:
While the Panther received knife and fork with a growl,
And concluded the banquet--
'What IS the use of repeating all that stuff,' the Mock Turtle
interrupted, 'if you don't explain it as you go on? It's by far the most
confusing thing I ever heard!'
'Yes, I think you'd better leave off,' said the Gryphon: and Alice was
only too glad to do so.
'Shall we try another figure of the Lobster Quadrille?' the Gryphon went
on. 'Or would you like the Mock Turtle to sing you a song?'
'Oh, a song, please, if the Mock Turtle would be so kind,' Alice
replied, so eagerly that the Gryphon said, in a rather offended tone,
'Hm! No accounting for tastes! Sing her "Turtle Soup," will you, old
fellow?'
The Mock Turtle sighed deeply, and began, in a voice sometimes choked
with sobs, to sing this:--
'Beautiful Soup, so rich and green,
Waiting in a hot tureen!
Who for such dainties would not stoop?
Soup of the evening, beautiful Soup!
Soup of the evening, beautiful Soup!
Beau--ootiful Soo--oop!
Beau--ootiful Soo--oop!
Soo--oop of the e--e--evening,
Beautiful, beautiful Soup!
'Beautiful Soup! Who cares for fish,
Game, or any other dish?
Who would not give all else for two
Pennyworth only of beautiful Soup?
Pennyworth only of beautiful Soup?
Beau--ootiful Soo--oop!
Beau--ootiful Soo--oop!
Soo--oop of the e--e--evening,
Beautiful, beauti--FUL SOUP!'
'Chorus again!' cried the Gryphon, and the Mock Turtle had just begun
to repeat it, when a cry of 'The trial's beginning!' was heard in the
distance.
'Come on!' cried the Gryphon, and, taking Alice by the hand, it hurried
off, without waiting for the end of the song.
'What trial is it?' Alice panted as she ran; but the Gryphon only
answered 'Come on!' and ran the faster, while more and more faintly
came, carried on the breeze that followed them, the melancholy words:--
'Soo--oop of the e--e--evening,
Beautiful, beautiful Soup!'
## CHAPTER XI. Who Stole the Tarts?
The King and Queen of Hearts were seated on their throne when they
arrived, with a great crowd assembled about them--all sorts of little
birds and beasts, as well as the whole pack of cards: the Knave was
standing before them, in chains, with a soldier on each side to guard
him; and near the King was the White Rabbit, with a trumpet in one hand,
and a scroll of parchment in the other. In the very middle of the court
was a table, with a large dish of tarts upon it: they looked so good,
that it made Alice quite hungry to look at them--'I wish they'd get the
trial done,' she thought, 'and hand round the refreshments!' But there
seemed to be no chance of this, so she began looking at everything about
her, to pass away the time.
<NAME> had never been in a court of justice before, but she had read
about them in books, and she was quite pleased to find that she knew
the name of nearly everything there. 'That's the judge,' she said to
herself, 'because of his great wig.'
The judge, by the way, was the King; and as he wore his crown over the
wig, (look at the frontispiece if you want to see how he did it,) he did
not look at all comfortable, and it was certainly not becoming.
'And that's the jury-box,' thought <NAME>, 'and those twelve creatures,'
(she was obliged to say 'creatures,' you see, because some of them were
animals, and some were birds,) 'I suppose they are the jurors.' She said
this last word two or three times over to herself, being rather proud of
it: for she thought, and rightly too, that very few little girls of her
age knew the meaning of it at all. However, 'jury-men' would have done
just as well.
The twelve jurors were all writing very busily on slates. 'What are they
doing?' <NAME> whispered to the Gryphon. 'They can't have anything to put
down yet, before the trial's begun.'
'They're putting down their names,' the Gryphon whispered in reply, 'for
fear they should forget them before the end of the trial.'
'Stupid things!' Alice began in a loud, indignant voice, but she stopped
hastily, for the White Rabbit cried out, 'Silence in the court!' and the
King put on his spectacles and looked anxiously round, to make out who
was talking.
Alice could see, as well as if she were looking over their shoulders,
that all the jurors were writing down 'stupid things!' on their slates,
and she could even make out that one of them didn't know how to spell
'stupid,' and that he had to ask his neighbour to tell him. 'A nice
muddle their slates'll be in before the trial's over!' thought Alice.
One of the jurors had a pencil that squeaked. This of course, Alice
could not stand, and she went round the court and got behind him, and
very soon found an opportunity of taking it away. She did it so quickly
that the poor little juror (it was Bill, the Lizard) could not make out
at all what had become of it; so, after hunting all about for it, he was
obliged to write with one finger for the rest of the day; and this was
of very little use, as it left no mark on the slate.
'Herald, read the accusation!' said the King.
On this the White Rabbit blew three blasts on the trumpet, and then
unrolled the parchment scroll, and read as follows:--
'The Queen of Hearts, she made some tarts,
All on a summer day:
The Knave of Hearts, he stole those tarts,
And took them quite away!'
'Consider your verdict,' the King said to the jury.
'Not yet, not yet!' the Rabbit hastily interrupted. 'There's a great
deal to come before that!'
'Call the first witness,' said the King; and the White Rabbit blew three
blasts on the trumpet, and called out, 'First witness!'
The first witness was the Hatter. He came in with a teacup in one
hand and a piece of bread-and-butter in the other. 'I beg pardon, your
Majesty,' he began, 'for bringing these in: but I hadn't quite finished
my tea when I was sent for.'
'You ought to have finished,' said the King. 'When did you begin?'
The Hatter looked at the March Hare, who had followed him into the
court, arm-in-arm with the Dormouse. 'Fourteenth of March, I think it
was,' he said.
'Fifteenth,' said the March Hare.
'Sixteenth,' added the Dormouse.
'Write that down,' the King said to the jury, and the jury eagerly
wrote down all three dates on their slates, and then added them up, and
reduced the answer to shillings and pence.
'Take off your hat,' the King said to the Hatter.
'It isn't mine,' said the Hatter.
'Stolen!' the King exclaimed, turning to the jury, who instantly made a
memorandum of the fact.
'I keep them to sell,' the Hatter added as an explanation; 'I've none of
my own. I'm a hatter.'
Here the Queen put on her spectacles, and began staring at the Hatter,
who turned pale and fidgeted.
'Give your evidence,' said the King; 'and don't be nervous, or I'll have
you executed on the spot.'
This did not seem to encourage the witness at all: he kept shifting
from one foot to the other, looking uneasily at the Queen, and in
his confusion he bit a large piece out of his teacup instead of the
bread-and-butter.
Just at this moment Alice felt a very curious sensation, which puzzled
her a good deal until she made out what it was: she was beginning to
grow larger again, and she thought at first she would get up and leave
the court; but on second thoughts she decided to remain where she was as
long as there was room for her.
'I wish you wouldn't squeeze so.' said the Dormouse, who was sitting
next to her. 'I can hardly breathe.'
'I can't help it,' said Alice very meekly: 'I'm growing.'
'You've no right to grow here,' said the Dormouse.
'Don't talk nonsense,' said Alice more boldly: 'you know you're growing
too.'
'Yes, but I grow at a reasonable pace,' said the Dormouse: 'not in that
ridiculous fashion.' And he got up very sulkily and crossed over to the
other side of the court.
All this time the Queen had never left off staring at the Hatter, and,
just as the Dormouse crossed the court, she said to one of the officers
of the court, 'Bring me the list of the singers in the last concert!' on
which the wretched Hatter trembled so, that he shook both his shoes off.
'Give your evidence,' the King repeated angrily, 'or I'll have you
executed, whether you're nervous or not.'
'I'm a poor man, your Majesty,' the Hatter began, in a trembling voice,
'--and I hadn't begun my tea--not above a week or so--and what with the
bread-and-butter getting so thin--and the twinkling of the tea--'
'The twinkling of the what?' said the King.
'It began with the tea,' the Hatter replied.
'Of course twinkling begins with a T!' said the King sharply. 'Do you
take me for a dunce? Go on!'
'I'm a poor man,' the Hatter went on, 'and most things twinkled after
that--only the March Hare said--'
'I didn't!' the March Hare interrupted in a great hurry.
'You did!' said the Hatter.
'I deny it!' said the March Hare.
'He denies it,' said the King: 'leave out that part.'
'Well, at any rate, the Dormouse said--' the Hatter went on, looking
anxiously round to see if he would deny it too: but the Dormouse denied
nothing, being fast asleep.
'After that,' continued the Hatter, 'I cut some more bread-and-butter--'
'But what did the Dormouse say?' one of the jury asked.
'That I can't remember,' said the Hatter.
'You MUST remember,' remarked the King, 'or I'll have you executed.'
The miserable Hatter dropped his teacup and bread-and-butter, and went
down on one knee. 'I'm a poor man, your Majesty,' he began.
'You're a very poor speaker,' said the King.
Here one of the guinea-pigs cheered, and was immediately suppressed by
the officers of the court. (As that is rather a hard word, I will just
explain to you how it was done. They had a large canvas bag, which tied
up at the mouth with strings: into this they slipped the guinea-pig,
head first, and then sat upon it.)
'I'm glad I've seen that done,' thought Alice. 'I've so often read
in the newspapers, at the end of trials, "There was some attempts
at applause, which was immediately suppressed by the officers of the
court," and I never understood what it meant till now.'
'If that's all you know about it, you may stand down,' continued the
King.
'I can't go no lower,' said the Hatter: 'I'm on the floor, as it is.'
'Then you may SIT down,' the King replied.
Here the other guinea-pig cheered, and was suppressed.
'Come, that finished the guinea-pigs!' thought Alice. 'Now we shall get
on better.'
'I'd rather finish my tea,' said the Hatter, with an anxious look at the
Queen, who was reading the list of singers.
'You may go,' said the King, and the Hatter hurriedly left the court,
without even waiting to put his shoes on.
'--and just take his head off outside,' the Queen added to one of the
officers: but the Hatter was out of sight before the officer could get
to the door.
'Call the next witness!' said the King.
The next witness was the Duchess's cook. She carried the pepper-box in
her hand, and Alice guessed who it was, even before she got into the
court, by the way the people near the door began sneezing all at once.
'Give your evidence,' said the King.
'Shan't,' said the cook.
The King looked anxiously at the White Rabbit, who said in a low voice,
'Your Majesty must cross-examine THIS witness.'
'Well, if I must, I must,' the King said, with a melancholy air, and,
after folding his arms and frowning at the cook till his eyes were
nearly out of sight, he said in a deep voice, 'What are tarts made of?'
'Pepper, mostly,' said the cook.
'Treacle,' said a sleepy voice behind her.
'Collar that Dormouse,' the Queen shrieked out. 'Behead that Dormouse!
Turn that Dormouse out of court! Suppress him! Pinch him! Off with his
whiskers!'
For some minutes the whole court was in confusion, getting the Dormouse
turned out, and, by the time they had settled down again, the cook had
disappeared.
'Never mind!' said the King, with an air of great relief. 'Call the next
witness.' And he added in an undertone to the Queen, 'Really, my dear,
YOU must cross-examine the next witness. It quite makes my forehead
ache!'
Alice watched the White Rabbit as he fumbled over the list, feeling very
curious to see what the next witness would be like, '--for they haven't
got much evidence YET,' she said to herself. Imagine her surprise, when
the White Rabbit read out, at the top of his shrill little voice, the
name '<NAME>!'
## CHAPTER XII. Alice's Evidence
'Here!' cried <NAME>, quite forgetting in the flurry of the moment how
large she had grown in the last few minutes, and she jumped up in such
a hurry that she tipped over the jury-box with the edge of her skirt,
upsetting all the jurymen on to the heads of the crowd below, and there
they lay sprawling about, reminding her very much of a globe of goldfish
she had accidentally upset the week before.
'Oh, I BEG your pardon!' she exclaimed in a tone of great dismay, and
began picking them up again as quickly as she could, for the accident of
the goldfish kept running in her head, and she had a vague sort of idea
that they must be collected at once and put back into the jury-box, or
they would die.
'The trial cannot proceed,' said the King in a very grave voice, 'until
all the jurymen are back in their proper places--ALL,' he repeated with
great emphasis, looking hard at Alice as he said do.
Alice looked at the jury-box, and saw that, in her haste, she had put
the Lizard in head downwards, and the poor little thing was waving its
tail about in a melancholy way, being quite unable to move. She soon got
it out again, and put it right; 'not that it signifies much,' she said
to herself; 'I should think it would be QUITE as much use in the trial
one way up as the other.'
As soon as the jury had a little recovered from the shock of being
upset, and their slates and pencils had been found and handed back to
them, they set to work very diligently to write out a history of the
accident, all except the Lizard, who seemed too much overcome to do
anything but sit with its mouth open, gazing up into the roof of the
court.
'What do you know about this business?' the King said to Alice.
'Nothing,' said Alice.
'Nothing WHATEVER?' persisted the King.
'Nothing whatever,' said Alice.
'That's very important,' the King said, turning to the jury. They were
just beginning to write this down on their slates, when the White Rabbit
interrupted: 'UNimportant, your Majesty means, of course,' he said in a
very respectful tone, but frowning and making faces at him as he spoke.
'UNimportant, of course, I meant,' the King hastily said, and went on
to himself in an undertone,
'important--unimportant--unimportant--important--' as if he were trying
which word sounded best.
Some of the jury wrote it down 'important,' and some 'unimportant.'
Alice could see this, as she was near enough to look over their slates;
'but it doesn't matter a bit,' she thought to herself.
At this moment the King, who had been for some time busily writing in
his note-book, cackled out 'Silence!' and read out from his book, 'Rule
Forty-two. ALL PERSONS MORE THAN A MILE HIGH TO LEAVE THE COURT.'
Everybody looked at Alice.
'I'M not a mile high,' said Alice.
'You are,' said the King.
'Nearly two miles high,' added the Queen.
'Well, I shan't go, at any rate,' said Alice: 'besides, that's not a
regular rule: you invented it just now.'
'It's the oldest rule in the book,' said the King.
'Then it ought to be Number One,' said Alice.
The King turned pale, and shut his note-book hastily. 'Consider your
verdict,' he said to the jury, in a low, trembling voice.
'There's more evidence to come yet, please your Majesty,' said the White
Rabbit, jumping up in a great hurry; 'this paper has just been picked
up.'
'What's in it?' said the Queen.
'I haven't opened it yet,' said the White Rabbit, 'but it seems to be a
letter, written by the prisoner to--to somebody.'
'It must have been that,' said the King, 'unless it was written to
nobody, which isn't usual, you know.'
'Who is it directed to?' said one of the jurymen.
'It isn't directed at all,' said the White Rabbit; 'in fact, there's
nothing written on the OUTSIDE.' He unfolded the paper as he spoke, and
added 'It isn't a letter, after all: it's a set of verses.'
'Are they in the prisoner's handwriting?' asked another of the jurymen.
'No, they're not,' said the White Rabbit, 'and that's the queerest thing
about it.' (The jury all looked puzzled.)
'He must have imitated somebody else's hand,' said the King. (The jury
all brightened up again.)
'Please your Majesty,' said the Knave, 'I didn't write it, and they
can't prove I did: there's no name signed at the end.'
'If you didn't sign it,' said the King, 'that only makes the matter
worse. You MUST have meant some mischief, or else you'd have signed your
name like an honest man.'
There was a general clapping of hands at this: it was the first really
clever thing the King had said that day.
'That PROVES his guilt,' said the Queen.
'It proves nothing of the sort!' said Alice. 'Why, you don't even know
what they're about!'
'Read them,' said the King.
The White Rabbit put on his spectacles. 'Where shall I begin, please
your Majesty?' he asked.
'Begin at the beginning,' the King said gravely, 'and go on till you
come to the end: then stop.'
These were the verses the White Rabbit read:--
'They told me you had been to her,
And mentioned me to him:
She gave me a good character,
But said I could not swim.
He sent them word I had not gone
(We know it to be true):
If she should push the matter on,
What would become of you?
I gave her one, they gave him two,
You gave us three or more;
They all returned from him to you,
Though they were mine before.
If I or she should chance to be
Involved in this affair,
He trusts to you to set them free,
Exactly as we were.
My notion was that you had been
(Before she had this fit)
An obstacle that came between
Him, and ourselves, and it.
Don't let him know she liked them best,
For this must ever be
A secret, kept from all the rest,
Between yourself and me.'
'That's the most important piece of evidence we've heard yet,' said the
King, rubbing his hands; 'so now let the jury--'
'If any one of them can explain it,' said Alice, (she had grown so large
in the last few minutes that she wasn't a bit afraid of interrupting
him,) 'I'll give him sixpence. _I_ don't believe there's an atom of
meaning in it.'
The jury all wrote down on their slates, 'SHE doesn't believe there's an
atom of meaning in it,' but none of them attempted to explain the paper.
'If there's no meaning in it,' said the King, 'that saves a world of
trouble, you know, as we needn't try to find any. And yet I don't know,'
he went on, spreading out the verses on his knee, and looking at them
with one eye; 'I seem to see some meaning in them, after all. "--SAID
I COULD NOT SWIM--" you can't swim, can you?' he added, turning to the
Knave.
The Knave shook his head sadly. 'Do I look like it?' he said. (Which he
certainly did NOT, being made entirely of cardboard.)
'All right, so far,' said the King, and he went on muttering over
the verses to himself: '"WE KNOW IT TO BE TRUE--" that's the jury, of
course--"I GAVE HER ONE, THEY GAVE HIM TWO--" why, that must be what he
did with the tarts, you know--'
'But, it goes on "THEY ALL RETURNED FROM HIM TO YOU,"' said Alice.
'Why, there they are!' said the King triumphantly, pointing to the tarts
on the table. 'Nothing can be clearer than THAT. Then again--"BEFORE SHE
HAD THIS FIT--" you never had fits, my dear, I think?' he said to the
Queen.
'Never!' said the Queen furiously, throwing an inkstand at the Lizard
as she spoke. (The unfortunate little Bill had left off writing on his
slate with one finger, as he found it made no mark; but he now hastily
began again, using the ink, that was trickling down his face, as long as
it lasted.)
'Then the words don't FIT you,' said the King, looking round the court
with a smile. There was a dead silence.
'It's a pun!' the King added in an offended tone, and everybody laughed,
'Let the jury consider their verdict,' the King said, for about the
twentieth time that day.
'No, no!' said the Queen. 'Sentence first--verdict afterwards.'
'Stuff and nonsense!' said Alice loudly. 'The idea of having the
sentence first!'
'Hold your tongue!' said the Queen, turning purple.
'I won't!' said Alice.
'Off with her head!' the Queen shouted at the top of her voice. Nobody
moved.
'Who cares for you?' said <NAME>, (she had grown to her full size by this
time.) 'You're nothing but a pack of cards!'
At this the whole pack rose up into the air, and came flying down upon
her: she gave a little scream, half of fright and half of anger, and
tried to beat them off, and found herself lying on the bank, with her
head in the lap of her sister, who was gently brushing away some dead
leaves that had fluttered down from the trees upon her face.
'Wake up, <NAME> dear!' said her sister; 'Why, what a long sleep you've
had!'
'Oh, I've had such a curious dream!' said <NAME>, and she told her
sister, as well as she could remember them, all these strange Adventures
of hers that you have just been reading about; and when she had
finished, her sister kissed her, and said, 'It WAS a curious dream,
dear, certainly: but now run in to your tea; it's getting late.' So
<NAME> got up and ran off, thinking while she ran, as well she might,
what a wonderful dream it had been.
But her sister sat still just as she left her, leaning her head on her
hand, watching the setting sun, and thinking of little Alice and all her
wonderful Adventures, till she too began dreaming after a fashion, and
this was her dream:--
First, she dreamed of little Alice herself, and once again the tiny
hands were clasped upon her knee, and the bright eager eyes were looking
up into hers--she could hear the very tones of her voice, and see that
queer little toss of her head to keep back the wandering hair that
WOULD always get into her eyes--and still as she listened, or seemed to
listen, the whole place around her became alive with the strange creatures
of her little sister's dream.
The long grass rustled at her feet as the White Rabbit hurried by--the
frightened Mouse splashed his way through the neighbouring pool--she
could hear the rattle of the teacups as the March Hare and his friends
shared their never-ending meal, and the shrill voice of the Queen
ordering off her unfortunate guests to execution--once more the pig-baby
was sneezing on the Duchess's knee, while plates and dishes crashed
around it--once more the shriek of the Gryphon, the squeaking of the
Lizard's slate-pencil, and the choking of the suppressed guinea-pigs,
filled the air, mixed up with the distant sobs of the miserable Mock
Turtle.
So she sat on, with closed eyes, and half believed herself in
Wonderland, though she knew she had but to open them again, and all
would change to dull reality--the grass would be only rustling in the
wind, and the pool rippling to the waving of the reeds--the rattling
teacups would change to tinkling sheep-bells, and the Queen's shrill
cries to the voice of the shepherd boy--and the sneeze of the baby, the
shriek of the Gryphon, and all the other queer noises, would change (she
knew) to the confused clamour of the busy farm-yard--while the lowing
of the cattle in the distance would take the place of the Mock Turtle's
heavy sobs.
Lastly, she pictured to herself how this same little sister of hers
would, in the after-time, be herself a grown woman; and how she would
keep, through all her riper years, the simple and loving heart of her
childhood: and how she would gather about her other little children, and
make THEIR eyes bright and eager with many a strange tale, perhaps even
with the dream of Wonderland of long ago: and how she would feel with
all their simple sorrows, and find a pleasure in all their simple joys,
remembering her own child-life, and the happy summer days.
"""
| true | module.exports = """
# Through the Looking-Glass
'Really, now you ask me,' said PI:NAME:<NAME>END_PI, very much confused, 'I don't
think—'
'Then you shouldn't talk,' said the Hatter.
This piece of rudeness was more than Alice could bear: she got up in
great disgust, and walked off; the Dormouse fell asleep instantly, and
neither of the others took the least notice of her going, though she
looked back once or twice, half hoping that they would call after her:
the last time she saw them, they were trying to put the Dormouse into
the teapot.
'At any rate I'll never go THERE again!' said PI:NAME:<NAME>END_PI as she picked her
way through the wood. 'It's the stupidest tea-party I ever was at in all
my life!'
Just as she said this, she noticed that one of the trees had a door
leading right into it. 'That's very curious!' she thought. 'But
everything's curious today. I think I may as well go in at once.' And in
she went.
Once more she found herself in the long hall, and close to the little
glass table. 'Now, I'll manage better this time,' she said to herself,
and began by taking the little golden key, and unlocking the door that
led into the garden. Then she went to work nibbling at the mushroom (she
had kept a piece of it in her pocket) till she was about a foot high:
then she walked down the little passage: and THEN—she found herself at
last in the beautiful garden, among the bright flower-beds and the cool
fountains.
Alice opened the door and found that it led into a small passage, not
much larger than a rat-hole: she knelt down and looked along the passage
into the loveliest garden you ever saw. How she longed to get out of
that dark hall, and wander about among those beds of bright flowers and
those cool fountains, but she could not even get her head through the
doorway; 'and even if my head would go through,' thought poor Alice, 'it
would be of very little use without my shoulders. Oh, how I wish I could
shut up like a telescope! I think I could, if I only knew how to begin.'
For, you see, so many out-of-the-way things had happened lately,
that Alice had begun to think that very few things indeed were really
impossible.
'Only mustard isn't a bird,' Alice remarked.
'Right, as usual,' said the Duchess: 'what a clear way you have of
putting things!'
'It's a mineral, I THINK,' said Alice.
'Of course it is,' said the Duchess, who seemed ready to agree to
everything that Alice said; 'there's a large mustard-mine near here. And
the moral of that is--"The more there is of mine, the less there is of
yours."'
'Oh, I know!' exclaimed Alice, who had not attended to this last remark,
'it's a vegetable. It doesn't look like one, but it is.'
'I quite agree with you,' said the Duchess; 'and the moral of that
is--"Be what you would seem to be"--or if you'd like it put more
simply--*Never imagine yourself not to be otherwise than what it might
appear to others that what you were or might have been was not otherwise
than what you had been would have appeared to them to be otherwise.*'
'I think I should understand that better,' Alice said very politely, 'if
I had it written down: but I can't quite follow it as you say it.'
'That's nothing to what I could say if I chose,' the Duchess replied, in
a pleased tone.
'Pray don't trouble yourself to say it any longer than that,' said
Alice.
'Oh, don't talk about trouble!' said the Duchess. 'I make you a present
of everything I've said as yet.'
'A cheap sort of present!' thought Alice. 'I'm glad they don't give
birthday presents like that!' But she did not venture to say it out
loud.
'Thinking again?' the Duchess asked, with another dig of her sharp
little chin.
'I've a right to think,' said Alice sharply, for she was beginning to
feel a little worried.
'Just about as much right,' said the Duchess, 'as pigs have to fly; and
the m--'
But here, to Alice's great surprise, the Duchess's voice died away, even
in the middle of her favourite word 'moral,' and the arm that was linked
into hers began to tremble. PI:NAME:<NAME>END_PI looked up, and there stood the Queen
in front of them, with her arms folded, frowning like a thunderstorm.
'A fine day, your Majesty!' the Duchess began in a low, weak voice.
'Now, I give you fair warning,' shouted the Queen, stamping on the
ground as she spoke; 'either you or your head must be off, and that in
about half no time! Take your choice!'
The Duchess took her choice, and was gone in a moment.
'Let's go on with the game,' the Queen said to PI:NAME:<NAME>END_PI; and Alice was
too much frightened to say a word, but slowly followed her back to the
croquet-ground.
The other guests had taken advantage of the Queen's absence, and were
resting in the shade: however, the moment they saw her, they hurried
back to the game, the Queen merely remarking that a moment's delay would
cost them their lives.
All the time they were playing the Queen never left off quarrelling with
the other players, and shouting 'Off with his head!' or 'Off with her
head!' Those whom she sentenced were taken into custody by the soldiers,
who of course had to leave off being arches to do this, so that by
the end of half an hour or so there were no arches left, and all the
players, except the King, the Queen, and PI:NAME:<NAME>END_PI, were in custody and
under sentence of execution.
Then the Queen left off, quite out of breath, and said to Alice, 'Have
you seen the Mock Turtle yet?'
'No,' said Alice. 'I don't even know what a Mock Turtle is.'
'It's the thing Mock Turtle Soup is made from,' said the Queen.
'I never saw one, or heard of one,' said PI:NAME:<NAME>END_PI.
'Come on, then,' said the Queen, 'and he shall tell you his history,'
As they walked off together, Alice heard the King say in a low voice,
to the company generally, 'You are all pardoned.' 'Come, THAT'S a good
thing!' she said to herself, for she had felt quite unhappy at the
number of executions the Queen had ordered.
They very soon came upon a Gryphon, lying fast asleep in the sun.
(IF you don't know what a Gryphon is, look at the picture.) 'Up, lazy
thing!' said the Queen, 'and take this young lady to see the Mock
Turtle, and to hear his history. I must go back and see after some
executions I have ordered'; and she walked off, leaving Alice alone with
the Gryphon. Alice did not quite like the look of the creature, but on
the whole she thought it would be quite as safe to stay with it as to go
after that savage Queen: so she waited.
The Gryphon sat up and rubbed its eyes: then it watched the Queen till
she was out of sight: then it chuckled. 'What fun!' said the Gryphon,
half to itself, half to Alice.
'What IS the fun?' said Alice.
'Why, SHE,' said the Gryphon. 'It's all her fancy, that: they never
executes nobody, you know. Come on!'
'Everybody says "come on!" here,' thought Alice, as she went slowly
after it: 'I never was so ordered about in all my life, never!'
They had not gone far before they saw the Mock Turtle in the distance,
sitting sad and lonely on a little ledge of rock, and, as they came
nearer, Alice could hear him sighing as if his heart would break. She
pitied him deeply. 'What is his sorrow?' she asked the Gryphon, and the
Gryphon answered, very nearly in the same words as before, 'It's all his
fancy, that: he hasn't got no sorrow, you know. Come on!'
So they went up to the Mock Turtle, who looked at them with large eyes
full of tears, but said nothing.
'This here young lady,' said the Gryphon, 'she wants for to know your
history, she do.'
'I'll tell it her,' said the Mock Turtle in a deep, hollow tone: 'sit
down, both of you, and don't speak a word till I've finished.'
So they sat down, and nobody spoke for some minutes. Alice thought to
herself, 'I don't see how he can EVEN finish, if he doesn't begin.' But
she waited patiently.
'Once,' said the Mock Turtle at last, with a deep sigh, 'I was a real
Turtle.'
These words were followed by a very long silence, broken only by an
occasional exclamation of 'Hjckrrh!' from the Gryphon, and the constant
heavy sobbing of the Mock Turtle. Alice was very nearly getting up and
saying, 'Thank you, sir, for your interesting story,' but she could
not help thinking there MUST be more to come, so she sat still and said
nothing.
'When we were little,' the Mock Turtle went on at last, more calmly,
though still sobbing a little now and then, 'we went to school in the
sea. The master was an old Turtle--we used to call him Tortoise--'
'Why did you call him Tortoise, if he wasn't one?' Alice asked.
'We called him Tortoise because he taught us,' said the Mock Turtle
angrily: 'really you are very dull!'
'You ought to be ashamed of yourself for asking such a simple question,'
added the Gryphon; and then they both sat silent and looked at poor
Alice, who felt ready to sink into the earth. At last the Gryphon said
to the Mock Turtle, 'Drive on, old fellow! Don't be all day about it!'
and he went on in these words:
'Yes, we went to school in the sea, though you mayn't believe it--'
'I never said I didn't!' interrupted Alice.
'You did,' said the Mock Turtle.
'Hold your tongue!' added the Gryphon, before Alice could speak again.
The Mock Turtle went on.
'We had the best of educations--in fact, we went to school every day--'
'I'VE been to a day-school, too,' said Alice; 'you needn't be so proud
as all that.'
'With extras?' asked the Mock Turtle a little anxiously.
'Yes,' said Alice, 'we learned French and music.'
'And washing?' said the Mock Turtle.
'Certainly not!' said Alice indignantly.
'Ah! then yours wasn't a really good school,' said the Mock Turtle in
a tone of great relief. 'Now at OURS they had at the end of the bill,
"French, music, AND WASHING--extra."'
'How the creatures order one about, and make one repeat lessons!'
thought Alice; 'I might as well be at school at once.' However, she
got up, and began to repeat it, but her head was so full of the Lobster
Quadrille, that she hardly knew what she was saying, and the words came
very queer indeed:--
''Tis the voice of the Lobster; I heard him declare,
"You have baked me too brown, I must sugar my hair."
As a duck with its eyelids, so he with his nose
Trims his belt and his buttons, and turns out his toes.'
When the sands are all dry, he is gay as a lark,
And will talk in contemptuous tones of the Shark,
But, when the tide rises and sharks are around,
His voice has a timid and tremulous sound.
'That's different from what I used to say when I was a child,' said the
Gryphon.
'Well, I never heard it before,' said the Mock Turtle; 'but it sounds
uncommon nonsense.'
Alice said nothing; she had sat down with her face in her hands,
wondering if anything would EVER happen in a natural way again.
'I should like to have it explained,' said the Mock Turtle.
'She can't explain it,' said the Gryphon hastily. 'Go on with the next
verse.'
'But about his toes?' the Mock Turtle persisted. 'How COULD he turn them
out with his nose, you know?'
'It's the first position in dancing.' Alice said; but was dreadfully
puzzled by the whole thing, and longed to change the subject.
'Go on with the next verse,' the Gryphon repeated impatiently: 'it
begins "I passed by his garden."'
Alice did not dare to disobey, though she felt sure it would all come
wrong, and she went on in a trembling voice:--
'I passed by his garden, and marked, with one eye,
How the Owl and the Panther were sharing a pie--'
The Panther took pie-crust, and gravy, and meat,
While the Owl had the dish as its share of the treat.
When the pie was all finished, the Owl, as a boon,
Was kindly permitted to pocket the spoon:
While the Panther received knife and fork with a growl,
And concluded the banquet--
'What IS the use of repeating all that stuff,' the Mock Turtle
interrupted, 'if you don't explain it as you go on? It's by far the most
confusing thing I ever heard!'
'Yes, I think you'd better leave off,' said the Gryphon: and Alice was
only too glad to do so.
'Shall we try another figure of the Lobster Quadrille?' the Gryphon went
on. 'Or would you like the Mock Turtle to sing you a song?'
'Oh, a song, please, if the Mock Turtle would be so kind,' Alice
replied, so eagerly that the Gryphon said, in a rather offended tone,
'Hm! No accounting for tastes! Sing her "Turtle Soup," will you, old
fellow?'
The Mock Turtle sighed deeply, and began, in a voice sometimes choked
with sobs, to sing this:--
'Beautiful Soup, so rich and green,
Waiting in a hot tureen!
Who for such dainties would not stoop?
Soup of the evening, beautiful Soup!
Soup of the evening, beautiful Soup!
Beau--ootiful Soo--oop!
Beau--ootiful Soo--oop!
Soo--oop of the e--e--evening,
Beautiful, beautiful Soup!
'Beautiful Soup! Who cares for fish,
Game, or any other dish?
Who would not give all else for two
Pennyworth only of beautiful Soup?
Pennyworth only of beautiful Soup?
Beau--ootiful Soo--oop!
Beau--ootiful Soo--oop!
Soo--oop of the e--e--evening,
Beautiful, beauti--FUL SOUP!'
'Chorus again!' cried the Gryphon, and the Mock Turtle had just begun
to repeat it, when a cry of 'The trial's beginning!' was heard in the
distance.
'Come on!' cried the Gryphon, and, taking Alice by the hand, it hurried
off, without waiting for the end of the song.
'What trial is it?' Alice panted as she ran; but the Gryphon only
answered 'Come on!' and ran the faster, while more and more faintly
came, carried on the breeze that followed them, the melancholy words:--
'Soo--oop of the e--e--evening,
Beautiful, beautiful Soup!'
## CHAPTER XI. Who Stole the Tarts?
The King and Queen of Hearts were seated on their throne when they
arrived, with a great crowd assembled about them--all sorts of little
birds and beasts, as well as the whole pack of cards: the Knave was
standing before them, in chains, with a soldier on each side to guard
him; and near the King was the White Rabbit, with a trumpet in one hand,
and a scroll of parchment in the other. In the very middle of the court
was a table, with a large dish of tarts upon it: they looked so good,
that it made Alice quite hungry to look at them--'I wish they'd get the
trial done,' she thought, 'and hand round the refreshments!' But there
seemed to be no chance of this, so she began looking at everything about
her, to pass away the time.
PI:NAME:<NAME>END_PI had never been in a court of justice before, but she had read
about them in books, and she was quite pleased to find that she knew
the name of nearly everything there. 'That's the judge,' she said to
herself, 'because of his great wig.'
The judge, by the way, was the King; and as he wore his crown over the
wig, (look at the frontispiece if you want to see how he did it,) he did
not look at all comfortable, and it was certainly not becoming.
'And that's the jury-box,' thought PI:NAME:<NAME>END_PI, 'and those twelve creatures,'
(she was obliged to say 'creatures,' you see, because some of them were
animals, and some were birds,) 'I suppose they are the jurors.' She said
this last word two or three times over to herself, being rather proud of
it: for she thought, and rightly too, that very few little girls of her
age knew the meaning of it at all. However, 'jury-men' would have done
just as well.
The twelve jurors were all writing very busily on slates. 'What are they
doing?' PI:NAME:<NAME>END_PI whispered to the Gryphon. 'They can't have anything to put
down yet, before the trial's begun.'
'They're putting down their names,' the Gryphon whispered in reply, 'for
fear they should forget them before the end of the trial.'
'Stupid things!' Alice began in a loud, indignant voice, but she stopped
hastily, for the White Rabbit cried out, 'Silence in the court!' and the
King put on his spectacles and looked anxiously round, to make out who
was talking.
Alice could see, as well as if she were looking over their shoulders,
that all the jurors were writing down 'stupid things!' on their slates,
and she could even make out that one of them didn't know how to spell
'stupid,' and that he had to ask his neighbour to tell him. 'A nice
muddle their slates'll be in before the trial's over!' thought Alice.
One of the jurors had a pencil that squeaked. This of course, Alice
could not stand, and she went round the court and got behind him, and
very soon found an opportunity of taking it away. She did it so quickly
that the poor little juror (it was Bill, the Lizard) could not make out
at all what had become of it; so, after hunting all about for it, he was
obliged to write with one finger for the rest of the day; and this was
of very little use, as it left no mark on the slate.
'Herald, read the accusation!' said the King.
On this the White Rabbit blew three blasts on the trumpet, and then
unrolled the parchment scroll, and read as follows:--
'The Queen of Hearts, she made some tarts,
All on a summer day:
The Knave of Hearts, he stole those tarts,
And took them quite away!'
'Consider your verdict,' the King said to the jury.
'Not yet, not yet!' the Rabbit hastily interrupted. 'There's a great
deal to come before that!'
'Call the first witness,' said the King; and the White Rabbit blew three
blasts on the trumpet, and called out, 'First witness!'
The first witness was the Hatter. He came in with a teacup in one
hand and a piece of bread-and-butter in the other. 'I beg pardon, your
Majesty,' he began, 'for bringing these in: but I hadn't quite finished
my tea when I was sent for.'
'You ought to have finished,' said the King. 'When did you begin?'
The Hatter looked at the March Hare, who had followed him into the
court, arm-in-arm with the Dormouse. 'Fourteenth of March, I think it
was,' he said.
'Fifteenth,' said the March Hare.
'Sixteenth,' added the Dormouse.
'Write that down,' the King said to the jury, and the jury eagerly
wrote down all three dates on their slates, and then added them up, and
reduced the answer to shillings and pence.
'Take off your hat,' the King said to the Hatter.
'It isn't mine,' said the Hatter.
'Stolen!' the King exclaimed, turning to the jury, who instantly made a
memorandum of the fact.
'I keep them to sell,' the Hatter added as an explanation; 'I've none of
my own. I'm a hatter.'
Here the Queen put on her spectacles, and began staring at the Hatter,
who turned pale and fidgeted.
'Give your evidence,' said the King; 'and don't be nervous, or I'll have
you executed on the spot.'
This did not seem to encourage the witness at all: he kept shifting
from one foot to the other, looking uneasily at the Queen, and in
his confusion he bit a large piece out of his teacup instead of the
bread-and-butter.
Just at this moment Alice felt a very curious sensation, which puzzled
her a good deal until she made out what it was: she was beginning to
grow larger again, and she thought at first she would get up and leave
the court; but on second thoughts she decided to remain where she was as
long as there was room for her.
'I wish you wouldn't squeeze so.' said the Dormouse, who was sitting
next to her. 'I can hardly breathe.'
'I can't help it,' said Alice very meekly: 'I'm growing.'
'You've no right to grow here,' said the Dormouse.
'Don't talk nonsense,' said Alice more boldly: 'you know you're growing
too.'
'Yes, but I grow at a reasonable pace,' said the Dormouse: 'not in that
ridiculous fashion.' And he got up very sulkily and crossed over to the
other side of the court.
All this time the Queen had never left off staring at the Hatter, and,
just as the Dormouse crossed the court, she said to one of the officers
of the court, 'Bring me the list of the singers in the last concert!' on
which the wretched Hatter trembled so, that he shook both his shoes off.
'Give your evidence,' the King repeated angrily, 'or I'll have you
executed, whether you're nervous or not.'
'I'm a poor man, your Majesty,' the Hatter began, in a trembling voice,
'--and I hadn't begun my tea--not above a week or so--and what with the
bread-and-butter getting so thin--and the twinkling of the tea--'
'The twinkling of the what?' said the King.
'It began with the tea,' the Hatter replied.
'Of course twinkling begins with a T!' said the King sharply. 'Do you
take me for a dunce? Go on!'
'I'm a poor man,' the Hatter went on, 'and most things twinkled after
that--only the March Hare said--'
'I didn't!' the March Hare interrupted in a great hurry.
'You did!' said the Hatter.
'I deny it!' said the March Hare.
'He denies it,' said the King: 'leave out that part.'
'Well, at any rate, the Dormouse said--' the Hatter went on, looking
anxiously round to see if he would deny it too: but the Dormouse denied
nothing, being fast asleep.
'After that,' continued the Hatter, 'I cut some more bread-and-butter--'
'But what did the Dormouse say?' one of the jury asked.
'That I can't remember,' said the Hatter.
'You MUST remember,' remarked the King, 'or I'll have you executed.'
The miserable Hatter dropped his teacup and bread-and-butter, and went
down on one knee. 'I'm a poor man, your Majesty,' he began.
'You're a very poor speaker,' said the King.
Here one of the guinea-pigs cheered, and was immediately suppressed by
the officers of the court. (As that is rather a hard word, I will just
explain to you how it was done. They had a large canvas bag, which tied
up at the mouth with strings: into this they slipped the guinea-pig,
head first, and then sat upon it.)
'I'm glad I've seen that done,' thought Alice. 'I've so often read
in the newspapers, at the end of trials, "There was some attempts
at applause, which was immediately suppressed by the officers of the
court," and I never understood what it meant till now.'
'If that's all you know about it, you may stand down,' continued the
King.
'I can't go no lower,' said the Hatter: 'I'm on the floor, as it is.'
'Then you may SIT down,' the King replied.
Here the other guinea-pig cheered, and was suppressed.
'Come, that finished the guinea-pigs!' thought Alice. 'Now we shall get
on better.'
'I'd rather finish my tea,' said the Hatter, with an anxious look at the
Queen, who was reading the list of singers.
'You may go,' said the King, and the Hatter hurriedly left the court,
without even waiting to put his shoes on.
'--and just take his head off outside,' the Queen added to one of the
officers: but the Hatter was out of sight before the officer could get
to the door.
'Call the next witness!' said the King.
The next witness was the Duchess's cook. She carried the pepper-box in
her hand, and Alice guessed who it was, even before she got into the
court, by the way the people near the door began sneezing all at once.
'Give your evidence,' said the King.
'Shan't,' said the cook.
The King looked anxiously at the White Rabbit, who said in a low voice,
'Your Majesty must cross-examine THIS witness.'
'Well, if I must, I must,' the King said, with a melancholy air, and,
after folding his arms and frowning at the cook till his eyes were
nearly out of sight, he said in a deep voice, 'What are tarts made of?'
'Pepper, mostly,' said the cook.
'Treacle,' said a sleepy voice behind her.
'Collar that Dormouse,' the Queen shrieked out. 'Behead that Dormouse!
Turn that Dormouse out of court! Suppress him! Pinch him! Off with his
whiskers!'
For some minutes the whole court was in confusion, getting the Dormouse
turned out, and, by the time they had settled down again, the cook had
disappeared.
'Never mind!' said the King, with an air of great relief. 'Call the next
witness.' And he added in an undertone to the Queen, 'Really, my dear,
YOU must cross-examine the next witness. It quite makes my forehead
ache!'
Alice watched the White Rabbit as he fumbled over the list, feeling very
curious to see what the next witness would be like, '--for they haven't
got much evidence YET,' she said to herself. Imagine her surprise, when
the White Rabbit read out, at the top of his shrill little voice, the
name 'PI:NAME:<NAME>END_PI!'
## CHAPTER XII. Alice's Evidence
'Here!' cried PI:NAME:<NAME>END_PI, quite forgetting in the flurry of the moment how
large she had grown in the last few minutes, and she jumped up in such
a hurry that she tipped over the jury-box with the edge of her skirt,
upsetting all the jurymen on to the heads of the crowd below, and there
they lay sprawling about, reminding her very much of a globe of goldfish
she had accidentally upset the week before.
'Oh, I BEG your pardon!' she exclaimed in a tone of great dismay, and
began picking them up again as quickly as she could, for the accident of
the goldfish kept running in her head, and she had a vague sort of idea
that they must be collected at once and put back into the jury-box, or
they would die.
'The trial cannot proceed,' said the King in a very grave voice, 'until
all the jurymen are back in their proper places--ALL,' he repeated with
great emphasis, looking hard at Alice as he said do.
Alice looked at the jury-box, and saw that, in her haste, she had put
the Lizard in head downwards, and the poor little thing was waving its
tail about in a melancholy way, being quite unable to move. She soon got
it out again, and put it right; 'not that it signifies much,' she said
to herself; 'I should think it would be QUITE as much use in the trial
one way up as the other.'
As soon as the jury had a little recovered from the shock of being
upset, and their slates and pencils had been found and handed back to
them, they set to work very diligently to write out a history of the
accident, all except the Lizard, who seemed too much overcome to do
anything but sit with its mouth open, gazing up into the roof of the
court.
'What do you know about this business?' the King said to Alice.
'Nothing,' said Alice.
'Nothing WHATEVER?' persisted the King.
'Nothing whatever,' said Alice.
'That's very important,' the King said, turning to the jury. They were
just beginning to write this down on their slates, when the White Rabbit
interrupted: 'UNimportant, your Majesty means, of course,' he said in a
very respectful tone, but frowning and making faces at him as he spoke.
'UNimportant, of course, I meant,' the King hastily said, and went on
to himself in an undertone,
'important--unimportant--unimportant--important--' as if he were trying
which word sounded best.
Some of the jury wrote it down 'important,' and some 'unimportant.'
Alice could see this, as she was near enough to look over their slates;
'but it doesn't matter a bit,' she thought to herself.
At this moment the King, who had been for some time busily writing in
his note-book, cackled out 'Silence!' and read out from his book, 'Rule
Forty-two. ALL PERSONS MORE THAN A MILE HIGH TO LEAVE THE COURT.'
Everybody looked at Alice.
'I'M not a mile high,' said Alice.
'You are,' said the King.
'Nearly two miles high,' added the Queen.
'Well, I shan't go, at any rate,' said Alice: 'besides, that's not a
regular rule: you invented it just now.'
'It's the oldest rule in the book,' said the King.
'Then it ought to be Number One,' said Alice.
The King turned pale, and shut his note-book hastily. 'Consider your
verdict,' he said to the jury, in a low, trembling voice.
'There's more evidence to come yet, please your Majesty,' said the White
Rabbit, jumping up in a great hurry; 'this paper has just been picked
up.'
'What's in it?' said the Queen.
'I haven't opened it yet,' said the White Rabbit, 'but it seems to be a
letter, written by the prisoner to--to somebody.'
'It must have been that,' said the King, 'unless it was written to
nobody, which isn't usual, you know.'
'Who is it directed to?' said one of the jurymen.
'It isn't directed at all,' said the White Rabbit; 'in fact, there's
nothing written on the OUTSIDE.' He unfolded the paper as he spoke, and
added 'It isn't a letter, after all: it's a set of verses.'
'Are they in the prisoner's handwriting?' asked another of the jurymen.
'No, they're not,' said the White Rabbit, 'and that's the queerest thing
about it.' (The jury all looked puzzled.)
'He must have imitated somebody else's hand,' said the King. (The jury
all brightened up again.)
'Please your Majesty,' said the Knave, 'I didn't write it, and they
can't prove I did: there's no name signed at the end.'
'If you didn't sign it,' said the King, 'that only makes the matter
worse. You MUST have meant some mischief, or else you'd have signed your
name like an honest man.'
There was a general clapping of hands at this: it was the first really
clever thing the King had said that day.
'That PROVES his guilt,' said the Queen.
'It proves nothing of the sort!' said Alice. 'Why, you don't even know
what they're about!'
'Read them,' said the King.
The White Rabbit put on his spectacles. 'Where shall I begin, please
your Majesty?' he asked.
'Begin at the beginning,' the King said gravely, 'and go on till you
come to the end: then stop.'
These were the verses the White Rabbit read:--
'They told me you had been to her,
And mentioned me to him:
She gave me a good character,
But said I could not swim.
He sent them word I had not gone
(We know it to be true):
If she should push the matter on,
What would become of you?
I gave her one, they gave him two,
You gave us three or more;
They all returned from him to you,
Though they were mine before.
If I or she should chance to be
Involved in this affair,
He trusts to you to set them free,
Exactly as we were.
My notion was that you had been
(Before she had this fit)
An obstacle that came between
Him, and ourselves, and it.
Don't let him know she liked them best,
For this must ever be
A secret, kept from all the rest,
Between yourself and me.'
'That's the most important piece of evidence we've heard yet,' said the
King, rubbing his hands; 'so now let the jury--'
'If any one of them can explain it,' said Alice, (she had grown so large
in the last few minutes that she wasn't a bit afraid of interrupting
him,) 'I'll give him sixpence. _I_ don't believe there's an atom of
meaning in it.'
The jury all wrote down on their slates, 'SHE doesn't believe there's an
atom of meaning in it,' but none of them attempted to explain the paper.
'If there's no meaning in it,' said the King, 'that saves a world of
trouble, you know, as we needn't try to find any. And yet I don't know,'
he went on, spreading out the verses on his knee, and looking at them
with one eye; 'I seem to see some meaning in them, after all. "--SAID
I COULD NOT SWIM--" you can't swim, can you?' he added, turning to the
Knave.
The Knave shook his head sadly. 'Do I look like it?' he said. (Which he
certainly did NOT, being made entirely of cardboard.)
'All right, so far,' said the King, and he went on muttering over
the verses to himself: '"WE KNOW IT TO BE TRUE--" that's the jury, of
course--"I GAVE HER ONE, THEY GAVE HIM TWO--" why, that must be what he
did with the tarts, you know--'
'But, it goes on "THEY ALL RETURNED FROM HIM TO YOU,"' said Alice.
'Why, there they are!' said the King triumphantly, pointing to the tarts
on the table. 'Nothing can be clearer than THAT. Then again--"BEFORE SHE
HAD THIS FIT--" you never had fits, my dear, I think?' he said to the
Queen.
'Never!' said the Queen furiously, throwing an inkstand at the Lizard
as she spoke. (The unfortunate little Bill had left off writing on his
slate with one finger, as he found it made no mark; but he now hastily
began again, using the ink, that was trickling down his face, as long as
it lasted.)
'Then the words don't FIT you,' said the King, looking round the court
with a smile. There was a dead silence.
'It's a pun!' the King added in an offended tone, and everybody laughed,
'Let the jury consider their verdict,' the King said, for about the
twentieth time that day.
'No, no!' said the Queen. 'Sentence first--verdict afterwards.'
'Stuff and nonsense!' said Alice loudly. 'The idea of having the
sentence first!'
'Hold your tongue!' said the Queen, turning purple.
'I won't!' said Alice.
'Off with her head!' the Queen shouted at the top of her voice. Nobody
moved.
'Who cares for you?' said PI:NAME:<NAME>END_PI, (she had grown to her full size by this
time.) 'You're nothing but a pack of cards!'
At this the whole pack rose up into the air, and came flying down upon
her: she gave a little scream, half of fright and half of anger, and
tried to beat them off, and found herself lying on the bank, with her
head in the lap of her sister, who was gently brushing away some dead
leaves that had fluttered down from the trees upon her face.
'Wake up, PI:NAME:<NAME>END_PI dear!' said her sister; 'Why, what a long sleep you've
had!'
'Oh, I've had such a curious dream!' said PI:NAME:<NAME>END_PI, and she told her
sister, as well as she could remember them, all these strange Adventures
of hers that you have just been reading about; and when she had
finished, her sister kissed her, and said, 'It WAS a curious dream,
dear, certainly: but now run in to your tea; it's getting late.' So
PI:NAME:<NAME>END_PI got up and ran off, thinking while she ran, as well she might,
what a wonderful dream it had been.
But her sister sat still just as she left her, leaning her head on her
hand, watching the setting sun, and thinking of little Alice and all her
wonderful Adventures, till she too began dreaming after a fashion, and
this was her dream:--
First, she dreamed of little Alice herself, and once again the tiny
hands were clasped upon her knee, and the bright eager eyes were looking
up into hers--she could hear the very tones of her voice, and see that
queer little toss of her head to keep back the wandering hair that
WOULD always get into her eyes--and still as she listened, or seemed to
listen, the whole place around her became alive with the strange creatures
of her little sister's dream.
The long grass rustled at her feet as the White Rabbit hurried by--the
frightened Mouse splashed his way through the neighbouring pool--she
could hear the rattle of the teacups as the March Hare and his friends
shared their never-ending meal, and the shrill voice of the Queen
ordering off her unfortunate guests to execution--once more the pig-baby
was sneezing on the Duchess's knee, while plates and dishes crashed
around it--once more the shriek of the Gryphon, the squeaking of the
Lizard's slate-pencil, and the choking of the suppressed guinea-pigs,
filled the air, mixed up with the distant sobs of the miserable Mock
Turtle.
So she sat on, with closed eyes, and half believed herself in
Wonderland, though she knew she had but to open them again, and all
would change to dull reality--the grass would be only rustling in the
wind, and the pool rippling to the waving of the reeds--the rattling
teacups would change to tinkling sheep-bells, and the Queen's shrill
cries to the voice of the shepherd boy--and the sneeze of the baby, the
shriek of the Gryphon, and all the other queer noises, would change (she
knew) to the confused clamour of the busy farm-yard--while the lowing
of the cattle in the distance would take the place of the Mock Turtle's
heavy sobs.
Lastly, she pictured to herself how this same little sister of hers
would, in the after-time, be herself a grown woman; and how she would
keep, through all her riper years, the simple and loving heart of her
childhood: and how she would gather about her other little children, and
make THEIR eyes bright and eager with many a strange tale, perhaps even
with the dream of Wonderland of long ago: and how she would feel with
all their simple sorrows, and find a pleasure in all their simple joys,
remembering her own child-life, and the happy summer days.
"""
|
[
{
"context": "/global_state_endpoint'\n @globalState = {key: 'val'}\n\n afterEach ->\n jasmine.Ajax.uninstall()\n ",
"end": 260,
"score": 0.9769308567047119,
"start": 257,
"tag": "KEY",
"value": "val"
}
] | spec/javascripts/global_state_saver_spec.coffee | sciencelabshs/lara | 0 | describe 'GlobalIframeSaver', ->
beforeEach ->
loadFixtures "global-iframe-saver.html" # just 3 iframes
jasmine.Ajax.install()
jasmine.mockIframePhone.install()
@saveUrl = 'https://lara.url/global_state_endpoint'
@globalState = {key: 'val'}
afterEach ->
jasmine.Ajax.uninstall()
jasmine.mockIframePhone.uninstall()
it 'should broadcast global state if it is provided in config', ->
@globalSaver = new GlobalIframeSaver save_url: @saveUrl, raw_data: JSON.stringify(@globalState)
$('iframe').each (idx, iframeEl) =>
@globalSaver.addNewInteractive(iframeEl)
expect(jasmine.mockIframePhone.messages.count()).toEqual 3
$('iframe').each (idx, iframeEl) =>
expect(jasmine.mockIframePhone.messages.at(idx)).toEqual
source: window
target: iframeEl
message:
type: 'loadInteractiveGlobal'
content: @globalState
describe 'when "interactiveStateGlobal" message is received from iframe', ->
beforeEach ->
@globalSaver = new GlobalIframeSaver save_url: @saveUrl
$('iframe').each (idx, iframeEl) =>
@globalSaver.addNewInteractive(iframeEl)
jasmine.mockIframePhone.postMessageFrom $('iframe')[0], {type: 'interactiveStateGlobal', content: @globalState}
it 'should broadcast "loadInteractiveGlobal" to other iframes', ->
expect(jasmine.mockIframePhone.messages.count()).toEqual 3
# Initial message.
expect(jasmine.mockIframePhone.messages.at(0)).toEqual
source: $('iframe')[0]
target: window
message:
type: 'interactiveStateGlobal'
content: @globalState
# Messages posted by GlobalIframeSaver:
expect(jasmine.mockIframePhone.messages.at(1)).toEqual
source: window
target: $('iframe')[1]
message:
type: 'loadInteractiveGlobal'
content: @globalState
expect(jasmine.mockIframePhone.messages.at(2)).toEqual
source: window
target: $('iframe')[2]
message:
type: 'loadInteractiveGlobal'
content: @globalState
it 'should send state to LARA server', ->
request = jasmine.Ajax.requests.mostRecent()
expect(request.url).toBe @saveUrl
expect(request.method).toBe 'POST'
# No idea why raw data needs to be wrapped in array - caused by jQuery or MockAjax?
expect(request.data()).toEqual raw_data: [JSON.stringify(@globalState)]
| 182058 | describe 'GlobalIframeSaver', ->
beforeEach ->
loadFixtures "global-iframe-saver.html" # just 3 iframes
jasmine.Ajax.install()
jasmine.mockIframePhone.install()
@saveUrl = 'https://lara.url/global_state_endpoint'
@globalState = {key: '<KEY>'}
afterEach ->
jasmine.Ajax.uninstall()
jasmine.mockIframePhone.uninstall()
it 'should broadcast global state if it is provided in config', ->
@globalSaver = new GlobalIframeSaver save_url: @saveUrl, raw_data: JSON.stringify(@globalState)
$('iframe').each (idx, iframeEl) =>
@globalSaver.addNewInteractive(iframeEl)
expect(jasmine.mockIframePhone.messages.count()).toEqual 3
$('iframe').each (idx, iframeEl) =>
expect(jasmine.mockIframePhone.messages.at(idx)).toEqual
source: window
target: iframeEl
message:
type: 'loadInteractiveGlobal'
content: @globalState
describe 'when "interactiveStateGlobal" message is received from iframe', ->
beforeEach ->
@globalSaver = new GlobalIframeSaver save_url: @saveUrl
$('iframe').each (idx, iframeEl) =>
@globalSaver.addNewInteractive(iframeEl)
jasmine.mockIframePhone.postMessageFrom $('iframe')[0], {type: 'interactiveStateGlobal', content: @globalState}
it 'should broadcast "loadInteractiveGlobal" to other iframes', ->
expect(jasmine.mockIframePhone.messages.count()).toEqual 3
# Initial message.
expect(jasmine.mockIframePhone.messages.at(0)).toEqual
source: $('iframe')[0]
target: window
message:
type: 'interactiveStateGlobal'
content: @globalState
# Messages posted by GlobalIframeSaver:
expect(jasmine.mockIframePhone.messages.at(1)).toEqual
source: window
target: $('iframe')[1]
message:
type: 'loadInteractiveGlobal'
content: @globalState
expect(jasmine.mockIframePhone.messages.at(2)).toEqual
source: window
target: $('iframe')[2]
message:
type: 'loadInteractiveGlobal'
content: @globalState
it 'should send state to LARA server', ->
request = jasmine.Ajax.requests.mostRecent()
expect(request.url).toBe @saveUrl
expect(request.method).toBe 'POST'
# No idea why raw data needs to be wrapped in array - caused by jQuery or MockAjax?
expect(request.data()).toEqual raw_data: [JSON.stringify(@globalState)]
| true | describe 'GlobalIframeSaver', ->
beforeEach ->
loadFixtures "global-iframe-saver.html" # just 3 iframes
jasmine.Ajax.install()
jasmine.mockIframePhone.install()
@saveUrl = 'https://lara.url/global_state_endpoint'
@globalState = {key: 'PI:KEY:<KEY>END_PI'}
afterEach ->
jasmine.Ajax.uninstall()
jasmine.mockIframePhone.uninstall()
it 'should broadcast global state if it is provided in config', ->
@globalSaver = new GlobalIframeSaver save_url: @saveUrl, raw_data: JSON.stringify(@globalState)
$('iframe').each (idx, iframeEl) =>
@globalSaver.addNewInteractive(iframeEl)
expect(jasmine.mockIframePhone.messages.count()).toEqual 3
$('iframe').each (idx, iframeEl) =>
expect(jasmine.mockIframePhone.messages.at(idx)).toEqual
source: window
target: iframeEl
message:
type: 'loadInteractiveGlobal'
content: @globalState
describe 'when "interactiveStateGlobal" message is received from iframe', ->
beforeEach ->
@globalSaver = new GlobalIframeSaver save_url: @saveUrl
$('iframe').each (idx, iframeEl) =>
@globalSaver.addNewInteractive(iframeEl)
jasmine.mockIframePhone.postMessageFrom $('iframe')[0], {type: 'interactiveStateGlobal', content: @globalState}
it 'should broadcast "loadInteractiveGlobal" to other iframes', ->
expect(jasmine.mockIframePhone.messages.count()).toEqual 3
# Initial message.
expect(jasmine.mockIframePhone.messages.at(0)).toEqual
source: $('iframe')[0]
target: window
message:
type: 'interactiveStateGlobal'
content: @globalState
# Messages posted by GlobalIframeSaver:
expect(jasmine.mockIframePhone.messages.at(1)).toEqual
source: window
target: $('iframe')[1]
message:
type: 'loadInteractiveGlobal'
content: @globalState
expect(jasmine.mockIframePhone.messages.at(2)).toEqual
source: window
target: $('iframe')[2]
message:
type: 'loadInteractiveGlobal'
content: @globalState
it 'should send state to LARA server', ->
request = jasmine.Ajax.requests.mostRecent()
expect(request.url).toBe @saveUrl
expect(request.method).toBe 'POST'
# No idea why raw data needs to be wrapped in array - caused by jQuery or MockAjax?
expect(request.data()).toEqual raw_data: [JSON.stringify(@globalState)]
|
[
{
"context": " socksHost: config.get 'proxy.socks5.host', '127.0.0.1'\n socksPort: config.get 'proxy.socks5.po",
"end": 1016,
"score": 0.999779462814331,
"start": 1007,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "Agent\n agentOptions:\n socksHost: '127.0.0.1'\n socksPort: config.get 'proxy.shadowsoc",
"end": 1249,
"score": 0.999774694442749,
"start": 1240,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "http'\n host = config.get 'proxy.http.host', '127.0.0.1'\n port = config.get 'proxy.http.port', 8118\n",
"end": 1423,
"score": 0.9997021555900574,
"start": 1414,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "st = config.get 'proxy.shadowsocks.server.host', '127.0.0.1'\n port = config.get 'proxy.shadowsocks.server.",
"end": 1863,
"score": 0.9997736811637878,
"start": 1854,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "sword = config.get 'proxy.shadowsocks.password', 'PASSWORD'\n method = config.get 'proxy.shadowsocks.metho",
"end": 2050,
"score": 0.9973863959312439,
"start": 2042,
"tag": "PASSWORD",
"value": "PASSWORD"
},
{
"context": "er host, port, local, password, method, timeout, '127.0.0.1'\n load: ->\n self = @\n # HTTP Requests\n ",
"end": 2275,
"score": 0.9997825622558594,
"start": 2266,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " socksHost: config.get 'proxy.socks5.host', '127.0.0.1'\n socksPort: config.get 'proxy.socks5.",
"end": 6631,
"score": 0.999761164188385,
"start": 6622,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "eateConnection\n socksHost: config.get '127.0.0.1'\n socksPort: config.get 'proxy.shadows",
"end": 7213,
"score": 0.9997626543045044,
"start": 7204,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "'\n host = config.get 'proxy.http.host', '127.0.0.1'\n port = config.get 'proxy.http.port', 8",
"end": 7769,
"score": 0.9997748136520386,
"start": 7760,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | lib/proxy.coffee | dazzyd/poi | 0 | Promise = require 'bluebird'
async = Promise.coroutine
EventEmitter = require 'events'
url = require 'url'
net = require 'net'
http = require 'http'
querystring = require 'querystring'
_ = require 'underscore'
caseNormalizer = require 'header-case-normalizer'
fs = Promise.promisifyAll require 'fs-extra'
request = Promise.promisifyAll require 'request'
requestAsync = Promise.promisify request
shadowsocks = require 'shadowsocks'
mime = require 'mime'
socks = require 'socks5-client'
SocksHttpAgent = require 'socks5-http-client/lib/Agent'
config = require './config'
{log, warn, error, resolveBody, isStaticResource, findHack, findHackExPath, findCache, findCacheExPath} = require './utils'
# Network error retries
retries = config.get 'poi.proxy.retries', 0
resolve = (req) ->
switch config.get 'proxy.use'
# HTTP Request via SOCKS5 proxy
when 'socks5'
return _.extend req,
agentClass: SocksHttpAgent
agentOptions:
socksHost: config.get 'proxy.socks5.host', '127.0.0.1'
socksPort: config.get 'proxy.socks5.port', 1080
# HTTP Request via Shadowsocks
when 'shadowsocks'
return _.extend req,
agentClass: SocksHttpAgent
agentOptions:
socksHost: '127.0.0.1'
socksPort: config.get 'proxy.shadowsocks.local.port', 1080
# HTTP Request via HTTP proxy
when 'http'
host = config.get 'proxy.http.host', '127.0.0.1'
port = config.get 'proxy.http.port', 8118
return _.extend req,
proxy: "http://#{host}:#{port}"
# Directly
else
return req
class Proxy extends EventEmitter
constructor: ->
super()
@startShadowsocks()
@load()
# Start Shadowsocks local server
startShadowsocks: ->
return unless config.get('proxy.use') == 'shadowsocks'
host = config.get 'proxy.shadowsocks.server.host', '127.0.0.1'
port = config.get 'proxy.shadowsocks.server.port', 8388
local = config.get 'proxy.shadowsocks.local.port', 1080
password = config.get 'proxy.shadowsocks.password', 'PASSWORD'
method = config.get 'proxy.shadowsocks.method', 'aes-256-cfb'
timeout = config.get 'proxy.shadowsocks.timeout', 600000
@sslocal = shadowsocks.createServer host, port, local, password, method, timeout, '127.0.0.1'
load: ->
self = @
# HTTP Requests
@server = http.createServer (req, res) ->
delete req.headers['proxy-connection']
# Disable HTTP Keep-Alive
req.headers['connection'] = 'close'
parsed = url.parse req.url
isGameApi = parsed.pathname.startsWith '/kcsapi'
cacheFile = null
if isStaticResource(parsed.pathname)
cacheFile = findHack(parsed.pathname) || findHackExPath(parsed.pathname) || findCache(parsed.pathname) || findCacheExPath(parsed.pathname)
reqBody = new Buffer(0)
# Get all request body
req.on 'data', (data) ->
reqBody = Buffer.concat [reqBody, data]
req.on 'end', async ->
try
options =
method: req.method
url: req.url
headers: req.headers
encoding: null
followRedirect: false
# Add body to request
if reqBody.length > 0
options = _.extend options,
body: reqBody
# Use cache file
if cacheFile
stats = yield fs.statAsync cacheFile
# Cache is new
if req.headers['if-modified-since']? && (new Date(req.headers['if-modified-since']) >= stats.mtime)
res.writeHead 304,
'Server': 'Apache'
'Last-Modified': stats.mtime.toGMTString()
res.end()
# Cache is old
else
data = yield fs.readFileAsync cacheFile
res.writeHead 200,
'Server': 'Apache'
'Content-Length': data.length
'Content-Type': mime.lookup cacheFile
'Last-Modified': stats.mtime.toGMTString()
res.end data
# Enable retry for game api
else if isGameApi
success = false
for i in [0..retries]
break if success
try
# Emit request event to plugins
self.emit 'game.on.request', req.method, parsed.pathname, querystring.parse reqBody.toString()
# Create remote request
[response, body] = yield requestAsync resolve options
success = true
res.writeHead response.statusCode, response.headers
res.end body
# Emit response events to plugins
resolvedBody = yield resolveBody response.headers['content-encoding'], body
if !resolvedBody?
throw new Error('Empty Body')
if response.statusCode == 200
self.emit 'game.on.response', req.method, parsed.pathname, resolvedBody, querystring.parse reqBody.toString()
else if response.statusCode == 503
throw new Error('Service unavailable')
else
self.emit 'network.invalid.code', response.statusCode
catch e
error "Api failed: #{req.method} #{req.url} #{e.toString()}"
self.emit 'network.error.retry', i + 1 if i < retries
# Delay 3s for retry
yield Promise.delay(3000) unless success
else
[response, body] = yield requestAsync resolve options
res.writeHead response.statusCode, response.headers
res.end body
if parsed.pathname in ['/kcs/mainD2.swf', '/kcsapi/api_start2', '/kcsapi/api_get_member/basic']
self.emit 'game.start'
else if req.url.startsWith 'http://www.dmm.com/netgame/social/application/-/purchase/=/app_id=854854/payment_id='
self.emit 'game.payitem'
catch e
error "#{req.method} #{req.url} #{e.toString()}"
if req.url.startsWith('http://www.dmm.com/netgame/') or req.url.indexOf('/kcs/') != -1 or req.url.indexOf('/kcsapi/') != -1
self.emit 'network.error'
# HTTPS Requests
@server.on 'connect', (req, client, head) ->
delete req.headers['proxy-connection']
# Disable HTTP Keep-Alive
req.headers['connection'] = 'close'
remoteUrl = url.parse "https://#{req.url}"
remote = null
switch config.get 'proxy.use'
when 'socks5'
# Write data directly to SOCKS5 proxy
remote = socks.createConnection
socksHost: config.get 'proxy.socks5.host', '127.0.0.1'
socksPort: config.get 'proxy.socks5.port', 1080
host: remoteUrl.hostname
port: remoteUrl.port
remote.on 'connect', ->
client.write "HTTP/1.1 200 Connection Established\r\nConnection: close\r\n\r\n"
remote.write head
client.on 'data', (data) ->
remote.write data
remote.on 'data', (data) ->
client.write data
# Write data directly to Shadowsocks
when 'shadowsocks'
remote = socks.createConnection
socksHost: config.get '127.0.0.1'
socksPort: config.get 'proxy.shadowsocks.local.port', 1080
host: remoteUrl.hostname
port: remoteUrl.port
remote.on 'connect', ->
client.write "HTTP/1.1 200 Connection Established\r\nConnection: close\r\n\r\n"
remote.write head
client.on 'data', (data) ->
remote.write data
remote.on 'data', (data) ->
client.write data
# Write data directly to HTTP proxy
when 'http'
host = config.get 'proxy.http.host', '127.0.0.1'
port = config.get 'proxy.http.port', 8118
# Write header to http proxy
msg = "CONNECT #{remoteUrl.hostname}:#{remoteUrl.port} HTTP/#{req.httpVersion}\r\n"
for k, v of req.headers
msg += "#{caseNormalizer(k)}: #{v}\r\n"
msg += "\r\n"
remote = net.connect port, host, ->
remote.write msg
remote.write head
client.pipe remote
remote.pipe client
# Connect to remote directly
else
remote = net.connect remoteUrl.port, remoteUrl.hostname, ->
client.write "HTTP/1.1 200 Connection Established\r\nConnection: close\r\n\r\n"
remote.write head
client.pipe remote
remote.pipe client
client.on 'end', ->
remote.end()
remote.on 'end', ->
client.end()
client.on 'error', (e) ->
error e
remote.destroy()
remote.on 'error', (e) ->
error e
client.destroy()
client.on 'timeout', ->
client.destroy()
remote.destroy()
remote.on 'timeout', ->
client.destroy()
remote.destroy()
listenPort = config.get 'poi.port', 12450
@server.listen listenPort, ->
log "Proxy listening on #{listenPort}"
module.exports = new Proxy()
| 167418 | Promise = require 'bluebird'
async = Promise.coroutine
EventEmitter = require 'events'
url = require 'url'
net = require 'net'
http = require 'http'
querystring = require 'querystring'
_ = require 'underscore'
caseNormalizer = require 'header-case-normalizer'
fs = Promise.promisifyAll require 'fs-extra'
request = Promise.promisifyAll require 'request'
requestAsync = Promise.promisify request
shadowsocks = require 'shadowsocks'
mime = require 'mime'
socks = require 'socks5-client'
SocksHttpAgent = require 'socks5-http-client/lib/Agent'
config = require './config'
{log, warn, error, resolveBody, isStaticResource, findHack, findHackExPath, findCache, findCacheExPath} = require './utils'
# Network error retries
retries = config.get 'poi.proxy.retries', 0
resolve = (req) ->
switch config.get 'proxy.use'
# HTTP Request via SOCKS5 proxy
when 'socks5'
return _.extend req,
agentClass: SocksHttpAgent
agentOptions:
socksHost: config.get 'proxy.socks5.host', '127.0.0.1'
socksPort: config.get 'proxy.socks5.port', 1080
# HTTP Request via Shadowsocks
when 'shadowsocks'
return _.extend req,
agentClass: SocksHttpAgent
agentOptions:
socksHost: '127.0.0.1'
socksPort: config.get 'proxy.shadowsocks.local.port', 1080
# HTTP Request via HTTP proxy
when 'http'
host = config.get 'proxy.http.host', '127.0.0.1'
port = config.get 'proxy.http.port', 8118
return _.extend req,
proxy: "http://#{host}:#{port}"
# Directly
else
return req
class Proxy extends EventEmitter
constructor: ->
super()
@startShadowsocks()
@load()
# Start Shadowsocks local server
startShadowsocks: ->
return unless config.get('proxy.use') == 'shadowsocks'
host = config.get 'proxy.shadowsocks.server.host', '127.0.0.1'
port = config.get 'proxy.shadowsocks.server.port', 8388
local = config.get 'proxy.shadowsocks.local.port', 1080
password = config.get 'proxy.shadowsocks.password', '<PASSWORD>'
method = config.get 'proxy.shadowsocks.method', 'aes-256-cfb'
timeout = config.get 'proxy.shadowsocks.timeout', 600000
@sslocal = shadowsocks.createServer host, port, local, password, method, timeout, '127.0.0.1'
load: ->
self = @
# HTTP Requests
@server = http.createServer (req, res) ->
delete req.headers['proxy-connection']
# Disable HTTP Keep-Alive
req.headers['connection'] = 'close'
parsed = url.parse req.url
isGameApi = parsed.pathname.startsWith '/kcsapi'
cacheFile = null
if isStaticResource(parsed.pathname)
cacheFile = findHack(parsed.pathname) || findHackExPath(parsed.pathname) || findCache(parsed.pathname) || findCacheExPath(parsed.pathname)
reqBody = new Buffer(0)
# Get all request body
req.on 'data', (data) ->
reqBody = Buffer.concat [reqBody, data]
req.on 'end', async ->
try
options =
method: req.method
url: req.url
headers: req.headers
encoding: null
followRedirect: false
# Add body to request
if reqBody.length > 0
options = _.extend options,
body: reqBody
# Use cache file
if cacheFile
stats = yield fs.statAsync cacheFile
# Cache is new
if req.headers['if-modified-since']? && (new Date(req.headers['if-modified-since']) >= stats.mtime)
res.writeHead 304,
'Server': 'Apache'
'Last-Modified': stats.mtime.toGMTString()
res.end()
# Cache is old
else
data = yield fs.readFileAsync cacheFile
res.writeHead 200,
'Server': 'Apache'
'Content-Length': data.length
'Content-Type': mime.lookup cacheFile
'Last-Modified': stats.mtime.toGMTString()
res.end data
# Enable retry for game api
else if isGameApi
success = false
for i in [0..retries]
break if success
try
# Emit request event to plugins
self.emit 'game.on.request', req.method, parsed.pathname, querystring.parse reqBody.toString()
# Create remote request
[response, body] = yield requestAsync resolve options
success = true
res.writeHead response.statusCode, response.headers
res.end body
# Emit response events to plugins
resolvedBody = yield resolveBody response.headers['content-encoding'], body
if !resolvedBody?
throw new Error('Empty Body')
if response.statusCode == 200
self.emit 'game.on.response', req.method, parsed.pathname, resolvedBody, querystring.parse reqBody.toString()
else if response.statusCode == 503
throw new Error('Service unavailable')
else
self.emit 'network.invalid.code', response.statusCode
catch e
error "Api failed: #{req.method} #{req.url} #{e.toString()}"
self.emit 'network.error.retry', i + 1 if i < retries
# Delay 3s for retry
yield Promise.delay(3000) unless success
else
[response, body] = yield requestAsync resolve options
res.writeHead response.statusCode, response.headers
res.end body
if parsed.pathname in ['/kcs/mainD2.swf', '/kcsapi/api_start2', '/kcsapi/api_get_member/basic']
self.emit 'game.start'
else if req.url.startsWith 'http://www.dmm.com/netgame/social/application/-/purchase/=/app_id=854854/payment_id='
self.emit 'game.payitem'
catch e
error "#{req.method} #{req.url} #{e.toString()}"
if req.url.startsWith('http://www.dmm.com/netgame/') or req.url.indexOf('/kcs/') != -1 or req.url.indexOf('/kcsapi/') != -1
self.emit 'network.error'
# HTTPS Requests
@server.on 'connect', (req, client, head) ->
delete req.headers['proxy-connection']
# Disable HTTP Keep-Alive
req.headers['connection'] = 'close'
remoteUrl = url.parse "https://#{req.url}"
remote = null
switch config.get 'proxy.use'
when 'socks5'
# Write data directly to SOCKS5 proxy
remote = socks.createConnection
socksHost: config.get 'proxy.socks5.host', '127.0.0.1'
socksPort: config.get 'proxy.socks5.port', 1080
host: remoteUrl.hostname
port: remoteUrl.port
remote.on 'connect', ->
client.write "HTTP/1.1 200 Connection Established\r\nConnection: close\r\n\r\n"
remote.write head
client.on 'data', (data) ->
remote.write data
remote.on 'data', (data) ->
client.write data
# Write data directly to Shadowsocks
when 'shadowsocks'
remote = socks.createConnection
socksHost: config.get '127.0.0.1'
socksPort: config.get 'proxy.shadowsocks.local.port', 1080
host: remoteUrl.hostname
port: remoteUrl.port
remote.on 'connect', ->
client.write "HTTP/1.1 200 Connection Established\r\nConnection: close\r\n\r\n"
remote.write head
client.on 'data', (data) ->
remote.write data
remote.on 'data', (data) ->
client.write data
# Write data directly to HTTP proxy
when 'http'
host = config.get 'proxy.http.host', '127.0.0.1'
port = config.get 'proxy.http.port', 8118
# Write header to http proxy
msg = "CONNECT #{remoteUrl.hostname}:#{remoteUrl.port} HTTP/#{req.httpVersion}\r\n"
for k, v of req.headers
msg += "#{caseNormalizer(k)}: #{v}\r\n"
msg += "\r\n"
remote = net.connect port, host, ->
remote.write msg
remote.write head
client.pipe remote
remote.pipe client
# Connect to remote directly
else
remote = net.connect remoteUrl.port, remoteUrl.hostname, ->
client.write "HTTP/1.1 200 Connection Established\r\nConnection: close\r\n\r\n"
remote.write head
client.pipe remote
remote.pipe client
client.on 'end', ->
remote.end()
remote.on 'end', ->
client.end()
client.on 'error', (e) ->
error e
remote.destroy()
remote.on 'error', (e) ->
error e
client.destroy()
client.on 'timeout', ->
client.destroy()
remote.destroy()
remote.on 'timeout', ->
client.destroy()
remote.destroy()
listenPort = config.get 'poi.port', 12450
@server.listen listenPort, ->
log "Proxy listening on #{listenPort}"
module.exports = new Proxy()
| true | Promise = require 'bluebird'
async = Promise.coroutine
EventEmitter = require 'events'
url = require 'url'
net = require 'net'
http = require 'http'
querystring = require 'querystring'
_ = require 'underscore'
caseNormalizer = require 'header-case-normalizer'
fs = Promise.promisifyAll require 'fs-extra'
request = Promise.promisifyAll require 'request'
requestAsync = Promise.promisify request
shadowsocks = require 'shadowsocks'
mime = require 'mime'
socks = require 'socks5-client'
SocksHttpAgent = require 'socks5-http-client/lib/Agent'
config = require './config'
{log, warn, error, resolveBody, isStaticResource, findHack, findHackExPath, findCache, findCacheExPath} = require './utils'
# Network error retries
retries = config.get 'poi.proxy.retries', 0
resolve = (req) ->
switch config.get 'proxy.use'
# HTTP Request via SOCKS5 proxy
when 'socks5'
return _.extend req,
agentClass: SocksHttpAgent
agentOptions:
socksHost: config.get 'proxy.socks5.host', '127.0.0.1'
socksPort: config.get 'proxy.socks5.port', 1080
# HTTP Request via Shadowsocks
when 'shadowsocks'
return _.extend req,
agentClass: SocksHttpAgent
agentOptions:
socksHost: '127.0.0.1'
socksPort: config.get 'proxy.shadowsocks.local.port', 1080
# HTTP Request via HTTP proxy
when 'http'
host = config.get 'proxy.http.host', '127.0.0.1'
port = config.get 'proxy.http.port', 8118
return _.extend req,
proxy: "http://#{host}:#{port}"
# Directly
else
return req
class Proxy extends EventEmitter
constructor: ->
super()
@startShadowsocks()
@load()
# Start Shadowsocks local server
startShadowsocks: ->
return unless config.get('proxy.use') == 'shadowsocks'
host = config.get 'proxy.shadowsocks.server.host', '127.0.0.1'
port = config.get 'proxy.shadowsocks.server.port', 8388
local = config.get 'proxy.shadowsocks.local.port', 1080
password = config.get 'proxy.shadowsocks.password', 'PI:PASSWORD:<PASSWORD>END_PI'
method = config.get 'proxy.shadowsocks.method', 'aes-256-cfb'
timeout = config.get 'proxy.shadowsocks.timeout', 600000
@sslocal = shadowsocks.createServer host, port, local, password, method, timeout, '127.0.0.1'
load: ->
self = @
# HTTP Requests
@server = http.createServer (req, res) ->
delete req.headers['proxy-connection']
# Disable HTTP Keep-Alive
req.headers['connection'] = 'close'
parsed = url.parse req.url
isGameApi = parsed.pathname.startsWith '/kcsapi'
cacheFile = null
if isStaticResource(parsed.pathname)
cacheFile = findHack(parsed.pathname) || findHackExPath(parsed.pathname) || findCache(parsed.pathname) || findCacheExPath(parsed.pathname)
reqBody = new Buffer(0)
# Get all request body
req.on 'data', (data) ->
reqBody = Buffer.concat [reqBody, data]
req.on 'end', async ->
try
options =
method: req.method
url: req.url
headers: req.headers
encoding: null
followRedirect: false
# Add body to request
if reqBody.length > 0
options = _.extend options,
body: reqBody
# Use cache file
if cacheFile
stats = yield fs.statAsync cacheFile
# Cache is new
if req.headers['if-modified-since']? && (new Date(req.headers['if-modified-since']) >= stats.mtime)
res.writeHead 304,
'Server': 'Apache'
'Last-Modified': stats.mtime.toGMTString()
res.end()
# Cache is old
else
data = yield fs.readFileAsync cacheFile
res.writeHead 200,
'Server': 'Apache'
'Content-Length': data.length
'Content-Type': mime.lookup cacheFile
'Last-Modified': stats.mtime.toGMTString()
res.end data
# Enable retry for game api
else if isGameApi
success = false
for i in [0..retries]
break if success
try
# Emit request event to plugins
self.emit 'game.on.request', req.method, parsed.pathname, querystring.parse reqBody.toString()
# Create remote request
[response, body] = yield requestAsync resolve options
success = true
res.writeHead response.statusCode, response.headers
res.end body
# Emit response events to plugins
resolvedBody = yield resolveBody response.headers['content-encoding'], body
if !resolvedBody?
throw new Error('Empty Body')
if response.statusCode == 200
self.emit 'game.on.response', req.method, parsed.pathname, resolvedBody, querystring.parse reqBody.toString()
else if response.statusCode == 503
throw new Error('Service unavailable')
else
self.emit 'network.invalid.code', response.statusCode
catch e
error "Api failed: #{req.method} #{req.url} #{e.toString()}"
self.emit 'network.error.retry', i + 1 if i < retries
# Delay 3s for retry
yield Promise.delay(3000) unless success
else
[response, body] = yield requestAsync resolve options
res.writeHead response.statusCode, response.headers
res.end body
if parsed.pathname in ['/kcs/mainD2.swf', '/kcsapi/api_start2', '/kcsapi/api_get_member/basic']
self.emit 'game.start'
else if req.url.startsWith 'http://www.dmm.com/netgame/social/application/-/purchase/=/app_id=854854/payment_id='
self.emit 'game.payitem'
catch e
error "#{req.method} #{req.url} #{e.toString()}"
if req.url.startsWith('http://www.dmm.com/netgame/') or req.url.indexOf('/kcs/') != -1 or req.url.indexOf('/kcsapi/') != -1
self.emit 'network.error'
# HTTPS Requests
@server.on 'connect', (req, client, head) ->
delete req.headers['proxy-connection']
# Disable HTTP Keep-Alive
req.headers['connection'] = 'close'
remoteUrl = url.parse "https://#{req.url}"
remote = null
switch config.get 'proxy.use'
when 'socks5'
# Write data directly to SOCKS5 proxy
remote = socks.createConnection
socksHost: config.get 'proxy.socks5.host', '127.0.0.1'
socksPort: config.get 'proxy.socks5.port', 1080
host: remoteUrl.hostname
port: remoteUrl.port
remote.on 'connect', ->
client.write "HTTP/1.1 200 Connection Established\r\nConnection: close\r\n\r\n"
remote.write head
client.on 'data', (data) ->
remote.write data
remote.on 'data', (data) ->
client.write data
# Write data directly to Shadowsocks
when 'shadowsocks'
remote = socks.createConnection
socksHost: config.get '127.0.0.1'
socksPort: config.get 'proxy.shadowsocks.local.port', 1080
host: remoteUrl.hostname
port: remoteUrl.port
remote.on 'connect', ->
client.write "HTTP/1.1 200 Connection Established\r\nConnection: close\r\n\r\n"
remote.write head
client.on 'data', (data) ->
remote.write data
remote.on 'data', (data) ->
client.write data
# Write data directly to HTTP proxy
when 'http'
host = config.get 'proxy.http.host', '127.0.0.1'
port = config.get 'proxy.http.port', 8118
# Write header to http proxy
msg = "CONNECT #{remoteUrl.hostname}:#{remoteUrl.port} HTTP/#{req.httpVersion}\r\n"
for k, v of req.headers
msg += "#{caseNormalizer(k)}: #{v}\r\n"
msg += "\r\n"
remote = net.connect port, host, ->
remote.write msg
remote.write head
client.pipe remote
remote.pipe client
# Connect to remote directly
else
remote = net.connect remoteUrl.port, remoteUrl.hostname, ->
client.write "HTTP/1.1 200 Connection Established\r\nConnection: close\r\n\r\n"
remote.write head
client.pipe remote
remote.pipe client
client.on 'end', ->
remote.end()
remote.on 'end', ->
client.end()
client.on 'error', (e) ->
error e
remote.destroy()
remote.on 'error', (e) ->
error e
client.destroy()
client.on 'timeout', ->
client.destroy()
remote.destroy()
remote.on 'timeout', ->
client.destroy()
remote.destroy()
listenPort = config.get 'poi.port', 12450
@server.listen listenPort, ->
log "Proxy listening on #{listenPort}"
module.exports = new Proxy()
|
[
{
"context": "inimaps for WXTiles.\n# Based largely on minimap by Jan Pieter Waagmeester <jieter@jieter.nl>\n\n_cloneLayer = (layer) ->\n\topt",
"end": 124,
"score": 0.9999028444290161,
"start": 102,
"tag": "NAME",
"value": "Jan Pieter Waagmeester"
},
{
"context": "sed largely on minimap by Jan Pieter Waagmeester <jieter@jieter.nl>\n\n_cloneLayer = (layer) ->\n\toptions = layer.optio",
"end": 142,
"score": 0.9999287724494934,
"start": 126,
"tag": "EMAIL",
"value": "jieter@jieter.nl"
},
{
"context": "ound for Firefox android issue https://github.com/Leaflet/Leaflet/issues/2033\n\t\t\tL.DomEvent.on form, 'click",
"end": 4757,
"score": 0.9984477162361145,
"start": 4750,
"tag": "USERNAME",
"value": "Leaflet"
}
] | src/wxtiles.leaflet.minimap.coffee | metocean/wxserver-api | 3 | # # WXTilesMinimap
#
# Layers control with synced minimaps for WXTiles.
# Based largely on minimap by Jan Pieter Waagmeester <jieter@jieter.nl>
_cloneLayer = (layer) ->
options = layer.options
if layer instanceof L.WXTileLayer
result = L.wxTileLayer layer._config, options
result.setField layer._field
result.setKey layer._key
return result
return L.tileLayer(layer._url, options) if layer instanceof L.TileLayer
return L.imageOverlay(layer._url, layer._bounds, options) if layer instanceof L.ImageOverlay
return L.polygon(layer.getLatLngs(), options) if layer instanceof L.Polygon or layer instanceof L.Rectangle
return L.marker(layer.getLatLng(), options) if layer instanceof L.Marker
return L.circleMarker(layer.getLatLng(), options) if layer instanceof L.circleMarker
return L.polyline(layer.getLatLngs(), options) if layer instanceof L.Polyline
return L.polyline(layer.getLatLngs(), options) if layer instanceof L.MultiPolyline
return L.MultiPolygon(layer.getLatLngs(), options) if layer instanceof L.MultiPolygon
return L.circle(layer.getLatLng(), layer.getRadius(), options) if layer instanceof L.Circle
return L.geoJson(layer.toGeoJSON(), options) if layer instanceof L.GeoJSON
# no interaction on minimaps, add FeatureGroup as LayerGroup
if layer instanceof L.LayerGroup or layer instanceof L.FeatureGroup
layergroup = L.layerGroup()
layer.eachLayer (inner) ->
layergroup.addLayer _cloneLayer inner
layergroup
L.Control.Layers.WXTilesMinimap = L.Control.extend
options:
collapsed: yes
autoZIndex: yes
position: 'topright'
topPadding: 10
bottomPadding: 40
backgroundLayer: L.tileLayer 'http://a{s}.acetate.geoiq.com/tiles/acetate-base/{z}/{x}/{y}.png',
attribution: '©2012 Esri & Stamen, Data from OSM and Natural Earth'
subdomains: '0123'
minZoom: 2
maxZoom: 18
initialize: (layers, options) ->
L.setOptions @, options
@_layers = {}
@_lastZIndex = 0
@_handlingClick = no
for i of layers
@_addLayer layers[i], i
onAdd: (map) ->
@_initLayout()
@_update()
map
.on 'layeradd', @_onLayerChange, @
.on 'layerremove', @_onLayerChange, @
@_container
onRemove: (map) ->
map
.off 'layeradd', @_onLayerChange, @
.off 'layerremove', @_onLayerChange, @
addLayer: (layer, name) ->
@_addLayer layer, name
@_update()
@
removeLayer: (layer) ->
id = L.stamp layer
delete @_layers[id]
@_update()
@
_addLayer: (layer, name) ->
id = L.stamp layer
@_layers[id] =
layer: layer
name: name
if @options.autoZIndex and layer.setZIndex
@_lastZIndex++
layer.setZIndex @_lastZIndex
_onLayerChange: (e) ->
obj = @_layers[L.stamp(e.layer)]
return unless obj
@_update() unless @_handlingClick
type = (if e.type is 'layeradd' then 'overlayadd' else 'overlayremove')
@_map.fire type, obj if type
if obj.layer instanceof L.WXTileLayer
@_map.fire 'wxfieldchange', obj.layer.getField()
else
@_map.fire 'wxfieldremove'
filter: (string) ->
string = string.trim()
layerLabels = @_container.querySelectorAll 'label'
i = 0
while i < layerLabels.length
layerLabel = layerLabels[i]
if string isnt '' and layerLabel._layerName.indexOf(string) is -1
L.DomUtil.addClass layerLabel, 'leaflet-minimap-hidden'
else
L.DomUtil.removeClass layerLabel, 'leaflet-minimap-hidden'
i++
@_onListScroll()
isCollapsed: ->
not L.DomUtil.hasClass @_container, 'leaflet-control-layers-expanded'
_expand: (e) ->
if e? and e.preventDefault?
e.preventDefault()
L.DomUtil.addClass @_container, 'leaflet-control-layers-expanded'
@_onListScroll()
_collapse: ->
@_container.className = @_container.className.replace ' leaflet-control-layers-expanded', ''
_initLayout: ->
className = 'leaflet-control-layers'
container = @_container = L.DomUtil.create 'div', className
#Makes this work on IE10 Touch devices by stopping it from firing a mouseout event when the touch is released
container.setAttribute 'aria-haspopup', yes
unless L.Browser.touch
L.DomEvent.disableClickPropagation(container).disableScrollPropagation container
else
L.DomEvent.on container, 'click', L.DomEvent.stopPropagation
form = @_form = L.DomUtil.create('form', className + '-list')
if @options.collapsed
#L.DomEvent
# .on(container, 'mouseover', @_expand, @)
# .on container, 'mouseout', @_collapse, @ unless L.Browser.android
link = @_layersLink = L.DomUtil.create('a', className + '-toggle', container)
link.href = '#'
link.title = 'Layers'
if L.Browser.touch
L.DomEvent
.on(link, 'click', L.DomEvent.stop)
.on link, 'click', @_expand, @
else
L.DomEvent.on link, 'click', @_expand, @
#Work around for Firefox android issue https://github.com/Leaflet/Leaflet/issues/2033
L.DomEvent.on form, 'click', (->
setTimeout L.bind(@_onInputClick, @), 0
return
), @
@_map.on 'click', @_collapse, @
# TODO keyboard accessibility
else
@_expand()
@_layerList = L.DomUtil.create('div', className + '-layers', form)
container.appendChild form
L.DomUtil.addClass @_container, 'leaflet-control-layers-minimap'
L.DomEvent.on @_container, 'scroll', @_onListScroll, @
_update: ->
if @_container
@_layerList.innerHTML = ""
@_addItem layer for _, layer of @_layers
@_map.on 'resize', @_onResize, @
@_onResize()
@_map.whenReady @_onListScroll, @
# IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
_createRadioElement: (name, checked) ->
radioHtml = "<input type=\"radio\" class=\"leaflet-control-layers-selector\" name=\"" + name + "\""
radioHtml += " checked=\"checked\"" if checked
radioHtml += "/>"
radioFragment = document.createElement 'div'
radioFragment.innerHTML = radioHtml
radioFragment.firstChild
_addItem: (obj) ->
container = @_layerList
label = L.DomUtil.create 'label', 'leaflet-minimap-container', container
label._layerName = obj.name
checked = @_map.hasLayer obj.layer
@_createMinimap L.DomUtil.create('div', 'leaflet-minimap', label), obj.layer
span = L.DomUtil.create 'span', 'leaflet-minimap-label', label
input = @_createRadioElement 'leaflet-control-layers-selector', checked
input.layerId = L.stamp obj.layer
span.appendChild input
L.DomEvent.on label, 'click', @_onInputClick, @
name = L.DomUtil.create 'span', '', span
name.innerHTML = ' ' + obj.name
_onResize: ->
mapHeight = @_map.getContainer().clientHeight
controlHeight = @_container.clientHeight
@_container.style.overflowY = 'scroll' if controlHeight > mapHeight - @options.bottomPadding
@_container.style.maxHeight = (mapHeight - @options.bottomPadding - @options.topPadding) + 'px'
_onListScroll: ->
minimaps = document.querySelectorAll "label[class='leaflet-minimap-container']"
return if minimaps.length is 0
first = undefined
last = undefined
if @isCollapsed()
first = last = -1
else
minimapHeight = minimaps.item(0).clientHeight
container = @_container
listHeight = container.clientHeight
scrollTop = container.scrollTop
first = Math.floor scrollTop / minimapHeight
last = Math.ceil((scrollTop + listHeight) / minimapHeight)
i = 0
while i < minimaps.length
minimap = minimaps[i].childNodes.item 0
map = minimap._miniMap
layer = map._layer
continue unless layer
if i >= first and i <= last
layer.addTo map unless map.hasLayer layer
map.invalidateSize()
else
map.removeLayer layer if map.hasLayer layer
++i
_onInputClick: ->
i = undefined
input = undefined
obj = undefined
inputs = @_form.getElementsByTagName 'input'
inputsLen = inputs.length
@_handlingClick = yes
i = 0
while i < inputsLen
input = inputs[i]
obj = @_layers[input.layerId]
if input.checked and not @_map.hasLayer(obj.layer)
@_map.addLayer obj.layer
else @_map.removeLayer obj.layer if not input.checked and @_map.hasLayer(obj.layer)
i++
@_handlingClick = no
@_refocusOnMap()
_createMinimap: (mapContainer, originalLayer) ->
minimap = mapContainer._miniMap = L.map mapContainer,
attributionControl: no
zoomControl: no
# disable interaction.
dragging: no
touchZoom: no
doubleClickZoom: no
scrollWheelZoom: no
boxZoom: no
keyboard: no
tap: no
# create tilelayer, but do not add it to the map yet.
minimap._layer = L.layerGroup [
_cloneLayer @options.backgroundLayer
_cloneLayer originalLayer
]
map = @_map
map.whenReady ->
minimap.setView map.getCenter(), map.getZoom()
map.sync minimap
L.control.layers.wxTilesMinimap = (layers, options) ->
new L.Control.Layers.WXTilesMinimap(layers, options) | 83684 | # # WXTilesMinimap
#
# Layers control with synced minimaps for WXTiles.
# Based largely on minimap by <NAME> <<EMAIL>>
_cloneLayer = (layer) ->
options = layer.options
if layer instanceof L.WXTileLayer
result = L.wxTileLayer layer._config, options
result.setField layer._field
result.setKey layer._key
return result
return L.tileLayer(layer._url, options) if layer instanceof L.TileLayer
return L.imageOverlay(layer._url, layer._bounds, options) if layer instanceof L.ImageOverlay
return L.polygon(layer.getLatLngs(), options) if layer instanceof L.Polygon or layer instanceof L.Rectangle
return L.marker(layer.getLatLng(), options) if layer instanceof L.Marker
return L.circleMarker(layer.getLatLng(), options) if layer instanceof L.circleMarker
return L.polyline(layer.getLatLngs(), options) if layer instanceof L.Polyline
return L.polyline(layer.getLatLngs(), options) if layer instanceof L.MultiPolyline
return L.MultiPolygon(layer.getLatLngs(), options) if layer instanceof L.MultiPolygon
return L.circle(layer.getLatLng(), layer.getRadius(), options) if layer instanceof L.Circle
return L.geoJson(layer.toGeoJSON(), options) if layer instanceof L.GeoJSON
# no interaction on minimaps, add FeatureGroup as LayerGroup
if layer instanceof L.LayerGroup or layer instanceof L.FeatureGroup
layergroup = L.layerGroup()
layer.eachLayer (inner) ->
layergroup.addLayer _cloneLayer inner
layergroup
L.Control.Layers.WXTilesMinimap = L.Control.extend
options:
collapsed: yes
autoZIndex: yes
position: 'topright'
topPadding: 10
bottomPadding: 40
backgroundLayer: L.tileLayer 'http://a{s}.acetate.geoiq.com/tiles/acetate-base/{z}/{x}/{y}.png',
attribution: '©2012 Esri & Stamen, Data from OSM and Natural Earth'
subdomains: '0123'
minZoom: 2
maxZoom: 18
initialize: (layers, options) ->
L.setOptions @, options
@_layers = {}
@_lastZIndex = 0
@_handlingClick = no
for i of layers
@_addLayer layers[i], i
onAdd: (map) ->
@_initLayout()
@_update()
map
.on 'layeradd', @_onLayerChange, @
.on 'layerremove', @_onLayerChange, @
@_container
onRemove: (map) ->
map
.off 'layeradd', @_onLayerChange, @
.off 'layerremove', @_onLayerChange, @
addLayer: (layer, name) ->
@_addLayer layer, name
@_update()
@
removeLayer: (layer) ->
id = L.stamp layer
delete @_layers[id]
@_update()
@
_addLayer: (layer, name) ->
id = L.stamp layer
@_layers[id] =
layer: layer
name: name
if @options.autoZIndex and layer.setZIndex
@_lastZIndex++
layer.setZIndex @_lastZIndex
_onLayerChange: (e) ->
obj = @_layers[L.stamp(e.layer)]
return unless obj
@_update() unless @_handlingClick
type = (if e.type is 'layeradd' then 'overlayadd' else 'overlayremove')
@_map.fire type, obj if type
if obj.layer instanceof L.WXTileLayer
@_map.fire 'wxfieldchange', obj.layer.getField()
else
@_map.fire 'wxfieldremove'
filter: (string) ->
string = string.trim()
layerLabels = @_container.querySelectorAll 'label'
i = 0
while i < layerLabels.length
layerLabel = layerLabels[i]
if string isnt '' and layerLabel._layerName.indexOf(string) is -1
L.DomUtil.addClass layerLabel, 'leaflet-minimap-hidden'
else
L.DomUtil.removeClass layerLabel, 'leaflet-minimap-hidden'
i++
@_onListScroll()
isCollapsed: ->
not L.DomUtil.hasClass @_container, 'leaflet-control-layers-expanded'
_expand: (e) ->
if e? and e.preventDefault?
e.preventDefault()
L.DomUtil.addClass @_container, 'leaflet-control-layers-expanded'
@_onListScroll()
_collapse: ->
@_container.className = @_container.className.replace ' leaflet-control-layers-expanded', ''
_initLayout: ->
className = 'leaflet-control-layers'
container = @_container = L.DomUtil.create 'div', className
#Makes this work on IE10 Touch devices by stopping it from firing a mouseout event when the touch is released
container.setAttribute 'aria-haspopup', yes
unless L.Browser.touch
L.DomEvent.disableClickPropagation(container).disableScrollPropagation container
else
L.DomEvent.on container, 'click', L.DomEvent.stopPropagation
form = @_form = L.DomUtil.create('form', className + '-list')
if @options.collapsed
#L.DomEvent
# .on(container, 'mouseover', @_expand, @)
# .on container, 'mouseout', @_collapse, @ unless L.Browser.android
link = @_layersLink = L.DomUtil.create('a', className + '-toggle', container)
link.href = '#'
link.title = 'Layers'
if L.Browser.touch
L.DomEvent
.on(link, 'click', L.DomEvent.stop)
.on link, 'click', @_expand, @
else
L.DomEvent.on link, 'click', @_expand, @
#Work around for Firefox android issue https://github.com/Leaflet/Leaflet/issues/2033
L.DomEvent.on form, 'click', (->
setTimeout L.bind(@_onInputClick, @), 0
return
), @
@_map.on 'click', @_collapse, @
# TODO keyboard accessibility
else
@_expand()
@_layerList = L.DomUtil.create('div', className + '-layers', form)
container.appendChild form
L.DomUtil.addClass @_container, 'leaflet-control-layers-minimap'
L.DomEvent.on @_container, 'scroll', @_onListScroll, @
_update: ->
if @_container
@_layerList.innerHTML = ""
@_addItem layer for _, layer of @_layers
@_map.on 'resize', @_onResize, @
@_onResize()
@_map.whenReady @_onListScroll, @
# IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
_createRadioElement: (name, checked) ->
radioHtml = "<input type=\"radio\" class=\"leaflet-control-layers-selector\" name=\"" + name + "\""
radioHtml += " checked=\"checked\"" if checked
radioHtml += "/>"
radioFragment = document.createElement 'div'
radioFragment.innerHTML = radioHtml
radioFragment.firstChild
_addItem: (obj) ->
container = @_layerList
label = L.DomUtil.create 'label', 'leaflet-minimap-container', container
label._layerName = obj.name
checked = @_map.hasLayer obj.layer
@_createMinimap L.DomUtil.create('div', 'leaflet-minimap', label), obj.layer
span = L.DomUtil.create 'span', 'leaflet-minimap-label', label
input = @_createRadioElement 'leaflet-control-layers-selector', checked
input.layerId = L.stamp obj.layer
span.appendChild input
L.DomEvent.on label, 'click', @_onInputClick, @
name = L.DomUtil.create 'span', '', span
name.innerHTML = ' ' + obj.name
_onResize: ->
mapHeight = @_map.getContainer().clientHeight
controlHeight = @_container.clientHeight
@_container.style.overflowY = 'scroll' if controlHeight > mapHeight - @options.bottomPadding
@_container.style.maxHeight = (mapHeight - @options.bottomPadding - @options.topPadding) + 'px'
_onListScroll: ->
minimaps = document.querySelectorAll "label[class='leaflet-minimap-container']"
return if minimaps.length is 0
first = undefined
last = undefined
if @isCollapsed()
first = last = -1
else
minimapHeight = minimaps.item(0).clientHeight
container = @_container
listHeight = container.clientHeight
scrollTop = container.scrollTop
first = Math.floor scrollTop / minimapHeight
last = Math.ceil((scrollTop + listHeight) / minimapHeight)
i = 0
while i < minimaps.length
minimap = minimaps[i].childNodes.item 0
map = minimap._miniMap
layer = map._layer
continue unless layer
if i >= first and i <= last
layer.addTo map unless map.hasLayer layer
map.invalidateSize()
else
map.removeLayer layer if map.hasLayer layer
++i
_onInputClick: ->
i = undefined
input = undefined
obj = undefined
inputs = @_form.getElementsByTagName 'input'
inputsLen = inputs.length
@_handlingClick = yes
i = 0
while i < inputsLen
input = inputs[i]
obj = @_layers[input.layerId]
if input.checked and not @_map.hasLayer(obj.layer)
@_map.addLayer obj.layer
else @_map.removeLayer obj.layer if not input.checked and @_map.hasLayer(obj.layer)
i++
@_handlingClick = no
@_refocusOnMap()
_createMinimap: (mapContainer, originalLayer) ->
minimap = mapContainer._miniMap = L.map mapContainer,
attributionControl: no
zoomControl: no
# disable interaction.
dragging: no
touchZoom: no
doubleClickZoom: no
scrollWheelZoom: no
boxZoom: no
keyboard: no
tap: no
# create tilelayer, but do not add it to the map yet.
minimap._layer = L.layerGroup [
_cloneLayer @options.backgroundLayer
_cloneLayer originalLayer
]
map = @_map
map.whenReady ->
minimap.setView map.getCenter(), map.getZoom()
map.sync minimap
L.control.layers.wxTilesMinimap = (layers, options) ->
new L.Control.Layers.WXTilesMinimap(layers, options) | true | # # WXTilesMinimap
#
# Layers control with synced minimaps for WXTiles.
# Based largely on minimap by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
_cloneLayer = (layer) ->
options = layer.options
if layer instanceof L.WXTileLayer
result = L.wxTileLayer layer._config, options
result.setField layer._field
result.setKey layer._key
return result
return L.tileLayer(layer._url, options) if layer instanceof L.TileLayer
return L.imageOverlay(layer._url, layer._bounds, options) if layer instanceof L.ImageOverlay
return L.polygon(layer.getLatLngs(), options) if layer instanceof L.Polygon or layer instanceof L.Rectangle
return L.marker(layer.getLatLng(), options) if layer instanceof L.Marker
return L.circleMarker(layer.getLatLng(), options) if layer instanceof L.circleMarker
return L.polyline(layer.getLatLngs(), options) if layer instanceof L.Polyline
return L.polyline(layer.getLatLngs(), options) if layer instanceof L.MultiPolyline
return L.MultiPolygon(layer.getLatLngs(), options) if layer instanceof L.MultiPolygon
return L.circle(layer.getLatLng(), layer.getRadius(), options) if layer instanceof L.Circle
return L.geoJson(layer.toGeoJSON(), options) if layer instanceof L.GeoJSON
# no interaction on minimaps, add FeatureGroup as LayerGroup
if layer instanceof L.LayerGroup or layer instanceof L.FeatureGroup
layergroup = L.layerGroup()
layer.eachLayer (inner) ->
layergroup.addLayer _cloneLayer inner
layergroup
L.Control.Layers.WXTilesMinimap = L.Control.extend
options:
collapsed: yes
autoZIndex: yes
position: 'topright'
topPadding: 10
bottomPadding: 40
backgroundLayer: L.tileLayer 'http://a{s}.acetate.geoiq.com/tiles/acetate-base/{z}/{x}/{y}.png',
attribution: '©2012 Esri & Stamen, Data from OSM and Natural Earth'
subdomains: '0123'
minZoom: 2
maxZoom: 18
initialize: (layers, options) ->
L.setOptions @, options
@_layers = {}
@_lastZIndex = 0
@_handlingClick = no
for i of layers
@_addLayer layers[i], i
onAdd: (map) ->
@_initLayout()
@_update()
map
.on 'layeradd', @_onLayerChange, @
.on 'layerremove', @_onLayerChange, @
@_container
onRemove: (map) ->
map
.off 'layeradd', @_onLayerChange, @
.off 'layerremove', @_onLayerChange, @
addLayer: (layer, name) ->
@_addLayer layer, name
@_update()
@
removeLayer: (layer) ->
id = L.stamp layer
delete @_layers[id]
@_update()
@
_addLayer: (layer, name) ->
id = L.stamp layer
@_layers[id] =
layer: layer
name: name
if @options.autoZIndex and layer.setZIndex
@_lastZIndex++
layer.setZIndex @_lastZIndex
_onLayerChange: (e) ->
obj = @_layers[L.stamp(e.layer)]
return unless obj
@_update() unless @_handlingClick
type = (if e.type is 'layeradd' then 'overlayadd' else 'overlayremove')
@_map.fire type, obj if type
if obj.layer instanceof L.WXTileLayer
@_map.fire 'wxfieldchange', obj.layer.getField()
else
@_map.fire 'wxfieldremove'
filter: (string) ->
string = string.trim()
layerLabels = @_container.querySelectorAll 'label'
i = 0
while i < layerLabels.length
layerLabel = layerLabels[i]
if string isnt '' and layerLabel._layerName.indexOf(string) is -1
L.DomUtil.addClass layerLabel, 'leaflet-minimap-hidden'
else
L.DomUtil.removeClass layerLabel, 'leaflet-minimap-hidden'
i++
@_onListScroll()
isCollapsed: ->
not L.DomUtil.hasClass @_container, 'leaflet-control-layers-expanded'
_expand: (e) ->
if e? and e.preventDefault?
e.preventDefault()
L.DomUtil.addClass @_container, 'leaflet-control-layers-expanded'
@_onListScroll()
_collapse: ->
@_container.className = @_container.className.replace ' leaflet-control-layers-expanded', ''
_initLayout: ->
className = 'leaflet-control-layers'
container = @_container = L.DomUtil.create 'div', className
#Makes this work on IE10 Touch devices by stopping it from firing a mouseout event when the touch is released
container.setAttribute 'aria-haspopup', yes
unless L.Browser.touch
L.DomEvent.disableClickPropagation(container).disableScrollPropagation container
else
L.DomEvent.on container, 'click', L.DomEvent.stopPropagation
form = @_form = L.DomUtil.create('form', className + '-list')
if @options.collapsed
#L.DomEvent
# .on(container, 'mouseover', @_expand, @)
# .on container, 'mouseout', @_collapse, @ unless L.Browser.android
link = @_layersLink = L.DomUtil.create('a', className + '-toggle', container)
link.href = '#'
link.title = 'Layers'
if L.Browser.touch
L.DomEvent
.on(link, 'click', L.DomEvent.stop)
.on link, 'click', @_expand, @
else
L.DomEvent.on link, 'click', @_expand, @
#Work around for Firefox android issue https://github.com/Leaflet/Leaflet/issues/2033
L.DomEvent.on form, 'click', (->
setTimeout L.bind(@_onInputClick, @), 0
return
), @
@_map.on 'click', @_collapse, @
# TODO keyboard accessibility
else
@_expand()
@_layerList = L.DomUtil.create('div', className + '-layers', form)
container.appendChild form
L.DomUtil.addClass @_container, 'leaflet-control-layers-minimap'
L.DomEvent.on @_container, 'scroll', @_onListScroll, @
_update: ->
if @_container
@_layerList.innerHTML = ""
@_addItem layer for _, layer of @_layers
@_map.on 'resize', @_onResize, @
@_onResize()
@_map.whenReady @_onListScroll, @
# IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
_createRadioElement: (name, checked) ->
radioHtml = "<input type=\"radio\" class=\"leaflet-control-layers-selector\" name=\"" + name + "\""
radioHtml += " checked=\"checked\"" if checked
radioHtml += "/>"
radioFragment = document.createElement 'div'
radioFragment.innerHTML = radioHtml
radioFragment.firstChild
_addItem: (obj) ->
container = @_layerList
label = L.DomUtil.create 'label', 'leaflet-minimap-container', container
label._layerName = obj.name
checked = @_map.hasLayer obj.layer
@_createMinimap L.DomUtil.create('div', 'leaflet-minimap', label), obj.layer
span = L.DomUtil.create 'span', 'leaflet-minimap-label', label
input = @_createRadioElement 'leaflet-control-layers-selector', checked
input.layerId = L.stamp obj.layer
span.appendChild input
L.DomEvent.on label, 'click', @_onInputClick, @
name = L.DomUtil.create 'span', '', span
name.innerHTML = ' ' + obj.name
_onResize: ->
mapHeight = @_map.getContainer().clientHeight
controlHeight = @_container.clientHeight
@_container.style.overflowY = 'scroll' if controlHeight > mapHeight - @options.bottomPadding
@_container.style.maxHeight = (mapHeight - @options.bottomPadding - @options.topPadding) + 'px'
_onListScroll: ->
minimaps = document.querySelectorAll "label[class='leaflet-minimap-container']"
return if minimaps.length is 0
first = undefined
last = undefined
if @isCollapsed()
first = last = -1
else
minimapHeight = minimaps.item(0).clientHeight
container = @_container
listHeight = container.clientHeight
scrollTop = container.scrollTop
first = Math.floor scrollTop / minimapHeight
last = Math.ceil((scrollTop + listHeight) / minimapHeight)
i = 0
while i < minimaps.length
minimap = minimaps[i].childNodes.item 0
map = minimap._miniMap
layer = map._layer
continue unless layer
if i >= first and i <= last
layer.addTo map unless map.hasLayer layer
map.invalidateSize()
else
map.removeLayer layer if map.hasLayer layer
++i
_onInputClick: ->
i = undefined
input = undefined
obj = undefined
inputs = @_form.getElementsByTagName 'input'
inputsLen = inputs.length
@_handlingClick = yes
i = 0
while i < inputsLen
input = inputs[i]
obj = @_layers[input.layerId]
if input.checked and not @_map.hasLayer(obj.layer)
@_map.addLayer obj.layer
else @_map.removeLayer obj.layer if not input.checked and @_map.hasLayer(obj.layer)
i++
@_handlingClick = no
@_refocusOnMap()
_createMinimap: (mapContainer, originalLayer) ->
minimap = mapContainer._miniMap = L.map mapContainer,
attributionControl: no
zoomControl: no
# disable interaction.
dragging: no
touchZoom: no
doubleClickZoom: no
scrollWheelZoom: no
boxZoom: no
keyboard: no
tap: no
# create tilelayer, but do not add it to the map yet.
minimap._layer = L.layerGroup [
_cloneLayer @options.backgroundLayer
_cloneLayer originalLayer
]
map = @_map
map.whenReady ->
minimap.setView map.getCenter(), map.getZoom()
map.sync minimap
L.control.layers.wxTilesMinimap = (layers, options) ->
new L.Control.Layers.WXTilesMinimap(layers, options) |
[
{
"context": "ink-shortener'\n redis: 'localhost'\n redis_key: 'link-shortener'\n\n memcached: 'localhost'\n\n cookie_session: {\n ",
"end": 141,
"score": 0.9800238609313965,
"start": 127,
"tag": "KEY",
"value": "link-shortener"
},
{
"context": "ookie_session: {\n enabled: no\n secret_key: 'MY_UNIQUE_ENCRYPTION_KEY'\n }\n\n allow_http_method_override: on\n allow_mo",
"end": 247,
"score": 0.9086469411849976,
"start": 223,
"tag": "KEY",
"value": "MY_UNIQUE_ENCRYPTION_KEY"
},
{
"context": "eloper: {\n show_error_stack: on\n debug_ip: '107.181.69.70'\n }\n}\n\n",
"end": 413,
"score": 0.9997198581695557,
"start": 400,
"tag": "IP_ADDRESS",
"value": "107.181.69.70"
}
] | conf.iced | tosadvisor/link-shortener | 0 | module.exports = conf = {
cluster: off
port: 10001
mongo: 'localhost/link-shortener'
redis: 'localhost'
redis_key: 'link-shortener'
memcached: 'localhost'
cookie_session: {
enabled: no
secret_key: 'MY_UNIQUE_ENCRYPTION_KEY'
}
allow_http_method_override: on
allow_model_exposure: on
allow_underscore_routes: on
developer: {
show_error_stack: on
debug_ip: '107.181.69.70'
}
}
| 98009 | module.exports = conf = {
cluster: off
port: 10001
mongo: 'localhost/link-shortener'
redis: 'localhost'
redis_key: '<KEY>'
memcached: 'localhost'
cookie_session: {
enabled: no
secret_key: '<KEY>'
}
allow_http_method_override: on
allow_model_exposure: on
allow_underscore_routes: on
developer: {
show_error_stack: on
debug_ip: '192.168.3.11'
}
}
| true | module.exports = conf = {
cluster: off
port: 10001
mongo: 'localhost/link-shortener'
redis: 'localhost'
redis_key: 'PI:KEY:<KEY>END_PI'
memcached: 'localhost'
cookie_session: {
enabled: no
secret_key: 'PI:KEY:<KEY>END_PI'
}
allow_http_method_override: on
allow_model_exposure: on
allow_underscore_routes: on
developer: {
show_error_stack: on
debug_ip: 'PI:IP_ADDRESS:192.168.3.11END_PI'
}
}
|
[
{
"context": "n't perform something twice\", ->\n onceToken = \"I'm a nice onceToken\"\n a = 2\n CB.DispatchOnce onceToke",
"end": 724,
"score": 0.8478125929832458,
"start": 714,
"tag": "PASSWORD",
"value": "I'm a nice"
}
] | test/support/dispatch_test.js.coffee | zhangkaiyufromdongbei/CocoaBean | 0 | describe "Dispatch Async", ->
a = 25
time = new Date().getTime()
beforeEach (done) ->
CB.DispatchAsync(-> a = 26; done())
it "should perform function right away", ->
later = new Date().getTime()
expect(a).toBe(26)
expect(later - time).not.toBeGreaterThan(200)
describe "Dispatch After", ->
a = 20
time = new Date().getTime()
beforeEach (done) ->
CB.DispatchAfter (-> a = 30; done()), 2000
it "should perform after some time", ->
later = new Date().getTime()
expect(a).toBe(30)
expect(later - time).toBeGreaterThan(2000)
expect(later - time).not.toBeGreaterThan(2200)
describe "Dispatch Once", ->
it "shouldn't perform something twice", ->
onceToken = "I'm a nice onceToken"
a = 2
CB.DispatchOnce onceToken, ->
a++
CB.DispatchOnce onceToken, ->
a++
expect(a).toBe(3)
describe "Dispatch Debug", ->
it "should perform when debug token is on", ->
CB.__DebugToken = true
aValue = 20
CB.DispatchDebug(-> aValue = 21)
expect(aValue).toBe(21)
it "shouldn't perform when debug token is off", ->
CB.__DebugToken = false
aValue = 30
CB.DispatchDebug(-> aValue = 88)
expect(aValue).toBe(30)
| 38418 | describe "Dispatch Async", ->
a = 25
time = new Date().getTime()
beforeEach (done) ->
CB.DispatchAsync(-> a = 26; done())
it "should perform function right away", ->
later = new Date().getTime()
expect(a).toBe(26)
expect(later - time).not.toBeGreaterThan(200)
describe "Dispatch After", ->
a = 20
time = new Date().getTime()
beforeEach (done) ->
CB.DispatchAfter (-> a = 30; done()), 2000
it "should perform after some time", ->
later = new Date().getTime()
expect(a).toBe(30)
expect(later - time).toBeGreaterThan(2000)
expect(later - time).not.toBeGreaterThan(2200)
describe "Dispatch Once", ->
it "shouldn't perform something twice", ->
onceToken = "<PASSWORD> onceToken"
a = 2
CB.DispatchOnce onceToken, ->
a++
CB.DispatchOnce onceToken, ->
a++
expect(a).toBe(3)
describe "Dispatch Debug", ->
it "should perform when debug token is on", ->
CB.__DebugToken = true
aValue = 20
CB.DispatchDebug(-> aValue = 21)
expect(aValue).toBe(21)
it "shouldn't perform when debug token is off", ->
CB.__DebugToken = false
aValue = 30
CB.DispatchDebug(-> aValue = 88)
expect(aValue).toBe(30)
| true | describe "Dispatch Async", ->
a = 25
time = new Date().getTime()
beforeEach (done) ->
CB.DispatchAsync(-> a = 26; done())
it "should perform function right away", ->
later = new Date().getTime()
expect(a).toBe(26)
expect(later - time).not.toBeGreaterThan(200)
describe "Dispatch After", ->
a = 20
time = new Date().getTime()
beforeEach (done) ->
CB.DispatchAfter (-> a = 30; done()), 2000
it "should perform after some time", ->
later = new Date().getTime()
expect(a).toBe(30)
expect(later - time).toBeGreaterThan(2000)
expect(later - time).not.toBeGreaterThan(2200)
describe "Dispatch Once", ->
it "shouldn't perform something twice", ->
onceToken = "PI:PASSWORD:<PASSWORD>END_PI onceToken"
a = 2
CB.DispatchOnce onceToken, ->
a++
CB.DispatchOnce onceToken, ->
a++
expect(a).toBe(3)
describe "Dispatch Debug", ->
it "should perform when debug token is on", ->
CB.__DebugToken = true
aValue = 20
CB.DispatchDebug(-> aValue = 21)
expect(aValue).toBe(21)
it "shouldn't perform when debug token is off", ->
CB.__DebugToken = false
aValue = 30
CB.DispatchDebug(-> aValue = 88)
expect(aValue).toBe(30)
|
[
{
"context": "h ->\n @game = new GamingAPI.Models.Game(name: \"test1\")\n @view = new GamingAPI.Views.Game(game: @gam",
"end": 102,
"score": 0.8605642318725586,
"start": 97,
"tag": "NAME",
"value": "test1"
}
] | spec/javascripts/games/views/game_spec.js.coffee | Mack0856/gaming_api | 0 | describe "GamingAPI.Views.Game", ->
beforeEach ->
@game = new GamingAPI.Models.Game(name: "test1")
@view = new GamingAPI.Views.Game(game: @game)
@view.render()
describe "#render", ->
it "renders the specific game", ->
expect(@view.$("a").text()).toEqual "test1"
| 144925 | describe "GamingAPI.Views.Game", ->
beforeEach ->
@game = new GamingAPI.Models.Game(name: "<NAME>")
@view = new GamingAPI.Views.Game(game: @game)
@view.render()
describe "#render", ->
it "renders the specific game", ->
expect(@view.$("a").text()).toEqual "test1"
| true | describe "GamingAPI.Views.Game", ->
beforeEach ->
@game = new GamingAPI.Models.Game(name: "PI:NAME:<NAME>END_PI")
@view = new GamingAPI.Views.Game(game: @game)
@view.render()
describe "#render", ->
it "renders the specific game", ->
expect(@view.$("a").text()).toEqual "test1"
|
[
{
"context": "\"continue\"\n Number(context.registers[\"for\"][@name]) or 0\n else\n Number(context[@attribu",
"end": 2743,
"score": 0.9939426183700562,
"start": 2738,
"tag": "USERNAME",
"value": "@name"
},
{
"context": "][@name]) or 0\n else\n Number(context[@attributes.offset]) or 0\n\n limit = context[@attributes.limit]\n",
"end": 2803,
"score": 0.5731690526008606,
"start": 2786,
"tag": "USERNAME",
"value": "attributes.offset"
},
{
"context": "@attributes.offset]) or 0\n\n limit = context[@attributes.limit]\n to = if limit then Number(limit) + from",
"end": 2851,
"score": 0.6553677916526794,
"start": 2835,
"tag": "USERNAME",
"value": "attributes.limit"
},
{
"context": "r the continue flag\n context.registers[\"for\"][@name] = from + segment.length\n\n context.stack =>\n",
"end": 3223,
"score": 0.9914181232452393,
"start": 3218,
"tag": "USERNAME",
"value": "@name"
},
{
"context": " context.set \"forloop\",\n name : @name\n length : length\n ",
"end": 3448,
"score": 0.6932690143585205,
"start": 3448,
"tag": "NAME",
"value": ""
}
] | src/liquid/tags/for.coffee | bergie/liquid-node | 1 | Liquid = require "../../liquid"
_ = require("underscore")._
# "For" iterates over an array or collection.
# Several useful variables are available to you within the loop.
#
# == Basic usage:
# {% for item in collection %}
# {{ forloop.index }}: {{ item.name }}
# {% endfor %}
#
# == Advanced usage:
# {% for item in collection %}
# <div {% if forloop.first %}class="first"{% endif %}>
# Item {{ forloop.index }}: {{ item.name }}
# </div>
# {% else %}
# There is nothing in the collection.
# {% endfor %}
#
# You can also define a limit and offset much like SQL. Remember
# that offset starts at 0 for the first item.
#
# {% for item in collection limit:5 offset:10 %}
# {{ item.name }}
# {% end %}
#
# To reverse the for loop simply use {% for item in collection reversed %}
#
# == Available variables:
#
# forloop.name:: 'item-collection'
# forloop.length:: Length of the loop
# forloop.index:: The current item's position in the collection;
# forloop.index starts at 1.
# This is helpful for non-programmers who start believe
# the first item in an array is 1, not 0.
# forloop.index0:: The current item's position in the collection
# where the first item is 0
# forloop.rindex:: Number of items remaining in the loop
# (length - index) where 1 is the last item.
# forloop.rindex0:: Number of items remaining in the loop
# where 0 is the last item.
# forloop.first:: Returns true if the item is the first item.
# forloop.last:: Returns true if the item is the last item.
#
module.exports = class For extends Liquid.Block
SyntaxHelp = "Syntax Error in 'for loop' - Valid syntax: for [item] in [collection]"
Syntax = ///
(\w+)\s+in\s+
((?:#{Liquid.QuotedFragment.source})+)
\s*(reversed)?
///
constructor: (tagName, markup, tokens) ->
match = Syntax.exec(markup)
if match
@variableName = match[1]
@collectionName = match[2]
@name = "#{match[1]}=#{match[2]}"
@reversed = match[3]
@attributes = {}
Liquid.Helpers.scan(markup, Liquid.TagAttributes).forEach (key, value) =>
@attributes[key] = value
else
throw new Liquid.SyntaxError(SyntaxHelp)
@nodelist = @forBlock = []
super
unknownTag: (tag, markup, tokens) ->
return super unless tag == "else"
@nodelist = @elseBlock = []
render: (context) ->
context.registers.for or= {}
Liquid.async.when(context.get(@collectionName)).when (collection) =>
return @renderElse(context) unless collection and collection.forEach
from = if @attributes.offset == "continue"
Number(context.registers["for"][@name]) or 0
else
Number(context[@attributes.offset]) or 0
limit = context[@attributes.limit]
to = if limit then Number(limit) + from else null
segment = @sliceCollectionUsingEach(collection, from, to)
return @renderElse(context) if segment.length == 0
segment = _.reverse segment if @reversed
length = segment.length
# Store our progress through the collection for the continue flag
context.registers["for"][@name] = from + segment.length
context.stack =>
Liquid.async.map segment, (item, index) =>
try
context.set @variableName, item
context.set "forloop",
name : @name
length : length
index : index + 1
index0 : index,
rindex : length - index
rindex0 : length - index - 1
first : index == 0
last : index == length - 1
@renderAll(@forBlock, context)
catch e
console.log "for-loop failed: %s %s", e, e.stack
throw e
.when (chunks) -> chunks.join("")
sliceCollectionUsingEach: (collection, from, to) ->
segments = []
index = 0
yielded = 0
_(collection).detect (item) =>
if to and to <= index
true
if from <= index
segments.push item
index += 1
false
segments
renderElse: (context) ->
if @elseBlock
return @renderAll(@elseBlock, context)
else
""
Liquid.Template.registerTag "for", For
| 61742 | Liquid = require "../../liquid"
_ = require("underscore")._
# "For" iterates over an array or collection.
# Several useful variables are available to you within the loop.
#
# == Basic usage:
# {% for item in collection %}
# {{ forloop.index }}: {{ item.name }}
# {% endfor %}
#
# == Advanced usage:
# {% for item in collection %}
# <div {% if forloop.first %}class="first"{% endif %}>
# Item {{ forloop.index }}: {{ item.name }}
# </div>
# {% else %}
# There is nothing in the collection.
# {% endfor %}
#
# You can also define a limit and offset much like SQL. Remember
# that offset starts at 0 for the first item.
#
# {% for item in collection limit:5 offset:10 %}
# {{ item.name }}
# {% end %}
#
# To reverse the for loop simply use {% for item in collection reversed %}
#
# == Available variables:
#
# forloop.name:: 'item-collection'
# forloop.length:: Length of the loop
# forloop.index:: The current item's position in the collection;
# forloop.index starts at 1.
# This is helpful for non-programmers who start believe
# the first item in an array is 1, not 0.
# forloop.index0:: The current item's position in the collection
# where the first item is 0
# forloop.rindex:: Number of items remaining in the loop
# (length - index) where 1 is the last item.
# forloop.rindex0:: Number of items remaining in the loop
# where 0 is the last item.
# forloop.first:: Returns true if the item is the first item.
# forloop.last:: Returns true if the item is the last item.
#
module.exports = class For extends Liquid.Block
SyntaxHelp = "Syntax Error in 'for loop' - Valid syntax: for [item] in [collection]"
Syntax = ///
(\w+)\s+in\s+
((?:#{Liquid.QuotedFragment.source})+)
\s*(reversed)?
///
constructor: (tagName, markup, tokens) ->
match = Syntax.exec(markup)
if match
@variableName = match[1]
@collectionName = match[2]
@name = "#{match[1]}=#{match[2]}"
@reversed = match[3]
@attributes = {}
Liquid.Helpers.scan(markup, Liquid.TagAttributes).forEach (key, value) =>
@attributes[key] = value
else
throw new Liquid.SyntaxError(SyntaxHelp)
@nodelist = @forBlock = []
super
unknownTag: (tag, markup, tokens) ->
return super unless tag == "else"
@nodelist = @elseBlock = []
render: (context) ->
context.registers.for or= {}
Liquid.async.when(context.get(@collectionName)).when (collection) =>
return @renderElse(context) unless collection and collection.forEach
from = if @attributes.offset == "continue"
Number(context.registers["for"][@name]) or 0
else
Number(context[@attributes.offset]) or 0
limit = context[@attributes.limit]
to = if limit then Number(limit) + from else null
segment = @sliceCollectionUsingEach(collection, from, to)
return @renderElse(context) if segment.length == 0
segment = _.reverse segment if @reversed
length = segment.length
# Store our progress through the collection for the continue flag
context.registers["for"][@name] = from + segment.length
context.stack =>
Liquid.async.map segment, (item, index) =>
try
context.set @variableName, item
context.set "forloop",
name :<NAME> @name
length : length
index : index + 1
index0 : index,
rindex : length - index
rindex0 : length - index - 1
first : index == 0
last : index == length - 1
@renderAll(@forBlock, context)
catch e
console.log "for-loop failed: %s %s", e, e.stack
throw e
.when (chunks) -> chunks.join("")
sliceCollectionUsingEach: (collection, from, to) ->
segments = []
index = 0
yielded = 0
_(collection).detect (item) =>
if to and to <= index
true
if from <= index
segments.push item
index += 1
false
segments
renderElse: (context) ->
if @elseBlock
return @renderAll(@elseBlock, context)
else
""
Liquid.Template.registerTag "for", For
| true | Liquid = require "../../liquid"
_ = require("underscore")._
# "For" iterates over an array or collection.
# Several useful variables are available to you within the loop.
#
# == Basic usage:
# {% for item in collection %}
# {{ forloop.index }}: {{ item.name }}
# {% endfor %}
#
# == Advanced usage:
# {% for item in collection %}
# <div {% if forloop.first %}class="first"{% endif %}>
# Item {{ forloop.index }}: {{ item.name }}
# </div>
# {% else %}
# There is nothing in the collection.
# {% endfor %}
#
# You can also define a limit and offset much like SQL. Remember
# that offset starts at 0 for the first item.
#
# {% for item in collection limit:5 offset:10 %}
# {{ item.name }}
# {% end %}
#
# To reverse the for loop simply use {% for item in collection reversed %}
#
# == Available variables:
#
# forloop.name:: 'item-collection'
# forloop.length:: Length of the loop
# forloop.index:: The current item's position in the collection;
# forloop.index starts at 1.
# This is helpful for non-programmers who start believe
# the first item in an array is 1, not 0.
# forloop.index0:: The current item's position in the collection
# where the first item is 0
# forloop.rindex:: Number of items remaining in the loop
# (length - index) where 1 is the last item.
# forloop.rindex0:: Number of items remaining in the loop
# where 0 is the last item.
# forloop.first:: Returns true if the item is the first item.
# forloop.last:: Returns true if the item is the last item.
#
module.exports = class For extends Liquid.Block
SyntaxHelp = "Syntax Error in 'for loop' - Valid syntax: for [item] in [collection]"
Syntax = ///
(\w+)\s+in\s+
((?:#{Liquid.QuotedFragment.source})+)
\s*(reversed)?
///
constructor: (tagName, markup, tokens) ->
match = Syntax.exec(markup)
if match
@variableName = match[1]
@collectionName = match[2]
@name = "#{match[1]}=#{match[2]}"
@reversed = match[3]
@attributes = {}
Liquid.Helpers.scan(markup, Liquid.TagAttributes).forEach (key, value) =>
@attributes[key] = value
else
throw new Liquid.SyntaxError(SyntaxHelp)
@nodelist = @forBlock = []
super
unknownTag: (tag, markup, tokens) ->
return super unless tag == "else"
@nodelist = @elseBlock = []
render: (context) ->
context.registers.for or= {}
Liquid.async.when(context.get(@collectionName)).when (collection) =>
return @renderElse(context) unless collection and collection.forEach
from = if @attributes.offset == "continue"
Number(context.registers["for"][@name]) or 0
else
Number(context[@attributes.offset]) or 0
limit = context[@attributes.limit]
to = if limit then Number(limit) + from else null
segment = @sliceCollectionUsingEach(collection, from, to)
return @renderElse(context) if segment.length == 0
segment = _.reverse segment if @reversed
length = segment.length
# Store our progress through the collection for the continue flag
context.registers["for"][@name] = from + segment.length
context.stack =>
Liquid.async.map segment, (item, index) =>
try
context.set @variableName, item
context.set "forloop",
name :PI:NAME:<NAME>END_PI @name
length : length
index : index + 1
index0 : index,
rindex : length - index
rindex0 : length - index - 1
first : index == 0
last : index == length - 1
@renderAll(@forBlock, context)
catch e
console.log "for-loop failed: %s %s", e, e.stack
throw e
.when (chunks) -> chunks.join("")
sliceCollectionUsingEach: (collection, from, to) ->
segments = []
index = 0
yielded = 0
_(collection).detect (item) =>
if to and to <= index
true
if from <= index
segments.push item
index += 1
false
segments
renderElse: (context) ->
if @elseBlock
return @renderAll(@elseBlock, context)
else
""
Liquid.Template.registerTag "for", For
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.