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": ": @data.get 'account.email'\n password: @data.get 'account.password'\n # client_id: @data.get ",
"end": 616,
"score": 0.9110838174819946,
"start": 607,
"tag": "PASSWORD",
"value": "@data.get"
},
{
"context": "ccount.email'\n password: @data.get ... | src/views/login.coffee | hanzoai/daisho | 88 | import El from 'el.js'
import Events from '../events'
import m from '../mediator'
import {
isRequired,
isEmail,
isPassword,
} from './middleware'
import html from '../templates/login'
class Login extends El.Form
tag: 'daisho-login'
html: html
configs:
'account.email': [ isRequired, isEmail ]
'account.password': [ isPassword ]
error: null
disabled: false
init: ->
if !@data.get 'account'
@data.set 'account',
email: ''
password: ''
super
_submit: (event) ->
opts =
email: @data.get 'account.email'
password: @data.get 'account.password'
# client_id: @data.get 'organization'
# grant_type: 'password'
@error = null
m.trigger Events.Login
@disabled = true
@scheduleUpdate()
@client.dashv2.login(opts).then (res) =>
@disabled = false
@data.set 'account.password', ''
@data.set 'account', res.user
@data.set 'orgs', res.organizations
@data.set 'activeOrg', 0
m.trigger Events.LoginSuccess, res
@scheduleUpdate()
.catch (err) =>
@disabled = false
@error = err.message
m.trigger Events.LoginFailed, err
@scheduleUpdate()
export default Login
| 114739 | import El from 'el.js'
import Events from '../events'
import m from '../mediator'
import {
isRequired,
isEmail,
isPassword,
} from './middleware'
import html from '../templates/login'
class Login extends El.Form
tag: 'daisho-login'
html: html
configs:
'account.email': [ isRequired, isEmail ]
'account.password': [ isPassword ]
error: null
disabled: false
init: ->
if !@data.get 'account'
@data.set 'account',
email: ''
password: ''
super
_submit: (event) ->
opts =
email: @data.get 'account.email'
password: <PASSWORD> 'account.<PASSWORD>'
# client_id: @data.get 'organization'
# grant_type: 'password'
@error = null
m.trigger Events.Login
@disabled = true
@scheduleUpdate()
@client.dashv2.login(opts).then (res) =>
@disabled = false
@data.set 'account.password', ''
@data.set 'account', res.user
@data.set 'orgs', res.organizations
@data.set 'activeOrg', 0
m.trigger Events.LoginSuccess, res
@scheduleUpdate()
.catch (err) =>
@disabled = false
@error = err.message
m.trigger Events.LoginFailed, err
@scheduleUpdate()
export default Login
| true | import El from 'el.js'
import Events from '../events'
import m from '../mediator'
import {
isRequired,
isEmail,
isPassword,
} from './middleware'
import html from '../templates/login'
class Login extends El.Form
tag: 'daisho-login'
html: html
configs:
'account.email': [ isRequired, isEmail ]
'account.password': [ isPassword ]
error: null
disabled: false
init: ->
if !@data.get 'account'
@data.set 'account',
email: ''
password: ''
super
_submit: (event) ->
opts =
email: @data.get 'account.email'
password: PI:PASSWORD:<PASSWORD>END_PI 'account.PI:PASSWORD:<PASSWORD>END_PI'
# client_id: @data.get 'organization'
# grant_type: 'password'
@error = null
m.trigger Events.Login
@disabled = true
@scheduleUpdate()
@client.dashv2.login(opts).then (res) =>
@disabled = false
@data.set 'account.password', ''
@data.set 'account', res.user
@data.set 'orgs', res.organizations
@data.set 'activeOrg', 0
m.trigger Events.LoginSuccess, res
@scheduleUpdate()
.catch (err) =>
@disabled = false
@error = err.message
m.trigger Events.LoginFailed, err
@scheduleUpdate()
export default Login
|
[
{
"context": "oGLib\n# Module | Stat methods\n# Author | Sherif Emabrak\n# Description | mean for array of inputs\n# ------",
"end": 163,
"score": 0.9998784065246582,
"start": 149,
"tag": "NAME",
"value": "Sherif Emabrak"
}
] | src/lib/statistics/summary/mean.coffee | Sherif-Embarak/gp-test | 0 | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat methods
# Author | Sherif Emabrak
# Description | mean for array of inputs
# ------------------------------------------------------------------------------
mean = () -> | 35794 | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat methods
# Author | <NAME>
# Description | mean for array of inputs
# ------------------------------------------------------------------------------
mean = () -> | true | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat methods
# Author | PI:NAME:<NAME>END_PI
# Description | mean for array of inputs
# ------------------------------------------------------------------------------
mean = () -> |
[
{
"context": "dmin\n h.parse_hostfile \"\n [ 127.0.0.1 domain ]\n\n zombies are eating my brain",
"end": 426,
"score": 0.99973464012146,
"start": 417,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "min\n\n h.parse_hostfile \"\"\... | test/hostadmin.coffee | tg123/hostadmin.js | 1 | assert = require("assert")
HostAdmin = require("../lib/hostadmin").HostAdmin
describe 'HostAdmin', ->
describe '#parse_hostfile', ->
it "empty file", ->
h = new HostAdmin
h.parse_hostfile ""
assert.deepEqual {}, h.hosts
assert.deepEqual {}, h.groups
it "junk file", ->
h = new HostAdmin
h.parse_hostfile "
[ 127.0.0.1 domain ]
zombies are eating my brain
php is the best programming language
# wtf...
"
assert.deepEqual {}, h.hosts
assert.deepEqual {}, h.groups
it 'host ip v4', ->
h = new HostAdmin
h.parse_hostfile """
127.0.0.1 domain
#127.0.0.1 domain
127.0.0.1 domain2
"""
assert.deepEqual h.hosts['domain'], [
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":false,"line_no":0,"hide":false}
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":true, "line_no":1,"hide":false}
]
assert.deepEqual h.hosts['domain2'], [
{"ip":"127.0.0.1","host":["domain2"],"comment":"","disabled":false,"line_no":3,"hide":false}
]
it 'parse multi times', ->
h = new HostAdmin
[0..10].forEach ->
h.parse_hostfile """
127.0.0.1 domain
#127.0.0.1 domain
127.0.0.1 domain2
"""
assert.deepEqual h.hosts['domain'], [
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":false,"line_no":0,"hide":false}
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":true, "line_no":1,"hide":false}
]
assert.deepEqual h.hosts['domain2'], [
{"ip":"127.0.0.1","host":["domain2"],"comment":"","disabled":false,"line_no":3,"hide":false}
]
it 'host ip v6', ->
h = new HostAdmin
h.parse_hostfile """
::1 localhost
#1::1 localhost
#fe80::1%lo0 localhost1
"""
assert.deepEqual h.hosts['localhost'], [
{"ip":"::1","host":["localhost"],"comment":"","disabled":false,"line_no":0,"hide":false}
{"ip":"1::1","host":["localhost"],"comment":"","disabled":true, "line_no":1,"hide":false}
]
assert.deepEqual h.hosts['localhost1'], [
{"ip":"fe80::1%lo0","host":["localhost1"],"comment":"","disabled":true,"line_no":3,"hide":false}
]
it 'host with comment and hide', ->
h = new HostAdmin
h.parse_hostfile """
127.0.0.1 domain #test
#127.0.0.1 domain #hide
"""
assert.deepEqual h.hosts['domain'], [
{"ip":"127.0.0.1","host":["domain"],"comment":"test","disabled":false,"line_no":0,"hide":false}
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":true, "line_no":1,"hide":true}
]
it 'directive HIDE_ALL_OF_BELOW', ->
h = new HostAdmin
h.parse_hostfile """
#HIDE_ALL_OF_BELOW
127.0.0.1 domain
#127.0.0.1 domain
"""
assert.deepEqual h.hosts['domain'], [
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":false,"line_no":1,"hide":true}
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":true, "line_no":2,"hide":true}
]
it 'grouping', ->
h = new HostAdmin
h.parse_hostfile """
#====
127.0.0.1 localhost1
##127.0.0.1 localhost2 #hide
##127.0.0.1 localhost3
#====
#
#==== Project 1
127.0.0.1 localhost1
##127.0.0.1 localhost2 #hide
##127.0.0.1 localhost3
#====
#
#==== Project 2
127.0.0.1 localhost1
#127.0.0.1 localhost2
#127.0.0.1 localhost3
#====
#
#==== Project 3
127.0.0.1 localhost1
#127.0.0.1 localhost2
#127.0.0.1 localhost3
#====
"""
assert.deepEqual h.groups, [
{
name: 'Group 1'
hosts: [
{"ip":"127.0.0.1","host":["localhost1"],"comment":"","disabled":false,"line_no":1,"hide":false}
{"ip":"127.0.0.1","host":["localhost2"],"comment":"","disabled":true, "line_no":2,"hide":true}
{"ip":"127.0.0.1","host":["localhost3"],"comment":"","disabled":true, "line_no":3,"hide":false}
]
}
{
name: 'Project 1'
hosts: [
{"ip":"127.0.0.1","host":["localhost1"],"comment":"","disabled":false,"line_no":8,"hide":false}
{"ip":"127.0.0.1","host":["localhost2"],"comment":"","disabled":true, "line_no":9,"hide":true}
{"ip":"127.0.0.1","host":["localhost3"],"comment":"","disabled":true, "line_no":10,"hide":false}
]
}
{
name: 'Project 2'
hosts: [
{"ip":"127.0.0.1","host":["localhost1"],"comment":"","disabled":false,"line_no":15,"hide":false}
{"ip":"127.0.0.1","host":["localhost2"],"comment":"","disabled":true, "line_no":16,"hide":false}
{"ip":"127.0.0.1","host":["localhost3"],"comment":"","disabled":true, "line_no":17,"hide":false}
]
}
{
name: 'Project 3'
hosts: [
{"ip":"127.0.0.1","host":["localhost1"],"comment":"","disabled":false,"line_no":22,"hide":false}
{"ip":"127.0.0.1","host":["localhost2"],"comment":"","disabled":true, "line_no":23,"hide":false}
{"ip":"127.0.0.1","host":["localhost3"],"comment":"","disabled":true, "line_no":24,"hide":false}
]
}
]
describe '#host_toggle', ->
it 'toggle on -> off', ->
h = new HostAdmin
h.parse_hostfile """
127.0.0.1 domain
#127.0.0.1 domain
127.0.0.1 domain2
"""
domain = h.hosts['domain'][0]
domain2 = h.hosts['domain2'][0]
h.host_toggle('domain', domain)
assert.equal h.to_hostfile(), """
#127.0.0.1 domain
#127.0.0.1 domain
127.0.0.1 domain2
"""
assert.equal domain.disabled, true
h.host_toggle('domain2', domain2)
assert.equal h.to_hostfile(), """
#127.0.0.1 domain
#127.0.0.1 domain
#127.0.0.1 domain2
"""
assert.equal domain2.disabled, true
it 'toggle off -> on , exclusive', ->
h = new HostAdmin
h.parse_hostfile """
127.0.0.1 domain
#127.0.0.1 domain
#127.0.0.1 domain2
"""
domain = h.hosts['domain'][1]
domain2 = h.hosts['domain2'][0]
h.host_toggle('domain', domain)
assert.equal h.to_hostfile(), """
#127.0.0.1 domain
127.0.0.1 domain
#127.0.0.1 domain2
"""
assert.equal domain.disabled, false
assert.equal h.hosts['domain'][0].disabled, true
h.host_toggle('domain2', domain2)
assert.equal h.to_hostfile(), """
#127.0.0.1 domain
127.0.0.1 domain
127.0.0.1 domain2
"""
assert.equal domain2.disabled, false
describe '# group_toggle', ->
it 'all enable test', ->
h = new HostAdmin
h.parse_hostfile """
#==== Project 1
127.0.0.1 localhost1
##127.0.0.1 localhost2 #hide
##127.0.0.1 localhost3
#====
127.0.0.1 localhost2
127.0.0.1 localhost3
#
#==== Project 2
127.0.0.1 localhost1
127.0.0.1 localhost2 #hide
127.0.0.1 localhost3
#====
"""
project1 = h.groups[0]
project2 = h.groups[1]
assert.equal h.group_is_all_enabled(project1), false
assert.equal h.group_is_all_enabled(project2), true
it 'toogle on and toggle off', ->
h = new HostAdmin
h.parse_hostfile """
#==== Project 1
127.0.0.1 localhost1
##127.0.0.1 localhost2 #hide
##127.0.0.1 localhost3
#====
127.0.0.1 localhost2
127.0.0.1 localhost3
#
#==== Project 2
127.0.0.1 localhost1
127.0.0.1 localhost2 #hide
127.0.0.1 localhost3
#====
"""
project1 = h.groups[0]
project2 = h.groups[1]
h.group_toggle(project1)
assert.equal h.to_hostfile(), """
#==== Project 1
127.0.0.1 localhost1
127.0.0.1 localhost2 #hide
127.0.0.1 localhost3
#====
127.0.0.1 localhost2
127.0.0.1 localhost3
#
#==== Project 2
127.0.0.1 localhost1
127.0.0.1 localhost2 #hide
127.0.0.1 localhost3
#====
"""
assert.equal h.group_is_all_enabled(project1), true
h.group_toggle(project2)
assert.equal h.to_hostfile(), """
#==== Project 1
127.0.0.1 localhost1
127.0.0.1 localhost2 #hide
127.0.0.1 localhost3
#====
127.0.0.1 localhost2
127.0.0.1 localhost3
#
#==== Project 2
#127.0.0.1 localhost1
#127.0.0.1 localhost2 #hide
#127.0.0.1 localhost3
#====
"""
assert.equal h.group_is_all_enabled(project2), false
| 59372 | assert = require("assert")
HostAdmin = require("../lib/hostadmin").HostAdmin
describe 'HostAdmin', ->
describe '#parse_hostfile', ->
it "empty file", ->
h = new HostAdmin
h.parse_hostfile ""
assert.deepEqual {}, h.hosts
assert.deepEqual {}, h.groups
it "junk file", ->
h = new HostAdmin
h.parse_hostfile "
[ 127.0.0.1 domain ]
zombies are eating my brain
php is the best programming language
# wtf...
"
assert.deepEqual {}, h.hosts
assert.deepEqual {}, h.groups
it 'host ip v4', ->
h = new HostAdmin
h.parse_hostfile """
127.0.0.1 domain
#127.0.0.1 domain
127.0.0.1 domain2
"""
assert.deepEqual h.hosts['domain'], [
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":false,"line_no":0,"hide":false}
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":true, "line_no":1,"hide":false}
]
assert.deepEqual h.hosts['domain2'], [
{"ip":"127.0.0.1","host":["domain2"],"comment":"","disabled":false,"line_no":3,"hide":false}
]
it 'parse multi times', ->
h = new HostAdmin
[0..10].forEach ->
h.parse_hostfile """
127.0.0.1 domain
#127.0.0.1 domain
127.0.0.1 domain2
"""
assert.deepEqual h.hosts['domain'], [
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":false,"line_no":0,"hide":false}
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":true, "line_no":1,"hide":false}
]
assert.deepEqual h.hosts['domain2'], [
{"ip":"127.0.0.1","host":["domain2"],"comment":"","disabled":false,"line_no":3,"hide":false}
]
it 'host ip v6', ->
h = new HostAdmin
h.parse_hostfile """
::1 localhost
#1::1 localhost
#fe80::1%lo0 localhost1
"""
assert.deepEqual h.hosts['localhost'], [
{"ip":"::1","host":["localhost"],"comment":"","disabled":false,"line_no":0,"hide":false}
{"ip":"fc00:e968:6179::de52:7100","host":["localhost"],"comment":"","disabled":true, "line_no":1,"hide":false}
]
assert.deepEqual h.hosts['localhost1'], [
{"ip":"fe80::1%lo0","host":["localhost1"],"comment":"","disabled":true,"line_no":3,"hide":false}
]
it 'host with comment and hide', ->
h = new HostAdmin
h.parse_hostfile """
127.0.0.1 domain #test
#127.0.0.1 domain #hide
"""
assert.deepEqual h.hosts['domain'], [
{"ip":"127.0.0.1","host":["domain"],"comment":"test","disabled":false,"line_no":0,"hide":false}
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":true, "line_no":1,"hide":true}
]
it 'directive HIDE_ALL_OF_BELOW', ->
h = new HostAdmin
h.parse_hostfile """
#HIDE_ALL_OF_BELOW
127.0.0.1 domain
#127.0.0.1 domain
"""
assert.deepEqual h.hosts['domain'], [
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":false,"line_no":1,"hide":true}
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":true, "line_no":2,"hide":true}
]
it 'grouping', ->
h = new HostAdmin
h.parse_hostfile """
#====
127.0.0.1 localhost1
##127.0.0.1 localhost2 #hide
##127.0.0.1 localhost3
#====
#
#==== Project 1
127.0.0.1 localhost1
##127.0.0.1 localhost2 #hide
##127.0.0.1 localhost3
#====
#
#==== Project 2
127.0.0.1 localhost1
#127.0.0.1 localhost2
#127.0.0.1 localhost3
#====
#
#==== Project 3
127.0.0.1 localhost1
#127.0.0.1 localhost2
#127.0.0.1 localhost3
#====
"""
assert.deepEqual h.groups, [
{
name: 'Group 1'
hosts: [
{"ip":"127.0.0.1","host":["localhost1"],"comment":"","disabled":false,"line_no":1,"hide":false}
{"ip":"127.0.0.1","host":["localhost2"],"comment":"","disabled":true, "line_no":2,"hide":true}
{"ip":"127.0.0.1","host":["localhost3"],"comment":"","disabled":true, "line_no":3,"hide":false}
]
}
{
name: 'Project 1'
hosts: [
{"ip":"127.0.0.1","host":["localhost1"],"comment":"","disabled":false,"line_no":8,"hide":false}
{"ip":"127.0.0.1","host":["localhost2"],"comment":"","disabled":true, "line_no":9,"hide":true}
{"ip":"127.0.0.1","host":["localhost3"],"comment":"","disabled":true, "line_no":10,"hide":false}
]
}
{
name: 'Project 2'
hosts: [
{"ip":"127.0.0.1","host":["localhost1"],"comment":"","disabled":false,"line_no":15,"hide":false}
{"ip":"127.0.0.1","host":["localhost2"],"comment":"","disabled":true, "line_no":16,"hide":false}
{"ip":"127.0.0.1","host":["localhost3"],"comment":"","disabled":true, "line_no":17,"hide":false}
]
}
{
name: 'Project 3'
hosts: [
{"ip":"127.0.0.1","host":["localhost1"],"comment":"","disabled":false,"line_no":22,"hide":false}
{"ip":"127.0.0.1","host":["localhost2"],"comment":"","disabled":true, "line_no":23,"hide":false}
{"ip":"127.0.0.1","host":["localhost3"],"comment":"","disabled":true, "line_no":24,"hide":false}
]
}
]
describe '#host_toggle', ->
it 'toggle on -> off', ->
h = new HostAdmin
h.parse_hostfile """
127.0.0.1 domain
#127.0.0.1 domain
127.0.0.1 domain2
"""
domain = h.hosts['domain'][0]
domain2 = h.hosts['domain2'][0]
h.host_toggle('domain', domain)
assert.equal h.to_hostfile(), """
#127.0.0.1 domain
#127.0.0.1 domain
127.0.0.1 domain2
"""
assert.equal domain.disabled, true
h.host_toggle('domain2', domain2)
assert.equal h.to_hostfile(), """
#127.0.0.1 domain
#127.0.0.1 domain
#127.0.0.1 domain2
"""
assert.equal domain2.disabled, true
it 'toggle off -> on , exclusive', ->
h = new HostAdmin
h.parse_hostfile """
127.0.0.1 domain
#127.0.0.1 domain
#127.0.0.1 domain2
"""
domain = h.hosts['domain'][1]
domain2 = h.hosts['domain2'][0]
h.host_toggle('domain', domain)
assert.equal h.to_hostfile(), """
#127.0.0.1 domain
127.0.0.1 domain
#127.0.0.1 domain2
"""
assert.equal domain.disabled, false
assert.equal h.hosts['domain'][0].disabled, true
h.host_toggle('domain2', domain2)
assert.equal h.to_hostfile(), """
#127.0.0.1 domain
127.0.0.1 domain
127.0.0.1 domain2
"""
assert.equal domain2.disabled, false
describe '# group_toggle', ->
it 'all enable test', ->
h = new HostAdmin
h.parse_hostfile """
#==== Project 1
127.0.0.1 localhost1
##127.0.0.1 localhost2 #hide
##127.0.0.1 localhost3
#====
127.0.0.1 localhost2
127.0.0.1 localhost3
#
#==== Project 2
127.0.0.1 localhost1
127.0.0.1 localhost2 #hide
127.0.0.1 localhost3
#====
"""
project1 = h.groups[0]
project2 = h.groups[1]
assert.equal h.group_is_all_enabled(project1), false
assert.equal h.group_is_all_enabled(project2), true
it 'toogle on and toggle off', ->
h = new HostAdmin
h.parse_hostfile """
#==== Project 1
127.0.0.1 localhost1
##127.0.0.1 localhost2 #hide
##127.0.0.1 localhost3
#====
127.0.0.1 localhost2
127.0.0.1 localhost3
#
#==== Project 2
127.0.0.1 localhost1
127.0.0.1 localhost2 #hide
127.0.0.1 localhost3
#====
"""
project1 = h.groups[0]
project2 = h.groups[1]
h.group_toggle(project1)
assert.equal h.to_hostfile(), """
#==== Project 1
127.0.0.1 localhost1
127.0.0.1 localhost2 #hide
127.0.0.1 localhost3
#====
127.0.0.1 localhost2
127.0.0.1 localhost3
#
#==== Project 2
127.0.0.1 localhost1
127.0.0.1 localhost2 #hide
127.0.0.1 localhost3
#====
"""
assert.equal h.group_is_all_enabled(project1), true
h.group_toggle(project2)
assert.equal h.to_hostfile(), """
#==== Project 1
127.0.0.1 localhost1
127.0.0.1 localhost2 #hide
127.0.0.1 localhost3
#====
127.0.0.1 localhost2
127.0.0.1 localhost3
#
#==== Project 2
#127.0.0.1 localhost1
#127.0.0.1 localhost2 #hide
#127.0.0.1 localhost3
#====
"""
assert.equal h.group_is_all_enabled(project2), false
| true | assert = require("assert")
HostAdmin = require("../lib/hostadmin").HostAdmin
describe 'HostAdmin', ->
describe '#parse_hostfile', ->
it "empty file", ->
h = new HostAdmin
h.parse_hostfile ""
assert.deepEqual {}, h.hosts
assert.deepEqual {}, h.groups
it "junk file", ->
h = new HostAdmin
h.parse_hostfile "
[ 127.0.0.1 domain ]
zombies are eating my brain
php is the best programming language
# wtf...
"
assert.deepEqual {}, h.hosts
assert.deepEqual {}, h.groups
it 'host ip v4', ->
h = new HostAdmin
h.parse_hostfile """
127.0.0.1 domain
#127.0.0.1 domain
127.0.0.1 domain2
"""
assert.deepEqual h.hosts['domain'], [
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":false,"line_no":0,"hide":false}
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":true, "line_no":1,"hide":false}
]
assert.deepEqual h.hosts['domain2'], [
{"ip":"127.0.0.1","host":["domain2"],"comment":"","disabled":false,"line_no":3,"hide":false}
]
it 'parse multi times', ->
h = new HostAdmin
[0..10].forEach ->
h.parse_hostfile """
127.0.0.1 domain
#127.0.0.1 domain
127.0.0.1 domain2
"""
assert.deepEqual h.hosts['domain'], [
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":false,"line_no":0,"hide":false}
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":true, "line_no":1,"hide":false}
]
assert.deepEqual h.hosts['domain2'], [
{"ip":"127.0.0.1","host":["domain2"],"comment":"","disabled":false,"line_no":3,"hide":false}
]
it 'host ip v6', ->
h = new HostAdmin
h.parse_hostfile """
::1 localhost
#1::1 localhost
#fe80::1%lo0 localhost1
"""
assert.deepEqual h.hosts['localhost'], [
{"ip":"::1","host":["localhost"],"comment":"","disabled":false,"line_no":0,"hide":false}
{"ip":"PI:IP_ADDRESS:fc00:e968:6179::de52:7100END_PI","host":["localhost"],"comment":"","disabled":true, "line_no":1,"hide":false}
]
assert.deepEqual h.hosts['localhost1'], [
{"ip":"fe80::1%lo0","host":["localhost1"],"comment":"","disabled":true,"line_no":3,"hide":false}
]
it 'host with comment and hide', ->
h = new HostAdmin
h.parse_hostfile """
127.0.0.1 domain #test
#127.0.0.1 domain #hide
"""
assert.deepEqual h.hosts['domain'], [
{"ip":"127.0.0.1","host":["domain"],"comment":"test","disabled":false,"line_no":0,"hide":false}
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":true, "line_no":1,"hide":true}
]
it 'directive HIDE_ALL_OF_BELOW', ->
h = new HostAdmin
h.parse_hostfile """
#HIDE_ALL_OF_BELOW
127.0.0.1 domain
#127.0.0.1 domain
"""
assert.deepEqual h.hosts['domain'], [
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":false,"line_no":1,"hide":true}
{"ip":"127.0.0.1","host":["domain"],"comment":"","disabled":true, "line_no":2,"hide":true}
]
it 'grouping', ->
h = new HostAdmin
h.parse_hostfile """
#====
127.0.0.1 localhost1
##127.0.0.1 localhost2 #hide
##127.0.0.1 localhost3
#====
#
#==== Project 1
127.0.0.1 localhost1
##127.0.0.1 localhost2 #hide
##127.0.0.1 localhost3
#====
#
#==== Project 2
127.0.0.1 localhost1
#127.0.0.1 localhost2
#127.0.0.1 localhost3
#====
#
#==== Project 3
127.0.0.1 localhost1
#127.0.0.1 localhost2
#127.0.0.1 localhost3
#====
"""
assert.deepEqual h.groups, [
{
name: 'Group 1'
hosts: [
{"ip":"127.0.0.1","host":["localhost1"],"comment":"","disabled":false,"line_no":1,"hide":false}
{"ip":"127.0.0.1","host":["localhost2"],"comment":"","disabled":true, "line_no":2,"hide":true}
{"ip":"127.0.0.1","host":["localhost3"],"comment":"","disabled":true, "line_no":3,"hide":false}
]
}
{
name: 'Project 1'
hosts: [
{"ip":"127.0.0.1","host":["localhost1"],"comment":"","disabled":false,"line_no":8,"hide":false}
{"ip":"127.0.0.1","host":["localhost2"],"comment":"","disabled":true, "line_no":9,"hide":true}
{"ip":"127.0.0.1","host":["localhost3"],"comment":"","disabled":true, "line_no":10,"hide":false}
]
}
{
name: 'Project 2'
hosts: [
{"ip":"127.0.0.1","host":["localhost1"],"comment":"","disabled":false,"line_no":15,"hide":false}
{"ip":"127.0.0.1","host":["localhost2"],"comment":"","disabled":true, "line_no":16,"hide":false}
{"ip":"127.0.0.1","host":["localhost3"],"comment":"","disabled":true, "line_no":17,"hide":false}
]
}
{
name: 'Project 3'
hosts: [
{"ip":"127.0.0.1","host":["localhost1"],"comment":"","disabled":false,"line_no":22,"hide":false}
{"ip":"127.0.0.1","host":["localhost2"],"comment":"","disabled":true, "line_no":23,"hide":false}
{"ip":"127.0.0.1","host":["localhost3"],"comment":"","disabled":true, "line_no":24,"hide":false}
]
}
]
describe '#host_toggle', ->
it 'toggle on -> off', ->
h = new HostAdmin
h.parse_hostfile """
127.0.0.1 domain
#127.0.0.1 domain
127.0.0.1 domain2
"""
domain = h.hosts['domain'][0]
domain2 = h.hosts['domain2'][0]
h.host_toggle('domain', domain)
assert.equal h.to_hostfile(), """
#127.0.0.1 domain
#127.0.0.1 domain
127.0.0.1 domain2
"""
assert.equal domain.disabled, true
h.host_toggle('domain2', domain2)
assert.equal h.to_hostfile(), """
#127.0.0.1 domain
#127.0.0.1 domain
#127.0.0.1 domain2
"""
assert.equal domain2.disabled, true
it 'toggle off -> on , exclusive', ->
h = new HostAdmin
h.parse_hostfile """
127.0.0.1 domain
#127.0.0.1 domain
#127.0.0.1 domain2
"""
domain = h.hosts['domain'][1]
domain2 = h.hosts['domain2'][0]
h.host_toggle('domain', domain)
assert.equal h.to_hostfile(), """
#127.0.0.1 domain
127.0.0.1 domain
#127.0.0.1 domain2
"""
assert.equal domain.disabled, false
assert.equal h.hosts['domain'][0].disabled, true
h.host_toggle('domain2', domain2)
assert.equal h.to_hostfile(), """
#127.0.0.1 domain
127.0.0.1 domain
127.0.0.1 domain2
"""
assert.equal domain2.disabled, false
describe '# group_toggle', ->
it 'all enable test', ->
h = new HostAdmin
h.parse_hostfile """
#==== Project 1
127.0.0.1 localhost1
##127.0.0.1 localhost2 #hide
##127.0.0.1 localhost3
#====
127.0.0.1 localhost2
127.0.0.1 localhost3
#
#==== Project 2
127.0.0.1 localhost1
127.0.0.1 localhost2 #hide
127.0.0.1 localhost3
#====
"""
project1 = h.groups[0]
project2 = h.groups[1]
assert.equal h.group_is_all_enabled(project1), false
assert.equal h.group_is_all_enabled(project2), true
it 'toogle on and toggle off', ->
h = new HostAdmin
h.parse_hostfile """
#==== Project 1
127.0.0.1 localhost1
##127.0.0.1 localhost2 #hide
##127.0.0.1 localhost3
#====
127.0.0.1 localhost2
127.0.0.1 localhost3
#
#==== Project 2
127.0.0.1 localhost1
127.0.0.1 localhost2 #hide
127.0.0.1 localhost3
#====
"""
project1 = h.groups[0]
project2 = h.groups[1]
h.group_toggle(project1)
assert.equal h.to_hostfile(), """
#==== Project 1
127.0.0.1 localhost1
127.0.0.1 localhost2 #hide
127.0.0.1 localhost3
#====
127.0.0.1 localhost2
127.0.0.1 localhost3
#
#==== Project 2
127.0.0.1 localhost1
127.0.0.1 localhost2 #hide
127.0.0.1 localhost3
#====
"""
assert.equal h.group_is_all_enabled(project1), true
h.group_toggle(project2)
assert.equal h.to_hostfile(), """
#==== Project 1
127.0.0.1 localhost1
127.0.0.1 localhost2 #hide
127.0.0.1 localhost3
#====
127.0.0.1 localhost2
127.0.0.1 localhost3
#
#==== Project 2
#127.0.0.1 localhost1
#127.0.0.1 localhost2 #hide
#127.0.0.1 localhost3
#====
"""
assert.equal h.group_is_all_enabled(project2), false
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999106526374817,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/profile-page/user-page.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 { ExtraHeader } from './extra-header'
import { UserPageEditor } from './user-page-editor'
import * as React from 'react'
import { a, button, div, span, p } from 'react-dom-factories'
import { StringWithComponent } from 'string-with-component'
el = React.createElement
export class UserPage extends React.Component
render: =>
isBlank = @props.userPage.initialRaw.trim() == ''
canEdit = @props.withEdit || window.currentUser.is_moderator || window.currentUser.is_admin
div className: 'page-extra page-extra--userpage',
el ExtraHeader, name: @props.name, withEdit: @props.withEdit
if !@props.userPage.editing && canEdit && !isBlank
div className: 'page-extra__actions',
button
type: 'button'
title: osu.trans('users.show.page.button')
className: 'profile-page-toggle'
onClick: @editStart
span className: 'fas fa-pencil-alt'
if @props.userPage.editing
el UserPageEditor, userPage: @props.userPage, user: @props.user
else
div className: 'page-extra__content-overflow-wrapper-outer u-fancy-scrollbar',
if @props.withEdit && isBlank
@pageNew()
else
div className: 'page-extra__content-overflow-wrapper-inner',
@pageShow()
editStart: ->
$.publish 'user:page:update', editing: true
pageNew: =>
div className: 'profile-extra-user-page profile-extra-user-page--new',
button
className: 'profile-extra-user-page__new-content btn-osu btn-osu--lite btn-osu--profile-page-edit'
onClick: @editStart
disabled: !@props.user.has_supported
osu.trans 'users.show.page.edit_big'
p className: 'profile-extra-user-page__new-content profile-extra-user-page__new-content--icon',
span className: 'fas fa-edit'
p
className: 'profile-extra-user-page__new-content'
dangerouslySetInnerHTML:
__html: osu.trans 'users.show.page.description'
if !@props.user.has_supported
p
className: 'profile-extra-user-page__new-content'
el StringWithComponent,
mappings:
':link': a
href: laroute.route('store.products.show', product: 'supporter-tag')
key: 'link'
target: '_blank'
osu.trans 'users.show.page.restriction_info.link'
pattern: osu.trans 'users.show.page.restriction_info._'
pageShow: =>
div dangerouslySetInnerHTML:
__html: @props.userPage.html
| 785 | # 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 { ExtraHeader } from './extra-header'
import { UserPageEditor } from './user-page-editor'
import * as React from 'react'
import { a, button, div, span, p } from 'react-dom-factories'
import { StringWithComponent } from 'string-with-component'
el = React.createElement
export class UserPage extends React.Component
render: =>
isBlank = @props.userPage.initialRaw.trim() == ''
canEdit = @props.withEdit || window.currentUser.is_moderator || window.currentUser.is_admin
div className: 'page-extra page-extra--userpage',
el ExtraHeader, name: @props.name, withEdit: @props.withEdit
if !@props.userPage.editing && canEdit && !isBlank
div className: 'page-extra__actions',
button
type: 'button'
title: osu.trans('users.show.page.button')
className: 'profile-page-toggle'
onClick: @editStart
span className: 'fas fa-pencil-alt'
if @props.userPage.editing
el UserPageEditor, userPage: @props.userPage, user: @props.user
else
div className: 'page-extra__content-overflow-wrapper-outer u-fancy-scrollbar',
if @props.withEdit && isBlank
@pageNew()
else
div className: 'page-extra__content-overflow-wrapper-inner',
@pageShow()
editStart: ->
$.publish 'user:page:update', editing: true
pageNew: =>
div className: 'profile-extra-user-page profile-extra-user-page--new',
button
className: 'profile-extra-user-page__new-content btn-osu btn-osu--lite btn-osu--profile-page-edit'
onClick: @editStart
disabled: !@props.user.has_supported
osu.trans 'users.show.page.edit_big'
p className: 'profile-extra-user-page__new-content profile-extra-user-page__new-content--icon',
span className: 'fas fa-edit'
p
className: 'profile-extra-user-page__new-content'
dangerouslySetInnerHTML:
__html: osu.trans 'users.show.page.description'
if !@props.user.has_supported
p
className: 'profile-extra-user-page__new-content'
el StringWithComponent,
mappings:
':link': a
href: laroute.route('store.products.show', product: 'supporter-tag')
key: 'link'
target: '_blank'
osu.trans 'users.show.page.restriction_info.link'
pattern: osu.trans 'users.show.page.restriction_info._'
pageShow: =>
div dangerouslySetInnerHTML:
__html: @props.userPage.html
| 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 { ExtraHeader } from './extra-header'
import { UserPageEditor } from './user-page-editor'
import * as React from 'react'
import { a, button, div, span, p } from 'react-dom-factories'
import { StringWithComponent } from 'string-with-component'
el = React.createElement
export class UserPage extends React.Component
render: =>
isBlank = @props.userPage.initialRaw.trim() == ''
canEdit = @props.withEdit || window.currentUser.is_moderator || window.currentUser.is_admin
div className: 'page-extra page-extra--userpage',
el ExtraHeader, name: @props.name, withEdit: @props.withEdit
if !@props.userPage.editing && canEdit && !isBlank
div className: 'page-extra__actions',
button
type: 'button'
title: osu.trans('users.show.page.button')
className: 'profile-page-toggle'
onClick: @editStart
span className: 'fas fa-pencil-alt'
if @props.userPage.editing
el UserPageEditor, userPage: @props.userPage, user: @props.user
else
div className: 'page-extra__content-overflow-wrapper-outer u-fancy-scrollbar',
if @props.withEdit && isBlank
@pageNew()
else
div className: 'page-extra__content-overflow-wrapper-inner',
@pageShow()
editStart: ->
$.publish 'user:page:update', editing: true
pageNew: =>
div className: 'profile-extra-user-page profile-extra-user-page--new',
button
className: 'profile-extra-user-page__new-content btn-osu btn-osu--lite btn-osu--profile-page-edit'
onClick: @editStart
disabled: !@props.user.has_supported
osu.trans 'users.show.page.edit_big'
p className: 'profile-extra-user-page__new-content profile-extra-user-page__new-content--icon',
span className: 'fas fa-edit'
p
className: 'profile-extra-user-page__new-content'
dangerouslySetInnerHTML:
__html: osu.trans 'users.show.page.description'
if !@props.user.has_supported
p
className: 'profile-extra-user-page__new-content'
el StringWithComponent,
mappings:
':link': a
href: laroute.route('store.products.show', product: 'supporter-tag')
key: 'link'
target: '_blank'
osu.trans 'users.show.page.restriction_info.link'
pattern: osu.trans 'users.show.page.restriction_info._'
pageShow: =>
div dangerouslySetInnerHTML:
__html: @props.userPage.html
|
[
{
"context": "np\"\n data: ([\n 'api_key=PZN1ZYVWOPFLCUR5'\n 'track_id='+song.tracks[0].forei",
"end": 955,
"score": 0.9993739724159241,
"start": 939,
"tag": "KEY",
"value": "PZN1ZYVWOPFLCUR5"
},
{
"context": "x.textAlign=\"left\";\n ctx.... | scripts/main.iced | jceipek/Spiradic | 0 | require.config({
baseUrl: 'javascripts'
paths: {
jquery: 'jquery-1.11.2.min'
}
})
require ['./state', 'jquery'], (STATE, $) ->
DEBUG = true
print = (x) ->
if DEBUG
console.log(x)
ECHONEST_ID = 'YSN67FHUAZZDWQBSL'
initSongData = (cb) ->
url = 'http://developer.echonest.com/api/v4/song/search?' +
(['api_key='+ECHONEST_ID
'format=json'
'results=1'
'min_tempo=120'
'mood=excited'
'sort=song_hotttnesss-desc'
'bucket=id:fma'
'bucket=tracks'
'limit=true'
].join('&'))
await $.getJSON(url, defer res )
fmaData = []
songList = res.response.songs
print(songList)
await
for song,i in songList
url = 'http://freemusicarchive.org/api/get/tracks.jsonp?'
$.ajax({
url: url
jsonp: "callback"
dataType: "jsonp"
data: ([
'api_key=PZN1ZYVWOPFLCUR5'
'track_id='+song.tracks[0].foreign_id[('fma:track:'.length)..]
].join('&'))
success: defer(fmaData[i])
error: (e) -> console.log(e.message)
})
print(fmaData)
songFiles = (({ artist_name: song.dataset[0].artist_name, track_title: song.dataset[0].track_title, track_url: song.dataset[0].track_url, track_id: songList[i].tracks[0].id}) for song,i in fmaData)
console.log(songFiles)
STATE.songs.set(songFiles)
cb(songFiles)
initSongAnalysis = (songInfo) ->
songAnalyses = []
for track in songInfo
url = 'http://developer.echonest.com/api/v4/track/profile?' +
(['api_key='+ECHONEST_ID
'format=json'
'id='+track.track_id
'bucket=audio_summary'
].join('&'))
await $.getJSON(url, defer res )
await $.getJSON(res.response.track.audio_summary.analysis_url, defer res )
songAnalyses.push({song_info: track, analysis: res})
STATE.song_analyses.set(songAnalyses)
initGameData = () ->
gs = {
levelIndex: 1
isPaused: true
invincibilityTimer: 0
didGetHitTimer: 0
levelTime: 10
elapsedTime: -2
audio: {
beatIndex: 0
beats: []
bars: []
tatums: []
segments: []
}
worldRot: 0
player: {
type: 0
totalTypes: 2
collisionRadius: 0.05
}
screenDims: {
widthPX: 1024
heightPX: 768
}
worldDims: {
width: 1
height: 3/4
}
input: {
change: false
}
}
STATE.set(gs)
# unless STATE.songs.read()?
initSongData((songData) -> initSongAnalysis(STATE.songs.read()))
# STATE.songs.set('')
# initSongData()
# initSongAnalysis(STATE.songs.read())
console.log(STATE.song_analyses.read())
document.getElementById('loading-msg').remove()
# unless STATE.read()?
initGameData()
# else print("GAME NOT INITIALIZED")
P = (() ->
gameScreenCanvas = document.getElementById('game')
backBufferCanvas = document.createElement('canvas')
G = STATE.read()
$(gameScreenCanvas).attr('width', G.screenDims.widthPX)
$(gameScreenCanvas).attr('height', G.screenDims.heightPX)
$(backBufferCanvas).attr('width', G.screenDims.widthPX)
$(backBufferCanvas).attr('height', G.screenDims.heightPX)
backBufferCanvas.width = G.screenDims.widthPX
backBufferCanvas.width = G.screenDims.widthPX
backBufferCanvas.height = G.screenDims.heightPX
backBufferCanvas.height = G.screenDims.heightPX
backBuffer = backBufferCanvas.getContext('2d')
gameScreen = gameScreenCanvas.getContext('2d')
events = []
$(window).keydown (e) ->
events.push(e)
if e.keyCode is 32
e.preventDefault()
{
swapBuffers: () -> gameScreen.drawImage(backBufferCanvas, 0, 0)
backBuffer: backBuffer
readInput: () ->
read = events
events = []
read
}
)()
step = (() ->
lastTimestamp = null
(timestamp) ->
elapsed = timestamp - lastTimestamp
G = guar(P.backBuffer, STATE.read(), elapsed)
G.input = {}
es = P.readInput()
for e in es
if e.keyCode is 32
G.input.change = true
STATE.set(G)
lastTimestamp = timestamp
window.requestAnimationFrame step)()
typeColors = ['#FC3A8B', '#01B0F0'] #['#FFF', '#000']
clearScreen = (ctx, screenDims, type) ->
ctx.fillStyle = typeColors[type]
ctx.fillRect(0,0, screenDims.widthPX,
screenDims.heightPX)
drawEntityNew = (ctx, pixelsPerUnit, posOuter, posInner, invincibility) ->
if invincibility > 0
ctx.strokeStyle = '#FFF'
else
ctx.strokeStyle = '#AEEE00'
ctx.beginPath()
ctx.moveTo(posInner.x*pixelsPerUnit, posInner.y*pixelsPerUnit)
ctx.lineTo(posOuter.x*pixelsPerUnit, posOuter.y*pixelsPerUnit)
# radius = 0.01
# ctx.arc(pos.x*pixelsPerUnit, pos.y*pixelsPerUnit, radius*pixelsPerUnit, 0, Math.PI * 2)
# ctx.closePath()
ctx.stroke()
drawEntity = (ctx, pixelsPerUnit, pos, invincibility) ->
if invincibility > 0
ctx.fillStyle = '#FFF'
else
ctx.fillStyle = '#AEEE00'
ctx.beginPath()
radius = 0.01
ctx.arc(pos.x*pixelsPerUnit, pos.y*pixelsPerUnit, radius*pixelsPerUnit, 0, Math.PI * 2)
ctx.closePath()
ctx.fill()
# ctx.fillRect(pos.x*pixelsPerUnit-sidelength/2,pos.y*pixelsPerUnit-sidelength/2,sidelength,sidelength)
drawBeat = (ctx, pixelsPerUnit, pos, percentage, type) ->
ctx.fillStyle = typeColors[type]
# ctx.strokeStyle = typeColors[type]
ctx.beginPath()
radius = 0.01 * percentage# + (0.001*type)
ctx.arc(pos.x*pixelsPerUnit, pos.y*pixelsPerUnit, radius*pixelsPerUnit, 0, Math.PI * 2)
ctx.closePath()
ctx.fill()
drawTatum = (ctx, pixelsPerUnit, pos, type) ->
ctx.fillStyle = typeColors[type]
ctx.beginPath()
radius = 0.005
ctx.arc(pos.x*pixelsPerUnit, pos.y*pixelsPerUnit, radius*pixelsPerUnit, 0, Math.PI * 2)
ctx.closePath()
ctx.fill()
drawCenterTatum = (ctx, pixelsPerUnit, radius, pos) ->
ctx.fillStyle = '#FFF'
ctx.beginPath()
ctx.arc(pos.x*pixelsPerUnit, pos.y*pixelsPerUnit, radius*pixelsPerUnit, 0, Math.PI * 2)
ctx.closePath()
ctx.fill()
spiralToCartesian = (spins, spinTheta, center) ->
x: Math.cos(spins*2*Math.PI - spinTheta) * spins*2*Math.PI * 0.01 + center.x
y: Math.sin(spins*2*Math.PI - spinTheta) * spins*2*Math.PI * 0.01 + center.y
circleToCartesian = (time, maxTime, radius, spinTheta, center) ->
theta = time/maxTime * 2 * Math.PI - Math.PI/2
{x: Math.cos(theta - spinTheta)*radius + center.x
y: Math.sin(theta - spinTheta)*radius + center.y}
audioLoaded = false
audioPlaying = false
audioInfo = null
audioPlayer = null
chosenSongInfo = null
guar = (ctx, G, dt) ->
pixelsPerUnit = G.screenDims.widthPX;
unless audioLoaded
audioInfo = STATE.song_analyses.read()
songIndex = 0
if not audioInfo? or audioInfo.length <= songIndex
print "NOT ENOUGH HITS"
if audioInfo? and audioInfo.length > songIndex
chosenSongInfo = audioInfo[songIndex]
audioPlayer = new Audio(chosenSongInfo.song_info.track_url+'/download')
# audioPlayer.preload = true
G.audio.beats = chosenSongInfo.analysis.beats
G.audio.bars = chosenSongInfo.analysis.bars
G.audio.tatums = chosenSongInfo.analysis.tatums
G.audio.segments = chosenSongInfo.analysis.segments
audioLoaded = true
audioPlayer.currentTime = G.elapsedTime
audioPlayer.oncanplay = () ->
unless audioPlaying
audioPlayer.play()
audioPlayer.currentTime = G.elapsedTime
audioPlaying = true
# print(audioPlayer.currentTime)
if audioPlaying
G = gameplayLoop(ctx, G, dt)
else
clearScreen(ctx, G.screenDims,0)
ctx.textAlign="left";
ctx.fillStyle = '#000'
ctx.font="20px Open Sans";
ctx.fillText("Loading...",10,30);
# ms Counter
# ctx.textAlign="right";
# ctx.fillStyle = '#000'
# ctx.font="20px Open Sans";
# ctx.fillText(parseInt(dt*10)/10,pixelsPerUnit * (G.worldDims.width-0.01),30);
if chosenSongInfo != null
ctx.textAlign="right";
ctx.fillStyle = '#000'
ctx.font="20px Open Sans";
ctx.fillText('music by',pixelsPerUnit * (G.worldDims.width-0.01),pixelsPerUnit * (G.worldDims.height-0.07));
ctx.fillText(chosenSongInfo.song_info.artist_name,pixelsPerUnit * (G.worldDims.width-0.01),pixelsPerUnit * (G.worldDims.height-0.04));
ctx.fillText(chosenSongInfo.song_info.track_title,pixelsPerUnit * (G.worldDims.width-0.01),pixelsPerUnit * (G.worldDims.height-0.02));
ctx.textAlign="left";
ctx.fillText("crafted by Julian Ceipek",pixelsPerUnit * (0.01),pixelsPerUnit * (G.worldDims.height-0.02));
P.swapBuffers()
G
# a b c d e
# 01 23 45 67 89
beatType = (index, difficulty) ->
if difficulty < 5
if Math.floor(index/(5 - difficulty)) % 2 == 0
return 1
return 0
if difficulty < 10
if difficulty % 2 == 0
if index % 2 == 0
return 1
if Math.floor(index/2) % 2 == 0
return 1
return 0
if difficulty % 3 == 0
if index % 2 == 0
return 1
return 0
if Math.floor(index/2) % 2 == 0
return 1
return 0
gameplayLoop = (ctx, G, dt) ->
pixelsPerUnit = G.screenDims.widthPX;
center = {
x: G.worldDims.width/2
y: G.worldDims.height/2
}
if G.didGetHitTimer > 0
G.didGetHitTimer -= dt
if G.didGetHitTimer <= 0
G.elapsedTime = Math.max(G.elapsedTime - 0.3, G.levelTime * (G.levelIndex - 1) )
audioPlayer.currentTime = G.elapsedTime
audioPlayer.play()
else if not G.isPaused
if Math.ceil(audioPlayer.duration/G.levelTime) > G.elapsedTime/G.levelTime
G.elapsedTime += dt/1000
else
G.elapsedTime = Math.ceil(audioPlayer.duration/G.levelTime) * G.levelTime
# if G.elapsedTime - audioPlayer.currentTime > 0
# G.elapsedTime = audioPlayer.currentTime
if G.input.change
if G.isPaused
G.isPaused = false
audioPlayer.currentTime = G.elapsedTime
audioPlayer.play()
else
G.player.type += 1
G.player.type = G.player.type % G.player.totalTypes
unless G.isPaused
if G.elapsedTime > G.levelTime * G.levelIndex
G.levelIndex += 1
# G.isPaused = true
# audioPlayer.pause()
# Clear the bg
clearScreen(ctx, G.screenDims, G.player.type)
G.audio.beatIndex = 0
while G.audio.beats.length > G.audio.beatIndex+1 and G.audio.beats[G.audio.beatIndex]? and G.audio.beats[G.audio.beatIndex].start < G.elapsedTime
# print(G.audio.beats[G.audio.beatIndex])
G.audio.beatIndex++
# print(G.audio.beatIndex)
G.worldRot = G.elapsedTime * 0.1
G.worldRot = G.worldRot % (2*Math.PI) # Wrap around
ctx.strokeStyle = '#000'
ctx.lineWidth = 0.004 * pixelsPerUnit
ctx.beginPath()
scaler = 0.02 * Math.sin(G.audio.beats[G.audio.beatIndex].duration - (G.elapsedTime - G.audio.beats[G.audio.beatIndex].start))
radius = 0.30 + scaler
ctx.arc(center.x * pixelsPerUnit, center.y * pixelsPerUnit, radius * pixelsPerUnit, 0, 2 * Math.PI)
ctx.stroke()
ctx.fillStyle = '#000'
ctx.beginPath()
x = Math.cos(Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.6 + center.x
y = Math.sin(Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.6 + center.y
ctx.moveTo(x * pixelsPerUnit, y * pixelsPerUnit)
x = Math.cos(Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.8 + center.x
y = Math.sin(Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.8 + center.y
ctx.lineTo(x * pixelsPerUnit, y * pixelsPerUnit)
ctx.arc(center.x * pixelsPerUnit, center.y * pixelsPerUnit, radius*0.8 * pixelsPerUnit,
(Math.PI * 2 - Math.PI/2 - G.worldRot) % (Math.PI * 2),
(G.elapsedTime/(G.levelTime) * 2 * Math.PI - Math.PI/2+0.001 - G.worldRot) % (Math.PI * 2))
x = Math.cos(G.elapsedTime/G.levelTime * Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.6 + center.x
y = Math.sin(G.elapsedTime/G.levelTime * Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.6 + center.y
ctx.lineTo(x * pixelsPerUnit, y * pixelsPerUnit)
ctx.arc(center.x * pixelsPerUnit, center.y * pixelsPerUnit, radius*0.6 * pixelsPerUnit,
(G.elapsedTime/(G.levelTime) * 2 * Math.PI - Math.PI/2+0.001 - G.worldRot) % (Math.PI * 2),
(Math.PI * 2 - Math.PI/2 - G.worldRot) % (Math.PI * 2))
# ctx.arc(center.x * pixelsPerUnit, center.y * pixelsPerUnit, radius * pixelsPerUnit, 0, 2 * Math.PI)
# x = Math.cos(Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.6 + center.x
# y = Math.sin(Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.6 + center.y
# ctx.lineTo(x * pixelsPerUnit, y * pixelsPerUnit)
ctx.fill()
playerPos = circleToCartesian(G.elapsedTime, G.levelTime, radius, G.worldRot, center)
playerPosInner = circleToCartesian(G.elapsedTime, G.levelTime, radius/2, G.worldRot, center)
ctx.strokeStyle = '#000'
ctx.beginPath()
ctx.moveTo(playerPos.x * pixelsPerUnit, playerPos.y * pixelsPerUnit)
ctx.lineTo(center.x*pixelsPerUnit, center.y*pixelsPerUnit)
# ctx.closePath()
ctx.stroke()
tatumIndex = 0
while G.audio.tatums.length > tatumIndex+1 and G.audio.tatums[tatumIndex]? and G.audio.tatums[tatumIndex].start < audioPlayer.currentTime
# print(G.audio.beats[G.audio.beatIndex])
tatumIndex++
tatumScaler = 0.05 * Math.sin(G.audio.tatums[tatumIndex].duration - (audioPlayer.currentTime - G.audio.tatums[tatumIndex].start))
tatumRadius = 0.06 + tatumScaler
drawCenterTatum(ctx, pixelsPerUnit, tatumRadius, center)
if G.invincibilityTimer > 0
G.invincibilityTimer -= dt
for beat,i in G.audio.beats
if beat?
t = beatType(i, Math.floor(beat.start/G.levelTime)) #(if beat.confidence > 0.6 then 1 else 0)
# if beat.start < (G.levelTime * G.levelIndex) and beat.start > (G.levelTime * (G.levelIndex - 1)) #and beat.start > G.elapsedTime
pos = circleToCartesian(beat.start, G.levelTime, radius, G.worldRot, center)
percentage = 0
if Math.abs(beat.start - G.elapsedTime) < G.levelTime*0.2
percentage = 1-Math.abs((beat.start - G.elapsedTime))/(G.levelTime*0.2)
percentage = Math.max(Math.min(percentage, 1), 0)
drawBeat(ctx, pixelsPerUnit, pos, percentage, t)
if G.invincibilityTimer <= 0 and Math.abs(G.elapsedTime - beat.start) <= G.player.collisionRadius and t != G.player.type
# print 'die'
audioPlayer.pause()
G.invincibilityTimer = (1/60*1000) * 30
G.didGetHitTimer = (1/60*1000) * 20
# else if beat.start < (G.levelTime * (G.levelIndex+1)) and beat.start > (G.levelTime * (G.levelIndex))
# pos = circleToCartesian(beat.start, G.levelTime, radius/2, -G.worldRot, center)
# drawBeat(ctx, pixelsPerUnit, pos, 0.5, t)
# for tatum in G.audio.tatums
# if tatum? and tatum.start < G.levelTime
# pos = circleToCartesian(tatum.start, G.levelTime, radius, G.worldRot, center)
# t = (if tatum.confidence > 0.6 then 1 else 0)
# drawTatum(ctx, pixelsPerUnit, pos, t)
# if Math.abs((G.elapsedTime % G.levelTime) - beat.start) <= G.player.collisionRadius and t != G.player.type
# print 'die'
# G.elapsedTime -= 1
# audioPlayer.currentTime = G.elapsedTime
playerPos = circleToCartesian(G.elapsedTime, G.levelTime, radius*1.02, G.worldRot, center)
drawEntityNew(ctx, pixelsPerUnit, playerPos, playerPosInner, G.invincibilityTimer)
# drawEntity(ctx, pixelsPerUnit, playerPos, G.invincibilityTimer)
# levelTime
# ctx.beginPath();
# ctx.moveTo(center.x*pixelsPerUnit, center.y*pixelsPerUnit);
# ctx.strokeStyle = '#000'
# ctx.lineWidth = 4
# spiralRings = 5
# last = {}
# for t in [0..spiralRings] by 0.01
# {x: x, y: y} = spiralToCartesian(t, G.worldRot, center)
# ctx.lineTo(x*pixelsPerUnit, y*pixelsPerUnit)
# ctx.stroke()
# v = 2*Math.PI*0.005/4 # speed for approx 10 sec; TODO(JULIAN): Make Exact
# playerRotSpeed = if G.playerPos.theta<=0 then 0 else v/(2*Math.PI * G.playerPos.theta)
# beatTime = 0
# beatRot = 5
# while beatTime < 2
# beatRotSpeed = if beatRot<=0 then 0 else v/(2*Math.PI * beatRot)
# drawBeat(ctx, pixelsPerUnit, spiralToCartesian(beatRot, G.worldRot, center))
# beatRot -= 16 * beatRotSpeed
# beatTime += v
# console.log(G.playerPos.theta)
# G.playerPos.theta -= dt * playerRotSpeed
# G.playerPos.theta = G.playerPos.theta % (2*Math.PI)
# pos = spiralToCartesian(G.playerPos.theta, G.worldRot, center)
# drawEntity(ctx, pixelsPerUnit, pos)
# console.log(G.playerPos.x)
if G.isPaused
ctx.textAlign="center";
ctx.fillStyle = '#000'
ctx.font="20px Open Sans";
ctx.fillText('[SPACE]',pixelsPerUnit * center.x,pixelsPerUnit * center.y + 7);
G
window.requestAnimationFrame step | 106635 | require.config({
baseUrl: 'javascripts'
paths: {
jquery: 'jquery-1.11.2.min'
}
})
require ['./state', 'jquery'], (STATE, $) ->
DEBUG = true
print = (x) ->
if DEBUG
console.log(x)
ECHONEST_ID = 'YSN67FHUAZZDWQBSL'
initSongData = (cb) ->
url = 'http://developer.echonest.com/api/v4/song/search?' +
(['api_key='+ECHONEST_ID
'format=json'
'results=1'
'min_tempo=120'
'mood=excited'
'sort=song_hotttnesss-desc'
'bucket=id:fma'
'bucket=tracks'
'limit=true'
].join('&'))
await $.getJSON(url, defer res )
fmaData = []
songList = res.response.songs
print(songList)
await
for song,i in songList
url = 'http://freemusicarchive.org/api/get/tracks.jsonp?'
$.ajax({
url: url
jsonp: "callback"
dataType: "jsonp"
data: ([
'api_key=<KEY>'
'track_id='+song.tracks[0].foreign_id[('fma:track:'.length)..]
].join('&'))
success: defer(fmaData[i])
error: (e) -> console.log(e.message)
})
print(fmaData)
songFiles = (({ artist_name: song.dataset[0].artist_name, track_title: song.dataset[0].track_title, track_url: song.dataset[0].track_url, track_id: songList[i].tracks[0].id}) for song,i in fmaData)
console.log(songFiles)
STATE.songs.set(songFiles)
cb(songFiles)
initSongAnalysis = (songInfo) ->
songAnalyses = []
for track in songInfo
url = 'http://developer.echonest.com/api/v4/track/profile?' +
(['api_key='+ECHONEST_ID
'format=json'
'id='+track.track_id
'bucket=audio_summary'
].join('&'))
await $.getJSON(url, defer res )
await $.getJSON(res.response.track.audio_summary.analysis_url, defer res )
songAnalyses.push({song_info: track, analysis: res})
STATE.song_analyses.set(songAnalyses)
initGameData = () ->
gs = {
levelIndex: 1
isPaused: true
invincibilityTimer: 0
didGetHitTimer: 0
levelTime: 10
elapsedTime: -2
audio: {
beatIndex: 0
beats: []
bars: []
tatums: []
segments: []
}
worldRot: 0
player: {
type: 0
totalTypes: 2
collisionRadius: 0.05
}
screenDims: {
widthPX: 1024
heightPX: 768
}
worldDims: {
width: 1
height: 3/4
}
input: {
change: false
}
}
STATE.set(gs)
# unless STATE.songs.read()?
initSongData((songData) -> initSongAnalysis(STATE.songs.read()))
# STATE.songs.set('')
# initSongData()
# initSongAnalysis(STATE.songs.read())
console.log(STATE.song_analyses.read())
document.getElementById('loading-msg').remove()
# unless STATE.read()?
initGameData()
# else print("GAME NOT INITIALIZED")
P = (() ->
gameScreenCanvas = document.getElementById('game')
backBufferCanvas = document.createElement('canvas')
G = STATE.read()
$(gameScreenCanvas).attr('width', G.screenDims.widthPX)
$(gameScreenCanvas).attr('height', G.screenDims.heightPX)
$(backBufferCanvas).attr('width', G.screenDims.widthPX)
$(backBufferCanvas).attr('height', G.screenDims.heightPX)
backBufferCanvas.width = G.screenDims.widthPX
backBufferCanvas.width = G.screenDims.widthPX
backBufferCanvas.height = G.screenDims.heightPX
backBufferCanvas.height = G.screenDims.heightPX
backBuffer = backBufferCanvas.getContext('2d')
gameScreen = gameScreenCanvas.getContext('2d')
events = []
$(window).keydown (e) ->
events.push(e)
if e.keyCode is 32
e.preventDefault()
{
swapBuffers: () -> gameScreen.drawImage(backBufferCanvas, 0, 0)
backBuffer: backBuffer
readInput: () ->
read = events
events = []
read
}
)()
step = (() ->
lastTimestamp = null
(timestamp) ->
elapsed = timestamp - lastTimestamp
G = guar(P.backBuffer, STATE.read(), elapsed)
G.input = {}
es = P.readInput()
for e in es
if e.keyCode is 32
G.input.change = true
STATE.set(G)
lastTimestamp = timestamp
window.requestAnimationFrame step)()
typeColors = ['#FC3A8B', '#01B0F0'] #['#FFF', '#000']
clearScreen = (ctx, screenDims, type) ->
ctx.fillStyle = typeColors[type]
ctx.fillRect(0,0, screenDims.widthPX,
screenDims.heightPX)
drawEntityNew = (ctx, pixelsPerUnit, posOuter, posInner, invincibility) ->
if invincibility > 0
ctx.strokeStyle = '#FFF'
else
ctx.strokeStyle = '#AEEE00'
ctx.beginPath()
ctx.moveTo(posInner.x*pixelsPerUnit, posInner.y*pixelsPerUnit)
ctx.lineTo(posOuter.x*pixelsPerUnit, posOuter.y*pixelsPerUnit)
# radius = 0.01
# ctx.arc(pos.x*pixelsPerUnit, pos.y*pixelsPerUnit, radius*pixelsPerUnit, 0, Math.PI * 2)
# ctx.closePath()
ctx.stroke()
drawEntity = (ctx, pixelsPerUnit, pos, invincibility) ->
if invincibility > 0
ctx.fillStyle = '#FFF'
else
ctx.fillStyle = '#AEEE00'
ctx.beginPath()
radius = 0.01
ctx.arc(pos.x*pixelsPerUnit, pos.y*pixelsPerUnit, radius*pixelsPerUnit, 0, Math.PI * 2)
ctx.closePath()
ctx.fill()
# ctx.fillRect(pos.x*pixelsPerUnit-sidelength/2,pos.y*pixelsPerUnit-sidelength/2,sidelength,sidelength)
drawBeat = (ctx, pixelsPerUnit, pos, percentage, type) ->
ctx.fillStyle = typeColors[type]
# ctx.strokeStyle = typeColors[type]
ctx.beginPath()
radius = 0.01 * percentage# + (0.001*type)
ctx.arc(pos.x*pixelsPerUnit, pos.y*pixelsPerUnit, radius*pixelsPerUnit, 0, Math.PI * 2)
ctx.closePath()
ctx.fill()
drawTatum = (ctx, pixelsPerUnit, pos, type) ->
ctx.fillStyle = typeColors[type]
ctx.beginPath()
radius = 0.005
ctx.arc(pos.x*pixelsPerUnit, pos.y*pixelsPerUnit, radius*pixelsPerUnit, 0, Math.PI * 2)
ctx.closePath()
ctx.fill()
drawCenterTatum = (ctx, pixelsPerUnit, radius, pos) ->
ctx.fillStyle = '#FFF'
ctx.beginPath()
ctx.arc(pos.x*pixelsPerUnit, pos.y*pixelsPerUnit, radius*pixelsPerUnit, 0, Math.PI * 2)
ctx.closePath()
ctx.fill()
spiralToCartesian = (spins, spinTheta, center) ->
x: Math.cos(spins*2*Math.PI - spinTheta) * spins*2*Math.PI * 0.01 + center.x
y: Math.sin(spins*2*Math.PI - spinTheta) * spins*2*Math.PI * 0.01 + center.y
circleToCartesian = (time, maxTime, radius, spinTheta, center) ->
theta = time/maxTime * 2 * Math.PI - Math.PI/2
{x: Math.cos(theta - spinTheta)*radius + center.x
y: Math.sin(theta - spinTheta)*radius + center.y}
audioLoaded = false
audioPlaying = false
audioInfo = null
audioPlayer = null
chosenSongInfo = null
guar = (ctx, G, dt) ->
pixelsPerUnit = G.screenDims.widthPX;
unless audioLoaded
audioInfo = STATE.song_analyses.read()
songIndex = 0
if not audioInfo? or audioInfo.length <= songIndex
print "NOT ENOUGH HITS"
if audioInfo? and audioInfo.length > songIndex
chosenSongInfo = audioInfo[songIndex]
audioPlayer = new Audio(chosenSongInfo.song_info.track_url+'/download')
# audioPlayer.preload = true
G.audio.beats = chosenSongInfo.analysis.beats
G.audio.bars = chosenSongInfo.analysis.bars
G.audio.tatums = chosenSongInfo.analysis.tatums
G.audio.segments = chosenSongInfo.analysis.segments
audioLoaded = true
audioPlayer.currentTime = G.elapsedTime
audioPlayer.oncanplay = () ->
unless audioPlaying
audioPlayer.play()
audioPlayer.currentTime = G.elapsedTime
audioPlaying = true
# print(audioPlayer.currentTime)
if audioPlaying
G = gameplayLoop(ctx, G, dt)
else
clearScreen(ctx, G.screenDims,0)
ctx.textAlign="left";
ctx.fillStyle = '#000'
ctx.font="20px Open Sans";
ctx.fillText("Loading...",10,30);
# ms Counter
# ctx.textAlign="right";
# ctx.fillStyle = '#000'
# ctx.font="20px Open Sans";
# ctx.fillText(parseInt(dt*10)/10,pixelsPerUnit * (G.worldDims.width-0.01),30);
if chosenSongInfo != null
ctx.textAlign="right";
ctx.fillStyle = '#000'
ctx.font="20px Open Sans";
ctx.fillText('music by',pixelsPerUnit * (G.worldDims.width-0.01),pixelsPerUnit * (G.worldDims.height-0.07));
ctx.fillText(chosenSongInfo.song_info.artist_name,pixelsPerUnit * (G.worldDims.width-0.01),pixelsPerUnit * (G.worldDims.height-0.04));
ctx.fillText(chosenSongInfo.song_info.track_title,pixelsPerUnit * (G.worldDims.width-0.01),pixelsPerUnit * (G.worldDims.height-0.02));
ctx.textAlign="left";
ctx.fillText("crafted by <NAME>",pixelsPerUnit * (0.01),pixelsPerUnit * (G.worldDims.height-0.02));
P.swapBuffers()
G
# a b c d e
# 01 23 45 67 89
beatType = (index, difficulty) ->
if difficulty < 5
if Math.floor(index/(5 - difficulty)) % 2 == 0
return 1
return 0
if difficulty < 10
if difficulty % 2 == 0
if index % 2 == 0
return 1
if Math.floor(index/2) % 2 == 0
return 1
return 0
if difficulty % 3 == 0
if index % 2 == 0
return 1
return 0
if Math.floor(index/2) % 2 == 0
return 1
return 0
gameplayLoop = (ctx, G, dt) ->
pixelsPerUnit = G.screenDims.widthPX;
center = {
x: G.worldDims.width/2
y: G.worldDims.height/2
}
if G.didGetHitTimer > 0
G.didGetHitTimer -= dt
if G.didGetHitTimer <= 0
G.elapsedTime = Math.max(G.elapsedTime - 0.3, G.levelTime * (G.levelIndex - 1) )
audioPlayer.currentTime = G.elapsedTime
audioPlayer.play()
else if not G.isPaused
if Math.ceil(audioPlayer.duration/G.levelTime) > G.elapsedTime/G.levelTime
G.elapsedTime += dt/1000
else
G.elapsedTime = Math.ceil(audioPlayer.duration/G.levelTime) * G.levelTime
# if G.elapsedTime - audioPlayer.currentTime > 0
# G.elapsedTime = audioPlayer.currentTime
if G.input.change
if G.isPaused
G.isPaused = false
audioPlayer.currentTime = G.elapsedTime
audioPlayer.play()
else
G.player.type += 1
G.player.type = G.player.type % G.player.totalTypes
unless G.isPaused
if G.elapsedTime > G.levelTime * G.levelIndex
G.levelIndex += 1
# G.isPaused = true
# audioPlayer.pause()
# Clear the bg
clearScreen(ctx, G.screenDims, G.player.type)
G.audio.beatIndex = 0
while G.audio.beats.length > G.audio.beatIndex+1 and G.audio.beats[G.audio.beatIndex]? and G.audio.beats[G.audio.beatIndex].start < G.elapsedTime
# print(G.audio.beats[G.audio.beatIndex])
G.audio.beatIndex++
# print(G.audio.beatIndex)
G.worldRot = G.elapsedTime * 0.1
G.worldRot = G.worldRot % (2*Math.PI) # Wrap around
ctx.strokeStyle = '#000'
ctx.lineWidth = 0.004 * pixelsPerUnit
ctx.beginPath()
scaler = 0.02 * Math.sin(G.audio.beats[G.audio.beatIndex].duration - (G.elapsedTime - G.audio.beats[G.audio.beatIndex].start))
radius = 0.30 + scaler
ctx.arc(center.x * pixelsPerUnit, center.y * pixelsPerUnit, radius * pixelsPerUnit, 0, 2 * Math.PI)
ctx.stroke()
ctx.fillStyle = '#000'
ctx.beginPath()
x = Math.cos(Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.6 + center.x
y = Math.sin(Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.6 + center.y
ctx.moveTo(x * pixelsPerUnit, y * pixelsPerUnit)
x = Math.cos(Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.8 + center.x
y = Math.sin(Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.8 + center.y
ctx.lineTo(x * pixelsPerUnit, y * pixelsPerUnit)
ctx.arc(center.x * pixelsPerUnit, center.y * pixelsPerUnit, radius*0.8 * pixelsPerUnit,
(Math.PI * 2 - Math.PI/2 - G.worldRot) % (Math.PI * 2),
(G.elapsedTime/(G.levelTime) * 2 * Math.PI - Math.PI/2+0.001 - G.worldRot) % (Math.PI * 2))
x = Math.cos(G.elapsedTime/G.levelTime * Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.6 + center.x
y = Math.sin(G.elapsedTime/G.levelTime * Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.6 + center.y
ctx.lineTo(x * pixelsPerUnit, y * pixelsPerUnit)
ctx.arc(center.x * pixelsPerUnit, center.y * pixelsPerUnit, radius*0.6 * pixelsPerUnit,
(G.elapsedTime/(G.levelTime) * 2 * Math.PI - Math.PI/2+0.001 - G.worldRot) % (Math.PI * 2),
(Math.PI * 2 - Math.PI/2 - G.worldRot) % (Math.PI * 2))
# ctx.arc(center.x * pixelsPerUnit, center.y * pixelsPerUnit, radius * pixelsPerUnit, 0, 2 * Math.PI)
# x = Math.cos(Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.6 + center.x
# y = Math.sin(Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.6 + center.y
# ctx.lineTo(x * pixelsPerUnit, y * pixelsPerUnit)
ctx.fill()
playerPos = circleToCartesian(G.elapsedTime, G.levelTime, radius, G.worldRot, center)
playerPosInner = circleToCartesian(G.elapsedTime, G.levelTime, radius/2, G.worldRot, center)
ctx.strokeStyle = '#000'
ctx.beginPath()
ctx.moveTo(playerPos.x * pixelsPerUnit, playerPos.y * pixelsPerUnit)
ctx.lineTo(center.x*pixelsPerUnit, center.y*pixelsPerUnit)
# ctx.closePath()
ctx.stroke()
tatumIndex = 0
while G.audio.tatums.length > tatumIndex+1 and G.audio.tatums[tatumIndex]? and G.audio.tatums[tatumIndex].start < audioPlayer.currentTime
# print(G.audio.beats[G.audio.beatIndex])
tatumIndex++
tatumScaler = 0.05 * Math.sin(G.audio.tatums[tatumIndex].duration - (audioPlayer.currentTime - G.audio.tatums[tatumIndex].start))
tatumRadius = 0.06 + tatumScaler
drawCenterTatum(ctx, pixelsPerUnit, tatumRadius, center)
if G.invincibilityTimer > 0
G.invincibilityTimer -= dt
for beat,i in G.audio.beats
if beat?
t = beatType(i, Math.floor(beat.start/G.levelTime)) #(if beat.confidence > 0.6 then 1 else 0)
# if beat.start < (G.levelTime * G.levelIndex) and beat.start > (G.levelTime * (G.levelIndex - 1)) #and beat.start > G.elapsedTime
pos = circleToCartesian(beat.start, G.levelTime, radius, G.worldRot, center)
percentage = 0
if Math.abs(beat.start - G.elapsedTime) < G.levelTime*0.2
percentage = 1-Math.abs((beat.start - G.elapsedTime))/(G.levelTime*0.2)
percentage = Math.max(Math.min(percentage, 1), 0)
drawBeat(ctx, pixelsPerUnit, pos, percentage, t)
if G.invincibilityTimer <= 0 and Math.abs(G.elapsedTime - beat.start) <= G.player.collisionRadius and t != G.player.type
# print 'die'
audioPlayer.pause()
G.invincibilityTimer = (1/60*1000) * 30
G.didGetHitTimer = (1/60*1000) * 20
# else if beat.start < (G.levelTime * (G.levelIndex+1)) and beat.start > (G.levelTime * (G.levelIndex))
# pos = circleToCartesian(beat.start, G.levelTime, radius/2, -G.worldRot, center)
# drawBeat(ctx, pixelsPerUnit, pos, 0.5, t)
# for tatum in G.audio.tatums
# if tatum? and tatum.start < G.levelTime
# pos = circleToCartesian(tatum.start, G.levelTime, radius, G.worldRot, center)
# t = (if tatum.confidence > 0.6 then 1 else 0)
# drawTatum(ctx, pixelsPerUnit, pos, t)
# if Math.abs((G.elapsedTime % G.levelTime) - beat.start) <= G.player.collisionRadius and t != G.player.type
# print 'die'
# G.elapsedTime -= 1
# audioPlayer.currentTime = G.elapsedTime
playerPos = circleToCartesian(G.elapsedTime, G.levelTime, radius*1.02, G.worldRot, center)
drawEntityNew(ctx, pixelsPerUnit, playerPos, playerPosInner, G.invincibilityTimer)
# drawEntity(ctx, pixelsPerUnit, playerPos, G.invincibilityTimer)
# levelTime
# ctx.beginPath();
# ctx.moveTo(center.x*pixelsPerUnit, center.y*pixelsPerUnit);
# ctx.strokeStyle = '#000'
# ctx.lineWidth = 4
# spiralRings = 5
# last = {}
# for t in [0..spiralRings] by 0.01
# {x: x, y: y} = spiralToCartesian(t, G.worldRot, center)
# ctx.lineTo(x*pixelsPerUnit, y*pixelsPerUnit)
# ctx.stroke()
# v = 2*Math.PI*0.005/4 # speed for approx 10 sec; TODO(JULIAN): Make Exact
# playerRotSpeed = if G.playerPos.theta<=0 then 0 else v/(2*Math.PI * G.playerPos.theta)
# beatTime = 0
# beatRot = 5
# while beatTime < 2
# beatRotSpeed = if beatRot<=0 then 0 else v/(2*Math.PI * beatRot)
# drawBeat(ctx, pixelsPerUnit, spiralToCartesian(beatRot, G.worldRot, center))
# beatRot -= 16 * beatRotSpeed
# beatTime += v
# console.log(G.playerPos.theta)
# G.playerPos.theta -= dt * playerRotSpeed
# G.playerPos.theta = G.playerPos.theta % (2*Math.PI)
# pos = spiralToCartesian(G.playerPos.theta, G.worldRot, center)
# drawEntity(ctx, pixelsPerUnit, pos)
# console.log(G.playerPos.x)
if G.isPaused
ctx.textAlign="center";
ctx.fillStyle = '#000'
ctx.font="20px Open Sans";
ctx.fillText('[SPACE]',pixelsPerUnit * center.x,pixelsPerUnit * center.y + 7);
G
window.requestAnimationFrame step | true | require.config({
baseUrl: 'javascripts'
paths: {
jquery: 'jquery-1.11.2.min'
}
})
require ['./state', 'jquery'], (STATE, $) ->
DEBUG = true
print = (x) ->
if DEBUG
console.log(x)
ECHONEST_ID = 'YSN67FHUAZZDWQBSL'
initSongData = (cb) ->
url = 'http://developer.echonest.com/api/v4/song/search?' +
(['api_key='+ECHONEST_ID
'format=json'
'results=1'
'min_tempo=120'
'mood=excited'
'sort=song_hotttnesss-desc'
'bucket=id:fma'
'bucket=tracks'
'limit=true'
].join('&'))
await $.getJSON(url, defer res )
fmaData = []
songList = res.response.songs
print(songList)
await
for song,i in songList
url = 'http://freemusicarchive.org/api/get/tracks.jsonp?'
$.ajax({
url: url
jsonp: "callback"
dataType: "jsonp"
data: ([
'api_key=PI:KEY:<KEY>END_PI'
'track_id='+song.tracks[0].foreign_id[('fma:track:'.length)..]
].join('&'))
success: defer(fmaData[i])
error: (e) -> console.log(e.message)
})
print(fmaData)
songFiles = (({ artist_name: song.dataset[0].artist_name, track_title: song.dataset[0].track_title, track_url: song.dataset[0].track_url, track_id: songList[i].tracks[0].id}) for song,i in fmaData)
console.log(songFiles)
STATE.songs.set(songFiles)
cb(songFiles)
initSongAnalysis = (songInfo) ->
songAnalyses = []
for track in songInfo
url = 'http://developer.echonest.com/api/v4/track/profile?' +
(['api_key='+ECHONEST_ID
'format=json'
'id='+track.track_id
'bucket=audio_summary'
].join('&'))
await $.getJSON(url, defer res )
await $.getJSON(res.response.track.audio_summary.analysis_url, defer res )
songAnalyses.push({song_info: track, analysis: res})
STATE.song_analyses.set(songAnalyses)
initGameData = () ->
gs = {
levelIndex: 1
isPaused: true
invincibilityTimer: 0
didGetHitTimer: 0
levelTime: 10
elapsedTime: -2
audio: {
beatIndex: 0
beats: []
bars: []
tatums: []
segments: []
}
worldRot: 0
player: {
type: 0
totalTypes: 2
collisionRadius: 0.05
}
screenDims: {
widthPX: 1024
heightPX: 768
}
worldDims: {
width: 1
height: 3/4
}
input: {
change: false
}
}
STATE.set(gs)
# unless STATE.songs.read()?
initSongData((songData) -> initSongAnalysis(STATE.songs.read()))
# STATE.songs.set('')
# initSongData()
# initSongAnalysis(STATE.songs.read())
console.log(STATE.song_analyses.read())
document.getElementById('loading-msg').remove()
# unless STATE.read()?
initGameData()
# else print("GAME NOT INITIALIZED")
P = (() ->
gameScreenCanvas = document.getElementById('game')
backBufferCanvas = document.createElement('canvas')
G = STATE.read()
$(gameScreenCanvas).attr('width', G.screenDims.widthPX)
$(gameScreenCanvas).attr('height', G.screenDims.heightPX)
$(backBufferCanvas).attr('width', G.screenDims.widthPX)
$(backBufferCanvas).attr('height', G.screenDims.heightPX)
backBufferCanvas.width = G.screenDims.widthPX
backBufferCanvas.width = G.screenDims.widthPX
backBufferCanvas.height = G.screenDims.heightPX
backBufferCanvas.height = G.screenDims.heightPX
backBuffer = backBufferCanvas.getContext('2d')
gameScreen = gameScreenCanvas.getContext('2d')
events = []
$(window).keydown (e) ->
events.push(e)
if e.keyCode is 32
e.preventDefault()
{
swapBuffers: () -> gameScreen.drawImage(backBufferCanvas, 0, 0)
backBuffer: backBuffer
readInput: () ->
read = events
events = []
read
}
)()
step = (() ->
lastTimestamp = null
(timestamp) ->
elapsed = timestamp - lastTimestamp
G = guar(P.backBuffer, STATE.read(), elapsed)
G.input = {}
es = P.readInput()
for e in es
if e.keyCode is 32
G.input.change = true
STATE.set(G)
lastTimestamp = timestamp
window.requestAnimationFrame step)()
typeColors = ['#FC3A8B', '#01B0F0'] #['#FFF', '#000']
clearScreen = (ctx, screenDims, type) ->
ctx.fillStyle = typeColors[type]
ctx.fillRect(0,0, screenDims.widthPX,
screenDims.heightPX)
drawEntityNew = (ctx, pixelsPerUnit, posOuter, posInner, invincibility) ->
if invincibility > 0
ctx.strokeStyle = '#FFF'
else
ctx.strokeStyle = '#AEEE00'
ctx.beginPath()
ctx.moveTo(posInner.x*pixelsPerUnit, posInner.y*pixelsPerUnit)
ctx.lineTo(posOuter.x*pixelsPerUnit, posOuter.y*pixelsPerUnit)
# radius = 0.01
# ctx.arc(pos.x*pixelsPerUnit, pos.y*pixelsPerUnit, radius*pixelsPerUnit, 0, Math.PI * 2)
# ctx.closePath()
ctx.stroke()
drawEntity = (ctx, pixelsPerUnit, pos, invincibility) ->
if invincibility > 0
ctx.fillStyle = '#FFF'
else
ctx.fillStyle = '#AEEE00'
ctx.beginPath()
radius = 0.01
ctx.arc(pos.x*pixelsPerUnit, pos.y*pixelsPerUnit, radius*pixelsPerUnit, 0, Math.PI * 2)
ctx.closePath()
ctx.fill()
# ctx.fillRect(pos.x*pixelsPerUnit-sidelength/2,pos.y*pixelsPerUnit-sidelength/2,sidelength,sidelength)
drawBeat = (ctx, pixelsPerUnit, pos, percentage, type) ->
ctx.fillStyle = typeColors[type]
# ctx.strokeStyle = typeColors[type]
ctx.beginPath()
radius = 0.01 * percentage# + (0.001*type)
ctx.arc(pos.x*pixelsPerUnit, pos.y*pixelsPerUnit, radius*pixelsPerUnit, 0, Math.PI * 2)
ctx.closePath()
ctx.fill()
drawTatum = (ctx, pixelsPerUnit, pos, type) ->
ctx.fillStyle = typeColors[type]
ctx.beginPath()
radius = 0.005
ctx.arc(pos.x*pixelsPerUnit, pos.y*pixelsPerUnit, radius*pixelsPerUnit, 0, Math.PI * 2)
ctx.closePath()
ctx.fill()
drawCenterTatum = (ctx, pixelsPerUnit, radius, pos) ->
ctx.fillStyle = '#FFF'
ctx.beginPath()
ctx.arc(pos.x*pixelsPerUnit, pos.y*pixelsPerUnit, radius*pixelsPerUnit, 0, Math.PI * 2)
ctx.closePath()
ctx.fill()
spiralToCartesian = (spins, spinTheta, center) ->
x: Math.cos(spins*2*Math.PI - spinTheta) * spins*2*Math.PI * 0.01 + center.x
y: Math.sin(spins*2*Math.PI - spinTheta) * spins*2*Math.PI * 0.01 + center.y
circleToCartesian = (time, maxTime, radius, spinTheta, center) ->
theta = time/maxTime * 2 * Math.PI - Math.PI/2
{x: Math.cos(theta - spinTheta)*radius + center.x
y: Math.sin(theta - spinTheta)*radius + center.y}
audioLoaded = false
audioPlaying = false
audioInfo = null
audioPlayer = null
chosenSongInfo = null
guar = (ctx, G, dt) ->
pixelsPerUnit = G.screenDims.widthPX;
unless audioLoaded
audioInfo = STATE.song_analyses.read()
songIndex = 0
if not audioInfo? or audioInfo.length <= songIndex
print "NOT ENOUGH HITS"
if audioInfo? and audioInfo.length > songIndex
chosenSongInfo = audioInfo[songIndex]
audioPlayer = new Audio(chosenSongInfo.song_info.track_url+'/download')
# audioPlayer.preload = true
G.audio.beats = chosenSongInfo.analysis.beats
G.audio.bars = chosenSongInfo.analysis.bars
G.audio.tatums = chosenSongInfo.analysis.tatums
G.audio.segments = chosenSongInfo.analysis.segments
audioLoaded = true
audioPlayer.currentTime = G.elapsedTime
audioPlayer.oncanplay = () ->
unless audioPlaying
audioPlayer.play()
audioPlayer.currentTime = G.elapsedTime
audioPlaying = true
# print(audioPlayer.currentTime)
if audioPlaying
G = gameplayLoop(ctx, G, dt)
else
clearScreen(ctx, G.screenDims,0)
ctx.textAlign="left";
ctx.fillStyle = '#000'
ctx.font="20px Open Sans";
ctx.fillText("Loading...",10,30);
# ms Counter
# ctx.textAlign="right";
# ctx.fillStyle = '#000'
# ctx.font="20px Open Sans";
# ctx.fillText(parseInt(dt*10)/10,pixelsPerUnit * (G.worldDims.width-0.01),30);
if chosenSongInfo != null
ctx.textAlign="right";
ctx.fillStyle = '#000'
ctx.font="20px Open Sans";
ctx.fillText('music by',pixelsPerUnit * (G.worldDims.width-0.01),pixelsPerUnit * (G.worldDims.height-0.07));
ctx.fillText(chosenSongInfo.song_info.artist_name,pixelsPerUnit * (G.worldDims.width-0.01),pixelsPerUnit * (G.worldDims.height-0.04));
ctx.fillText(chosenSongInfo.song_info.track_title,pixelsPerUnit * (G.worldDims.width-0.01),pixelsPerUnit * (G.worldDims.height-0.02));
ctx.textAlign="left";
ctx.fillText("crafted by PI:NAME:<NAME>END_PI",pixelsPerUnit * (0.01),pixelsPerUnit * (G.worldDims.height-0.02));
P.swapBuffers()
G
# a b c d e
# 01 23 45 67 89
beatType = (index, difficulty) ->
if difficulty < 5
if Math.floor(index/(5 - difficulty)) % 2 == 0
return 1
return 0
if difficulty < 10
if difficulty % 2 == 0
if index % 2 == 0
return 1
if Math.floor(index/2) % 2 == 0
return 1
return 0
if difficulty % 3 == 0
if index % 2 == 0
return 1
return 0
if Math.floor(index/2) % 2 == 0
return 1
return 0
gameplayLoop = (ctx, G, dt) ->
pixelsPerUnit = G.screenDims.widthPX;
center = {
x: G.worldDims.width/2
y: G.worldDims.height/2
}
if G.didGetHitTimer > 0
G.didGetHitTimer -= dt
if G.didGetHitTimer <= 0
G.elapsedTime = Math.max(G.elapsedTime - 0.3, G.levelTime * (G.levelIndex - 1) )
audioPlayer.currentTime = G.elapsedTime
audioPlayer.play()
else if not G.isPaused
if Math.ceil(audioPlayer.duration/G.levelTime) > G.elapsedTime/G.levelTime
G.elapsedTime += dt/1000
else
G.elapsedTime = Math.ceil(audioPlayer.duration/G.levelTime) * G.levelTime
# if G.elapsedTime - audioPlayer.currentTime > 0
# G.elapsedTime = audioPlayer.currentTime
if G.input.change
if G.isPaused
G.isPaused = false
audioPlayer.currentTime = G.elapsedTime
audioPlayer.play()
else
G.player.type += 1
G.player.type = G.player.type % G.player.totalTypes
unless G.isPaused
if G.elapsedTime > G.levelTime * G.levelIndex
G.levelIndex += 1
# G.isPaused = true
# audioPlayer.pause()
# Clear the bg
clearScreen(ctx, G.screenDims, G.player.type)
G.audio.beatIndex = 0
while G.audio.beats.length > G.audio.beatIndex+1 and G.audio.beats[G.audio.beatIndex]? and G.audio.beats[G.audio.beatIndex].start < G.elapsedTime
# print(G.audio.beats[G.audio.beatIndex])
G.audio.beatIndex++
# print(G.audio.beatIndex)
G.worldRot = G.elapsedTime * 0.1
G.worldRot = G.worldRot % (2*Math.PI) # Wrap around
ctx.strokeStyle = '#000'
ctx.lineWidth = 0.004 * pixelsPerUnit
ctx.beginPath()
scaler = 0.02 * Math.sin(G.audio.beats[G.audio.beatIndex].duration - (G.elapsedTime - G.audio.beats[G.audio.beatIndex].start))
radius = 0.30 + scaler
ctx.arc(center.x * pixelsPerUnit, center.y * pixelsPerUnit, radius * pixelsPerUnit, 0, 2 * Math.PI)
ctx.stroke()
ctx.fillStyle = '#000'
ctx.beginPath()
x = Math.cos(Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.6 + center.x
y = Math.sin(Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.6 + center.y
ctx.moveTo(x * pixelsPerUnit, y * pixelsPerUnit)
x = Math.cos(Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.8 + center.x
y = Math.sin(Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.8 + center.y
ctx.lineTo(x * pixelsPerUnit, y * pixelsPerUnit)
ctx.arc(center.x * pixelsPerUnit, center.y * pixelsPerUnit, radius*0.8 * pixelsPerUnit,
(Math.PI * 2 - Math.PI/2 - G.worldRot) % (Math.PI * 2),
(G.elapsedTime/(G.levelTime) * 2 * Math.PI - Math.PI/2+0.001 - G.worldRot) % (Math.PI * 2))
x = Math.cos(G.elapsedTime/G.levelTime * Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.6 + center.x
y = Math.sin(G.elapsedTime/G.levelTime * Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.6 + center.y
ctx.lineTo(x * pixelsPerUnit, y * pixelsPerUnit)
ctx.arc(center.x * pixelsPerUnit, center.y * pixelsPerUnit, radius*0.6 * pixelsPerUnit,
(G.elapsedTime/(G.levelTime) * 2 * Math.PI - Math.PI/2+0.001 - G.worldRot) % (Math.PI * 2),
(Math.PI * 2 - Math.PI/2 - G.worldRot) % (Math.PI * 2))
# ctx.arc(center.x * pixelsPerUnit, center.y * pixelsPerUnit, radius * pixelsPerUnit, 0, 2 * Math.PI)
# x = Math.cos(Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.6 + center.x
# y = Math.sin(Math.PI * 2 - Math.PI/2 - G.worldRot)*radius*0.6 + center.y
# ctx.lineTo(x * pixelsPerUnit, y * pixelsPerUnit)
ctx.fill()
playerPos = circleToCartesian(G.elapsedTime, G.levelTime, radius, G.worldRot, center)
playerPosInner = circleToCartesian(G.elapsedTime, G.levelTime, radius/2, G.worldRot, center)
ctx.strokeStyle = '#000'
ctx.beginPath()
ctx.moveTo(playerPos.x * pixelsPerUnit, playerPos.y * pixelsPerUnit)
ctx.lineTo(center.x*pixelsPerUnit, center.y*pixelsPerUnit)
# ctx.closePath()
ctx.stroke()
tatumIndex = 0
while G.audio.tatums.length > tatumIndex+1 and G.audio.tatums[tatumIndex]? and G.audio.tatums[tatumIndex].start < audioPlayer.currentTime
# print(G.audio.beats[G.audio.beatIndex])
tatumIndex++
tatumScaler = 0.05 * Math.sin(G.audio.tatums[tatumIndex].duration - (audioPlayer.currentTime - G.audio.tatums[tatumIndex].start))
tatumRadius = 0.06 + tatumScaler
drawCenterTatum(ctx, pixelsPerUnit, tatumRadius, center)
if G.invincibilityTimer > 0
G.invincibilityTimer -= dt
for beat,i in G.audio.beats
if beat?
t = beatType(i, Math.floor(beat.start/G.levelTime)) #(if beat.confidence > 0.6 then 1 else 0)
# if beat.start < (G.levelTime * G.levelIndex) and beat.start > (G.levelTime * (G.levelIndex - 1)) #and beat.start > G.elapsedTime
pos = circleToCartesian(beat.start, G.levelTime, radius, G.worldRot, center)
percentage = 0
if Math.abs(beat.start - G.elapsedTime) < G.levelTime*0.2
percentage = 1-Math.abs((beat.start - G.elapsedTime))/(G.levelTime*0.2)
percentage = Math.max(Math.min(percentage, 1), 0)
drawBeat(ctx, pixelsPerUnit, pos, percentage, t)
if G.invincibilityTimer <= 0 and Math.abs(G.elapsedTime - beat.start) <= G.player.collisionRadius and t != G.player.type
# print 'die'
audioPlayer.pause()
G.invincibilityTimer = (1/60*1000) * 30
G.didGetHitTimer = (1/60*1000) * 20
# else if beat.start < (G.levelTime * (G.levelIndex+1)) and beat.start > (G.levelTime * (G.levelIndex))
# pos = circleToCartesian(beat.start, G.levelTime, radius/2, -G.worldRot, center)
# drawBeat(ctx, pixelsPerUnit, pos, 0.5, t)
# for tatum in G.audio.tatums
# if tatum? and tatum.start < G.levelTime
# pos = circleToCartesian(tatum.start, G.levelTime, radius, G.worldRot, center)
# t = (if tatum.confidence > 0.6 then 1 else 0)
# drawTatum(ctx, pixelsPerUnit, pos, t)
# if Math.abs((G.elapsedTime % G.levelTime) - beat.start) <= G.player.collisionRadius and t != G.player.type
# print 'die'
# G.elapsedTime -= 1
# audioPlayer.currentTime = G.elapsedTime
playerPos = circleToCartesian(G.elapsedTime, G.levelTime, radius*1.02, G.worldRot, center)
drawEntityNew(ctx, pixelsPerUnit, playerPos, playerPosInner, G.invincibilityTimer)
# drawEntity(ctx, pixelsPerUnit, playerPos, G.invincibilityTimer)
# levelTime
# ctx.beginPath();
# ctx.moveTo(center.x*pixelsPerUnit, center.y*pixelsPerUnit);
# ctx.strokeStyle = '#000'
# ctx.lineWidth = 4
# spiralRings = 5
# last = {}
# for t in [0..spiralRings] by 0.01
# {x: x, y: y} = spiralToCartesian(t, G.worldRot, center)
# ctx.lineTo(x*pixelsPerUnit, y*pixelsPerUnit)
# ctx.stroke()
# v = 2*Math.PI*0.005/4 # speed for approx 10 sec; TODO(JULIAN): Make Exact
# playerRotSpeed = if G.playerPos.theta<=0 then 0 else v/(2*Math.PI * G.playerPos.theta)
# beatTime = 0
# beatRot = 5
# while beatTime < 2
# beatRotSpeed = if beatRot<=0 then 0 else v/(2*Math.PI * beatRot)
# drawBeat(ctx, pixelsPerUnit, spiralToCartesian(beatRot, G.worldRot, center))
# beatRot -= 16 * beatRotSpeed
# beatTime += v
# console.log(G.playerPos.theta)
# G.playerPos.theta -= dt * playerRotSpeed
# G.playerPos.theta = G.playerPos.theta % (2*Math.PI)
# pos = spiralToCartesian(G.playerPos.theta, G.worldRot, center)
# drawEntity(ctx, pixelsPerUnit, pos)
# console.log(G.playerPos.x)
if G.isPaused
ctx.textAlign="center";
ctx.fillStyle = '#000'
ctx.font="20px Open Sans";
ctx.fillText('[SPACE]',pixelsPerUnit * center.x,pixelsPerUnit * center.y + 7);
G
window.requestAnimationFrame step |
[
{
"context": "# Copyright (c) 2015 Jesse Grosjean. All rights reserved.\n\nFoldingTextService = requi",
"end": 35,
"score": 0.9996684193611145,
"start": 21,
"tag": "NAME",
"value": "Jesse Grosjean"
}
] | atom/packages/foldingtext-for-atom/lib/extensions/status/index.coffee | prookie/dotfiles-1 | 0 | # Copyright (c) 2015 Jesse Grosjean. All rights reserved.
FoldingTextService = require '../../foldingtext-service'
toggleStatus = (editor, status) ->
outline = editor.outline
undoManager = outline.undoManager
selectedItems = editor.selection.items
firstItem = selectedItems[0]
if firstItem
if firstItem.getAttribute('data-status') is status
status = undefined
outline.beginUpdates()
undoManager.beginUndoGrouping()
for each in selectedItems
each.setAttribute('data-status', status)
undoManager.endUndoGrouping()
outline.endUpdates()
FoldingTextService.eventRegistery.listen '.bstatus',
click: (e) ->
status = e.target.dataset.status
outlineEditor = FoldingTextService.OutlineEditor.findOutlineEditor e.target
outlineEditor.setSearch "@status = #{status}"
e.stopPropagation()
e.preventDefault()
FoldingTextService.observeOutlineEditors (editor) ->
editor.addItemBadgeRenderer (item, addBadgeElement) ->
if status = item.getAttribute 'data-status'
a = document.createElement 'A'
a.className = 'bstatus'
a.setAttribute 'data-status', status
addBadgeElement a
atom.commands.add 'ft-outline-editor',
'outline-editor:toggle-status-todo': -> toggleStatus @editor, 'todo'
'outline-editor:toggle-status-waiting': -> toggleStatus @editor, 'waiting'
'outline-editor:toggle-status-active': -> toggleStatus @editor, 'active'
'outline-editor:toggle-status-complete': -> toggleStatus @editor, 'complete'
atom.keymaps.add 'status-bindings',
'ft-outline-editor':
'ctrl-space': 'outline-editor:toggle-status-complete'
'ft-outline-editor.outline-mode':
's t': 'outline-editor:toggle-status-todo'
's w': 'outline-editor:toggle-status-waiting'
's a': 'outline-editor:toggle-status-active'
's c': 'outline-editor:toggle-status-complete'
'space': 'outline-editor:toggle-status-complete' | 141633 | # Copyright (c) 2015 <NAME>. All rights reserved.
FoldingTextService = require '../../foldingtext-service'
toggleStatus = (editor, status) ->
outline = editor.outline
undoManager = outline.undoManager
selectedItems = editor.selection.items
firstItem = selectedItems[0]
if firstItem
if firstItem.getAttribute('data-status') is status
status = undefined
outline.beginUpdates()
undoManager.beginUndoGrouping()
for each in selectedItems
each.setAttribute('data-status', status)
undoManager.endUndoGrouping()
outline.endUpdates()
FoldingTextService.eventRegistery.listen '.bstatus',
click: (e) ->
status = e.target.dataset.status
outlineEditor = FoldingTextService.OutlineEditor.findOutlineEditor e.target
outlineEditor.setSearch "@status = #{status}"
e.stopPropagation()
e.preventDefault()
FoldingTextService.observeOutlineEditors (editor) ->
editor.addItemBadgeRenderer (item, addBadgeElement) ->
if status = item.getAttribute 'data-status'
a = document.createElement 'A'
a.className = 'bstatus'
a.setAttribute 'data-status', status
addBadgeElement a
atom.commands.add 'ft-outline-editor',
'outline-editor:toggle-status-todo': -> toggleStatus @editor, 'todo'
'outline-editor:toggle-status-waiting': -> toggleStatus @editor, 'waiting'
'outline-editor:toggle-status-active': -> toggleStatus @editor, 'active'
'outline-editor:toggle-status-complete': -> toggleStatus @editor, 'complete'
atom.keymaps.add 'status-bindings',
'ft-outline-editor':
'ctrl-space': 'outline-editor:toggle-status-complete'
'ft-outline-editor.outline-mode':
's t': 'outline-editor:toggle-status-todo'
's w': 'outline-editor:toggle-status-waiting'
's a': 'outline-editor:toggle-status-active'
's c': 'outline-editor:toggle-status-complete'
'space': 'outline-editor:toggle-status-complete' | true | # Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved.
FoldingTextService = require '../../foldingtext-service'
toggleStatus = (editor, status) ->
outline = editor.outline
undoManager = outline.undoManager
selectedItems = editor.selection.items
firstItem = selectedItems[0]
if firstItem
if firstItem.getAttribute('data-status') is status
status = undefined
outline.beginUpdates()
undoManager.beginUndoGrouping()
for each in selectedItems
each.setAttribute('data-status', status)
undoManager.endUndoGrouping()
outline.endUpdates()
FoldingTextService.eventRegistery.listen '.bstatus',
click: (e) ->
status = e.target.dataset.status
outlineEditor = FoldingTextService.OutlineEditor.findOutlineEditor e.target
outlineEditor.setSearch "@status = #{status}"
e.stopPropagation()
e.preventDefault()
FoldingTextService.observeOutlineEditors (editor) ->
editor.addItemBadgeRenderer (item, addBadgeElement) ->
if status = item.getAttribute 'data-status'
a = document.createElement 'A'
a.className = 'bstatus'
a.setAttribute 'data-status', status
addBadgeElement a
atom.commands.add 'ft-outline-editor',
'outline-editor:toggle-status-todo': -> toggleStatus @editor, 'todo'
'outline-editor:toggle-status-waiting': -> toggleStatus @editor, 'waiting'
'outline-editor:toggle-status-active': -> toggleStatus @editor, 'active'
'outline-editor:toggle-status-complete': -> toggleStatus @editor, 'complete'
atom.keymaps.add 'status-bindings',
'ft-outline-editor':
'ctrl-space': 'outline-editor:toggle-status-complete'
'ft-outline-editor.outline-mode':
's t': 'outline-editor:toggle-status-todo'
's w': 'outline-editor:toggle-status-waiting'
's a': 'outline-editor:toggle-status-active'
's c': 'outline-editor:toggle-status-complete'
'space': 'outline-editor:toggle-status-complete' |
[
{
"context": "n seo.coffee\n\n@Config =\n\n\t# Basic Details\n\tname: 'Thing To Sell'\n\ttitle: ->\n\t\t\tTAPi18n.__ 'Buy Sell and Pay'\n\tsub",
"end": 152,
"score": 0.9800525903701782,
"start": 139,
"tag": "NAME",
"value": "Thing To Sell"
},
{
"context": "s\n\tlegal:\n\t\taddress: '... | lib/_config/_config.coffee | prod-tts/www.thingtosell.com | 0 | # These values get propagated through the app
# E.g. The 'name' and 'subtitle' are used in seo.coffee
@Config =
# Basic Details
name: 'Thing To Sell'
title: ->
TAPi18n.__ 'Buy Sell and Pay'
subtitle: ->
TAPi18n.__ 'any Thing'
logo: ->
'<b>' + @name + '</b>'
footer: ->
@name + ' - Copyright ' + new Date().getFullYear()
# Emails
emails:
from: 'admin@' + Meteor.absoluteUrl()
contact: 'hello' + Meteor.absoluteUrl()
# Username - if true, users are forced to set a username
username: false
# Localisation
defaultLanguage: 'en'
dateFormat: 'D/M/YYYY'
# Meta / Extenrnal content
privacyUrl: 'https://thingtosell.com'
termsUrl: 'https://thingtosell.com'
# For email footers
legal:
address: 'San Francisco, CA'
name: 'Thing to Sell'
url: 'https://thingtosell.com'
about: 'https://thingtosell.com'
blog: 'https://learn.thingtosell.com'
socialMedia:
facebook:
url: 'https://www.facebook.com/tose.llthing'
icon: 'facebook'
twitter:
url: 'https://twitter.com/tosellthing'
icon: 'twitter'
github:
url: 'https://github.com/thingtosell'
icon: 'github'
info:
url: 'https://thingtosell.com'
icon: 'link'
#Routes
homeRoute: '/'
publicRoutes: ['home']
dashboardRoute: '/dashboard'
| 130794 | # These values get propagated through the app
# E.g. The 'name' and 'subtitle' are used in seo.coffee
@Config =
# Basic Details
name: '<NAME>'
title: ->
TAPi18n.__ 'Buy Sell and Pay'
subtitle: ->
TAPi18n.__ 'any Thing'
logo: ->
'<b>' + @name + '</b>'
footer: ->
@name + ' - Copyright ' + new Date().getFullYear()
# Emails
emails:
from: 'admin@' + Meteor.absoluteUrl()
contact: 'hello' + Meteor.absoluteUrl()
# Username - if true, users are forced to set a username
username: false
# Localisation
defaultLanguage: 'en'
dateFormat: 'D/M/YYYY'
# Meta / Extenrnal content
privacyUrl: 'https://thingtosell.com'
termsUrl: 'https://thingtosell.com'
# For email footers
legal:
address: 'San Francisco, CA'
name: '<NAME>'
url: 'https://thingtosell.com'
about: 'https://thingtosell.com'
blog: 'https://learn.thingtosell.com'
socialMedia:
facebook:
url: 'https://www.facebook.com/tose.llthing'
icon: 'facebook'
twitter:
url: 'https://twitter.com/tosellthing'
icon: 'twitter'
github:
url: 'https://github.com/thingtosell'
icon: 'github'
info:
url: 'https://thingtosell.com'
icon: 'link'
#Routes
homeRoute: '/'
publicRoutes: ['home']
dashboardRoute: '/dashboard'
| true | # These values get propagated through the app
# E.g. The 'name' and 'subtitle' are used in seo.coffee
@Config =
# Basic Details
name: 'PI:NAME:<NAME>END_PI'
title: ->
TAPi18n.__ 'Buy Sell and Pay'
subtitle: ->
TAPi18n.__ 'any Thing'
logo: ->
'<b>' + @name + '</b>'
footer: ->
@name + ' - Copyright ' + new Date().getFullYear()
# Emails
emails:
from: 'admin@' + Meteor.absoluteUrl()
contact: 'hello' + Meteor.absoluteUrl()
# Username - if true, users are forced to set a username
username: false
# Localisation
defaultLanguage: 'en'
dateFormat: 'D/M/YYYY'
# Meta / Extenrnal content
privacyUrl: 'https://thingtosell.com'
termsUrl: 'https://thingtosell.com'
# For email footers
legal:
address: 'San Francisco, CA'
name: 'PI:NAME:<NAME>END_PI'
url: 'https://thingtosell.com'
about: 'https://thingtosell.com'
blog: 'https://learn.thingtosell.com'
socialMedia:
facebook:
url: 'https://www.facebook.com/tose.llthing'
icon: 'facebook'
twitter:
url: 'https://twitter.com/tosellthing'
icon: 'twitter'
github:
url: 'https://github.com/thingtosell'
icon: 'github'
info:
url: 'https://thingtosell.com'
icon: 'link'
#Routes
homeRoute: '/'
publicRoutes: ['home']
dashboardRoute: '/dashboard'
|
[
{
"context": "Ḁ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(\n\t\t(?:1(?:[\\s\\xa0]*(?:ka)?Johane|John))\n\t\t\t)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)\\uff08",
"end": 12809,
"score": 0.9971674084663391,
"start": 12803,
"tag": "NAME",
"value": "Johane"
},
{
"context": "-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(\n\t\t(?:1(?:[\\s\... | lib/bible-tools/lib/Bible-Passage-Reference-Parser/src/zu/regexps.coffee | saiba-mais/bible-lessons | 0 | 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]
| title (?! [a-z] ) #could be followed by a number
| isahluko | futhi | ivesi | kuye | ff
| [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* title
| \d \W* ff (?: [\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 = "1\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "2\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "3\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|futhi|kuye)"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|kuye)"
# 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})(
(?:UGenesise|Gen(?:esise)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:U\-?Eksodusi|E(?:ksodusi|xod|ks))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:ULevitikusi|Lev(?:itikusi|i)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UNumeri|Num(?:eri)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sir)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Wis)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:IsiLilo|Lam)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:EpJer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Is(?:Ambulo|amb)|Samb|Rev)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:PrMan)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UDuteronomi|D(?:uteronomi|uter|eut))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UJoshuwa|Josh(?:uwa)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:AbAhluleli|Judg)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:URuthe|Ruthe?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1Esd)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2Esd)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:U\-?Isaya|Isa(?:ya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*(?:uSamuweli|Sam(?:uweli)?)|Sam))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*(?:uSamuweli|Sam(?:uweli)?)|Sam))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*AmaKhosi|Kgs))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*AmaKhosi|Kgs))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*[Ii]ziKronike|Chr))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*[Ii]ziKronike|Chr))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:U\-?)?Ezra)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UNehemiya|Neh(?:emiya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:GkEsth)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Esth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:U\-?Esteri|Est(?:eri|h))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Job"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UJobe|Jobe?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:AmaHubo|IHubo|Ps)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:PrAzar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:IzAga|Prov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UmShumayeli|Mshumayeli|Eccl)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:SgThree)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:IsiHlabelelo[\s\xa0]*[Ss]eziHlabelelo|Song)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UJeremiya|Jer(?:emiya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UHezekeli|Hezekeli|Ezek|Hez)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UDaniyeli|Dan(?:iyeli)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UHoseya|Hos(?:eya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UJoweli|Jo(?:weli|el))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:U\-?Amose|Amose?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:U\-?Obadiya|Obad(?:iya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jonah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UJona|Jonah?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UMika|Mi(?:ka|c))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UNahume|Nah(?:ume)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UHabakuki|Hab(?:akuki)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UZefaniya|Ze(?:faniya|ph))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UHagayi|Hag(?:ayi)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UZakariya|Z(?:akariya|ech))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UMalaki|Mal(?:aki)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:NgokukaMathewu|Mat(?:hewu|[ht]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mark"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:NgokukaMarku|Mark[ou]?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:NgokukaLuka|Luk[ae])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*(?:ka)?Johane|John))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*(?:ka)?Johane|John))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3(?:[\s\xa0]*(?:ka)?Johane|John))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["John"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:NgokukaJohane|Joh(?:ane|n))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:I(?:zE|Ze)nzo|Acts)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:KwabaseRoma|AmaRoma|Roma?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*(?:kwabaseKorinte|Kor(?:inte)?)|Cor))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*(?:kwabaseKorinte|Kor(?:inte)?)|Cor))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:KwabaseGalathiya|Gal(?:athiya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kwabase\-?Efesu|E(?:fesu|ph))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:KwabaseFilipi|Filipi|Phil)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:wabaseK)?olose|Col)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*(?:kwabase)?Thesalonika|Thess))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*(?:kwabase)?Thesalonika|Thess))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*(?:ku)?Thimothewu|Tim))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*(?:ku)?Thimothewu|Tim))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:KuThithu|Titus)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:KuFilemoni|Phlm)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:KumaHeberu|Heb)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:EkaJakobe|Ja(?:kobe|s))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*(?:ka)?Petru|Pet))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*(?:ka)?Petru|Pet))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:EkaJuda|Jude)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Tob)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jdt)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sus)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2Macc)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3Macc)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:4Macc)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1Macc)
)(?:(?=[\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"
| 9119 | 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]
| title (?! [a-z] ) #could be followed by a number
| isahluko | futhi | ivesi | kuye | ff
| [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* title
| \d \W* ff (?: [\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 = "1\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "2\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "3\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|futhi|kuye)"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|kuye)"
# 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})(
(?:UGenesise|Gen(?:esise)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:U\-?Eksodusi|E(?:ksodusi|xod|ks))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:ULevitikusi|Lev(?:itikusi|i)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UNumeri|Num(?:eri)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sir)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Wis)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:IsiLilo|Lam)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:EpJer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Is(?:Ambulo|amb)|Samb|Rev)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:PrMan)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UDuteronomi|D(?:uteronomi|uter|eut))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UJoshuwa|Josh(?:uwa)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:AbAhluleli|Judg)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:URuthe|Ruthe?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1Esd)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2Esd)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:U\-?Isaya|Isa(?:ya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*(?:uSamuweli|Sam(?:uweli)?)|Sam))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*(?:uSamuweli|Sam(?:uweli)?)|Sam))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*AmaKhosi|Kgs))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*AmaKhosi|Kgs))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*[Ii]ziKronike|Chr))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*[Ii]ziKronike|Chr))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:U\-?)?Ezra)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UNehemiya|Neh(?:emiya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:GkEsth)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Esth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:U\-?Esteri|Est(?:eri|h))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Job"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UJobe|Jobe?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:AmaHubo|IHubo|Ps)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:PrAzar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:IzAga|Prov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UmShumayeli|Mshumayeli|Eccl)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:SgThree)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:IsiHlabelelo[\s\xa0]*[Ss]eziHlabelelo|Song)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UJeremiya|Jer(?:emiya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UHezekeli|Hezekeli|Ezek|Hez)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UDaniyeli|Dan(?:iyeli)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UHoseya|Hos(?:eya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UJoweli|Jo(?:weli|el))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:U\-?Amose|Amose?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:U\-?Obadiya|Obad(?:iya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jonah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UJona|Jonah?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UMika|Mi(?:ka|c))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UNahume|Nah(?:ume)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UHabakuki|Hab(?:akuki)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UZefaniya|Ze(?:faniya|ph))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UHagayi|Hag(?:ayi)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UZakariya|Z(?:akariya|ech))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UMalaki|Mal(?:aki)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:NgokukaMathewu|Mat(?:hewu|[ht]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mark"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:NgokukaMarku|Mark[ou]?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:NgokukaLuka|Luk[ae])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*(?:ka)?<NAME>|<NAME>))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*(?:ka)?<NAME>|<NAME>))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3(?:[\s\xa0]*(?:ka)?Johane|<NAME>))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["John"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:NgokukaJohane|Joh(?:ane|n))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:I(?:zE|Ze)nzo|Acts)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:KwabaseRoma|AmaRoma|Roma?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*(?:kwabaseKorinte|Kor(?:inte)?)|Cor))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*(?:kwabaseKorinte|Kor(?:inte)?)|Cor))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:KwabaseGalathiya|Gal(?:athiya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kwabase\-?Efesu|E(?:fesu|ph))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:KwabaseFilipi|Filipi|Phil)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:wabaseK)?olose|Col)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*(?:kwabase)?Thesalonika|Thess))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*(?:kwabase)?Thesalonika|Thess))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*(?:ku)?Thimothewu|Tim))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*(?:ku)?Thimothewu|Tim))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:KuThithu|Titus)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:KuFilemoni|Phlm)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:KumaHeberu|Heb)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:EkaJakobe|Ja(?:kobe|s))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*(?:ka)?Petru|Pet))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*(?:ka)?Petru|Pet))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:EkaJuda|Jude)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Tob)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jdt)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sus)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2Macc)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3Macc)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:4Macc)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1Macc)
)(?:(?=[\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]
| title (?! [a-z] ) #could be followed by a number
| isahluko | futhi | ivesi | kuye | ff
| [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* title
| \d \W* ff (?: [\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 = "1\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "2\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "3\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|futhi|kuye)"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|kuye)"
# 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})(
(?:UGenesise|Gen(?:esise)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:U\-?Eksodusi|E(?:ksodusi|xod|ks))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:ULevitikusi|Lev(?:itikusi|i)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UNumeri|Num(?:eri)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sir)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Wis)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:IsiLilo|Lam)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:EpJer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Is(?:Ambulo|amb)|Samb|Rev)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:PrMan)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UDuteronomi|D(?:uteronomi|uter|eut))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UJoshuwa|Josh(?:uwa)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:AbAhluleli|Judg)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:URuthe|Ruthe?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1Esd)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2Esd)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:U\-?Isaya|Isa(?:ya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*(?:uSamuweli|Sam(?:uweli)?)|Sam))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*(?:uSamuweli|Sam(?:uweli)?)|Sam))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*AmaKhosi|Kgs))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*AmaKhosi|Kgs))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*[Ii]ziKronike|Chr))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*[Ii]ziKronike|Chr))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:U\-?)?Ezra)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UNehemiya|Neh(?:emiya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:GkEsth)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Esth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:U\-?Esteri|Est(?:eri|h))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Job"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UJobe|Jobe?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:AmaHubo|IHubo|Ps)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:PrAzar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:IzAga|Prov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UmShumayeli|Mshumayeli|Eccl)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:SgThree)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:IsiHlabelelo[\s\xa0]*[Ss]eziHlabelelo|Song)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UJeremiya|Jer(?:emiya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UHezekeli|Hezekeli|Ezek|Hez)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UDaniyeli|Dan(?:iyeli)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UHoseya|Hos(?:eya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UJoweli|Jo(?:weli|el))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:U\-?Amose|Amose?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:U\-?Obadiya|Obad(?:iya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jonah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UJona|Jonah?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UMika|Mi(?:ka|c))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UNahume|Nah(?:ume)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UHabakuki|Hab(?:akuki)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UZefaniya|Ze(?:faniya|ph))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UHagayi|Hag(?:ayi)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UZakariya|Z(?:akariya|ech))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:UMalaki|Mal(?:aki)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:NgokukaMathewu|Mat(?:hewu|[ht]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mark"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:NgokukaMarku|Mark[ou]?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:NgokukaLuka|Luk[ae])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*(?:ka)?PI:NAME:<NAME>END_PI|PI:NAME:<NAME>END_PI))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*(?:ka)?PI:NAME:<NAME>END_PI|PI:NAME:<NAME>END_PI))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3(?:[\s\xa0]*(?:ka)?Johane|PI:NAME:<NAME>END_PI))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["John"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:NgokukaJohane|Joh(?:ane|n))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:I(?:zE|Ze)nzo|Acts)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:KwabaseRoma|AmaRoma|Roma?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*(?:kwabaseKorinte|Kor(?:inte)?)|Cor))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*(?:kwabaseKorinte|Kor(?:inte)?)|Cor))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:KwabaseGalathiya|Gal(?:athiya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kwabase\-?Efesu|E(?:fesu|ph))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:KwabaseFilipi|Filipi|Phil)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:wabaseK)?olose|Col)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*(?:kwabase)?Thesalonika|Thess))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*(?:kwabase)?Thesalonika|Thess))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*(?:ku)?Thimothewu|Tim))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*(?:ku)?Thimothewu|Tim))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:KuThithu|Titus)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:KuFilemoni|Phlm)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:KumaHeberu|Heb)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:EkaJakobe|Ja(?:kobe|s))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*(?:ka)?Petru|Pet))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*(?:ka)?Petru|Pet))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:EkaJuda|Jude)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Tob)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jdt)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sus)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2Macc)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3Macc)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:4Macc)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1Macc)
)(?:(?=[\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": "view Tests for no-warning-comments rule.\n# @author Alexander Schmidt <https:#github.com/lxanders>\n###\n\n'use strict'\n\n#",
"end": 84,
"score": 0.9998292922973633,
"start": 67,
"tag": "NAME",
"value": "Alexander Schmidt"
},
{
"context": "e.\n# @author Alexander Schmi... | src/tests/rules/no-warning-comments.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for no-warning-comments rule.
# @author Alexander Schmidt <https:#github.com/lxanders>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-warning-comments'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-warning-comments', rule,
valid: [
code: '# any comment', options: [terms: ['fixme']]
,
code: '# any comment', options: [terms: ['fixme', 'todo']]
,
'# any comment'
,
code: '# any comment', options: [location: 'anywhere']
,
code: '# any comment with TODO, FIXME or XXX'
options: [location: 'start']
,
'# any comment with TODO, FIXME or XXX'
,
code: '### any block comment ###', options: [terms: ['fixme']]
,
code: '### any block comment ###', options: [terms: ['fixme', 'todo']]
,
'### any block comment ###'
,
code: '### any block comment ###', options: [location: 'anywhere']
,
code: '### any block comment with TODO, FIXME or XXX ###'
options: [location: 'start']
,
'### any block comment with TODO, FIXME or XXX ###'
"### any block comment with (TODO, FIXME's or XXX!) ###"
,
code: '# comments containing terms as substrings like TodoMVC'
options: [terms: ['todo'], location: 'anywhere']
,
code: "# special regex characters don't cause problems"
options: [terms: ['[aeiou]'], location: 'anywhere']
,
'###eslint no-warning-comments: [2, { "terms": ["todo", "fixme", "any other term"], "location": "anywhere" }]###\n\nx = 10\n'
,
code:
'###eslint no-warning-comments: [2, { "terms": ["todo", "fixme", "any other term"], "location": "anywhere" }]###\n\nx = 10\n'
options: [location: 'anywhere']
]
invalid: [
code: '# fixme', errors: [message: "Unexpected 'fixme' comment."]
,
code: '# any fixme'
options: [location: 'anywhere']
errors: [message: "Unexpected 'fixme' comment."]
,
code: '# any fixme'
options: [terms: ['fixme'], location: 'anywhere']
errors: [message: "Unexpected 'fixme' comment."]
,
code: '# any FIXME'
options: [terms: ['fixme'], location: 'anywhere']
errors: [message: "Unexpected 'fixme' comment."]
,
code: '# any fIxMe'
options: [terms: ['fixme'], location: 'anywhere']
errors: [message: "Unexpected 'fixme' comment."]
,
code: '### any fixme ###'
options: [terms: ['FIXME'], location: 'anywhere']
errors: [message: "Unexpected 'FIXME' comment."]
,
code: '### any FIXME ###'
options: [terms: ['FIXME'], location: 'anywhere']
errors: [message: "Unexpected 'FIXME' comment."]
,
code: '### any fIxMe ###'
options: [terms: ['FIXME'], location: 'anywhere']
errors: [message: "Unexpected 'FIXME' comment."]
,
code: '# any fixme or todo'
options: [terms: ['fixme', 'todo'], location: 'anywhere']
errors: [
message: "Unexpected 'fixme' comment."
,
message: "Unexpected 'todo' comment."
]
,
code: '### any fixme or todo ###'
options: [terms: ['fixme', 'todo'], location: 'anywhere']
errors: [
message: "Unexpected 'fixme' comment."
,
message: "Unexpected 'todo' comment."
]
,
code: '### any fixme or todo ###'
options: [location: 'anywhere']
errors: [
message: "Unexpected 'todo' comment."
,
message: "Unexpected 'fixme' comment."
]
,
code: '### fixme and todo ###'
errors: [message: "Unexpected 'fixme' comment."]
,
code: '### fixme and todo ###'
options: [location: 'anywhere']
errors: [
message: "Unexpected 'todo' comment."
,
message: "Unexpected 'fixme' comment."
]
,
code: '### any fixme ###'
options: [location: 'anywhere']
errors: [message: "Unexpected 'fixme' comment."]
,
code: '### fixme! ###'
options: [terms: ['fixme']]
errors: [message: "Unexpected 'fixme' comment."]
,
code: '# regex [litera|$]'
options: [terms: ['[litera|$]'], location: 'anywhere']
errors: [message: "Unexpected '[litera|$]' comment."]
,
code: '### eslint one-var: 2 ###'
options: [terms: ['eslint']]
errors: [message: "Unexpected 'eslint' comment."]
,
code: '### eslint one-var: 2 ###'
options: [terms: ['one'], location: 'anywhere']
errors: [message: "Unexpected 'one' comment."]
,
code: '### any block comment with TODO, FIXME or XXX ###'
options: [location: 'anywhere']
errors: [
message: "Unexpected 'todo' comment."
,
message: "Unexpected 'fixme' comment."
,
message: "Unexpected 'xxx' comment."
]
,
code: "### any block comment with (TODO, FIXME's or XXX!) ###"
options: [location: 'anywhere']
errors: [
message: "Unexpected 'todo' comment."
,
message: "Unexpected 'fixme' comment."
,
message: "Unexpected 'xxx' comment."
]
,
code: "###* \n *any block comment \n*with (TODO, FIXME's or XXX!) *###"
options: [location: 'anywhere']
errors: [
message: "Unexpected 'todo' comment."
,
message: "Unexpected 'fixme' comment."
,
message: "Unexpected 'xxx' comment."
]
,
code: '# any comment with TODO, FIXME or XXX'
options: [location: 'anywhere']
errors: [
message: "Unexpected 'todo' comment."
,
message: "Unexpected 'fixme' comment."
,
message: "Unexpected 'xxx' comment."
]
]
| 2405 | ###*
# @fileoverview Tests for no-warning-comments rule.
# @author <NAME> <https:#github.com/lxanders>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-warning-comments'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-warning-comments', rule,
valid: [
code: '# any comment', options: [terms: ['fixme']]
,
code: '# any comment', options: [terms: ['fixme', 'todo']]
,
'# any comment'
,
code: '# any comment', options: [location: 'anywhere']
,
code: '# any comment with TODO, FIXME or XXX'
options: [location: 'start']
,
'# any comment with TODO, FIXME or XXX'
,
code: '### any block comment ###', options: [terms: ['fixme']]
,
code: '### any block comment ###', options: [terms: ['fixme', 'todo']]
,
'### any block comment ###'
,
code: '### any block comment ###', options: [location: 'anywhere']
,
code: '### any block comment with TODO, FIXME or XXX ###'
options: [location: 'start']
,
'### any block comment with TODO, FIXME or XXX ###'
"### any block comment with (TODO, FIXME's or XXX!) ###"
,
code: '# comments containing terms as substrings like TodoMVC'
options: [terms: ['todo'], location: 'anywhere']
,
code: "# special regex characters don't cause problems"
options: [terms: ['[aeiou]'], location: 'anywhere']
,
'###eslint no-warning-comments: [2, { "terms": ["todo", "fixme", "any other term"], "location": "anywhere" }]###\n\nx = 10\n'
,
code:
'###eslint no-warning-comments: [2, { "terms": ["todo", "fixme", "any other term"], "location": "anywhere" }]###\n\nx = 10\n'
options: [location: 'anywhere']
]
invalid: [
code: '# fixme', errors: [message: "Unexpected 'fixme' comment."]
,
code: '# any fixme'
options: [location: 'anywhere']
errors: [message: "Unexpected 'fixme' comment."]
,
code: '# any fixme'
options: [terms: ['fixme'], location: 'anywhere']
errors: [message: "Unexpected 'fixme' comment."]
,
code: '# any FIXME'
options: [terms: ['fixme'], location: 'anywhere']
errors: [message: "Unexpected 'fixme' comment."]
,
code: '# any fIxMe'
options: [terms: ['fixme'], location: 'anywhere']
errors: [message: "Unexpected 'fixme' comment."]
,
code: '### any fixme ###'
options: [terms: ['FIXME'], location: 'anywhere']
errors: [message: "Unexpected 'FIXME' comment."]
,
code: '### any FIXME ###'
options: [terms: ['FIXME'], location: 'anywhere']
errors: [message: "Unexpected 'FIXME' comment."]
,
code: '### any fIxMe ###'
options: [terms: ['FIXME'], location: 'anywhere']
errors: [message: "Unexpected 'FIXME' comment."]
,
code: '# any fixme or todo'
options: [terms: ['fixme', 'todo'], location: 'anywhere']
errors: [
message: "Unexpected 'fixme' comment."
,
message: "Unexpected 'todo' comment."
]
,
code: '### any fixme or todo ###'
options: [terms: ['fixme', 'todo'], location: 'anywhere']
errors: [
message: "Unexpected 'fixme' comment."
,
message: "Unexpected 'todo' comment."
]
,
code: '### any fixme or todo ###'
options: [location: 'anywhere']
errors: [
message: "Unexpected 'todo' comment."
,
message: "Unexpected 'fixme' comment."
]
,
code: '### fixme and todo ###'
errors: [message: "Unexpected 'fixme' comment."]
,
code: '### fixme and todo ###'
options: [location: 'anywhere']
errors: [
message: "Unexpected 'todo' comment."
,
message: "Unexpected 'fixme' comment."
]
,
code: '### any fixme ###'
options: [location: 'anywhere']
errors: [message: "Unexpected 'fixme' comment."]
,
code: '### fixme! ###'
options: [terms: ['fixme']]
errors: [message: "Unexpected 'fixme' comment."]
,
code: '# regex [litera|$]'
options: [terms: ['[litera|$]'], location: 'anywhere']
errors: [message: "Unexpected '[litera|$]' comment."]
,
code: '### eslint one-var: 2 ###'
options: [terms: ['eslint']]
errors: [message: "Unexpected 'eslint' comment."]
,
code: '### eslint one-var: 2 ###'
options: [terms: ['one'], location: 'anywhere']
errors: [message: "Unexpected 'one' comment."]
,
code: '### any block comment with TODO, FIXME or XXX ###'
options: [location: 'anywhere']
errors: [
message: "Unexpected 'todo' comment."
,
message: "Unexpected 'fixme' comment."
,
message: "Unexpected 'xxx' comment."
]
,
code: "### any block comment with (TODO, FIXME's or XXX!) ###"
options: [location: 'anywhere']
errors: [
message: "Unexpected 'todo' comment."
,
message: "Unexpected 'fixme' comment."
,
message: "Unexpected 'xxx' comment."
]
,
code: "###* \n *any block comment \n*with (TODO, FIXME's or XXX!) *###"
options: [location: 'anywhere']
errors: [
message: "Unexpected 'todo' comment."
,
message: "Unexpected 'fixme' comment."
,
message: "Unexpected 'xxx' comment."
]
,
code: '# any comment with TODO, FIXME or XXX'
options: [location: 'anywhere']
errors: [
message: "Unexpected 'todo' comment."
,
message: "Unexpected 'fixme' comment."
,
message: "Unexpected 'xxx' comment."
]
]
| true | ###*
# @fileoverview Tests for no-warning-comments rule.
# @author PI:NAME:<NAME>END_PI <https:#github.com/lxanders>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-warning-comments'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-warning-comments', rule,
valid: [
code: '# any comment', options: [terms: ['fixme']]
,
code: '# any comment', options: [terms: ['fixme', 'todo']]
,
'# any comment'
,
code: '# any comment', options: [location: 'anywhere']
,
code: '# any comment with TODO, FIXME or XXX'
options: [location: 'start']
,
'# any comment with TODO, FIXME or XXX'
,
code: '### any block comment ###', options: [terms: ['fixme']]
,
code: '### any block comment ###', options: [terms: ['fixme', 'todo']]
,
'### any block comment ###'
,
code: '### any block comment ###', options: [location: 'anywhere']
,
code: '### any block comment with TODO, FIXME or XXX ###'
options: [location: 'start']
,
'### any block comment with TODO, FIXME or XXX ###'
"### any block comment with (TODO, FIXME's or XXX!) ###"
,
code: '# comments containing terms as substrings like TodoMVC'
options: [terms: ['todo'], location: 'anywhere']
,
code: "# special regex characters don't cause problems"
options: [terms: ['[aeiou]'], location: 'anywhere']
,
'###eslint no-warning-comments: [2, { "terms": ["todo", "fixme", "any other term"], "location": "anywhere" }]###\n\nx = 10\n'
,
code:
'###eslint no-warning-comments: [2, { "terms": ["todo", "fixme", "any other term"], "location": "anywhere" }]###\n\nx = 10\n'
options: [location: 'anywhere']
]
invalid: [
code: '# fixme', errors: [message: "Unexpected 'fixme' comment."]
,
code: '# any fixme'
options: [location: 'anywhere']
errors: [message: "Unexpected 'fixme' comment."]
,
code: '# any fixme'
options: [terms: ['fixme'], location: 'anywhere']
errors: [message: "Unexpected 'fixme' comment."]
,
code: '# any FIXME'
options: [terms: ['fixme'], location: 'anywhere']
errors: [message: "Unexpected 'fixme' comment."]
,
code: '# any fIxMe'
options: [terms: ['fixme'], location: 'anywhere']
errors: [message: "Unexpected 'fixme' comment."]
,
code: '### any fixme ###'
options: [terms: ['FIXME'], location: 'anywhere']
errors: [message: "Unexpected 'FIXME' comment."]
,
code: '### any FIXME ###'
options: [terms: ['FIXME'], location: 'anywhere']
errors: [message: "Unexpected 'FIXME' comment."]
,
code: '### any fIxMe ###'
options: [terms: ['FIXME'], location: 'anywhere']
errors: [message: "Unexpected 'FIXME' comment."]
,
code: '# any fixme or todo'
options: [terms: ['fixme', 'todo'], location: 'anywhere']
errors: [
message: "Unexpected 'fixme' comment."
,
message: "Unexpected 'todo' comment."
]
,
code: '### any fixme or todo ###'
options: [terms: ['fixme', 'todo'], location: 'anywhere']
errors: [
message: "Unexpected 'fixme' comment."
,
message: "Unexpected 'todo' comment."
]
,
code: '### any fixme or todo ###'
options: [location: 'anywhere']
errors: [
message: "Unexpected 'todo' comment."
,
message: "Unexpected 'fixme' comment."
]
,
code: '### fixme and todo ###'
errors: [message: "Unexpected 'fixme' comment."]
,
code: '### fixme and todo ###'
options: [location: 'anywhere']
errors: [
message: "Unexpected 'todo' comment."
,
message: "Unexpected 'fixme' comment."
]
,
code: '### any fixme ###'
options: [location: 'anywhere']
errors: [message: "Unexpected 'fixme' comment."]
,
code: '### fixme! ###'
options: [terms: ['fixme']]
errors: [message: "Unexpected 'fixme' comment."]
,
code: '# regex [litera|$]'
options: [terms: ['[litera|$]'], location: 'anywhere']
errors: [message: "Unexpected '[litera|$]' comment."]
,
code: '### eslint one-var: 2 ###'
options: [terms: ['eslint']]
errors: [message: "Unexpected 'eslint' comment."]
,
code: '### eslint one-var: 2 ###'
options: [terms: ['one'], location: 'anywhere']
errors: [message: "Unexpected 'one' comment."]
,
code: '### any block comment with TODO, FIXME or XXX ###'
options: [location: 'anywhere']
errors: [
message: "Unexpected 'todo' comment."
,
message: "Unexpected 'fixme' comment."
,
message: "Unexpected 'xxx' comment."
]
,
code: "### any block comment with (TODO, FIXME's or XXX!) ###"
options: [location: 'anywhere']
errors: [
message: "Unexpected 'todo' comment."
,
message: "Unexpected 'fixme' comment."
,
message: "Unexpected 'xxx' comment."
]
,
code: "###* \n *any block comment \n*with (TODO, FIXME's or XXX!) *###"
options: [location: 'anywhere']
errors: [
message: "Unexpected 'todo' comment."
,
message: "Unexpected 'fixme' comment."
,
message: "Unexpected 'xxx' comment."
]
,
code: '# any comment with TODO, FIXME or XXX'
options: [location: 'anywhere']
errors: [
message: "Unexpected 'todo' comment."
,
message: "Unexpected 'fixme' comment."
,
message: "Unexpected 'xxx' comment."
]
]
|
[
{
"context": "###\n Pokemon Go(c) MITM node proxy\n by Michael Strassburger <codepoet@cpan.org>\n\n Append the hidden IV% to t",
"end": 61,
"score": 0.9998732805252075,
"start": 41,
"tag": "NAME",
"value": "Michael Strassburger"
},
{
"context": " Go(c) MITM node proxy\n by Michae... | example.pokemonIVdisplay.coffee | noobcakes4603/tinkering | 393 | ###
Pokemon Go(c) MITM node proxy
by Michael Strassburger <codepoet@cpan.org>
Append the hidden IV% to the end of Pokémon names in our inventory
###
PokemonGoMITM = require './lib/pokemon-go-mitm'
changeCase = require 'change-case'
server = new PokemonGoMITM port: 8081
# Always get the full inventory
#.addRequestHandler "GetInventory", (data) ->
# data.last_timestamp_ms = 0
# data
# Append IV% to existing Pokémon names
.addResponseHandler "GetInventory", (data) ->
if data.inventory_delta
for item in data.inventory_delta.inventory_items when item.inventory_item_data
if pokemon = item.inventory_item_data.pokemon_data
id = changeCase.titleCase pokemon.pokemon_id
name = pokemon.nickname or id.replace(" Male", "♂").replace(" Female", "♀")
atk = pokemon.individual_attack or 0
def = pokemon.individual_defense or 0
sta = pokemon.individual_stamina or 0
iv = Math.round((atk + def + sta) * 100/45)
pokemon.nickname = "#{name} #{iv}%"
data
| 64910 | ###
Pokemon Go(c) MITM node proxy
by <NAME> <<EMAIL>>
Append the hidden IV% to the end of Pokémon names in our inventory
###
PokemonGoMITM = require './lib/pokemon-go-mitm'
changeCase = require 'change-case'
server = new PokemonGoMITM port: 8081
# Always get the full inventory
#.addRequestHandler "GetInventory", (data) ->
# data.last_timestamp_ms = 0
# data
# Append IV% to existing Pokémon names
.addResponseHandler "GetInventory", (data) ->
if data.inventory_delta
for item in data.inventory_delta.inventory_items when item.inventory_item_data
if pokemon = item.inventory_item_data.pokemon_data
id = changeCase.titleCase pokemon.pokemon_id
name = pokemon.nickname or id.replace(" Male", "♂").replace(" Female", "♀")
atk = pokemon.individual_attack or 0
def = pokemon.individual_defense or 0
sta = pokemon.individual_stamina or 0
iv = Math.round((atk + def + sta) * 100/45)
pokemon.nickname = "#{name} #{iv}%"
data
| true | ###
Pokemon Go(c) MITM node proxy
by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
Append the hidden IV% to the end of Pokémon names in our inventory
###
PokemonGoMITM = require './lib/pokemon-go-mitm'
changeCase = require 'change-case'
server = new PokemonGoMITM port: 8081
# Always get the full inventory
#.addRequestHandler "GetInventory", (data) ->
# data.last_timestamp_ms = 0
# data
# Append IV% to existing Pokémon names
.addResponseHandler "GetInventory", (data) ->
if data.inventory_delta
for item in data.inventory_delta.inventory_items when item.inventory_item_data
if pokemon = item.inventory_item_data.pokemon_data
id = changeCase.titleCase pokemon.pokemon_id
name = pokemon.nickname or id.replace(" Male", "♂").replace(" Female", "♀")
atk = pokemon.individual_attack or 0
def = pokemon.individual_defense or 0
sta = pokemon.individual_stamina or 0
iv = Math.round((atk + def + sta) * 100/45)
pokemon.nickname = "#{name} #{iv}%"
data
|
[
{
"context": "e_visit] == 'next' %>\n<% @page += 1 %>\n<% @pages[@arm.id] = @page %>\n<% session[:service_calendar_pages][@",
"end": 2301,
"score": 0.7890868186950684,
"start": 2295,
"tag": "EMAIL",
"value": "arm.id"
},
{
"context": "sit] == 'previous' %>\n<% @page -= 1 %>\n<% @pages... | app/views/visit_groups/update.js.coffee | lawhead/sparc-request | 18 | # Copyright © 2011-2020 MUSC Foundation for Research Development
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
$('[name=change_visit]').remove()
<% if @errors %>
$("[name^='visit_group']:not([type='hidden'])").parents('.form-group').removeClass('is-invalid').addClass('is-valid')
$('.form-error').remove()
<% @errors.messages.each do |attr, messages| %>
<% messages.each do |message| %>
$("[name='visit_group[<%= attr.to_s %>]']").parents('.form-group').removeClass('is-valid').addClass('is-invalid').append("<small class='form-text form-error'><%= message.capitalize.html_safe %></small>")
<% end %>
<% end %>
<% else %>
$(".visit-group-<%= @visit_group.id %>").popover('dispose')
# Change the page up if moving to previous page of visits
<% if @visit_group.position % VisitGroup.per_page == 0 && params[:change_visit] == 'next' %>
<% @page += 1 %>
<% @pages[@arm.id] = @page %>
<% session[:service_calendar_pages][@arm.id.to_s] = @page %>
$(".arm-<%= @arm.id %>-container").replaceWith("<%= j render '/service_calendars/master_calendar/pppv/pppv_calendar', tab: @tab, arm: @arm, service_request: @service_request, sub_service_request: @sub_service_request, page: @page, pages: @pages, merged: false, consolidated: false %>")
# Change the page down if moving to previous page of visits
<% elsif @visit_group.position % VisitGroup.per_page == 1 && params[:change_visit] == 'previous' %>
<% @page -= 1 %>
<% @pages[@arm.id] = @page %>
<% session[:service_calendar_pages][@arm.id.to_s] = @page %>
$(".arm-<%= @arm.id %>-container").replaceWith("<%= j render '/service_calendars/master_calendar/pppv/pppv_calendar', tab: @tab, arm: @arm, service_request: @service_request, sub_service_request: @sub_service_request, page: @page, pages: @pages, merged: false, consolidated: false %>")
# Update the whole calendar if the position changed
<% else %>
$(".arm-<%= @arm.id %>-container").replaceWith("<%= j render '/service_calendars/master_calendar/pppv/pppv_calendar', tab: @tab, arm: @arm, service_request: @service_request, sub_service_request: @sub_service_request, page: @page, pages: @pages, merged: false, consolidated: false %>")
<% end %>
adjustCalendarHeaders()
# If changing the visit using the chevrons, open the new visit
# else re-focus the visit for tabbing
<% if params[:change_visit].present? %>
$.ajax
method: 'GET'
dataType: 'script'
url: "<%= edit_visit_group_path(params[:change_visit] == 'next' ? @visit_group.lower_item : @visit_group.higher_item, srid: @service_request.try(:id), ssrid: @sub_service_request.try(:id), tab: @tab, page: @page, pages: @pages) %>"
<% else %>
$(".visit-group-<%= @visit_group.id %>").trigger('focus')
<% end %>
$("#flashContainer").replaceWith("<%= j render 'layouts/flash' %>")
$(document).trigger('ajax:complete') # rails-ujs element replacement bug fix
<% end %>
| 130634 | # Copyright © 2011-2020 MUSC Foundation for Research Development
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
$('[name=change_visit]').remove()
<% if @errors %>
$("[name^='visit_group']:not([type='hidden'])").parents('.form-group').removeClass('is-invalid').addClass('is-valid')
$('.form-error').remove()
<% @errors.messages.each do |attr, messages| %>
<% messages.each do |message| %>
$("[name='visit_group[<%= attr.to_s %>]']").parents('.form-group').removeClass('is-valid').addClass('is-invalid').append("<small class='form-text form-error'><%= message.capitalize.html_safe %></small>")
<% end %>
<% end %>
<% else %>
$(".visit-group-<%= @visit_group.id %>").popover('dispose')
# Change the page up if moving to previous page of visits
<% if @visit_group.position % VisitGroup.per_page == 0 && params[:change_visit] == 'next' %>
<% @page += 1 %>
<% @pages[@<EMAIL>] = @page %>
<% session[:service_calendar_pages][@arm.id.to_s] = @page %>
$(".arm-<%= @arm.id %>-container").replaceWith("<%= j render '/service_calendars/master_calendar/pppv/pppv_calendar', tab: @tab, arm: @arm, service_request: @service_request, sub_service_request: @sub_service_request, page: @page, pages: @pages, merged: false, consolidated: false %>")
# Change the page down if moving to previous page of visits
<% elsif @visit_group.position % VisitGroup.per_page == 1 && params[:change_visit] == 'previous' %>
<% @page -= 1 %>
<% @pages[@<EMAIL>] = @page %>
<% session[:service_calendar_pages][@arm.id.to_s] = @page %>
$(".arm-<%= @arm.id %>-container").replaceWith("<%= j render '/service_calendars/master_calendar/pppv/pppv_calendar', tab: @tab, arm: @arm, service_request: @service_request, sub_service_request: @sub_service_request, page: @page, pages: @pages, merged: false, consolidated: false %>")
# Update the whole calendar if the position changed
<% else %>
$(".arm-<%= @arm.id %>-container").replaceWith("<%= j render '/service_calendars/master_calendar/pppv/pppv_calendar', tab: @tab, arm: @arm, service_request: @service_request, sub_service_request: @sub_service_request, page: @page, pages: @pages, merged: false, consolidated: false %>")
<% end %>
adjustCalendarHeaders()
# If changing the visit using the chevrons, open the new visit
# else re-focus the visit for tabbing
<% if params[:change_visit].present? %>
$.ajax
method: 'GET'
dataType: 'script'
url: "<%= edit_visit_group_path(params[:change_visit] == 'next' ? @visit_group.lower_item : @visit_group.higher_item, srid: @service_request.try(:id), ssrid: @sub_service_request.try(:id), tab: @tab, page: @page, pages: @pages) %>"
<% else %>
$(".visit-group-<%= @visit_group.id %>").trigger('focus')
<% end %>
$("#flashContainer").replaceWith("<%= j render 'layouts/flash' %>")
$(document).trigger('ajax:complete') # rails-ujs element replacement bug fix
<% end %>
| true | # Copyright © 2011-2020 MUSC Foundation for Research Development
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
$('[name=change_visit]').remove()
<% if @errors %>
$("[name^='visit_group']:not([type='hidden'])").parents('.form-group').removeClass('is-invalid').addClass('is-valid')
$('.form-error').remove()
<% @errors.messages.each do |attr, messages| %>
<% messages.each do |message| %>
$("[name='visit_group[<%= attr.to_s %>]']").parents('.form-group').removeClass('is-valid').addClass('is-invalid').append("<small class='form-text form-error'><%= message.capitalize.html_safe %></small>")
<% end %>
<% end %>
<% else %>
$(".visit-group-<%= @visit_group.id %>").popover('dispose')
# Change the page up if moving to previous page of visits
<% if @visit_group.position % VisitGroup.per_page == 0 && params[:change_visit] == 'next' %>
<% @page += 1 %>
<% @pages[@PI:EMAIL:<EMAIL>END_PI] = @page %>
<% session[:service_calendar_pages][@arm.id.to_s] = @page %>
$(".arm-<%= @arm.id %>-container").replaceWith("<%= j render '/service_calendars/master_calendar/pppv/pppv_calendar', tab: @tab, arm: @arm, service_request: @service_request, sub_service_request: @sub_service_request, page: @page, pages: @pages, merged: false, consolidated: false %>")
# Change the page down if moving to previous page of visits
<% elsif @visit_group.position % VisitGroup.per_page == 1 && params[:change_visit] == 'previous' %>
<% @page -= 1 %>
<% @pages[@PI:EMAIL:<EMAIL>END_PI] = @page %>
<% session[:service_calendar_pages][@arm.id.to_s] = @page %>
$(".arm-<%= @arm.id %>-container").replaceWith("<%= j render '/service_calendars/master_calendar/pppv/pppv_calendar', tab: @tab, arm: @arm, service_request: @service_request, sub_service_request: @sub_service_request, page: @page, pages: @pages, merged: false, consolidated: false %>")
# Update the whole calendar if the position changed
<% else %>
$(".arm-<%= @arm.id %>-container").replaceWith("<%= j render '/service_calendars/master_calendar/pppv/pppv_calendar', tab: @tab, arm: @arm, service_request: @service_request, sub_service_request: @sub_service_request, page: @page, pages: @pages, merged: false, consolidated: false %>")
<% end %>
adjustCalendarHeaders()
# If changing the visit using the chevrons, open the new visit
# else re-focus the visit for tabbing
<% if params[:change_visit].present? %>
$.ajax
method: 'GET'
dataType: 'script'
url: "<%= edit_visit_group_path(params[:change_visit] == 'next' ? @visit_group.lower_item : @visit_group.higher_item, srid: @service_request.try(:id), ssrid: @sub_service_request.try(:id), tab: @tab, page: @page, pages: @pages) %>"
<% else %>
$(".visit-group-<%= @visit_group.id %>").trigger('focus')
<% end %>
$("#flashContainer").replaceWith("<%= j render 'layouts/flash' %>")
$(document).trigger('ajax:complete') # rails-ujs element replacement bug fix
<% end %>
|
[
{
"context": "aintained by <a href=\"http://julianrosenblum.com\">Julian Rosenblum</a>.\n Developers are encouraged to check out",
"end": 293,
"score": 0.9998766779899597,
"start": 277,
"tag": "NAME",
"value": "Julian Rosenblum"
},
{
"context": " check out Markato on <a href=\"h... | public/scripts/MarkatoFooter.cjsx | markato/markato.github.io | 21 | React = require 'react'
{ Grid, Row, Col } = require 'react-bootstrap'
module.exports = React.createClass
shouldComponentUpdate: ->
false
render: ->
<Grid><Row><Col md=12><footer><p>
Markato is written and maintained by <a href="http://julianrosenblum.com">Julian Rosenblum</a>.
Developers are encouraged to check out Markato on <a href="https://github.com/jsrmath/markato">GitHub</a>.
</p></footer></Col></Row></Grid>
| 118043 | React = require 'react'
{ Grid, Row, Col } = require 'react-bootstrap'
module.exports = React.createClass
shouldComponentUpdate: ->
false
render: ->
<Grid><Row><Col md=12><footer><p>
Markato is written and maintained by <a href="http://julianrosenblum.com"><NAME></a>.
Developers are encouraged to check out Markato on <a href="https://github.com/jsrmath/markato">GitHub</a>.
</p></footer></Col></Row></Grid>
| true | React = require 'react'
{ Grid, Row, Col } = require 'react-bootstrap'
module.exports = React.createClass
shouldComponentUpdate: ->
false
render: ->
<Grid><Row><Col md=12><footer><p>
Markato is written and maintained by <a href="http://julianrosenblum.com">PI:NAME:<NAME>END_PI</a>.
Developers are encouraged to check out Markato on <a href="https://github.com/jsrmath/markato">GitHub</a>.
</p></footer></Col></Row></Grid>
|
[
{
"context": "#Language: Romanian\n#Translators: alexhuszar\n\nro =\n\n add: \"adaugă\"\n and: \"și\"\n back: \"înapo",
"end": 44,
"score": 0.9924980998039246,
"start": 34,
"tag": "USERNAME",
"value": "alexhuszar"
},
{
"context": "\"\n and: \"și\"\n back: \"înapoi\"\n changePas... | t9n/ro.coffee | XavierSamuelHuppe/xav-accounts-t9n | 0 | #Language: Romanian
#Translators: alexhuszar
ro =
add: "adaugă"
and: "și"
back: "înapoi"
changePassword: "Schimbare parolă"
choosePassword: "Alege o parolă"
clickAgree: "Click pe Register, sunteți de acord"
configure: "Configurare"
createAccount: "Creați un cont"
currentPassword: "Parola curentă"
dontHaveAnAccount: "Nu ai un cont?"
email: "E-mail"
emailAddress: "Adresa de e-mail"
emailResetLink: "Link de resetare parolă"
forgotPassword: "Ți-ai uitat parola?"
ifYouAlreadyHaveAnAccount: "Dacă ai deja un cont"
newPassword: "Parolă nouă"
newPasswordAgain: "Parolă nouă (din nou)"
optional: "Opțional"
OR: "SAU"
password: "Parolă"
passwordAgain: "Parolă (din nou)"
privacyPolicy: "Politica de confidentialitate"
remove: "Elimină"
resetYourPassword: "Schimbati parola"
setPassword: "Setati parola"
sign: "Înregistrează"
signIn: "Autentificare"
signin: "Autentificare"
signOut: "Deconectare"
signUp: "Înregistrare"
signupCode: "Codul de înregistrare"
signUpWithYourEmailAddress: "Înregistrați-vă adresa de e-mail"
terms: "Condiții de utilizare"
updateYourPassword: "Actualizați parola dvs."
username: "Nume utilizator"
usernameOrEmail: "Nume utilizator sau e-mail"
with: "cu"
info:
emailSent: "Email trimis"
emailVerified: "Email verificat"
passwordChanged: "Parola a fost schimbata"
passwordReset: "Resetare parola"
error:
emailRequired: "Introduceti Email-ul."
minChar: "Parolă minima de 7 caractere "
pwdsDontMatch: "Parolele nu se potrivesc"
pwOneDigit: "Parola trebuie să contină cel puțin o cifră."
pwOneLetter: "Parola necesită o scrisoare."
signInRequired: "Autentificare."
signupCodeIncorrect: "Codul de înregistrare este incorectă."
signupCodeRequired: "Aveti nevoie de cod de înregistrare."
usernameIsEmail: "Numele de utilizator nu poate fi o adresă de e-mail."
usernameRequired: "Introduceti numele de utilizator."
accounts:
#---- accounts-base
#"@" + domain + " email required"
#"A login handler should return a result or undefined"
"Email already exists.": "E-mail există deja."
"Email doesn't match the criteria.": "E-mail nu se potrivește cu criteriile."
"Invalid login token": "Token invalid"
"Login forbidden": "Autentificare interzisă"
#"Service " + options.service + " already configured"
"Service unknown": "Service necunoscut"
"Unrecognized options for login request": "Opțiuni nerecunoscute de cerere de conectare"
"User validation failed": "Validare utilizator nereușit"
"Username already exists.": "Numele de utilizator existent."
"You are not logged in.": "Nu sunteti autentificat."
"You've been logged out by the server. Please log in again.": "Ați fost deconectat de către server rugam sa va logati din nou."
"Your session has expired. Please log in again.": "Sesiunea a expirat rugam sa va logati din nou."
#---- accounts-oauth
"No matching login attempt found": "Autentificare nereusită"
#---- accounts-password-client
"Password is old. Please reset your password.": "Parola expirata, Vă rugăm să resetati parola."
#---- accounts-password
"Incorrect password": "Parola incorectă"
"Invalid email": "E-mail invalid"
"Must be logged in": "Trebuie sa fii logat"
"Need to set a username or email": "Adaugati un nume utilizator sau un e-mail"
"old password format": "Parola cu format vechi"
"Password may not be empty": "Parola nu poate fi gol"
"Signups forbidden": "Înscrieri interzisă"
"Token expired": "Token expirat"
"Token has invalid email address": "Token are adresă de email invalidă"
"User has no password set": "Utilizator nu are parola setată"
"User not found": "Utilizator nu a fost găsit"
"Verify email link expired": "Link-ul de e-mail a expirat"
"Verify email link is for unknown address": "Link-ul de e-mail nu corespunde"
#---- match
"Match failed": "Potrivire nereușită"
#---- Misc...
"Unknown error": "Eroare necunoscută"
T9n.map "ro", ro | 143841 | #Language: Romanian
#Translators: alexhuszar
ro =
add: "adaugă"
and: "și"
back: "înapoi"
changePassword: "<PASSWORD>"
choosePassword: "<PASSWORD>"
clickAgree: "Click pe Register, sunteți de acord"
configure: "Configurare"
createAccount: "Creați un cont"
currentPassword: "<PASSWORD>"
dontHaveAnAccount: "Nu ai un cont?"
email: "E-mail"
emailAddress: "Adresa de e-mail"
emailResetLink: "Link de resetare parolă"
forgotPassword: "<PASSWORD>?"
ifYouAlreadyHaveAnAccount: "Dacă ai deja un cont"
newPassword: "<PASSWORD>"
newPasswordAgain: "<PASSWORD> (din nou)"
optional: "Opțional"
OR: "SAU"
password: "<PASSWORD>"
passwordAgain: "<PASSWORD> (din nou)"
privacyPolicy: "Politica de confidentialitate"
remove: "Elimină"
resetYourPassword: "<PASSWORD>"
setPassword: "<PASSWORD>"
sign: "Înregistrează"
signIn: "Autentificare"
signin: "Autentificare"
signOut: "Deconectare"
signUp: "Înregistrare"
signupCode: "Codul de înregistrare"
signUpWithYourEmailAddress: "Înregistrați-vă adresa de e-mail"
terms: "Condiții de utilizare"
updateYourPassword: "Actualizați parola dvs."
username: "Nume utilizator"
usernameOrEmail: "Nume utilizator sau e-mail"
with: "cu"
info:
emailSent: "Email trimis"
emailVerified: "Email verificat"
passwordChanged: "<PASSWORD>"
passwordReset: "<PASSWORD>"
error:
emailRequired: "Introduceti Email-ul."
minChar: "Parolă minima de 7 caractere "
pwdsDontMatch: "Parolele nu se potrivesc"
pwOneDigit: "Parola trebuie să contină cel puțin o cifră."
pwOneLetter: "Parola necesită o scrisoare."
signInRequired: "Autentificare."
signupCodeIncorrect: "Codul de înregistrare este incorectă."
signupCodeRequired: "Aveti nevoie de cod de înregistrare."
usernameIsEmail: "Numele de utilizator nu poate fi o adresă de e-mail."
usernameRequired: "Introduceti numele de utilizator."
accounts:
#---- accounts-base
#"@" + domain + " email required"
#"A login handler should return a result or undefined"
"Email already exists.": "E-mail există deja."
"Email doesn't match the criteria.": "E-mail nu se potrivește cu criteriile."
"Invalid login token": "Token invalid"
"Login forbidden": "Autentificare interzisă"
#"Service " + options.service + " already configured"
"Service unknown": "Service necunoscut"
"Unrecognized options for login request": "Opțiuni nerecunoscute de cerere de conectare"
"User validation failed": "Validare utilizator nereușit"
"Username already exists.": "Numele de utilizator existent."
"You are not logged in.": "Nu sunteti autentificat."
"You've been logged out by the server. Please log in again.": "Ați fost deconectat de către server rugam sa va logati din nou."
"Your session has expired. Please log in again.": "Sesiunea a expirat rugam sa va logati din nou."
#---- accounts-oauth
"No matching login attempt found": "Autentificare nereusită"
#---- accounts-password-client
"Password is old. Please reset your password.": "Parola expirata, Vă rugăm să resetati parola."
#---- accounts-password
"Incorrect password": "<PASSWORD>"
"Invalid email": "E-mail invalid"
"Must be logged in": "Trebuie sa fii logat"
"Need to set a username or email": "Adaugati un nume utilizator sau un e-mail"
"old password format": "Par<PASSWORD> cu format vechi"
"Password may not be empty": "Par<PASSWORD> nu poate fi gol"
"Signups forbidden": "Înscrieri interzisă"
"Token expired": "Token expirat"
"Token has invalid email address": "Token are adresă de email invalidă"
"User has no password set": "Utilizator nu are parola setată"
"User not found": "Utilizator nu a fost găsit"
"Verify email link expired": "Link-ul de e-mail a expirat"
"Verify email link is for unknown address": "Link-ul de e-mail nu corespunde"
#---- match
"Match failed": "Potrivire nereușită"
#---- Misc...
"Unknown error": "Eroare necunoscută"
T9n.map "ro", ro | true | #Language: Romanian
#Translators: alexhuszar
ro =
add: "adaugă"
and: "și"
back: "înapoi"
changePassword: "PI:PASSWORD:<PASSWORD>END_PI"
choosePassword: "PI:PASSWORD:<PASSWORD>END_PI"
clickAgree: "Click pe Register, sunteți de acord"
configure: "Configurare"
createAccount: "Creați un cont"
currentPassword: "PI:PASSWORD:<PASSWORD>END_PI"
dontHaveAnAccount: "Nu ai un cont?"
email: "E-mail"
emailAddress: "Adresa de e-mail"
emailResetLink: "Link de resetare parolă"
forgotPassword: "PI:PASSWORD:<PASSWORD>END_PI?"
ifYouAlreadyHaveAnAccount: "Dacă ai deja un cont"
newPassword: "PI:PASSWORD:<PASSWORD>END_PI"
newPasswordAgain: "PI:PASSWORD:<PASSWORD>END_PI (din nou)"
optional: "Opțional"
OR: "SAU"
password: "PI:PASSWORD:<PASSWORD>END_PI"
passwordAgain: "PI:PASSWORD:<PASSWORD>END_PI (din nou)"
privacyPolicy: "Politica de confidentialitate"
remove: "Elimină"
resetYourPassword: "PI:PASSWORD:<PASSWORD>END_PI"
setPassword: "PI:PASSWORD:<PASSWORD>END_PI"
sign: "Înregistrează"
signIn: "Autentificare"
signin: "Autentificare"
signOut: "Deconectare"
signUp: "Înregistrare"
signupCode: "Codul de înregistrare"
signUpWithYourEmailAddress: "Înregistrați-vă adresa de e-mail"
terms: "Condiții de utilizare"
updateYourPassword: "Actualizați parola dvs."
username: "Nume utilizator"
usernameOrEmail: "Nume utilizator sau e-mail"
with: "cu"
info:
emailSent: "Email trimis"
emailVerified: "Email verificat"
passwordChanged: "PI:PASSWORD:<PASSWORD>END_PI"
passwordReset: "PI:PASSWORD:<PASSWORD>END_PI"
error:
emailRequired: "Introduceti Email-ul."
minChar: "Parolă minima de 7 caractere "
pwdsDontMatch: "Parolele nu se potrivesc"
pwOneDigit: "Parola trebuie să contină cel puțin o cifră."
pwOneLetter: "Parola necesită o scrisoare."
signInRequired: "Autentificare."
signupCodeIncorrect: "Codul de înregistrare este incorectă."
signupCodeRequired: "Aveti nevoie de cod de înregistrare."
usernameIsEmail: "Numele de utilizator nu poate fi o adresă de e-mail."
usernameRequired: "Introduceti numele de utilizator."
accounts:
#---- accounts-base
#"@" + domain + " email required"
#"A login handler should return a result or undefined"
"Email already exists.": "E-mail există deja."
"Email doesn't match the criteria.": "E-mail nu se potrivește cu criteriile."
"Invalid login token": "Token invalid"
"Login forbidden": "Autentificare interzisă"
#"Service " + options.service + " already configured"
"Service unknown": "Service necunoscut"
"Unrecognized options for login request": "Opțiuni nerecunoscute de cerere de conectare"
"User validation failed": "Validare utilizator nereușit"
"Username already exists.": "Numele de utilizator existent."
"You are not logged in.": "Nu sunteti autentificat."
"You've been logged out by the server. Please log in again.": "Ați fost deconectat de către server rugam sa va logati din nou."
"Your session has expired. Please log in again.": "Sesiunea a expirat rugam sa va logati din nou."
#---- accounts-oauth
"No matching login attempt found": "Autentificare nereusită"
#---- accounts-password-client
"Password is old. Please reset your password.": "Parola expirata, Vă rugăm să resetati parola."
#---- accounts-password
"Incorrect password": "PI:PASSWORD:<PASSWORD>END_PI"
"Invalid email": "E-mail invalid"
"Must be logged in": "Trebuie sa fii logat"
"Need to set a username or email": "Adaugati un nume utilizator sau un e-mail"
"old password format": "ParPI:PASSWORD:<PASSWORD>END_PI cu format vechi"
"Password may not be empty": "ParPI:PASSWORD:<PASSWORD>END_PI nu poate fi gol"
"Signups forbidden": "Înscrieri interzisă"
"Token expired": "Token expirat"
"Token has invalid email address": "Token are adresă de email invalidă"
"User has no password set": "Utilizator nu are parola setată"
"User not found": "Utilizator nu a fost găsit"
"Verify email link expired": "Link-ul de e-mail a expirat"
"Verify email link is for unknown address": "Link-ul de e-mail nu corespunde"
#---- match
"Match failed": "Potrivire nereușită"
#---- Misc...
"Unknown error": "Eroare necunoscută"
T9n.map "ro", ro |
[
{
"context": " members: [req.user.get('_id')]\n name: 'Single Player'\n ownerID: req.user.get('_id')\n ace",
"end": 2866,
"score": 0.8301626443862915,
"start": 2853,
"tag": "NAME",
"value": "Single Player"
}
] | server/courses/course_instance_handler.coffee | teplyja1/codecombat | 1 | async = require 'async'
Handler = require '../commons/Handler'
Campaign = require '../campaigns/Campaign'
Classroom = require '../classrooms/Classroom'
Course = require './Course'
CourseInstance = require './CourseInstance'
LevelSession = require '../levels/sessions/LevelSession'
LevelSessionHandler = require '../levels/sessions/level_session_handler'
Prepaid = require '../prepaids/Prepaid'
PrepaidHandler = require '../prepaids/prepaid_handler'
User = require '../users/User'
UserHandler = require '../users/user_handler'
utils = require '../../app/core/utils'
{objectIdFromTimestamp} = require '../lib/utils'
sendwithus = require '../sendwithus'
mongoose = require 'mongoose'
CourseInstanceHandler = class CourseInstanceHandler extends Handler
modelClass: CourseInstance
jsonSchema: require '../../app/schemas/models/course_instance.schema'
allowedMethods: ['GET', 'POST', 'PUT', 'DELETE']
logError: (user, msg) ->
console.warn "Course instance error: #{user.get('slug')} (#{user._id}): '#{msg}'"
hasAccess: (req) ->
req.method in @allowedMethods or req.user?.isAdmin()
hasAccessToDocument: (req, document, method=null) ->
return true if document?.get('ownerID')?.equals(req.user?.get('_id'))
return true if req.method is 'GET' and _.find document?.get('members'), (a) -> a.equals(req.user?.get('_id'))
req.user?.isAdmin()
getByRelationship: (req, res, args...) ->
relationship = args[1]
return @createHOCAPI(req, res) if relationship is 'create-for-hoc'
return @getLevelSessionsAPI(req, res, args[0]) if args[1] is 'level_sessions'
return @addMember(req, res, args[0]) if req.method is 'POST' and args[1] is 'members'
return @removeMember(req, res, args[0]) if req.method is 'DELETE' and args[1] is 'members'
return @getMembersAPI(req, res, args[0]) if args[1] is 'members'
return @inviteStudents(req, res, args[0]) if relationship is 'invite_students'
return @getRecentAPI(req, res) if relationship is 'recent'
return @redeemPrepaidCodeAPI(req, res) if args[1] is 'redeem_prepaid'
return @getMyCourseLevelSessionsAPI(req, res, args[0]) if args[1] is 'my-course-level-sessions'
return @findByLevel(req, res, args[2]) if args[1] is 'find_by_level'
super arguments...
createHOCAPI: (req, res) ->
return @sendUnauthorizedError(res) if not req.user?
courseID = mongoose.Types.ObjectId('560f1a9f22961295f9427742')
CourseInstance.findOne { courseID: courseID, ownerID: req.user.get('_id'), hourOfCode: true }, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
if courseInstance
console.log 'already made a course instance'
return @sendSuccess(res, courseInstance) if courseInstance
courseInstance = new CourseInstance({
courseID: courseID
members: [req.user.get('_id')]
name: 'Single Player'
ownerID: req.user.get('_id')
aceConfig: { language: 'python' }
hourOfCode: true
})
courseInstance.save (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
@sendCreated(res, courseInstance)
addMember: (req, res, courseInstanceID) ->
return @sendUnauthorizedError(res) if not req.user?
userID = req.body.userID
return @sendBadInputError(res, 'Input must be a MongoDB ID') unless utils.isID(userID)
CourseInstance.findById courseInstanceID, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Course instance not found') unless courseInstance
Classroom.findById courseInstance.get('classroomID'), (err, classroom) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Classroom referenced by course instance not found') unless classroom
return @sendForbiddenError(res) unless _.any(classroom.get('members'), (memberID) -> memberID.toString() is userID)
ownsCourseInstance = courseInstance.get('ownerID').equals(req.user.get('_id'))
addingSelf = userID is req.user.id
return @sendForbiddenError(res) unless ownsCourseInstance or addingSelf
alreadyInCourseInstance = _.any courseInstance.get('members') or [], (memberID) -> memberID.toString() is userID
return @sendSuccess(res, @formatEntity(req, courseInstance)) if alreadyInCourseInstance
Prepaid.find({ 'redeemers.userID': mongoose.Types.ObjectId(userID) }).count (err, userIsPrepaid) =>
return @sendDatabaseError(res, err) if err
Course.findById courseInstance.get('courseID'), (err, course) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Course referenced by course instance not found') unless course
if not (course.get('free') or userIsPrepaid)
return @sendPaymentRequiredError(res, 'Cannot add this user to a course instance until they are added to a prepaid')
members = courseInstance.get('members')
members.push(userID)
courseInstance.set('members', members)
courseInstance.save (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
User.update {_id: mongoose.Types.ObjectId(userID)}, {$addToSet: {courseInstances: courseInstance.get('_id')}}, (err) =>
return @sendDatabaseError(res, err) if err
@sendSuccess(res, @formatEntity(req, courseInstance))
removeMember: (req, res, courseInstanceID) ->
return @sendUnauthorizedError(res) if not req.user?
userID = req.body.userID
return @sendBadInputError(res, 'Input must be a MongoDB ID') unless utils.isID(userID)
CourseInstance.findById courseInstanceID, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Course instance not found') unless courseInstance
Classroom.findById courseInstance.get('classroomID'), (err, classroom) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Classroom referenced by course instance not found') unless classroom
return @sendForbiddenError(res) unless _.any(classroom.get('members'), (memberID) -> memberID.toString() is userID)
ownsCourseInstance = courseInstance.get('ownerID').equals(req.user.get('_id'))
removingSelf = userID is req.user.id
return @sendForbiddenError(res) unless ownsCourseInstance or removingSelf
alreadyNotInCourseInstance = not _.any courseInstance.get('members') or [], (memberID) -> memberID.toString() is userID
return @sendSuccess(res, @formatEntity(req, courseInstance)) if alreadyNotInCourseInstance
members = _.clone(courseInstance.get('members'))
members = (m for m in members when m.toString() isnt userID)
courseInstance.set('members', members)
courseInstance.save (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
User.update {_id: mongoose.Types.ObjectId(userID)}, {$pull: {courseInstances: courseInstance.get('_id')}}, (err) =>
return @sendDatabaseError(res, err) if err
@sendSuccess(res, @formatEntity(req, courseInstance))
post: (req, res) ->
return @sendUnauthorizedError(res) if not req.user?
return @sendBadInputError(res, 'No classroomID') unless req.body.classroomID
return @sendBadInputError(res, 'No courseID') unless req.body.courseID
Classroom.findById req.body.classroomID, (err, classroom) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Classroom not found') unless classroom
return @sendForbiddenError(res) unless classroom.get('ownerID').equals(req.user.get('_id'))
Course.findById req.body.courseID, (err, course) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Course not found') unless course
q = {
courseID: mongoose.Types.ObjectId(req.body.courseID)
classroomID: mongoose.Types.ObjectId(req.body.classroomID)
}
CourseInstance.findOne(q).exec (err, doc) =>
return @sendDatabaseError(res, err) if err
return @sendSuccess(res, @formatEntity(req, doc)) if doc
super(req, res)
makeNewInstance: (req) ->
doc = new CourseInstance({
members: []
ownerID: req.user.get('_id')
})
doc.set('aceConfig', {}) # constructor will ignore empty objects
return doc
getLevelSessionsAPI: (req, res, courseInstanceID) ->
return @sendUnauthorizedError(res) if not req.user?
CourseInstance.findById courseInstanceID, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless courseInstance
Course.findById courseInstance.get('courseID'), (err, course) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless course
Campaign.findById course.get('campaignID'), (err, campaign) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless campaign
levelIDs = (levelID for levelID of campaign.get('levels'))
memberIDs = _.map courseInstance.get('members') ? [], (memberID) -> memberID.toHexString?() or memberID
query = {$and: [{creator: {$in: memberIDs}}, {'level.original': {$in: levelIDs}}]}
cursor = LevelSession.find(query)
cursor = cursor.select(req.query.project) if req.query.project
cursor.exec (err, documents) =>
return @sendDatabaseError(res, err) if err?
cleandocs = (LevelSessionHandler.formatEntity(req, doc) for doc in documents)
@sendSuccess(res, cleandocs)
getMyCourseLevelSessionsAPI: (req, res, courseInstanceID) ->
return @sendUnauthorizedError(res) if not req.user?
CourseInstance.findById courseInstanceID, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless courseInstance
Course.findById courseInstance.get('courseID'), (err, course) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless course
Campaign.findById course.get('campaignID'), (err, campaign) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless campaign
levelIDs = (levelID for levelID, level of campaign.get('levels') when not _.contains(level.type, 'ladder'))
query = {$and: [{creator: req.user.id}, {'level.original': {$in: levelIDs}}]}
cursor = LevelSession.find(query)
cursor = cursor.select(req.query.project) if req.query.project
cursor.exec (err, documents) =>
return @sendDatabaseError(res, err) if err?
cleandocs = (LevelSessionHandler.formatEntity(req, doc) for doc in documents)
@sendSuccess(res, cleandocs)
getMembersAPI: (req, res, courseInstanceID) ->
return @sendUnauthorizedError(res) if not req.user?
CourseInstance.findById courseInstanceID, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless courseInstance
memberIDs = courseInstance.get('members') ? []
User.find {_id: {$in: memberIDs}}, (err, users) =>
return @sendDatabaseError(res, err) if err
cleandocs = (UserHandler.formatEntity(req, doc) for doc in users)
@sendSuccess(res, cleandocs)
getRecentAPI: (req, res) ->
return @sendUnauthorizedError(res) unless req.user?.isAdmin()
query = {$and: [{name: {$ne: 'Single Player'}}, {hourOfCode: {$ne: true}}]}
query["$and"].push(_id: {$gte: objectIdFromTimestamp(req.body.startDay + "T00:00:00.000Z")}) if req.body.startDay?
query["$and"].push(_id: {$lt: objectIdFromTimestamp(req.body.endDay + "T00:00:00.000Z")}) if req.body.endDay?
CourseInstance.find query, {courseID: 1, members: 1, ownerID: 1}, (err, courseInstances) =>
return @sendDatabaseError(res, err) if err
userIDs = []
for courseInstance in courseInstances
if members = courseInstance.get('members')
userIDs.push(userID) for userID in members
User.find {_id: {$in: userIDs}}, {coursePrepaidID: 1}, (err, users) =>
return @sendDatabaseError(res, err) if err
prepaidIDs = []
for user in users
if prepaidID = user.get('coursePrepaidID')
prepaidIDs.push(prepaidID)
Prepaid.find {_id: {$in: prepaidIDs}}, {properties: 1}, (err, prepaids) =>
return @sendDatabaseError(res, err) if err
data =
courseInstances: (@formatEntity(req, courseInstance) for courseInstance in courseInstances)
students: (@formatEntity(req, user) for user in users)
prepaids: (@formatEntity(req, prepaid) for prepaid in prepaids)
@sendSuccess(res, data)
inviteStudents: (req, res, courseInstanceID) ->
return @sendUnauthorizedError(res) if not req.user?
if not req.body.emails
return @sendBadInputError(res, 'Emails not included')
CourseInstance.findById courseInstanceID, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless courseInstance
return @sendForbiddenError(res) unless @hasAccessToDocument(req, courseInstance)
Course.findById courseInstance.get('courseID'), (err, course) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless course
Prepaid.findById courseInstance.get('prepaidID'), (err, prepaid) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless prepaid
return @sendForbiddenError(res) unless prepaid.get('maxRedeemers') > prepaid.get('redeemers').length
for email in req.body.emails
context =
email_id: sendwithus.templates.course_invite_email
recipient:
address: email
subject: course.get('name')
email_data:
class_name: course.get('name')
join_link: "https://codecombat.com/courses/students?_ppc=" + prepaid.get('code')
sendwithus.api.send context, _.noop
return @sendSuccess(res, {})
redeemPrepaidCodeAPI: (req, res) ->
return @sendUnauthorizedError(res) if not req.user? or req.user?.isAnonymous()
return @sendBadInputError(res) unless req.body?.prepaidCode
prepaidCode = req.body?.prepaidCode
Prepaid.find code: prepaidCode, (err, prepaids) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) if prepaids.length < 1
return @sendDatabaseError(res, "Multiple prepaid codes found for #{prepaidCode}") if prepaids.length > 1
prepaid = prepaids[0]
CourseInstance.find prepaidID: prepaid.get('_id'), (err, courseInstances) =>
return @sendDatabaseError(res, err) if err
return @sendForbiddenError(res) if prepaid.get('redeemers')?.length >= prepaid.get('maxRedeemers')
if _.find((prepaid.get('redeemers') ? []), (a) -> a.userID.equals(req.user.id))
return @sendSuccess(res, courseInstances)
# Add to prepaid redeemers
query =
_id: prepaid.get('_id')
'redeemers.userID': { $ne: req.user.get('_id') }
$where: "this.redeemers.length < #{prepaid.get('maxRedeemers')}"
update = { $push: { redeemers : { date: new Date(), userID: req.user.get('_id') } }}
Prepaid.update query, update, (err, result) =>
return @sendDatabaseError(res, err) if err
if result?.nModified is 0
@logError(req.user, "Course instance update prepaid lost race on maxRedeemers")
return @sendForbiddenError(res)
# Add to each course instance
makeAddMemberToCourseInstanceFn = (courseInstance) =>
(done) => courseInstance.update({$addToSet: { members: req.user.get('_id')}}, done)
tasks = (makeAddMemberToCourseInstanceFn(courseInstance) for courseInstance in courseInstances)
async.parallel tasks, (err, results) =>
return @sendDatabaseError(res, err) if err
@sendSuccess(res, courseInstances)
findByLevel: (req, res, levelOriginal) ->
return @sendUnauthorizedError(res) if not req.user?
# Find all CourseInstances that req.user is a part of that match the given level.
CourseInstance.find {_id: {$in: req.user.get('courseInstances')}}, (err, courseInstances) =>
return @sendDatabaseError res, err if err
return @sendSuccess res, [] unless courseInstances.length
courseIDs = _.uniq (ci.get('courseID') for ci in courseInstances)
Course.find {_id: {$in: courseIDs}}, {name: 1, campaignID: 1}, (err, courses) =>
return @sendDatabaseError res, err if err
return @sendSuccess res, [] unless courses.length
campaignIDs = _.uniq (c.get('campaignID') for c in courses)
Campaign.find {_id: {$in: campaignIDs}, "levels.#{levelOriginal}": {$exists: true}}, {_id: 1}, (err, campaigns) =>
return @sendDatabaseError res, err if err
return @sendSuccess res, [] unless campaigns.length
courses = _.filter courses, (course) -> _.find campaigns, (campaign) -> campaign.get('_id').toString() is course.get('campaignID').toString()
courseInstances = _.filter courseInstances, (courseInstance) -> _.find courses, (course) -> course.get('_id').toString() is courseInstance.get('courseID').toString()
return @sendSuccess res, courseInstances
get: (req, res) ->
if ownerID = req.query.ownerID
return @sendForbiddenError(res) unless req.user and (req.user.isAdmin() or ownerID is req.user.id)
return @sendBadInputError(res, 'Bad ownerID') unless utils.isID ownerID
CourseInstance.find {ownerID: mongoose.Types.ObjectId(ownerID)}, (err, courseInstances) =>
return @sendDatabaseError(res, err) if err
return @sendSuccess(res, (@formatEntity(req, courseInstance) for courseInstance in courseInstances))
else if memberID = req.query.memberID
return @sendForbiddenError(res) unless req.user and (req.user.isAdmin() or memberID is req.user.id)
return @sendBadInputError(res, 'Bad memberID') unless utils.isID memberID
CourseInstance.find {members: mongoose.Types.ObjectId(memberID)}, (err, courseInstances) =>
return @sendDatabaseError(res, err) if err
return @sendSuccess(res, (@formatEntity(req, courseInstance) for courseInstance in courseInstances))
else if classroomID = req.query.classroomID
return @sendForbiddenError(res) unless req.user
return @sendBadInputError(res, 'Bad memberID') unless utils.isID classroomID
Classroom.findById classroomID, (err, classroom) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless classroom
return @sendForbiddenError(res) unless classroom.isMember(req.user._id) or classroom.isOwner(req.user._id)
CourseInstance.find {classroomID: mongoose.Types.ObjectId(classroomID)}, (err, courseInstances) =>
return @sendDatabaseError(res, err) if err
return @sendSuccess(res, (@formatEntity(req, courseInstance) for courseInstance in courseInstances))
else
super(arguments...)
module.exports = new CourseInstanceHandler()
| 195775 | async = require 'async'
Handler = require '../commons/Handler'
Campaign = require '../campaigns/Campaign'
Classroom = require '../classrooms/Classroom'
Course = require './Course'
CourseInstance = require './CourseInstance'
LevelSession = require '../levels/sessions/LevelSession'
LevelSessionHandler = require '../levels/sessions/level_session_handler'
Prepaid = require '../prepaids/Prepaid'
PrepaidHandler = require '../prepaids/prepaid_handler'
User = require '../users/User'
UserHandler = require '../users/user_handler'
utils = require '../../app/core/utils'
{objectIdFromTimestamp} = require '../lib/utils'
sendwithus = require '../sendwithus'
mongoose = require 'mongoose'
CourseInstanceHandler = class CourseInstanceHandler extends Handler
modelClass: CourseInstance
jsonSchema: require '../../app/schemas/models/course_instance.schema'
allowedMethods: ['GET', 'POST', 'PUT', 'DELETE']
logError: (user, msg) ->
console.warn "Course instance error: #{user.get('slug')} (#{user._id}): '#{msg}'"
hasAccess: (req) ->
req.method in @allowedMethods or req.user?.isAdmin()
hasAccessToDocument: (req, document, method=null) ->
return true if document?.get('ownerID')?.equals(req.user?.get('_id'))
return true if req.method is 'GET' and _.find document?.get('members'), (a) -> a.equals(req.user?.get('_id'))
req.user?.isAdmin()
getByRelationship: (req, res, args...) ->
relationship = args[1]
return @createHOCAPI(req, res) if relationship is 'create-for-hoc'
return @getLevelSessionsAPI(req, res, args[0]) if args[1] is 'level_sessions'
return @addMember(req, res, args[0]) if req.method is 'POST' and args[1] is 'members'
return @removeMember(req, res, args[0]) if req.method is 'DELETE' and args[1] is 'members'
return @getMembersAPI(req, res, args[0]) if args[1] is 'members'
return @inviteStudents(req, res, args[0]) if relationship is 'invite_students'
return @getRecentAPI(req, res) if relationship is 'recent'
return @redeemPrepaidCodeAPI(req, res) if args[1] is 'redeem_prepaid'
return @getMyCourseLevelSessionsAPI(req, res, args[0]) if args[1] is 'my-course-level-sessions'
return @findByLevel(req, res, args[2]) if args[1] is 'find_by_level'
super arguments...
createHOCAPI: (req, res) ->
return @sendUnauthorizedError(res) if not req.user?
courseID = mongoose.Types.ObjectId('560f1a9f22961295f9427742')
CourseInstance.findOne { courseID: courseID, ownerID: req.user.get('_id'), hourOfCode: true }, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
if courseInstance
console.log 'already made a course instance'
return @sendSuccess(res, courseInstance) if courseInstance
courseInstance = new CourseInstance({
courseID: courseID
members: [req.user.get('_id')]
name: '<NAME>'
ownerID: req.user.get('_id')
aceConfig: { language: 'python' }
hourOfCode: true
})
courseInstance.save (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
@sendCreated(res, courseInstance)
addMember: (req, res, courseInstanceID) ->
return @sendUnauthorizedError(res) if not req.user?
userID = req.body.userID
return @sendBadInputError(res, 'Input must be a MongoDB ID') unless utils.isID(userID)
CourseInstance.findById courseInstanceID, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Course instance not found') unless courseInstance
Classroom.findById courseInstance.get('classroomID'), (err, classroom) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Classroom referenced by course instance not found') unless classroom
return @sendForbiddenError(res) unless _.any(classroom.get('members'), (memberID) -> memberID.toString() is userID)
ownsCourseInstance = courseInstance.get('ownerID').equals(req.user.get('_id'))
addingSelf = userID is req.user.id
return @sendForbiddenError(res) unless ownsCourseInstance or addingSelf
alreadyInCourseInstance = _.any courseInstance.get('members') or [], (memberID) -> memberID.toString() is userID
return @sendSuccess(res, @formatEntity(req, courseInstance)) if alreadyInCourseInstance
Prepaid.find({ 'redeemers.userID': mongoose.Types.ObjectId(userID) }).count (err, userIsPrepaid) =>
return @sendDatabaseError(res, err) if err
Course.findById courseInstance.get('courseID'), (err, course) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Course referenced by course instance not found') unless course
if not (course.get('free') or userIsPrepaid)
return @sendPaymentRequiredError(res, 'Cannot add this user to a course instance until they are added to a prepaid')
members = courseInstance.get('members')
members.push(userID)
courseInstance.set('members', members)
courseInstance.save (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
User.update {_id: mongoose.Types.ObjectId(userID)}, {$addToSet: {courseInstances: courseInstance.get('_id')}}, (err) =>
return @sendDatabaseError(res, err) if err
@sendSuccess(res, @formatEntity(req, courseInstance))
removeMember: (req, res, courseInstanceID) ->
return @sendUnauthorizedError(res) if not req.user?
userID = req.body.userID
return @sendBadInputError(res, 'Input must be a MongoDB ID') unless utils.isID(userID)
CourseInstance.findById courseInstanceID, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Course instance not found') unless courseInstance
Classroom.findById courseInstance.get('classroomID'), (err, classroom) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Classroom referenced by course instance not found') unless classroom
return @sendForbiddenError(res) unless _.any(classroom.get('members'), (memberID) -> memberID.toString() is userID)
ownsCourseInstance = courseInstance.get('ownerID').equals(req.user.get('_id'))
removingSelf = userID is req.user.id
return @sendForbiddenError(res) unless ownsCourseInstance or removingSelf
alreadyNotInCourseInstance = not _.any courseInstance.get('members') or [], (memberID) -> memberID.toString() is userID
return @sendSuccess(res, @formatEntity(req, courseInstance)) if alreadyNotInCourseInstance
members = _.clone(courseInstance.get('members'))
members = (m for m in members when m.toString() isnt userID)
courseInstance.set('members', members)
courseInstance.save (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
User.update {_id: mongoose.Types.ObjectId(userID)}, {$pull: {courseInstances: courseInstance.get('_id')}}, (err) =>
return @sendDatabaseError(res, err) if err
@sendSuccess(res, @formatEntity(req, courseInstance))
post: (req, res) ->
return @sendUnauthorizedError(res) if not req.user?
return @sendBadInputError(res, 'No classroomID') unless req.body.classroomID
return @sendBadInputError(res, 'No courseID') unless req.body.courseID
Classroom.findById req.body.classroomID, (err, classroom) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Classroom not found') unless classroom
return @sendForbiddenError(res) unless classroom.get('ownerID').equals(req.user.get('_id'))
Course.findById req.body.courseID, (err, course) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Course not found') unless course
q = {
courseID: mongoose.Types.ObjectId(req.body.courseID)
classroomID: mongoose.Types.ObjectId(req.body.classroomID)
}
CourseInstance.findOne(q).exec (err, doc) =>
return @sendDatabaseError(res, err) if err
return @sendSuccess(res, @formatEntity(req, doc)) if doc
super(req, res)
makeNewInstance: (req) ->
doc = new CourseInstance({
members: []
ownerID: req.user.get('_id')
})
doc.set('aceConfig', {}) # constructor will ignore empty objects
return doc
getLevelSessionsAPI: (req, res, courseInstanceID) ->
return @sendUnauthorizedError(res) if not req.user?
CourseInstance.findById courseInstanceID, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless courseInstance
Course.findById courseInstance.get('courseID'), (err, course) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless course
Campaign.findById course.get('campaignID'), (err, campaign) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless campaign
levelIDs = (levelID for levelID of campaign.get('levels'))
memberIDs = _.map courseInstance.get('members') ? [], (memberID) -> memberID.toHexString?() or memberID
query = {$and: [{creator: {$in: memberIDs}}, {'level.original': {$in: levelIDs}}]}
cursor = LevelSession.find(query)
cursor = cursor.select(req.query.project) if req.query.project
cursor.exec (err, documents) =>
return @sendDatabaseError(res, err) if err?
cleandocs = (LevelSessionHandler.formatEntity(req, doc) for doc in documents)
@sendSuccess(res, cleandocs)
getMyCourseLevelSessionsAPI: (req, res, courseInstanceID) ->
return @sendUnauthorizedError(res) if not req.user?
CourseInstance.findById courseInstanceID, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless courseInstance
Course.findById courseInstance.get('courseID'), (err, course) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless course
Campaign.findById course.get('campaignID'), (err, campaign) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless campaign
levelIDs = (levelID for levelID, level of campaign.get('levels') when not _.contains(level.type, 'ladder'))
query = {$and: [{creator: req.user.id}, {'level.original': {$in: levelIDs}}]}
cursor = LevelSession.find(query)
cursor = cursor.select(req.query.project) if req.query.project
cursor.exec (err, documents) =>
return @sendDatabaseError(res, err) if err?
cleandocs = (LevelSessionHandler.formatEntity(req, doc) for doc in documents)
@sendSuccess(res, cleandocs)
getMembersAPI: (req, res, courseInstanceID) ->
return @sendUnauthorizedError(res) if not req.user?
CourseInstance.findById courseInstanceID, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless courseInstance
memberIDs = courseInstance.get('members') ? []
User.find {_id: {$in: memberIDs}}, (err, users) =>
return @sendDatabaseError(res, err) if err
cleandocs = (UserHandler.formatEntity(req, doc) for doc in users)
@sendSuccess(res, cleandocs)
getRecentAPI: (req, res) ->
return @sendUnauthorizedError(res) unless req.user?.isAdmin()
query = {$and: [{name: {$ne: 'Single Player'}}, {hourOfCode: {$ne: true}}]}
query["$and"].push(_id: {$gte: objectIdFromTimestamp(req.body.startDay + "T00:00:00.000Z")}) if req.body.startDay?
query["$and"].push(_id: {$lt: objectIdFromTimestamp(req.body.endDay + "T00:00:00.000Z")}) if req.body.endDay?
CourseInstance.find query, {courseID: 1, members: 1, ownerID: 1}, (err, courseInstances) =>
return @sendDatabaseError(res, err) if err
userIDs = []
for courseInstance in courseInstances
if members = courseInstance.get('members')
userIDs.push(userID) for userID in members
User.find {_id: {$in: userIDs}}, {coursePrepaidID: 1}, (err, users) =>
return @sendDatabaseError(res, err) if err
prepaidIDs = []
for user in users
if prepaidID = user.get('coursePrepaidID')
prepaidIDs.push(prepaidID)
Prepaid.find {_id: {$in: prepaidIDs}}, {properties: 1}, (err, prepaids) =>
return @sendDatabaseError(res, err) if err
data =
courseInstances: (@formatEntity(req, courseInstance) for courseInstance in courseInstances)
students: (@formatEntity(req, user) for user in users)
prepaids: (@formatEntity(req, prepaid) for prepaid in prepaids)
@sendSuccess(res, data)
inviteStudents: (req, res, courseInstanceID) ->
return @sendUnauthorizedError(res) if not req.user?
if not req.body.emails
return @sendBadInputError(res, 'Emails not included')
CourseInstance.findById courseInstanceID, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless courseInstance
return @sendForbiddenError(res) unless @hasAccessToDocument(req, courseInstance)
Course.findById courseInstance.get('courseID'), (err, course) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless course
Prepaid.findById courseInstance.get('prepaidID'), (err, prepaid) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless prepaid
return @sendForbiddenError(res) unless prepaid.get('maxRedeemers') > prepaid.get('redeemers').length
for email in req.body.emails
context =
email_id: sendwithus.templates.course_invite_email
recipient:
address: email
subject: course.get('name')
email_data:
class_name: course.get('name')
join_link: "https://codecombat.com/courses/students?_ppc=" + prepaid.get('code')
sendwithus.api.send context, _.noop
return @sendSuccess(res, {})
redeemPrepaidCodeAPI: (req, res) ->
return @sendUnauthorizedError(res) if not req.user? or req.user?.isAnonymous()
return @sendBadInputError(res) unless req.body?.prepaidCode
prepaidCode = req.body?.prepaidCode
Prepaid.find code: prepaidCode, (err, prepaids) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) if prepaids.length < 1
return @sendDatabaseError(res, "Multiple prepaid codes found for #{prepaidCode}") if prepaids.length > 1
prepaid = prepaids[0]
CourseInstance.find prepaidID: prepaid.get('_id'), (err, courseInstances) =>
return @sendDatabaseError(res, err) if err
return @sendForbiddenError(res) if prepaid.get('redeemers')?.length >= prepaid.get('maxRedeemers')
if _.find((prepaid.get('redeemers') ? []), (a) -> a.userID.equals(req.user.id))
return @sendSuccess(res, courseInstances)
# Add to prepaid redeemers
query =
_id: prepaid.get('_id')
'redeemers.userID': { $ne: req.user.get('_id') }
$where: "this.redeemers.length < #{prepaid.get('maxRedeemers')}"
update = { $push: { redeemers : { date: new Date(), userID: req.user.get('_id') } }}
Prepaid.update query, update, (err, result) =>
return @sendDatabaseError(res, err) if err
if result?.nModified is 0
@logError(req.user, "Course instance update prepaid lost race on maxRedeemers")
return @sendForbiddenError(res)
# Add to each course instance
makeAddMemberToCourseInstanceFn = (courseInstance) =>
(done) => courseInstance.update({$addToSet: { members: req.user.get('_id')}}, done)
tasks = (makeAddMemberToCourseInstanceFn(courseInstance) for courseInstance in courseInstances)
async.parallel tasks, (err, results) =>
return @sendDatabaseError(res, err) if err
@sendSuccess(res, courseInstances)
findByLevel: (req, res, levelOriginal) ->
return @sendUnauthorizedError(res) if not req.user?
# Find all CourseInstances that req.user is a part of that match the given level.
CourseInstance.find {_id: {$in: req.user.get('courseInstances')}}, (err, courseInstances) =>
return @sendDatabaseError res, err if err
return @sendSuccess res, [] unless courseInstances.length
courseIDs = _.uniq (ci.get('courseID') for ci in courseInstances)
Course.find {_id: {$in: courseIDs}}, {name: 1, campaignID: 1}, (err, courses) =>
return @sendDatabaseError res, err if err
return @sendSuccess res, [] unless courses.length
campaignIDs = _.uniq (c.get('campaignID') for c in courses)
Campaign.find {_id: {$in: campaignIDs}, "levels.#{levelOriginal}": {$exists: true}}, {_id: 1}, (err, campaigns) =>
return @sendDatabaseError res, err if err
return @sendSuccess res, [] unless campaigns.length
courses = _.filter courses, (course) -> _.find campaigns, (campaign) -> campaign.get('_id').toString() is course.get('campaignID').toString()
courseInstances = _.filter courseInstances, (courseInstance) -> _.find courses, (course) -> course.get('_id').toString() is courseInstance.get('courseID').toString()
return @sendSuccess res, courseInstances
get: (req, res) ->
if ownerID = req.query.ownerID
return @sendForbiddenError(res) unless req.user and (req.user.isAdmin() or ownerID is req.user.id)
return @sendBadInputError(res, 'Bad ownerID') unless utils.isID ownerID
CourseInstance.find {ownerID: mongoose.Types.ObjectId(ownerID)}, (err, courseInstances) =>
return @sendDatabaseError(res, err) if err
return @sendSuccess(res, (@formatEntity(req, courseInstance) for courseInstance in courseInstances))
else if memberID = req.query.memberID
return @sendForbiddenError(res) unless req.user and (req.user.isAdmin() or memberID is req.user.id)
return @sendBadInputError(res, 'Bad memberID') unless utils.isID memberID
CourseInstance.find {members: mongoose.Types.ObjectId(memberID)}, (err, courseInstances) =>
return @sendDatabaseError(res, err) if err
return @sendSuccess(res, (@formatEntity(req, courseInstance) for courseInstance in courseInstances))
else if classroomID = req.query.classroomID
return @sendForbiddenError(res) unless req.user
return @sendBadInputError(res, 'Bad memberID') unless utils.isID classroomID
Classroom.findById classroomID, (err, classroom) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless classroom
return @sendForbiddenError(res) unless classroom.isMember(req.user._id) or classroom.isOwner(req.user._id)
CourseInstance.find {classroomID: mongoose.Types.ObjectId(classroomID)}, (err, courseInstances) =>
return @sendDatabaseError(res, err) if err
return @sendSuccess(res, (@formatEntity(req, courseInstance) for courseInstance in courseInstances))
else
super(arguments...)
module.exports = new CourseInstanceHandler()
| true | async = require 'async'
Handler = require '../commons/Handler'
Campaign = require '../campaigns/Campaign'
Classroom = require '../classrooms/Classroom'
Course = require './Course'
CourseInstance = require './CourseInstance'
LevelSession = require '../levels/sessions/LevelSession'
LevelSessionHandler = require '../levels/sessions/level_session_handler'
Prepaid = require '../prepaids/Prepaid'
PrepaidHandler = require '../prepaids/prepaid_handler'
User = require '../users/User'
UserHandler = require '../users/user_handler'
utils = require '../../app/core/utils'
{objectIdFromTimestamp} = require '../lib/utils'
sendwithus = require '../sendwithus'
mongoose = require 'mongoose'
CourseInstanceHandler = class CourseInstanceHandler extends Handler
modelClass: CourseInstance
jsonSchema: require '../../app/schemas/models/course_instance.schema'
allowedMethods: ['GET', 'POST', 'PUT', 'DELETE']
logError: (user, msg) ->
console.warn "Course instance error: #{user.get('slug')} (#{user._id}): '#{msg}'"
hasAccess: (req) ->
req.method in @allowedMethods or req.user?.isAdmin()
hasAccessToDocument: (req, document, method=null) ->
return true if document?.get('ownerID')?.equals(req.user?.get('_id'))
return true if req.method is 'GET' and _.find document?.get('members'), (a) -> a.equals(req.user?.get('_id'))
req.user?.isAdmin()
getByRelationship: (req, res, args...) ->
relationship = args[1]
return @createHOCAPI(req, res) if relationship is 'create-for-hoc'
return @getLevelSessionsAPI(req, res, args[0]) if args[1] is 'level_sessions'
return @addMember(req, res, args[0]) if req.method is 'POST' and args[1] is 'members'
return @removeMember(req, res, args[0]) if req.method is 'DELETE' and args[1] is 'members'
return @getMembersAPI(req, res, args[0]) if args[1] is 'members'
return @inviteStudents(req, res, args[0]) if relationship is 'invite_students'
return @getRecentAPI(req, res) if relationship is 'recent'
return @redeemPrepaidCodeAPI(req, res) if args[1] is 'redeem_prepaid'
return @getMyCourseLevelSessionsAPI(req, res, args[0]) if args[1] is 'my-course-level-sessions'
return @findByLevel(req, res, args[2]) if args[1] is 'find_by_level'
super arguments...
createHOCAPI: (req, res) ->
return @sendUnauthorizedError(res) if not req.user?
courseID = mongoose.Types.ObjectId('560f1a9f22961295f9427742')
CourseInstance.findOne { courseID: courseID, ownerID: req.user.get('_id'), hourOfCode: true }, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
if courseInstance
console.log 'already made a course instance'
return @sendSuccess(res, courseInstance) if courseInstance
courseInstance = new CourseInstance({
courseID: courseID
members: [req.user.get('_id')]
name: 'PI:NAME:<NAME>END_PI'
ownerID: req.user.get('_id')
aceConfig: { language: 'python' }
hourOfCode: true
})
courseInstance.save (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
@sendCreated(res, courseInstance)
addMember: (req, res, courseInstanceID) ->
return @sendUnauthorizedError(res) if not req.user?
userID = req.body.userID
return @sendBadInputError(res, 'Input must be a MongoDB ID') unless utils.isID(userID)
CourseInstance.findById courseInstanceID, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Course instance not found') unless courseInstance
Classroom.findById courseInstance.get('classroomID'), (err, classroom) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Classroom referenced by course instance not found') unless classroom
return @sendForbiddenError(res) unless _.any(classroom.get('members'), (memberID) -> memberID.toString() is userID)
ownsCourseInstance = courseInstance.get('ownerID').equals(req.user.get('_id'))
addingSelf = userID is req.user.id
return @sendForbiddenError(res) unless ownsCourseInstance or addingSelf
alreadyInCourseInstance = _.any courseInstance.get('members') or [], (memberID) -> memberID.toString() is userID
return @sendSuccess(res, @formatEntity(req, courseInstance)) if alreadyInCourseInstance
Prepaid.find({ 'redeemers.userID': mongoose.Types.ObjectId(userID) }).count (err, userIsPrepaid) =>
return @sendDatabaseError(res, err) if err
Course.findById courseInstance.get('courseID'), (err, course) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Course referenced by course instance not found') unless course
if not (course.get('free') or userIsPrepaid)
return @sendPaymentRequiredError(res, 'Cannot add this user to a course instance until they are added to a prepaid')
members = courseInstance.get('members')
members.push(userID)
courseInstance.set('members', members)
courseInstance.save (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
User.update {_id: mongoose.Types.ObjectId(userID)}, {$addToSet: {courseInstances: courseInstance.get('_id')}}, (err) =>
return @sendDatabaseError(res, err) if err
@sendSuccess(res, @formatEntity(req, courseInstance))
removeMember: (req, res, courseInstanceID) ->
return @sendUnauthorizedError(res) if not req.user?
userID = req.body.userID
return @sendBadInputError(res, 'Input must be a MongoDB ID') unless utils.isID(userID)
CourseInstance.findById courseInstanceID, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Course instance not found') unless courseInstance
Classroom.findById courseInstance.get('classroomID'), (err, classroom) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Classroom referenced by course instance not found') unless classroom
return @sendForbiddenError(res) unless _.any(classroom.get('members'), (memberID) -> memberID.toString() is userID)
ownsCourseInstance = courseInstance.get('ownerID').equals(req.user.get('_id'))
removingSelf = userID is req.user.id
return @sendForbiddenError(res) unless ownsCourseInstance or removingSelf
alreadyNotInCourseInstance = not _.any courseInstance.get('members') or [], (memberID) -> memberID.toString() is userID
return @sendSuccess(res, @formatEntity(req, courseInstance)) if alreadyNotInCourseInstance
members = _.clone(courseInstance.get('members'))
members = (m for m in members when m.toString() isnt userID)
courseInstance.set('members', members)
courseInstance.save (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
User.update {_id: mongoose.Types.ObjectId(userID)}, {$pull: {courseInstances: courseInstance.get('_id')}}, (err) =>
return @sendDatabaseError(res, err) if err
@sendSuccess(res, @formatEntity(req, courseInstance))
post: (req, res) ->
return @sendUnauthorizedError(res) if not req.user?
return @sendBadInputError(res, 'No classroomID') unless req.body.classroomID
return @sendBadInputError(res, 'No courseID') unless req.body.courseID
Classroom.findById req.body.classroomID, (err, classroom) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Classroom not found') unless classroom
return @sendForbiddenError(res) unless classroom.get('ownerID').equals(req.user.get('_id'))
Course.findById req.body.courseID, (err, course) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res, 'Course not found') unless course
q = {
courseID: mongoose.Types.ObjectId(req.body.courseID)
classroomID: mongoose.Types.ObjectId(req.body.classroomID)
}
CourseInstance.findOne(q).exec (err, doc) =>
return @sendDatabaseError(res, err) if err
return @sendSuccess(res, @formatEntity(req, doc)) if doc
super(req, res)
makeNewInstance: (req) ->
doc = new CourseInstance({
members: []
ownerID: req.user.get('_id')
})
doc.set('aceConfig', {}) # constructor will ignore empty objects
return doc
getLevelSessionsAPI: (req, res, courseInstanceID) ->
return @sendUnauthorizedError(res) if not req.user?
CourseInstance.findById courseInstanceID, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless courseInstance
Course.findById courseInstance.get('courseID'), (err, course) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless course
Campaign.findById course.get('campaignID'), (err, campaign) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless campaign
levelIDs = (levelID for levelID of campaign.get('levels'))
memberIDs = _.map courseInstance.get('members') ? [], (memberID) -> memberID.toHexString?() or memberID
query = {$and: [{creator: {$in: memberIDs}}, {'level.original': {$in: levelIDs}}]}
cursor = LevelSession.find(query)
cursor = cursor.select(req.query.project) if req.query.project
cursor.exec (err, documents) =>
return @sendDatabaseError(res, err) if err?
cleandocs = (LevelSessionHandler.formatEntity(req, doc) for doc in documents)
@sendSuccess(res, cleandocs)
getMyCourseLevelSessionsAPI: (req, res, courseInstanceID) ->
return @sendUnauthorizedError(res) if not req.user?
CourseInstance.findById courseInstanceID, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless courseInstance
Course.findById courseInstance.get('courseID'), (err, course) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless course
Campaign.findById course.get('campaignID'), (err, campaign) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless campaign
levelIDs = (levelID for levelID, level of campaign.get('levels') when not _.contains(level.type, 'ladder'))
query = {$and: [{creator: req.user.id}, {'level.original': {$in: levelIDs}}]}
cursor = LevelSession.find(query)
cursor = cursor.select(req.query.project) if req.query.project
cursor.exec (err, documents) =>
return @sendDatabaseError(res, err) if err?
cleandocs = (LevelSessionHandler.formatEntity(req, doc) for doc in documents)
@sendSuccess(res, cleandocs)
getMembersAPI: (req, res, courseInstanceID) ->
return @sendUnauthorizedError(res) if not req.user?
CourseInstance.findById courseInstanceID, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless courseInstance
memberIDs = courseInstance.get('members') ? []
User.find {_id: {$in: memberIDs}}, (err, users) =>
return @sendDatabaseError(res, err) if err
cleandocs = (UserHandler.formatEntity(req, doc) for doc in users)
@sendSuccess(res, cleandocs)
getRecentAPI: (req, res) ->
return @sendUnauthorizedError(res) unless req.user?.isAdmin()
query = {$and: [{name: {$ne: 'Single Player'}}, {hourOfCode: {$ne: true}}]}
query["$and"].push(_id: {$gte: objectIdFromTimestamp(req.body.startDay + "T00:00:00.000Z")}) if req.body.startDay?
query["$and"].push(_id: {$lt: objectIdFromTimestamp(req.body.endDay + "T00:00:00.000Z")}) if req.body.endDay?
CourseInstance.find query, {courseID: 1, members: 1, ownerID: 1}, (err, courseInstances) =>
return @sendDatabaseError(res, err) if err
userIDs = []
for courseInstance in courseInstances
if members = courseInstance.get('members')
userIDs.push(userID) for userID in members
User.find {_id: {$in: userIDs}}, {coursePrepaidID: 1}, (err, users) =>
return @sendDatabaseError(res, err) if err
prepaidIDs = []
for user in users
if prepaidID = user.get('coursePrepaidID')
prepaidIDs.push(prepaidID)
Prepaid.find {_id: {$in: prepaidIDs}}, {properties: 1}, (err, prepaids) =>
return @sendDatabaseError(res, err) if err
data =
courseInstances: (@formatEntity(req, courseInstance) for courseInstance in courseInstances)
students: (@formatEntity(req, user) for user in users)
prepaids: (@formatEntity(req, prepaid) for prepaid in prepaids)
@sendSuccess(res, data)
inviteStudents: (req, res, courseInstanceID) ->
return @sendUnauthorizedError(res) if not req.user?
if not req.body.emails
return @sendBadInputError(res, 'Emails not included')
CourseInstance.findById courseInstanceID, (err, courseInstance) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless courseInstance
return @sendForbiddenError(res) unless @hasAccessToDocument(req, courseInstance)
Course.findById courseInstance.get('courseID'), (err, course) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless course
Prepaid.findById courseInstance.get('prepaidID'), (err, prepaid) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless prepaid
return @sendForbiddenError(res) unless prepaid.get('maxRedeemers') > prepaid.get('redeemers').length
for email in req.body.emails
context =
email_id: sendwithus.templates.course_invite_email
recipient:
address: email
subject: course.get('name')
email_data:
class_name: course.get('name')
join_link: "https://codecombat.com/courses/students?_ppc=" + prepaid.get('code')
sendwithus.api.send context, _.noop
return @sendSuccess(res, {})
redeemPrepaidCodeAPI: (req, res) ->
return @sendUnauthorizedError(res) if not req.user? or req.user?.isAnonymous()
return @sendBadInputError(res) unless req.body?.prepaidCode
prepaidCode = req.body?.prepaidCode
Prepaid.find code: prepaidCode, (err, prepaids) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) if prepaids.length < 1
return @sendDatabaseError(res, "Multiple prepaid codes found for #{prepaidCode}") if prepaids.length > 1
prepaid = prepaids[0]
CourseInstance.find prepaidID: prepaid.get('_id'), (err, courseInstances) =>
return @sendDatabaseError(res, err) if err
return @sendForbiddenError(res) if prepaid.get('redeemers')?.length >= prepaid.get('maxRedeemers')
if _.find((prepaid.get('redeemers') ? []), (a) -> a.userID.equals(req.user.id))
return @sendSuccess(res, courseInstances)
# Add to prepaid redeemers
query =
_id: prepaid.get('_id')
'redeemers.userID': { $ne: req.user.get('_id') }
$where: "this.redeemers.length < #{prepaid.get('maxRedeemers')}"
update = { $push: { redeemers : { date: new Date(), userID: req.user.get('_id') } }}
Prepaid.update query, update, (err, result) =>
return @sendDatabaseError(res, err) if err
if result?.nModified is 0
@logError(req.user, "Course instance update prepaid lost race on maxRedeemers")
return @sendForbiddenError(res)
# Add to each course instance
makeAddMemberToCourseInstanceFn = (courseInstance) =>
(done) => courseInstance.update({$addToSet: { members: req.user.get('_id')}}, done)
tasks = (makeAddMemberToCourseInstanceFn(courseInstance) for courseInstance in courseInstances)
async.parallel tasks, (err, results) =>
return @sendDatabaseError(res, err) if err
@sendSuccess(res, courseInstances)
findByLevel: (req, res, levelOriginal) ->
return @sendUnauthorizedError(res) if not req.user?
# Find all CourseInstances that req.user is a part of that match the given level.
CourseInstance.find {_id: {$in: req.user.get('courseInstances')}}, (err, courseInstances) =>
return @sendDatabaseError res, err if err
return @sendSuccess res, [] unless courseInstances.length
courseIDs = _.uniq (ci.get('courseID') for ci in courseInstances)
Course.find {_id: {$in: courseIDs}}, {name: 1, campaignID: 1}, (err, courses) =>
return @sendDatabaseError res, err if err
return @sendSuccess res, [] unless courses.length
campaignIDs = _.uniq (c.get('campaignID') for c in courses)
Campaign.find {_id: {$in: campaignIDs}, "levels.#{levelOriginal}": {$exists: true}}, {_id: 1}, (err, campaigns) =>
return @sendDatabaseError res, err if err
return @sendSuccess res, [] unless campaigns.length
courses = _.filter courses, (course) -> _.find campaigns, (campaign) -> campaign.get('_id').toString() is course.get('campaignID').toString()
courseInstances = _.filter courseInstances, (courseInstance) -> _.find courses, (course) -> course.get('_id').toString() is courseInstance.get('courseID').toString()
return @sendSuccess res, courseInstances
get: (req, res) ->
if ownerID = req.query.ownerID
return @sendForbiddenError(res) unless req.user and (req.user.isAdmin() or ownerID is req.user.id)
return @sendBadInputError(res, 'Bad ownerID') unless utils.isID ownerID
CourseInstance.find {ownerID: mongoose.Types.ObjectId(ownerID)}, (err, courseInstances) =>
return @sendDatabaseError(res, err) if err
return @sendSuccess(res, (@formatEntity(req, courseInstance) for courseInstance in courseInstances))
else if memberID = req.query.memberID
return @sendForbiddenError(res) unless req.user and (req.user.isAdmin() or memberID is req.user.id)
return @sendBadInputError(res, 'Bad memberID') unless utils.isID memberID
CourseInstance.find {members: mongoose.Types.ObjectId(memberID)}, (err, courseInstances) =>
return @sendDatabaseError(res, err) if err
return @sendSuccess(res, (@formatEntity(req, courseInstance) for courseInstance in courseInstances))
else if classroomID = req.query.classroomID
return @sendForbiddenError(res) unless req.user
return @sendBadInputError(res, 'Bad memberID') unless utils.isID classroomID
Classroom.findById classroomID, (err, classroom) =>
return @sendDatabaseError(res, err) if err
return @sendNotFoundError(res) unless classroom
return @sendForbiddenError(res) unless classroom.isMember(req.user._id) or classroom.isOwner(req.user._id)
CourseInstance.find {classroomID: mongoose.Types.ObjectId(classroomID)}, (err, courseInstances) =>
return @sendDatabaseError(res, err) if err
return @sendSuccess(res, (@formatEntity(req, courseInstance) for courseInstance in courseInstances))
else
super(arguments...)
module.exports = new CourseInstanceHandler()
|
[
{
"context": "# -*- coding: utf-8 -*-\n# Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>\n#\n# Redistribution and u",
"end": 59,
"score": 0.9997926354408264,
"start": 46,
"tag": "NAME",
"value": "Yusuke Suzuki"
},
{
"context": "g: utf-8 -*-\n# Copyright (C) 2015 Yusuke Su... | test/es6.coffee | svenanders/estraverse-compat | 2 | # -*- coding: utf-8 -*-
# Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'use strict'
Dumper = require './dumper'
harmony = require './third_party/esprima'
espree = require 'espree'
{expect} = require 'chai'
{traverse} = require '..'
classDeclaration = ->
program = harmony.parse """
class Hello {
};
"""
program.body[0]
describe 'rest expression', ->
it 'argument', ->
tree =
type: 'RestElement'
argument: {
type: 'Identifier'
name: 'hello'
}
expect(Dumper.dump(tree)).to.be.equal """
enter - RestElement
enter - Identifier
leave - Identifier
leave - RestElement
"""
describe 'class', ->
it 'declaration#1', ->
tree = harmony.parse """
class Hello extends World {
method() {
}
};
"""
expect(Dumper.dump(tree)).to.be.equal """
enter - Program
enter - ClassDeclaration
enter - Identifier
leave - Identifier
enter - Identifier
leave - Identifier
enter - ClassBody
enter - MethodDefinition
enter - Identifier
leave - Identifier
enter - FunctionExpression
enter - BlockStatement
leave - BlockStatement
leave - FunctionExpression
leave - MethodDefinition
leave - ClassBody
leave - ClassDeclaration
enter - EmptyStatement
leave - EmptyStatement
leave - Program
"""
it 'declaration#2', ->
tree = harmony.parse """
class Hello extends ok() {
method() {
}
};
"""
expect(Dumper.dump(tree)).to.be.equal """
enter - Program
enter - ClassDeclaration
enter - Identifier
leave - Identifier
enter - CallExpression
enter - Identifier
leave - Identifier
leave - CallExpression
enter - ClassBody
enter - MethodDefinition
enter - Identifier
leave - Identifier
enter - FunctionExpression
enter - BlockStatement
leave - BlockStatement
leave - FunctionExpression
leave - MethodDefinition
leave - ClassBody
leave - ClassDeclaration
enter - EmptyStatement
leave - EmptyStatement
leave - Program
"""
describe 'export', ->
it 'named declaration #1', ->
tree =
type: 'ExportNamedDeclaration'
declaration: {
type: 'VariableDeclaration'
declarations: [{
type: 'VariableDeclarator'
id: {
type: 'Identifier'
name: 'hello'
}
init: {
type: 'Literal'
value: 6
}
}]
}
expect(Dumper.dump(tree)).to.be.equal """
enter - ExportNamedDeclaration
enter - VariableDeclaration
enter - VariableDeclarator
enter - Identifier
leave - Identifier
enter - Literal
leave - Literal
leave - VariableDeclarator
leave - VariableDeclaration
leave - ExportNamedDeclaration
"""
it 'named declaration #2', ->
tree =
type: 'ExportNamedDeclaration'
declaration: null
specifiers: [{
type: 'ExportSpecifier',
exported: {
type: 'Identifier',
name: 'foo'
}
local: {
type: 'Identifier',
name: 'bar'
}
}]
source: {
type: 'Literal',
value: 'hello'
}
expect(Dumper.dump(tree)).to.be.equal """
enter - ExportNamedDeclaration
enter - ExportSpecifier
enter - Identifier
leave - Identifier
enter - Identifier
leave - Identifier
leave - ExportSpecifier
enter - Literal
leave - Literal
leave - ExportNamedDeclaration
"""
it 'all declaration #1', ->
tree =
type: 'ExportAllDeclaration'
source: {
type: 'Literal',
value: 'hello'
}
expect(Dumper.dump(tree)).to.be.equal """
enter - ExportAllDeclaration
enter - Literal
leave - Literal
leave - ExportAllDeclaration
"""
it 'default declaration #1', ->
tree =
type: 'ExportDefaultDeclaration'
declaration: classDeclaration()
expect(Dumper.dump(tree)).to.be.equal """
enter - ExportDefaultDeclaration
enter - ClassDeclaration
enter - Identifier
leave - Identifier
enter - ClassBody
leave - ClassBody
leave - ClassDeclaration
leave - ExportDefaultDeclaration
"""
it 'default declaration #1', ->
tree =
type: 'ExportDefaultDeclaration'
declaration: classDeclaration()
expect(Dumper.dump(tree)).to.be.equal """
enter - ExportDefaultDeclaration
enter - ClassDeclaration
enter - Identifier
leave - Identifier
enter - ClassBody
leave - ClassBody
leave - ClassDeclaration
leave - ExportDefaultDeclaration
"""
describe 'import', ->
it 'default specifier #1', ->
tree = espree.parse """
import Cocoa from 'rabbit-house'
""", {
ecmaFeatures:
modules: yes
}
expect(Dumper.dump(tree)).to.be.equal """
enter - Program
enter - ImportDeclaration
enter - ImportDefaultSpecifier
enter - Identifier
leave - Identifier
leave - ImportDefaultSpecifier
enter - Literal
leave - Literal
leave - ImportDeclaration
leave - Program
"""
it 'named specifier #1', ->
tree = espree.parse """
import {Cocoa, Cappuccino as Chino} from 'rabbit-house'
""", {
ecmaFeatures:
modules: yes
}
expect(Dumper.dump(tree)).to.be.equal """
enter - Program
enter - ImportDeclaration
enter - ImportSpecifier
enter - Identifier
leave - Identifier
enter - Identifier
leave - Identifier
leave - ImportSpecifier
enter - ImportSpecifier
enter - Identifier
leave - Identifier
enter - Identifier
leave - Identifier
leave - ImportSpecifier
enter - Literal
leave - Literal
leave - ImportDeclaration
leave - Program
"""
it 'namespace specifier #1', ->
tree = espree.parse """
import * as RabbitHouse from 'rabbit-house'
""", {
ecmaFeatures:
modules: yes
}
expect(Dumper.dump(tree)).to.be.equal """
enter - Program
enter - ImportDeclaration
enter - ImportNamespaceSpecifier
enter - Identifier
leave - Identifier
leave - ImportNamespaceSpecifier
enter - Literal
leave - Literal
leave - ImportDeclaration
leave - Program
"""
describe 'pattern', ->
it 'assignment pattern#1', ->
tree =
type: 'AssignmentPattern'
left: {
type: 'Identifier'
name: 'hello'
}
right: {
type: 'Literal'
value: 'world'
}
expect(Dumper.dump(tree)).to.be.equal """
enter - AssignmentPattern
enter - Identifier
leave - Identifier
enter - Literal
leave - Literal
leave - AssignmentPattern
"""
describe 'super', ->
it 'super expression#1', ->
tree =
type: 'Super'
expect(Dumper.dump(tree)).to.be.equal """
enter - Super
leave - Super
"""
describe 'meta property', ->
it 'MetaProperty in constructor #1', ->
tree =
type: 'UnaryExpression'
operator: 'typeof'
prefix: true
argument: {
type: 'MetaProperty'
meta: {
type: 'Identifier'
name: 'new'
}
property: {
type: 'Identifier'
name: 'target'
}
}
expect(Dumper.dump(tree)).to.be.equal """
enter - UnaryExpression
enter - MetaProperty
enter - Identifier
leave - Identifier
enter - Identifier
leave - Identifier
leave - MetaProperty
leave - UnaryExpression
"""
# vim: set sw=4 ts=4 et tw=80 :
| 60965 | # -*- coding: utf-8 -*-
# Copyright (C) 2015 <NAME> <<EMAIL>>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'use strict'
Dumper = require './dumper'
harmony = require './third_party/esprima'
espree = require 'espree'
{expect} = require 'chai'
{traverse} = require '..'
classDeclaration = ->
program = harmony.parse """
class Hello {
};
"""
program.body[0]
describe 'rest expression', ->
it 'argument', ->
tree =
type: 'RestElement'
argument: {
type: 'Identifier'
name: 'hello'
}
expect(Dumper.dump(tree)).to.be.equal """
enter - RestElement
enter - Identifier
leave - Identifier
leave - RestElement
"""
describe 'class', ->
it 'declaration#1', ->
tree = harmony.parse """
class Hello extends World {
method() {
}
};
"""
expect(Dumper.dump(tree)).to.be.equal """
enter - Program
enter - ClassDeclaration
enter - Identifier
leave - Identifier
enter - Identifier
leave - Identifier
enter - ClassBody
enter - MethodDefinition
enter - Identifier
leave - Identifier
enter - FunctionExpression
enter - BlockStatement
leave - BlockStatement
leave - FunctionExpression
leave - MethodDefinition
leave - ClassBody
leave - ClassDeclaration
enter - EmptyStatement
leave - EmptyStatement
leave - Program
"""
it 'declaration#2', ->
tree = harmony.parse """
class Hello extends ok() {
method() {
}
};
"""
expect(Dumper.dump(tree)).to.be.equal """
enter - Program
enter - ClassDeclaration
enter - Identifier
leave - Identifier
enter - CallExpression
enter - Identifier
leave - Identifier
leave - CallExpression
enter - ClassBody
enter - MethodDefinition
enter - Identifier
leave - Identifier
enter - FunctionExpression
enter - BlockStatement
leave - BlockStatement
leave - FunctionExpression
leave - MethodDefinition
leave - ClassBody
leave - ClassDeclaration
enter - EmptyStatement
leave - EmptyStatement
leave - Program
"""
describe 'export', ->
it 'named declaration #1', ->
tree =
type: 'ExportNamedDeclaration'
declaration: {
type: 'VariableDeclaration'
declarations: [{
type: 'VariableDeclarator'
id: {
type: 'Identifier'
name: '<NAME>'
}
init: {
type: 'Literal'
value: 6
}
}]
}
expect(Dumper.dump(tree)).to.be.equal """
enter - ExportNamedDeclaration
enter - VariableDeclaration
enter - VariableDeclarator
enter - Identifier
leave - Identifier
enter - Literal
leave - Literal
leave - VariableDeclarator
leave - VariableDeclaration
leave - ExportNamedDeclaration
"""
it 'named declaration #2', ->
tree =
type: 'ExportNamedDeclaration'
declaration: null
specifiers: [{
type: 'ExportSpecifier',
exported: {
type: 'Identifier',
name: 'foo'
}
local: {
type: 'Identifier',
name: 'bar'
}
}]
source: {
type: 'Literal',
value: 'hello'
}
expect(Dumper.dump(tree)).to.be.equal """
enter - ExportNamedDeclaration
enter - ExportSpecifier
enter - Identifier
leave - Identifier
enter - Identifier
leave - Identifier
leave - ExportSpecifier
enter - Literal
leave - Literal
leave - ExportNamedDeclaration
"""
it 'all declaration #1', ->
tree =
type: 'ExportAllDeclaration'
source: {
type: 'Literal',
value: 'hello'
}
expect(Dumper.dump(tree)).to.be.equal """
enter - ExportAllDeclaration
enter - Literal
leave - Literal
leave - ExportAllDeclaration
"""
it 'default declaration #1', ->
tree =
type: 'ExportDefaultDeclaration'
declaration: classDeclaration()
expect(Dumper.dump(tree)).to.be.equal """
enter - ExportDefaultDeclaration
enter - ClassDeclaration
enter - Identifier
leave - Identifier
enter - ClassBody
leave - ClassBody
leave - ClassDeclaration
leave - ExportDefaultDeclaration
"""
it 'default declaration #1', ->
tree =
type: 'ExportDefaultDeclaration'
declaration: classDeclaration()
expect(Dumper.dump(tree)).to.be.equal """
enter - ExportDefaultDeclaration
enter - ClassDeclaration
enter - Identifier
leave - Identifier
enter - ClassBody
leave - ClassBody
leave - ClassDeclaration
leave - ExportDefaultDeclaration
"""
describe 'import', ->
it 'default specifier #1', ->
tree = espree.parse """
import Cocoa from 'rabbit-house'
""", {
ecmaFeatures:
modules: yes
}
expect(Dumper.dump(tree)).to.be.equal """
enter - Program
enter - ImportDeclaration
enter - ImportDefaultSpecifier
enter - Identifier
leave - Identifier
leave - ImportDefaultSpecifier
enter - Literal
leave - Literal
leave - ImportDeclaration
leave - Program
"""
it 'named specifier #1', ->
tree = espree.parse """
import {Cocoa, Cappuccino as Chino} from 'rabbit-house'
""", {
ecmaFeatures:
modules: yes
}
expect(Dumper.dump(tree)).to.be.equal """
enter - Program
enter - ImportDeclaration
enter - ImportSpecifier
enter - Identifier
leave - Identifier
enter - Identifier
leave - Identifier
leave - ImportSpecifier
enter - ImportSpecifier
enter - Identifier
leave - Identifier
enter - Identifier
leave - Identifier
leave - ImportSpecifier
enter - Literal
leave - Literal
leave - ImportDeclaration
leave - Program
"""
it 'namespace specifier #1', ->
tree = espree.parse """
import * as RabbitHouse from 'rabbit-house'
""", {
ecmaFeatures:
modules: yes
}
expect(Dumper.dump(tree)).to.be.equal """
enter - Program
enter - ImportDeclaration
enter - ImportNamespaceSpecifier
enter - Identifier
leave - Identifier
leave - ImportNamespaceSpecifier
enter - Literal
leave - Literal
leave - ImportDeclaration
leave - Program
"""
describe 'pattern', ->
it 'assignment pattern#1', ->
tree =
type: 'AssignmentPattern'
left: {
type: 'Identifier'
name: '<NAME>'
}
right: {
type: 'Literal'
value: 'world'
}
expect(Dumper.dump(tree)).to.be.equal """
enter - AssignmentPattern
enter - Identifier
leave - Identifier
enter - Literal
leave - Literal
leave - AssignmentPattern
"""
describe 'super', ->
it 'super expression#1', ->
tree =
type: 'Super'
expect(Dumper.dump(tree)).to.be.equal """
enter - Super
leave - Super
"""
describe 'meta property', ->
it 'MetaProperty in constructor #1', ->
tree =
type: 'UnaryExpression'
operator: 'typeof'
prefix: true
argument: {
type: 'MetaProperty'
meta: {
type: 'Identifier'
name: 'new'
}
property: {
type: 'Identifier'
name: 'target'
}
}
expect(Dumper.dump(tree)).to.be.equal """
enter - UnaryExpression
enter - MetaProperty
enter - Identifier
leave - Identifier
enter - Identifier
leave - Identifier
leave - MetaProperty
leave - UnaryExpression
"""
# vim: set sw=4 ts=4 et tw=80 :
| true | # -*- coding: utf-8 -*-
# Copyright (C) 2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'use strict'
Dumper = require './dumper'
harmony = require './third_party/esprima'
espree = require 'espree'
{expect} = require 'chai'
{traverse} = require '..'
classDeclaration = ->
program = harmony.parse """
class Hello {
};
"""
program.body[0]
describe 'rest expression', ->
it 'argument', ->
tree =
type: 'RestElement'
argument: {
type: 'Identifier'
name: 'hello'
}
expect(Dumper.dump(tree)).to.be.equal """
enter - RestElement
enter - Identifier
leave - Identifier
leave - RestElement
"""
describe 'class', ->
it 'declaration#1', ->
tree = harmony.parse """
class Hello extends World {
method() {
}
};
"""
expect(Dumper.dump(tree)).to.be.equal """
enter - Program
enter - ClassDeclaration
enter - Identifier
leave - Identifier
enter - Identifier
leave - Identifier
enter - ClassBody
enter - MethodDefinition
enter - Identifier
leave - Identifier
enter - FunctionExpression
enter - BlockStatement
leave - BlockStatement
leave - FunctionExpression
leave - MethodDefinition
leave - ClassBody
leave - ClassDeclaration
enter - EmptyStatement
leave - EmptyStatement
leave - Program
"""
it 'declaration#2', ->
tree = harmony.parse """
class Hello extends ok() {
method() {
}
};
"""
expect(Dumper.dump(tree)).to.be.equal """
enter - Program
enter - ClassDeclaration
enter - Identifier
leave - Identifier
enter - CallExpression
enter - Identifier
leave - Identifier
leave - CallExpression
enter - ClassBody
enter - MethodDefinition
enter - Identifier
leave - Identifier
enter - FunctionExpression
enter - BlockStatement
leave - BlockStatement
leave - FunctionExpression
leave - MethodDefinition
leave - ClassBody
leave - ClassDeclaration
enter - EmptyStatement
leave - EmptyStatement
leave - Program
"""
describe 'export', ->
it 'named declaration #1', ->
tree =
type: 'ExportNamedDeclaration'
declaration: {
type: 'VariableDeclaration'
declarations: [{
type: 'VariableDeclarator'
id: {
type: 'Identifier'
name: 'PI:NAME:<NAME>END_PI'
}
init: {
type: 'Literal'
value: 6
}
}]
}
expect(Dumper.dump(tree)).to.be.equal """
enter - ExportNamedDeclaration
enter - VariableDeclaration
enter - VariableDeclarator
enter - Identifier
leave - Identifier
enter - Literal
leave - Literal
leave - VariableDeclarator
leave - VariableDeclaration
leave - ExportNamedDeclaration
"""
it 'named declaration #2', ->
tree =
type: 'ExportNamedDeclaration'
declaration: null
specifiers: [{
type: 'ExportSpecifier',
exported: {
type: 'Identifier',
name: 'foo'
}
local: {
type: 'Identifier',
name: 'bar'
}
}]
source: {
type: 'Literal',
value: 'hello'
}
expect(Dumper.dump(tree)).to.be.equal """
enter - ExportNamedDeclaration
enter - ExportSpecifier
enter - Identifier
leave - Identifier
enter - Identifier
leave - Identifier
leave - ExportSpecifier
enter - Literal
leave - Literal
leave - ExportNamedDeclaration
"""
it 'all declaration #1', ->
tree =
type: 'ExportAllDeclaration'
source: {
type: 'Literal',
value: 'hello'
}
expect(Dumper.dump(tree)).to.be.equal """
enter - ExportAllDeclaration
enter - Literal
leave - Literal
leave - ExportAllDeclaration
"""
it 'default declaration #1', ->
tree =
type: 'ExportDefaultDeclaration'
declaration: classDeclaration()
expect(Dumper.dump(tree)).to.be.equal """
enter - ExportDefaultDeclaration
enter - ClassDeclaration
enter - Identifier
leave - Identifier
enter - ClassBody
leave - ClassBody
leave - ClassDeclaration
leave - ExportDefaultDeclaration
"""
it 'default declaration #1', ->
tree =
type: 'ExportDefaultDeclaration'
declaration: classDeclaration()
expect(Dumper.dump(tree)).to.be.equal """
enter - ExportDefaultDeclaration
enter - ClassDeclaration
enter - Identifier
leave - Identifier
enter - ClassBody
leave - ClassBody
leave - ClassDeclaration
leave - ExportDefaultDeclaration
"""
describe 'import', ->
it 'default specifier #1', ->
tree = espree.parse """
import Cocoa from 'rabbit-house'
""", {
ecmaFeatures:
modules: yes
}
expect(Dumper.dump(tree)).to.be.equal """
enter - Program
enter - ImportDeclaration
enter - ImportDefaultSpecifier
enter - Identifier
leave - Identifier
leave - ImportDefaultSpecifier
enter - Literal
leave - Literal
leave - ImportDeclaration
leave - Program
"""
it 'named specifier #1', ->
tree = espree.parse """
import {Cocoa, Cappuccino as Chino} from 'rabbit-house'
""", {
ecmaFeatures:
modules: yes
}
expect(Dumper.dump(tree)).to.be.equal """
enter - Program
enter - ImportDeclaration
enter - ImportSpecifier
enter - Identifier
leave - Identifier
enter - Identifier
leave - Identifier
leave - ImportSpecifier
enter - ImportSpecifier
enter - Identifier
leave - Identifier
enter - Identifier
leave - Identifier
leave - ImportSpecifier
enter - Literal
leave - Literal
leave - ImportDeclaration
leave - Program
"""
it 'namespace specifier #1', ->
tree = espree.parse """
import * as RabbitHouse from 'rabbit-house'
""", {
ecmaFeatures:
modules: yes
}
expect(Dumper.dump(tree)).to.be.equal """
enter - Program
enter - ImportDeclaration
enter - ImportNamespaceSpecifier
enter - Identifier
leave - Identifier
leave - ImportNamespaceSpecifier
enter - Literal
leave - Literal
leave - ImportDeclaration
leave - Program
"""
describe 'pattern', ->
it 'assignment pattern#1', ->
tree =
type: 'AssignmentPattern'
left: {
type: 'Identifier'
name: 'PI:NAME:<NAME>END_PI'
}
right: {
type: 'Literal'
value: 'world'
}
expect(Dumper.dump(tree)).to.be.equal """
enter - AssignmentPattern
enter - Identifier
leave - Identifier
enter - Literal
leave - Literal
leave - AssignmentPattern
"""
describe 'super', ->
it 'super expression#1', ->
tree =
type: 'Super'
expect(Dumper.dump(tree)).to.be.equal """
enter - Super
leave - Super
"""
describe 'meta property', ->
it 'MetaProperty in constructor #1', ->
tree =
type: 'UnaryExpression'
operator: 'typeof'
prefix: true
argument: {
type: 'MetaProperty'
meta: {
type: 'Identifier'
name: 'new'
}
property: {
type: 'Identifier'
name: 'target'
}
}
expect(Dumper.dump(tree)).to.be.equal """
enter - UnaryExpression
enter - MetaProperty
enter - Identifier
leave - Identifier
enter - Identifier
leave - Identifier
leave - MetaProperty
leave - UnaryExpression
"""
# vim: set sw=4 ts=4 et tw=80 :
|
[
{
"context": "running) ->\n t = fn.test\n key = \"#{t.currentFile} (#{t.attemptedTests}): #{t.description}\"\n pend",
"end": 1067,
"score": 0.676989734172821,
"start": 1062,
"tag": "KEY",
"value": "File}"
}
] | test/suite-runner.coffee | paigeruten/pencil-tracer | 1 | # This instruments each test file from CoffeeScript's test suite and runs the
# result. Most of the code in this file is borrowed from CoffeeScript's
# Cakefile.
fs = require "fs"
path = require "path"
Contextify = require "contextify"
assert = require "assert"
{instrumentCoffee} = require "../lib/index"
coffeeScript = if process.argv[2] is "iced" then require("iced-coffee-script") else require("coffee-script")
bold = red = green = reset = ''
unless process.env.NODE_DISABLE_COLORS
bold = '\x1B[0;1m'
red = '\x1B[0;31m'
green = '\x1B[0;32m'
reset = '\x1B[0m'
log = (message, color, explanation) ->
console.log color + message + reset + ' ' + (explanation or '')
runTests = (CoffeeScript, testsDir) ->
CoffeeScript.register()
startTime = Date.now()
currentFile = null
passedTests = 0
failures = []
attemptedTests = 0
pendingTests = {}
global.CoffeeScript = CoffeeScript
global.pencilTrace = (event) ->
global[name] = func for name, func of assert
track = (fn, running) ->
t = fn.test
key = "#{t.currentFile} (#{t.attemptedTests}): #{t.description}"
pendingTests[key] = running
# Our test helper function for delimiting different test cases.
global.test = (description, fn) ->
try
++attemptedTests
fn.test = {description, currentFile, attemptedTests}
track fn, true
fn.call(fn)
++passedTests
track fn, false
catch e
failures.push
filename: currentFile
error: e
description: description if description?
source: fn.toString() if fn.toString?
# An async testing primitive
global.atest = (description, fn) ->
++attemptedTests
fn.test = { description, currentFile, attemptedTests }
track fn, true
fn.call fn, (ok, e) =>
if ok
++passedTests
track fn, false
else
e.description = description if description?
e.source = fn.toString() if fn.toString?
failures.push filename : currentFile, error : e
# See http://wiki.ecmascript.org/doku.php?id=harmony:egal
egal = (a, b) ->
if a is b
a isnt 0 or 1/a is 1/b
else
a isnt a and b isnt b
# A recursive functional equivalence helper; uses egal for testing equivalence.
arrayEgal = (a, b) ->
if egal a, b then yes
else if a instanceof Array and b instanceof Array
return no unless a.length is b.length
return no for el, idx in a when not arrayEgal el, b[idx]
yes
global.eq = (a, b, msg) -> assert.ok egal(a, b), msg ? "Expected #{a} to equal #{b}"
global.arrayEq = (a, b, msg) -> assert.ok arrayEgal(a,b), msg ? "Expected #{a} to deep equal #{b}"
# When all the tests have run, collect and print errors.
# If a stacktrace is available, output the compiled function source.
process.on 'exit', ->
time = ((Date.now() - startTime) / 1000).toFixed(2)
message = "passed #{passedTests} tests in #{time} seconds#{reset}"
if passedTests != attemptedTests
log("Only #{passedTests} of #{attemptedTests} came back; some went missing!", red)
for desc, pending of pendingTests when pending
log(desc, red)
return log(message, green) unless failures.length
log "failed #{failures.length} and #{message}", red
for fail in failures
{error, filename, description, source} = fail
console.log ''
log " #{description}", red if description
log " #{error.stack}", red
console.log " #{source}" if source
process.exit(1)
return
# Run every test in the `coffee` folder, recording failures.
files = fs.readdirSync testsDir
for file in files when CoffeeScript.helpers.isCoffee file
console.log "XX #{file}"
literate = CoffeeScript.helpers.isLiterate file
currentFile = filename = path.join testsDir, file
code = fs.readFileSync filename
try
mainModule = require.main
mainModule.filename = fs.realpathSync filename
mainModule.moduleCache and= {}
mainModule.paths = require("module")._nodeModulePaths fs.realpathSync(testsDir)
code = instrumentCoffee code.toString(), CoffeeScript, { literate: literate }
mainModule._compile code, mainModule.filename
catch error
console.log error
failures.push {filename, error}
return !failures.length
if coffeeScript.iced?
console.log "\nRunning Iced CoffeeScript test suite"
runTests coffeeScript, path.join(path.dirname(__filename), "suite/iced")
else
console.log "\nRunning CoffeeScript test suite"
runTests coffeeScript, path.join(path.dirname(__filename), "suite/coffee")
| 70239 | # This instruments each test file from CoffeeScript's test suite and runs the
# result. Most of the code in this file is borrowed from CoffeeScript's
# Cakefile.
fs = require "fs"
path = require "path"
Contextify = require "contextify"
assert = require "assert"
{instrumentCoffee} = require "../lib/index"
coffeeScript = if process.argv[2] is "iced" then require("iced-coffee-script") else require("coffee-script")
bold = red = green = reset = ''
unless process.env.NODE_DISABLE_COLORS
bold = '\x1B[0;1m'
red = '\x1B[0;31m'
green = '\x1B[0;32m'
reset = '\x1B[0m'
log = (message, color, explanation) ->
console.log color + message + reset + ' ' + (explanation or '')
runTests = (CoffeeScript, testsDir) ->
CoffeeScript.register()
startTime = Date.now()
currentFile = null
passedTests = 0
failures = []
attemptedTests = 0
pendingTests = {}
global.CoffeeScript = CoffeeScript
global.pencilTrace = (event) ->
global[name] = func for name, func of assert
track = (fn, running) ->
t = fn.test
key = "#{t.current<KEY> (#{t.attemptedTests}): #{t.description}"
pendingTests[key] = running
# Our test helper function for delimiting different test cases.
global.test = (description, fn) ->
try
++attemptedTests
fn.test = {description, currentFile, attemptedTests}
track fn, true
fn.call(fn)
++passedTests
track fn, false
catch e
failures.push
filename: currentFile
error: e
description: description if description?
source: fn.toString() if fn.toString?
# An async testing primitive
global.atest = (description, fn) ->
++attemptedTests
fn.test = { description, currentFile, attemptedTests }
track fn, true
fn.call fn, (ok, e) =>
if ok
++passedTests
track fn, false
else
e.description = description if description?
e.source = fn.toString() if fn.toString?
failures.push filename : currentFile, error : e
# See http://wiki.ecmascript.org/doku.php?id=harmony:egal
egal = (a, b) ->
if a is b
a isnt 0 or 1/a is 1/b
else
a isnt a and b isnt b
# A recursive functional equivalence helper; uses egal for testing equivalence.
arrayEgal = (a, b) ->
if egal a, b then yes
else if a instanceof Array and b instanceof Array
return no unless a.length is b.length
return no for el, idx in a when not arrayEgal el, b[idx]
yes
global.eq = (a, b, msg) -> assert.ok egal(a, b), msg ? "Expected #{a} to equal #{b}"
global.arrayEq = (a, b, msg) -> assert.ok arrayEgal(a,b), msg ? "Expected #{a} to deep equal #{b}"
# When all the tests have run, collect and print errors.
# If a stacktrace is available, output the compiled function source.
process.on 'exit', ->
time = ((Date.now() - startTime) / 1000).toFixed(2)
message = "passed #{passedTests} tests in #{time} seconds#{reset}"
if passedTests != attemptedTests
log("Only #{passedTests} of #{attemptedTests} came back; some went missing!", red)
for desc, pending of pendingTests when pending
log(desc, red)
return log(message, green) unless failures.length
log "failed #{failures.length} and #{message}", red
for fail in failures
{error, filename, description, source} = fail
console.log ''
log " #{description}", red if description
log " #{error.stack}", red
console.log " #{source}" if source
process.exit(1)
return
# Run every test in the `coffee` folder, recording failures.
files = fs.readdirSync testsDir
for file in files when CoffeeScript.helpers.isCoffee file
console.log "XX #{file}"
literate = CoffeeScript.helpers.isLiterate file
currentFile = filename = path.join testsDir, file
code = fs.readFileSync filename
try
mainModule = require.main
mainModule.filename = fs.realpathSync filename
mainModule.moduleCache and= {}
mainModule.paths = require("module")._nodeModulePaths fs.realpathSync(testsDir)
code = instrumentCoffee code.toString(), CoffeeScript, { literate: literate }
mainModule._compile code, mainModule.filename
catch error
console.log error
failures.push {filename, error}
return !failures.length
if coffeeScript.iced?
console.log "\nRunning Iced CoffeeScript test suite"
runTests coffeeScript, path.join(path.dirname(__filename), "suite/iced")
else
console.log "\nRunning CoffeeScript test suite"
runTests coffeeScript, path.join(path.dirname(__filename), "suite/coffee")
| true | # This instruments each test file from CoffeeScript's test suite and runs the
# result. Most of the code in this file is borrowed from CoffeeScript's
# Cakefile.
fs = require "fs"
path = require "path"
Contextify = require "contextify"
assert = require "assert"
{instrumentCoffee} = require "../lib/index"
coffeeScript = if process.argv[2] is "iced" then require("iced-coffee-script") else require("coffee-script")
bold = red = green = reset = ''
unless process.env.NODE_DISABLE_COLORS
bold = '\x1B[0;1m'
red = '\x1B[0;31m'
green = '\x1B[0;32m'
reset = '\x1B[0m'
log = (message, color, explanation) ->
console.log color + message + reset + ' ' + (explanation or '')
runTests = (CoffeeScript, testsDir) ->
CoffeeScript.register()
startTime = Date.now()
currentFile = null
passedTests = 0
failures = []
attemptedTests = 0
pendingTests = {}
global.CoffeeScript = CoffeeScript
global.pencilTrace = (event) ->
global[name] = func for name, func of assert
track = (fn, running) ->
t = fn.test
key = "#{t.currentPI:KEY:<KEY>END_PI (#{t.attemptedTests}): #{t.description}"
pendingTests[key] = running
# Our test helper function for delimiting different test cases.
global.test = (description, fn) ->
try
++attemptedTests
fn.test = {description, currentFile, attemptedTests}
track fn, true
fn.call(fn)
++passedTests
track fn, false
catch e
failures.push
filename: currentFile
error: e
description: description if description?
source: fn.toString() if fn.toString?
# An async testing primitive
global.atest = (description, fn) ->
++attemptedTests
fn.test = { description, currentFile, attemptedTests }
track fn, true
fn.call fn, (ok, e) =>
if ok
++passedTests
track fn, false
else
e.description = description if description?
e.source = fn.toString() if fn.toString?
failures.push filename : currentFile, error : e
# See http://wiki.ecmascript.org/doku.php?id=harmony:egal
egal = (a, b) ->
if a is b
a isnt 0 or 1/a is 1/b
else
a isnt a and b isnt b
# A recursive functional equivalence helper; uses egal for testing equivalence.
arrayEgal = (a, b) ->
if egal a, b then yes
else if a instanceof Array and b instanceof Array
return no unless a.length is b.length
return no for el, idx in a when not arrayEgal el, b[idx]
yes
global.eq = (a, b, msg) -> assert.ok egal(a, b), msg ? "Expected #{a} to equal #{b}"
global.arrayEq = (a, b, msg) -> assert.ok arrayEgal(a,b), msg ? "Expected #{a} to deep equal #{b}"
# When all the tests have run, collect and print errors.
# If a stacktrace is available, output the compiled function source.
process.on 'exit', ->
time = ((Date.now() - startTime) / 1000).toFixed(2)
message = "passed #{passedTests} tests in #{time} seconds#{reset}"
if passedTests != attemptedTests
log("Only #{passedTests} of #{attemptedTests} came back; some went missing!", red)
for desc, pending of pendingTests when pending
log(desc, red)
return log(message, green) unless failures.length
log "failed #{failures.length} and #{message}", red
for fail in failures
{error, filename, description, source} = fail
console.log ''
log " #{description}", red if description
log " #{error.stack}", red
console.log " #{source}" if source
process.exit(1)
return
# Run every test in the `coffee` folder, recording failures.
files = fs.readdirSync testsDir
for file in files when CoffeeScript.helpers.isCoffee file
console.log "XX #{file}"
literate = CoffeeScript.helpers.isLiterate file
currentFile = filename = path.join testsDir, file
code = fs.readFileSync filename
try
mainModule = require.main
mainModule.filename = fs.realpathSync filename
mainModule.moduleCache and= {}
mainModule.paths = require("module")._nodeModulePaths fs.realpathSync(testsDir)
code = instrumentCoffee code.toString(), CoffeeScript, { literate: literate }
mainModule._compile code, mainModule.filename
catch error
console.log error
failures.push {filename, error}
return !failures.length
if coffeeScript.iced?
console.log "\nRunning Iced CoffeeScript test suite"
runTests coffeeScript, path.join(path.dirname(__filename), "suite/iced")
else
console.log "\nRunning CoffeeScript test suite"
runTests coffeeScript, path.join(path.dirname(__filename), "suite/coffee")
|
[
{
"context": "|all|significant) (period) [limit]\n#\n# Author:\n# EnriqueVidal\n\nlookup_site = \"http://earthquake.usgs.gov\"\n\nmodu",
"end": 257,
"score": 0.9866876602172852,
"start": 245,
"tag": "NAME",
"value": "EnriqueVidal"
}
] | src/scripts/quakes.coffee | Reelhouse/hubot-scripts | 2 | # Description:
# Ask hubot about the recent earthquakes in the last (hour, day, week or month).
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot quakes (intensity|all|significant) (period) [limit]
#
# Author:
# EnriqueVidal
lookup_site = "http://earthquake.usgs.gov"
module.exports = (robot)->
robot.respond /quakes (([12](\.[05])?)|all|significant)? (hour|day|week|month)( \d+)?$/i, (message)->
check_for_rapture message, message.match[1], message.match[4], parseInt( message.match[5] )
check_for_rapture = (message, intensity, period, limit)->
rapture_url = [ lookup_site, "earthquakes", "feed", "geojson", intensity, period ].join '/'
message.http( rapture_url ).get() (error, response, body)->
return message.send 'Sorry, something went wrong' if error
list = JSON.parse( body ).features
count = 0
for quake in list
count++
quake = quake.properties
time = build_time quake
url = [ lookup_site, quake.url ].join ''
message.send "Magnitude: #{ quake.mag }, Location: #{ quake.place }, Time: #{ time } - #{ url }"
break if count is limit
build_time = ( object )->
time = new Date object.time * 1000
[ time.getHours(), time.getMinutes(), time.getSeconds() ].join ':'
| 213913 | # Description:
# Ask hubot about the recent earthquakes in the last (hour, day, week or month).
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot quakes (intensity|all|significant) (period) [limit]
#
# Author:
# <NAME>
lookup_site = "http://earthquake.usgs.gov"
module.exports = (robot)->
robot.respond /quakes (([12](\.[05])?)|all|significant)? (hour|day|week|month)( \d+)?$/i, (message)->
check_for_rapture message, message.match[1], message.match[4], parseInt( message.match[5] )
check_for_rapture = (message, intensity, period, limit)->
rapture_url = [ lookup_site, "earthquakes", "feed", "geojson", intensity, period ].join '/'
message.http( rapture_url ).get() (error, response, body)->
return message.send 'Sorry, something went wrong' if error
list = JSON.parse( body ).features
count = 0
for quake in list
count++
quake = quake.properties
time = build_time quake
url = [ lookup_site, quake.url ].join ''
message.send "Magnitude: #{ quake.mag }, Location: #{ quake.place }, Time: #{ time } - #{ url }"
break if count is limit
build_time = ( object )->
time = new Date object.time * 1000
[ time.getHours(), time.getMinutes(), time.getSeconds() ].join ':'
| true | # Description:
# Ask hubot about the recent earthquakes in the last (hour, day, week or month).
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot quakes (intensity|all|significant) (period) [limit]
#
# Author:
# PI:NAME:<NAME>END_PI
lookup_site = "http://earthquake.usgs.gov"
module.exports = (robot)->
robot.respond /quakes (([12](\.[05])?)|all|significant)? (hour|day|week|month)( \d+)?$/i, (message)->
check_for_rapture message, message.match[1], message.match[4], parseInt( message.match[5] )
check_for_rapture = (message, intensity, period, limit)->
rapture_url = [ lookup_site, "earthquakes", "feed", "geojson", intensity, period ].join '/'
message.http( rapture_url ).get() (error, response, body)->
return message.send 'Sorry, something went wrong' if error
list = JSON.parse( body ).features
count = 0
for quake in list
count++
quake = quake.properties
time = build_time quake
url = [ lookup_site, quake.url ].join ''
message.send "Magnitude: #{ quake.mag }, Location: #{ quake.place }, Time: #{ time } - #{ url }"
break if count is limit
build_time = ( object )->
time = new Date object.time * 1000
[ time.getHours(), time.getMinutes(), time.getSeconds() ].join ':'
|
[
{
"context": " Tests for the no-array-constructor rule\n# @author Matt DuVall <http://www.mattduvall.com/>\n###\n\n'use strict'\n\n#",
"end": 82,
"score": 0.9998157620429993,
"start": 71,
"tag": "NAME",
"value": "Matt DuVall"
}
] | src/tests/rules/no-array-constructor.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for the no-array-constructor rule
# @author Matt DuVall <http://www.mattduvall.com/>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-array-constructor'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-array-constructor', rule,
valid: [
'new Array(x)'
'Array(x)'
'new Array(9)'
'Array(9)'
'new foo.Array()'
'foo.Array()'
'new Array.foo'
'Array.foo()'
]
invalid: [
code: 'new Array()'
errors: [messageId: 'preferLiteral', type: 'NewExpression']
,
code: 'new Array'
errors: [messageId: 'preferLiteral', type: 'NewExpression']
,
code: 'new Array(x, y)'
errors: [messageId: 'preferLiteral', type: 'NewExpression']
,
code: 'new Array(0, 1, 2)'
errors: [messageId: 'preferLiteral', type: 'NewExpression']
]
| 131248 | ###*
# @fileoverview Tests for the no-array-constructor rule
# @author <NAME> <http://www.mattduvall.com/>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-array-constructor'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-array-constructor', rule,
valid: [
'new Array(x)'
'Array(x)'
'new Array(9)'
'Array(9)'
'new foo.Array()'
'foo.Array()'
'new Array.foo'
'Array.foo()'
]
invalid: [
code: 'new Array()'
errors: [messageId: 'preferLiteral', type: 'NewExpression']
,
code: 'new Array'
errors: [messageId: 'preferLiteral', type: 'NewExpression']
,
code: 'new Array(x, y)'
errors: [messageId: 'preferLiteral', type: 'NewExpression']
,
code: 'new Array(0, 1, 2)'
errors: [messageId: 'preferLiteral', type: 'NewExpression']
]
| true | ###*
# @fileoverview Tests for the no-array-constructor rule
# @author PI:NAME:<NAME>END_PI <http://www.mattduvall.com/>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-array-constructor'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-array-constructor', rule,
valid: [
'new Array(x)'
'Array(x)'
'new Array(9)'
'Array(9)'
'new foo.Array()'
'foo.Array()'
'new Array.foo'
'Array.foo()'
]
invalid: [
code: 'new Array()'
errors: [messageId: 'preferLiteral', type: 'NewExpression']
,
code: 'new Array'
errors: [messageId: 'preferLiteral', type: 'NewExpression']
,
code: 'new Array(x, y)'
errors: [messageId: 'preferLiteral', type: 'NewExpression']
,
code: 'new Array(0, 1, 2)'
errors: [messageId: 'preferLiteral', type: 'NewExpression']
]
|
[
{
"context": "###################################\n#\n# Created by Markus on 26/10/2015.\n#\n################################",
"end": 75,
"score": 0.997893214225769,
"start": 69,
"tag": "NAME",
"value": "Markus"
},
{
"context": "if not user\n\t\tuser =\n\t\t\temail: email,\n\t\t\tpa... | server/server.coffee | agottschalk10/worklearn | 0 | #####################################################
#
# Created by Markus on 26/10/2015.
#
#####################################################
#####################################################
_handle_startup_setting = () ->
# make sure all indices are created
_initialize_indices()
_check_environment_variables()
# The rest only works with a settings file and on localhost.
# For security reasons we do not create default admin access.
if not Meteor.settings
return
if not get_environment()=="local"
return
# add an admin if on localhost
if Meteor.settings.admin
param = Meteor.settings.admin
_add_admin param.email, param.password
# set default permissions if necessary
if Meteor.settings.init_default_permissions && (Meteor.settings.init_default_permissions == true)
_initialize_permissions()
# add test data
if Meteor.settings.init_test_data
_initialize_database()
#####################################################
# Prepare indices
#####################################################
#####################################################
_initialize_indices = ()->
msg = "Validating MongoDB indices"
log_event msg
index =
owner_id: 1
Challenges._ensureIndex index
Solutions._ensureIndex index
Reviews._ensureIndex index
Feedback._ensureIndex index
Profiles._ensureIndex index
Messages._ensureIndex index
Posts._ensureIndex index
index =
parent_id: 1
Challenges._ensureIndex index
Solutions._ensureIndex index
Reviews._ensureIndex index
Feedback._ensureIndex index
Profiles._ensureIndex index
Posts._ensureIndex index
index =
solution_id: 1
Reviews._ensureIndex index
Feedback._ensureIndex index
index =
challenge_id: 1
Solutions._ensureIndex index
Reviews._ensureIndex index
Feedback._ensureIndex index
index =
content: "text"
title: "text"
Challenges._ensureIndex index
Solutions._ensureIndex index
Reviews._ensureIndex index
Feedback._ensureIndex index
Posts._ensureIndex index
msg = "MongoDB indices initialized"
log_event msg
#####################################################
# Checks
#####################################################
#####################################################
_check_environment_variables = () ->
msg = "Checking enviromnent variables"
log_event msg
url = process.env.MAIL_URL
if url
msg = "-- MAIL_URL is set."
log_event msg
else
msg = "-- MAIL_URL not set. Mail notifications are disabled!"
log_event msg, event_general, event_warn
token = process.env.DROP_BOX_ACCESS_TOKEN
if token
msg = "-- DROP_BOX_ACCESS_TOKEN is set."
log_event msg
else
msg = "-- DROP_BOX_ACCESS_TOKEN not set. Saving files is disabled!"
log_event msg, event_general, event_warn
msg = "Environment variables checked"
log_event msg
#####################################################
# Permissions
#####################################################
#####################################################
_initialize_permissions = () ->
log_event "Inserting default permissions"
asset_path = "db/defaultcollections/permissions.json"
asset_pobj = Meteor.settings.default_permissions_asset_path
if asset_pobj
assetp = asset_pobj.toString()
if not assetp == ""
asset_path = assetp
perms_txt = Assets.getText(asset_path)
perms = JSON.parse(perms_txt)
for perm, i in perms
_insert_permission_safe(perm)
#####################################################
# Helper functions to fill in default permissions
#####################################################
#####################################################
_find_permission_by_effectors = (p) ->
filter =
role: p.role
field: p.field
collection_name: p.collection_name
Permissions.find(filter)
#####################################################
_insert_permission_unsafe = (p) ->
id = Permissions.insert p
if not id
throw new Meteor.Error 'Could not insert permission to db : ' + p
return id
#####################################################
_insert_permission_safe = (p) ->
existing_permission = _find_permission_by_effectors(p)
if existing_permission.count() == 0
_insert_permission_unsafe(p)
else
#msg = "Permission already exists: " + JSON.stringify(p)
#log_event msg, event_db, event_info
#####################################################
# Database testing
#####################################################
#####################################################
_add_admin = (email, password) ->
log_event "Adding admin"
user = Accounts.findUserByEmail(email)
if not user
user =
email: email,
password: password,
user = Accounts.createUser(user)
Roles.setUserRoles user, ["admin", "db_admin", "editor", "challenge_designer"]
user = Accounts.findUserByEmail(email)
filter =
owner_id: user._id
profile = Profiles.findOne filter
if profile
return profile._id
profile_id = gen_profile user, "learner"
msg = "admin added " + user.email + " " + profile_id
log_event msg, event_testing, event_info
return profile_id
####################################################
_initialize_database = () ->
console.log "####################################################"
console.log "## adding test data ##"
console.log "####################################################"
title = "The test challenge"
filter =
title: title
challenge = Challenges.findOne filter
if not challenge
challenge_id = _test_challenge title
challenge = Challenges.findOne challenge_id
learners = []
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9]
mail = String(i) + "@uni.edu"
profile_id = _test_user_creation mail, "learner"
profile = Profiles.findOne profile_id
user = Meteor.users.findOne profile.owner_id
learners.push user
solutions = []
for s in learners
solution_id = _test_solution challenge, s
solution = Solutions.findOne solution_id
solutions.push solution
for i in [1..challenge.num_reviews]
reviews = []
for s in learners
review_id = _test_review challenge, null, s
review = Reviews.findOne review_id
reviews.push review
for solution in solutions
filter =
solution_id: solution._id
reviews = Reviews.find(filter).fetch()
user = Meteor.users.findOne solution.owner_id
for review in reviews
_test_feedback solution, review, user
console.log "####################################################"
console.log "## test data added ##"
console.log "####################################################"
# TODO: test reviews when there is a solution like for tutors
#####################################################
_test_user_creation = (mail, occupation) ->
user = Accounts.findUserByEmail(mail)
if not user
user =
email: mail,
password: "none",
user_id = Accounts.createUser(user)
user = Meteor.users.findOne user_id
console.log "Test user creation: " + user.emails[0].address
filter =
owner_id: user._id
profile = Profiles.findOne filter
if profile
return profile._id
profile_id = gen_profile user
modify_field_unprotected Profiles, profile_id, "avatar", faker.image.avatar()
modify_field_unprotected Profiles, profile_id, "given_name", faker.name.firstName()
modify_field_unprotected Profiles, profile_id, "family_name", faker.name.lastName()
modify_field_unprotected Profiles, profile_id, "middle_name", faker.name.firstName()
modify_field_unprotected Profiles, profile_id, "city", faker.address.city()
modify_field_unprotected Profiles, profile_id, "country", faker.address.country()
modify_field_unprotected Profiles, profile_id, "state", faker.address.state()
modify_field_unprotected Profiles, profile_id, "hours_per_week", Math.round(Random.fraction() * 40)
modify_field_unprotected Profiles, profile_id, "job_locale", Random.choice ["remote", "local"]
modify_field_unprotected Profiles, profile_id, "job_type", Random.choice ["free", "full"]
modify_field_unprotected Profiles, profile_id, "occupation", occupation
modify_field_unprotected Profiles, profile_id, "resume", faker.lorem.paragraphs 2
modify_field_unprotected Profiles, profile_id, "job_interested", true
modify_field_unprotected Profiles, profile_id, "test_object", true
return profile_id
#####################################################
_test_challenge = (title) ->
user = Accounts.findUserByEmail("designer@mooqita.org")
if not user
_test_user_creation "designer@mooqita.org", "organization"
user = Accounts.findUserByEmail("designer@mooqita.org")
Roles.setUserRoles user, ["admin", "editor", "challenge_designer"]
challenge_id = gen_challenge user
modify_field_unprotected Challenges, challenge_id, "title", title
modify_field_unprotected Challenges, challenge_id, "content", faker.lorem.paragraphs(3)
modify_field_unprotected Challenges, challenge_id, "test_object", true
#TODO: add test for material
challenge = Challenges.findOne challenge_id
challenge_id = finish_challenge challenge, user
return challenge_id
#####################################################
_test_solution = (challenge, user) ->
filter =
challenge_id: challenge._id
owner_id: user._id
solution = Solutions.findOne filter
if solution
return solution._id
solution_id = gen_solution challenge, user
modify_field_unprotected Solutions, solution_id, "content", faker.lorem.paragraphs(3)
modify_field_unprotected Solutions, solution_id, "test_object", true
solution = Solutions.findOne solution_id
solution_id = finish_solution solution, user
solution = Solutions.findOne solution_id
solution_id = reopen_solution solution, user
solution = Solutions.findOne solution_id
solution_id = finish_solution solution, user
#TODO: add reopen fail test
return solution_id
#####################################################
_test_review = (challenge, solution, user) ->
try
res = assign_review challenge, solution, user
catch e
if e.error == "no-review"
return
throw e
modify_field_unprotected Reviews, res.review_id, "content", faker.lorem.paragraphs(3)
modify_field_unprotected Reviews, res.review_id, "rating", Random.choice [1,2,3,4,5]
modify_field_unprotected Reviews, res.review_id, "test_object", true
review = Reviews.findOne res.review_id
review_id = finish_review review, user
review = Reviews.findOne res.review_id
review_id = reopen_review review, user
review = Reviews.findOne res.review_id
review_id = finish_review review, user
#TODO: add reopen fail test
return review_id
#####################################################
_test_feedback = (solution, review, user) ->
feedback_id = gen_feedback solution, review, user
feedback = Feedback.findOne feedback_id
if feedback.published == true
return
modify_field_unprotected Feedback, feedback_id, "content", faker.lorem.paragraphs(3)
modify_field_unprotected Feedback, feedback_id, "rating", Random.choice [1,2,3,4,5]
modify_field_unprotected Feedback, feedback_id, "test_object", true
feedback = Feedback.findOne feedback_id
feedback_id = finish_feedback feedback, user
feedback_id = reopen_feedback feedback, user
feedback_id = finish_feedback feedback, user
#TODO: add reopen test
#TODO: add reopen fail test
#TODO: add repair fail test
return feedback_id
#####################################################
# start up
#####################################################
Meteor.startup () ->
try
_handle_startup_setting()
catch e
console.log e
| 160724 | #####################################################
#
# Created by <NAME> on 26/10/2015.
#
#####################################################
#####################################################
_handle_startup_setting = () ->
# make sure all indices are created
_initialize_indices()
_check_environment_variables()
# The rest only works with a settings file and on localhost.
# For security reasons we do not create default admin access.
if not Meteor.settings
return
if not get_environment()=="local"
return
# add an admin if on localhost
if Meteor.settings.admin
param = Meteor.settings.admin
_add_admin param.email, param.password
# set default permissions if necessary
if Meteor.settings.init_default_permissions && (Meteor.settings.init_default_permissions == true)
_initialize_permissions()
# add test data
if Meteor.settings.init_test_data
_initialize_database()
#####################################################
# Prepare indices
#####################################################
#####################################################
_initialize_indices = ()->
msg = "Validating MongoDB indices"
log_event msg
index =
owner_id: 1
Challenges._ensureIndex index
Solutions._ensureIndex index
Reviews._ensureIndex index
Feedback._ensureIndex index
Profiles._ensureIndex index
Messages._ensureIndex index
Posts._ensureIndex index
index =
parent_id: 1
Challenges._ensureIndex index
Solutions._ensureIndex index
Reviews._ensureIndex index
Feedback._ensureIndex index
Profiles._ensureIndex index
Posts._ensureIndex index
index =
solution_id: 1
Reviews._ensureIndex index
Feedback._ensureIndex index
index =
challenge_id: 1
Solutions._ensureIndex index
Reviews._ensureIndex index
Feedback._ensureIndex index
index =
content: "text"
title: "text"
Challenges._ensureIndex index
Solutions._ensureIndex index
Reviews._ensureIndex index
Feedback._ensureIndex index
Posts._ensureIndex index
msg = "MongoDB indices initialized"
log_event msg
#####################################################
# Checks
#####################################################
#####################################################
_check_environment_variables = () ->
msg = "Checking enviromnent variables"
log_event msg
url = process.env.MAIL_URL
if url
msg = "-- MAIL_URL is set."
log_event msg
else
msg = "-- MAIL_URL not set. Mail notifications are disabled!"
log_event msg, event_general, event_warn
token = process.env.DROP_BOX_ACCESS_TOKEN
if token
msg = "-- DROP_BOX_ACCESS_TOKEN is set."
log_event msg
else
msg = "-- DROP_BOX_ACCESS_TOKEN not set. Saving files is disabled!"
log_event msg, event_general, event_warn
msg = "Environment variables checked"
log_event msg
#####################################################
# Permissions
#####################################################
#####################################################
_initialize_permissions = () ->
log_event "Inserting default permissions"
asset_path = "db/defaultcollections/permissions.json"
asset_pobj = Meteor.settings.default_permissions_asset_path
if asset_pobj
assetp = asset_pobj.toString()
if not assetp == ""
asset_path = assetp
perms_txt = Assets.getText(asset_path)
perms = JSON.parse(perms_txt)
for perm, i in perms
_insert_permission_safe(perm)
#####################################################
# Helper functions to fill in default permissions
#####################################################
#####################################################
_find_permission_by_effectors = (p) ->
filter =
role: p.role
field: p.field
collection_name: p.collection_name
Permissions.find(filter)
#####################################################
_insert_permission_unsafe = (p) ->
id = Permissions.insert p
if not id
throw new Meteor.Error 'Could not insert permission to db : ' + p
return id
#####################################################
_insert_permission_safe = (p) ->
existing_permission = _find_permission_by_effectors(p)
if existing_permission.count() == 0
_insert_permission_unsafe(p)
else
#msg = "Permission already exists: " + JSON.stringify(p)
#log_event msg, event_db, event_info
#####################################################
# Database testing
#####################################################
#####################################################
_add_admin = (email, password) ->
log_event "Adding admin"
user = Accounts.findUserByEmail(email)
if not user
user =
email: email,
password: <PASSWORD>,
user = Accounts.createUser(user)
Roles.setUserRoles user, ["admin", "db_admin", "editor", "challenge_designer"]
user = Accounts.findUserByEmail(email)
filter =
owner_id: user._id
profile = Profiles.findOne filter
if profile
return profile._id
profile_id = gen_profile user, "learner"
msg = "admin added " + user.email + " " + profile_id
log_event msg, event_testing, event_info
return profile_id
####################################################
_initialize_database = () ->
console.log "####################################################"
console.log "## adding test data ##"
console.log "####################################################"
title = "The test challenge"
filter =
title: title
challenge = Challenges.findOne filter
if not challenge
challenge_id = _test_challenge title
challenge = Challenges.findOne challenge_id
learners = []
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9]
mail = String(i) + "@uni.edu"
profile_id = _test_user_creation mail, "learner"
profile = Profiles.findOne profile_id
user = Meteor.users.findOne profile.owner_id
learners.push user
solutions = []
for s in learners
solution_id = _test_solution challenge, s
solution = Solutions.findOne solution_id
solutions.push solution
for i in [1..challenge.num_reviews]
reviews = []
for s in learners
review_id = _test_review challenge, null, s
review = Reviews.findOne review_id
reviews.push review
for solution in solutions
filter =
solution_id: solution._id
reviews = Reviews.find(filter).fetch()
user = Meteor.users.findOne solution.owner_id
for review in reviews
_test_feedback solution, review, user
console.log "####################################################"
console.log "## test data added ##"
console.log "####################################################"
# TODO: test reviews when there is a solution like for tutors
#####################################################
_test_user_creation = (mail, occupation) ->
user = Accounts.findUserByEmail(mail)
if not user
user =
email: mail,
password: "<PASSWORD>",
user_id = Accounts.createUser(user)
user = Meteor.users.findOne user_id
console.log "Test user creation: " + user.emails[0].address
filter =
owner_id: user._id
profile = Profiles.findOne filter
if profile
return profile._id
profile_id = gen_profile user
modify_field_unprotected Profiles, profile_id, "avatar", faker.image.avatar()
modify_field_unprotected Profiles, profile_id, "given_name", faker.name.firstName()
modify_field_unprotected Profiles, profile_id, "family_name", faker.name.lastName()
modify_field_unprotected Profiles, profile_id, "middle_name", faker.name.firstName()
modify_field_unprotected Profiles, profile_id, "city", faker.address.city()
modify_field_unprotected Profiles, profile_id, "country", faker.address.country()
modify_field_unprotected Profiles, profile_id, "state", faker.address.state()
modify_field_unprotected Profiles, profile_id, "hours_per_week", Math.round(Random.fraction() * 40)
modify_field_unprotected Profiles, profile_id, "job_locale", Random.choice ["remote", "local"]
modify_field_unprotected Profiles, profile_id, "job_type", Random.choice ["free", "full"]
modify_field_unprotected Profiles, profile_id, "occupation", occupation
modify_field_unprotected Profiles, profile_id, "resume", faker.lorem.paragraphs 2
modify_field_unprotected Profiles, profile_id, "job_interested", true
modify_field_unprotected Profiles, profile_id, "test_object", true
return profile_id
#####################################################
_test_challenge = (title) ->
user = Accounts.findUserByEmail("<EMAIL>")
if not user
_test_user_creation "<EMAIL>", "organization"
user = Accounts.findUserByEmail("<EMAIL>")
Roles.setUserRoles user, ["admin", "editor", "challenge_designer"]
challenge_id = gen_challenge user
modify_field_unprotected Challenges, challenge_id, "title", title
modify_field_unprotected Challenges, challenge_id, "content", faker.lorem.paragraphs(3)
modify_field_unprotected Challenges, challenge_id, "test_object", true
#TODO: add test for material
challenge = Challenges.findOne challenge_id
challenge_id = finish_challenge challenge, user
return challenge_id
#####################################################
_test_solution = (challenge, user) ->
filter =
challenge_id: challenge._id
owner_id: user._id
solution = Solutions.findOne filter
if solution
return solution._id
solution_id = gen_solution challenge, user
modify_field_unprotected Solutions, solution_id, "content", faker.lorem.paragraphs(3)
modify_field_unprotected Solutions, solution_id, "test_object", true
solution = Solutions.findOne solution_id
solution_id = finish_solution solution, user
solution = Solutions.findOne solution_id
solution_id = reopen_solution solution, user
solution = Solutions.findOne solution_id
solution_id = finish_solution solution, user
#TODO: add reopen fail test
return solution_id
#####################################################
_test_review = (challenge, solution, user) ->
try
res = assign_review challenge, solution, user
catch e
if e.error == "no-review"
return
throw e
modify_field_unprotected Reviews, res.review_id, "content", faker.lorem.paragraphs(3)
modify_field_unprotected Reviews, res.review_id, "rating", Random.choice [1,2,3,4,5]
modify_field_unprotected Reviews, res.review_id, "test_object", true
review = Reviews.findOne res.review_id
review_id = finish_review review, user
review = Reviews.findOne res.review_id
review_id = reopen_review review, user
review = Reviews.findOne res.review_id
review_id = finish_review review, user
#TODO: add reopen fail test
return review_id
#####################################################
_test_feedback = (solution, review, user) ->
feedback_id = gen_feedback solution, review, user
feedback = Feedback.findOne feedback_id
if feedback.published == true
return
modify_field_unprotected Feedback, feedback_id, "content", faker.lorem.paragraphs(3)
modify_field_unprotected Feedback, feedback_id, "rating", Random.choice [1,2,3,4,5]
modify_field_unprotected Feedback, feedback_id, "test_object", true
feedback = Feedback.findOne feedback_id
feedback_id = finish_feedback feedback, user
feedback_id = reopen_feedback feedback, user
feedback_id = finish_feedback feedback, user
#TODO: add reopen test
#TODO: add reopen fail test
#TODO: add repair fail test
return feedback_id
#####################################################
# start up
#####################################################
Meteor.startup () ->
try
_handle_startup_setting()
catch e
console.log e
| true | #####################################################
#
# Created by PI:NAME:<NAME>END_PI on 26/10/2015.
#
#####################################################
#####################################################
_handle_startup_setting = () ->
# make sure all indices are created
_initialize_indices()
_check_environment_variables()
# The rest only works with a settings file and on localhost.
# For security reasons we do not create default admin access.
if not Meteor.settings
return
if not get_environment()=="local"
return
# add an admin if on localhost
if Meteor.settings.admin
param = Meteor.settings.admin
_add_admin param.email, param.password
# set default permissions if necessary
if Meteor.settings.init_default_permissions && (Meteor.settings.init_default_permissions == true)
_initialize_permissions()
# add test data
if Meteor.settings.init_test_data
_initialize_database()
#####################################################
# Prepare indices
#####################################################
#####################################################
_initialize_indices = ()->
msg = "Validating MongoDB indices"
log_event msg
index =
owner_id: 1
Challenges._ensureIndex index
Solutions._ensureIndex index
Reviews._ensureIndex index
Feedback._ensureIndex index
Profiles._ensureIndex index
Messages._ensureIndex index
Posts._ensureIndex index
index =
parent_id: 1
Challenges._ensureIndex index
Solutions._ensureIndex index
Reviews._ensureIndex index
Feedback._ensureIndex index
Profiles._ensureIndex index
Posts._ensureIndex index
index =
solution_id: 1
Reviews._ensureIndex index
Feedback._ensureIndex index
index =
challenge_id: 1
Solutions._ensureIndex index
Reviews._ensureIndex index
Feedback._ensureIndex index
index =
content: "text"
title: "text"
Challenges._ensureIndex index
Solutions._ensureIndex index
Reviews._ensureIndex index
Feedback._ensureIndex index
Posts._ensureIndex index
msg = "MongoDB indices initialized"
log_event msg
#####################################################
# Checks
#####################################################
#####################################################
_check_environment_variables = () ->
msg = "Checking enviromnent variables"
log_event msg
url = process.env.MAIL_URL
if url
msg = "-- MAIL_URL is set."
log_event msg
else
msg = "-- MAIL_URL not set. Mail notifications are disabled!"
log_event msg, event_general, event_warn
token = process.env.DROP_BOX_ACCESS_TOKEN
if token
msg = "-- DROP_BOX_ACCESS_TOKEN is set."
log_event msg
else
msg = "-- DROP_BOX_ACCESS_TOKEN not set. Saving files is disabled!"
log_event msg, event_general, event_warn
msg = "Environment variables checked"
log_event msg
#####################################################
# Permissions
#####################################################
#####################################################
_initialize_permissions = () ->
log_event "Inserting default permissions"
asset_path = "db/defaultcollections/permissions.json"
asset_pobj = Meteor.settings.default_permissions_asset_path
if asset_pobj
assetp = asset_pobj.toString()
if not assetp == ""
asset_path = assetp
perms_txt = Assets.getText(asset_path)
perms = JSON.parse(perms_txt)
for perm, i in perms
_insert_permission_safe(perm)
#####################################################
# Helper functions to fill in default permissions
#####################################################
#####################################################
_find_permission_by_effectors = (p) ->
filter =
role: p.role
field: p.field
collection_name: p.collection_name
Permissions.find(filter)
#####################################################
_insert_permission_unsafe = (p) ->
id = Permissions.insert p
if not id
throw new Meteor.Error 'Could not insert permission to db : ' + p
return id
#####################################################
_insert_permission_safe = (p) ->
existing_permission = _find_permission_by_effectors(p)
if existing_permission.count() == 0
_insert_permission_unsafe(p)
else
#msg = "Permission already exists: " + JSON.stringify(p)
#log_event msg, event_db, event_info
#####################################################
# Database testing
#####################################################
#####################################################
_add_admin = (email, password) ->
log_event "Adding admin"
user = Accounts.findUserByEmail(email)
if not user
user =
email: email,
password: PI:PASSWORD:<PASSWORD>END_PI,
user = Accounts.createUser(user)
Roles.setUserRoles user, ["admin", "db_admin", "editor", "challenge_designer"]
user = Accounts.findUserByEmail(email)
filter =
owner_id: user._id
profile = Profiles.findOne filter
if profile
return profile._id
profile_id = gen_profile user, "learner"
msg = "admin added " + user.email + " " + profile_id
log_event msg, event_testing, event_info
return profile_id
####################################################
_initialize_database = () ->
console.log "####################################################"
console.log "## adding test data ##"
console.log "####################################################"
title = "The test challenge"
filter =
title: title
challenge = Challenges.findOne filter
if not challenge
challenge_id = _test_challenge title
challenge = Challenges.findOne challenge_id
learners = []
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9]
mail = String(i) + "@uni.edu"
profile_id = _test_user_creation mail, "learner"
profile = Profiles.findOne profile_id
user = Meteor.users.findOne profile.owner_id
learners.push user
solutions = []
for s in learners
solution_id = _test_solution challenge, s
solution = Solutions.findOne solution_id
solutions.push solution
for i in [1..challenge.num_reviews]
reviews = []
for s in learners
review_id = _test_review challenge, null, s
review = Reviews.findOne review_id
reviews.push review
for solution in solutions
filter =
solution_id: solution._id
reviews = Reviews.find(filter).fetch()
user = Meteor.users.findOne solution.owner_id
for review in reviews
_test_feedback solution, review, user
console.log "####################################################"
console.log "## test data added ##"
console.log "####################################################"
# TODO: test reviews when there is a solution like for tutors
#####################################################
_test_user_creation = (mail, occupation) ->
user = Accounts.findUserByEmail(mail)
if not user
user =
email: mail,
password: "PI:PASSWORD:<PASSWORD>END_PI",
user_id = Accounts.createUser(user)
user = Meteor.users.findOne user_id
console.log "Test user creation: " + user.emails[0].address
filter =
owner_id: user._id
profile = Profiles.findOne filter
if profile
return profile._id
profile_id = gen_profile user
modify_field_unprotected Profiles, profile_id, "avatar", faker.image.avatar()
modify_field_unprotected Profiles, profile_id, "given_name", faker.name.firstName()
modify_field_unprotected Profiles, profile_id, "family_name", faker.name.lastName()
modify_field_unprotected Profiles, profile_id, "middle_name", faker.name.firstName()
modify_field_unprotected Profiles, profile_id, "city", faker.address.city()
modify_field_unprotected Profiles, profile_id, "country", faker.address.country()
modify_field_unprotected Profiles, profile_id, "state", faker.address.state()
modify_field_unprotected Profiles, profile_id, "hours_per_week", Math.round(Random.fraction() * 40)
modify_field_unprotected Profiles, profile_id, "job_locale", Random.choice ["remote", "local"]
modify_field_unprotected Profiles, profile_id, "job_type", Random.choice ["free", "full"]
modify_field_unprotected Profiles, profile_id, "occupation", occupation
modify_field_unprotected Profiles, profile_id, "resume", faker.lorem.paragraphs 2
modify_field_unprotected Profiles, profile_id, "job_interested", true
modify_field_unprotected Profiles, profile_id, "test_object", true
return profile_id
#####################################################
_test_challenge = (title) ->
user = Accounts.findUserByEmail("PI:EMAIL:<EMAIL>END_PI")
if not user
_test_user_creation "PI:EMAIL:<EMAIL>END_PI", "organization"
user = Accounts.findUserByEmail("PI:EMAIL:<EMAIL>END_PI")
Roles.setUserRoles user, ["admin", "editor", "challenge_designer"]
challenge_id = gen_challenge user
modify_field_unprotected Challenges, challenge_id, "title", title
modify_field_unprotected Challenges, challenge_id, "content", faker.lorem.paragraphs(3)
modify_field_unprotected Challenges, challenge_id, "test_object", true
#TODO: add test for material
challenge = Challenges.findOne challenge_id
challenge_id = finish_challenge challenge, user
return challenge_id
#####################################################
_test_solution = (challenge, user) ->
filter =
challenge_id: challenge._id
owner_id: user._id
solution = Solutions.findOne filter
if solution
return solution._id
solution_id = gen_solution challenge, user
modify_field_unprotected Solutions, solution_id, "content", faker.lorem.paragraphs(3)
modify_field_unprotected Solutions, solution_id, "test_object", true
solution = Solutions.findOne solution_id
solution_id = finish_solution solution, user
solution = Solutions.findOne solution_id
solution_id = reopen_solution solution, user
solution = Solutions.findOne solution_id
solution_id = finish_solution solution, user
#TODO: add reopen fail test
return solution_id
#####################################################
_test_review = (challenge, solution, user) ->
try
res = assign_review challenge, solution, user
catch e
if e.error == "no-review"
return
throw e
modify_field_unprotected Reviews, res.review_id, "content", faker.lorem.paragraphs(3)
modify_field_unprotected Reviews, res.review_id, "rating", Random.choice [1,2,3,4,5]
modify_field_unprotected Reviews, res.review_id, "test_object", true
review = Reviews.findOne res.review_id
review_id = finish_review review, user
review = Reviews.findOne res.review_id
review_id = reopen_review review, user
review = Reviews.findOne res.review_id
review_id = finish_review review, user
#TODO: add reopen fail test
return review_id
#####################################################
_test_feedback = (solution, review, user) ->
feedback_id = gen_feedback solution, review, user
feedback = Feedback.findOne feedback_id
if feedback.published == true
return
modify_field_unprotected Feedback, feedback_id, "content", faker.lorem.paragraphs(3)
modify_field_unprotected Feedback, feedback_id, "rating", Random.choice [1,2,3,4,5]
modify_field_unprotected Feedback, feedback_id, "test_object", true
feedback = Feedback.findOne feedback_id
feedback_id = finish_feedback feedback, user
feedback_id = reopen_feedback feedback, user
feedback_id = finish_feedback feedback, user
#TODO: add reopen test
#TODO: add reopen fail test
#TODO: add repair fail test
return feedback_id
#####################################################
# start up
#####################################################
Meteor.startup () ->
try
_handle_startup_setting()
catch e
console.log e
|
[
{
"context": "r thumbnail in thumbnail_array\n key = 'pte-confirm['+thumbnail.name+']'\n data[key] = thumbn",
"end": 3636,
"score": 0.9567822217941284,
"start": 3623,
"tag": "KEY",
"value": "pte-confirm['"
}
] | web/app/plugins/post-thumbnail-editor/js/controllers/PteCtrl.coffee | elizabeets/kim | 0 | define [
'angular'
'cs!apps/pteApp'
'cs!settings'
'cs!jquery'
], (angular, app, settings, $) ->
app.controller "PteCtrl", ['$scope','$resource','$log', '$filter', ($scope, $resource, $log, $filter) ->
###
# Page handling feature
#
# Switch the enabled page to change the view
###
$scope.page =
loading: on
crop: off
view: off
$scope.changePage = (page) ->
$scope.viewFilterValue = off
for key, value of $scope.page
if key == page
$scope.page[key] = on
else
$scope.page[key] = off
###
# Set the Tab Class to active when the page is enabled
#
# This is watched by the view on a ng-class directive.
###
$scope.pageClass = (page) ->
if $scope.page[page]
return "nav-tab-active"
###
# Resource
###
$scope.thumbnailResource = $resource settings.ajaxurl,
'action': 'pte_ajax'
'pte-action': 'get-thumbnail-info'
###
# Catch the thumbnail selected event and broadcast to all the children scopes
###
#$scope.$on 'thumbnail_selected', (event, thumbs) ->
# $scope.$broadcast 'thumbnail_selected', thumbs
# return
###
# Publish selected event
###
$scope.updateSelected = ->
$scope.$broadcast 'thumbnail_selected'
###
# Update options
#
# Use this to update user/site options
###
$scope.updateOptions = (update_options) ->
update_options['pte-action'] = 'change-options'
update_options['pte-nonce'] = settings.options_nonce
$log.log "Updating Options", update_options
updated = $scope.thumbnailResource.get update_options, ->
$log.log "Updated options"
return
###
# ViewFilter is a filter expression that checks if the viewFilter specifies
# certain thumbnail names to display or if it should just be all modified.
#
# Using the tab buttons will reset this feature.
###
$scope.viewFilterValue = off
$scope.view = (val) ->
event?.stopPropagation?()
$scope.changePage('view')
$scope.viewFilterValue = val
return
$scope.viewFilterFunc = (thumbnail) ->
if $scope.viewFilterValue is off
return true
if angular.isString $scope.viewFilterValue
if thumbnail.name is $scope.viewFilterValue
return true
else
return false
if angular.isArray $scope.viewFilterValue
# check if thumbnail.name is in array
if thumbnail.name in $scope.viewFilterValue
return true
# This sets the view to show only the recently changed images
if $scope.viewFilterValue
return thumbnail.proposed?
return true
###
# SAVE
###
$scope.save = (thumbnail) ->
#event?.stopPropagation?()
#$log.log thumbnail_array
data =
'pte-action': 'confirm-images'
'pte-nonce': nonces['pte-nonce']
id: id
thumbnail_array = []
if !thumbnail
angular.forEach $scope.thumbnails, (thumb) ->
if thumb.proposed
thumbnail_array.push thumb
return
if thumbnail_array.length < 1
return
else
thumbnail_array.push thumbnail
for thumbnail in thumbnail_array
key = 'pte-confirm['+thumbnail.name+']'
data[key] = thumbnail.proposed.file
$log.log data
confirm_results = $scope.thumbnailResource.get data, ->
$scope.confirmResults confirm_results
return
$scope.confirmResults = (confirm_results) ->
if !confirm_results.thumbnails
$scope.setErrorMessage $scope.i18n.save_crop_problem
return
#$filter('randomizeUrl') {reset: true}
viewFilter = []
resetUrls = []
for thumbnail in $scope.thumbnails
if confirm_results.thumbnails[thumbnail.name]
viewFilter.push thumbnail.name
thumbnail.current = confirm_results.thumbnails[thumbnail.name].current
resetUrls.push thumbnail.current.url
if thumbnail.proposed?.url
resetUrls.push thumbnail.proposed.url
#if !angular.isObject thumbnail.current
# thumbnail.current = {}
#thumbnail.current.url = thumbnail.proposed.url
#thumbnail.selected = false
$scope.trash thumbnail
if confirm_results.immediate
# Change to the view
#$scope.view viewFilter
else
checkFilter()
$filter('randomizeUrl') {reset: true, urls: resetUrls}
return
###
# Clean up procedures
#
# trash function just removes from view.
# trashAll deletes from server, and we hook into the unload
# event to cleanup after ourselves
###
$scope.trash = (thumbnail) ->
event?.stopPropagation?()
delete thumbnail.proposed
thumbnail.showProposed = false
# if there aren't any other proposed, set the viewFilter to false
checkFilter()
# if there aren't any other proposed, set the viewFilter to false
checkFilter = ->
for thumbnail in $scope.thumbnails
if thumbnail.proposed
return
$scope.viewFilterValue = off
$scope.trashAll = ->
deleteTemp()
angular.forEach $scope.thumbnails, (thumb) ->
$scope.trash thumb
$filter('randomizeUrl') {reset: true}
return
deleteTemp = ->
if not nonces?['pte-delete-nonce']?
return
deleteResults = $.ajax settings.ajaxurl,
async: false
data:
'action': 'pte_ajax'
id: id
'pte-action': 'delete-images'
'pte-nonce': nonces['pte-delete-nonce']
return
$(window).unload (event) ->
deleteTemp()
return
###
# Allow selecting based on the aspect ratio
###
$scope.aspectRatios = []
addToAspectRatios = (thumb) ->
ar = thumb.width/thumb.height
# Check for valid AspectRatio
if !ar? or ar is Infinity
return
if !thumb.crop or +thumb.crop < 1
return
for aspectRatio in $scope.aspectRatios
if ar - 0.01 < aspectRatio.size < ar + 0.01
aspectRatio.thumbnails.push thumb.name
return
$scope.aspectRatios.push
size: ar
thumbnails: [thumb.name]
return
###
# Initialization
###
id = settings.id
if !id
$log.error "No ID Found"
$scope.i18n = settings.i18n
$scope.infoMessage = null
$scope.setInfoMessage = (message) ->
$scope.infoMessage = message
$scope.errorMessage = null
$scope.setErrorMessage = (message) ->
$scope.errorMessage = message
nonces = null
$scope.setNonces = (nonceObj) ->
nonces = nonceObj
## LOAD THE THUMBNAIL INFORMATION ##
$scope.thumbnails = []
$scope.thumbnailObject = $scope.thumbnailResource.get {id: id}, ->
angular.forEach $scope.thumbnailObject, (thumb, name) ->
if name not in ["$promise", "$resolved"]
thumb.name = name
@thumbnails.push thumb
addToAspectRatios thumb
return
, $scope
$scope.updateSelected()
# Turn off loading page
$log.info "Disabling loading screen"
$scope.changePage('crop')
return
$scope.anyProposed = ->
for thumb in $scope.thumbnails
if thumb.proposed?
return true
return false
###
# Used to hide/show the existing thumbnails
#
# @since 2.2.0
###
$scope.anySelected = ->
for thumb in $scope.thumbnails
if thumb.selected
return true
return false
###
# Update wordpress option when the currentThumbnailBarPosition changes
###
$scope.$watch 'currentThumbnailBarPosition', (x,y) ->
if x is y
return
$scope.updateOptions
'pte_thumbnail_bar': $scope.currentThumbnailBarPosition
return
$scope.toggleCurrentThumbnailBarPosition = ->
positions = ["vertical", "horizontal"]
if $scope.currentThumbnailBarPosition is positions[0]
$scope.currentThumbnailBarPosition = positions[1]
else
$scope.currentThumbnailBarPosition = positions[0]
return
### STOP THE MADNESS ###
return
]
return app
| 169943 | define [
'angular'
'cs!apps/pteApp'
'cs!settings'
'cs!jquery'
], (angular, app, settings, $) ->
app.controller "PteCtrl", ['$scope','$resource','$log', '$filter', ($scope, $resource, $log, $filter) ->
###
# Page handling feature
#
# Switch the enabled page to change the view
###
$scope.page =
loading: on
crop: off
view: off
$scope.changePage = (page) ->
$scope.viewFilterValue = off
for key, value of $scope.page
if key == page
$scope.page[key] = on
else
$scope.page[key] = off
###
# Set the Tab Class to active when the page is enabled
#
# This is watched by the view on a ng-class directive.
###
$scope.pageClass = (page) ->
if $scope.page[page]
return "nav-tab-active"
###
# Resource
###
$scope.thumbnailResource = $resource settings.ajaxurl,
'action': 'pte_ajax'
'pte-action': 'get-thumbnail-info'
###
# Catch the thumbnail selected event and broadcast to all the children scopes
###
#$scope.$on 'thumbnail_selected', (event, thumbs) ->
# $scope.$broadcast 'thumbnail_selected', thumbs
# return
###
# Publish selected event
###
$scope.updateSelected = ->
$scope.$broadcast 'thumbnail_selected'
###
# Update options
#
# Use this to update user/site options
###
$scope.updateOptions = (update_options) ->
update_options['pte-action'] = 'change-options'
update_options['pte-nonce'] = settings.options_nonce
$log.log "Updating Options", update_options
updated = $scope.thumbnailResource.get update_options, ->
$log.log "Updated options"
return
###
# ViewFilter is a filter expression that checks if the viewFilter specifies
# certain thumbnail names to display or if it should just be all modified.
#
# Using the tab buttons will reset this feature.
###
$scope.viewFilterValue = off
$scope.view = (val) ->
event?.stopPropagation?()
$scope.changePage('view')
$scope.viewFilterValue = val
return
$scope.viewFilterFunc = (thumbnail) ->
if $scope.viewFilterValue is off
return true
if angular.isString $scope.viewFilterValue
if thumbnail.name is $scope.viewFilterValue
return true
else
return false
if angular.isArray $scope.viewFilterValue
# check if thumbnail.name is in array
if thumbnail.name in $scope.viewFilterValue
return true
# This sets the view to show only the recently changed images
if $scope.viewFilterValue
return thumbnail.proposed?
return true
###
# SAVE
###
$scope.save = (thumbnail) ->
#event?.stopPropagation?()
#$log.log thumbnail_array
data =
'pte-action': 'confirm-images'
'pte-nonce': nonces['pte-nonce']
id: id
thumbnail_array = []
if !thumbnail
angular.forEach $scope.thumbnails, (thumb) ->
if thumb.proposed
thumbnail_array.push thumb
return
if thumbnail_array.length < 1
return
else
thumbnail_array.push thumbnail
for thumbnail in thumbnail_array
key = '<KEY>+thumbnail.name+']'
data[key] = thumbnail.proposed.file
$log.log data
confirm_results = $scope.thumbnailResource.get data, ->
$scope.confirmResults confirm_results
return
$scope.confirmResults = (confirm_results) ->
if !confirm_results.thumbnails
$scope.setErrorMessage $scope.i18n.save_crop_problem
return
#$filter('randomizeUrl') {reset: true}
viewFilter = []
resetUrls = []
for thumbnail in $scope.thumbnails
if confirm_results.thumbnails[thumbnail.name]
viewFilter.push thumbnail.name
thumbnail.current = confirm_results.thumbnails[thumbnail.name].current
resetUrls.push thumbnail.current.url
if thumbnail.proposed?.url
resetUrls.push thumbnail.proposed.url
#if !angular.isObject thumbnail.current
# thumbnail.current = {}
#thumbnail.current.url = thumbnail.proposed.url
#thumbnail.selected = false
$scope.trash thumbnail
if confirm_results.immediate
# Change to the view
#$scope.view viewFilter
else
checkFilter()
$filter('randomizeUrl') {reset: true, urls: resetUrls}
return
###
# Clean up procedures
#
# trash function just removes from view.
# trashAll deletes from server, and we hook into the unload
# event to cleanup after ourselves
###
$scope.trash = (thumbnail) ->
event?.stopPropagation?()
delete thumbnail.proposed
thumbnail.showProposed = false
# if there aren't any other proposed, set the viewFilter to false
checkFilter()
# if there aren't any other proposed, set the viewFilter to false
checkFilter = ->
for thumbnail in $scope.thumbnails
if thumbnail.proposed
return
$scope.viewFilterValue = off
$scope.trashAll = ->
deleteTemp()
angular.forEach $scope.thumbnails, (thumb) ->
$scope.trash thumb
$filter('randomizeUrl') {reset: true}
return
deleteTemp = ->
if not nonces?['pte-delete-nonce']?
return
deleteResults = $.ajax settings.ajaxurl,
async: false
data:
'action': 'pte_ajax'
id: id
'pte-action': 'delete-images'
'pte-nonce': nonces['pte-delete-nonce']
return
$(window).unload (event) ->
deleteTemp()
return
###
# Allow selecting based on the aspect ratio
###
$scope.aspectRatios = []
addToAspectRatios = (thumb) ->
ar = thumb.width/thumb.height
# Check for valid AspectRatio
if !ar? or ar is Infinity
return
if !thumb.crop or +thumb.crop < 1
return
for aspectRatio in $scope.aspectRatios
if ar - 0.01 < aspectRatio.size < ar + 0.01
aspectRatio.thumbnails.push thumb.name
return
$scope.aspectRatios.push
size: ar
thumbnails: [thumb.name]
return
###
# Initialization
###
id = settings.id
if !id
$log.error "No ID Found"
$scope.i18n = settings.i18n
$scope.infoMessage = null
$scope.setInfoMessage = (message) ->
$scope.infoMessage = message
$scope.errorMessage = null
$scope.setErrorMessage = (message) ->
$scope.errorMessage = message
nonces = null
$scope.setNonces = (nonceObj) ->
nonces = nonceObj
## LOAD THE THUMBNAIL INFORMATION ##
$scope.thumbnails = []
$scope.thumbnailObject = $scope.thumbnailResource.get {id: id}, ->
angular.forEach $scope.thumbnailObject, (thumb, name) ->
if name not in ["$promise", "$resolved"]
thumb.name = name
@thumbnails.push thumb
addToAspectRatios thumb
return
, $scope
$scope.updateSelected()
# Turn off loading page
$log.info "Disabling loading screen"
$scope.changePage('crop')
return
$scope.anyProposed = ->
for thumb in $scope.thumbnails
if thumb.proposed?
return true
return false
###
# Used to hide/show the existing thumbnails
#
# @since 2.2.0
###
$scope.anySelected = ->
for thumb in $scope.thumbnails
if thumb.selected
return true
return false
###
# Update wordpress option when the currentThumbnailBarPosition changes
###
$scope.$watch 'currentThumbnailBarPosition', (x,y) ->
if x is y
return
$scope.updateOptions
'pte_thumbnail_bar': $scope.currentThumbnailBarPosition
return
$scope.toggleCurrentThumbnailBarPosition = ->
positions = ["vertical", "horizontal"]
if $scope.currentThumbnailBarPosition is positions[0]
$scope.currentThumbnailBarPosition = positions[1]
else
$scope.currentThumbnailBarPosition = positions[0]
return
### STOP THE MADNESS ###
return
]
return app
| true | define [
'angular'
'cs!apps/pteApp'
'cs!settings'
'cs!jquery'
], (angular, app, settings, $) ->
app.controller "PteCtrl", ['$scope','$resource','$log', '$filter', ($scope, $resource, $log, $filter) ->
###
# Page handling feature
#
# Switch the enabled page to change the view
###
$scope.page =
loading: on
crop: off
view: off
$scope.changePage = (page) ->
$scope.viewFilterValue = off
for key, value of $scope.page
if key == page
$scope.page[key] = on
else
$scope.page[key] = off
###
# Set the Tab Class to active when the page is enabled
#
# This is watched by the view on a ng-class directive.
###
$scope.pageClass = (page) ->
if $scope.page[page]
return "nav-tab-active"
###
# Resource
###
$scope.thumbnailResource = $resource settings.ajaxurl,
'action': 'pte_ajax'
'pte-action': 'get-thumbnail-info'
###
# Catch the thumbnail selected event and broadcast to all the children scopes
###
#$scope.$on 'thumbnail_selected', (event, thumbs) ->
# $scope.$broadcast 'thumbnail_selected', thumbs
# return
###
# Publish selected event
###
$scope.updateSelected = ->
$scope.$broadcast 'thumbnail_selected'
###
# Update options
#
# Use this to update user/site options
###
$scope.updateOptions = (update_options) ->
update_options['pte-action'] = 'change-options'
update_options['pte-nonce'] = settings.options_nonce
$log.log "Updating Options", update_options
updated = $scope.thumbnailResource.get update_options, ->
$log.log "Updated options"
return
###
# ViewFilter is a filter expression that checks if the viewFilter specifies
# certain thumbnail names to display or if it should just be all modified.
#
# Using the tab buttons will reset this feature.
###
$scope.viewFilterValue = off
$scope.view = (val) ->
event?.stopPropagation?()
$scope.changePage('view')
$scope.viewFilterValue = val
return
$scope.viewFilterFunc = (thumbnail) ->
if $scope.viewFilterValue is off
return true
if angular.isString $scope.viewFilterValue
if thumbnail.name is $scope.viewFilterValue
return true
else
return false
if angular.isArray $scope.viewFilterValue
# check if thumbnail.name is in array
if thumbnail.name in $scope.viewFilterValue
return true
# This sets the view to show only the recently changed images
if $scope.viewFilterValue
return thumbnail.proposed?
return true
###
# SAVE
###
$scope.save = (thumbnail) ->
#event?.stopPropagation?()
#$log.log thumbnail_array
data =
'pte-action': 'confirm-images'
'pte-nonce': nonces['pte-nonce']
id: id
thumbnail_array = []
if !thumbnail
angular.forEach $scope.thumbnails, (thumb) ->
if thumb.proposed
thumbnail_array.push thumb
return
if thumbnail_array.length < 1
return
else
thumbnail_array.push thumbnail
for thumbnail in thumbnail_array
key = 'PI:KEY:<KEY>END_PI+thumbnail.name+']'
data[key] = thumbnail.proposed.file
$log.log data
confirm_results = $scope.thumbnailResource.get data, ->
$scope.confirmResults confirm_results
return
$scope.confirmResults = (confirm_results) ->
if !confirm_results.thumbnails
$scope.setErrorMessage $scope.i18n.save_crop_problem
return
#$filter('randomizeUrl') {reset: true}
viewFilter = []
resetUrls = []
for thumbnail in $scope.thumbnails
if confirm_results.thumbnails[thumbnail.name]
viewFilter.push thumbnail.name
thumbnail.current = confirm_results.thumbnails[thumbnail.name].current
resetUrls.push thumbnail.current.url
if thumbnail.proposed?.url
resetUrls.push thumbnail.proposed.url
#if !angular.isObject thumbnail.current
# thumbnail.current = {}
#thumbnail.current.url = thumbnail.proposed.url
#thumbnail.selected = false
$scope.trash thumbnail
if confirm_results.immediate
# Change to the view
#$scope.view viewFilter
else
checkFilter()
$filter('randomizeUrl') {reset: true, urls: resetUrls}
return
###
# Clean up procedures
#
# trash function just removes from view.
# trashAll deletes from server, and we hook into the unload
# event to cleanup after ourselves
###
$scope.trash = (thumbnail) ->
event?.stopPropagation?()
delete thumbnail.proposed
thumbnail.showProposed = false
# if there aren't any other proposed, set the viewFilter to false
checkFilter()
# if there aren't any other proposed, set the viewFilter to false
checkFilter = ->
for thumbnail in $scope.thumbnails
if thumbnail.proposed
return
$scope.viewFilterValue = off
$scope.trashAll = ->
deleteTemp()
angular.forEach $scope.thumbnails, (thumb) ->
$scope.trash thumb
$filter('randomizeUrl') {reset: true}
return
deleteTemp = ->
if not nonces?['pte-delete-nonce']?
return
deleteResults = $.ajax settings.ajaxurl,
async: false
data:
'action': 'pte_ajax'
id: id
'pte-action': 'delete-images'
'pte-nonce': nonces['pte-delete-nonce']
return
$(window).unload (event) ->
deleteTemp()
return
###
# Allow selecting based on the aspect ratio
###
$scope.aspectRatios = []
addToAspectRatios = (thumb) ->
ar = thumb.width/thumb.height
# Check for valid AspectRatio
if !ar? or ar is Infinity
return
if !thumb.crop or +thumb.crop < 1
return
for aspectRatio in $scope.aspectRatios
if ar - 0.01 < aspectRatio.size < ar + 0.01
aspectRatio.thumbnails.push thumb.name
return
$scope.aspectRatios.push
size: ar
thumbnails: [thumb.name]
return
###
# Initialization
###
id = settings.id
if !id
$log.error "No ID Found"
$scope.i18n = settings.i18n
$scope.infoMessage = null
$scope.setInfoMessage = (message) ->
$scope.infoMessage = message
$scope.errorMessage = null
$scope.setErrorMessage = (message) ->
$scope.errorMessage = message
nonces = null
$scope.setNonces = (nonceObj) ->
nonces = nonceObj
## LOAD THE THUMBNAIL INFORMATION ##
$scope.thumbnails = []
$scope.thumbnailObject = $scope.thumbnailResource.get {id: id}, ->
angular.forEach $scope.thumbnailObject, (thumb, name) ->
if name not in ["$promise", "$resolved"]
thumb.name = name
@thumbnails.push thumb
addToAspectRatios thumb
return
, $scope
$scope.updateSelected()
# Turn off loading page
$log.info "Disabling loading screen"
$scope.changePage('crop')
return
$scope.anyProposed = ->
for thumb in $scope.thumbnails
if thumb.proposed?
return true
return false
###
# Used to hide/show the existing thumbnails
#
# @since 2.2.0
###
$scope.anySelected = ->
for thumb in $scope.thumbnails
if thumb.selected
return true
return false
###
# Update wordpress option when the currentThumbnailBarPosition changes
###
$scope.$watch 'currentThumbnailBarPosition', (x,y) ->
if x is y
return
$scope.updateOptions
'pte_thumbnail_bar': $scope.currentThumbnailBarPosition
return
$scope.toggleCurrentThumbnailBarPosition = ->
positions = ["vertical", "horizontal"]
if $scope.currentThumbnailBarPosition is positions[0]
$scope.currentThumbnailBarPosition = positions[1]
else
$scope.currentThumbnailBarPosition = positions[0]
return
### STOP THE MADNESS ###
return
]
return app
|
[
{
"context": "elper.defaultGateway.customer.create {firstName: 'Jane', lastName: 'Doe'}, (err, response) ->\n cu",
"end": 3236,
"score": 0.9996705055236816,
"start": 3232,
"tag": "NAME",
"value": "Jane"
},
{
"context": "ay.customer.create {firstName: 'Jane', lastName: 'Doe'}, ... | spec/integration/braintree/paypal_account_gateway_spec.coffee | StreamCo/braintree_node | 0 | require('../../spec_helper')
_ = require('underscore')._
braintree = specHelper.braintree
util = require('util')
{PayPalAccount} = require('../../../lib/braintree/paypal_account')
{Config} = require('../../../lib/braintree/config')
{Nonces} = require('../../../lib/braintree/test/nonces')
describe "PayPalGateway", ->
describe "find", ->
it "finds the paypal account", (done) ->
specHelper.defaultGateway.customer.create {}, (err, response) ->
paymentMethodParams =
customerId: response.customer.id
paymentMethodNonce: Nonces.PayPalFuturePayment
specHelper.defaultGateway.paymentMethod.create paymentMethodParams, (err, response) ->
paymentMethodToken = response.paymentMethod.token
specHelper.defaultGateway.paypalAccount.find paymentMethodToken, (err, paypalAccount) ->
assert.isNull(err)
assert.isString(paypalAccount.email)
assert.isString(paypalAccount.imageUrl)
assert.isString(paypalAccount.createdAt)
assert.isString(paypalAccount.updatedAt)
done()
it "handles not finding the paypal account", (done) ->
specHelper.defaultGateway.paypalAccount.find 'NONEXISTENT_TOKEN', (err, creditCard) ->
assert.equal(err.type, braintree.errorTypes.notFoundError)
done()
it "handles whitespace", (done) ->
specHelper.defaultGateway.paypalAccount.find ' ', (err, creditCard) ->
assert.equal(err.type, braintree.errorTypes.notFoundError)
done()
it "returns subscriptions associated with a paypal account", (done) ->
specHelper.defaultGateway.customer.create {}, (err, response) ->
paymentMethodParams =
customerId: response.customer.id
paymentMethodNonce: Nonces.PayPalFuturePayment
specHelper.defaultGateway.paymentMethod.create paymentMethodParams, (err, response) ->
token = response.paymentMethod.token
subscriptionParams =
paymentMethodToken: token
planId: specHelper.plans.trialless.id
specHelper.defaultGateway.subscription.create subscriptionParams, (err, response) ->
assert.isNull(err)
assert.isTrue(response.success)
subscription1 = response.subscription
specHelper.defaultGateway.subscription.create subscriptionParams, (err, response) ->
assert.isNull(err)
assert.isTrue(response.success)
subscription2 = response.subscription
specHelper.defaultGateway.paypalAccount.find token, (err, paypalAccount) ->
assert.isNull(err)
assert.equal(paypalAccount.subscriptions.length, 2)
subscriptionIds = [paypalAccount.subscriptions[0].id, paypalAccount.subscriptions[1].id]
assert.include(subscriptionIds, subscription1.id)
assert.include(subscriptionIds, subscription2.id)
done()
describe "update", ->
paymentMethodToken = null
customerId = null
beforeEach (done) ->
paymentMethodToken = Math.floor(Math.random() * Math.pow(36,3)).toString(36)
specHelper.defaultGateway.customer.create {firstName: 'Jane', lastName: 'Doe'}, (err, response) ->
customerId = response.customer.id
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({}, (err, result) ->
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
authorizationFingerprint = clientToken.authorizationFingerprint
params = {
authorizationFingerprint: authorizationFingerprint,
paypalAccount: {
consentCode: 'PAYPAL_CONSENT_CODE'
token: paymentMethodToken
}
}
myHttp.post("/client_api/v1/payment_methods/paypal_accounts.json", params, (statusCode, body) ->
nonce = JSON.parse(body).paypalAccounts[0].nonce
paypalAccountParams =
customerId: customerId
paymentMethodNonce: nonce
specHelper.defaultGateway.paymentMethod.create paypalAccountParams, (err, response) ->
paymentMethodToken = response.paymentMethod.token
done()
)
)
it "updates the paypal account", (done) ->
updateParams =
token: paymentMethodToken+'123'
specHelper.defaultGateway.paypalAccount.update paymentMethodToken, updateParams, (err, response) ->
assert.isNull(err)
assert.isTrue(response.success)
assert.equal(response.paypalAccount.token, paymentMethodToken+'123')
specHelper.defaultGateway.paypalAccount.find paymentMethodToken, (err, response) ->
assert.equal(err.type, braintree.errorTypes.notFoundError)
done()
it "updates and makes an account the default", (done) ->
creditCardParams =
customerId: customerId
number: '5105105105105100'
expirationDate: '05/2012'
options:
makeDefault: true
specHelper.defaultGateway.creditCard.create creditCardParams, (err, response) ->
assert.isTrue(response.success)
assert.isTrue(response.creditCard.default)
updateParams =
token: paymentMethodToken
options:
makeDefault: true
specHelper.defaultGateway.paypalAccount.update paymentMethodToken, updateParams, (err, response) ->
assert.isTrue(response.success)
assert.isTrue(response.paypalAccount.default)
done()
it "handles errors", (done) ->
paypalAccountParams =
customerId: customerId
paymentMethodNonce: Nonces.PayPalFuturePayment
specHelper.defaultGateway.paymentMethod.create paypalAccountParams, (err, response) ->
assert.isTrue(response.success)
originalToken = response.paymentMethod.token
specHelper.defaultGateway.paymentMethod.create paypalAccountParams, (err, response) ->
newPaymentMethodToken = response.paymentMethod.token
updateParams =
token: originalToken
specHelper.defaultGateway.paypalAccount.update newPaymentMethodToken, updateParams, (err, response) ->
assert.isFalse(response.success)
assert.equal(
response.errors.for('paypalAccount').on('token')[0].code,
'92906'
)
done()
describe "delete", (done) ->
paymentMethodToken = null
before (done) ->
specHelper.defaultGateway.customer.create {firstName: 'Jane', lastName: 'Doe'}, (err, response) ->
customerId = response.customer.id
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({}, (err, result) ->
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
authorizationFingerprint = clientToken.authorizationFingerprint
params = {
authorizationFingerprint: authorizationFingerprint,
paypalAccount: {
consentCode: 'PAYPAL_CONSENT_CODE'
}
}
myHttp.post("/client_api/v1/payment_methods/paypal_accounts.json", params, (statusCode, body) ->
nonce = JSON.parse(body).paypalAccounts[0].nonce
paypalAccountParams =
customerId: customerId
paymentMethodNonce: nonce
specHelper.defaultGateway.paymentMethod.create paypalAccountParams, (err, response) ->
paymentMethodToken = response.paymentMethod.token
done()
)
)
it "deletes the paypal account", (done) ->
specHelper.defaultGateway.paypalAccount.delete paymentMethodToken, (err) ->
assert.isNull(err)
specHelper.defaultGateway.paypalAccount.find paymentMethodToken, (err, response) ->
assert.equal(err.type, braintree.errorTypes.notFoundError)
done()
it "handles invalid tokens", (done) ->
specHelper.defaultGateway.paypalAccount.delete 'NON_EXISTENT_TOKEN', (err) ->
assert.equal(err.type, braintree.errorTypes.notFoundError)
done()
| 27673 | require('../../spec_helper')
_ = require('underscore')._
braintree = specHelper.braintree
util = require('util')
{PayPalAccount} = require('../../../lib/braintree/paypal_account')
{Config} = require('../../../lib/braintree/config')
{Nonces} = require('../../../lib/braintree/test/nonces')
describe "PayPalGateway", ->
describe "find", ->
it "finds the paypal account", (done) ->
specHelper.defaultGateway.customer.create {}, (err, response) ->
paymentMethodParams =
customerId: response.customer.id
paymentMethodNonce: Nonces.PayPalFuturePayment
specHelper.defaultGateway.paymentMethod.create paymentMethodParams, (err, response) ->
paymentMethodToken = response.paymentMethod.token
specHelper.defaultGateway.paypalAccount.find paymentMethodToken, (err, paypalAccount) ->
assert.isNull(err)
assert.isString(paypalAccount.email)
assert.isString(paypalAccount.imageUrl)
assert.isString(paypalAccount.createdAt)
assert.isString(paypalAccount.updatedAt)
done()
it "handles not finding the paypal account", (done) ->
specHelper.defaultGateway.paypalAccount.find 'NONEXISTENT_TOKEN', (err, creditCard) ->
assert.equal(err.type, braintree.errorTypes.notFoundError)
done()
it "handles whitespace", (done) ->
specHelper.defaultGateway.paypalAccount.find ' ', (err, creditCard) ->
assert.equal(err.type, braintree.errorTypes.notFoundError)
done()
it "returns subscriptions associated with a paypal account", (done) ->
specHelper.defaultGateway.customer.create {}, (err, response) ->
paymentMethodParams =
customerId: response.customer.id
paymentMethodNonce: Nonces.PayPalFuturePayment
specHelper.defaultGateway.paymentMethod.create paymentMethodParams, (err, response) ->
token = response.paymentMethod.token
subscriptionParams =
paymentMethodToken: token
planId: specHelper.plans.trialless.id
specHelper.defaultGateway.subscription.create subscriptionParams, (err, response) ->
assert.isNull(err)
assert.isTrue(response.success)
subscription1 = response.subscription
specHelper.defaultGateway.subscription.create subscriptionParams, (err, response) ->
assert.isNull(err)
assert.isTrue(response.success)
subscription2 = response.subscription
specHelper.defaultGateway.paypalAccount.find token, (err, paypalAccount) ->
assert.isNull(err)
assert.equal(paypalAccount.subscriptions.length, 2)
subscriptionIds = [paypalAccount.subscriptions[0].id, paypalAccount.subscriptions[1].id]
assert.include(subscriptionIds, subscription1.id)
assert.include(subscriptionIds, subscription2.id)
done()
describe "update", ->
paymentMethodToken = null
customerId = null
beforeEach (done) ->
paymentMethodToken = Math.floor(Math.random() * Math.pow(36,3)).toString(36)
specHelper.defaultGateway.customer.create {firstName: '<NAME>', lastName: '<NAME>'}, (err, response) ->
customerId = response.customer.id
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({}, (err, result) ->
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
authorizationFingerprint = clientToken.authorizationFingerprint
params = {
authorizationFingerprint: authorizationFingerprint,
paypalAccount: {
consentCode: 'PAYPAL_CONSENT_CODE'
token: paymentMethodToken
}
}
myHttp.post("/client_api/v1/payment_methods/paypal_accounts.json", params, (statusCode, body) ->
nonce = JSON.parse(body).paypalAccounts[0].nonce
paypalAccountParams =
customerId: customerId
paymentMethodNonce: nonce
specHelper.defaultGateway.paymentMethod.create paypalAccountParams, (err, response) ->
paymentMethodToken = response.paymentMethod.token
done()
)
)
it "updates the paypal account", (done) ->
updateParams =
token: paymentMethodToken+'<PASSWORD>'
specHelper.defaultGateway.paypalAccount.update paymentMethodToken, updateParams, (err, response) ->
assert.isNull(err)
assert.isTrue(response.success)
assert.equal(response.paypalAccount.token, paymentMethodToken+'<PASSWORD>')
specHelper.defaultGateway.paypalAccount.find paymentMethodToken, (err, response) ->
assert.equal(err.type, braintree.errorTypes.notFoundError)
done()
it "updates and makes an account the default", (done) ->
creditCardParams =
customerId: customerId
number: '5105105105105100'
expirationDate: '05/2012'
options:
makeDefault: true
specHelper.defaultGateway.creditCard.create creditCardParams, (err, response) ->
assert.isTrue(response.success)
assert.isTrue(response.creditCard.default)
updateParams =
token: paymentMethodToken
options:
makeDefault: true
specHelper.defaultGateway.paypalAccount.update paymentMethodToken, updateParams, (err, response) ->
assert.isTrue(response.success)
assert.isTrue(response.paypalAccount.default)
done()
it "handles errors", (done) ->
paypalAccountParams =
customerId: customerId
paymentMethodNonce: Nonces.PayPalFuturePayment
specHelper.defaultGateway.paymentMethod.create paypalAccountParams, (err, response) ->
assert.isTrue(response.success)
originalToken = response.paymentMethod.token
specHelper.defaultGateway.paymentMethod.create paypalAccountParams, (err, response) ->
newPaymentMethodToken = response.paymentMethod.token
updateParams =
token: originalToken
specHelper.defaultGateway.paypalAccount.update newPaymentMethodToken, updateParams, (err, response) ->
assert.isFalse(response.success)
assert.equal(
response.errors.for('paypalAccount').on('token')[0].code,
'92906'
)
done()
describe "delete", (done) ->
paymentMethodToken = null
before (done) ->
specHelper.defaultGateway.customer.create {firstName: '<NAME>', lastName: '<NAME>'}, (err, response) ->
customerId = response.customer.id
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({}, (err, result) ->
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
authorizationFingerprint = clientToken.authorizationFingerprint
params = {
authorizationFingerprint: authorizationFingerprint,
paypalAccount: {
consentCode: 'PAYPAL_CONSENT_CODE'
}
}
myHttp.post("/client_api/v1/payment_methods/paypal_accounts.json", params, (statusCode, body) ->
nonce = JSON.parse(body).paypalAccounts[0].nonce
paypalAccountParams =
customerId: customerId
paymentMethodNonce: nonce
specHelper.defaultGateway.paymentMethod.create paypalAccountParams, (err, response) ->
paymentMethodToken = response.paymentMethod.token
done()
)
)
it "deletes the paypal account", (done) ->
specHelper.defaultGateway.paypalAccount.delete paymentMethodToken, (err) ->
assert.isNull(err)
specHelper.defaultGateway.paypalAccount.find paymentMethodToken, (err, response) ->
assert.equal(err.type, braintree.errorTypes.notFoundError)
done()
it "handles invalid tokens", (done) ->
specHelper.defaultGateway.paypalAccount.delete 'NON_EXISTENT_TOKEN', (err) ->
assert.equal(err.type, braintree.errorTypes.notFoundError)
done()
| true | require('../../spec_helper')
_ = require('underscore')._
braintree = specHelper.braintree
util = require('util')
{PayPalAccount} = require('../../../lib/braintree/paypal_account')
{Config} = require('../../../lib/braintree/config')
{Nonces} = require('../../../lib/braintree/test/nonces')
describe "PayPalGateway", ->
describe "find", ->
it "finds the paypal account", (done) ->
specHelper.defaultGateway.customer.create {}, (err, response) ->
paymentMethodParams =
customerId: response.customer.id
paymentMethodNonce: Nonces.PayPalFuturePayment
specHelper.defaultGateway.paymentMethod.create paymentMethodParams, (err, response) ->
paymentMethodToken = response.paymentMethod.token
specHelper.defaultGateway.paypalAccount.find paymentMethodToken, (err, paypalAccount) ->
assert.isNull(err)
assert.isString(paypalAccount.email)
assert.isString(paypalAccount.imageUrl)
assert.isString(paypalAccount.createdAt)
assert.isString(paypalAccount.updatedAt)
done()
it "handles not finding the paypal account", (done) ->
specHelper.defaultGateway.paypalAccount.find 'NONEXISTENT_TOKEN', (err, creditCard) ->
assert.equal(err.type, braintree.errorTypes.notFoundError)
done()
it "handles whitespace", (done) ->
specHelper.defaultGateway.paypalAccount.find ' ', (err, creditCard) ->
assert.equal(err.type, braintree.errorTypes.notFoundError)
done()
it "returns subscriptions associated with a paypal account", (done) ->
specHelper.defaultGateway.customer.create {}, (err, response) ->
paymentMethodParams =
customerId: response.customer.id
paymentMethodNonce: Nonces.PayPalFuturePayment
specHelper.defaultGateway.paymentMethod.create paymentMethodParams, (err, response) ->
token = response.paymentMethod.token
subscriptionParams =
paymentMethodToken: token
planId: specHelper.plans.trialless.id
specHelper.defaultGateway.subscription.create subscriptionParams, (err, response) ->
assert.isNull(err)
assert.isTrue(response.success)
subscription1 = response.subscription
specHelper.defaultGateway.subscription.create subscriptionParams, (err, response) ->
assert.isNull(err)
assert.isTrue(response.success)
subscription2 = response.subscription
specHelper.defaultGateway.paypalAccount.find token, (err, paypalAccount) ->
assert.isNull(err)
assert.equal(paypalAccount.subscriptions.length, 2)
subscriptionIds = [paypalAccount.subscriptions[0].id, paypalAccount.subscriptions[1].id]
assert.include(subscriptionIds, subscription1.id)
assert.include(subscriptionIds, subscription2.id)
done()
describe "update", ->
paymentMethodToken = null
customerId = null
beforeEach (done) ->
paymentMethodToken = Math.floor(Math.random() * Math.pow(36,3)).toString(36)
specHelper.defaultGateway.customer.create {firstName: 'PI:NAME:<NAME>END_PI', lastName: 'PI:NAME:<NAME>END_PI'}, (err, response) ->
customerId = response.customer.id
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({}, (err, result) ->
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
authorizationFingerprint = clientToken.authorizationFingerprint
params = {
authorizationFingerprint: authorizationFingerprint,
paypalAccount: {
consentCode: 'PAYPAL_CONSENT_CODE'
token: paymentMethodToken
}
}
myHttp.post("/client_api/v1/payment_methods/paypal_accounts.json", params, (statusCode, body) ->
nonce = JSON.parse(body).paypalAccounts[0].nonce
paypalAccountParams =
customerId: customerId
paymentMethodNonce: nonce
specHelper.defaultGateway.paymentMethod.create paypalAccountParams, (err, response) ->
paymentMethodToken = response.paymentMethod.token
done()
)
)
it "updates the paypal account", (done) ->
updateParams =
token: paymentMethodToken+'PI:PASSWORD:<PASSWORD>END_PI'
specHelper.defaultGateway.paypalAccount.update paymentMethodToken, updateParams, (err, response) ->
assert.isNull(err)
assert.isTrue(response.success)
assert.equal(response.paypalAccount.token, paymentMethodToken+'PI:PASSWORD:<PASSWORD>END_PI')
specHelper.defaultGateway.paypalAccount.find paymentMethodToken, (err, response) ->
assert.equal(err.type, braintree.errorTypes.notFoundError)
done()
it "updates and makes an account the default", (done) ->
creditCardParams =
customerId: customerId
number: '5105105105105100'
expirationDate: '05/2012'
options:
makeDefault: true
specHelper.defaultGateway.creditCard.create creditCardParams, (err, response) ->
assert.isTrue(response.success)
assert.isTrue(response.creditCard.default)
updateParams =
token: paymentMethodToken
options:
makeDefault: true
specHelper.defaultGateway.paypalAccount.update paymentMethodToken, updateParams, (err, response) ->
assert.isTrue(response.success)
assert.isTrue(response.paypalAccount.default)
done()
it "handles errors", (done) ->
paypalAccountParams =
customerId: customerId
paymentMethodNonce: Nonces.PayPalFuturePayment
specHelper.defaultGateway.paymentMethod.create paypalAccountParams, (err, response) ->
assert.isTrue(response.success)
originalToken = response.paymentMethod.token
specHelper.defaultGateway.paymentMethod.create paypalAccountParams, (err, response) ->
newPaymentMethodToken = response.paymentMethod.token
updateParams =
token: originalToken
specHelper.defaultGateway.paypalAccount.update newPaymentMethodToken, updateParams, (err, response) ->
assert.isFalse(response.success)
assert.equal(
response.errors.for('paypalAccount').on('token')[0].code,
'92906'
)
done()
describe "delete", (done) ->
paymentMethodToken = null
before (done) ->
specHelper.defaultGateway.customer.create {firstName: 'PI:NAME:<NAME>END_PI', lastName: 'PI:NAME:<NAME>END_PI'}, (err, response) ->
customerId = response.customer.id
myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig))
specHelper.defaultGateway.clientToken.generate({}, (err, result) ->
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
authorizationFingerprint = clientToken.authorizationFingerprint
params = {
authorizationFingerprint: authorizationFingerprint,
paypalAccount: {
consentCode: 'PAYPAL_CONSENT_CODE'
}
}
myHttp.post("/client_api/v1/payment_methods/paypal_accounts.json", params, (statusCode, body) ->
nonce = JSON.parse(body).paypalAccounts[0].nonce
paypalAccountParams =
customerId: customerId
paymentMethodNonce: nonce
specHelper.defaultGateway.paymentMethod.create paypalAccountParams, (err, response) ->
paymentMethodToken = response.paymentMethod.token
done()
)
)
it "deletes the paypal account", (done) ->
specHelper.defaultGateway.paypalAccount.delete paymentMethodToken, (err) ->
assert.isNull(err)
specHelper.defaultGateway.paypalAccount.find paymentMethodToken, (err, response) ->
assert.equal(err.type, braintree.errorTypes.notFoundError)
done()
it "handles invalid tokens", (done) ->
specHelper.defaultGateway.paypalAccount.delete 'NON_EXISTENT_TOKEN', (err) ->
assert.equal(err.type, braintree.errorTypes.notFoundError)
done()
|
[
{
"context": "\nwordlist = [\n 'abaco'\n 'abbaglio'\n 'abbinato'\n 'abete'\n 'abisso'\n ",
"end": 22,
"score": 0.947329044342041,
"start": 19,
"tag": "NAME",
"value": "aco"
},
{
"context": "\nwordlist = [\n 'abaco'\n 'abbaglio'\n 'abbinato'\n 'abete'\n 'abisso'\n 'abolire'... | addon/utils/wordlists/it.coffee | melis-wallet/melis-cm-svcs | 0 |
wordlist = [
'abaco'
'abbaglio'
'abbinato'
'abete'
'abisso'
'abolire'
'abrasivo'
'abrogato'
'accadere'
'accenno'
'accusato'
'acetone'
'achille'
'acido'
'acqua'
'acre'
'acrilico'
'acrobata'
'acuto'
'adagio'
'addebito'
'addome'
'adeguato'
'aderire'
'adipe'
'adottare'
'adulare'
'affabile'
'affetto'
'affisso'
'affranto'
'aforisma'
'afoso'
'africano'
'agave'
'agente'
'agevole'
'aggancio'
'agire'
'agitare'
'agonismo'
'agricolo'
'agrumeto'
'aguzzo'
'alabarda'
'alato'
'albatro'
'alberato'
'albo'
'albume'
'alce'
'alcolico'
'alettone'
'alfa'
'algebra'
'aliante'
'alibi'
'alimento'
'allagato'
'allegro'
'allievo'
'allodola'
'allusivo'
'almeno'
'alogeno'
'alpaca'
'alpestre'
'altalena'
'alterno'
'alticcio'
'altrove'
'alunno'
'alveolo'
'alzare'
'amalgama'
'amanita'
'amarena'
'ambito'
'ambrato'
'ameba'
'america'
'ametista'
'amico'
'ammasso'
'ammenda'
'ammirare'
'ammonito'
'amore'
'ampio'
'ampliare'
'amuleto'
'anacardo'
'anagrafe'
'analista'
'anarchia'
'anatra'
'anca'
'ancella'
'ancora'
'andare'
'andrea'
'anello'
'angelo'
'angolare'
'angusto'
'anima'
'annegare'
'annidato'
'anno'
'annuncio'
'anonimo'
'anticipo'
'anzi'
'apatico'
'apertura'
'apode'
'apparire'
'appetito'
'appoggio'
'approdo'
'appunto'
'aprile'
'arabica'
'arachide'
'aragosta'
'araldica'
'arancio'
'aratura'
'arazzo'
'arbitro'
'archivio'
'ardito'
'arenile'
'argento'
'argine'
'arguto'
'aria'
'armonia'
'arnese'
'arredato'
'arringa'
'arrosto'
'arsenico'
'arso'
'artefice'
'arzillo'
'asciutto'
'ascolto'
'asepsi'
'asettico'
'asfalto'
'asino'
'asola'
'aspirato'
'aspro'
'assaggio'
'asse'
'assoluto'
'assurdo'
'asta'
'astenuto'
'astice'
'astratto'
'atavico'
'ateismo'
'atomico'
'atono'
'attesa'
'attivare'
'attorno'
'attrito'
'attuale'
'ausilio'
'austria'
'autista'
'autonomo'
'autunno'
'avanzato'
'avere'
'avvenire'
'avviso'
'avvolgere'
'azione'
'azoto'
'azzimo'
'azzurro'
'babele'
'baccano'
'bacino'
'baco'
'badessa'
'badilata'
'bagnato'
'baita'
'balcone'
'baldo'
'balena'
'ballata'
'balzano'
'bambino'
'bandire'
'baraonda'
'barbaro'
'barca'
'baritono'
'barlume'
'barocco'
'basilico'
'basso'
'batosta'
'battuto'
'baule'
'bava'
'bavosa'
'becco'
'beffa'
'belgio'
'belva'
'benda'
'benevole'
'benigno'
'benzina'
'bere'
'berlina'
'beta'
'bibita'
'bici'
'bidone'
'bifido'
'biga'
'bilancia'
'bimbo'
'binocolo'
'biologo'
'bipede'
'bipolare'
'birbante'
'birra'
'biscotto'
'bisesto'
'bisnonno'
'bisonte'
'bisturi'
'bizzarro'
'blando'
'blatta'
'bollito'
'bonifico'
'bordo'
'bosco'
'botanico'
'bottino'
'bozzolo'
'braccio'
'bradipo'
'brama'
'branca'
'bravura'
'bretella'
'brevetto'
'brezza'
'briglia'
'brillante'
'brindare'
'broccolo'
'brodo'
'bronzina'
'brullo'
'bruno'
'bubbone'
'buca'
'budino'
'buffone'
'buio'
'bulbo'
'buono'
'burlone'
'burrasca'
'bussola'
'busta'
'cadetto'
'caduco'
'calamaro'
'calcolo'
'calesse'
'calibro'
'calmo'
'caloria'
'cambusa'
'camerata'
'camicia'
'cammino'
'camola'
'campale'
'canapa'
'candela'
'cane'
'canino'
'canotto'
'cantina'
'capace'
'capello'
'capitolo'
'capogiro'
'cappero'
'capra'
'capsula'
'carapace'
'carcassa'
'cardo'
'carisma'
'carovana'
'carretto'
'cartolina'
'casaccio'
'cascata'
'caserma'
'caso'
'cassone'
'castello'
'casuale'
'catasta'
'catena'
'catrame'
'cauto'
'cavillo'
'cedibile'
'cedrata'
'cefalo'
'celebre'
'cellulare'
'cena'
'cenone'
'centesimo'
'ceramica'
'cercare'
'certo'
'cerume'
'cervello'
'cesoia'
'cespo'
'ceto'
'chela'
'chiaro'
'chicca'
'chiedere'
'chimera'
'china'
'chirurgo'
'chitarra'
'ciao'
'ciclismo'
'cifrare'
'cigno'
'cilindro'
'ciottolo'
'circa'
'cirrosi'
'citrico'
'cittadino'
'ciuffo'
'civetta'
'civile'
'classico'
'clinica'
'cloro'
'cocco'
'codardo'
'codice'
'coerente'
'cognome'
'collare'
'colmato'
'colore'
'colposo'
'coltivato'
'colza'
'coma'
'cometa'
'commando'
'comodo'
'computer'
'comune'
'conciso'
'condurre'
'conferma'
'congelare'
'coniuge'
'connesso'
'conoscere'
'consumo'
'continuo'
'convegno'
'coperto'
'copione'
'coppia'
'copricapo'
'corazza'
'cordata'
'coricato'
'cornice'
'corolla'
'corpo'
'corredo'
'corsia'
'cortese'
'cosmico'
'costante'
'cottura'
'covato'
'cratere'
'cravatta'
'creato'
'credere'
'cremoso'
'crescita'
'creta'
'criceto'
'crinale'
'crisi'
'critico'
'croce'
'cronaca'
'crostata'
'cruciale'
'crusca'
'cucire'
'cuculo'
'cugino'
'cullato'
'cupola'
'curatore'
'cursore'
'curvo'
'cuscino'
'custode'
'dado'
'daino'
'dalmata'
'damerino'
'daniela'
'dannoso'
'danzare'
'datato'
'davanti'
'davvero'
'debutto'
'decennio'
'deciso'
'declino'
'decollo'
'decreto'
'dedicato'
'definito'
'deforme'
'degno'
'delegare'
'delfino'
'delirio'
'delta'
'demenza'
'denotato'
'dentro'
'deposito'
'derapata'
'derivare'
'deroga'
'descritto'
'deserto'
'desiderio'
'desumere'
'detersivo'
'devoto'
'diametro'
'dicembre'
'diedro'
'difeso'
'diffuso'
'digerire'
'digitale'
'diluvio'
'dinamico'
'dinnanzi'
'dipinto'
'diploma'
'dipolo'
'diradare'
'dire'
'dirotto'
'dirupo'
'disagio'
'discreto'
'disfare'
'disgelo'
'disposto'
'distanza'
'disumano'
'dito'
'divano'
'divelto'
'dividere'
'divorato'
'doblone'
'docente'
'doganale'
'dogma'
'dolce'
'domato'
'domenica'
'dominare'
'dondolo'
'dono'
'dormire'
'dote'
'dottore'
'dovuto'
'dozzina'
'drago'
'druido'
'dubbio'
'dubitare'
'ducale'
'duna'
'duomo'
'duplice'
'duraturo'
'ebano'
'eccesso'
'ecco'
'eclissi'
'economia'
'edera'
'edicola'
'edile'
'editoria'
'educare'
'egemonia'
'egli'
'egoismo'
'egregio'
'elaborato'
'elargire'
'elegante'
'elencato'
'eletto'
'elevare'
'elfico'
'elica'
'elmo'
'elsa'
'eluso'
'emanato'
'emblema'
'emesso'
'emiro'
'emotivo'
'emozione'
'empirico'
'emulo'
'endemico'
'enduro'
'energia'
'enfasi'
'enoteca'
'entrare'
'enzima'
'epatite'
'epilogo'
'episodio'
'epocale'
'eppure'
'equatore'
'erario'
'erba'
'erboso'
'erede'
'eremita'
'erigere'
'ermetico'
'eroe'
'erosivo'
'errante'
'esagono'
'esame'
'esanime'
'esaudire'
'esca'
'esempio'
'esercito'
'esibito'
'esigente'
'esistere'
'esito'
'esofago'
'esortato'
'esoso'
'espanso'
'espresso'
'essenza'
'esso'
'esteso'
'estimare'
'estonia'
'estroso'
'esultare'
'etilico'
'etnico'
'etrusco'
'etto'
'euclideo'
'europa'
'evaso'
'evidenza'
'evitato'
'evoluto'
'evviva'
'fabbrica'
'faccenda'
'fachiro'
'falco'
'famiglia'
'fanale'
'fanfara'
'fango'
'fantasma'
'fare'
'farfalla'
'farinoso'
'farmaco'
'fascia'
'fastoso'
'fasullo'
'faticare'
'fato'
'favoloso'
'febbre'
'fecola'
'fede'
'fegato'
'felpa'
'feltro'
'femmina'
'fendere'
'fenomeno'
'fermento'
'ferro'
'fertile'
'fessura'
'festivo'
'fetta'
'feudo'
'fiaba'
'fiducia'
'fifa'
'figurato'
'filo'
'finanza'
'finestra'
'finire'
'fiore'
'fiscale'
'fisico'
'fiume'
'flacone'
'flamenco'
'flebo'
'flemma'
'florido'
'fluente'
'fluoro'
'fobico'
'focaccia'
'focoso'
'foderato'
'foglio'
'folata'
'folclore'
'folgore'
'fondente'
'fonetico'
'fonia'
'fontana'
'forbito'
'forchetta'
'foresta'
'formica'
'fornaio'
'foro'
'fortezza'
'forzare'
'fosfato'
'fosso'
'fracasso'
'frana'
'frassino'
'fratello'
'freccetta'
'frenata'
'fresco'
'frigo'
'frollino'
'fronde'
'frugale'
'frutta'
'fucilata'
'fucsia'
'fuggente'
'fulmine'
'fulvo'
'fumante'
'fumetto'
'fumoso'
'fune'
'funzione'
'fuoco'
'furbo'
'furgone'
'furore'
'fuso'
'futile'
'gabbiano'
'gaffe'
'galateo'
'gallina'
'galoppo'
'gambero'
'gamma'
'garanzia'
'garbo'
'garofano'
'garzone'
'gasdotto'
'gasolio'
'gastrico'
'gatto'
'gaudio'
'gazebo'
'gazzella'
'geco'
'gelatina'
'gelso'
'gemello'
'gemmato'
'gene'
'genitore'
'gennaio'
'genotipo'
'gergo'
'ghepardo'
'ghiaccio'
'ghisa'
'giallo'
'gilda'
'ginepro'
'giocare'
'gioiello'
'giorno'
'giove'
'girato'
'girone'
'gittata'
'giudizio'
'giurato'
'giusto'
'globulo'
'glutine'
'gnomo'
'gobba'
'golf'
'gomito'
'gommone'
'gonfio'
'gonna'
'governo'
'gracile'
'grado'
'grafico'
'grammo'
'grande'
'grattare'
'gravoso'
'grazia'
'greca'
'gregge'
'grifone'
'grigio'
'grinza'
'grotta'
'gruppo'
'guadagno'
'guaio'
'guanto'
'guardare'
'gufo'
'guidare'
'ibernato'
'icona'
'identico'
'idillio'
'idolo'
'idra'
'idrico'
'idrogeno'
'igiene'
'ignaro'
'ignorato'
'ilare'
'illeso'
'illogico'
'illudere'
'imballo'
'imbevuto'
'imbocco'
'imbuto'
'immane'
'immerso'
'immolato'
'impacco'
'impeto'
'impiego'
'importo'
'impronta'
'inalare'
'inarcare'
'inattivo'
'incanto'
'incendio'
'inchino'
'incisivo'
'incluso'
'incontro'
'incrocio'
'incubo'
'indagine'
'india'
'indole'
'inedito'
'infatti'
'infilare'
'inflitto'
'ingaggio'
'ingegno'
'inglese'
'ingordo'
'ingrosso'
'innesco'
'inodore'
'inoltrare'
'inondato'
'insano'
'insetto'
'insieme'
'insonnia'
'insulina'
'intasato'
'intero'
'intonaco'
'intuito'
'inumidire'
'invalido'
'invece'
'invito'
'iperbole'
'ipnotico'
'ipotesi'
'ippica'
'iride'
'irlanda'
'ironico'
'irrigato'
'irrorare'
'isolato'
'isotopo'
'isterico'
'istituto'
'istrice'
'italia'
'iterare'
'labbro'
'labirinto'
'lacca'
'lacerato'
'lacrima'
'lacuna'
'laddove'
'lago'
'lampo'
'lancetta'
'lanterna'
'lardoso'
'larga'
'laringe'
'lastra'
'latenza'
'latino'
'lattuga'
'lavagna'
'lavoro'
'legale'
'leggero'
'lembo'
'lentezza'
'lenza'
'leone'
'lepre'
'lesivo'
'lessato'
'lesto'
'letterale'
'leva'
'levigato'
'libero'
'lido'
'lievito'
'lilla'
'limatura'
'limitare'
'limpido'
'lineare'
'lingua'
'liquido'
'lira'
'lirica'
'lisca'
'lite'
'litigio'
'livrea'
'locanda'
'lode'
'logica'
'lombare'
'londra'
'longevo'
'loquace'
'lorenzo'
'loto'
'lotteria'
'luce'
'lucidato'
'lumaca'
'luminoso'
'lungo'
'lupo'
'luppolo'
'lusinga'
'lusso'
'lutto'
'macabro'
'macchina'
'macero'
'macinato'
'madama'
'magico'
'maglia'
'magnete'
'magro'
'maiolica'
'malafede'
'malgrado'
'malinteso'
'malsano'
'malto'
'malumore'
'mana'
'mancia'
'mandorla'
'mangiare'
'manifesto'
'mannaro'
'manovra'
'mansarda'
'mantide'
'manubrio'
'mappa'
'maratona'
'marcire'
'maretta'
'marmo'
'marsupio'
'maschera'
'massaia'
'mastino'
'materasso'
'matricola'
'mattone'
'maturo'
'mazurca'
'meandro'
'meccanico'
'mecenate'
'medesimo'
'meditare'
'mega'
'melassa'
'melis'
'melodia'
'meninge'
'meno'
'mensola'
'mercurio'
'merenda'
'merlo'
'meschino'
'mese'
'messere'
'mestolo'
'metallo'
'metodo'
'mettere'
'miagolare'
'mica'
'micelio'
'michele'
'microbo'
'midollo'
'miele'
'migliore'
'milano'
'milite'
'mimosa'
'minerale'
'mini'
'minore'
'mirino'
'mirtillo'
'miscela'
'missiva'
'misto'
'misurare'
'mitezza'
'mitigare'
'mitra'
'mittente'
'mnemonico'
'modello'
'modifica'
'modulo'
'mogano'
'mogio'
'mole'
'molosso'
'monastero'
'monco'
'mondina'
'monetario'
'monile'
'monotono'
'monsone'
'montato'
'monviso'
'mora'
'mordere'
'morsicato'
'mostro'
'motivato'
'motosega'
'motto'
'movenza'
'movimento'
'mozzo'
'mucca'
'mucosa'
'muffa'
'mughetto'
'mugnaio'
'mulatto'
'mulinello'
'multiplo'
'mummia'
'munto'
'muovere'
'murale'
'musa'
'muscolo'
'musica'
'mutevole'
'muto'
'nababbo'
'nafta'
'nanometro'
'narciso'
'narice'
'narrato'
'nascere'
'nastrare'
'naturale'
'nautica'
'naviglio'
'nebulosa'
'necrosi'
'negativo'
'negozio'
'nemmeno'
'neofita'
'neretto'
'nervo'
'nessuno'
'nettuno'
'neutrale'
'neve'
'nevrotico'
'nicchia'
'ninfa'
'nitido'
'nobile'
'nocivo'
'nodo'
'nome'
'nomina'
'nordico'
'normale'
'norvegese'
'nostrano'
'notare'
'notizia'
'notturno'
'novella'
'nucleo'
'nulla'
'numero'
'nuovo'
'nutrire'
'nuvola'
'nuziale'
'oasi'
'obbedire'
'obbligo'
'obelisco'
'oblio'
'obolo'
'obsoleto'
'occasione'
'occhio'
'occidente'
'occorrere'
'occultare'
'ocra'
'oculato'
'odierno'
'odorare'
'offerta'
'offrire'
'offuscato'
'oggetto'
'oggi'
'ognuno'
'olandese'
'olfatto'
'oliato'
'oliva'
'ologramma'
'oltre'
'omaggio'
'ombelico'
'ombra'
'omega'
'omissione'
'ondoso'
'onere'
'onice'
'onnivoro'
'onorevole'
'onta'
'operato'
'opinione'
'opposto'
'oracolo'
'orafo'
'ordine'
'orecchino'
'orefice'
'orfano'
'organico'
'origine'
'orizzonte'
'orma'
'ormeggio'
'ornativo'
'orologio'
'orrendo'
'orribile'
'ortensia'
'ortica'
'orzata'
'orzo'
'osare'
'oscurare'
'osmosi'
'ospedale'
'ospite'
'ossa'
'ossidare'
'ostacolo'
'oste'
'otite'
'otre'
'ottagono'
'ottimo'
'ottobre'
'ovale'
'ovest'
'ovino'
'oviparo'
'ovocito'
'ovunque'
'ovviare'
'ozio'
'pacchetto'
'pace'
'pacifico'
'padella'
'padrone'
'paese'
'paga'
'pagina'
'palazzina'
'palesare'
'pallido'
'palo'
'palude'
'pandoro'
'pannello'
'paolo'
'paonazzo'
'paprica'
'parabola'
'parcella'
'parere'
'pargolo'
'pari'
'parlato'
'parola'
'partire'
'parvenza'
'parziale'
'passivo'
'pasticca'
'patacca'
'patologia'
'pattume'
'pavone'
'peccato'
'pedalare'
'pedonale'
'peggio'
'peloso'
'penare'
'pendice'
'penisola'
'pennuto'
'penombra'
'pensare'
'pentola'
'pepe'
'pepita'
'perbene'
'percorso'
'perdonato'
'perforare'
'pergamena'
'periodo'
'permesso'
'perno'
'perplesso'
'persuaso'
'pertugio'
'pervaso'
'pesatore'
'pesista'
'peso'
'pestifero'
'petalo'
'pettine'
'petulante'
'pezzo'
'piacere'
'pianta'
'piattino'
'piccino'
'picozza'
'piega'
'pietra'
'piffero'
'pigiama'
'pigolio'
'pigro'
'pila'
'pilifero'
'pillola'
'pilota'
'pimpante'
'pineta'
'pinna'
'pinolo'
'pioggia'
'piombo'
'piramide'
'piretico'
'pirite'
'pirolisi'
'pitone'
'pizzico'
'placebo'
'planare'
'plasma'
'platano'
'plenario'
'pochezza'
'poderoso'
'podismo'
'poesia'
'poggiare'
'polenta'
'poligono'
'pollice'
'polmonite'
'polpetta'
'polso'
'poltrona'
'polvere'
'pomice'
'pomodoro'
'ponte'
'popoloso'
'porfido'
'poroso'
'porpora'
'porre'
'portata'
'posa'
'positivo'
'possesso'
'postulato'
'potassio'
'potere'
'pranzo'
'prassi'
'pratica'
'precluso'
'predica'
'prefisso'
'pregiato'
'prelievo'
'premere'
'prenotare'
'preparato'
'presenza'
'pretesto'
'prevalso'
'prima'
'principe'
'privato'
'problema'
'procura'
'produrre'
'profumo'
'progetto'
'prolunga'
'promessa'
'pronome'
'proposta'
'proroga'
'proteso'
'prova'
'prudente'
'prugna'
'prurito'
'psiche'
'pubblico'
'pudica'
'pugilato'
'pugno'
'pulce'
'pulito'
'pulsante'
'puntare'
'pupazzo'
'pupilla'
'puro'
'quadro'
'qualcosa'
'quasi'
'querela'
'quota'
'raccolto'
'raddoppio'
'radicale'
'radunato'
'raffica'
'ragazzo'
'ragione'
'ragno'
'ramarro'
'ramingo'
'ramo'
'randagio'
'rantolare'
'rapato'
'rapina'
'rappreso'
'rasatura'
'raschiato'
'rasente'
'rassegna'
'rastrello'
'rata'
'ravveduto'
'reale'
'recepire'
'recinto'
'recluta'
'recondito'
'recupero'
'reddito'
'redimere'
'regalato'
'registro'
'regola'
'regresso'
'relazione'
'remare'
'remoto'
'renna'
'replica'
'reprimere'
'reputare'
'resa'
'residente'
'responso'
'restauro'
'rete'
'retina'
'retorica'
'rettifica'
'revocato'
'riassunto'
'ribadire'
'ribelle'
'ribrezzo'
'ricarica'
'ricco'
'ricevere'
'riciclato'
'ricordo'
'ricreduto'
'ridicolo'
'ridurre'
'rifasare'
'riflesso'
'riforma'
'rifugio'
'rigare'
'rigettato'
'righello'
'rilassato'
'rilevato'
'rimanere'
'rimbalzo'
'rimedio'
'rimorchio'
'rinascita'
'rincaro'
'rinforzo'
'rinnovo'
'rinomato'
'rinsavito'
'rintocco'
'rinuncia'
'rinvenire'
'riparato'
'ripetuto'
'ripieno'
'riportare'
'ripresa'
'ripulire'
'risata'
'rischio'
'riserva'
'risibile'
'riso'
'rispetto'
'ristoro'
'risultato'
'risvolto'
'ritardo'
'ritegno'
'ritmico'
'ritrovo'
'riunione'
'riva'
'riverso'
'rivincita'
'rivolto'
'rizoma'
'roba'
'robotico'
'robusto'
'roccia'
'roco'
'rodaggio'
'rodere'
'roditore'
'rogito'
'rollio'
'romantico'
'rompere'
'ronzio'
'rosolare'
'rospo'
'rotante'
'rotondo'
'rotula'
'rovescio'
'rubizzo'
'rubrica'
'ruga'
'rullino'
'rumine'
'rumoroso'
'ruolo'
'rupe'
'russare'
'rustico'
'sabato'
'sabbiare'
'sabotato'
'sagoma'
'salasso'
'saldatura'
'salgemma'
'salivare'
'salmone'
'salone'
'saltare'
'saluto'
'salvo'
'sapere'
'sapido'
'saporito'
'saraceno'
'sarcasmo'
'sarto'
'sassoso'
'satellite'
'satira'
'satollo'
'saturno'
'savana'
'savio'
'saziato'
'sbadiglio'
'sbalzo'
'sbancato'
'sbarra'
'sbattere'
'sbavare'
'sbendare'
'sbirciare'
'sbloccato'
'sbocciato'
'sbrinare'
'sbruffone'
'sbuffare'
'scabroso'
'scadenza'
'scala'
'scambiare'
'scandalo'
'scapola'
'scarso'
'scatenare'
'scavato'
'scelto'
'scenico'
'scettro'
'scheda'
'schiena'
'sciarpa'
'scienza'
'scindere'
'scippo'
'sciroppo'
'scivolo'
'sclerare'
'scodella'
'scolpito'
'scomparto'
'sconforto'
'scoprire'
'scorta'
'scossone'
'scozzese'
'scriba'
'scrollare'
'scrutinio'
'scuderia'
'scultore'
'scuola'
'scuro'
'scusare'
'sdebitare'
'sdoganare'
'seccatura'
'secondo'
'sedano'
'seggiola'
'segnalato'
'segregato'
'seguito'
'selciato'
'selettivo'
'sella'
'selvaggio'
'semaforo'
'sembrare'
'seme'
'seminato'
'sempre'
'senso'
'sentire'
'sepolto'
'sequenza'
'serata'
'serbato'
'sereno'
'serio'
'serpente'
'serraglio'
'servire'
'sestina'
'setola'
'settimana'
'sfacelo'
'sfaldare'
'sfamato'
'sfarzoso'
'sfaticato'
'sfera'
'sfida'
'sfilato'
'sfinge'
'sfocato'
'sfoderare'
'sfogo'
'sfoltire'
'sforzato'
'sfratto'
'sfruttato'
'sfuggito'
'sfumare'
'sfuso'
'sgabello'
'sgarbato'
'sgonfiare'
'sgorbio'
'sgrassato'
'sguardo'
'sibilo'
'siccome'
'sierra'
'sigla'
'signore'
'silenzio'
'sillaba'
'simbolo'
'simpatico'
'simulato'
'sinfonia'
'singolo'
'sinistro'
'sino'
'sintesi'
'sinusoide'
'sipario'
'sisma'
'sistole'
'situato'
'slitta'
'slogatura'
'sloveno'
'smarrito'
'smemorato'
'smentito'
'smeraldo'
'smilzo'
'smontare'
'smottato'
'smussato'
'snellire'
'snervato'
'snodo'
'sobbalzo'
'sobrio'
'soccorso'
'sociale'
'sodale'
'soffitto'
'sogno'
'soldato'
'solenne'
'solido'
'sollazzo'
'solo'
'solubile'
'solvente'
'somatico'
'somma'
'sonda'
'sonetto'
'sonnifero'
'sopire'
'soppeso'
'sopra'
'sorgere'
'sorpasso'
'sorriso'
'sorso'
'sorteggio'
'sorvolato'
'sospiro'
'sosta'
'sottile'
'spada'
'spalla'
'spargere'
'spatola'
'spavento'
'spazzola'
'specie'
'spedire'
'spegnere'
'spelatura'
'speranza'
'spessore'
'spettrale'
'spezzato'
'spia'
'spigoloso'
'spillato'
'spinoso'
'spirale'
'splendido'
'sportivo'
'sposo'
'spranga'
'sprecare'
'spronato'
'spruzzo'
'spuntino'
'squillo'
'sradicare'
'srotolato'
'stabile'
'stacco'
'staffa'
'stagnare'
'stampato'
'stantio'
'starnuto'
'stasera'
'statuto'
'stelo'
'steppa'
'sterzo'
'stiletto'
'stima'
'stirpe'
'stivale'
'stizzoso'
'stonato'
'storico'
'strappo'
'stregato'
'stridulo'
'strozzare'
'strutto'
'stuccare'
'stufo'
'stupendo'
'subentro'
'succoso'
'sudore'
'suggerito'
'sugo'
'sultano'
'suonare'
'superbo'
'supporto'
'surgelato'
'surrogato'
'sussurro'
'sutura'
'svagare'
'svedese'
'sveglio'
'svelare'
'svenuto'
'svezia'
'sviluppo'
'svista'
'svizzera'
'svolta'
'svuotare'
'tabacco'
'tabulato'
'tacciare'
'taciturno'
'tale'
'talismano'
'tampone'
'tannino'
'tara'
'tardivo'
'targato'
'tariffa'
'tarpare'
'tartaruga'
'tasto'
'tattico'
'taverna'
'tavolata'
'tazza'
'teca'
'tecnico'
'telefono'
'temerario'
'tempo'
'temuto'
'tendone'
'tenero'
'tensione'
'tentacolo'
'teorema'
'terme'
'terrazzo'
'terzetto'
'tesi'
'tesserato'
'testato'
'tetro'
'tettoia'
'tifare'
'tigella'
'timbro'
'tinto'
'tipico'
'tipografo'
'tiraggio'
'tiro'
'titanio'
'titolo'
'titubante'
'tizio'
'tizzone'
'toccare'
'tollerare'
'tolto'
'tombola'
'tomo'
'tonfo'
'tonsilla'
'topazio'
'topologia'
'toppa'
'torba'
'tornare'
'torrone'
'tortora'
'toscano'
'tossire'
'tostatura'
'totano'
'trabocco'
'trachea'
'trafila'
'tragedia'
'tralcio'
'tramonto'
'transito'
'trapano'
'trarre'
'trasloco'
'trattato'
'trave'
'treccia'
'tremolio'
'trespolo'
'tributo'
'tricheco'
'trifoglio'
'trillo'
'trincea'
'trio'
'tristezza'
'triturato'
'trivella'
'tromba'
'trono'
'troppo'
'trottola'
'trovare'
'truccato'
'tubatura'
'tuffato'
'tulipano'
'tumulto'
'tunisia'
'turbare'
'turchino'
'tuta'
'tutela'
'ubicato'
'uccello'
'uccisore'
'udire'
'uditivo'
'uffa'
'ufficio'
'uguale'
'ulisse'
'ultimato'
'umano'
'umile'
'umorismo'
'uncinetto'
'ungere'
'ungherese'
'unicorno'
'unificato'
'unisono'
'unitario'
'unte'
'uovo'
'upupa'
'uragano'
'urgenza'
'urlo'
'usanza'
'usato'
'uscito'
'usignolo'
'usuraio'
'utensile'
'utilizzo'
'utopia'
'vacante'
'vaccinato'
'vagabondo'
'vagliato'
'valanga'
'valgo'
'valico'
'valletta'
'valoroso'
'valutare'
'valvola'
'vampata'
'vangare'
'vanitoso'
'vano'
'vantaggio'
'vanvera'
'vapore'
'varano'
'varcato'
'variante'
'vasca'
'vedetta'
'vedova'
'veduto'
'vegetale'
'veicolo'
'velcro'
'velina'
'velluto'
'veloce'
'venato'
'vendemmia'
'vento'
'verace'
'verbale'
'vergogna'
'verifica'
'vero'
'verruca'
'verticale'
'vescica'
'vessillo'
'vestale'
'veterano'
'vetrina'
'vetusto'
'viandante'
'vibrante'
'vicenda'
'vichingo'
'vicinanza'
'vidimare'
'vigilia'
'vigneto'
'vigore'
'vile'
'villano'
'vimini'
'vincitore'
'viola'
'vipera'
'virgola'
'virologo'
'virulento'
'viscoso'
'visione'
'vispo'
'vissuto'
'visura'
'vita'
'vitello'
'vittima'
'vivanda'
'vivido'
'viziare'
'voce'
'voga'
'volatile'
'volere'
'volpe'
'voragine'
'vulcano'
'zampogna'
'zanna'
'zappato'
'zattera'
'zavorra'
'zefiro'
'zelante'
'zelo'
'zenzero'
'zerbino'
'zibetto'
'zinco'
'zircone'
'zitto'
'zolla'
'zotico'
'zucchero'
'zufolo'
'zulu'
'zuppa'
]
`export default wordlist` | 162434 |
wordlist = [
'ab<NAME>'
'abb<NAME>'
'abbinato'
'abete'
'abisso'
'abolire'
'abrasivo'
'abrogato'
'accadere'
'accenno'
'accusato'
'acetone'
'achille'
'acido'
'acqua'
'acre'
'acrilico'
'acrobata'
'acuto'
'adagio'
'addebito'
'addome'
'adeguato'
'aderire'
'adipe'
'adottare'
'adulare'
'affabile'
'affetto'
'affisso'
'affranto'
'aforisma'
'afoso'
'africano'
'agave'
'agente'
'agevole'
'aggancio'
'agire'
'agitare'
'agonismo'
'agricolo'
'agrumeto'
'aguzzo'
'alabarda'
'alato'
'albatro'
'alberato'
'albo'
'albume'
'alce'
'alcolico'
'alettone'
'alfa'
'algebra'
'aliante'
'alibi'
'alimento'
'allagato'
'allegro'
'allievo'
'allodola'
'allusivo'
'almeno'
'alogeno'
'alpaca'
'alpestre'
'altalena'
'alterno'
'alticcio'
'altrove'
'alunno'
'alveolo'
'alzare'
'amalgama'
'amanita'
'amarena'
'ambito'
'ambrato'
'ameba'
'america'
'ametista'
'amico'
'ammasso'
'ammenda'
'ammirare'
'ammonito'
'amore'
'ampio'
'ampliare'
'amule<NAME>'
'anacardo'
'anagrafe'
'analista'
'anarchia'
'anatra'
'anca'
'ancella'
'ancora'
'<NAME>'
'andrea'
'<NAME>'
'angelo'
'<NAME>'
'angusto'
'anima'
'anneg<NAME>'
'annidato'
'anno'
'annuncio'
'anonimo'
'anticipo'
'anzi'
'apatico'
'apertura'
'apode'
'apparire'
'appetito'
'appoggio'
'approdo'
'appunto'
'aprile'
'arabica'
'arachide'
'aragosta'
'araldica'
'arancio'
'aratura'
'arazzo'
'arbitro'
'archivio'
'ardito'
'arenile'
'argento'
'argine'
'arguto'
'aria'
'armonia'
'arnese'
'arredato'
'arringa'
'arrosto'
'arsenico'
'arso'
'artefice'
'arzillo'
'asciutto'
'ascolto'
'asepsi'
'asettico'
'asfalto'
'asino'
'asola'
'aspirato'
'aspro'
'assaggio'
'asse'
'assoluto'
'assurdo'
'asta'
'astenuto'
'astice'
'astratto'
'atavico'
'ateismo'
'atomico'
'atono'
'attesa'
'attivare'
'attorno'
'attrito'
'attuale'
'ausilio'
'austria'
'autista'
'autonomo'
'autunno'
'avanzato'
'avere'
'avvenire'
'avviso'
'avvolgere'
'azione'
'<NAME>'
'<NAME>'
'azz<NAME>ro'
'babele'
'bac<NAME>o'
'bacino'
'baco'
'badessa'
'badilata'
'bagnato'
'baita'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'bar<NAME>'
'barca'
'baritono'
'barlume'
'barocco'
'basilico'
'basso'
'batosta'
'battuto'
'baule'
'bava'
'bavosa'
'<NAME>'
'<NAME>'
'bel<NAME>'
'belva'
'benda'
'<NAME>'
'<NAME>'
'ben<NAME>ina'
'bere'
'berlina'
'beta'
'bibita'
'bici'
'bidone'
'bifido'
'biga'
'bil<NAME>'
'bimbo'
'binocolo'
'biologo'
'bipede'
'bipolare'
'birbante'
'birra'
'biscotto'
'bisesto'
'bisnonno'
'bisonte'
'bisturi'
'bizz<NAME>ro'
'bl<NAME>'
'bl<NAME>ta'
'<NAME>'
'<NAME>'
'<NAME>'
'bos<NAME>'
'botanico'
'bottino'
'bozzolo'
'braccio'
'bradipo'
'brama'
'branca'
'bravura'
'bretella'
'brevetto'
'brezza'
'briglia'
'brillante'
'brindare'
'broccolo'
'brodo'
'bronzina'
'brullo'
'bruno'
'bubbone'
'buca'
'budino'
'buffone'
'buio'
'bulbo'
'buono'
'burlone'
'burrasca'
'bussola'
'busta'
'cadetto'
'caduco'
'calamaro'
'calcolo'
'calesse'
'calibro'
'calmo'
'caloria'
'cambusa'
'camerata'
'camicia'
'cammino'
'camola'
'campale'
'canapa'
'candela'
'cane'
'canino'
'canotto'
'cantina'
'capace'
'capello'
'capitolo'
'capogiro'
'cappero'
'capra'
'capsula'
'carapace'
'carcassa'
'cardo'
'carisma'
'carovana'
'carretto'
'cartolina'
'casaccio'
'cascata'
'caserma'
'caso'
'cassone'
'castello'
'casuale'
'catasta'
'catena'
'catrame'
'cauto'
'cavillo'
'cedibile'
'cedrata'
'cefalo'
'celebre'
'cellulare'
'cena'
'cenone'
'centesimo'
'ceramica'
'cercare'
'certo'
'cerume'
'cervello'
'cesoia'
'cespo'
'ceto'
'chela'
'chiaro'
'chicca'
'chiedere'
'chimera'
'china'
'chirurgo'
'chitarra'
'ciao'
'ciclismo'
'cifrare'
'cigno'
'cilindro'
'ciottolo'
'circa'
'cirrosi'
'citrico'
'cittadino'
'ciuffo'
'civetta'
'civile'
'classico'
'clinica'
'cloro'
'cocco'
'codardo'
'codice'
'coerente'
'cognome'
'collare'
'colmato'
'colore'
'colposo'
'coltivato'
'colza'
'coma'
'cometa'
'commando'
'comodo'
'computer'
'comune'
'conciso'
'condurre'
'conferma'
'congelare'
'coniuge'
'connesso'
'conoscere'
'consumo'
'continuo'
'convegno'
'coperto'
'copione'
'coppia'
'copricapo'
'corazza'
'cordata'
'coricato'
'cornice'
'corolla'
'corpo'
'corredo'
'corsia'
'cortese'
'cosmico'
'costante'
'cottura'
'covato'
'cratere'
'cravatta'
'creato'
'credere'
'cremoso'
'crescita'
'creta'
'criceto'
'crinale'
'crisi'
'critico'
'croce'
'cronaca'
'crostata'
'cruciale'
'crusca'
'cucire'
'cuculo'
'cugino'
'cullato'
'cupola'
'curatore'
'cursore'
'curvo'
'cuscino'
'custode'
'dado'
'daino'
'dalmata'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'datato'
'<NAME>anti'
'<NAME>'
'debutto'
'decennio'
'deciso'
'declino'
'decollo'
'decreto'
'dedicato'
'definito'
'deforme'
'degno'
'delegare'
'delfino'
'delirio'
'delta'
'demenza'
'denotato'
'dentro'
'deposito'
'derapata'
'derivare'
'deroga'
'descritto'
'deserto'
'desiderio'
'desumere'
'detersivo'
'devoto'
'diametro'
'dicembre'
'diedro'
'difeso'
'diffuso'
'digerire'
'digitale'
'diluvio'
'dinamico'
'dinnanzi'
'dipinto'
'diploma'
'dipolo'
'diradare'
'dire'
'dirotto'
'dirupo'
'disagio'
'discreto'
'disfare'
'disgelo'
'disposto'
'distanza'
'disumano'
'dito'
'divano'
'divelto'
'dividere'
'divorato'
'doblone'
'docente'
'doganale'
'dogma'
'dolce'
'domato'
'domenica'
'dominare'
'dondolo'
'dono'
'dormire'
'dote'
'dottore'
'dovuto'
'dozzina'
'drago'
'druido'
'dubbio'
'dubitare'
'ducale'
'duna'
'duomo'
'duplice'
'duraturo'
'ebano'
'eccesso'
'ecco'
'eclissi'
'economia'
'edera'
'edicola'
'edile'
'editoria'
'educare'
'egemonia'
'egli'
'egoismo'
'egregio'
'elaborato'
'elargire'
'elegante'
'elencato'
'eletto'
'elevare'
'elfico'
'elica'
'elmo'
'elsa'
'eluso'
'emanato'
'emblema'
'emesso'
'emiro'
'emotivo'
'emozione'
'empirico'
'emulo'
'endemico'
'enduro'
'energia'
'enfasi'
'enoteca'
'entrare'
'enzima'
'epatite'
'epilogo'
'episodio'
'epocale'
'eppure'
'equatore'
'erario'
'erba'
'erboso'
'erede'
'eremita'
'erigere'
'ermetico'
'eroe'
'erosivo'
'errante'
'esagono'
'esame'
'esanime'
'esaudire'
'esca'
'esempio'
'esercito'
'esibito'
'esigente'
'esistere'
'esito'
'esofago'
'esortato'
'esoso'
'espanso'
'espresso'
'essenza'
'esso'
'esteso'
'estimare'
'estonia'
'estroso'
'esultare'
'etilico'
'etnico'
'etrusco'
'etto'
'euclideo'
'europa'
'evaso'
'evidenza'
'evitato'
'evoluto'
'evviva'
'fabbrica'
'faccenda'
'fachiro'
'falco'
'famiglia'
'fanale'
'fanfara'
'fango'
'fantasma'
'fare'
'farfalla'
'farinoso'
'farmaco'
'fascia'
'fastoso'
'fasullo'
'faticare'
'fato'
'favoloso'
'febbre'
'fecola'
'fede'
'fegato'
'felpa'
'feltro'
'femmina'
'fendere'
'fenomeno'
'fermento'
'ferro'
'fertile'
'fessura'
'festivo'
'fetta'
'feudo'
'fiaba'
'fiducia'
'fifa'
'figurato'
'filo'
'finanza'
'finestra'
'finire'
'fiore'
'fiscale'
'fisico'
'fiume'
'flacone'
'flamenco'
'flebo'
'flemma'
'florido'
'fluente'
'fluoro'
'fobico'
'focaccia'
'focoso'
'foderato'
'foglio'
'folata'
'folclore'
'folgore'
'fondente'
'fonetico'
'fonia'
'fontana'
'forbito'
'forchetta'
'foresta'
'formica'
'fornaio'
'foro'
'fortezza'
'forzare'
'fosfato'
'fosso'
'fracasso'
'frana'
'frassino'
'fratello'
'freccetta'
'frenata'
'fresco'
'frigo'
'frollino'
'fronde'
'frugale'
'frutta'
'fucilata'
'fucsia'
'fuggente'
'fulmine'
'fulvo'
'fumante'
'fumetto'
'fumoso'
'fune'
'funzione'
'fuoco'
'furbo'
'furgone'
'furore'
'fuso'
'futile'
'gabbiano'
'gaffe'
'galateo'
'gallina'
'galoppo'
'gambero'
'gamma'
'garanzia'
'garbo'
'garofano'
'garzone'
'gasdotto'
'gasolio'
'gastrico'
'gat<NAME>'
'gaudio'
'gazebo'
'gazzella'
'geco'
'gelatina'
'gelso'
'gemello'
'gemmato'
'gene'
'genitore'
'gen<NAME>'
'genotipo'
'ger<NAME>'
'<NAME>'
'ghi<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'giocare'
'gio<NAME>'
'giorno'
'giove'
'girato'
'girone'
'gittata'
'giudizio'
'giurato'
'giusto'
'glo<NAME>lo'
'glutine'
'gnomo'
'gobba'
'g<NAME>'
'gomito'
'gommone'
'gon<NAME>'
'gon<NAME>'
'g<NAME>'
'gracile'
'grado'
'grafico'
'grammo'
'grande'
'grattare'
'gravoso'
'grazia'
'greca'
'gregge'
'grifone'
'g<NAME>'
'grinza'
'grotta'
'gruppo'
'guadagno'
'guaio'
'guanto'
'guardare'
'gufo'
'guidare'
'ibernato'
'icona'
'<NAME>o'
'<NAME>'
'idolo'
'idra'
'idrico'
'idrogeno'
'igiene'
'ignaro'
'ignorato'
'ilare'
'illeso'
'illogico'
'illudere'
'imballo'
'imbevuto'
'imbocco'
'imbuto'
'immane'
'immerso'
'immolato'
'impacco'
'impeto'
'impiego'
'importo'
'impronta'
'inalare'
'inarcare'
'inattivo'
'incanto'
'incendio'
'inchino'
'incisivo'
'incluso'
'incontro'
'incrocio'
'incubo'
'indagine'
'india'
'indole'
'inedito'
'infatti'
'infilare'
'inflitto'
'ingaggio'
'ingegno'
'inglese'
'ingordo'
'ingrosso'
'innesco'
'inodore'
'inoltrare'
'inondato'
'insano'
'insetto'
'insieme'
'insonnia'
'insulina'
'intasato'
'intero'
'intonaco'
'intuito'
'inumidire'
'invalido'
'invece'
'invito'
'iperbole'
'ipnotico'
'ipotesi'
'ippica'
'iride'
'irlanda'
'ironico'
'irrigato'
'irrorare'
'isolato'
'isotopo'
'isterico'
'istituto'
'istrice'
'italia'
'iterare'
'labbro'
'labirinto'
'lacca'
'lacerato'
'lacrima'
'lacuna'
'laddove'
'lago'
'lampo'
'lancetta'
'lanterna'
'lardoso'
'larga'
'laringe'
'lastra'
'latenza'
'latino'
'lattuga'
'lavagna'
'lavoro'
'legale'
'leggero'
'lembo'
'lentezza'
'lenza'
'leone'
'lepre'
'lesivo'
'lessato'
'lesto'
'letterale'
'leva'
'levigato'
'libero'
'lido'
'lievito'
'lilla'
'limatura'
'limitare'
'limpido'
'lineare'
'lingua'
'liquido'
'lira'
'lirica'
'lisca'
'lite'
'litigio'
'livrea'
'locanda'
'lode'
'logica'
'lombare'
'londra'
'longevo'
'loquace'
'lorenzo'
'loto'
'lotteria'
'luce'
'lucidato'
'lumaca'
'luminoso'
'lungo'
'lupo'
'luppolo'
'lusinga'
'lusso'
'lutto'
'macabro'
'macchina'
'macero'
'macinato'
'mad<NAME>'
'magico'
'maglia'
'magnete'
'magro'
'maiolica'
'malafede'
'malgrado'
'malinteso'
'malsano'
'malto'
'malumore'
'mana'
'<NAME>'
'<NAME>'
'<NAME>'
'manifesto'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'maturo'
'mazurca'
'<NAME>'
'<NAME>an<NAME>'
'mecenate'
'medesimo'
'meditare'
'mega'
'melassa'
'melis'
'melodia'
'meninge'
'meno'
'<NAME>ola'
'<NAME>'
'<NAME>enda'
'merlo'
'meschino'
'mese'
'messere'
'mestolo'
'metallo'
'metodo'
'mettere'
'<NAME>'
'mica'
'micelio'
'michele'
'microbo'
'midollo'
'miele'
'migliore'
'milano'
'milite'
'mimosa'
'minerale'
'mini'
'minore'
'mirino'
'mirtillo'
'miscela'
'missiva'
'misto'
'misurare'
'mitezza'
'mitigare'
'mitra'
'mittente'
'mnemonico'
'modello'
'modifica'
'modulo'
'mogano'
'mogio'
'mole'
'molosso'
'monastero'
'monco'
'mondina'
'monetario'
'monile'
'monotono'
'monsone'
'montato'
'monviso'
'mora'
'mordere'
'morsicato'
'mostro'
'motivato'
'motosega'
'motto'
'movenza'
'movimento'
'mozzo'
'mucca'
'mucosa'
'muffa'
'mughetto'
'mugnaio'
'mulatto'
'mulinello'
'multiplo'
'mummia'
'munto'
'muovere'
'murale'
'musa'
'muscolo'
'musica'
'mutevole'
'muto'
'nababbo'
'nafta'
'nanometro'
'narciso'
'nar<NAME>'
'narrato'
'nascere'
'nastrare'
'naturale'
'nautica'
'naviglio'
'nebulosa'
'necrosi'
'negativo'
'negozio'
'nemmeno'
'neofita'
'neretto'
'nervo'
'nessuno'
'nettuno'
'neutrale'
'neve'
'nevrotico'
'nicchia'
'ninfa'
'nitido'
'nobile'
'nocivo'
'nodo'
'nome'
'nomina'
'nordico'
'normale'
'norvegese'
'nostrano'
'notare'
'notizia'
'notturno'
'novella'
'nucleo'
'nulla'
'numero'
'nuovo'
'nutrire'
'nuvola'
'nuziale'
'oasi'
'obbedire'
'obbligo'
'obelisco'
'oblio'
'obolo'
'obsoleto'
'occasione'
'occhio'
'occidente'
'occorrere'
'occultare'
'ocra'
'oculato'
'odierno'
'odorare'
'offerta'
'offrire'
'offuscato'
'oggetto'
'oggi'
'ognuno'
'olandese'
'olfatto'
'oliato'
'oliva'
'ologramma'
'oltre'
'omaggio'
'ombelico'
'ombra'
'omega'
'omissione'
'ondoso'
'onere'
'onice'
'onnivoro'
'onorevole'
'onta'
'operato'
'opinione'
'opposto'
'oracolo'
'orafo'
'ordine'
'orecchino'
'orefice'
'orfano'
'organico'
'origine'
'orizzonte'
'orma'
'ormeggio'
'ornativo'
'orologio'
'orrendo'
'orribile'
'ortensia'
'ortica'
'orzata'
'orzo'
'osare'
'oscurare'
'osmosi'
'ospedale'
'ospite'
'ossa'
'ossidare'
'ostacolo'
'oste'
'otite'
'otre'
'ottagono'
'ottimo'
'ottobre'
'ovale'
'ovest'
'ovino'
'oviparo'
'ovocito'
'ovunque'
'ovviare'
'ozio'
'pacchetto'
'pace'
'pacifico'
'padella'
'padrone'
'paese'
'paga'
'pagina'
'palazzina'
'palesare'
'pallido'
'palo'
'palude'
'pandoro'
'pannello'
'paolo'
'paonazzo'
'paprica'
'parabola'
'parcella'
'parere'
'pargolo'
'pari'
'parlato'
'parola'
'partire'
'parvenza'
'parziale'
'passivo'
'pasticca'
'patacca'
'patologia'
'pattume'
'pavone'
'peccato'
'pedalare'
'pedonale'
'peggio'
'peloso'
'penare'
'pendice'
'penisola'
'pennuto'
'penombra'
'pensare'
'pentola'
'pepe'
'pepita'
'perbene'
'percorso'
'perdonato'
'perforare'
'pergamena'
'periodo'
'permesso'
'perno'
'perplesso'
'persuaso'
'pertugio'
'pervaso'
'pesatore'
'pesista'
'peso'
'pestifero'
'petalo'
'pettine'
'petulante'
'pezzo'
'piacere'
'pianta'
'piattino'
'piccino'
'picozza'
'piega'
'pietra'
'piffero'
'pigiama'
'pigolio'
'pigro'
'pila'
'pilifero'
'pillola'
'pilota'
'pimpante'
'pineta'
'pinna'
'pinolo'
'pioggia'
'piombo'
'piramide'
'piretico'
'pirite'
'pirolisi'
'pitone'
'pizzico'
'placebo'
'planare'
'plasma'
'platano'
'plenario'
'pochezza'
'poderoso'
'podismo'
'poesia'
'poggiare'
'polenta'
'poligono'
'pollice'
'polmonite'
'polpetta'
'polso'
'poltrona'
'polvere'
'pomice'
'pomodoro'
'ponte'
'popoloso'
'porfido'
'poroso'
'porpora'
'porre'
'portata'
'posa'
'positivo'
'possesso'
'postulato'
'potassio'
'potere'
'pranzo'
'prassi'
'pratica'
'precluso'
'predica'
'prefisso'
'pregiato'
'prelievo'
'premere'
'prenotare'
'preparato'
'presenza'
'pretesto'
'prevalso'
'prima'
'principe'
'privato'
'problema'
'procura'
'produrre'
'profumo'
'progetto'
'prolunga'
'promessa'
'pronome'
'proposta'
'proroga'
'proteso'
'prova'
'prudente'
'prugna'
'prurito'
'psiche'
'pubblico'
'pudica'
'pugilato'
'pugno'
'pulce'
'pulito'
'pulsante'
'puntare'
'pupazzo'
'pupilla'
'puro'
'quadro'
'qualcosa'
'quasi'
'querela'
'quota'
'raccolto'
'raddoppio'
'radicale'
'radunato'
'raffica'
'ragazzo'
'ragione'
'ragno'
'ramarro'
'ramingo'
'ramo'
'randagio'
'rantolare'
'rapato'
'rapina'
'rappreso'
'rasatura'
'raschiato'
'rasente'
'rassegna'
'rastrello'
'rata'
'ravveduto'
'reale'
'recepire'
'recinto'
'recluta'
'recondito'
'recupero'
'reddito'
'redimere'
'regalato'
'registro'
'regola'
'regresso'
'relazione'
'remare'
'remoto'
'renna'
'replica'
'reprimere'
'reputare'
'resa'
'residente'
'responso'
'restauro'
'rete'
'retina'
'retorica'
'rettifica'
'revocato'
'riassunto'
'ribadire'
'ribelle'
'ribrezzo'
'ricarica'
'ricco'
'ricevere'
'riciclato'
'ricordo'
'ricreduto'
'ridicolo'
'ridurre'
'rifasare'
'riflesso'
'riforma'
'rifugio'
'rigare'
'rigettato'
'righello'
'rilassato'
'rilevato'
'rimanere'
'rimbalzo'
'rimedio'
'rimorchio'
'rinascita'
'rincaro'
'rinforzo'
'<NAME>'
'rinomato'
'rinsavito'
'rintocco'
'rinuncia'
'rinvenire'
'riparato'
'ripetuto'
'ripieno'
'riportare'
'ripresa'
'ripul<NAME>'
'risata'
'ris<NAME>io'
'ris<NAME>va'
'risibile'
'riso'
'rispetto'
'ristoro'
'risultato'
'risvolto'
'ritardo'
'ritegno'
'ritmico'
'ritrovo'
'riunione'
'riva'
'riverso'
'rivincita'
'rivolto'
'rizoma'
'roba'
'robotico'
'rob<NAME>'
'roccia'
'roco'
'rodaggio'
'rodere'
'roditore'
'rogito'
'rollio'
'romantico'
'rompere'
'<NAME>'
'ro<NAME>'
'rospo'
'rotante'
'rotondo'
'rotula'
'rovescio'
'rubizzo'
'rubrica'
'ruga'
'rullino'
'rumine'
'rumoroso'
'ruolo'
'rupe'
'russare'
'<NAME>'
'sabato'
'sab<NAME>'
'sabotato'
'sagoma'
'salasso'
'saldatura'
'salgemma'
'salivare'
'salmone'
'salone'
'saltare'
'saluto'
'salvo'
'sapere'
'sapido'
'saporito'
'saraceno'
'sarcasmo'
'sarto'
'sassoso'
'satellite'
'satira'
'satollo'
'saturno'
'savana'
'savio'
'saziato'
'sbadiglio'
'sbalzo'
'sbancato'
'sbarra'
'sbattere'
'sbavare'
'sbendare'
'sbirciare'
'sbloccato'
'sbocciato'
'sbrinare'
'sbruffone'
'sbuffare'
'scabroso'
'scadenza'
'scala'
'scambiare'
'scandalo'
'scapola'
'scarso'
'scatenare'
'scavato'
'scelto'
'scenico'
'scettro'
'scheda'
'schiena'
'sciarpa'
'scienza'
'scindere'
'scippo'
'sciroppo'
'scivolo'
'sclerare'
'scodella'
'scolpito'
'scomparto'
'sconforto'
'scoprire'
'scorta'
'scossone'
'scozzese'
'scriba'
'scrollare'
'scrutinio'
'scuderia'
'scultore'
'scuola'
'scuro'
'scusare'
'sdebitare'
'sdoganare'
'seccatura'
'secondo'
'sedano'
'seggiola'
'segnalato'
'segregato'
'seguito'
'selciato'
'selettivo'
'sella'
'selvaggio'
'semaforo'
'sembrare'
'seme'
'seminato'
'sempre'
'senso'
'sentire'
'sepolto'
'sequenza'
'serata'
'serbato'
'sereno'
'serio'
'serpente'
'serraglio'
'servire'
'sestina'
'setola'
'settimana'
'sfacelo'
'sfaldare'
'sfamato'
'sfarzoso'
'sfaticato'
'sfera'
'sfida'
'sfilato'
'sfinge'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
's<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'sint<NAME>'
'sin<NAME>'
'<NAME>'
'<NAME>'
'sist<NAME>'
'situato'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'sod<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'sollazzo'
'solo'
'solubile'
'sol<NAME>'
'som<NAME>o'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'sorso'
'<NAME>'
'sor<NAME>ato'
'sospiro'
'sosta'
'sottile'
'spada'
'spalla'
'spargere'
'spatola'
'spavento'
'spazzola'
'specie'
'spedire'
'spegnere'
'spelatura'
'speranza'
'spessore'
'spettrale'
'spezzato'
'spia'
'spigoloso'
'spillato'
'spinoso'
'spirale'
'splendido'
'sportivo'
'sposo'
'spranga'
'sprecare'
'spronato'
'spruzzo'
'spuntino'
'squillo'
'sradicare'
'srotolato'
'stabile'
'stacco'
'staffa'
'stagnare'
'stampato'
'stantio'
'starnuto'
'stasera'
'statuto'
'stelo'
'steppa'
'sterzo'
'stiletto'
'stima'
'stirpe'
'stivale'
'stizzoso'
'stonato'
'storico'
'strappo'
'stregato'
'stridulo'
'strozzare'
'strutto'
'stuccare'
'stufo'
'stupendo'
'subentro'
'succoso'
'sudore'
'suggerito'
'sugo'
'sultano'
'suonare'
'superbo'
'supporto'
'surgelato'
'surrogato'
'sussurro'
'sutura'
'svagare'
'svedese'
'sveglio'
'svelare'
'svenuto'
'svezia'
'sviluppo'
'svista'
'svizzera'
'svolta'
'svuotare'
'tabacco'
'tabulato'
'tacciare'
'taciturno'
'tale'
'talismano'
'tampone'
'tannino'
'tara'
'tardivo'
'targato'
'tariffa'
'tarpare'
'tartaruga'
'tasto'
'tattico'
'taverna'
'tavolata'
'tazza'
'teca'
'tecnico'
'telefono'
'temerario'
'tempo'
'temuto'
'tendone'
'tenero'
'tensione'
'tentacolo'
'teorema'
'terme'
'terrazzo'
'terzetto'
'tesi'
'tesserato'
'testato'
'tetro'
'tettoia'
'tifare'
'tigella'
'timbro'
'tinto'
'tipico'
'tipografo'
'tiraggio'
'tiro'
'titanio'
'titolo'
'titubante'
'tizio'
'tizzone'
'toccare'
'tollerare'
'tolto'
'tombola'
'tomo'
'tonfo'
'tonsilla'
'topazio'
'topologia'
'toppa'
'torba'
'tornare'
'torrone'
'tortora'
'toscano'
'tossire'
'tostatura'
'totano'
'trabocco'
'trachea'
'trafila'
'tragedia'
'tralcio'
'tramonto'
'transito'
'trapano'
'trarre'
'trasloco'
'trattato'
'trave'
'treccia'
'tremolio'
'trespolo'
'tributo'
'tricheco'
'trifoglio'
'trillo'
'trincea'
'trio'
'tristezza'
'triturato'
'trivella'
'tromba'
'trono'
'troppo'
'trottola'
'trovare'
'truccato'
'tubatura'
'tuffato'
'tulipano'
'tumulto'
'tunisia'
'turbare'
'turchino'
'tuta'
'tutela'
'ubicato'
'uccello'
'uccisore'
'udire'
'uditivo'
'uffa'
'ufficio'
'uguale'
'ulisse'
'ultimato'
'umano'
'umile'
'umorismo'
'uncinetto'
'ungere'
'ungherese'
'unicorno'
'unificato'
'unisono'
'unitario'
'unte'
'uovo'
'upupa'
'uragano'
'urgenza'
'urlo'
'usanza'
'usato'
'uscito'
'usignolo'
'usuraio'
'utensile'
'utilizzo'
'utopia'
'vacante'
'vaccinato'
'vagabondo'
'vagliato'
'valanga'
'valgo'
'valico'
'valletta'
'valoroso'
'valutare'
'valvola'
'vampata'
'vangare'
'vanitoso'
'vano'
'vantaggio'
'vanvera'
'vapore'
'varano'
'varcato'
'variante'
'vasca'
'vedetta'
'vedova'
'veduto'
'vegetale'
'veicolo'
'velcro'
'velina'
'velluto'
'veloce'
'venato'
'vendemmia'
'vento'
'verace'
'verbale'
'vergogna'
'verifica'
'vero'
'verruca'
'verticale'
'vescica'
'vessillo'
'vestale'
'veterano'
'vetrina'
'vetusto'
'viandante'
'vibrante'
'vicenda'
'vichingo'
'<NAME>'
'<NAME>'
'<NAME>'
'vigneto'
'vigore'
'vile'
'<NAME>'
'<NAME>'
'vincitore'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>ul<NAME>'
'viscoso'
'visione'
'vispo'
'vissuto'
'visura'
'vita'
'vitel<NAME>'
'vittima'
'vivanda'
'vivido'
'<NAME>are'
'voce'
'voga'
'volatile'
'vol<NAME>'
'volpe'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'zen<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>to'
'<NAME>'
'<NAME>'
'<NAME>uc<NAME>'
'zufolo'
'zulu'
'zuppa'
]
`export default wordlist` | true |
wordlist = [
'abPI:NAME:<NAME>END_PI'
'abbPI:NAME:<NAME>END_PI'
'abbinato'
'abete'
'abisso'
'abolire'
'abrasivo'
'abrogato'
'accadere'
'accenno'
'accusato'
'acetone'
'achille'
'acido'
'acqua'
'acre'
'acrilico'
'acrobata'
'acuto'
'adagio'
'addebito'
'addome'
'adeguato'
'aderire'
'adipe'
'adottare'
'adulare'
'affabile'
'affetto'
'affisso'
'affranto'
'aforisma'
'afoso'
'africano'
'agave'
'agente'
'agevole'
'aggancio'
'agire'
'agitare'
'agonismo'
'agricolo'
'agrumeto'
'aguzzo'
'alabarda'
'alato'
'albatro'
'alberato'
'albo'
'albume'
'alce'
'alcolico'
'alettone'
'alfa'
'algebra'
'aliante'
'alibi'
'alimento'
'allagato'
'allegro'
'allievo'
'allodola'
'allusivo'
'almeno'
'alogeno'
'alpaca'
'alpestre'
'altalena'
'alterno'
'alticcio'
'altrove'
'alunno'
'alveolo'
'alzare'
'amalgama'
'amanita'
'amarena'
'ambito'
'ambrato'
'ameba'
'america'
'ametista'
'amico'
'ammasso'
'ammenda'
'ammirare'
'ammonito'
'amore'
'ampio'
'ampliare'
'amulePI:NAME:<NAME>END_PI'
'anacardo'
'anagrafe'
'analista'
'anarchia'
'anatra'
'anca'
'ancella'
'ancora'
'PI:NAME:<NAME>END_PI'
'andrea'
'PI:NAME:<NAME>END_PI'
'angelo'
'PI:NAME:<NAME>END_PI'
'angusto'
'anima'
'annegPI:NAME:<NAME>END_PI'
'annidato'
'anno'
'annuncio'
'anonimo'
'anticipo'
'anzi'
'apatico'
'apertura'
'apode'
'apparire'
'appetito'
'appoggio'
'approdo'
'appunto'
'aprile'
'arabica'
'arachide'
'aragosta'
'araldica'
'arancio'
'aratura'
'arazzo'
'arbitro'
'archivio'
'ardito'
'arenile'
'argento'
'argine'
'arguto'
'aria'
'armonia'
'arnese'
'arredato'
'arringa'
'arrosto'
'arsenico'
'arso'
'artefice'
'arzillo'
'asciutto'
'ascolto'
'asepsi'
'asettico'
'asfalto'
'asino'
'asola'
'aspirato'
'aspro'
'assaggio'
'asse'
'assoluto'
'assurdo'
'asta'
'astenuto'
'astice'
'astratto'
'atavico'
'ateismo'
'atomico'
'atono'
'attesa'
'attivare'
'attorno'
'attrito'
'attuale'
'ausilio'
'austria'
'autista'
'autonomo'
'autunno'
'avanzato'
'avere'
'avvenire'
'avviso'
'avvolgere'
'azione'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'azzPI:NAME:<NAME>END_PIro'
'babele'
'bacPI:NAME:<NAME>END_PIo'
'bacino'
'baco'
'badessa'
'badilata'
'bagnato'
'baita'
'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'
'barPI:NAME:<NAME>END_PI'
'barca'
'baritono'
'barlume'
'barocco'
'basilico'
'basso'
'batosta'
'battuto'
'baule'
'bava'
'bavosa'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'belPI:NAME:<NAME>END_PI'
'belva'
'benda'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'benPI:NAME:<NAME>END_PIina'
'bere'
'berlina'
'beta'
'bibita'
'bici'
'bidone'
'bifido'
'biga'
'bilPI:NAME:<NAME>END_PI'
'bimbo'
'binocolo'
'biologo'
'bipede'
'bipolare'
'birbante'
'birra'
'biscotto'
'bisesto'
'bisnonno'
'bisonte'
'bisturi'
'bizzPI:NAME:<NAME>END_PIro'
'blPI:NAME:<NAME>END_PI'
'blPI:NAME:<NAME>END_PIta'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'bosPI:NAME:<NAME>END_PI'
'botanico'
'bottino'
'bozzolo'
'braccio'
'bradipo'
'brama'
'branca'
'bravura'
'bretella'
'brevetto'
'brezza'
'briglia'
'brillante'
'brindare'
'broccolo'
'brodo'
'bronzina'
'brullo'
'bruno'
'bubbone'
'buca'
'budino'
'buffone'
'buio'
'bulbo'
'buono'
'burlone'
'burrasca'
'bussola'
'busta'
'cadetto'
'caduco'
'calamaro'
'calcolo'
'calesse'
'calibro'
'calmo'
'caloria'
'cambusa'
'camerata'
'camicia'
'cammino'
'camola'
'campale'
'canapa'
'candela'
'cane'
'canino'
'canotto'
'cantina'
'capace'
'capello'
'capitolo'
'capogiro'
'cappero'
'capra'
'capsula'
'carapace'
'carcassa'
'cardo'
'carisma'
'carovana'
'carretto'
'cartolina'
'casaccio'
'cascata'
'caserma'
'caso'
'cassone'
'castello'
'casuale'
'catasta'
'catena'
'catrame'
'cauto'
'cavillo'
'cedibile'
'cedrata'
'cefalo'
'celebre'
'cellulare'
'cena'
'cenone'
'centesimo'
'ceramica'
'cercare'
'certo'
'cerume'
'cervello'
'cesoia'
'cespo'
'ceto'
'chela'
'chiaro'
'chicca'
'chiedere'
'chimera'
'china'
'chirurgo'
'chitarra'
'ciao'
'ciclismo'
'cifrare'
'cigno'
'cilindro'
'ciottolo'
'circa'
'cirrosi'
'citrico'
'cittadino'
'ciuffo'
'civetta'
'civile'
'classico'
'clinica'
'cloro'
'cocco'
'codardo'
'codice'
'coerente'
'cognome'
'collare'
'colmato'
'colore'
'colposo'
'coltivato'
'colza'
'coma'
'cometa'
'commando'
'comodo'
'computer'
'comune'
'conciso'
'condurre'
'conferma'
'congelare'
'coniuge'
'connesso'
'conoscere'
'consumo'
'continuo'
'convegno'
'coperto'
'copione'
'coppia'
'copricapo'
'corazza'
'cordata'
'coricato'
'cornice'
'corolla'
'corpo'
'corredo'
'corsia'
'cortese'
'cosmico'
'costante'
'cottura'
'covato'
'cratere'
'cravatta'
'creato'
'credere'
'cremoso'
'crescita'
'creta'
'criceto'
'crinale'
'crisi'
'critico'
'croce'
'cronaca'
'crostata'
'cruciale'
'crusca'
'cucire'
'cuculo'
'cugino'
'cullato'
'cupola'
'curatore'
'cursore'
'curvo'
'cuscino'
'custode'
'dado'
'daino'
'dalmata'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'datato'
'PI:NAME:<NAME>END_PIanti'
'PI:NAME:<NAME>END_PI'
'debutto'
'decennio'
'deciso'
'declino'
'decollo'
'decreto'
'dedicato'
'definito'
'deforme'
'degno'
'delegare'
'delfino'
'delirio'
'delta'
'demenza'
'denotato'
'dentro'
'deposito'
'derapata'
'derivare'
'deroga'
'descritto'
'deserto'
'desiderio'
'desumere'
'detersivo'
'devoto'
'diametro'
'dicembre'
'diedro'
'difeso'
'diffuso'
'digerire'
'digitale'
'diluvio'
'dinamico'
'dinnanzi'
'dipinto'
'diploma'
'dipolo'
'diradare'
'dire'
'dirotto'
'dirupo'
'disagio'
'discreto'
'disfare'
'disgelo'
'disposto'
'distanza'
'disumano'
'dito'
'divano'
'divelto'
'dividere'
'divorato'
'doblone'
'docente'
'doganale'
'dogma'
'dolce'
'domato'
'domenica'
'dominare'
'dondolo'
'dono'
'dormire'
'dote'
'dottore'
'dovuto'
'dozzina'
'drago'
'druido'
'dubbio'
'dubitare'
'ducale'
'duna'
'duomo'
'duplice'
'duraturo'
'ebano'
'eccesso'
'ecco'
'eclissi'
'economia'
'edera'
'edicola'
'edile'
'editoria'
'educare'
'egemonia'
'egli'
'egoismo'
'egregio'
'elaborato'
'elargire'
'elegante'
'elencato'
'eletto'
'elevare'
'elfico'
'elica'
'elmo'
'elsa'
'eluso'
'emanato'
'emblema'
'emesso'
'emiro'
'emotivo'
'emozione'
'empirico'
'emulo'
'endemico'
'enduro'
'energia'
'enfasi'
'enoteca'
'entrare'
'enzima'
'epatite'
'epilogo'
'episodio'
'epocale'
'eppure'
'equatore'
'erario'
'erba'
'erboso'
'erede'
'eremita'
'erigere'
'ermetico'
'eroe'
'erosivo'
'errante'
'esagono'
'esame'
'esanime'
'esaudire'
'esca'
'esempio'
'esercito'
'esibito'
'esigente'
'esistere'
'esito'
'esofago'
'esortato'
'esoso'
'espanso'
'espresso'
'essenza'
'esso'
'esteso'
'estimare'
'estonia'
'estroso'
'esultare'
'etilico'
'etnico'
'etrusco'
'etto'
'euclideo'
'europa'
'evaso'
'evidenza'
'evitato'
'evoluto'
'evviva'
'fabbrica'
'faccenda'
'fachiro'
'falco'
'famiglia'
'fanale'
'fanfara'
'fango'
'fantasma'
'fare'
'farfalla'
'farinoso'
'farmaco'
'fascia'
'fastoso'
'fasullo'
'faticare'
'fato'
'favoloso'
'febbre'
'fecola'
'fede'
'fegato'
'felpa'
'feltro'
'femmina'
'fendere'
'fenomeno'
'fermento'
'ferro'
'fertile'
'fessura'
'festivo'
'fetta'
'feudo'
'fiaba'
'fiducia'
'fifa'
'figurato'
'filo'
'finanza'
'finestra'
'finire'
'fiore'
'fiscale'
'fisico'
'fiume'
'flacone'
'flamenco'
'flebo'
'flemma'
'florido'
'fluente'
'fluoro'
'fobico'
'focaccia'
'focoso'
'foderato'
'foglio'
'folata'
'folclore'
'folgore'
'fondente'
'fonetico'
'fonia'
'fontana'
'forbito'
'forchetta'
'foresta'
'formica'
'fornaio'
'foro'
'fortezza'
'forzare'
'fosfato'
'fosso'
'fracasso'
'frana'
'frassino'
'fratello'
'freccetta'
'frenata'
'fresco'
'frigo'
'frollino'
'fronde'
'frugale'
'frutta'
'fucilata'
'fucsia'
'fuggente'
'fulmine'
'fulvo'
'fumante'
'fumetto'
'fumoso'
'fune'
'funzione'
'fuoco'
'furbo'
'furgone'
'furore'
'fuso'
'futile'
'gabbiano'
'gaffe'
'galateo'
'gallina'
'galoppo'
'gambero'
'gamma'
'garanzia'
'garbo'
'garofano'
'garzone'
'gasdotto'
'gasolio'
'gastrico'
'gatPI:NAME:<NAME>END_PI'
'gaudio'
'gazebo'
'gazzella'
'geco'
'gelatina'
'gelso'
'gemello'
'gemmato'
'gene'
'genitore'
'genPI:NAME:<NAME>END_PI'
'genotipo'
'gerPI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'ghiPI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'giocare'
'gioPI:NAME:<NAME>END_PI'
'giorno'
'giove'
'girato'
'girone'
'gittata'
'giudizio'
'giurato'
'giusto'
'gloPI:NAME:<NAME>END_PIlo'
'glutine'
'gnomo'
'gobba'
'gPI:NAME:<NAME>END_PI'
'gomito'
'gommone'
'gonPI:NAME:<NAME>END_PI'
'gonPI:NAME:<NAME>END_PI'
'gPI:NAME:<NAME>END_PI'
'gracile'
'grado'
'grafico'
'grammo'
'grande'
'grattare'
'gravoso'
'grazia'
'greca'
'gregge'
'grifone'
'gPI:NAME:<NAME>END_PI'
'grinza'
'grotta'
'gruppo'
'guadagno'
'guaio'
'guanto'
'guardare'
'gufo'
'guidare'
'ibernato'
'icona'
'PI:NAME:<NAME>END_PIo'
'PI:NAME:<NAME>END_PI'
'idolo'
'idra'
'idrico'
'idrogeno'
'igiene'
'ignaro'
'ignorato'
'ilare'
'illeso'
'illogico'
'illudere'
'imballo'
'imbevuto'
'imbocco'
'imbuto'
'immane'
'immerso'
'immolato'
'impacco'
'impeto'
'impiego'
'importo'
'impronta'
'inalare'
'inarcare'
'inattivo'
'incanto'
'incendio'
'inchino'
'incisivo'
'incluso'
'incontro'
'incrocio'
'incubo'
'indagine'
'india'
'indole'
'inedito'
'infatti'
'infilare'
'inflitto'
'ingaggio'
'ingegno'
'inglese'
'ingordo'
'ingrosso'
'innesco'
'inodore'
'inoltrare'
'inondato'
'insano'
'insetto'
'insieme'
'insonnia'
'insulina'
'intasato'
'intero'
'intonaco'
'intuito'
'inumidire'
'invalido'
'invece'
'invito'
'iperbole'
'ipnotico'
'ipotesi'
'ippica'
'iride'
'irlanda'
'ironico'
'irrigato'
'irrorare'
'isolato'
'isotopo'
'isterico'
'istituto'
'istrice'
'italia'
'iterare'
'labbro'
'labirinto'
'lacca'
'lacerato'
'lacrima'
'lacuna'
'laddove'
'lago'
'lampo'
'lancetta'
'lanterna'
'lardoso'
'larga'
'laringe'
'lastra'
'latenza'
'latino'
'lattuga'
'lavagna'
'lavoro'
'legale'
'leggero'
'lembo'
'lentezza'
'lenza'
'leone'
'lepre'
'lesivo'
'lessato'
'lesto'
'letterale'
'leva'
'levigato'
'libero'
'lido'
'lievito'
'lilla'
'limatura'
'limitare'
'limpido'
'lineare'
'lingua'
'liquido'
'lira'
'lirica'
'lisca'
'lite'
'litigio'
'livrea'
'locanda'
'lode'
'logica'
'lombare'
'londra'
'longevo'
'loquace'
'lorenzo'
'loto'
'lotteria'
'luce'
'lucidato'
'lumaca'
'luminoso'
'lungo'
'lupo'
'luppolo'
'lusinga'
'lusso'
'lutto'
'macabro'
'macchina'
'macero'
'macinato'
'madPI:NAME:<NAME>END_PI'
'magico'
'maglia'
'magnete'
'magro'
'maiolica'
'malafede'
'malgrado'
'malinteso'
'malsano'
'malto'
'malumore'
'mana'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'manifesto'
'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'
'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'
'maturo'
'mazurca'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PIanPI:NAME:<NAME>END_PI'
'mecenate'
'medesimo'
'meditare'
'mega'
'melassa'
'melis'
'melodia'
'meninge'
'meno'
'PI:NAME:<NAME>END_PIola'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PIenda'
'merlo'
'meschino'
'mese'
'messere'
'mestolo'
'metallo'
'metodo'
'mettere'
'PI:NAME:<NAME>END_PI'
'mica'
'micelio'
'michele'
'microbo'
'midollo'
'miele'
'migliore'
'milano'
'milite'
'mimosa'
'minerale'
'mini'
'minore'
'mirino'
'mirtillo'
'miscela'
'missiva'
'misto'
'misurare'
'mitezza'
'mitigare'
'mitra'
'mittente'
'mnemonico'
'modello'
'modifica'
'modulo'
'mogano'
'mogio'
'mole'
'molosso'
'monastero'
'monco'
'mondina'
'monetario'
'monile'
'monotono'
'monsone'
'montato'
'monviso'
'mora'
'mordere'
'morsicato'
'mostro'
'motivato'
'motosega'
'motto'
'movenza'
'movimento'
'mozzo'
'mucca'
'mucosa'
'muffa'
'mughetto'
'mugnaio'
'mulatto'
'mulinello'
'multiplo'
'mummia'
'munto'
'muovere'
'murale'
'musa'
'muscolo'
'musica'
'mutevole'
'muto'
'nababbo'
'nafta'
'nanometro'
'narciso'
'narPI:NAME:<NAME>END_PI'
'narrato'
'nascere'
'nastrare'
'naturale'
'nautica'
'naviglio'
'nebulosa'
'necrosi'
'negativo'
'negozio'
'nemmeno'
'neofita'
'neretto'
'nervo'
'nessuno'
'nettuno'
'neutrale'
'neve'
'nevrotico'
'nicchia'
'ninfa'
'nitido'
'nobile'
'nocivo'
'nodo'
'nome'
'nomina'
'nordico'
'normale'
'norvegese'
'nostrano'
'notare'
'notizia'
'notturno'
'novella'
'nucleo'
'nulla'
'numero'
'nuovo'
'nutrire'
'nuvola'
'nuziale'
'oasi'
'obbedire'
'obbligo'
'obelisco'
'oblio'
'obolo'
'obsoleto'
'occasione'
'occhio'
'occidente'
'occorrere'
'occultare'
'ocra'
'oculato'
'odierno'
'odorare'
'offerta'
'offrire'
'offuscato'
'oggetto'
'oggi'
'ognuno'
'olandese'
'olfatto'
'oliato'
'oliva'
'ologramma'
'oltre'
'omaggio'
'ombelico'
'ombra'
'omega'
'omissione'
'ondoso'
'onere'
'onice'
'onnivoro'
'onorevole'
'onta'
'operato'
'opinione'
'opposto'
'oracolo'
'orafo'
'ordine'
'orecchino'
'orefice'
'orfano'
'organico'
'origine'
'orizzonte'
'orma'
'ormeggio'
'ornativo'
'orologio'
'orrendo'
'orribile'
'ortensia'
'ortica'
'orzata'
'orzo'
'osare'
'oscurare'
'osmosi'
'ospedale'
'ospite'
'ossa'
'ossidare'
'ostacolo'
'oste'
'otite'
'otre'
'ottagono'
'ottimo'
'ottobre'
'ovale'
'ovest'
'ovino'
'oviparo'
'ovocito'
'ovunque'
'ovviare'
'ozio'
'pacchetto'
'pace'
'pacifico'
'padella'
'padrone'
'paese'
'paga'
'pagina'
'palazzina'
'palesare'
'pallido'
'palo'
'palude'
'pandoro'
'pannello'
'paolo'
'paonazzo'
'paprica'
'parabola'
'parcella'
'parere'
'pargolo'
'pari'
'parlato'
'parola'
'partire'
'parvenza'
'parziale'
'passivo'
'pasticca'
'patacca'
'patologia'
'pattume'
'pavone'
'peccato'
'pedalare'
'pedonale'
'peggio'
'peloso'
'penare'
'pendice'
'penisola'
'pennuto'
'penombra'
'pensare'
'pentola'
'pepe'
'pepita'
'perbene'
'percorso'
'perdonato'
'perforare'
'pergamena'
'periodo'
'permesso'
'perno'
'perplesso'
'persuaso'
'pertugio'
'pervaso'
'pesatore'
'pesista'
'peso'
'pestifero'
'petalo'
'pettine'
'petulante'
'pezzo'
'piacere'
'pianta'
'piattino'
'piccino'
'picozza'
'piega'
'pietra'
'piffero'
'pigiama'
'pigolio'
'pigro'
'pila'
'pilifero'
'pillola'
'pilota'
'pimpante'
'pineta'
'pinna'
'pinolo'
'pioggia'
'piombo'
'piramide'
'piretico'
'pirite'
'pirolisi'
'pitone'
'pizzico'
'placebo'
'planare'
'plasma'
'platano'
'plenario'
'pochezza'
'poderoso'
'podismo'
'poesia'
'poggiare'
'polenta'
'poligono'
'pollice'
'polmonite'
'polpetta'
'polso'
'poltrona'
'polvere'
'pomice'
'pomodoro'
'ponte'
'popoloso'
'porfido'
'poroso'
'porpora'
'porre'
'portata'
'posa'
'positivo'
'possesso'
'postulato'
'potassio'
'potere'
'pranzo'
'prassi'
'pratica'
'precluso'
'predica'
'prefisso'
'pregiato'
'prelievo'
'premere'
'prenotare'
'preparato'
'presenza'
'pretesto'
'prevalso'
'prima'
'principe'
'privato'
'problema'
'procura'
'produrre'
'profumo'
'progetto'
'prolunga'
'promessa'
'pronome'
'proposta'
'proroga'
'proteso'
'prova'
'prudente'
'prugna'
'prurito'
'psiche'
'pubblico'
'pudica'
'pugilato'
'pugno'
'pulce'
'pulito'
'pulsante'
'puntare'
'pupazzo'
'pupilla'
'puro'
'quadro'
'qualcosa'
'quasi'
'querela'
'quota'
'raccolto'
'raddoppio'
'radicale'
'radunato'
'raffica'
'ragazzo'
'ragione'
'ragno'
'ramarro'
'ramingo'
'ramo'
'randagio'
'rantolare'
'rapato'
'rapina'
'rappreso'
'rasatura'
'raschiato'
'rasente'
'rassegna'
'rastrello'
'rata'
'ravveduto'
'reale'
'recepire'
'recinto'
'recluta'
'recondito'
'recupero'
'reddito'
'redimere'
'regalato'
'registro'
'regola'
'regresso'
'relazione'
'remare'
'remoto'
'renna'
'replica'
'reprimere'
'reputare'
'resa'
'residente'
'responso'
'restauro'
'rete'
'retina'
'retorica'
'rettifica'
'revocato'
'riassunto'
'ribadire'
'ribelle'
'ribrezzo'
'ricarica'
'ricco'
'ricevere'
'riciclato'
'ricordo'
'ricreduto'
'ridicolo'
'ridurre'
'rifasare'
'riflesso'
'riforma'
'rifugio'
'rigare'
'rigettato'
'righello'
'rilassato'
'rilevato'
'rimanere'
'rimbalzo'
'rimedio'
'rimorchio'
'rinascita'
'rincaro'
'rinforzo'
'PI:NAME:<NAME>END_PI'
'rinomato'
'rinsavito'
'rintocco'
'rinuncia'
'rinvenire'
'riparato'
'ripetuto'
'ripieno'
'riportare'
'ripresa'
'ripulPI:NAME:<NAME>END_PI'
'risata'
'risPI:NAME:<NAME>END_PIio'
'risPI:NAME:<NAME>END_PIva'
'risibile'
'riso'
'rispetto'
'ristoro'
'risultato'
'risvolto'
'ritardo'
'ritegno'
'ritmico'
'ritrovo'
'riunione'
'riva'
'riverso'
'rivincita'
'rivolto'
'rizoma'
'roba'
'robotico'
'robPI:NAME:<NAME>END_PI'
'roccia'
'roco'
'rodaggio'
'rodere'
'roditore'
'rogito'
'rollio'
'romantico'
'rompere'
'PI:NAME:<NAME>END_PI'
'roPI:NAME:<NAME>END_PI'
'rospo'
'rotante'
'rotondo'
'rotula'
'rovescio'
'rubizzo'
'rubrica'
'ruga'
'rullino'
'rumine'
'rumoroso'
'ruolo'
'rupe'
'russare'
'PI:NAME:<NAME>END_PI'
'sabato'
'sabPI:NAME:<NAME>END_PI'
'sabotato'
'sagoma'
'salasso'
'saldatura'
'salgemma'
'salivare'
'salmone'
'salone'
'saltare'
'saluto'
'salvo'
'sapere'
'sapido'
'saporito'
'saraceno'
'sarcasmo'
'sarto'
'sassoso'
'satellite'
'satira'
'satollo'
'saturno'
'savana'
'savio'
'saziato'
'sbadiglio'
'sbalzo'
'sbancato'
'sbarra'
'sbattere'
'sbavare'
'sbendare'
'sbirciare'
'sbloccato'
'sbocciato'
'sbrinare'
'sbruffone'
'sbuffare'
'scabroso'
'scadenza'
'scala'
'scambiare'
'scandalo'
'scapola'
'scarso'
'scatenare'
'scavato'
'scelto'
'scenico'
'scettro'
'scheda'
'schiena'
'sciarpa'
'scienza'
'scindere'
'scippo'
'sciroppo'
'scivolo'
'sclerare'
'scodella'
'scolpito'
'scomparto'
'sconforto'
'scoprire'
'scorta'
'scossone'
'scozzese'
'scriba'
'scrollare'
'scrutinio'
'scuderia'
'scultore'
'scuola'
'scuro'
'scusare'
'sdebitare'
'sdoganare'
'seccatura'
'secondo'
'sedano'
'seggiola'
'segnalato'
'segregato'
'seguito'
'selciato'
'selettivo'
'sella'
'selvaggio'
'semaforo'
'sembrare'
'seme'
'seminato'
'sempre'
'senso'
'sentire'
'sepolto'
'sequenza'
'serata'
'serbato'
'sereno'
'serio'
'serpente'
'serraglio'
'servire'
'sestina'
'setola'
'settimana'
'sfacelo'
'sfaldare'
'sfamato'
'sfarzoso'
'sfaticato'
'sfera'
'sfida'
'sfilato'
'sfinge'
'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'
'sPI: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'
'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'
'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'
'sintPI:NAME:<NAME>END_PI'
'sinPI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'sistPI:NAME:<NAME>END_PI'
'situato'
'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'
'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'
'sodPI: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'
'sollazzo'
'solo'
'solubile'
'solPI:NAME:<NAME>END_PI'
'somPI:NAME:<NAME>END_PIo'
'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'
'PI:NAME:<NAME>END_PI'
'sorso'
'PI:NAME:<NAME>END_PI'
'sorPI:NAME:<NAME>END_PIato'
'sospiro'
'sosta'
'sottile'
'spada'
'spalla'
'spargere'
'spatola'
'spavento'
'spazzola'
'specie'
'spedire'
'spegnere'
'spelatura'
'speranza'
'spessore'
'spettrale'
'spezzato'
'spia'
'spigoloso'
'spillato'
'spinoso'
'spirale'
'splendido'
'sportivo'
'sposo'
'spranga'
'sprecare'
'spronato'
'spruzzo'
'spuntino'
'squillo'
'sradicare'
'srotolato'
'stabile'
'stacco'
'staffa'
'stagnare'
'stampato'
'stantio'
'starnuto'
'stasera'
'statuto'
'stelo'
'steppa'
'sterzo'
'stiletto'
'stima'
'stirpe'
'stivale'
'stizzoso'
'stonato'
'storico'
'strappo'
'stregato'
'stridulo'
'strozzare'
'strutto'
'stuccare'
'stufo'
'stupendo'
'subentro'
'succoso'
'sudore'
'suggerito'
'sugo'
'sultano'
'suonare'
'superbo'
'supporto'
'surgelato'
'surrogato'
'sussurro'
'sutura'
'svagare'
'svedese'
'sveglio'
'svelare'
'svenuto'
'svezia'
'sviluppo'
'svista'
'svizzera'
'svolta'
'svuotare'
'tabacco'
'tabulato'
'tacciare'
'taciturno'
'tale'
'talismano'
'tampone'
'tannino'
'tara'
'tardivo'
'targato'
'tariffa'
'tarpare'
'tartaruga'
'tasto'
'tattico'
'taverna'
'tavolata'
'tazza'
'teca'
'tecnico'
'telefono'
'temerario'
'tempo'
'temuto'
'tendone'
'tenero'
'tensione'
'tentacolo'
'teorema'
'terme'
'terrazzo'
'terzetto'
'tesi'
'tesserato'
'testato'
'tetro'
'tettoia'
'tifare'
'tigella'
'timbro'
'tinto'
'tipico'
'tipografo'
'tiraggio'
'tiro'
'titanio'
'titolo'
'titubante'
'tizio'
'tizzone'
'toccare'
'tollerare'
'tolto'
'tombola'
'tomo'
'tonfo'
'tonsilla'
'topazio'
'topologia'
'toppa'
'torba'
'tornare'
'torrone'
'tortora'
'toscano'
'tossire'
'tostatura'
'totano'
'trabocco'
'trachea'
'trafila'
'tragedia'
'tralcio'
'tramonto'
'transito'
'trapano'
'trarre'
'trasloco'
'trattato'
'trave'
'treccia'
'tremolio'
'trespolo'
'tributo'
'tricheco'
'trifoglio'
'trillo'
'trincea'
'trio'
'tristezza'
'triturato'
'trivella'
'tromba'
'trono'
'troppo'
'trottola'
'trovare'
'truccato'
'tubatura'
'tuffato'
'tulipano'
'tumulto'
'tunisia'
'turbare'
'turchino'
'tuta'
'tutela'
'ubicato'
'uccello'
'uccisore'
'udire'
'uditivo'
'uffa'
'ufficio'
'uguale'
'ulisse'
'ultimato'
'umano'
'umile'
'umorismo'
'uncinetto'
'ungere'
'ungherese'
'unicorno'
'unificato'
'unisono'
'unitario'
'unte'
'uovo'
'upupa'
'uragano'
'urgenza'
'urlo'
'usanza'
'usato'
'uscito'
'usignolo'
'usuraio'
'utensile'
'utilizzo'
'utopia'
'vacante'
'vaccinato'
'vagabondo'
'vagliato'
'valanga'
'valgo'
'valico'
'valletta'
'valoroso'
'valutare'
'valvola'
'vampata'
'vangare'
'vanitoso'
'vano'
'vantaggio'
'vanvera'
'vapore'
'varano'
'varcato'
'variante'
'vasca'
'vedetta'
'vedova'
'veduto'
'vegetale'
'veicolo'
'velcro'
'velina'
'velluto'
'veloce'
'venato'
'vendemmia'
'vento'
'verace'
'verbale'
'vergogna'
'verifica'
'vero'
'verruca'
'verticale'
'vescica'
'vessillo'
'vestale'
'veterano'
'vetrina'
'vetusto'
'viandante'
'vibrante'
'vicenda'
'vichingo'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'vigneto'
'vigore'
'vile'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'vincitore'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PIulPI:NAME:<NAME>END_PI'
'viscoso'
'visione'
'vispo'
'vissuto'
'visura'
'vita'
'vitelPI:NAME:<NAME>END_PI'
'vittima'
'vivanda'
'vivido'
'PI:NAME:<NAME>END_PIare'
'voce'
'voga'
'volatile'
'volPI:NAME:<NAME>END_PI'
'volpe'
'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'
'PI:NAME:<NAME>END_PI'
'zenPI: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_PIto'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PIucPI:NAME:<NAME>END_PI'
'zufolo'
'zulu'
'zuppa'
]
`export default wordlist` |
[
{
"context": "de options.body}\">\n <meta name=\"author\" content=\"Koding\">\n <meta name=\"robots\" content=\"#{robotsContent}",
"end": 1079,
"score": 0.7953338623046875,
"start": 1073,
"tag": "NAME",
"value": "Koding"
},
{
"context": "t\" content=\"!\">\n\n <meta itemprop=\"nam... | servers/lib/crawler/staticpages/graphmeta.coffee | ezgikaysi/koding | 1 | { uri, domains, client: { version } } = require 'koding-config-manager'
encoder = require 'htmlencode'
module.exports = (options = {}) ->
options.title ?= 'Koding | Say goodbye to your localhost and write code in the cloud.'
options.shareUrl ?= "https://#{domains.base}"
options.image ?= "#{uri.address}/a/images/logos/share_logo.png"
options.body ?= 'Koding is a cloud-based development environment complete with free VMs, IDE & sudo enabled terminal where you can learn Ruby, Go, Java, NodeJS, PHP, C, C++, Perl, Python, etc.'
options.index ?= no
robotsContent = 'noodp,noydir'
robotsContent = "#{robotsContent},noindex,nofollow" unless options.index
"""
<title>#{options.title}</title>
<meta name="keywords" content="Web IDE, Cloud VM, VM, VPS, Ruby, Node, PHP, Python, WordPress, Django, Programming, virtual machines">
<meta charset="utf-8">
<meta name="msvalidate.01" content="F56689F2116FE1CC34876D855B2A5A8A" />
<meta name="description" content="#{encoder.XSSEncode options.body}">
<meta name="author" content="Koding">
<meta name="robots" content="#{robotsContent}" />
<meta name="fragment" content="!">
<meta itemprop="name" content="Koding">
<meta itemprop="description" content="#{encoder.XSSEncode options.body}">
<meta itemprop="image" content="#{uri.address}/a/images/logos/share_logo.png">
<!-- og meta tags -->
<meta property="og:title" content="#{encoder.XSSEncode options.title}"/>
<meta property="og:type" content="website"/>
<meta property="og:url" content="#{options.shareUrl}"/>
<meta property="og:image" content="#{options.image}"/>
<meta property="og:image:secure_url" content="#{options.image}"/>
<meta property="og:description" content="#{encoder.XSSEncode options.body}"/>
<meta property="og:image:type" content="png">
<meta property="og:image:width" content="400"/>
<meta property="og:image:height" content="300"/>
<!-- twitter cards -->
<meta name="twitter:site" content="@koding"/>
<meta name="twitter:url" content="#{options.shareUrl}"/>
<meta name="twitter:title" content="#{encoder.XSSEncode options.title}"/>
<meta name="twitter:creator" content="@koding"/>
<meta name="twitter:card" content="summary"/>
<meta name="twitter:image" content="#{options.image}"/>
<meta name="twitter:description" content="#{encoder.XSSEncode options.body}"/>
<meta name="twitter:domain" content="koding.com">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Koding">
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1">
<link rel="shortcut icon" href="#{uri.address}/a/images/favicon.ico">
<link rel="fluid-icon" href="#{uri.address}/a/images/logos/fluid512.png" title="Koding">
<link rel="stylesheet" href="/a/p/p/#{version}/kd.css">
<link rel="stylesheet" href="/a/p/p/#{version}/app.css">
<link rel="stylesheet" href="/a/p/p/#{version}/activity.css">
<link rel="stylesheet" href="/a/p/p/#{version}/feeder.css">
<link rel="stylesheet" href="/a/p/p/#{version}/members.css">
<link href='https://chrome.google.com/webstore/detail/koding/fgbjpbdfegnodokpoejnbhnblcojccal' rel='chrome-webstore-item'>
"""
| 44291 | { uri, domains, client: { version } } = require 'koding-config-manager'
encoder = require 'htmlencode'
module.exports = (options = {}) ->
options.title ?= 'Koding | Say goodbye to your localhost and write code in the cloud.'
options.shareUrl ?= "https://#{domains.base}"
options.image ?= "#{uri.address}/a/images/logos/share_logo.png"
options.body ?= 'Koding is a cloud-based development environment complete with free VMs, IDE & sudo enabled terminal where you can learn Ruby, Go, Java, NodeJS, PHP, C, C++, Perl, Python, etc.'
options.index ?= no
robotsContent = 'noodp,noydir'
robotsContent = "#{robotsContent},noindex,nofollow" unless options.index
"""
<title>#{options.title}</title>
<meta name="keywords" content="Web IDE, Cloud VM, VM, VPS, Ruby, Node, PHP, Python, WordPress, Django, Programming, virtual machines">
<meta charset="utf-8">
<meta name="msvalidate.01" content="F56689F2116FE1CC34876D855B2A5A8A" />
<meta name="description" content="#{encoder.XSSEncode options.body}">
<meta name="author" content="<NAME>">
<meta name="robots" content="#{robotsContent}" />
<meta name="fragment" content="!">
<meta itemprop="name" content="<NAME>">
<meta itemprop="description" content="#{encoder.XSSEncode options.body}">
<meta itemprop="image" content="#{uri.address}/a/images/logos/share_logo.png">
<!-- og meta tags -->
<meta property="og:title" content="#{encoder.XSSEncode options.title}"/>
<meta property="og:type" content="website"/>
<meta property="og:url" content="#{options.shareUrl}"/>
<meta property="og:image" content="#{options.image}"/>
<meta property="og:image:secure_url" content="#{options.image}"/>
<meta property="og:description" content="#{encoder.XSSEncode options.body}"/>
<meta property="og:image:type" content="png">
<meta property="og:image:width" content="400"/>
<meta property="og:image:height" content="300"/>
<!-- twitter cards -->
<meta name="twitter:site" content="@koding"/>
<meta name="twitter:url" content="#{options.shareUrl}"/>
<meta name="twitter:title" content="#{encoder.XSSEncode options.title}"/>
<meta name="twitter:creator" content="@koding"/>
<meta name="twitter:card" content="summary"/>
<meta name="twitter:image" content="#{options.image}"/>
<meta name="twitter:description" content="#{encoder.XSSEncode options.body}"/>
<meta name="twitter:domain" content="koding.com">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Koding">
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1">
<link rel="shortcut icon" href="#{uri.address}/a/images/favicon.ico">
<link rel="fluid-icon" href="#{uri.address}/a/images/logos/fluid512.png" title="Koding">
<link rel="stylesheet" href="/a/p/p/#{version}/kd.css">
<link rel="stylesheet" href="/a/p/p/#{version}/app.css">
<link rel="stylesheet" href="/a/p/p/#{version}/activity.css">
<link rel="stylesheet" href="/a/p/p/#{version}/feeder.css">
<link rel="stylesheet" href="/a/p/p/#{version}/members.css">
<link href='https://chrome.google.com/webstore/detail/koding/fgbjpbdfegnodokpoejnbhnblcojccal' rel='chrome-webstore-item'>
"""
| true | { uri, domains, client: { version } } = require 'koding-config-manager'
encoder = require 'htmlencode'
module.exports = (options = {}) ->
options.title ?= 'Koding | Say goodbye to your localhost and write code in the cloud.'
options.shareUrl ?= "https://#{domains.base}"
options.image ?= "#{uri.address}/a/images/logos/share_logo.png"
options.body ?= 'Koding is a cloud-based development environment complete with free VMs, IDE & sudo enabled terminal where you can learn Ruby, Go, Java, NodeJS, PHP, C, C++, Perl, Python, etc.'
options.index ?= no
robotsContent = 'noodp,noydir'
robotsContent = "#{robotsContent},noindex,nofollow" unless options.index
"""
<title>#{options.title}</title>
<meta name="keywords" content="Web IDE, Cloud VM, VM, VPS, Ruby, Node, PHP, Python, WordPress, Django, Programming, virtual machines">
<meta charset="utf-8">
<meta name="msvalidate.01" content="F56689F2116FE1CC34876D855B2A5A8A" />
<meta name="description" content="#{encoder.XSSEncode options.body}">
<meta name="author" content="PI:NAME:<NAME>END_PI">
<meta name="robots" content="#{robotsContent}" />
<meta name="fragment" content="!">
<meta itemprop="name" content="PI:NAME:<NAME>END_PI">
<meta itemprop="description" content="#{encoder.XSSEncode options.body}">
<meta itemprop="image" content="#{uri.address}/a/images/logos/share_logo.png">
<!-- og meta tags -->
<meta property="og:title" content="#{encoder.XSSEncode options.title}"/>
<meta property="og:type" content="website"/>
<meta property="og:url" content="#{options.shareUrl}"/>
<meta property="og:image" content="#{options.image}"/>
<meta property="og:image:secure_url" content="#{options.image}"/>
<meta property="og:description" content="#{encoder.XSSEncode options.body}"/>
<meta property="og:image:type" content="png">
<meta property="og:image:width" content="400"/>
<meta property="og:image:height" content="300"/>
<!-- twitter cards -->
<meta name="twitter:site" content="@koding"/>
<meta name="twitter:url" content="#{options.shareUrl}"/>
<meta name="twitter:title" content="#{encoder.XSSEncode options.title}"/>
<meta name="twitter:creator" content="@koding"/>
<meta name="twitter:card" content="summary"/>
<meta name="twitter:image" content="#{options.image}"/>
<meta name="twitter:description" content="#{encoder.XSSEncode options.body}"/>
<meta name="twitter:domain" content="koding.com">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Koding">
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1">
<link rel="shortcut icon" href="#{uri.address}/a/images/favicon.ico">
<link rel="fluid-icon" href="#{uri.address}/a/images/logos/fluid512.png" title="Koding">
<link rel="stylesheet" href="/a/p/p/#{version}/kd.css">
<link rel="stylesheet" href="/a/p/p/#{version}/app.css">
<link rel="stylesheet" href="/a/p/p/#{version}/activity.css">
<link rel="stylesheet" href="/a/p/p/#{version}/feeder.css">
<link rel="stylesheet" href="/a/p/p/#{version}/members.css">
<link href='https://chrome.google.com/webstore/detail/koding/fgbjpbdfegnodokpoejnbhnblcojccal' rel='chrome-webstore-item'>
"""
|
[
{
"context": "LaTeX and the Terminal.\n#\n# Copyright (C) 2014, William Stein\n#\n# This program is free software: you can red",
"end": 217,
"score": 0.9998533725738525,
"start": 204,
"tag": "NAME",
"value": "William Stein"
},
{
"context": "ire('local_hub').start_server()\" | c... | .sagemathcloud/local_hub.coffee | febman/elastic-3D-model | 0 | ###############################################################################
#
# SageMathCloud: A collaborative web-based interface to Sage, IPython, LaTeX and the Terminal.
#
# Copyright (C) 2014, William Stein
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
#################################################################
#
# local_hub -- a node.js program that runs as a regular user, and
# coordinates and maintains the connections between
# the global hubs and *all* projects running as
# this particular user.
#
# The local_hub is a bit like the "screen" program for Unix, except
# that it simultaneously manages numerous sessions, since simultaneously
# doing a lot of IO-based things is what Node.JS is good at.
#
#
# NOTE: For local debugging, run this way, since it gives better stack
# traces.CodeMirrorSession: _connect to file
#
# make_coffee && echo "require('local_hub').start_server()" | coffee
#
# (c) William Stein, 2013, 2014
#
#################################################################
async = require 'async'
fs = require 'fs'
net = require 'net'
child_process = require 'child_process'
uuid = require 'node-uuid'
message = require 'message'
misc = require 'misc'
misc_node = require 'misc_node'
winston = require 'winston'
temp = require 'temp'
diffsync = require 'diffsync'
{to_json, from_json, defaults, required} = require 'misc'
json = (out) -> misc.trunc(misc.to_json(out),512)
{ensure_containing_directory_exists, abspath} = misc_node
expire_time = (ttl) -> if ttl then new Date((new Date() - 0) + ttl*1000)
# We make it an error for a client to try to edit a file larger than MAX_FILE_SIZE.
# I decided on this, because attempts to open a much larger file leads
# to disaster. Opening a 10MB file works but is a just a little slow.
MAX_FILE_SIZE = 10000000 # 10MB
check_file_size = (size) ->
if size? and size > MAX_FILE_SIZE
e = "Attempt to open large file of size #{Math.round(size/1000000)}MB; the maximum allowed size is #{Math.round(MAX_FILE_SIZE/1000000)}MB. Use vim, emacs, or pico from a terminal instead."
winston.debug(e)
return e
###
# Revision tracking misc.
###
# Save the revision_tracking info for a file to disk *at most* this frequently.
# NOTE: failing to save to disk would only mean missing a patch but should
# otherwise *NOT* corrupt the history.
REVISION_TRACKING_SAVE_INTERVAL = 45000 # 45 seconds
# Filename of revision tracking file associated to a given file
revision_tracking_path = (path) ->
s = misc.path_split(path)
return "#{s.head}/.#{s.tail}.sage-history"
# Create dmp patch that transforms the empty string to s.
### not used (so commented out), but could be useful...
patch_from_trivial = (s) ->
return [
diffs : [ [ 1, s ] ],
start1 : 0,
start2 : 0,
length1 : 0,
length2 : s.length }
]
###
#####################################################################
# Generate the "secret_token" file as
# $SAGEMATHCLOUD/data/secret_token if it does not already
# exist. All connections to all local-to-the user services that
# SageMathClouds starts must be prefixed with this key.
#####################################################################
# WARNING -- the sage_server.py program can't get these definitions from
# here, since it is not written in node; if this path changes, it has
# to be change there as well (it will use the SAGEMATHCLOUD environ
# variable though).
DATA = process.env['SAGEMATHCLOUD'] + '/data'
CONFPATH = exports.CONFPATH = abspath(DATA)
secret_token_filename = exports.secret_token_filename = "#{CONFPATH}/secret_token"
secret_token = undefined
# We use an n-character cryptographic random token, where n is given
# below. If you want to change this, changing only the following line
# should be safe.
secret_token_length = 128
init_confpath = () ->
async.series([
# Read or create the file; after this step the variable secret_token
# is set and the file exists.
(cb) ->
fs.exists secret_token_filename, (exists) ->
if exists
winston.debug("read '#{secret_token_filename}'")
fs.readFile secret_token_filename, (err, buf) ->
secret_token = buf.toString()
cb()
else
winston.debug("create '#{secret_token_filename}'")
require('crypto').randomBytes secret_token_length, (ex, buf) ->
secret_token = buf.toString('base64')
fs.writeFile(secret_token_filename, secret_token, cb)
# Ensure restrictive permissions on the secret token file.
(cb) ->
fs.chmod(secret_token_filename, 0o600, cb)
])
INFO = undefined
init_info_json = () ->
winston.debug("writing info.json")
filename = "#{process.env['SAGEMATHCLOUD']}/info.json"
v = process.env['HOME'].split('/')
project_id = v[v.length-1]
username = project_id.replace(/-/g,'')
host = require('os').networkInterfaces().eth0?[0].address
base_url = ''
port = 22
INFO =
project_id : project_id
location : {host:host, username:username, port:port, path:'.'}
base_url : base_url
fs.writeFileSync(filename, misc.to_json(INFO))
###############################################
# Console sessions
###############################################
ports = {}
get_port = (type, cb) -> # cb(err, port number)
if ports[type]?
cb(false, ports[type])
else
fs.readFile abspath("#{DATA}/#{type}_server.port"), (err, content) ->
if err
cb(err)
else
try
ports[type] = parseInt(content)
cb(false, ports[type])
catch e
cb("#{type}_server port file corrupted")
forget_port = (type) ->
if ports[type]?
delete ports[type]
# try to restart the console server and get port where it is listening
CONSOLE_SERVER_MAX_STARTUP_TIME_S = 10 # 10 seconds
_restarting_console_server = false
_restarted_console_server = 0 # time when we last restarted it
restart_console_server = (cb) -> # cb(err)
dbg = (m) -> winston.debug("restart_console_server: #{misc.to_json(m)}")
if _restarting_console_server
dbg("hit lock -- already restarting console server")
cb("already restarting console server")
return
t = new Date() - _restarted_console_server
if t <= CONSOLE_SERVER_MAX_STARTUP_TIME_S*1000
err = "restarted console server #{t}ms ago -- still waiting for it to start"
dbg(err)
cb(err)
return
_restarting_console_server = true
dbg("restarting the daemon")
dbg("killing all existing console sockets")
console_sessions.terminate_all_sessions()
port_file = abspath("#{DATA}/console_server.port")
port = undefined
async.series([
(cb) ->
dbg("remove port_file=#{port_file}")
fs.unlink port_file, (err) ->
cb() # ignore error, e.g., if file not there.
(cb) ->
dbg("restart console server")
misc_node.execute_code
command : "console_server restart"
timeout : 10
ulimit_timeout : false # very important -- so doesn't kill consoles after 10 seconds!
err_on_exit : true
bash : true
cb : cb
(cb) ->
dbg("wait a little to see if #{port_file} appears, and if so read it and return port")
f = (cb) ->
fs.exists port_file, (exists) ->
if not exists
cb(true)
else
fs.readFile port_file, (err, data) ->
if err
cb(err)
else
try
port = parseInt(data.toString())
cb()
catch error
cb('reading port corrupt')
misc.retry_until_success
f : f
max_time : 7000
cb : cb
], (err) =>
_restarting_console_server = false
_restarted_console_server = new Date()
dbg("finished trying to restart console_server")
if err
dbg("ERROR: #{err}")
cb(err, port)
)
class ConsoleSessions
constructor: () ->
@_sessions = {}
@_get_session_cbs = {}
session_exists: (session_uuid) =>
return @_sessions[session_uuid]?
terminate_session: (session_uuid, cb) =>
session = @_sessions[session_uuid]
if not session?
cb?()
else
winston.debug("terminate console session '#{session_uuid}'")
if session.status == 'running'
session.socket.end()
session.status = 'done'
cb?()
else
cb?()
terminate_all_sessions: () =>
for session_uuid, session of @_sessions[session_uuid]
try
session.socket.end()
catch e
session.status = 'done'
# Connect to (if 'running'), restart (if 'dead'), or create (if
# non-existing) the console session with mesg.session_uuid.
connect: (client_socket, mesg, cb) =>
if not mesg.session_uuid?
mesg.session_uuid = misc.uuid()
client_socket.on 'end', () =>
winston.debug("a console session client socket ended -- session_uuid=#{mesg.session_uuid}")
#client_socket.destroy()
@get_session mesg, (err, session) =>
if err
client_socket.write_mesg('json', message.error(id:mesg.id, error:err))
cb?(err)
else
client_socket.write_mesg('json', {desc:session.desc, history:session.history.toString()})
plug(client_socket, session.socket, 20000) # 20000 = max burst to client every few ms.
session.clients.push(client_socket)
cb?()
# Get or create session with given uuid.
# Can be safely called several times at once without creating multiple sessions...
get_session: (mesg, cb) =>
# TODO: must be robust against multiple clients opening same session_id at once, which
# would be likely to happen on network reconnect.
winston.debug("get_session: console session #{mesg.session_uuid}")
session = @_sessions[mesg.session_uuid]
if session? and session.status == 'running'
winston.debug("console session: done -- it's already there and working")
cb(undefined, session)
return
if not @_get_session_cbs[mesg.session_uuid]?
winston.debug("console session not yet created -- put on stack")
@_get_session_cbs[mesg.session_uuid] = [cb]
else
winston.debug("console session already being created -- just push cb onto stack and return")
@_get_session_cbs[mesg.session_uuid].push(cb)
return
port = undefined
history = undefined
async.series([
(cb) =>
if session?
history = session.history # maintain history
winston.debug("console session does not exist or is not running, so we make a new session")
session = undefined
get_port 'console', (err, _port) =>
if err
cb() # will try to restart console server in next step
else
port = _port
winston.debug("got console server port = #{port}")
cb()
(cb) =>
if port?
cb()
else
winston.debug("couldn't determine console server port; probably console server not running -- try restarting it")
restart_console_server (err, _port) =>
if err
cb(err)
else
port = _port
winston.debug("restarted console server, then got port = #{port}")
cb()
(cb) =>
# Got port -- now create the new session
@_new_session mesg, port, (err, _session) =>
if err
cb(err)
else
session = _session
if history? # we restarted session; maintain history
session.history = history
cb()
], (err) =>
# call all the callbacks that were waiting on this session.
for cb in @_get_session_cbs[mesg.session_uuid]
cb(err, session)
delete @_get_session_cbs[mesg.session_uuid]
)
_get_console_server_socket: (port, cb) =>
socket = undefined
f = (cb) =>
misc_node.connect_to_locked_socket
port : port
token : secret_token
cb : (err, _socket) =>
if err
cb(err)
else
socket = _socket
cb()
async.series([
(cb) =>
misc.retry_until_success
f : f
max_time : 5000
cb : (err) =>
cb() # ignore err on purpose -- no err sets socket
(cb) =>
if socket?
cb(); return
forget_port('console')
restart_console_server (err, _port) =>
if err
cb(err)
else
port = _port
cb()
(cb) =>
if socket?
cb(); return
misc.retry_until_success
f : f
max_time : 5000
cb : cb
], (err) =>
if err
cb(err)
else
cb(undefined, socket)
)
_new_session: (mesg, port, cb) => # cb(err, session)
winston.debug("_new_session: defined by #{json(mesg)}")
# Connect to port CONSOLE_PORT, send mesg, then hook sockets together.
@_get_console_server_socket port, (err, console_socket) =>
if err
cb("_new_session: console server failed to connect -- #{err}")
return
# Request a Console session from console_server
misc_node.enable_mesg(console_socket)
console_socket.write_mesg('json', mesg)
# Read one JSON message back, which describes the session
console_socket.once 'mesg', (type, desc) =>
if not history?
history = new Buffer(0)
# in future, history could be read from a file
# Disable JSON mesg protocol, since it isn't used further
misc_node.disable_mesg(console_socket)
session =
socket : console_socket
desc : desc
status : 'running'
clients : []
history : '' # TODO: this could come from something stored in a file
session_uuid : mesg.session_uuid
project_id : mesg.project_id
session.amount_of_data = 0
session.last_data = misc.mswalltime()
console_socket.on 'data', (data) ->
#winston.debug("receive #{data.length} of data from the pty: data='#{data.toString()}'")
# every 2 ms we reset the burst data watcher.
tm = misc.mswalltime()
if tm - session.last_data >= 2
session.amount_of_data = 0
session.last_data = tm
if session.amount_of_data > 50000
# We just got more than 50000 characters of output in <= 2 ms, so truncate it.
# I had a control-c here, but it was EVIL (and useless), so do *not* enable this.
# console_socket.write(String.fromCharCode(3))
data = '[...]'
session.history += data
session.amount_of_data += data.length
n = session.history.length
if n > 200000
session.history = session.history.slice(session.history.length - 100000)
@_sessions[mesg.session_uuid] = session
cb(undefined, session)
console_socket.on 'end', () =>
winston.debug("console session #{mesg.session_uuid} ended")
session = @_sessions[mesg.session_uuid]
if session?
session.status = 'done'
for client in session.clients
# close all of these connections
client.end()
# Return object that describes status of all Console sessions
info: (project_id) =>
obj = {}
for id, session of @_sessions
if session.project_id == project_id
obj[id] =
desc : session.desc
status : session.status
history_length : session.history.length
return obj
console_sessions = new ConsoleSessions()
###############################################
# Direct Sage socket session -- used internally in local hub, e.g., to assist CodeMirror editors...
###############################################
# Wait up to this long for the Sage server to start responding
# connection requests, after we restart it. It can
# take a while, since it pre-imports the sage library
# at startup, before forking.
SAGE_SERVER_MAX_STARTUP_TIME_S = 30 # 30 seconds
_restarting_sage_server = false
_restarted_sage_server = 0 # time when we last restarted it
exports.restart_sage_server = restart_sage_server = (cb) ->
dbg = (m) -> winston.debug("restart_sage_server: #{misc.to_json(m)}")
if _restarting_sage_server
dbg("hit lock")
cb("already restarting sage server")
return
t = new Date() - _restarted_sage_server
if t <= SAGE_SERVER_MAX_STARTUP_TIME_S*1000
err = "restarted sage server #{t}ms ago -- still waiting for it to start"
dbg(err)
cb(err)
return
_restarting_sage_server = true
dbg("restarting the daemon")
misc_node.execute_code
command : "sage_server stop; sage_server start"
timeout : 30
ulimit_timeout : false # very important -- so doesn't kill consoles after 30 seconds of cpu!
err_on_exit : true
bash : true
cb : (err) ->
_restarting_sage_server = false
_restarted_sage_server = new Date()
cb(err)
# Get a new connection to the Sage server. If the server
# isn't running, e.g., it was killed due to running out of memory,
# then attempt to restart it and try to connect.
get_sage_socket = (cb) ->
socket = undefined
try_to_connect = (cb) ->
_get_sage_socket (err, _socket) ->
if not err
socket = _socket
cb()
else
# Failed for some reason: try to restart one time, then try again.
# We do this because the Sage server can easily get killed due to out of memory conditions.
# But we don't constantly try to restart the server, since it can easily fail to start if
# there is something wrong with a local Sage install.
# Note that restarting the sage server doesn't impact currently running worksheets (they
# have their own process that isn't killed).
restart_sage_server (err) -> # won't actually try to restart if called recently.
# we ignore the returned err -- error does not matter, since we didn't connect
cb(true)
misc.retry_until_success
f : try_to_connect
start_delay : 2000
max_delay : 6000
factor : 1.5
max_time : SAGE_SERVER_MAX_STARTUP_TIME_S*1000
log : (m) -> winston.debug("get_sage_socket: #{m}")
cb : (err) ->
cb(err, socket)
_get_sage_socket = (cb) -> # cb(err, socket that is ready to use)
sage_socket = undefined
port = undefined
async.series([
(cb) =>
winston.debug("get sage server port")
get_port 'sage', (err, _port) =>
if err
cb(err); return
else
port = _port
cb()
(cb) =>
winston.debug("get and unlock socket")
misc_node.connect_to_locked_socket
port : port
token : secret_token
cb : (err, _socket) =>
if err
forget_port('sage')
winston.debug("unlock socket: _new_session: sage session denied connection: #{err}")
cb("_new_session: sage session denied connection: #{err}")
return
sage_socket = _socket
winston.debug("Successfully unlocked a sage session connection.")
cb()
(cb) =>
winston.debug("request sage session from server.")
misc_node.enable_mesg(sage_socket)
sage_socket.write_mesg('json', message.start_session(type:'sage'))
winston.debug("Waiting to read one JSON message back, which will describe the session....")
# TODO: couldn't this just hang forever :-(
sage_socket.once 'mesg', (type, desc) =>
winston.debug("Got message back from Sage server: #{json(desc)}")
sage_socket.pid = desc.pid
cb()
], (err) -> cb(err, sage_socket))
# Connect to sockets together. This is used mainly
# for the console server.
plug = (s1, s2, max_burst) -> # s1 = hub; s2 = console server
last_tm = misc.mswalltime()
last_data = ''
amount = 0
# Connect the sockets together.
s1_data = (data) ->
activity()
# record incoming activity (don't do this in other direction, since that shouldn't keep session alive)
if not s2.writable
s1.removeListener('data', s1_data)
else
s2.write(data)
s2_data = (data) ->
if not s1.writable
s2.removeListener('data', s2_data)
else
if max_burst?
tm = misc.mswalltime()
if tm - last_tm >= 20
if amount < 0 # was truncating
try
x = last_data.slice(Math.max(0, last_data.length - Math.floor(max_burst/4)))
catch e
# I don't know why the above sometimes causes an exception, but it *does* in
# Buffer.slice, which is a serious problem. Best to ignore that data.
x = ''
data = "]" + x + data
#console.log("max_burst: reset")
amount = 0
last_tm = tm
#console.log("max_burst: amount=#{amount}")
if amount >= max_burst
last_data = data
data = data.slice(0,Math.floor(max_burst/4)) + "[..."
amount = -1 # so do only once every 20ms.
setTimeout((()=>s2_data('')), 25) # write nothing in 25ms just to make sure ...] appears.
else if amount < 0
last_data += data
setTimeout((()=>s2_data('')), 25) # write nothing in 25ms just to make sure ...] appears.
else
amount += data.length
# Never push more than max_burst characters at once to hub, since that could overwhelm
s1.write(data)
s1.on('data', s1_data)
s2.on('data', s2_data)
###############################################
# Sage sessions
###############################################
## WARNING! I think this is no longer used! It was used for my first (few)
## approaches to worksheets.
class SageSessions
constructor: () ->
@_sessions = {}
session_exists: (session_uuid) =>
return @_sessions[session_uuid]?
terminate_session: (session_uuid, cb) =>
S = @_sessions[session_uuid]
if not S?
cb()
else
winston.debug("terminate sage session -- STUB!")
cb()
update_session_status: (session) =>
# Check if the process corresponding to the given session is
# *actually* running/healthy (?). Just because the socket hasn't sent
# an "end" doesn't mean anything.
try
process.kill(session.desc.pid, 0)
# process is running -- leave status as is.
catch e
# process is not running
session.status = 'done'
get_session: (uuid) =>
session = @_sessions[uuid]
if session?
@update_session_status(session)
return session
# Connect to (if 'running'), restart (if 'dead'), or create (if
# non-existing) the Sage session with mesg.session_uuid.
connect: (client_socket, mesg) =>
session = @get_session mesg.session_uuid
if session? and session.status == 'running'
winston.debug("sage sessions: connect to the running session with id #{mesg.session_uuid}")
client_socket.write_mesg('json', session.desc)
plug(client_socket, session.socket)
session.clients.push(client_socket)
else
winston.debug("make a connection to a new sage session.")
get_port 'sage', (err, port) =>
winston.debug("Got sage server port = #{port}")
if err
winston.debug("can't determine sage server port; probably sage server not running")
client_socket.write_mesg('json', message.error(id:mesg.id, error:"problem determining port of sage server."))
else
@_new_session(client_socket, mesg, port)
_new_session: (client_socket, mesg, port, retries) =>
winston.debug("_new_session: creating new sage session (retries=#{retries})")
# Connect to port, send mesg, then hook sockets together.
misc_node.connect_to_locked_socket
port : port
token : secret_token
cb : (err, sage_socket) =>
if err
winston.debug("_new_session: sage session denied connection: #{err}")
forget_port('sage')
if not retries? or retries <= 5
if not retries?
retries = 1
else
retries += 1
try_again = () =>
@_new_session(client_socket, mesg, port, retries)
setTimeout(try_again, 1000)
else
# give up.
client_socket.write_mesg('json', message.error(id:mesg.id, error:"local_hub -- Problem connecting to Sage server. -- #{err}"))
return
else
winston.debug("Successfully unlocked a sage session connection.")
winston.debug("Next, request a Sage session from sage_server.")
misc_node.enable_mesg(sage_socket)
sage_socket.write_mesg('json', message.start_session(type:'sage'))
winston.debug("Waiting to read one JSON message back, which will describe the session.")
sage_socket.once 'mesg', (type, desc) =>
winston.debug("Got message back from Sage server: #{json(desc)}")
client_socket.write_mesg('json', desc)
plug(client_socket, sage_socket)
# Finally, this socket is now connected to a sage server and ready to execute code.
@_sessions[mesg.session_uuid] =
socket : sage_socket
desc : desc
status : 'running'
clients : [client_socket]
project_id : mesg.project_id
sage_socket.on 'end', () =>
# this is *NOT* dependable, since a segfaulted process -- and sage does that -- might
# not send a FIN.
winston.debug("sage_socket: session #{mesg.session_uuid} terminated.")
session = @_sessions[mesg.session_uuid]
# TODO: should we close client_socket here?
if session?
winston.debug("sage_socket: setting status of session #{mesg.session_uuid} to terminated.")
session.status = 'done'
# Return object that describes status of all Sage sessions
info: (project_id) =>
obj = {}
for id, session of @_sessions
if session.project_id == project_id
obj[id] =
desc : session.desc
status : session.status
return obj
sage_sessions = new SageSessions()
############################################################################
#
# Differentially-Synchronized document editing sessions
#
# Here's a map YOU ARE HERE
# |
# [client]s.. ---> [hub] ---> [local hub] <--- [hub] <--- [client]s...
# |
# \|/
# [a file on disk]
#
#############################################################################
# The "live upstream content" of DiffSyncFile_client is the actual file on disk.
# # TODO: when applying diffs, we could use that the file is random access. This is not done yet!
class DiffSyncFile_server extends diffsync.DiffSync
constructor:(@cm_session, cb) ->
@path = @cm_session.path
no_master = undefined
stats_path = undefined
stats = undefined
file = undefined
async.series([
(cb) =>
fs.stat @path, (_no_master, _stats_path) =>
no_master = _no_master
stats_path = _stats_path
cb()
(cb) =>
if no_master
# create
file = @path
misc_node.ensure_containing_directory_exists @path, (err) =>
if err
cb(err)
else
fs.open file, 'w', (err, fd) =>
if err
cb(err)
else
fs.close fd, cb
else
# master exists
file = @path
stats = stats_path
cb()
(cb) =>
e = check_file_size(stats?.size)
if e
cb(e)
return
fs.readFile file, (err, data) =>
if err
cb(err); return
# NOTE: we immediately delete \r's since the client editor (Codemirror) immediately deletes them
# on editor creation; if we don't delete them, all sync attempts fail and hell is unleashed.
@init(doc:data.toString().replace(/\r/g,''), id:"file_server")
# winston.debug("got new file contents = '#{@live}'")
@_start_watching_file()
cb(err)
], (err) => cb(err, @live))
kill: () =>
if @_autosave?
clearInterval(@_autosave)
# be sure to clean this up, or -- after 11 times -- it will suddenly be impossible for
# the user to open a file without restarting their project server! (NOT GOOD)
fs.unwatchFile(@path, @_watcher)
_watcher: (event) =>
winston.debug("watch: file '#{@path}' modified.")
if not @_do_watch
winston.debug("watch: skipping read because watching is off.")
return
@_stop_watching_file()
async.series([
(cb) =>
fs.stat @path, (err, stats) =>
if err
cb(err)
else
cb(check_file_size(stats.size))
(cb) =>
fs.readFile @path, (err, data) =>
if err
cb(err)
else
@live = data.toString().replace(/\r/g,'') # NOTE: we immediately delete \r's (see above).
@cm_session.sync_filesystem(cb)
], (err) =>
if err
winston.debug("watch: file '#{@path}' error -- #{err}")
@_start_watching_file()
)
_start_watching_file: () =>
if @_do_watch?
@_do_watch = true
return
@_do_watch = true
winston.debug("watching #{@path}")
fs.watchFile(@path, @_watcher)
_stop_watching_file: () =>
@_do_watch = false
# NOTE: I tried using fs.watch as below, but *DAMN* -- even on
# Linux 12.10 -- fs.watch in Node.JS totally SUCKS. It led to
# file corruption, weird flakiness and errors, etc. fs.watchFile
# above, on the other hand, is great for my needs (which are not
# for immediate sync).
# _start_watching_file0: () =>
# winston.debug("(re)start watching...")
# if @_fs_watcher?
# @_stop_watching_file()
# try
# @_fs_watcher = fs.watch(@path, @_watcher)
# catch e
# setInterval(@_start_watching_file, 15000)
# winston.debug("WARNING: failed to start watching '#{@path}' -- will try later -- #{e}")
# _stop_watching_file0: () =>
# if @_fs_watcher?
# @_fs_watcher.close()
# delete @_fs_watcher
snapshot: (cb) => # cb(err, snapshot of live document)
cb(false, @live)
_apply_edits_to_live: (edits, cb) =>
if edits.length == 0
cb(); return
@_apply_edits edits, @live, (err, result) =>
if err
cb(err)
else
if result == @live
cb() # nothing to do
else
@live = result
@write_to_disk(cb)
write_to_disk: (cb) =>
@_stop_watching_file()
ensure_containing_directory_exists @path, (err) =>
if err
cb?(err); return
fs.writeFile @path, @live, (err) =>
@_start_watching_file()
cb?(err)
# The live content of DiffSyncFile_client is our in-memory buffer.
class DiffSyncFile_client extends diffsync.DiffSync
constructor:(@server) ->
super(doc:@server.live, id:"file_client")
# Connect the two together
@connect(@server)
@server.connect(@)
# The CodeMirrorDiffSyncHub class represents a downstream
# remote client for this local hub. There may be dozens of these.
# The local hub has no upstream server, except the on-disk file itself.
#
# NOTE: These have *nothing* a priori to do with CodeMirror -- the name is
# historical and should be changed. TODO.
#
class CodeMirrorDiffSyncHub
constructor : (@socket, @session_uuid, @client_id) ->
write_mesg: (event, obj) =>
if not obj?
obj = {}
obj.session_uuid = @session_uuid
mesg = message['codemirror_' + event](obj)
mesg.client_id = @client_id
@socket.write_mesg 'json', mesg
recv_edits : (edit_stack, last_version_ack, cb) =>
@write_mesg 'diffsync',
id : @current_mesg_id
edit_stack : edit_stack
last_version_ack : last_version_ack
cb?()
sync_ready: () =>
@write_mesg('diffsync_ready')
class CodeMirrorSession
constructor: (mesg, cb) ->
@path = mesg.path
@session_uuid = mesg.session_uuid
@_sage_output_cb = {}
@_sage_output_to_input_id = {}
# The downstream clients of this local hub -- these are global hubs that proxy requests on to browser clients
@diffsync_clients = {}
async.series([
(cb) =>
# if File doesn't exist, try to create it.
fs.exists @path, (exists) =>
if exists
cb()
else
fs.open @path,'w', (err, fd) =>
if err
cb(err)
else
fs.close(fd, cb)
(cb) =>
if @path.indexOf('.snapshots/') != -1
@readonly = true
cb()
else
misc_node.is_file_readonly
path : @path
cb : (err, readonly) =>
@readonly = readonly
cb(err)
(cb) =>
# If this is a non-readonly sagews file, create corresponding sage session.
if not @readonly and misc.filename_extension_notilde(@path) == 'sagews'
@process_new_content = @sage_update
@sage_socket(cb)
else
cb()
(cb) =>
# The *actual* file on disk. It's important to create this
# after successfully getting the sage socket, since if we fail to
# get the sage socket we end up creating too many fs.watch's on this file...
@diffsync_fileserver = new DiffSyncFile_server @, (err, content) =>
if err
cb(err); return
@content = content
@diffsync_fileclient = new DiffSyncFile_client(@diffsync_fileserver)
# worksheet freshly loaded from disk -- now ensure no cells appear to be running
# except for the auto cells that we spin up running.
@sage_update(kill:true, auto:true)
@_set_content_and_sync()
cb()
], (err) => cb?(err, @))
##############################
# Sage execution related code
##############################
sage_socket: (cb) => # cb(err, socket)
if @_sage_socket?
try
process.kill(@_sage_socket.pid, 0)
# process is still running fine
cb(false, @_sage_socket)
return
catch e
# sage process is dead.
@_sage_socket = undefined
winston.debug("sage_socket: initalize the newly started sage process")
# If we've already loaded the worksheet, then ensure
# that no cells appear to be running. This is important
# because the worksheet file that we just loaded could have had some
# markup that cells are running.
if @diffsync_fileclient?
@sage_update(kill:true)
# Connect to the local Sage server.
get_sage_socket (err, socket) =>
if err
winston.debug("sage_socket: fail -- #{err}.")
cb(err)
else
winston.debug("sage_socket: successfully opened a Sage session for worksheet '#{@path}'")
@_sage_socket = socket
# Set path to be the same as the file.
mesg = message.execute_code
id : misc.uuid()
code : "os.chdir(salvus.data['path']);__file__=salvus.data['file']"
data : {path: misc.path_split(@path).head, file:abspath(@path)}
preparse : false
socket.write_mesg('json', mesg)
socket.on 'end', () =>
@_sage_socket = undefined
winston.debug("codemirror session #{@session_uuid} sage socket terminated.")
socket.on 'mesg', (type, mesg) =>
#winston.debug("sage session: received message #{type}, #{misc.to_json(mesg)}")
switch type
when 'blob'
sha1 = mesg.uuid
if @diffsync_clients.length == 0
error = 'no global hubs are connected to the local hub, so nowhere to send file'
winston.debug("codemirror session: got blob from sage session -- #{error}")
resp = message.save_blob
error : error
sha1 : sha1
socket.write_mesg('json', resp)
else
winston.debug("codemirror session: got blob from sage session -- forwarding to a random hub")
hub = misc.random_choice_from_obj(@diffsync_clients)
client_id = hub[0]; ds_client = hub[1]
mesg.client_id = client_id
ds_client.remote.socket.write_mesg('blob', mesg)
receive_save_blob_message
sha1 : sha1
cb : (resp) -> socket.write_mesg('json', resp)
## DEBUG -- for testing purposes -- simulate the response message
## handle_save_blob_message(message.save_blob(sha1:sha1,ttl:1000))
when 'json'
# First check for callbacks (e.g., used in interact and things where the
# browser directly asks to evaluate code in this session).
c = @_sage_output_cb[mesg.id]
if c?
c(mesg)
if mesg.done
delete @_sage_output_cb[mesg.id]
return
# Handle code execution in browser messages
if mesg.event == 'execute_javascript'
# winston.debug("got execute_javascript message from sage session #{json(mesg)}")
# Wrap and forward it on as a broadcast message.
mesg.session_uuid = @session_uuid
bcast = message.codemirror_bcast
session_uuid : @session_uuid
mesg : mesg
@client_bcast(undefined, bcast)
return
# Finally, handle output messages
m = {}
for x, y of mesg
if x != 'id' and x != 'event' # the event is always "output"
if x == 'done' # don't bother with done=false
if y
m[x] = y
else
m[x] = y
#winston.debug("sage --> local_hub: '#{json(mesg)}'")
before = @content
@sage_output_mesg(mesg.id, m)
if before != @content
@_set_content_and_sync()
# If we've already loaded the worksheet, submit all auto cells to be evaluated.
if @diffsync_fileclient?
@sage_update(auto:true)
cb(false, @_sage_socket)
_set_content_and_sync: () =>
if @set_content(@content)
# Content actually changed, so suggest to all connected clients to sync.
for id, ds_client of @diffsync_clients
ds_client.remote.sync_ready()
sage_execute_cell: (id) =>
winston.debug("exec request for cell with id: '#{id}'")
@sage_remove_cell_flag(id, diffsync.FLAGS.execute)
{code, output_id} = @sage_initialize_cell_for_execute(id)
winston.debug("exec code '#{code}'; output id='#{output_id}'")
#if diffsync.FLAGS.auto in @sage_get_cell_flagstring(id) and 'auto' not in code
#@sage_remove_cell_flag(id, diffsync.FLAGS.auto)
@set_content(@content)
if code != ""
@_sage_output_to_input_id[output_id] = id
winston.debug("start running -- #{id}")
# Change the cell to "running" mode - this doesn't generate output, so we must explicit force clients
# to sync.
@sage_set_cell_flag(id, diffsync.FLAGS.running)
@sage_set_cell_flag(id, diffsync.FLAGS.this_session)
@_set_content_and_sync()
@sage_socket (err, socket) =>
if err
winston.debug("Error getting sage socket: #{err}")
@sage_output_mesg(output_id, {stderr: "Error getting sage socket (unable to execute code): #{err}"})
@sage_remove_cell_flag(id, diffsync.FLAGS.running)
return
winston.debug("Sending execute message to sage socket.")
socket.write_mesg 'json',
message.execute_code
id : output_id
cell_id : id # extra info -- which cell is running
code : code
preparse : true
# Execute code in the Sage session associated to this sync'd editor session
sage_execute_code: (client_socket, mesg) =>
#winston.debug("sage_execute_code '#{misc.to_json(mesg)}")
client_id = mesg.client_id
@_sage_output_cb[mesg.id] = (resp) =>
resp.client_id = client_id
#winston.debug("sage_execute_code -- got output: #{misc.to_json(resp)}")
client_socket.write_mesg('json', resp)
@sage_socket (err, socket) =>
#winston.debug("sage_execute_code: #{misc.to_json(err)}, #{socket}")
if err
#winston.debug("Error getting sage socket: #{err}")
resp = message.output(stderr: "Error getting sage socket (unable to execute code): #{err}", done:true)
client_socket.write_mesg('json', resp)
else
#winston.debug("sage_execute_code: writing request message -- #{misc.to_json(mesg)}")
mesg.event = 'execute_code' # event that sage session understands
socket.write_mesg('json', mesg)
sage_raw_input: (client_socket, mesg) =>
winston.debug("sage_raw_input '#{misc.to_json(mesg)}")
@sage_socket (err, socket) =>
if err
winston.debug("sage_raw_input: error getting sage socket -- #{err}")
else
socket.write_mesg('json', mesg)
sage_call: (opts) =>
opts = defaults opts,
mesg : required
cb : undefined
f = (resp) =>
opts.cb?(false, resp)
delete @_sage_output_cb[opts.mesg.id] # exactly one response
@sage_socket (err, socket) =>
if err
opts.cb?("error getting sage socket -- #{err}")
else
@_sage_output_cb[opts.mesg.id] = f
socket.write_mesg('json', opts.mesg)
sage_introspect:(client_socket, mesg) =>
mesg.event = 'introspect' # event that sage session understand
@sage_call
mesg : mesg
cb : (err, resp) =>
if err
resp = message.error(error:"Error getting sage socket (unable to introspect): #{err}")
client_socket.write_mesg('json', resp)
else
client_socket.write_mesg('json', resp)
send_signal_to_sage_session: (client_socket, mesg) =>
if @_sage_socket?
process_kill(@_sage_socket.pid, mesg.signal)
if mesg.id? and client_socket?
client_socket.write_mesg('json', message.signal_sent(id:mesg.id))
sage_update: (opts={}) =>
opts = defaults opts,
kill : false # if true, remove all running flags and all this_session flags
auto : false # if true, run all cells that have the auto flag set
if not @content? # document not initialized
return
# Here we:
# - scan the string @content for execution requests.
# - also, if we see a cell UUID that we've seen already, we randomly generate
# a new cell UUID; clients can annoyingly generate non-unique UUID's (e.g., via
# cut and paste) so we fix that.
winston.debug("sage_update")#: opts=#{misc.to_json(opts)}")
i = 0
prev_ids = {}
z = 0
while true
z += 1
if z > 5000
winston.debug("sage_update: ERROR -- hit a possible infinite loop; opts=#{misc.to_json(opts)}")
break
i = @content.indexOf(diffsync.MARKERS.cell, i)
if i == -1
break
j = @content.indexOf(diffsync.MARKERS.cell, i+1)
if j == -1
break # corrupt and is the last one, so not a problem.
id = @content.slice(i+1,i+37)
if misc.is_valid_uuid_string(id)
# if id isn't valid -- due to document corruption or a bug, just skip it rather than get into all kinds of trouble.
# TODO: repair.
if prev_ids[id]?
# oops, repeated "unique" id, so fix it.
id = uuid.v4()
@content = @content.slice(0,i+1) + id + @content.slice(i+37)
# Also, if 'r' in the flags for this cell, remove it since it
# can't possibly be already running (given the repeat).
flags = @content.slice(i+37, j)
if diffsync.FLAGS.running in flags
new_flags = ''
for t in flags
if t != diffsync.FLAGS.running
new_flags += t
@content = @content.slice(0,i+37) + new_flags + @content.slice(j)
prev_ids[id] = true
flags = @content.slice(i+37, j)
if opts.kill or opts.auto
if opts.kill
# worksheet process just killed, so clear certain flags.
new_flags = ''
for t in flags
if t != diffsync.FLAGS.running and t != diffsync.FLAGS.this_session
new_flags += t
#winston.debug("sage_update: kill=true, so changing flags from '#{flags}' to '#{new_flags}'")
if flags != new_flags
@content = @content.slice(0,i+37) + new_flags + @content.slice(j)
if opts.auto and diffsync.FLAGS.auto in flags
# worksheet process being restarted, so run auto cells
@sage_remove_cell_flag(id, diffsync.FLAGS.auto)
@sage_execute_cell(id)
else if diffsync.FLAGS.execute in flags
# normal execute
@sage_execute_cell(id)
# set i to next position after end of line that contained flag we just considered;
# above code may have added flags to this line (but won't have added anything before this line).
i = @content.indexOf('\n',j + 1)
if i == -1
break
sage_output_mesg: (output_id, mesg) =>
cell_id = @_sage_output_to_input_id[output_id]
#winston.debug("output_id=#{output_id}; cell_id=#{cell_id}; map=#{misc.to_json(@_sage_output_to_input_id)}")
if mesg.hide?
# Hide a single component (also, do not record the message itself in the
# document, just its impact).
flag = undefined
if mesg.hide == 'input'
flag = diffsync.FLAGS.hide_input
else if mesg.hide == 'output'
flag = diffsync.FLAGS.hide_output
if flag?
@sage_set_cell_flag(cell_id, flag)
else
winston.debug("invalid hide component: '#{mesg.hide}'")
delete mesg.hide
if mesg.show?
# Show a single component of cell.
flag = undefined
if mesg.show == 'input'
flag = diffsync.FLAGS.hide_input
else if mesg.show == 'output'
flag = diffsync.FLAGS.hide_output
if flag?
@sage_remove_cell_flag(cell_id, flag)
else
winston.debug("invalid hide component: '#{mesg.hide}'")
delete mesg.show
if mesg.auto?
# set or unset whether or not cell is automatically executed on startup of worksheet
if mesg.auto
@sage_set_cell_flag(cell_id, diffsync.FLAGS.auto)
else
@sage_remove_cell_flag(cell_id, diffsync.FLAGS.auto)
if mesg.done? and mesg.done and cell_id?
@sage_remove_cell_flag(cell_id, diffsync.FLAGS.running)
delete @_sage_output_to_input_id[output_id]
delete mesg.done # not needed
if /^\s\s*/.test(mesg.stdout) # final whitespace not needed for proper display
delete mesg.stdout
if /^\s\s*/.test(mesg.stderr)
delete mesg.stderr
if misc.is_empty_object(mesg)
return
if mesg.once? and mesg.once
# only javascript is define once=True
if mesg.javascript?
msg = message.execute_javascript
session_uuid : @session_uuid
code : mesg.javascript.code
coffeescript : mesg.javascript.coffeescript
obj : mesg.obj
cell_id : cell_id
bcast = message.codemirror_bcast
session_uuid : @session_uuid
mesg : msg
@client_bcast(undefined, bcast)
return # once = do *not* want to record this message in the output stream.
i = @content.indexOf(diffsync.MARKERS.output + output_id)
if i == -1
# no such output cell anymore -- ignore (?) -- or we could make such a cell...?
winston.debug("WORKSHEET: no such output cell (ignoring) -- #{output_id}")
return
n = @content.indexOf('\n', i)
if n == -1
winston.debug("WORKSHEET: output cell corrupted (ignoring) -- #{output_id}")
return
if mesg.clear?
# delete all output server side
k = i + (diffsync.MARKERS.output + output_id).length + 1
@content = @content.slice(0, k) + @content.slice(n)
return
if mesg.delete_last?
k = @content.lastIndexOf(diffsync.MARKERS.output, n-2)
@content = @content.slice(0, k+1) + @content.slice(n)
return
@content = @content.slice(0,n) + JSON.stringify(mesg) + diffsync.MARKERS.output + @content.slice(n)
sage_find_cell_meta: (id, start) =>
i = @content.indexOf(diffsync.MARKERS.cell + id, start)
j = @content.indexOf(diffsync.MARKERS.cell, i+1)
if j == -1
return undefined
return {start:i, end:j}
sage_get_cell_flagstring: (id) =>
pos = @sage_find_cell_meta(id)
return @content.slice(pos.start+37, pos.end)
sage_set_cell_flagstring: (id, flags) =>
pos = @sage_find_cell_meta(id)
if pos?
@content = @content.slice(0, pos.start+37) + flags + @content.slice(pos.end)
sage_set_cell_flag: (id, flag) =>
s = @sage_get_cell_flagstring(id)
if flag not in s
@sage_set_cell_flagstring(id, flag + s)
sage_remove_cell_flag: (id, flag) =>
s = @sage_get_cell_flagstring(id)
if flag in s
s = s.replace(new RegExp(flag, "g"), "")
@sage_set_cell_flagstring(id, s)
sage_initialize_cell_for_execute: (id, start) => # start is optional, but can speed finding cell
# Initialize the line of the document for output for the cell with given id.
# We do this by finding where that cell starts, then searching for the start
# of the next cell, deleting any output lines in between, and placing one new line
# for output. This function returns
# - output_id: a newly created id that identifies the new output line.
# - code: the string of code that will be executed by Sage.
# Or, it returns undefined if there is no cell with this id.
cell_start = @content.indexOf(diffsync.MARKERS.cell + id, start)
if cell_start == -1
# there is now no cell with this id.
return
code_start = @content.indexOf(diffsync.MARKERS.cell, cell_start+1)
if code_start == -1
# TODO: cell is mangled: would need to fix...?
return
newline = @content.indexOf('\n', cell_start) # next newline after cell_start
next_cell = @content.indexOf(diffsync.MARKERS.cell, code_start+1)
if newline == -1
# At end of document: append a newline to end of document; this is where the output will go.
# This is a very common special case; it's what we would get typing "2+2[shift-enter]"
# into a blank worksheet.
output_start = @content.length # position where the output will start
# Put some extra newlines in, since it is hard to put input at the bottom of the screen.
@content += '\n\n\n\n\n'
winston.debug("Add a new input cell at the very end (which will be after the output).")
else
while true
next_cell_start = @content.indexOf(diffsync.MARKERS.cell, newline)
if next_cell_start == -1
# This is the last cell, so we end the cell after the last line with no whitespace.
next_cell_start = @content.search(/\s+$/)
if next_cell_start == -1
next_cell_start = @content.length+1
@content += '\n\n\n\n\n'
else
while next_cell_start < @content.length and @content[next_cell_start]!='\n'
next_cell_start += 1
if @content[next_cell_start]!='\n'
@content += '\n\n\n\n\n'
next_cell_start += 1
output = @content.indexOf(diffsync.MARKERS.output, newline)
if output == -1 or output > next_cell_start
# no more output lines to delete
output_start = next_cell_start # this is where the output line will start
break
else
# delete the line of output we just found
output_end = @content.indexOf('\n', output+1)
@content = @content.slice(0, output) + @content.slice(output_end+1)
code = @content.slice(code_start+1, output_start)
output_id = uuid.v4()
if output_start > 0 and @content[output_start-1] != '\n'
output_insert = '\n'
else
output_insert = ''
output_insert += diffsync.MARKERS.output + output_id + diffsync.MARKERS.output + '\n'
if next_cell == -1
# There is no next cell.
output_insert += diffsync.MARKERS.cell + uuid.v4() + diffsync.MARKERS.cell + '\n'
@content = @content.slice(0, output_start) + output_insert + @content.slice(output_start)
return {code:code.trim(), output_id:output_id}
##############################
kill: () =>
# Put any cleanup here...
winston.debug("Killing session #{@session_uuid}")
@sync_filesystem () =>
@diffsync_fileserver.kill()
# TODO: Are any of these deletes needed? I don't know.
delete @content
delete @diffsync_fileclient
delete @diffsync_fileserver
if @_sage_socket?
# send FIN packet so that Sage process may terminate naturally
@_sage_socket.end()
# ... then, brutally kill it if need be (a few seconds later). :-)
if @_sage_socket.pid?
setTimeout( (() => process_kill(@_sage_socket.pid, 9)), 3000 )
set_content: (value) =>
@is_active = true
changed = false
if @content != value
@content = value
changed = true
if @diffsync_fileclient.live != value
@diffsync_fileclient.live = value
changed = true
for id, ds_client of @diffsync_clients
if ds_client.live != value
changed = true
ds_client.live = value
return changed
client_bcast: (socket, mesg) =>
@is_active = true
winston.debug("client_bcast: #{json(mesg)}")
# Forward this message on to all global hubs except the
# one that just sent it to us...
client_id = mesg.client_id
for id, ds_client of @diffsync_clients
if client_id != id
mesg.client_id = id
#winston.debug("BROADCAST: sending message from hub with socket.id=#{socket?.id} to hub with socket.id = #{id}")
ds_client.remote.socket.write_mesg('json', mesg)
client_diffsync: (socket, mesg) =>
@is_active = true
write_mesg = (event, obj) ->
if not obj?
obj = {}
obj.id = mesg.id
socket.write_mesg 'json', message[event](obj)
# Message from some client reporting new edits, thus initiating a sync.
ds_client = @diffsync_clients[mesg.client_id]
if not ds_client?
write_mesg('error', {error:"client #{mesg.client_id} not registered for synchronization"})
return
if @_client_sync_lock # or Math.random() <= .5 # (for testing)
winston.debug("client_diffsync hit a click_sync_lock -- send retry message back")
write_mesg('error', {error:"retry"})
return
if @_filesystem_sync_lock
if @_filesystem_sync_lock < new Date()
@_filesystem_sync_lock = false
else
winston.debug("client_diffsync hit a filesystem_sync_lock -- send retry message back")
write_mesg('error', {error:"retry"})
return
@_client_sync_lock = true
before = @content
ds_client.recv_edits mesg.edit_stack, mesg.last_version_ack, (err) => # TODO: why is this err ignored?
@set_content(ds_client.live)
@_client_sync_lock = false
@process_new_content?()
# Send back our own edits to the global hub.
ds_client.remote.current_mesg_id = mesg.id # used to tag the return message
ds_client.push_edits (err) =>
if err
winston.debug("CodeMirrorSession -- client push_edits returned -- #{err}")
else
changed = (before != @content)
if changed
# We also suggest to other clients to update their state.
@tell_clients_to_update(mesg.client_id)
@update_revision_tracking()
tell_clients_to_update: (exclude) =>
for id, ds_client of @diffsync_clients
if exclude != id
ds_client.remote.sync_ready()
sync_filesystem: (cb) =>
@is_active = true
if @_client_sync_lock # or Math.random() <= .5 # (for testing)
winston.debug("sync_filesystem -- hit client sync lock")
cb?("cannot sync with filesystem while syncing with clients")
return
if @_filesystem_sync_lock
if @_filesystem_sync_lock < new Date()
@_filesystem_sync_lock = false
else
winston.debug("sync_filesystem -- hit filesystem sync lock")
cb?("cannot sync with filesystem; already syncing")
return
before = @content
if not @diffsync_fileclient?
cb?("filesystem sync object (@diffsync_fileclient) no longer defined")
return
@_filesystem_sync_lock = expire_time(10) # lock expires in 10 seconds no matter what -- uncaught exception could require this
@diffsync_fileclient.sync (err) =>
if err
# Example error: 'reset -- checksum mismatch (29089 != 28959)'
winston.debug("@diffsync_fileclient.sync -- returned an error -- #{err}")
@diffsync_fileserver.kill() # stop autosaving and watching files
# Completely recreate diffsync file connection and try to sync once more.
@diffsync_fileserver = new DiffSyncFile_server @, (err, ignore_content) =>
if err
winston.debug("@diffsync_fileclient.sync -- making new server failed: #{err}")
@_filesystem_sync_lock = false
cb?(err); return
@diffsync_fileclient = new DiffSyncFile_client(@diffsync_fileserver)
@diffsync_fileclient.live = @content
@diffsync_fileclient.sync (err) =>
if err
winston.debug("@diffsync_fileclient.sync -- making server worked but re-sync failed -- #{err}")
@_filesystem_sync_lock = false
cb?("codemirror fileclient sync error -- '#{err}'")
else
@_filesystem_sync_lock = false
cb?()
return
if @diffsync_fileclient.live != @content
@set_content(@diffsync_fileclient.live)
# recommend all clients sync
for id, ds_client of @diffsync_clients
ds_client.remote.sync_ready()
@_filesystem_sync_lock = false
cb?()
add_client: (socket, client_id) =>
@is_active = true
ds_client = new diffsync.DiffSync(doc:@content)
ds_client.connect(new CodeMirrorDiffSyncHub(socket, @session_uuid, client_id))
@diffsync_clients[client_id] = ds_client
winston.debug("CodeMirrorSession(#{@path}).add_client(client_id=#{client_id}) -- now we have #{misc.len(@diffsync_clients)} clients.")
# Ensure we do not broadcast to a hub if it has already disconnected.
socket.on 'end', () =>
winston.debug("DISCONNECT: socket connection #{socket.id} from global hub disconected.")
delete @diffsync_clients[client_id]
remove_client: (socket, client_id) =>
delete @diffsync_clients[client_id]
write_to_disk: (socket, mesg) =>
@is_active = true
winston.debug("write_to_disk: #{json(mesg)} -- calling sync_filesystem")
@sync_filesystem (err) =>
if err
resp = message.error(id:mesg.id, error:"Error writing file '#{@path}' to disk -- #{err}")
else
resp = message.codemirror_wrote_to_disk(id:mesg.id, hash:misc.hash_string(@content))
socket.write_mesg('json', resp)
read_from_disk: (socket, mesg) =>
async.series([
(cb) =>
fs.stat (err, stats) =>
if err
cb(err)
else
cb(check_file_size(stats.size))
(cb) =>
fs.readFile @path, (err, data) =>
if err
cb("Error reading file '#{@path}' from disk -- #{err}")
else
value = data.toString()
if value != @content
@set_content(value)
# Tell the global hubs that now might be a good time to do a sync.
for id, ds of @diffsync_clients
ds.remote.sync_ready()
cb()
], (err) =>
if err
socket.write_mesg('json', message.error(id:mesg.id, error:err))
else
socket.write_mesg('json', message.success(id:mesg.id))
)
get_content: (socket, mesg) =>
@is_active = true
socket.write_mesg('json', message.codemirror_content(id:mesg.id, content:@content))
# enable or disable tracking all revisions of the document
revision_tracking: (socket, mesg) =>
winston.debug("revision_tracking for #{@path}: #{mesg.enable}")
d = (m) -> winston.debug("revision_tracking for #{@path}: #{m}")
if mesg.enable
d("enable it")
if @revision_tracking_doc?
d("already enabled")
# already enabled
socket.write_mesg('json', message.success(id:mesg.id))
else
if @readonly
# nothing to do -- silently don't enable (is this a good choice?)
socket.write_mesg('json', message.success(id:mesg.id))
return
# need to enable
d("need to enable")
codemirror_sessions.connect
mesg :
path : revision_tracking_path(@path)
project_id : INFO.project_id # todo -- won't need in long run
cb : (err, session) =>
d("got response -- #{err}")
if err
socket.write_mesg('json', message.error(id:mesg.id, error:err))
else
@revision_tracking_doc = session
socket.write_mesg('json', message.success(id:mesg.id))
@update_revision_tracking()
else
d("disable it")
delete @revision_tracking_doc
socket.write_mesg('json', message.success(id:mesg.id))
# If we are tracking the revision history of this file, add a new entry in that history.
# TODO: add user responsibile for this change as input to this function and as
# a field in the entry object below. NOTE: Be sure to include "changing the file on disk"
# as one of the users, which is *NOT* defined by an account_id.
update_revision_tracking: () =>
if not @revision_tracking_doc?
return
winston.debug("update revision tracking data - #{@path}")
# @revision_tracking_doc.HEAD is the last version of the document we're tracking, as a string.
# In particular, it is NOT in JSON format.
if not @revision_tracking_doc.HEAD?
# Initialize HEAD from the file
if @revision_tracking_doc.content.length == 0
# brand new -- first time.
@revision_tracking_doc.HEAD = @content
@revision_tracking_doc.content = misc.to_json(@content)
else
# we have tracked this file before.
i = @revision_tracking_doc.content.indexOf('\n')
if i == -1
# weird special case: there's no history yet -- just the initial version
@revision_tracking_doc.HEAD = misc.from_json(@revision_tracking_doc.content)
else
# there is a potential longer history; this initial version is the first line:
@revision_tracking_doc.HEAD = misc.from_json(@revision_tracking_doc.content.slice(0,i))
if @revision_tracking_doc.HEAD != @content
# compute diff that transforms @revision_tracking_doc.HEAD to @content
patch = diffsync.dmp.patch_make(@content, @revision_tracking_doc.HEAD)
@revision_tracking_doc.HEAD = @content
# replace the file by new version that has first line equal to JSON version of HEAD,
# and rest all the patches, with our one new patch inserted at the front.
# TODO: redo without doing a split for efficiency.
i = @revision_tracking_doc.content.indexOf('\n')
entry = {patch:diffsync.compress_patch(patch), time:new Date() - 0}
@revision_tracking_doc.content = misc.to_json(@content) + '\n' + \
misc.to_json(entry) + \
(if i != -1 then @revision_tracking_doc.content.slice(i) else "")
# now tell everybody
@revision_tracking_doc._set_content_and_sync()
# save the revision tracking file to disk (but not too frequently)
if not @revision_tracking_save_timer?
f = () =>
delete @revision_tracking_save_timer
@revision_tracking_doc.sync_filesystem()
@revision_tracking_save_timer = setInterval(f, REVISION_TRACKING_SAVE_INTERVAL)
# Collection of all CodeMirror sessions hosted by this local_hub.
class CodeMirrorSessions
constructor: () ->
@_sessions = {by_uuid:{}, by_path:{}, by_project:{}}
connect: (opts) =>
opts = defaults opts,
client_socket : undefined
mesg : required # event of type codemirror_get_session
cb : undefined # cb?(err, session)
mesg = opts.mesg
finish = (session) ->
if not opts.client_socket?
return
session.add_client(opts.client_socket, mesg.client_id)
opts.client_socket.write_mesg 'json', message.codemirror_session
id : mesg.id,
session_uuid : session.session_uuid
path : session.path
content : session.content
readonly : session.readonly
if mesg.session_uuid?
session = @_sessions.by_uuid[mesg.session_uuid]
if session?
finish(session)
opts.cb?(undefined, session)
return
if mesg.path?
session = @_sessions.by_path[mesg.path]
if session?
finish(session)
opts.cb?(undefined, session)
return
mesg.session_uuid = uuid.v4()
new CodeMirrorSession mesg, (err, session) =>
if err
opts.client_socket?.write_mesg('json', message.error(id:mesg.id, error:err))
opts.cb?(err)
else
@add_session_to_cache
session : session
project_id : mesg.project_id
timeout : 3600 # time in seconds (or undefined to not use timer)
finish(session)
opts.cb?(undefined, session)
add_session_to_cache: (opts) =>
opts = defaults opts,
session : required
project_id : undefined
timeout : undefined # or a time in seconds
winston.debug("Adding session #{opts.session.session_uuid} (of project #{opts.project_id}) to cache.")
@_sessions.by_uuid[opts.session.session_uuid] = opts.session
@_sessions.by_path[opts.session.path] = opts.session
if opts.project_id?
if not @_sessions.by_project[opts.project_id]?
@_sessions.by_project[opts.project_id] = {}
@_sessions.by_project[opts.project_id][opts.session.path] = opts.session
destroy = () =>
opts.session.kill()
delete @_sessions.by_uuid[opts.session.session_uuid]
delete @_sessions.by_path[opts.session.path]
x = @_sessions.by_project[opts.project_id]
if x?
delete x[opts.session.path]
if opts.timeout?
destroy_if_inactive = () =>
if not (opts.session.is_active? and opts.session.is_active)
winston.debug("Session #{opts.session.session_uuid} is inactive for #{opts.timeout} seconds; killing.")
destroy()
else
opts.session.is_active = false # it must be changed by the session before the next timer.
# We use setTimeout instead of setInterval, because we want to *ensure* that the
# checks are spaced out over at *least* opts.timeout time.
winston.debug("Starting a new activity check timer for session #{opts.session.session_uuid}.")
setTimeout(destroy_if_inactive, opts.timeout*1000)
setTimeout(destroy_if_inactive, opts.timeout*1000)
# Return object that describes status of CodeMirror sessions for a given project
info: (project_id) =>
obj = {}
X = @_sessions.by_project[project_id]
if X?
for path, session of X
obj[session.session_uuid] = {path : session.path}
return obj
handle_mesg: (client_socket, mesg) =>
winston.debug("CodeMirrorSessions.handle_mesg: '#{json(mesg)}'")
if mesg.event == 'codemirror_get_session'
@connect
client_socket : client_socket
mesg : mesg
return
# all other message types identify the session only by the uuid.
session = @_sessions.by_uuid[mesg.session_uuid]
if not session?
winston.debug("codemirror.handle_mesg -- Unknown CodeMirror session: #{mesg.session_uuid}.")
client_socket.write_mesg('json', message.error(id:mesg.id, error:"Unknown CodeMirror session: #{mesg.session_uuid}."))
return
switch mesg.event
when 'codemirror_diffsync'
session.client_diffsync(client_socket, mesg)
when 'codemirror_bcast'
session.client_bcast(client_socket, mesg)
when 'codemirror_write_to_disk'
session.write_to_disk(client_socket, mesg)
when 'codemirror_read_from_disk'
session.read_from_disk(client_socket, mesg)
when 'codemirror_get_content'
session.get_content(client_socket, mesg)
when 'codemirror_revision_tracking' # enable/disable revision_tracking
session.revision_tracking(client_socket, mesg)
when 'codemirror_execute_code'
session.sage_execute_code(client_socket, mesg)
when 'codemirror_introspect'
session.sage_introspect(client_socket, mesg)
when 'codemirror_send_signal'
session.send_signal_to_sage_session(client_socket, mesg)
when 'codemirror_disconnect'
session.remove_client(client_socket, mesg.client_id)
client_socket.write_mesg('json', message.success(id:mesg.id))
when 'codemirror_sage_raw_input'
session.sage_raw_input(client_socket, mesg)
else
client_socket.write_mesg('json', message.error(id:mesg.id, error:"unknown CodeMirror session event: #{mesg.event}."))
codemirror_sessions = new CodeMirrorSessions()
###############################################
# Connecting to existing session or making a
# new one.
###############################################
connect_to_session = (socket, mesg) ->
winston.debug("connect_to_session -- type='#{mesg.type}'")
switch mesg.type
when 'console'
console_sessions.connect(socket, mesg)
when 'sage'
sage_sessions.connect(socket, mesg)
else
err = message.error(id:mesg.id, error:"Unsupported session type '#{mesg.type}'")
socket.write_mesg('json', err)
###############################################
# Kill an existing session.
###############################################
terminate_session = (socket, mesg) ->
cb = (err) ->
if err
mesg = message.error(id:mesg.id, error:err)
socket.write_mesg('json', mesg)
sid = mesg.session_uuid
if console_sessions.session_exists(sid)
console_sessions.terminate_session(sid, cb)
else if sage_sessions.session_exists(sid)
sage_sessions.terminate_session(sid, cb)
else
cb()
###############################################
# Read and write individual files
###############################################
# Read a file located in the given project. This will result in an
# error if the readFile function fails, e.g., if the file doesn't
# exist or the project is not open. We then send the resulting file
# over the socket as a blob message.
#
# Directories get sent as a ".tar.bz2" file.
# TODO: should support -- 'tar', 'tar.bz2', 'tar.gz', 'zip', '7z'. and mesg.archive option!!!
#
read_file_from_project = (socket, mesg) ->
data = undefined
path = abspath(mesg.path)
is_dir = undefined
id = undefined
archive = undefined
stats = undefined
async.series([
(cb) ->
#winston.debug("Determine whether the path '#{path}' is a directory or file.")
fs.stat path, (err, _stats) ->
if err
cb(err)
else
stats = _stats
is_dir = stats.isDirectory()
cb()
(cb) ->
# make sure the file isn't too large
cb(check_file_size(stats.size))
(cb) ->
if is_dir
if mesg.archive != 'tar.bz2'
cb("The only supported directory archive format is tar.bz2")
return
target = temp.path(suffix:'.' + mesg.archive)
#winston.debug("'#{path}' is a directory, so archive it to '#{target}', change path, and read that file")
archive = mesg.archive
if path[path.length-1] == '/' # common nuisance with paths to directories
path = path.slice(0,path.length-1)
split = misc.path_split(path)
path = target
# same patterns also in project.coffee (TODO)
args = ["--exclude=.sagemathcloud*", '--exclude=.forever', '--exclude=.node*', '--exclude=.npm', '--exclude=.sage', '-jcf', target, split.tail]
#winston.debug("tar #{args.join(' ')}")
child_process.execFile 'tar', args, {cwd:split.head}, (err, stdout, stderr) ->
if err
winston.debug("Issue creating tarball: #{err}, #{stdout}, #{stderr}")
cb(err)
else
cb()
else
#winston.debug("It is a file.")
cb()
(cb) ->
#winston.debug("Read the file into memory.")
fs.readFile path, (err, _data) ->
data = _data
cb(err)
(cb) ->
#winston.debug("Compute hash of file.")
id = misc_node.uuidsha1(data)
winston.debug("Hash = #{id}")
cb()
# TODO
# (cb) ->
# winston.debug("Send hash of file to hub to see whether or not we really need to send the file itself; it might already be known.")
# cb()
# (cb) ->
# winston.debug("Get message back from hub -- do we send file or not?")
# cb()
(cb) ->
#winston.debug("Finally, we send the file as a blob back to the hub.")
socket.write_mesg 'json', message.file_read_from_project(id:mesg.id, data_uuid:id, archive:archive)
socket.write_mesg 'blob', {uuid:id, blob:data}
cb()
], (err) ->
if err and err != 'file already known'
socket.write_mesg 'json', message.error(id:mesg.id, error:err)
if is_dir
fs.exists path, (exists) ->
if exists
winston.debug("It was a directory, so remove the temporary archive '#{path}'.")
fs.unlink(path)
)
write_file_to_project = (socket, mesg) ->
data_uuid = mesg.data_uuid
path = abspath(mesg.path)
# Listen for the blob containing the actual content that we will write.
write_file = (type, value) ->
if type == 'blob' and value.uuid == data_uuid
socket.removeListener 'mesg', write_file
async.series([
(cb) ->
ensure_containing_directory_exists(path, cb)
(cb) ->
#winston.debug('writing the file')
fs.writeFile(path, value.blob, cb)
], (err) ->
if err
#winston.debug("error writing file -- #{err}")
socket.write_mesg 'json', message.error(id:mesg.id, error:err)
else
#winston.debug("wrote file '#{path}' fine")
socket.write_mesg 'json', message.file_written_to_project(id:mesg.id)
)
socket.on 'mesg', write_file
###############################################
# Printing an individual file to pdf
###############################################
print_sagews = (opts) ->
opts = defaults opts,
path : required
outfile : required
title : required
author : required
date : required
contents : required
extra_data : undefined # extra data that is useful for displaying certain things in the worksheet.
timeout : 90
cb : required
extra_data_file = undefined
args = [opts.path, '--outfile', opts.outfile, '--title', opts.title, '--author', opts.author,'--date', opts.date, '--contents', opts.contents]
async.series([
(cb) ->
if not opts.extra_data?
cb(); return
extra_data_file = temp.path() + '.json'
args.push('--extra_data_file')
args.push(extra_data_file)
# NOTE: extra_data is a string that is *already* in JSON format.
fs.writeFile(extra_data_file, opts.extra_data, cb)
(cb) ->
# run the converter script
misc_node.execute_code
command : "sagews2pdf.py"
args : args
err_on_exit : false
bash : false
timeout : opts.timeout
cb : cb
], (err) =>
if extra_data_file?
fs.unlink(extra_data_file) # no need to wait for completion before calling opts.cb
opts.cb(err)
)
print_to_pdf = (socket, mesg) ->
ext = misc.filename_extension(mesg.path)
if ext
pdf = "#{mesg.path.slice(0,mesg.path.length-ext.length)}pdf"
else
pdf = mesg.path + '.pdf'
async.series([
(cb) ->
switch ext
when 'sagews'
print_sagews
path : mesg.path
outfile : pdf
title : mesg.options.title
author : mesg.options.author
date : mesg.options.date
contents : mesg.options.contents
extra_data : mesg.options.extra_data
timeout : mesg.options.timeout
cb : cb
else
cb("unable to print file of type '#{ext}'")
], (err) ->
if err
socket.write_mesg('json', message.error(id:mesg.id, error:err))
else
socket.write_mesg('json', message.printed_to_pdf(id:mesg.id, path:pdf))
)
###############################################
# Info
###############################################
session_info = (project_id) ->
return {
'sage_sessions' : sage_sessions.info(project_id)
'console_sessions' : console_sessions.info(project_id)
'file_sessions' : codemirror_sessions.info(project_id)
}
###############################################
# Manage Jupyter server
###############################################
jupyter_port_queue = []
jupyter_port = (socket, mesg) ->
winston.debug("jupyter_port")
jupyter_port_queue.push({socket:socket, mesg:mesg})
if jupyter_port_queue.length > 1
return
misc_node.execute_code
command : "ipython-notebook"
args : ['start']
err_on_exit : true
bash : false
timeout : 60
ulimit_timeout : false # very important -- so doesn't kill consoles after 60 seconds cputime!
cb : (err, out) ->
if not err
try
info = misc.from_json(out.stdout)
port = info?.port
if not port?
err = "unable to start -- no port; info=#{misc.to_json(out)}"
else
catch e
err = "error parsing ipython-notebook startup output -- #{e}, {misc.to_json(out)}"
if err
error = "error starting Jupyter -- #{err}"
for x in jupyter_port_queue
err_mesg = message.error
id : x.mesg.id
error : error
x.socket.write_mesg('json', err_mesg)
else
for x in jupyter_port_queue
resp = message.jupyter_port
port : port
id : x.mesg.id
x.socket.write_mesg('json', resp)
jupyter_port_queue = []
###############################################
# Execute a command line or block of BASH
###############################################
project_exec = (socket, mesg) ->
winston.debug("project_exec")
if mesg.command == "ipython-notebook"
socket.write_mesg("json", message.error(id:mesg.id, error:"old client code -- you may not run ipython-notebook directly"))
return
misc_node.execute_code
command : mesg.command
args : mesg.args
path : abspath(mesg.path)
timeout : mesg.timeout
err_on_exit : mesg.err_on_exit
max_output : mesg.max_output
bash : mesg.bash
cb : (err, out) ->
if err
error = "Error executing command '#{mesg.command}' with args '#{mesg.args}' -- #{err}, #{out?.stdout}, #{out?.stderr}"
if error.indexOf("Connection refused") != -1
error += "-- Email help@sagemath.com if you need external network access, which is disabled by default."
if error.indexOf("=") != -1
error += "-- This is a BASH terminal, not a Sage worksheet. For Sage, use +New and create a Sage worksheet."
err_mesg = message.error
id : mesg.id
error : error
socket.write_mesg('json', err_mesg)
else
#winston.debug(json(out))
socket.write_mesg 'json', message.project_exec_output
id : mesg.id
stdout : out.stdout
stderr : out.stderr
exit_code : out.exit_code
_save_blob_callbacks = {}
receive_save_blob_message = (opts) ->
opts = defaults opts,
sha1 : required
cb : required
timeout : 30 # maximum time in seconds to wait for response message
sha1 = opts.sha1
id = misc.uuid()
if not _save_blob_callbacks[sha1]?
_save_blob_callbacks[sha1] = [[opts.cb, id]]
else
_save_blob_callbacks[sha1].push([opts.cb, id])
# Timeout functionality -- send a response after opts.timeout seconds,
# in case no hub responded.
f = () ->
v = _save_blob_callbacks[sha1]
if v?
mesg = message.save_blob
sha1 : sha1
error : "timed out after local hub waited for #{opts.timeout} seconds"
w = []
for x in v # this is O(n) instead of O(1), but who cares since n is usually 1.
if x[1] == id
x[0](mesg)
else
w.push(x)
if w.length == 0
delete _save_blob_callbacks[sha1]
else
_save_blob_callbacks[sha1] = w
if opts.timeout
setTimeout(f, opts.timeout*1000)
handle_save_blob_message = (mesg) ->
v = _save_blob_callbacks[mesg.sha1]
if v?
for x in v
x[0](mesg)
delete _save_blob_callbacks[mesg.sha1]
###############################################
# Handle a message from the client
###############################################
handle_mesg = (socket, mesg, handler) ->
activity() # record that there was some activity so process doesn't killall
try
winston.debug("Handling '#{json(mesg)}'")
if mesg.event.split('_')[0] == 'codemirror'
codemirror_sessions.handle_mesg(socket, mesg)
return
switch mesg.event
when 'connect_to_session', 'start_session'
# These sessions completely take over this connection, so we better stop listening
# for further control messages on this connection.
socket.removeListener 'mesg', handler
connect_to_session(socket, mesg)
when 'project_session_info'
resp = message.project_session_info
id : mesg.id
project_id : mesg.project_id
info : session_info(mesg.project_id)
socket.write_mesg('json', resp)
when 'jupyter_port'
jupyter_port(socket, mesg)
when 'project_exec'
project_exec(socket, mesg)
when 'read_file_from_project'
read_file_from_project(socket, mesg)
when 'write_file_to_project'
write_file_to_project(socket, mesg)
when 'print_to_pdf'
print_to_pdf(socket, mesg)
when 'send_signal'
process_kill(mesg.pid, mesg.signal)
if mesg.id?
socket.write_mesg('json', message.signal_sent(id:mesg.id))
when 'terminate_session'
terminate_session(socket, mesg)
when 'save_blob'
handle_save_blob_message(mesg)
else
if mesg.id?
err = message.error(id:mesg.id, error:"Local hub received an invalid mesg type '#{mesg.event}'")
socket.write_mesg('json', err)
catch e
winston.debug(new Error().stack)
winston.error "ERROR: '#{e}' handling message '#{json(mesg)}'"
process_kill = (pid, signal) ->
switch signal
when 2
signal = 'SIGINT'
when 3
signal = 'SIGQUIT'
when 9
signal = 'SIGKILL'
else
winston.debug("BUG -- process_kill: only signals 2 (SIGINT), 3 (SIGQUIT), and 9 (SIGKILL) are supported")
return
try
process.kill(pid, signal)
catch e
# it's normal to get an exception when sending a signal... to a process that doesn't exist.
server = net.createServer (socket) ->
winston.debug "PARENT: received connection"
misc_node.unlock_socket socket, secret_token, (err) ->
if err
winston.debug(err)
else
socket.id = uuid.v4()
misc_node.enable_mesg(socket)
handler = (type, mesg) ->
if type == "json" # other types are handled elsewhere in event code.
winston.debug "received control mesg #{json(mesg)}"
handle_mesg(socket, mesg, handler)
socket.on 'mesg', handler
start_tcp_server = (cb) ->
winston.info("starting tcp server...")
server.listen program.port, '0.0.0.0', () ->
winston.info("listening on port #{server.address().port}")
fs.writeFile(abspath("#{DATA}/local_hub.port"), server.address().port, cb)
# use of domain inspired by http://stackoverflow.com/questions/17940895/handle-uncaughtexception-in-express-and-restify
# This addresses an issue where the raw server fails to startup, maybe due to race condition with misc_node.free_port;
# and... in any case if anything uncaught goes wrong starting the raw server or running, this will ensure
# that it gets fixed automatically.
raw_server_domain = require('domain').create()
raw_server_domain.on 'error', (err) ->
winston.debug("got an exception in raw server, so restarting.")
start_raw_server( () -> winston.debug("restarted raw http server") )
start_raw_server = (cb) ->
raw_server_domain.run () ->
winston.info("starting raw server...")
info = INFO
winston.debug("info = #{misc.to_json(info)}")
express = require('express')
raw_server = express()
project_id = info.project_id
misc_node.free_port (err, port) ->
if err
winston.debug("error starting raw server: #{err}")
cb(err); return
fs.writeFile(abspath("#{DATA}/raw.port"), port, cb)
base = "#{info.base_url}/#{project_id}/raw/"
winston.info("raw server (port=#{port}), host='#{info.location.host}', base='#{base}'")
raw_server.configure () ->
raw_server.use(base, express.directory(process.env.HOME, {hidden:true, icons:true}))
raw_server.use(base, express.static(process.env.HOME, {hidden:true}))
# NOTE: It is critical to only listen on the host interface (not localhost), since otherwise other users
# on the same VM could listen in. We firewall connections from the other VM hosts above
# port 1024, so this is safe without authentication. TODO: should we add some sort of auth (?) just in case?
raw_server.listen port, info.location.host, (err) ->
winston.info("err = #{err}")
if err
cb(err); return
fs.writeFile(abspath("#{DATA}/raw.port"), port, cb)
last_activity = undefined
# Call this function to signal that there is activity.
activity = () ->
last_activity = misc.mswalltime()
# Truncate the ~/.sagemathcloud.log if it exceeds a certain length threshhold.
SAGEMATHCLOUD_LOG_THRESH = 5000 # log grows to at most 50% more than this
SAGEMATHCLOUD_LOG_FILE = process.env['HOME'] + '/.sagemathcloud.log'
log_truncate = (cb) ->
data = undefined
winston.info("log_truncate: checking that logfile isn't too long")
exists = undefined
async.series([
(cb) ->
fs.exists SAGEMATHCLOUD_LOG_FILE, (_exists) ->
exists = _exists
cb()
(cb) ->
if not exists
cb(); return
# read the log file
fs.readFile SAGEMATHCLOUD_LOG_FILE, (err, _data) ->
data = _data?.toString() # ? is important, since in case of err _data is not defined.
cb(err)
(cb) ->
if not exists
cb(); return
# if number of lines exceeds 50% more than MAX_LINES
n = misc.count(data, '\n')
if n >= SAGEMATHCLOUD_LOG_THRESH * 1.5
winston.debug("log_truncate: truncating log file to #{SAGEMATHCLOUD_LOG_THRESH} lines")
v = data.split('\n') # the -1 below is since last entry is a blank line
new_data = v.slice(n - SAGEMATHCLOUD_LOG_THRESH, v.length-1).join('\n')
fs.writeFile(SAGEMATHCLOUD_LOG_FILE, new_data, cb)
else
cb()
], cb)
start_log_truncate = (cb) ->
winston.info("start_log_truncate")
f = (c) ->
winston.debug("calling log_truncate")
log_truncate (err) ->
if err
winston.debug("ERROR: problem truncating log -- #{err}")
c()
setInterval(f, 1000*3600*12) # once every 12 hours
f(cb)
# Start listening for connections on the socket.
exports.start_server = start_server = () ->
async.series [start_log_truncate, start_tcp_server, start_raw_server], (err) ->
if err
winston.debug("Error starting a server -- #{err}")
else
winston.debug("Successfully started servers.")
# daemonize it
program = require('commander')
daemon = require("start-stop-daemon")
program.usage('[start/stop/restart/status] [options]')
.option('--pidfile [string]', 'store pid in this file', String, abspath("#{DATA}/local_hub.pid"))
.option('--logfile [string]', 'write log to this file', String, abspath("#{DATA}/local_hub.log"))
.option('--forever_logfile [string]', 'write forever log to this file', String, abspath("#{DATA}/forever_local_hub.log"))
.option('--debug [string]', 'logging debug level (default: "debug"); "" for no debugging output)', String, 'debug')
.parse(process.argv)
if program._name.split('.')[0] == 'local_hub'
if program.debug
winston.remove(winston.transports.Console)
winston.add(winston.transports.Console, {level: program.debug, timestamp:true, colorize:true})
winston.debug "Running as a Daemon"
# run as a server/daemon (otherwise, is being imported as a library)
process.addListener "uncaughtException", (err) ->
winston.debug("BUG ****************************************************************************")
winston.debug("Uncaught exception: " + err)
winston.debug(err.stack)
winston.debug("BUG ****************************************************************************")
if console? and console.trace?
console.trace()
console.log("setting up conf path")
init_confpath()
init_info_json()
# empty the forever logfile -- it doesn't get reset on startup and easily gets huge.
fs.writeFileSync(program.forever_logfile, '')
console.log("start daemon")
daemon({pidFile:program.pidfile, outFile:program.logfile, errFile:program.logfile, logFile:program.forever_logfile, max:1}, start_server)
console.log("after daemon")
| 141545 | ###############################################################################
#
# SageMathCloud: A collaborative web-based interface to Sage, IPython, LaTeX and the Terminal.
#
# Copyright (C) 2014, <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
#################################################################
#
# local_hub -- a node.js program that runs as a regular user, and
# coordinates and maintains the connections between
# the global hubs and *all* projects running as
# this particular user.
#
# The local_hub is a bit like the "screen" program for Unix, except
# that it simultaneously manages numerous sessions, since simultaneously
# doing a lot of IO-based things is what Node.JS is good at.
#
#
# NOTE: For local debugging, run this way, since it gives better stack
# traces.CodeMirrorSession: _connect to file
#
# make_coffee && echo "require('local_hub').start_server()" | coffee
#
# (c) <NAME>, 2013, 2014
#
#################################################################
async = require 'async'
fs = require 'fs'
net = require 'net'
child_process = require 'child_process'
uuid = require 'node-uuid'
message = require 'message'
misc = require 'misc'
misc_node = require 'misc_node'
winston = require 'winston'
temp = require 'temp'
diffsync = require 'diffsync'
{to_json, from_json, defaults, required} = require 'misc'
json = (out) -> misc.trunc(misc.to_json(out),512)
{ensure_containing_directory_exists, abspath} = misc_node
expire_time = (ttl) -> if ttl then new Date((new Date() - 0) + ttl*1000)
# We make it an error for a client to try to edit a file larger than MAX_FILE_SIZE.
# I decided on this, because attempts to open a much larger file leads
# to disaster. Opening a 10MB file works but is a just a little slow.
MAX_FILE_SIZE = 10000000 # 10MB
check_file_size = (size) ->
if size? and size > MAX_FILE_SIZE
e = "Attempt to open large file of size #{Math.round(size/1000000)}MB; the maximum allowed size is #{Math.round(MAX_FILE_SIZE/1000000)}MB. Use vim, emacs, or pico from a terminal instead."
winston.debug(e)
return e
###
# Revision tracking misc.
###
# Save the revision_tracking info for a file to disk *at most* this frequently.
# NOTE: failing to save to disk would only mean missing a patch but should
# otherwise *NOT* corrupt the history.
REVISION_TRACKING_SAVE_INTERVAL = 45000 # 45 seconds
# Filename of revision tracking file associated to a given file
revision_tracking_path = (path) ->
s = misc.path_split(path)
return "#{s.head}/.#{s.tail}.sage-history"
# Create dmp patch that transforms the empty string to s.
### not used (so commented out), but could be useful...
patch_from_trivial = (s) ->
return [
diffs : [ [ 1, s ] ],
start1 : 0,
start2 : 0,
length1 : 0,
length2 : s.length }
]
###
#####################################################################
# Generate the "secret_token" file as
# $SAGEMATHCLOUD/data/secret_token if it does not already
# exist. All connections to all local-to-the user services that
# SageMathClouds starts must be prefixed with this key.
#####################################################################
# WARNING -- the sage_server.py program can't get these definitions from
# here, since it is not written in node; if this path changes, it has
# to be change there as well (it will use the SAGEMATHCLOUD environ
# variable though).
DATA = process.env['SAGEMATHCLOUD'] + '/data'
CONFPATH = exports.CONFPATH = abspath(DATA)
secret_token_filename = exports.secret_token_filename = "#{CONFPATH}/secret_token"
secret_token = undefined
# We use an n-character cryptographic random token, where n is given
# below. If you want to change this, changing only the following line
# should be safe.
secret_token_length = 128
init_confpath = () ->
async.series([
# Read or create the file; after this step the variable secret_token
# is set and the file exists.
(cb) ->
fs.exists secret_token_filename, (exists) ->
if exists
winston.debug("read '#{secret_token_filename}'")
fs.readFile secret_token_filename, (err, buf) ->
secret_token = buf.toString()
cb()
else
winston.debug("create '#{secret_token_filename}'")
require('crypto').randomBytes secret_token_length, (ex, buf) ->
secret_token = buf.toString('base64')
fs.writeFile(secret_token_filename, secret_token, cb)
# Ensure restrictive permissions on the secret token file.
(cb) ->
fs.chmod(secret_token_filename, 0o600, cb)
])
INFO = undefined
init_info_json = () ->
winston.debug("writing info.json")
filename = "#{process.env['SAGEMATHCLOUD']}/info.json"
v = process.env['HOME'].split('/')
project_id = v[v.length-1]
username = project_id.replace(/-/g,'')
host = require('os').networkInterfaces().eth0?[0].address
base_url = ''
port = 22
INFO =
project_id : project_id
location : {host:host, username:username, port:port, path:'.'}
base_url : base_url
fs.writeFileSync(filename, misc.to_json(INFO))
###############################################
# Console sessions
###############################################
ports = {}
get_port = (type, cb) -> # cb(err, port number)
if ports[type]?
cb(false, ports[type])
else
fs.readFile abspath("#{DATA}/#{type}_server.port"), (err, content) ->
if err
cb(err)
else
try
ports[type] = parseInt(content)
cb(false, ports[type])
catch e
cb("#{type}_server port file corrupted")
forget_port = (type) ->
if ports[type]?
delete ports[type]
# try to restart the console server and get port where it is listening
CONSOLE_SERVER_MAX_STARTUP_TIME_S = 10 # 10 seconds
_restarting_console_server = false
_restarted_console_server = 0 # time when we last restarted it
restart_console_server = (cb) -> # cb(err)
dbg = (m) -> winston.debug("restart_console_server: #{misc.to_json(m)}")
if _restarting_console_server
dbg("hit lock -- already restarting console server")
cb("already restarting console server")
return
t = new Date() - _restarted_console_server
if t <= CONSOLE_SERVER_MAX_STARTUP_TIME_S*1000
err = "restarted console server #{t}ms ago -- still waiting for it to start"
dbg(err)
cb(err)
return
_restarting_console_server = true
dbg("restarting the daemon")
dbg("killing all existing console sockets")
console_sessions.terminate_all_sessions()
port_file = abspath("#{DATA}/console_server.port")
port = undefined
async.series([
(cb) ->
dbg("remove port_file=#{port_file}")
fs.unlink port_file, (err) ->
cb() # ignore error, e.g., if file not there.
(cb) ->
dbg("restart console server")
misc_node.execute_code
command : "console_server restart"
timeout : 10
ulimit_timeout : false # very important -- so doesn't kill consoles after 10 seconds!
err_on_exit : true
bash : true
cb : cb
(cb) ->
dbg("wait a little to see if #{port_file} appears, and if so read it and return port")
f = (cb) ->
fs.exists port_file, (exists) ->
if not exists
cb(true)
else
fs.readFile port_file, (err, data) ->
if err
cb(err)
else
try
port = parseInt(data.toString())
cb()
catch error
cb('reading port corrupt')
misc.retry_until_success
f : f
max_time : 7000
cb : cb
], (err) =>
_restarting_console_server = false
_restarted_console_server = new Date()
dbg("finished trying to restart console_server")
if err
dbg("ERROR: #{err}")
cb(err, port)
)
class ConsoleSessions
constructor: () ->
@_sessions = {}
@_get_session_cbs = {}
session_exists: (session_uuid) =>
return @_sessions[session_uuid]?
terminate_session: (session_uuid, cb) =>
session = @_sessions[session_uuid]
if not session?
cb?()
else
winston.debug("terminate console session '#{session_uuid}'")
if session.status == 'running'
session.socket.end()
session.status = 'done'
cb?()
else
cb?()
terminate_all_sessions: () =>
for session_uuid, session of @_sessions[session_uuid]
try
session.socket.end()
catch e
session.status = 'done'
# Connect to (if 'running'), restart (if 'dead'), or create (if
# non-existing) the console session with mesg.session_uuid.
connect: (client_socket, mesg, cb) =>
if not mesg.session_uuid?
mesg.session_uuid = misc.uuid()
client_socket.on 'end', () =>
winston.debug("a console session client socket ended -- session_uuid=#{mesg.session_uuid}")
#client_socket.destroy()
@get_session mesg, (err, session) =>
if err
client_socket.write_mesg('json', message.error(id:mesg.id, error:err))
cb?(err)
else
client_socket.write_mesg('json', {desc:session.desc, history:session.history.toString()})
plug(client_socket, session.socket, 20000) # 20000 = max burst to client every few ms.
session.clients.push(client_socket)
cb?()
# Get or create session with given uuid.
# Can be safely called several times at once without creating multiple sessions...
get_session: (mesg, cb) =>
# TODO: must be robust against multiple clients opening same session_id at once, which
# would be likely to happen on network reconnect.
winston.debug("get_session: console session #{mesg.session_uuid}")
session = @_sessions[mesg.session_uuid]
if session? and session.status == 'running'
winston.debug("console session: done -- it's already there and working")
cb(undefined, session)
return
if not @_get_session_cbs[mesg.session_uuid]?
winston.debug("console session not yet created -- put on stack")
@_get_session_cbs[mesg.session_uuid] = [cb]
else
winston.debug("console session already being created -- just push cb onto stack and return")
@_get_session_cbs[mesg.session_uuid].push(cb)
return
port = undefined
history = undefined
async.series([
(cb) =>
if session?
history = session.history # maintain history
winston.debug("console session does not exist or is not running, so we make a new session")
session = undefined
get_port 'console', (err, _port) =>
if err
cb() # will try to restart console server in next step
else
port = _port
winston.debug("got console server port = #{port}")
cb()
(cb) =>
if port?
cb()
else
winston.debug("couldn't determine console server port; probably console server not running -- try restarting it")
restart_console_server (err, _port) =>
if err
cb(err)
else
port = _port
winston.debug("restarted console server, then got port = #{port}")
cb()
(cb) =>
# Got port -- now create the new session
@_new_session mesg, port, (err, _session) =>
if err
cb(err)
else
session = _session
if history? # we restarted session; maintain history
session.history = history
cb()
], (err) =>
# call all the callbacks that were waiting on this session.
for cb in @_get_session_cbs[mesg.session_uuid]
cb(err, session)
delete @_get_session_cbs[mesg.session_uuid]
)
_get_console_server_socket: (port, cb) =>
socket = undefined
f = (cb) =>
misc_node.connect_to_locked_socket
port : port
token : <PASSWORD>_token
cb : (err, _socket) =>
if err
cb(err)
else
socket = _socket
cb()
async.series([
(cb) =>
misc.retry_until_success
f : f
max_time : 5000
cb : (err) =>
cb() # ignore err on purpose -- no err sets socket
(cb) =>
if socket?
cb(); return
forget_port('console')
restart_console_server (err, _port) =>
if err
cb(err)
else
port = _port
cb()
(cb) =>
if socket?
cb(); return
misc.retry_until_success
f : f
max_time : 5000
cb : cb
], (err) =>
if err
cb(err)
else
cb(undefined, socket)
)
_new_session: (mesg, port, cb) => # cb(err, session)
winston.debug("_new_session: defined by #{json(mesg)}")
# Connect to port CONSOLE_PORT, send mesg, then hook sockets together.
@_get_console_server_socket port, (err, console_socket) =>
if err
cb("_new_session: console server failed to connect -- #{err}")
return
# Request a Console session from console_server
misc_node.enable_mesg(console_socket)
console_socket.write_mesg('json', mesg)
# Read one JSON message back, which describes the session
console_socket.once 'mesg', (type, desc) =>
if not history?
history = new Buffer(0)
# in future, history could be read from a file
# Disable JSON mesg protocol, since it isn't used further
misc_node.disable_mesg(console_socket)
session =
socket : console_socket
desc : desc
status : 'running'
clients : []
history : '' # TODO: this could come from something stored in a file
session_uuid : mesg.session_uuid
project_id : mesg.project_id
session.amount_of_data = 0
session.last_data = misc.mswalltime()
console_socket.on 'data', (data) ->
#winston.debug("receive #{data.length} of data from the pty: data='#{data.toString()}'")
# every 2 ms we reset the burst data watcher.
tm = misc.mswalltime()
if tm - session.last_data >= 2
session.amount_of_data = 0
session.last_data = tm
if session.amount_of_data > 50000
# We just got more than 50000 characters of output in <= 2 ms, so truncate it.
# I had a control-c here, but it was EVIL (and useless), so do *not* enable this.
# console_socket.write(String.fromCharCode(3))
data = '[...]'
session.history += data
session.amount_of_data += data.length
n = session.history.length
if n > 200000
session.history = session.history.slice(session.history.length - 100000)
@_sessions[mesg.session_uuid] = session
cb(undefined, session)
console_socket.on 'end', () =>
winston.debug("console session #{mesg.session_uuid} ended")
session = @_sessions[mesg.session_uuid]
if session?
session.status = 'done'
for client in session.clients
# close all of these connections
client.end()
# Return object that describes status of all Console sessions
info: (project_id) =>
obj = {}
for id, session of @_sessions
if session.project_id == project_id
obj[id] =
desc : session.desc
status : session.status
history_length : session.history.length
return obj
console_sessions = new ConsoleSessions()
###############################################
# Direct Sage socket session -- used internally in local hub, e.g., to assist CodeMirror editors...
###############################################
# Wait up to this long for the Sage server to start responding
# connection requests, after we restart it. It can
# take a while, since it pre-imports the sage library
# at startup, before forking.
SAGE_SERVER_MAX_STARTUP_TIME_S = 30 # 30 seconds
_restarting_sage_server = false
_restarted_sage_server = 0 # time when we last restarted it
exports.restart_sage_server = restart_sage_server = (cb) ->
dbg = (m) -> winston.debug("restart_sage_server: #{misc.to_json(m)}")
if _restarting_sage_server
dbg("hit lock")
cb("already restarting sage server")
return
t = new Date() - _restarted_sage_server
if t <= SAGE_SERVER_MAX_STARTUP_TIME_S*1000
err = "restarted sage server #{t}ms ago -- still waiting for it to start"
dbg(err)
cb(err)
return
_restarting_sage_server = true
dbg("restarting the daemon")
misc_node.execute_code
command : "sage_server stop; sage_server start"
timeout : 30
ulimit_timeout : false # very important -- so doesn't kill consoles after 30 seconds of cpu!
err_on_exit : true
bash : true
cb : (err) ->
_restarting_sage_server = false
_restarted_sage_server = new Date()
cb(err)
# Get a new connection to the Sage server. If the server
# isn't running, e.g., it was killed due to running out of memory,
# then attempt to restart it and try to connect.
get_sage_socket = (cb) ->
socket = undefined
try_to_connect = (cb) ->
_get_sage_socket (err, _socket) ->
if not err
socket = _socket
cb()
else
# Failed for some reason: try to restart one time, then try again.
# We do this because the Sage server can easily get killed due to out of memory conditions.
# But we don't constantly try to restart the server, since it can easily fail to start if
# there is something wrong with a local Sage install.
# Note that restarting the sage server doesn't impact currently running worksheets (they
# have their own process that isn't killed).
restart_sage_server (err) -> # won't actually try to restart if called recently.
# we ignore the returned err -- error does not matter, since we didn't connect
cb(true)
misc.retry_until_success
f : try_to_connect
start_delay : 2000
max_delay : 6000
factor : 1.5
max_time : SAGE_SERVER_MAX_STARTUP_TIME_S*1000
log : (m) -> winston.debug("get_sage_socket: #{m}")
cb : (err) ->
cb(err, socket)
_get_sage_socket = (cb) -> # cb(err, socket that is ready to use)
sage_socket = undefined
port = undefined
async.series([
(cb) =>
winston.debug("get sage server port")
get_port 'sage', (err, _port) =>
if err
cb(err); return
else
port = _port
cb()
(cb) =>
winston.debug("get and unlock socket")
misc_node.connect_to_locked_socket
port : port
token : <PASSWORD>_token
cb : (err, _socket) =>
if err
forget_port('sage')
winston.debug("unlock socket: _new_session: sage session denied connection: #{err}")
cb("_new_session: sage session denied connection: #{err}")
return
sage_socket = _socket
winston.debug("Successfully unlocked a sage session connection.")
cb()
(cb) =>
winston.debug("request sage session from server.")
misc_node.enable_mesg(sage_socket)
sage_socket.write_mesg('json', message.start_session(type:'sage'))
winston.debug("Waiting to read one JSON message back, which will describe the session....")
# TODO: couldn't this just hang forever :-(
sage_socket.once 'mesg', (type, desc) =>
winston.debug("Got message back from Sage server: #{json(desc)}")
sage_socket.pid = desc.pid
cb()
], (err) -> cb(err, sage_socket))
# Connect to sockets together. This is used mainly
# for the console server.
plug = (s1, s2, max_burst) -> # s1 = hub; s2 = console server
last_tm = misc.mswalltime()
last_data = ''
amount = 0
# Connect the sockets together.
s1_data = (data) ->
activity()
# record incoming activity (don't do this in other direction, since that shouldn't keep session alive)
if not s2.writable
s1.removeListener('data', s1_data)
else
s2.write(data)
s2_data = (data) ->
if not s1.writable
s2.removeListener('data', s2_data)
else
if max_burst?
tm = misc.mswalltime()
if tm - last_tm >= 20
if amount < 0 # was truncating
try
x = last_data.slice(Math.max(0, last_data.length - Math.floor(max_burst/4)))
catch e
# I don't know why the above sometimes causes an exception, but it *does* in
# Buffer.slice, which is a serious problem. Best to ignore that data.
x = ''
data = "]" + x + data
#console.log("max_burst: reset")
amount = 0
last_tm = tm
#console.log("max_burst: amount=#{amount}")
if amount >= max_burst
last_data = data
data = data.slice(0,Math.floor(max_burst/4)) + "[..."
amount = -1 # so do only once every 20ms.
setTimeout((()=>s2_data('')), 25) # write nothing in 25ms just to make sure ...] appears.
else if amount < 0
last_data += data
setTimeout((()=>s2_data('')), 25) # write nothing in 25ms just to make sure ...] appears.
else
amount += data.length
# Never push more than max_burst characters at once to hub, since that could overwhelm
s1.write(data)
s1.on('data', s1_data)
s2.on('data', s2_data)
###############################################
# Sage sessions
###############################################
## WARNING! I think this is no longer used! It was used for my first (few)
## approaches to worksheets.
class SageSessions
constructor: () ->
@_sessions = {}
session_exists: (session_uuid) =>
return @_sessions[session_uuid]?
terminate_session: (session_uuid, cb) =>
S = @_sessions[session_uuid]
if not S?
cb()
else
winston.debug("terminate sage session -- STUB!")
cb()
update_session_status: (session) =>
# Check if the process corresponding to the given session is
# *actually* running/healthy (?). Just because the socket hasn't sent
# an "end" doesn't mean anything.
try
process.kill(session.desc.pid, 0)
# process is running -- leave status as is.
catch e
# process is not running
session.status = 'done'
get_session: (uuid) =>
session = @_sessions[uuid]
if session?
@update_session_status(session)
return session
# Connect to (if 'running'), restart (if 'dead'), or create (if
# non-existing) the Sage session with mesg.session_uuid.
connect: (client_socket, mesg) =>
session = @get_session mesg.session_uuid
if session? and session.status == 'running'
winston.debug("sage sessions: connect to the running session with id #{mesg.session_uuid}")
client_socket.write_mesg('json', session.desc)
plug(client_socket, session.socket)
session.clients.push(client_socket)
else
winston.debug("make a connection to a new sage session.")
get_port 'sage', (err, port) =>
winston.debug("Got sage server port = #{port}")
if err
winston.debug("can't determine sage server port; probably sage server not running")
client_socket.write_mesg('json', message.error(id:mesg.id, error:"problem determining port of sage server."))
else
@_new_session(client_socket, mesg, port)
_new_session: (client_socket, mesg, port, retries) =>
winston.debug("_new_session: creating new sage session (retries=#{retries})")
# Connect to port, send mesg, then hook sockets together.
misc_node.connect_to_locked_socket
port : port
token : secret_token
cb : (err, sage_socket) =>
if err
winston.debug("_new_session: sage session denied connection: #{err}")
forget_port('sage')
if not retries? or retries <= 5
if not retries?
retries = 1
else
retries += 1
try_again = () =>
@_new_session(client_socket, mesg, port, retries)
setTimeout(try_again, 1000)
else
# give up.
client_socket.write_mesg('json', message.error(id:mesg.id, error:"local_hub -- Problem connecting to Sage server. -- #{err}"))
return
else
winston.debug("Successfully unlocked a sage session connection.")
winston.debug("Next, request a Sage session from sage_server.")
misc_node.enable_mesg(sage_socket)
sage_socket.write_mesg('json', message.start_session(type:'sage'))
winston.debug("Waiting to read one JSON message back, which will describe the session.")
sage_socket.once 'mesg', (type, desc) =>
winston.debug("Got message back from Sage server: #{json(desc)}")
client_socket.write_mesg('json', desc)
plug(client_socket, sage_socket)
# Finally, this socket is now connected to a sage server and ready to execute code.
@_sessions[mesg.session_uuid] =
socket : sage_socket
desc : desc
status : 'running'
clients : [client_socket]
project_id : mesg.project_id
sage_socket.on 'end', () =>
# this is *NOT* dependable, since a segfaulted process -- and sage does that -- might
# not send a FIN.
winston.debug("sage_socket: session #{mesg.session_uuid} terminated.")
session = @_sessions[mesg.session_uuid]
# TODO: should we close client_socket here?
if session?
winston.debug("sage_socket: setting status of session #{mesg.session_uuid} to terminated.")
session.status = 'done'
# Return object that describes status of all Sage sessions
info: (project_id) =>
obj = {}
for id, session of @_sessions
if session.project_id == project_id
obj[id] =
desc : session.desc
status : session.status
return obj
sage_sessions = new SageSessions()
############################################################################
#
# Differentially-Synchronized document editing sessions
#
# Here's a map YOU ARE HERE
# |
# [client]s.. ---> [hub] ---> [local hub] <--- [hub] <--- [client]s...
# |
# \|/
# [a file on disk]
#
#############################################################################
# The "live upstream content" of DiffSyncFile_client is the actual file on disk.
# # TODO: when applying diffs, we could use that the file is random access. This is not done yet!
class DiffSyncFile_server extends diffsync.DiffSync
constructor:(@cm_session, cb) ->
@path = @cm_session.path
no_master = undefined
stats_path = undefined
stats = undefined
file = undefined
async.series([
(cb) =>
fs.stat @path, (_no_master, _stats_path) =>
no_master = _no_master
stats_path = _stats_path
cb()
(cb) =>
if no_master
# create
file = @path
misc_node.ensure_containing_directory_exists @path, (err) =>
if err
cb(err)
else
fs.open file, 'w', (err, fd) =>
if err
cb(err)
else
fs.close fd, cb
else
# master exists
file = @path
stats = stats_path
cb()
(cb) =>
e = check_file_size(stats?.size)
if e
cb(e)
return
fs.readFile file, (err, data) =>
if err
cb(err); return
# NOTE: we immediately delete \r's since the client editor (Codemirror) immediately deletes them
# on editor creation; if we don't delete them, all sync attempts fail and hell is unleashed.
@init(doc:data.toString().replace(/\r/g,''), id:"file_server")
# winston.debug("got new file contents = '#{@live}'")
@_start_watching_file()
cb(err)
], (err) => cb(err, @live))
kill: () =>
if @_autosave?
clearInterval(@_autosave)
# be sure to clean this up, or -- after 11 times -- it will suddenly be impossible for
# the user to open a file without restarting their project server! (NOT GOOD)
fs.unwatchFile(@path, @_watcher)
_watcher: (event) =>
winston.debug("watch: file '#{@path}' modified.")
if not @_do_watch
winston.debug("watch: skipping read because watching is off.")
return
@_stop_watching_file()
async.series([
(cb) =>
fs.stat @path, (err, stats) =>
if err
cb(err)
else
cb(check_file_size(stats.size))
(cb) =>
fs.readFile @path, (err, data) =>
if err
cb(err)
else
@live = data.toString().replace(/\r/g,'') # NOTE: we immediately delete \r's (see above).
@cm_session.sync_filesystem(cb)
], (err) =>
if err
winston.debug("watch: file '#{@path}' error -- #{err}")
@_start_watching_file()
)
_start_watching_file: () =>
if @_do_watch?
@_do_watch = true
return
@_do_watch = true
winston.debug("watching #{@path}")
fs.watchFile(@path, @_watcher)
_stop_watching_file: () =>
@_do_watch = false
# NOTE: I tried using fs.watch as below, but *DAMN* -- even on
# Linux 12.10 -- fs.watch in Node.JS totally SUCKS. It led to
# file corruption, weird flakiness and errors, etc. fs.watchFile
# above, on the other hand, is great for my needs (which are not
# for immediate sync).
# _start_watching_file0: () =>
# winston.debug("(re)start watching...")
# if @_fs_watcher?
# @_stop_watching_file()
# try
# @_fs_watcher = fs.watch(@path, @_watcher)
# catch e
# setInterval(@_start_watching_file, 15000)
# winston.debug("WARNING: failed to start watching '#{@path}' -- will try later -- #{e}")
# _stop_watching_file0: () =>
# if @_fs_watcher?
# @_fs_watcher.close()
# delete @_fs_watcher
snapshot: (cb) => # cb(err, snapshot of live document)
cb(false, @live)
_apply_edits_to_live: (edits, cb) =>
if edits.length == 0
cb(); return
@_apply_edits edits, @live, (err, result) =>
if err
cb(err)
else
if result == @live
cb() # nothing to do
else
@live = result
@write_to_disk(cb)
write_to_disk: (cb) =>
@_stop_watching_file()
ensure_containing_directory_exists @path, (err) =>
if err
cb?(err); return
fs.writeFile @path, @live, (err) =>
@_start_watching_file()
cb?(err)
# The live content of DiffSyncFile_client is our in-memory buffer.
class DiffSyncFile_client extends diffsync.DiffSync
constructor:(@server) ->
super(doc:@server.live, id:"file_client")
# Connect the two together
@connect(@server)
@server.connect(@)
# The CodeMirrorDiffSyncHub class represents a downstream
# remote client for this local hub. There may be dozens of these.
# The local hub has no upstream server, except the on-disk file itself.
#
# NOTE: These have *nothing* a priori to do with CodeMirror -- the name is
# historical and should be changed. TODO.
#
class CodeMirrorDiffSyncHub
constructor : (@socket, @session_uuid, @client_id) ->
write_mesg: (event, obj) =>
if not obj?
obj = {}
obj.session_uuid = @session_uuid
mesg = message['codemirror_' + event](obj)
mesg.client_id = @client_id
@socket.write_mesg 'json', mesg
recv_edits : (edit_stack, last_version_ack, cb) =>
@write_mesg 'diffsync',
id : @current_mesg_id
edit_stack : edit_stack
last_version_ack : last_version_ack
cb?()
sync_ready: () =>
@write_mesg('diffsync_ready')
class CodeMirrorSession
constructor: (mesg, cb) ->
@path = mesg.path
@session_uuid = mesg.session_uuid
@_sage_output_cb = {}
@_sage_output_to_input_id = {}
# The downstream clients of this local hub -- these are global hubs that proxy requests on to browser clients
@diffsync_clients = {}
async.series([
(cb) =>
# if File doesn't exist, try to create it.
fs.exists @path, (exists) =>
if exists
cb()
else
fs.open @path,'w', (err, fd) =>
if err
cb(err)
else
fs.close(fd, cb)
(cb) =>
if @path.indexOf('.snapshots/') != -1
@readonly = true
cb()
else
misc_node.is_file_readonly
path : @path
cb : (err, readonly) =>
@readonly = readonly
cb(err)
(cb) =>
# If this is a non-readonly sagews file, create corresponding sage session.
if not @readonly and misc.filename_extension_notilde(@path) == 'sagews'
@process_new_content = @sage_update
@sage_socket(cb)
else
cb()
(cb) =>
# The *actual* file on disk. It's important to create this
# after successfully getting the sage socket, since if we fail to
# get the sage socket we end up creating too many fs.watch's on this file...
@diffsync_fileserver = new DiffSyncFile_server @, (err, content) =>
if err
cb(err); return
@content = content
@diffsync_fileclient = new DiffSyncFile_client(@diffsync_fileserver)
# worksheet freshly loaded from disk -- now ensure no cells appear to be running
# except for the auto cells that we spin up running.
@sage_update(kill:true, auto:true)
@_set_content_and_sync()
cb()
], (err) => cb?(err, @))
##############################
# Sage execution related code
##############################
sage_socket: (cb) => # cb(err, socket)
if @_sage_socket?
try
process.kill(@_sage_socket.pid, 0)
# process is still running fine
cb(false, @_sage_socket)
return
catch e
# sage process is dead.
@_sage_socket = undefined
winston.debug("sage_socket: initalize the newly started sage process")
# If we've already loaded the worksheet, then ensure
# that no cells appear to be running. This is important
# because the worksheet file that we just loaded could have had some
# markup that cells are running.
if @diffsync_fileclient?
@sage_update(kill:true)
# Connect to the local Sage server.
get_sage_socket (err, socket) =>
if err
winston.debug("sage_socket: fail -- #{err}.")
cb(err)
else
winston.debug("sage_socket: successfully opened a Sage session for worksheet '#{@path}'")
@_sage_socket = socket
# Set path to be the same as the file.
mesg = message.execute_code
id : misc.uuid()
code : "os.chdir(salvus.data['path']);__file__=salvus.data['file']"
data : {path: misc.path_split(@path).head, file:abspath(@path)}
preparse : false
socket.write_mesg('json', mesg)
socket.on 'end', () =>
@_sage_socket = undefined
winston.debug("codemirror session #{@session_uuid} sage socket terminated.")
socket.on 'mesg', (type, mesg) =>
#winston.debug("sage session: received message #{type}, #{misc.to_json(mesg)}")
switch type
when 'blob'
sha1 = mesg.uuid
if @diffsync_clients.length == 0
error = 'no global hubs are connected to the local hub, so nowhere to send file'
winston.debug("codemirror session: got blob from sage session -- #{error}")
resp = message.save_blob
error : error
sha1 : sha1
socket.write_mesg('json', resp)
else
winston.debug("codemirror session: got blob from sage session -- forwarding to a random hub")
hub = misc.random_choice_from_obj(@diffsync_clients)
client_id = hub[0]; ds_client = hub[1]
mesg.client_id = client_id
ds_client.remote.socket.write_mesg('blob', mesg)
receive_save_blob_message
sha1 : sha1
cb : (resp) -> socket.write_mesg('json', resp)
## DEBUG -- for testing purposes -- simulate the response message
## handle_save_blob_message(message.save_blob(sha1:sha1,ttl:1000))
when 'json'
# First check for callbacks (e.g., used in interact and things where the
# browser directly asks to evaluate code in this session).
c = @_sage_output_cb[mesg.id]
if c?
c(mesg)
if mesg.done
delete @_sage_output_cb[mesg.id]
return
# Handle code execution in browser messages
if mesg.event == 'execute_javascript'
# winston.debug("got execute_javascript message from sage session #{json(mesg)}")
# Wrap and forward it on as a broadcast message.
mesg.session_uuid = @session_uuid
bcast = message.codemirror_bcast
session_uuid : @session_uuid
mesg : mesg
@client_bcast(undefined, bcast)
return
# Finally, handle output messages
m = {}
for x, y of mesg
if x != 'id' and x != 'event' # the event is always "output"
if x == 'done' # don't bother with done=false
if y
m[x] = y
else
m[x] = y
#winston.debug("sage --> local_hub: '#{json(mesg)}'")
before = @content
@sage_output_mesg(mesg.id, m)
if before != @content
@_set_content_and_sync()
# If we've already loaded the worksheet, submit all auto cells to be evaluated.
if @diffsync_fileclient?
@sage_update(auto:true)
cb(false, @_sage_socket)
_set_content_and_sync: () =>
if @set_content(@content)
# Content actually changed, so suggest to all connected clients to sync.
for id, ds_client of @diffsync_clients
ds_client.remote.sync_ready()
sage_execute_cell: (id) =>
winston.debug("exec request for cell with id: '#{id}'")
@sage_remove_cell_flag(id, diffsync.FLAGS.execute)
{code, output_id} = @sage_initialize_cell_for_execute(id)
winston.debug("exec code '#{code}'; output id='#{output_id}'")
#if diffsync.FLAGS.auto in @sage_get_cell_flagstring(id) and 'auto' not in code
#@sage_remove_cell_flag(id, diffsync.FLAGS.auto)
@set_content(@content)
if code != ""
@_sage_output_to_input_id[output_id] = id
winston.debug("start running -- #{id}")
# Change the cell to "running" mode - this doesn't generate output, so we must explicit force clients
# to sync.
@sage_set_cell_flag(id, diffsync.FLAGS.running)
@sage_set_cell_flag(id, diffsync.FLAGS.this_session)
@_set_content_and_sync()
@sage_socket (err, socket) =>
if err
winston.debug("Error getting sage socket: #{err}")
@sage_output_mesg(output_id, {stderr: "Error getting sage socket (unable to execute code): #{err}"})
@sage_remove_cell_flag(id, diffsync.FLAGS.running)
return
winston.debug("Sending execute message to sage socket.")
socket.write_mesg 'json',
message.execute_code
id : output_id
cell_id : id # extra info -- which cell is running
code : code
preparse : true
# Execute code in the Sage session associated to this sync'd editor session
sage_execute_code: (client_socket, mesg) =>
#winston.debug("sage_execute_code '#{misc.to_json(mesg)}")
client_id = mesg.client_id
@_sage_output_cb[mesg.id] = (resp) =>
resp.client_id = client_id
#winston.debug("sage_execute_code -- got output: #{misc.to_json(resp)}")
client_socket.write_mesg('json', resp)
@sage_socket (err, socket) =>
#winston.debug("sage_execute_code: #{misc.to_json(err)}, #{socket}")
if err
#winston.debug("Error getting sage socket: #{err}")
resp = message.output(stderr: "Error getting sage socket (unable to execute code): #{err}", done:true)
client_socket.write_mesg('json', resp)
else
#winston.debug("sage_execute_code: writing request message -- #{misc.to_json(mesg)}")
mesg.event = 'execute_code' # event that sage session understands
socket.write_mesg('json', mesg)
sage_raw_input: (client_socket, mesg) =>
winston.debug("sage_raw_input '#{misc.to_json(mesg)}")
@sage_socket (err, socket) =>
if err
winston.debug("sage_raw_input: error getting sage socket -- #{err}")
else
socket.write_mesg('json', mesg)
sage_call: (opts) =>
opts = defaults opts,
mesg : required
cb : undefined
f = (resp) =>
opts.cb?(false, resp)
delete @_sage_output_cb[opts.mesg.id] # exactly one response
@sage_socket (err, socket) =>
if err
opts.cb?("error getting sage socket -- #{err}")
else
@_sage_output_cb[opts.mesg.id] = f
socket.write_mesg('json', opts.mesg)
sage_introspect:(client_socket, mesg) =>
mesg.event = 'introspect' # event that sage session understand
@sage_call
mesg : mesg
cb : (err, resp) =>
if err
resp = message.error(error:"Error getting sage socket (unable to introspect): #{err}")
client_socket.write_mesg('json', resp)
else
client_socket.write_mesg('json', resp)
send_signal_to_sage_session: (client_socket, mesg) =>
if @_sage_socket?
process_kill(@_sage_socket.pid, mesg.signal)
if mesg.id? and client_socket?
client_socket.write_mesg('json', message.signal_sent(id:mesg.id))
sage_update: (opts={}) =>
opts = defaults opts,
kill : false # if true, remove all running flags and all this_session flags
auto : false # if true, run all cells that have the auto flag set
if not @content? # document not initialized
return
# Here we:
# - scan the string @content for execution requests.
# - also, if we see a cell UUID that we've seen already, we randomly generate
# a new cell UUID; clients can annoyingly generate non-unique UUID's (e.g., via
# cut and paste) so we fix that.
winston.debug("sage_update")#: opts=#{misc.to_json(opts)}")
i = 0
prev_ids = {}
z = 0
while true
z += 1
if z > 5000
winston.debug("sage_update: ERROR -- hit a possible infinite loop; opts=#{misc.to_json(opts)}")
break
i = @content.indexOf(diffsync.MARKERS.cell, i)
if i == -1
break
j = @content.indexOf(diffsync.MARKERS.cell, i+1)
if j == -1
break # corrupt and is the last one, so not a problem.
id = @content.slice(i+1,i+37)
if misc.is_valid_uuid_string(id)
# if id isn't valid -- due to document corruption or a bug, just skip it rather than get into all kinds of trouble.
# TODO: repair.
if prev_ids[id]?
# oops, repeated "unique" id, so fix it.
id = uuid.v4()
@content = @content.slice(0,i+1) + id + @content.slice(i+37)
# Also, if 'r' in the flags for this cell, remove it since it
# can't possibly be already running (given the repeat).
flags = @content.slice(i+37, j)
if diffsync.FLAGS.running in flags
new_flags = ''
for t in flags
if t != diffsync.FLAGS.running
new_flags += t
@content = @content.slice(0,i+37) + new_flags + @content.slice(j)
prev_ids[id] = true
flags = @content.slice(i+37, j)
if opts.kill or opts.auto
if opts.kill
# worksheet process just killed, so clear certain flags.
new_flags = ''
for t in flags
if t != diffsync.FLAGS.running and t != diffsync.FLAGS.this_session
new_flags += t
#winston.debug("sage_update: kill=true, so changing flags from '#{flags}' to '#{new_flags}'")
if flags != new_flags
@content = @content.slice(0,i+37) + new_flags + @content.slice(j)
if opts.auto and diffsync.FLAGS.auto in flags
# worksheet process being restarted, so run auto cells
@sage_remove_cell_flag(id, diffsync.FLAGS.auto)
@sage_execute_cell(id)
else if diffsync.FLAGS.execute in flags
# normal execute
@sage_execute_cell(id)
# set i to next position after end of line that contained flag we just considered;
# above code may have added flags to this line (but won't have added anything before this line).
i = @content.indexOf('\n',j + 1)
if i == -1
break
sage_output_mesg: (output_id, mesg) =>
cell_id = @_sage_output_to_input_id[output_id]
#winston.debug("output_id=#{output_id}; cell_id=#{cell_id}; map=#{misc.to_json(@_sage_output_to_input_id)}")
if mesg.hide?
# Hide a single component (also, do not record the message itself in the
# document, just its impact).
flag = undefined
if mesg.hide == 'input'
flag = diffsync.FLAGS.hide_input
else if mesg.hide == 'output'
flag = diffsync.FLAGS.hide_output
if flag?
@sage_set_cell_flag(cell_id, flag)
else
winston.debug("invalid hide component: '#{mesg.hide}'")
delete mesg.hide
if mesg.show?
# Show a single component of cell.
flag = undefined
if mesg.show == 'input'
flag = diffsync.FLAGS.hide_input
else if mesg.show == 'output'
flag = diffsync.FLAGS.hide_output
if flag?
@sage_remove_cell_flag(cell_id, flag)
else
winston.debug("invalid hide component: '#{mesg.hide}'")
delete mesg.show
if mesg.auto?
# set or unset whether or not cell is automatically executed on startup of worksheet
if mesg.auto
@sage_set_cell_flag(cell_id, diffsync.FLAGS.auto)
else
@sage_remove_cell_flag(cell_id, diffsync.FLAGS.auto)
if mesg.done? and mesg.done and cell_id?
@sage_remove_cell_flag(cell_id, diffsync.FLAGS.running)
delete @_sage_output_to_input_id[output_id]
delete mesg.done # not needed
if /^\s\s*/.test(mesg.stdout) # final whitespace not needed for proper display
delete mesg.stdout
if /^\s\s*/.test(mesg.stderr)
delete mesg.stderr
if misc.is_empty_object(mesg)
return
if mesg.once? and mesg.once
# only javascript is define once=True
if mesg.javascript?
msg = message.execute_javascript
session_uuid : @session_uuid
code : mesg.javascript.code
coffeescript : mesg.javascript.coffeescript
obj : mesg.obj
cell_id : cell_id
bcast = message.codemirror_bcast
session_uuid : @session_uuid
mesg : msg
@client_bcast(undefined, bcast)
return # once = do *not* want to record this message in the output stream.
i = @content.indexOf(diffsync.MARKERS.output + output_id)
if i == -1
# no such output cell anymore -- ignore (?) -- or we could make such a cell...?
winston.debug("WORKSHEET: no such output cell (ignoring) -- #{output_id}")
return
n = @content.indexOf('\n', i)
if n == -1
winston.debug("WORKSHEET: output cell corrupted (ignoring) -- #{output_id}")
return
if mesg.clear?
# delete all output server side
k = i + (diffsync.MARKERS.output + output_id).length + 1
@content = @content.slice(0, k) + @content.slice(n)
return
if mesg.delete_last?
k = @content.lastIndexOf(diffsync.MARKERS.output, n-2)
@content = @content.slice(0, k+1) + @content.slice(n)
return
@content = @content.slice(0,n) + JSON.stringify(mesg) + diffsync.MARKERS.output + @content.slice(n)
sage_find_cell_meta: (id, start) =>
i = @content.indexOf(diffsync.MARKERS.cell + id, start)
j = @content.indexOf(diffsync.MARKERS.cell, i+1)
if j == -1
return undefined
return {start:i, end:j}
sage_get_cell_flagstring: (id) =>
pos = @sage_find_cell_meta(id)
return @content.slice(pos.start+37, pos.end)
sage_set_cell_flagstring: (id, flags) =>
pos = @sage_find_cell_meta(id)
if pos?
@content = @content.slice(0, pos.start+37) + flags + @content.slice(pos.end)
sage_set_cell_flag: (id, flag) =>
s = @sage_get_cell_flagstring(id)
if flag not in s
@sage_set_cell_flagstring(id, flag + s)
sage_remove_cell_flag: (id, flag) =>
s = @sage_get_cell_flagstring(id)
if flag in s
s = s.replace(new RegExp(flag, "g"), "")
@sage_set_cell_flagstring(id, s)
sage_initialize_cell_for_execute: (id, start) => # start is optional, but can speed finding cell
# Initialize the line of the document for output for the cell with given id.
# We do this by finding where that cell starts, then searching for the start
# of the next cell, deleting any output lines in between, and placing one new line
# for output. This function returns
# - output_id: a newly created id that identifies the new output line.
# - code: the string of code that will be executed by Sage.
# Or, it returns undefined if there is no cell with this id.
cell_start = @content.indexOf(diffsync.MARKERS.cell + id, start)
if cell_start == -1
# there is now no cell with this id.
return
code_start = @content.indexOf(diffsync.MARKERS.cell, cell_start+1)
if code_start == -1
# TODO: cell is mangled: would need to fix...?
return
newline = @content.indexOf('\n', cell_start) # next newline after cell_start
next_cell = @content.indexOf(diffsync.MARKERS.cell, code_start+1)
if newline == -1
# At end of document: append a newline to end of document; this is where the output will go.
# This is a very common special case; it's what we would get typing "2+2[shift-enter]"
# into a blank worksheet.
output_start = @content.length # position where the output will start
# Put some extra newlines in, since it is hard to put input at the bottom of the screen.
@content += '\n\n\n\n\n'
winston.debug("Add a new input cell at the very end (which will be after the output).")
else
while true
next_cell_start = @content.indexOf(diffsync.MARKERS.cell, newline)
if next_cell_start == -1
# This is the last cell, so we end the cell after the last line with no whitespace.
next_cell_start = @content.search(/\s+$/)
if next_cell_start == -1
next_cell_start = @content.length+1
@content += '\n\n\n\n\n'
else
while next_cell_start < @content.length and @content[next_cell_start]!='\n'
next_cell_start += 1
if @content[next_cell_start]!='\n'
@content += '\n\n\n\n\n'
next_cell_start += 1
output = @content.indexOf(diffsync.MARKERS.output, newline)
if output == -1 or output > next_cell_start
# no more output lines to delete
output_start = next_cell_start # this is where the output line will start
break
else
# delete the line of output we just found
output_end = @content.indexOf('\n', output+1)
@content = @content.slice(0, output) + @content.slice(output_end+1)
code = @content.slice(code_start+1, output_start)
output_id = uuid.v4()
if output_start > 0 and @content[output_start-1] != '\n'
output_insert = '\n'
else
output_insert = ''
output_insert += diffsync.MARKERS.output + output_id + diffsync.MARKERS.output + '\n'
if next_cell == -1
# There is no next cell.
output_insert += diffsync.MARKERS.cell + uuid.v4() + diffsync.MARKERS.cell + '\n'
@content = @content.slice(0, output_start) + output_insert + @content.slice(output_start)
return {code:code.trim(), output_id:output_id}
##############################
kill: () =>
# Put any cleanup here...
winston.debug("Killing session #{@session_uuid}")
@sync_filesystem () =>
@diffsync_fileserver.kill()
# TODO: Are any of these deletes needed? I don't know.
delete @content
delete @diffsync_fileclient
delete @diffsync_fileserver
if @_sage_socket?
# send FIN packet so that Sage process may terminate naturally
@_sage_socket.end()
# ... then, brutally kill it if need be (a few seconds later). :-)
if @_sage_socket.pid?
setTimeout( (() => process_kill(@_sage_socket.pid, 9)), 3000 )
set_content: (value) =>
@is_active = true
changed = false
if @content != value
@content = value
changed = true
if @diffsync_fileclient.live != value
@diffsync_fileclient.live = value
changed = true
for id, ds_client of @diffsync_clients
if ds_client.live != value
changed = true
ds_client.live = value
return changed
client_bcast: (socket, mesg) =>
@is_active = true
winston.debug("client_bcast: #{json(mesg)}")
# Forward this message on to all global hubs except the
# one that just sent it to us...
client_id = mesg.client_id
for id, ds_client of @diffsync_clients
if client_id != id
mesg.client_id = id
#winston.debug("BROADCAST: sending message from hub with socket.id=#{socket?.id} to hub with socket.id = #{id}")
ds_client.remote.socket.write_mesg('json', mesg)
client_diffsync: (socket, mesg) =>
@is_active = true
write_mesg = (event, obj) ->
if not obj?
obj = {}
obj.id = mesg.id
socket.write_mesg 'json', message[event](obj)
# Message from some client reporting new edits, thus initiating a sync.
ds_client = @diffsync_clients[mesg.client_id]
if not ds_client?
write_mesg('error', {error:"client #{mesg.client_id} not registered for synchronization"})
return
if @_client_sync_lock # or Math.random() <= .5 # (for testing)
winston.debug("client_diffsync hit a click_sync_lock -- send retry message back")
write_mesg('error', {error:"retry"})
return
if @_filesystem_sync_lock
if @_filesystem_sync_lock < new Date()
@_filesystem_sync_lock = false
else
winston.debug("client_diffsync hit a filesystem_sync_lock -- send retry message back")
write_mesg('error', {error:"retry"})
return
@_client_sync_lock = true
before = @content
ds_client.recv_edits mesg.edit_stack, mesg.last_version_ack, (err) => # TODO: why is this err ignored?
@set_content(ds_client.live)
@_client_sync_lock = false
@process_new_content?()
# Send back our own edits to the global hub.
ds_client.remote.current_mesg_id = mesg.id # used to tag the return message
ds_client.push_edits (err) =>
if err
winston.debug("CodeMirrorSession -- client push_edits returned -- #{err}")
else
changed = (before != @content)
if changed
# We also suggest to other clients to update their state.
@tell_clients_to_update(mesg.client_id)
@update_revision_tracking()
tell_clients_to_update: (exclude) =>
for id, ds_client of @diffsync_clients
if exclude != id
ds_client.remote.sync_ready()
sync_filesystem: (cb) =>
@is_active = true
if @_client_sync_lock # or Math.random() <= .5 # (for testing)
winston.debug("sync_filesystem -- hit client sync lock")
cb?("cannot sync with filesystem while syncing with clients")
return
if @_filesystem_sync_lock
if @_filesystem_sync_lock < new Date()
@_filesystem_sync_lock = false
else
winston.debug("sync_filesystem -- hit filesystem sync lock")
cb?("cannot sync with filesystem; already syncing")
return
before = @content
if not @diffsync_fileclient?
cb?("filesystem sync object (@diffsync_fileclient) no longer defined")
return
@_filesystem_sync_lock = expire_time(10) # lock expires in 10 seconds no matter what -- uncaught exception could require this
@diffsync_fileclient.sync (err) =>
if err
# Example error: 'reset -- checksum mismatch (29089 != 28959)'
winston.debug("@diffsync_fileclient.sync -- returned an error -- #{err}")
@diffsync_fileserver.kill() # stop autosaving and watching files
# Completely recreate diffsync file connection and try to sync once more.
@diffsync_fileserver = new DiffSyncFile_server @, (err, ignore_content) =>
if err
winston.debug("@diffsync_fileclient.sync -- making new server failed: #{err}")
@_filesystem_sync_lock = false
cb?(err); return
@diffsync_fileclient = new DiffSyncFile_client(@diffsync_fileserver)
@diffsync_fileclient.live = @content
@diffsync_fileclient.sync (err) =>
if err
winston.debug("@diffsync_fileclient.sync -- making server worked but re-sync failed -- #{err}")
@_filesystem_sync_lock = false
cb?("codemirror fileclient sync error -- '#{err}'")
else
@_filesystem_sync_lock = false
cb?()
return
if @diffsync_fileclient.live != @content
@set_content(@diffsync_fileclient.live)
# recommend all clients sync
for id, ds_client of @diffsync_clients
ds_client.remote.sync_ready()
@_filesystem_sync_lock = false
cb?()
add_client: (socket, client_id) =>
@is_active = true
ds_client = new diffsync.DiffSync(doc:@content)
ds_client.connect(new CodeMirrorDiffSyncHub(socket, @session_uuid, client_id))
@diffsync_clients[client_id] = ds_client
winston.debug("CodeMirrorSession(#{@path}).add_client(client_id=#{client_id}) -- now we have #{misc.len(@diffsync_clients)} clients.")
# Ensure we do not broadcast to a hub if it has already disconnected.
socket.on 'end', () =>
winston.debug("DISCONNECT: socket connection #{socket.id} from global hub disconected.")
delete @diffsync_clients[client_id]
remove_client: (socket, client_id) =>
delete @diffsync_clients[client_id]
write_to_disk: (socket, mesg) =>
@is_active = true
winston.debug("write_to_disk: #{json(mesg)} -- calling sync_filesystem")
@sync_filesystem (err) =>
if err
resp = message.error(id:mesg.id, error:"Error writing file '#{@path}' to disk -- #{err}")
else
resp = message.codemirror_wrote_to_disk(id:mesg.id, hash:misc.hash_string(@content))
socket.write_mesg('json', resp)
read_from_disk: (socket, mesg) =>
async.series([
(cb) =>
fs.stat (err, stats) =>
if err
cb(err)
else
cb(check_file_size(stats.size))
(cb) =>
fs.readFile @path, (err, data) =>
if err
cb("Error reading file '#{@path}' from disk -- #{err}")
else
value = data.toString()
if value != @content
@set_content(value)
# Tell the global hubs that now might be a good time to do a sync.
for id, ds of @diffsync_clients
ds.remote.sync_ready()
cb()
], (err) =>
if err
socket.write_mesg('json', message.error(id:mesg.id, error:err))
else
socket.write_mesg('json', message.success(id:mesg.id))
)
get_content: (socket, mesg) =>
@is_active = true
socket.write_mesg('json', message.codemirror_content(id:mesg.id, content:@content))
# enable or disable tracking all revisions of the document
revision_tracking: (socket, mesg) =>
winston.debug("revision_tracking for #{@path}: #{mesg.enable}")
d = (m) -> winston.debug("revision_tracking for #{@path}: #{m}")
if mesg.enable
d("enable it")
if @revision_tracking_doc?
d("already enabled")
# already enabled
socket.write_mesg('json', message.success(id:mesg.id))
else
if @readonly
# nothing to do -- silently don't enable (is this a good choice?)
socket.write_mesg('json', message.success(id:mesg.id))
return
# need to enable
d("need to enable")
codemirror_sessions.connect
mesg :
path : revision_tracking_path(@path)
project_id : INFO.project_id # todo -- won't need in long run
cb : (err, session) =>
d("got response -- #{err}")
if err
socket.write_mesg('json', message.error(id:mesg.id, error:err))
else
@revision_tracking_doc = session
socket.write_mesg('json', message.success(id:mesg.id))
@update_revision_tracking()
else
d("disable it")
delete @revision_tracking_doc
socket.write_mesg('json', message.success(id:mesg.id))
# If we are tracking the revision history of this file, add a new entry in that history.
# TODO: add user responsibile for this change as input to this function and as
# a field in the entry object below. NOTE: Be sure to include "changing the file on disk"
# as one of the users, which is *NOT* defined by an account_id.
update_revision_tracking: () =>
if not @revision_tracking_doc?
return
winston.debug("update revision tracking data - #{@path}")
# @revision_tracking_doc.HEAD is the last version of the document we're tracking, as a string.
# In particular, it is NOT in JSON format.
if not @revision_tracking_doc.HEAD?
# Initialize HEAD from the file
if @revision_tracking_doc.content.length == 0
# brand new -- first time.
@revision_tracking_doc.HEAD = @content
@revision_tracking_doc.content = misc.to_json(@content)
else
# we have tracked this file before.
i = @revision_tracking_doc.content.indexOf('\n')
if i == -1
# weird special case: there's no history yet -- just the initial version
@revision_tracking_doc.HEAD = misc.from_json(@revision_tracking_doc.content)
else
# there is a potential longer history; this initial version is the first line:
@revision_tracking_doc.HEAD = misc.from_json(@revision_tracking_doc.content.slice(0,i))
if @revision_tracking_doc.HEAD != @content
# compute diff that transforms @revision_tracking_doc.HEAD to @content
patch = diffsync.dmp.patch_make(@content, @revision_tracking_doc.HEAD)
@revision_tracking_doc.HEAD = @content
# replace the file by new version that has first line equal to JSON version of HEAD,
# and rest all the patches, with our one new patch inserted at the front.
# TODO: redo without doing a split for efficiency.
i = @revision_tracking_doc.content.indexOf('\n')
entry = {patch:diffsync.compress_patch(patch), time:new Date() - 0}
@revision_tracking_doc.content = misc.to_json(@content) + '\n' + \
misc.to_json(entry) + \
(if i != -1 then @revision_tracking_doc.content.slice(i) else "")
# now tell everybody
@revision_tracking_doc._set_content_and_sync()
# save the revision tracking file to disk (but not too frequently)
if not @revision_tracking_save_timer?
f = () =>
delete @revision_tracking_save_timer
@revision_tracking_doc.sync_filesystem()
@revision_tracking_save_timer = setInterval(f, REVISION_TRACKING_SAVE_INTERVAL)
# Collection of all CodeMirror sessions hosted by this local_hub.
class CodeMirrorSessions
constructor: () ->
@_sessions = {by_uuid:{}, by_path:{}, by_project:{}}
connect: (opts) =>
opts = defaults opts,
client_socket : undefined
mesg : required # event of type codemirror_get_session
cb : undefined # cb?(err, session)
mesg = opts.mesg
finish = (session) ->
if not opts.client_socket?
return
session.add_client(opts.client_socket, mesg.client_id)
opts.client_socket.write_mesg 'json', message.codemirror_session
id : mesg.id,
session_uuid : session.session_uuid
path : session.path
content : session.content
readonly : session.readonly
if mesg.session_uuid?
session = @_sessions.by_uuid[mesg.session_uuid]
if session?
finish(session)
opts.cb?(undefined, session)
return
if mesg.path?
session = @_sessions.by_path[mesg.path]
if session?
finish(session)
opts.cb?(undefined, session)
return
mesg.session_uuid = uuid.v4()
new CodeMirrorSession mesg, (err, session) =>
if err
opts.client_socket?.write_mesg('json', message.error(id:mesg.id, error:err))
opts.cb?(err)
else
@add_session_to_cache
session : session
project_id : mesg.project_id
timeout : 3600 # time in seconds (or undefined to not use timer)
finish(session)
opts.cb?(undefined, session)
add_session_to_cache: (opts) =>
opts = defaults opts,
session : required
project_id : undefined
timeout : undefined # or a time in seconds
winston.debug("Adding session #{opts.session.session_uuid} (of project #{opts.project_id}) to cache.")
@_sessions.by_uuid[opts.session.session_uuid] = opts.session
@_sessions.by_path[opts.session.path] = opts.session
if opts.project_id?
if not @_sessions.by_project[opts.project_id]?
@_sessions.by_project[opts.project_id] = {}
@_sessions.by_project[opts.project_id][opts.session.path] = opts.session
destroy = () =>
opts.session.kill()
delete @_sessions.by_uuid[opts.session.session_uuid]
delete @_sessions.by_path[opts.session.path]
x = @_sessions.by_project[opts.project_id]
if x?
delete x[opts.session.path]
if opts.timeout?
destroy_if_inactive = () =>
if not (opts.session.is_active? and opts.session.is_active)
winston.debug("Session #{opts.session.session_uuid} is inactive for #{opts.timeout} seconds; killing.")
destroy()
else
opts.session.is_active = false # it must be changed by the session before the next timer.
# We use setTimeout instead of setInterval, because we want to *ensure* that the
# checks are spaced out over at *least* opts.timeout time.
winston.debug("Starting a new activity check timer for session #{opts.session.session_uuid}.")
setTimeout(destroy_if_inactive, opts.timeout*1000)
setTimeout(destroy_if_inactive, opts.timeout*1000)
# Return object that describes status of CodeMirror sessions for a given project
info: (project_id) =>
obj = {}
X = @_sessions.by_project[project_id]
if X?
for path, session of X
obj[session.session_uuid] = {path : session.path}
return obj
handle_mesg: (client_socket, mesg) =>
winston.debug("CodeMirrorSessions.handle_mesg: '#{json(mesg)}'")
if mesg.event == 'codemirror_get_session'
@connect
client_socket : client_socket
mesg : mesg
return
# all other message types identify the session only by the uuid.
session = @_sessions.by_uuid[mesg.session_uuid]
if not session?
winston.debug("codemirror.handle_mesg -- Unknown CodeMirror session: #{mesg.session_uuid}.")
client_socket.write_mesg('json', message.error(id:mesg.id, error:"Unknown CodeMirror session: #{mesg.session_uuid}."))
return
switch mesg.event
when 'codemirror_diffsync'
session.client_diffsync(client_socket, mesg)
when 'codemirror_bcast'
session.client_bcast(client_socket, mesg)
when 'codemirror_write_to_disk'
session.write_to_disk(client_socket, mesg)
when 'codemirror_read_from_disk'
session.read_from_disk(client_socket, mesg)
when 'codemirror_get_content'
session.get_content(client_socket, mesg)
when 'codemirror_revision_tracking' # enable/disable revision_tracking
session.revision_tracking(client_socket, mesg)
when 'codemirror_execute_code'
session.sage_execute_code(client_socket, mesg)
when 'codemirror_introspect'
session.sage_introspect(client_socket, mesg)
when 'codemirror_send_signal'
session.send_signal_to_sage_session(client_socket, mesg)
when 'codemirror_disconnect'
session.remove_client(client_socket, mesg.client_id)
client_socket.write_mesg('json', message.success(id:mesg.id))
when 'codemirror_sage_raw_input'
session.sage_raw_input(client_socket, mesg)
else
client_socket.write_mesg('json', message.error(id:mesg.id, error:"unknown CodeMirror session event: #{mesg.event}."))
codemirror_sessions = new CodeMirrorSessions()
###############################################
# Connecting to existing session or making a
# new one.
###############################################
connect_to_session = (socket, mesg) ->
winston.debug("connect_to_session -- type='#{mesg.type}'")
switch mesg.type
when 'console'
console_sessions.connect(socket, mesg)
when 'sage'
sage_sessions.connect(socket, mesg)
else
err = message.error(id:mesg.id, error:"Unsupported session type '#{mesg.type}'")
socket.write_mesg('json', err)
###############################################
# Kill an existing session.
###############################################
terminate_session = (socket, mesg) ->
cb = (err) ->
if err
mesg = message.error(id:mesg.id, error:err)
socket.write_mesg('json', mesg)
sid = mesg.session_uuid
if console_sessions.session_exists(sid)
console_sessions.terminate_session(sid, cb)
else if sage_sessions.session_exists(sid)
sage_sessions.terminate_session(sid, cb)
else
cb()
###############################################
# Read and write individual files
###############################################
# Read a file located in the given project. This will result in an
# error if the readFile function fails, e.g., if the file doesn't
# exist or the project is not open. We then send the resulting file
# over the socket as a blob message.
#
# Directories get sent as a ".tar.bz2" file.
# TODO: should support -- 'tar', 'tar.bz2', 'tar.gz', 'zip', '7z'. and mesg.archive option!!!
#
read_file_from_project = (socket, mesg) ->
data = undefined
path = abspath(mesg.path)
is_dir = undefined
id = undefined
archive = undefined
stats = undefined
async.series([
(cb) ->
#winston.debug("Determine whether the path '#{path}' is a directory or file.")
fs.stat path, (err, _stats) ->
if err
cb(err)
else
stats = _stats
is_dir = stats.isDirectory()
cb()
(cb) ->
# make sure the file isn't too large
cb(check_file_size(stats.size))
(cb) ->
if is_dir
if mesg.archive != 'tar.bz2'
cb("The only supported directory archive format is tar.bz2")
return
target = temp.path(suffix:'.' + mesg.archive)
#winston.debug("'#{path}' is a directory, so archive it to '#{target}', change path, and read that file")
archive = mesg.archive
if path[path.length-1] == '/' # common nuisance with paths to directories
path = path.slice(0,path.length-1)
split = misc.path_split(path)
path = target
# same patterns also in project.coffee (TODO)
args = ["--exclude=.sagemathcloud*", '--exclude=.forever', '--exclude=.node*', '--exclude=.npm', '--exclude=.sage', '-jcf', target, split.tail]
#winston.debug("tar #{args.join(' ')}")
child_process.execFile 'tar', args, {cwd:split.head}, (err, stdout, stderr) ->
if err
winston.debug("Issue creating tarball: #{err}, #{stdout}, #{stderr}")
cb(err)
else
cb()
else
#winston.debug("It is a file.")
cb()
(cb) ->
#winston.debug("Read the file into memory.")
fs.readFile path, (err, _data) ->
data = _data
cb(err)
(cb) ->
#winston.debug("Compute hash of file.")
id = misc_node.uuidsha1(data)
winston.debug("Hash = #{id}")
cb()
# TODO
# (cb) ->
# winston.debug("Send hash of file to hub to see whether or not we really need to send the file itself; it might already be known.")
# cb()
# (cb) ->
# winston.debug("Get message back from hub -- do we send file or not?")
# cb()
(cb) ->
#winston.debug("Finally, we send the file as a blob back to the hub.")
socket.write_mesg 'json', message.file_read_from_project(id:mesg.id, data_uuid:id, archive:archive)
socket.write_mesg 'blob', {uuid:id, blob:data}
cb()
], (err) ->
if err and err != 'file already known'
socket.write_mesg 'json', message.error(id:mesg.id, error:err)
if is_dir
fs.exists path, (exists) ->
if exists
winston.debug("It was a directory, so remove the temporary archive '#{path}'.")
fs.unlink(path)
)
write_file_to_project = (socket, mesg) ->
data_uuid = mesg.data_uuid
path = abspath(mesg.path)
# Listen for the blob containing the actual content that we will write.
write_file = (type, value) ->
if type == 'blob' and value.uuid == data_uuid
socket.removeListener 'mesg', write_file
async.series([
(cb) ->
ensure_containing_directory_exists(path, cb)
(cb) ->
#winston.debug('writing the file')
fs.writeFile(path, value.blob, cb)
], (err) ->
if err
#winston.debug("error writing file -- #{err}")
socket.write_mesg 'json', message.error(id:mesg.id, error:err)
else
#winston.debug("wrote file '#{path}' fine")
socket.write_mesg 'json', message.file_written_to_project(id:mesg.id)
)
socket.on 'mesg', write_file
###############################################
# Printing an individual file to pdf
###############################################
print_sagews = (opts) ->
opts = defaults opts,
path : required
outfile : required
title : required
author : required
date : required
contents : required
extra_data : undefined # extra data that is useful for displaying certain things in the worksheet.
timeout : 90
cb : required
extra_data_file = undefined
args = [opts.path, '--outfile', opts.outfile, '--title', opts.title, '--author', opts.author,'--date', opts.date, '--contents', opts.contents]
async.series([
(cb) ->
if not opts.extra_data?
cb(); return
extra_data_file = temp.path() + '.json'
args.push('--extra_data_file')
args.push(extra_data_file)
# NOTE: extra_data is a string that is *already* in JSON format.
fs.writeFile(extra_data_file, opts.extra_data, cb)
(cb) ->
# run the converter script
misc_node.execute_code
command : "sagews2pdf.py"
args : args
err_on_exit : false
bash : false
timeout : opts.timeout
cb : cb
], (err) =>
if extra_data_file?
fs.unlink(extra_data_file) # no need to wait for completion before calling opts.cb
opts.cb(err)
)
print_to_pdf = (socket, mesg) ->
ext = misc.filename_extension(mesg.path)
if ext
pdf = "#{mesg.path.slice(0,mesg.path.length-ext.length)}pdf"
else
pdf = mesg.path + '.pdf'
async.series([
(cb) ->
switch ext
when 'sagews'
print_sagews
path : mesg.path
outfile : pdf
title : mesg.options.title
author : mesg.options.author
date : mesg.options.date
contents : mesg.options.contents
extra_data : mesg.options.extra_data
timeout : mesg.options.timeout
cb : cb
else
cb("unable to print file of type '#{ext}'")
], (err) ->
if err
socket.write_mesg('json', message.error(id:mesg.id, error:err))
else
socket.write_mesg('json', message.printed_to_pdf(id:mesg.id, path:pdf))
)
###############################################
# Info
###############################################
session_info = (project_id) ->
return {
'sage_sessions' : sage_sessions.info(project_id)
'console_sessions' : console_sessions.info(project_id)
'file_sessions' : codemirror_sessions.info(project_id)
}
###############################################
# Manage Jupyter server
###############################################
jupyter_port_queue = []
jupyter_port = (socket, mesg) ->
winston.debug("jupyter_port")
jupyter_port_queue.push({socket:socket, mesg:mesg})
if jupyter_port_queue.length > 1
return
misc_node.execute_code
command : "ipython-notebook"
args : ['start']
err_on_exit : true
bash : false
timeout : 60
ulimit_timeout : false # very important -- so doesn't kill consoles after 60 seconds cputime!
cb : (err, out) ->
if not err
try
info = misc.from_json(out.stdout)
port = info?.port
if not port?
err = "unable to start -- no port; info=#{misc.to_json(out)}"
else
catch e
err = "error parsing ipython-notebook startup output -- #{e}, {misc.to_json(out)}"
if err
error = "error starting Jupyter -- #{err}"
for x in jupyter_port_queue
err_mesg = message.error
id : x.mesg.id
error : error
x.socket.write_mesg('json', err_mesg)
else
for x in jupyter_port_queue
resp = message.jupyter_port
port : port
id : x.mesg.id
x.socket.write_mesg('json', resp)
jupyter_port_queue = []
###############################################
# Execute a command line or block of BASH
###############################################
project_exec = (socket, mesg) ->
winston.debug("project_exec")
if mesg.command == "ipython-notebook"
socket.write_mesg("json", message.error(id:mesg.id, error:"old client code -- you may not run ipython-notebook directly"))
return
misc_node.execute_code
command : mesg.command
args : mesg.args
path : abspath(mesg.path)
timeout : mesg.timeout
err_on_exit : mesg.err_on_exit
max_output : mesg.max_output
bash : mesg.bash
cb : (err, out) ->
if err
error = "Error executing command '#{mesg.command}' with args '#{mesg.args}' -- #{err}, #{out?.stdout}, #{out?.stderr}"
if error.indexOf("Connection refused") != -1
error += "-- Email <EMAIL> if you need external network access, which is disabled by default."
if error.indexOf("=") != -1
error += "-- This is a BASH terminal, not a Sage worksheet. For Sage, use +New and create a Sage worksheet."
err_mesg = message.error
id : mesg.id
error : error
socket.write_mesg('json', err_mesg)
else
#winston.debug(json(out))
socket.write_mesg 'json', message.project_exec_output
id : mesg.id
stdout : out.stdout
stderr : out.stderr
exit_code : out.exit_code
_save_blob_callbacks = {}
receive_save_blob_message = (opts) ->
opts = defaults opts,
sha1 : required
cb : required
timeout : 30 # maximum time in seconds to wait for response message
sha1 = opts.sha1
id = misc.uuid()
if not _save_blob_callbacks[sha1]?
_save_blob_callbacks[sha1] = [[opts.cb, id]]
else
_save_blob_callbacks[sha1].push([opts.cb, id])
# Timeout functionality -- send a response after opts.timeout seconds,
# in case no hub responded.
f = () ->
v = _save_blob_callbacks[sha1]
if v?
mesg = message.save_blob
sha1 : sha1
error : "timed out after local hub waited for #{opts.timeout} seconds"
w = []
for x in v # this is O(n) instead of O(1), but who cares since n is usually 1.
if x[1] == id
x[0](mesg)
else
w.push(x)
if w.length == 0
delete _save_blob_callbacks[sha1]
else
_save_blob_callbacks[sha1] = w
if opts.timeout
setTimeout(f, opts.timeout*1000)
handle_save_blob_message = (mesg) ->
v = _save_blob_callbacks[mesg.sha1]
if v?
for x in v
x[0](mesg)
delete _save_blob_callbacks[mesg.sha1]
###############################################
# Handle a message from the client
###############################################
handle_mesg = (socket, mesg, handler) ->
activity() # record that there was some activity so process doesn't killall
try
winston.debug("Handling '#{json(mesg)}'")
if mesg.event.split('_')[0] == 'codemirror'
codemirror_sessions.handle_mesg(socket, mesg)
return
switch mesg.event
when 'connect_to_session', 'start_session'
# These sessions completely take over this connection, so we better stop listening
# for further control messages on this connection.
socket.removeListener 'mesg', handler
connect_to_session(socket, mesg)
when 'project_session_info'
resp = message.project_session_info
id : mesg.id
project_id : mesg.project_id
info : session_info(mesg.project_id)
socket.write_mesg('json', resp)
when 'jupyter_port'
jupyter_port(socket, mesg)
when 'project_exec'
project_exec(socket, mesg)
when 'read_file_from_project'
read_file_from_project(socket, mesg)
when 'write_file_to_project'
write_file_to_project(socket, mesg)
when 'print_to_pdf'
print_to_pdf(socket, mesg)
when 'send_signal'
process_kill(mesg.pid, mesg.signal)
if mesg.id?
socket.write_mesg('json', message.signal_sent(id:mesg.id))
when 'terminate_session'
terminate_session(socket, mesg)
when 'save_blob'
handle_save_blob_message(mesg)
else
if mesg.id?
err = message.error(id:mesg.id, error:"Local hub received an invalid mesg type '#{mesg.event}'")
socket.write_mesg('json', err)
catch e
winston.debug(new Error().stack)
winston.error "ERROR: '#{e}' handling message '#{json(mesg)}'"
process_kill = (pid, signal) ->
switch signal
when 2
signal = 'SIGINT'
when 3
signal = 'SIGQUIT'
when 9
signal = 'SIGKILL'
else
winston.debug("BUG -- process_kill: only signals 2 (SIGINT), 3 (SIGQUIT), and 9 (SIGKILL) are supported")
return
try
process.kill(pid, signal)
catch e
# it's normal to get an exception when sending a signal... to a process that doesn't exist.
server = net.createServer (socket) ->
winston.debug "PARENT: received connection"
misc_node.unlock_socket socket, secret_token, (err) ->
if err
winston.debug(err)
else
socket.id = uuid.v4()
misc_node.enable_mesg(socket)
handler = (type, mesg) ->
if type == "json" # other types are handled elsewhere in event code.
winston.debug "received control mesg #{json(mesg)}"
handle_mesg(socket, mesg, handler)
socket.on 'mesg', handler
start_tcp_server = (cb) ->
winston.info("starting tcp server...")
server.listen program.port, '0.0.0.0', () ->
winston.info("listening on port #{server.address().port}")
fs.writeFile(abspath("#{DATA}/local_hub.port"), server.address().port, cb)
# use of domain inspired by http://stackoverflow.com/questions/17940895/handle-uncaughtexception-in-express-and-restify
# This addresses an issue where the raw server fails to startup, maybe due to race condition with misc_node.free_port;
# and... in any case if anything uncaught goes wrong starting the raw server or running, this will ensure
# that it gets fixed automatically.
raw_server_domain = require('domain').create()
raw_server_domain.on 'error', (err) ->
winston.debug("got an exception in raw server, so restarting.")
start_raw_server( () -> winston.debug("restarted raw http server") )
start_raw_server = (cb) ->
raw_server_domain.run () ->
winston.info("starting raw server...")
info = INFO
winston.debug("info = #{misc.to_json(info)}")
express = require('express')
raw_server = express()
project_id = info.project_id
misc_node.free_port (err, port) ->
if err
winston.debug("error starting raw server: #{err}")
cb(err); return
fs.writeFile(abspath("#{DATA}/raw.port"), port, cb)
base = "#{info.base_url}/#{project_id}/raw/"
winston.info("raw server (port=#{port}), host='#{info.location.host}', base='#{base}'")
raw_server.configure () ->
raw_server.use(base, express.directory(process.env.HOME, {hidden:true, icons:true}))
raw_server.use(base, express.static(process.env.HOME, {hidden:true}))
# NOTE: It is critical to only listen on the host interface (not localhost), since otherwise other users
# on the same VM could listen in. We firewall connections from the other VM hosts above
# port 1024, so this is safe without authentication. TODO: should we add some sort of auth (?) just in case?
raw_server.listen port, info.location.host, (err) ->
winston.info("err = #{err}")
if err
cb(err); return
fs.writeFile(abspath("#{DATA}/raw.port"), port, cb)
last_activity = undefined
# Call this function to signal that there is activity.
activity = () ->
last_activity = misc.mswalltime()
# Truncate the ~/.sagemathcloud.log if it exceeds a certain length threshhold.
SAGEMATHCLOUD_LOG_THRESH = 5000 # log grows to at most 50% more than this
SAGEMATHCLOUD_LOG_FILE = process.env['HOME'] + '/.sagemathcloud.log'
log_truncate = (cb) ->
data = undefined
winston.info("log_truncate: checking that logfile isn't too long")
exists = undefined
async.series([
(cb) ->
fs.exists SAGEMATHCLOUD_LOG_FILE, (_exists) ->
exists = _exists
cb()
(cb) ->
if not exists
cb(); return
# read the log file
fs.readFile SAGEMATHCLOUD_LOG_FILE, (err, _data) ->
data = _data?.toString() # ? is important, since in case of err _data is not defined.
cb(err)
(cb) ->
if not exists
cb(); return
# if number of lines exceeds 50% more than MAX_LINES
n = misc.count(data, '\n')
if n >= SAGEMATHCLOUD_LOG_THRESH * 1.5
winston.debug("log_truncate: truncating log file to #{SAGEMATHCLOUD_LOG_THRESH} lines")
v = data.split('\n') # the -1 below is since last entry is a blank line
new_data = v.slice(n - SAGEMATHCLOUD_LOG_THRESH, v.length-1).join('\n')
fs.writeFile(SAGEMATHCLOUD_LOG_FILE, new_data, cb)
else
cb()
], cb)
start_log_truncate = (cb) ->
winston.info("start_log_truncate")
f = (c) ->
winston.debug("calling log_truncate")
log_truncate (err) ->
if err
winston.debug("ERROR: problem truncating log -- #{err}")
c()
setInterval(f, 1000*3600*12) # once every 12 hours
f(cb)
# Start listening for connections on the socket.
exports.start_server = start_server = () ->
async.series [start_log_truncate, start_tcp_server, start_raw_server], (err) ->
if err
winston.debug("Error starting a server -- #{err}")
else
winston.debug("Successfully started servers.")
# daemonize it
program = require('commander')
daemon = require("start-stop-daemon")
program.usage('[start/stop/restart/status] [options]')
.option('--pidfile [string]', 'store pid in this file', String, abspath("#{DATA}/local_hub.pid"))
.option('--logfile [string]', 'write log to this file', String, abspath("#{DATA}/local_hub.log"))
.option('--forever_logfile [string]', 'write forever log to this file', String, abspath("#{DATA}/forever_local_hub.log"))
.option('--debug [string]', 'logging debug level (default: "debug"); "" for no debugging output)', String, 'debug')
.parse(process.argv)
if program._name.split('.')[0] == 'local_hub'
if program.debug
winston.remove(winston.transports.Console)
winston.add(winston.transports.Console, {level: program.debug, timestamp:true, colorize:true})
winston.debug "Running as a Daemon"
# run as a server/daemon (otherwise, is being imported as a library)
process.addListener "uncaughtException", (err) ->
winston.debug("BUG ****************************************************************************")
winston.debug("Uncaught exception: " + err)
winston.debug(err.stack)
winston.debug("BUG ****************************************************************************")
if console? and console.trace?
console.trace()
console.log("setting up conf path")
init_confpath()
init_info_json()
# empty the forever logfile -- it doesn't get reset on startup and easily gets huge.
fs.writeFileSync(program.forever_logfile, '')
console.log("start daemon")
daemon({pidFile:program.pidfile, outFile:program.logfile, errFile:program.logfile, logFile:program.forever_logfile, max:1}, start_server)
console.log("after daemon")
| true | ###############################################################################
#
# SageMathCloud: A collaborative web-based interface to Sage, IPython, LaTeX and the Terminal.
#
# Copyright (C) 2014, PI:NAME:<NAME>END_PI
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
#################################################################
#
# local_hub -- a node.js program that runs as a regular user, and
# coordinates and maintains the connections between
# the global hubs and *all* projects running as
# this particular user.
#
# The local_hub is a bit like the "screen" program for Unix, except
# that it simultaneously manages numerous sessions, since simultaneously
# doing a lot of IO-based things is what Node.JS is good at.
#
#
# NOTE: For local debugging, run this way, since it gives better stack
# traces.CodeMirrorSession: _connect to file
#
# make_coffee && echo "require('local_hub').start_server()" | coffee
#
# (c) PI:NAME:<NAME>END_PI, 2013, 2014
#
#################################################################
async = require 'async'
fs = require 'fs'
net = require 'net'
child_process = require 'child_process'
uuid = require 'node-uuid'
message = require 'message'
misc = require 'misc'
misc_node = require 'misc_node'
winston = require 'winston'
temp = require 'temp'
diffsync = require 'diffsync'
{to_json, from_json, defaults, required} = require 'misc'
json = (out) -> misc.trunc(misc.to_json(out),512)
{ensure_containing_directory_exists, abspath} = misc_node
expire_time = (ttl) -> if ttl then new Date((new Date() - 0) + ttl*1000)
# We make it an error for a client to try to edit a file larger than MAX_FILE_SIZE.
# I decided on this, because attempts to open a much larger file leads
# to disaster. Opening a 10MB file works but is a just a little slow.
MAX_FILE_SIZE = 10000000 # 10MB
check_file_size = (size) ->
if size? and size > MAX_FILE_SIZE
e = "Attempt to open large file of size #{Math.round(size/1000000)}MB; the maximum allowed size is #{Math.round(MAX_FILE_SIZE/1000000)}MB. Use vim, emacs, or pico from a terminal instead."
winston.debug(e)
return e
###
# Revision tracking misc.
###
# Save the revision_tracking info for a file to disk *at most* this frequently.
# NOTE: failing to save to disk would only mean missing a patch but should
# otherwise *NOT* corrupt the history.
REVISION_TRACKING_SAVE_INTERVAL = 45000 # 45 seconds
# Filename of revision tracking file associated to a given file
revision_tracking_path = (path) ->
s = misc.path_split(path)
return "#{s.head}/.#{s.tail}.sage-history"
# Create dmp patch that transforms the empty string to s.
### not used (so commented out), but could be useful...
patch_from_trivial = (s) ->
return [
diffs : [ [ 1, s ] ],
start1 : 0,
start2 : 0,
length1 : 0,
length2 : s.length }
]
###
#####################################################################
# Generate the "secret_token" file as
# $SAGEMATHCLOUD/data/secret_token if it does not already
# exist. All connections to all local-to-the user services that
# SageMathClouds starts must be prefixed with this key.
#####################################################################
# WARNING -- the sage_server.py program can't get these definitions from
# here, since it is not written in node; if this path changes, it has
# to be change there as well (it will use the SAGEMATHCLOUD environ
# variable though).
DATA = process.env['SAGEMATHCLOUD'] + '/data'
CONFPATH = exports.CONFPATH = abspath(DATA)
secret_token_filename = exports.secret_token_filename = "#{CONFPATH}/secret_token"
secret_token = undefined
# We use an n-character cryptographic random token, where n is given
# below. If you want to change this, changing only the following line
# should be safe.
secret_token_length = 128
init_confpath = () ->
async.series([
# Read or create the file; after this step the variable secret_token
# is set and the file exists.
(cb) ->
fs.exists secret_token_filename, (exists) ->
if exists
winston.debug("read '#{secret_token_filename}'")
fs.readFile secret_token_filename, (err, buf) ->
secret_token = buf.toString()
cb()
else
winston.debug("create '#{secret_token_filename}'")
require('crypto').randomBytes secret_token_length, (ex, buf) ->
secret_token = buf.toString('base64')
fs.writeFile(secret_token_filename, secret_token, cb)
# Ensure restrictive permissions on the secret token file.
(cb) ->
fs.chmod(secret_token_filename, 0o600, cb)
])
INFO = undefined
init_info_json = () ->
winston.debug("writing info.json")
filename = "#{process.env['SAGEMATHCLOUD']}/info.json"
v = process.env['HOME'].split('/')
project_id = v[v.length-1]
username = project_id.replace(/-/g,'')
host = require('os').networkInterfaces().eth0?[0].address
base_url = ''
port = 22
INFO =
project_id : project_id
location : {host:host, username:username, port:port, path:'.'}
base_url : base_url
fs.writeFileSync(filename, misc.to_json(INFO))
###############################################
# Console sessions
###############################################
ports = {}
get_port = (type, cb) -> # cb(err, port number)
if ports[type]?
cb(false, ports[type])
else
fs.readFile abspath("#{DATA}/#{type}_server.port"), (err, content) ->
if err
cb(err)
else
try
ports[type] = parseInt(content)
cb(false, ports[type])
catch e
cb("#{type}_server port file corrupted")
forget_port = (type) ->
if ports[type]?
delete ports[type]
# try to restart the console server and get port where it is listening
CONSOLE_SERVER_MAX_STARTUP_TIME_S = 10 # 10 seconds
_restarting_console_server = false
_restarted_console_server = 0 # time when we last restarted it
restart_console_server = (cb) -> # cb(err)
dbg = (m) -> winston.debug("restart_console_server: #{misc.to_json(m)}")
if _restarting_console_server
dbg("hit lock -- already restarting console server")
cb("already restarting console server")
return
t = new Date() - _restarted_console_server
if t <= CONSOLE_SERVER_MAX_STARTUP_TIME_S*1000
err = "restarted console server #{t}ms ago -- still waiting for it to start"
dbg(err)
cb(err)
return
_restarting_console_server = true
dbg("restarting the daemon")
dbg("killing all existing console sockets")
console_sessions.terminate_all_sessions()
port_file = abspath("#{DATA}/console_server.port")
port = undefined
async.series([
(cb) ->
dbg("remove port_file=#{port_file}")
fs.unlink port_file, (err) ->
cb() # ignore error, e.g., if file not there.
(cb) ->
dbg("restart console server")
misc_node.execute_code
command : "console_server restart"
timeout : 10
ulimit_timeout : false # very important -- so doesn't kill consoles after 10 seconds!
err_on_exit : true
bash : true
cb : cb
(cb) ->
dbg("wait a little to see if #{port_file} appears, and if so read it and return port")
f = (cb) ->
fs.exists port_file, (exists) ->
if not exists
cb(true)
else
fs.readFile port_file, (err, data) ->
if err
cb(err)
else
try
port = parseInt(data.toString())
cb()
catch error
cb('reading port corrupt')
misc.retry_until_success
f : f
max_time : 7000
cb : cb
], (err) =>
_restarting_console_server = false
_restarted_console_server = new Date()
dbg("finished trying to restart console_server")
if err
dbg("ERROR: #{err}")
cb(err, port)
)
class ConsoleSessions
constructor: () ->
@_sessions = {}
@_get_session_cbs = {}
session_exists: (session_uuid) =>
return @_sessions[session_uuid]?
terminate_session: (session_uuid, cb) =>
session = @_sessions[session_uuid]
if not session?
cb?()
else
winston.debug("terminate console session '#{session_uuid}'")
if session.status == 'running'
session.socket.end()
session.status = 'done'
cb?()
else
cb?()
terminate_all_sessions: () =>
for session_uuid, session of @_sessions[session_uuid]
try
session.socket.end()
catch e
session.status = 'done'
# Connect to (if 'running'), restart (if 'dead'), or create (if
# non-existing) the console session with mesg.session_uuid.
connect: (client_socket, mesg, cb) =>
if not mesg.session_uuid?
mesg.session_uuid = misc.uuid()
client_socket.on 'end', () =>
winston.debug("a console session client socket ended -- session_uuid=#{mesg.session_uuid}")
#client_socket.destroy()
@get_session mesg, (err, session) =>
if err
client_socket.write_mesg('json', message.error(id:mesg.id, error:err))
cb?(err)
else
client_socket.write_mesg('json', {desc:session.desc, history:session.history.toString()})
plug(client_socket, session.socket, 20000) # 20000 = max burst to client every few ms.
session.clients.push(client_socket)
cb?()
# Get or create session with given uuid.
# Can be safely called several times at once without creating multiple sessions...
get_session: (mesg, cb) =>
# TODO: must be robust against multiple clients opening same session_id at once, which
# would be likely to happen on network reconnect.
winston.debug("get_session: console session #{mesg.session_uuid}")
session = @_sessions[mesg.session_uuid]
if session? and session.status == 'running'
winston.debug("console session: done -- it's already there and working")
cb(undefined, session)
return
if not @_get_session_cbs[mesg.session_uuid]?
winston.debug("console session not yet created -- put on stack")
@_get_session_cbs[mesg.session_uuid] = [cb]
else
winston.debug("console session already being created -- just push cb onto stack and return")
@_get_session_cbs[mesg.session_uuid].push(cb)
return
port = undefined
history = undefined
async.series([
(cb) =>
if session?
history = session.history # maintain history
winston.debug("console session does not exist or is not running, so we make a new session")
session = undefined
get_port 'console', (err, _port) =>
if err
cb() # will try to restart console server in next step
else
port = _port
winston.debug("got console server port = #{port}")
cb()
(cb) =>
if port?
cb()
else
winston.debug("couldn't determine console server port; probably console server not running -- try restarting it")
restart_console_server (err, _port) =>
if err
cb(err)
else
port = _port
winston.debug("restarted console server, then got port = #{port}")
cb()
(cb) =>
# Got port -- now create the new session
@_new_session mesg, port, (err, _session) =>
if err
cb(err)
else
session = _session
if history? # we restarted session; maintain history
session.history = history
cb()
], (err) =>
# call all the callbacks that were waiting on this session.
for cb in @_get_session_cbs[mesg.session_uuid]
cb(err, session)
delete @_get_session_cbs[mesg.session_uuid]
)
_get_console_server_socket: (port, cb) =>
socket = undefined
f = (cb) =>
misc_node.connect_to_locked_socket
port : port
token : PI:PASSWORD:<PASSWORD>END_PI_token
cb : (err, _socket) =>
if err
cb(err)
else
socket = _socket
cb()
async.series([
(cb) =>
misc.retry_until_success
f : f
max_time : 5000
cb : (err) =>
cb() # ignore err on purpose -- no err sets socket
(cb) =>
if socket?
cb(); return
forget_port('console')
restart_console_server (err, _port) =>
if err
cb(err)
else
port = _port
cb()
(cb) =>
if socket?
cb(); return
misc.retry_until_success
f : f
max_time : 5000
cb : cb
], (err) =>
if err
cb(err)
else
cb(undefined, socket)
)
_new_session: (mesg, port, cb) => # cb(err, session)
winston.debug("_new_session: defined by #{json(mesg)}")
# Connect to port CONSOLE_PORT, send mesg, then hook sockets together.
@_get_console_server_socket port, (err, console_socket) =>
if err
cb("_new_session: console server failed to connect -- #{err}")
return
# Request a Console session from console_server
misc_node.enable_mesg(console_socket)
console_socket.write_mesg('json', mesg)
# Read one JSON message back, which describes the session
console_socket.once 'mesg', (type, desc) =>
if not history?
history = new Buffer(0)
# in future, history could be read from a file
# Disable JSON mesg protocol, since it isn't used further
misc_node.disable_mesg(console_socket)
session =
socket : console_socket
desc : desc
status : 'running'
clients : []
history : '' # TODO: this could come from something stored in a file
session_uuid : mesg.session_uuid
project_id : mesg.project_id
session.amount_of_data = 0
session.last_data = misc.mswalltime()
console_socket.on 'data', (data) ->
#winston.debug("receive #{data.length} of data from the pty: data='#{data.toString()}'")
# every 2 ms we reset the burst data watcher.
tm = misc.mswalltime()
if tm - session.last_data >= 2
session.amount_of_data = 0
session.last_data = tm
if session.amount_of_data > 50000
# We just got more than 50000 characters of output in <= 2 ms, so truncate it.
# I had a control-c here, but it was EVIL (and useless), so do *not* enable this.
# console_socket.write(String.fromCharCode(3))
data = '[...]'
session.history += data
session.amount_of_data += data.length
n = session.history.length
if n > 200000
session.history = session.history.slice(session.history.length - 100000)
@_sessions[mesg.session_uuid] = session
cb(undefined, session)
console_socket.on 'end', () =>
winston.debug("console session #{mesg.session_uuid} ended")
session = @_sessions[mesg.session_uuid]
if session?
session.status = 'done'
for client in session.clients
# close all of these connections
client.end()
# Return object that describes status of all Console sessions
info: (project_id) =>
obj = {}
for id, session of @_sessions
if session.project_id == project_id
obj[id] =
desc : session.desc
status : session.status
history_length : session.history.length
return obj
console_sessions = new ConsoleSessions()
###############################################
# Direct Sage socket session -- used internally in local hub, e.g., to assist CodeMirror editors...
###############################################
# Wait up to this long for the Sage server to start responding
# connection requests, after we restart it. It can
# take a while, since it pre-imports the sage library
# at startup, before forking.
SAGE_SERVER_MAX_STARTUP_TIME_S = 30 # 30 seconds
_restarting_sage_server = false
_restarted_sage_server = 0 # time when we last restarted it
exports.restart_sage_server = restart_sage_server = (cb) ->
dbg = (m) -> winston.debug("restart_sage_server: #{misc.to_json(m)}")
if _restarting_sage_server
dbg("hit lock")
cb("already restarting sage server")
return
t = new Date() - _restarted_sage_server
if t <= SAGE_SERVER_MAX_STARTUP_TIME_S*1000
err = "restarted sage server #{t}ms ago -- still waiting for it to start"
dbg(err)
cb(err)
return
_restarting_sage_server = true
dbg("restarting the daemon")
misc_node.execute_code
command : "sage_server stop; sage_server start"
timeout : 30
ulimit_timeout : false # very important -- so doesn't kill consoles after 30 seconds of cpu!
err_on_exit : true
bash : true
cb : (err) ->
_restarting_sage_server = false
_restarted_sage_server = new Date()
cb(err)
# Get a new connection to the Sage server. If the server
# isn't running, e.g., it was killed due to running out of memory,
# then attempt to restart it and try to connect.
get_sage_socket = (cb) ->
socket = undefined
try_to_connect = (cb) ->
_get_sage_socket (err, _socket) ->
if not err
socket = _socket
cb()
else
# Failed for some reason: try to restart one time, then try again.
# We do this because the Sage server can easily get killed due to out of memory conditions.
# But we don't constantly try to restart the server, since it can easily fail to start if
# there is something wrong with a local Sage install.
# Note that restarting the sage server doesn't impact currently running worksheets (they
# have their own process that isn't killed).
restart_sage_server (err) -> # won't actually try to restart if called recently.
# we ignore the returned err -- error does not matter, since we didn't connect
cb(true)
misc.retry_until_success
f : try_to_connect
start_delay : 2000
max_delay : 6000
factor : 1.5
max_time : SAGE_SERVER_MAX_STARTUP_TIME_S*1000
log : (m) -> winston.debug("get_sage_socket: #{m}")
cb : (err) ->
cb(err, socket)
_get_sage_socket = (cb) -> # cb(err, socket that is ready to use)
sage_socket = undefined
port = undefined
async.series([
(cb) =>
winston.debug("get sage server port")
get_port 'sage', (err, _port) =>
if err
cb(err); return
else
port = _port
cb()
(cb) =>
winston.debug("get and unlock socket")
misc_node.connect_to_locked_socket
port : port
token : PI:PASSWORD:<PASSWORD>END_PI_token
cb : (err, _socket) =>
if err
forget_port('sage')
winston.debug("unlock socket: _new_session: sage session denied connection: #{err}")
cb("_new_session: sage session denied connection: #{err}")
return
sage_socket = _socket
winston.debug("Successfully unlocked a sage session connection.")
cb()
(cb) =>
winston.debug("request sage session from server.")
misc_node.enable_mesg(sage_socket)
sage_socket.write_mesg('json', message.start_session(type:'sage'))
winston.debug("Waiting to read one JSON message back, which will describe the session....")
# TODO: couldn't this just hang forever :-(
sage_socket.once 'mesg', (type, desc) =>
winston.debug("Got message back from Sage server: #{json(desc)}")
sage_socket.pid = desc.pid
cb()
], (err) -> cb(err, sage_socket))
# Connect to sockets together. This is used mainly
# for the console server.
plug = (s1, s2, max_burst) -> # s1 = hub; s2 = console server
last_tm = misc.mswalltime()
last_data = ''
amount = 0
# Connect the sockets together.
s1_data = (data) ->
activity()
# record incoming activity (don't do this in other direction, since that shouldn't keep session alive)
if not s2.writable
s1.removeListener('data', s1_data)
else
s2.write(data)
s2_data = (data) ->
if not s1.writable
s2.removeListener('data', s2_data)
else
if max_burst?
tm = misc.mswalltime()
if tm - last_tm >= 20
if amount < 0 # was truncating
try
x = last_data.slice(Math.max(0, last_data.length - Math.floor(max_burst/4)))
catch e
# I don't know why the above sometimes causes an exception, but it *does* in
# Buffer.slice, which is a serious problem. Best to ignore that data.
x = ''
data = "]" + x + data
#console.log("max_burst: reset")
amount = 0
last_tm = tm
#console.log("max_burst: amount=#{amount}")
if amount >= max_burst
last_data = data
data = data.slice(0,Math.floor(max_burst/4)) + "[..."
amount = -1 # so do only once every 20ms.
setTimeout((()=>s2_data('')), 25) # write nothing in 25ms just to make sure ...] appears.
else if amount < 0
last_data += data
setTimeout((()=>s2_data('')), 25) # write nothing in 25ms just to make sure ...] appears.
else
amount += data.length
# Never push more than max_burst characters at once to hub, since that could overwhelm
s1.write(data)
s1.on('data', s1_data)
s2.on('data', s2_data)
###############################################
# Sage sessions
###############################################
## WARNING! I think this is no longer used! It was used for my first (few)
## approaches to worksheets.
class SageSessions
constructor: () ->
@_sessions = {}
session_exists: (session_uuid) =>
return @_sessions[session_uuid]?
terminate_session: (session_uuid, cb) =>
S = @_sessions[session_uuid]
if not S?
cb()
else
winston.debug("terminate sage session -- STUB!")
cb()
update_session_status: (session) =>
# Check if the process corresponding to the given session is
# *actually* running/healthy (?). Just because the socket hasn't sent
# an "end" doesn't mean anything.
try
process.kill(session.desc.pid, 0)
# process is running -- leave status as is.
catch e
# process is not running
session.status = 'done'
get_session: (uuid) =>
session = @_sessions[uuid]
if session?
@update_session_status(session)
return session
# Connect to (if 'running'), restart (if 'dead'), or create (if
# non-existing) the Sage session with mesg.session_uuid.
connect: (client_socket, mesg) =>
session = @get_session mesg.session_uuid
if session? and session.status == 'running'
winston.debug("sage sessions: connect to the running session with id #{mesg.session_uuid}")
client_socket.write_mesg('json', session.desc)
plug(client_socket, session.socket)
session.clients.push(client_socket)
else
winston.debug("make a connection to a new sage session.")
get_port 'sage', (err, port) =>
winston.debug("Got sage server port = #{port}")
if err
winston.debug("can't determine sage server port; probably sage server not running")
client_socket.write_mesg('json', message.error(id:mesg.id, error:"problem determining port of sage server."))
else
@_new_session(client_socket, mesg, port)
_new_session: (client_socket, mesg, port, retries) =>
winston.debug("_new_session: creating new sage session (retries=#{retries})")
# Connect to port, send mesg, then hook sockets together.
misc_node.connect_to_locked_socket
port : port
token : secret_token
cb : (err, sage_socket) =>
if err
winston.debug("_new_session: sage session denied connection: #{err}")
forget_port('sage')
if not retries? or retries <= 5
if not retries?
retries = 1
else
retries += 1
try_again = () =>
@_new_session(client_socket, mesg, port, retries)
setTimeout(try_again, 1000)
else
# give up.
client_socket.write_mesg('json', message.error(id:mesg.id, error:"local_hub -- Problem connecting to Sage server. -- #{err}"))
return
else
winston.debug("Successfully unlocked a sage session connection.")
winston.debug("Next, request a Sage session from sage_server.")
misc_node.enable_mesg(sage_socket)
sage_socket.write_mesg('json', message.start_session(type:'sage'))
winston.debug("Waiting to read one JSON message back, which will describe the session.")
sage_socket.once 'mesg', (type, desc) =>
winston.debug("Got message back from Sage server: #{json(desc)}")
client_socket.write_mesg('json', desc)
plug(client_socket, sage_socket)
# Finally, this socket is now connected to a sage server and ready to execute code.
@_sessions[mesg.session_uuid] =
socket : sage_socket
desc : desc
status : 'running'
clients : [client_socket]
project_id : mesg.project_id
sage_socket.on 'end', () =>
# this is *NOT* dependable, since a segfaulted process -- and sage does that -- might
# not send a FIN.
winston.debug("sage_socket: session #{mesg.session_uuid} terminated.")
session = @_sessions[mesg.session_uuid]
# TODO: should we close client_socket here?
if session?
winston.debug("sage_socket: setting status of session #{mesg.session_uuid} to terminated.")
session.status = 'done'
# Return object that describes status of all Sage sessions
info: (project_id) =>
obj = {}
for id, session of @_sessions
if session.project_id == project_id
obj[id] =
desc : session.desc
status : session.status
return obj
sage_sessions = new SageSessions()
############################################################################
#
# Differentially-Synchronized document editing sessions
#
# Here's a map YOU ARE HERE
# |
# [client]s.. ---> [hub] ---> [local hub] <--- [hub] <--- [client]s...
# |
# \|/
# [a file on disk]
#
#############################################################################
# The "live upstream content" of DiffSyncFile_client is the actual file on disk.
# # TODO: when applying diffs, we could use that the file is random access. This is not done yet!
class DiffSyncFile_server extends diffsync.DiffSync
constructor:(@cm_session, cb) ->
@path = @cm_session.path
no_master = undefined
stats_path = undefined
stats = undefined
file = undefined
async.series([
(cb) =>
fs.stat @path, (_no_master, _stats_path) =>
no_master = _no_master
stats_path = _stats_path
cb()
(cb) =>
if no_master
# create
file = @path
misc_node.ensure_containing_directory_exists @path, (err) =>
if err
cb(err)
else
fs.open file, 'w', (err, fd) =>
if err
cb(err)
else
fs.close fd, cb
else
# master exists
file = @path
stats = stats_path
cb()
(cb) =>
e = check_file_size(stats?.size)
if e
cb(e)
return
fs.readFile file, (err, data) =>
if err
cb(err); return
# NOTE: we immediately delete \r's since the client editor (Codemirror) immediately deletes them
# on editor creation; if we don't delete them, all sync attempts fail and hell is unleashed.
@init(doc:data.toString().replace(/\r/g,''), id:"file_server")
# winston.debug("got new file contents = '#{@live}'")
@_start_watching_file()
cb(err)
], (err) => cb(err, @live))
kill: () =>
if @_autosave?
clearInterval(@_autosave)
# be sure to clean this up, or -- after 11 times -- it will suddenly be impossible for
# the user to open a file without restarting their project server! (NOT GOOD)
fs.unwatchFile(@path, @_watcher)
_watcher: (event) =>
winston.debug("watch: file '#{@path}' modified.")
if not @_do_watch
winston.debug("watch: skipping read because watching is off.")
return
@_stop_watching_file()
async.series([
(cb) =>
fs.stat @path, (err, stats) =>
if err
cb(err)
else
cb(check_file_size(stats.size))
(cb) =>
fs.readFile @path, (err, data) =>
if err
cb(err)
else
@live = data.toString().replace(/\r/g,'') # NOTE: we immediately delete \r's (see above).
@cm_session.sync_filesystem(cb)
], (err) =>
if err
winston.debug("watch: file '#{@path}' error -- #{err}")
@_start_watching_file()
)
_start_watching_file: () =>
if @_do_watch?
@_do_watch = true
return
@_do_watch = true
winston.debug("watching #{@path}")
fs.watchFile(@path, @_watcher)
_stop_watching_file: () =>
@_do_watch = false
# NOTE: I tried using fs.watch as below, but *DAMN* -- even on
# Linux 12.10 -- fs.watch in Node.JS totally SUCKS. It led to
# file corruption, weird flakiness and errors, etc. fs.watchFile
# above, on the other hand, is great for my needs (which are not
# for immediate sync).
# _start_watching_file0: () =>
# winston.debug("(re)start watching...")
# if @_fs_watcher?
# @_stop_watching_file()
# try
# @_fs_watcher = fs.watch(@path, @_watcher)
# catch e
# setInterval(@_start_watching_file, 15000)
# winston.debug("WARNING: failed to start watching '#{@path}' -- will try later -- #{e}")
# _stop_watching_file0: () =>
# if @_fs_watcher?
# @_fs_watcher.close()
# delete @_fs_watcher
snapshot: (cb) => # cb(err, snapshot of live document)
cb(false, @live)
_apply_edits_to_live: (edits, cb) =>
if edits.length == 0
cb(); return
@_apply_edits edits, @live, (err, result) =>
if err
cb(err)
else
if result == @live
cb() # nothing to do
else
@live = result
@write_to_disk(cb)
write_to_disk: (cb) =>
@_stop_watching_file()
ensure_containing_directory_exists @path, (err) =>
if err
cb?(err); return
fs.writeFile @path, @live, (err) =>
@_start_watching_file()
cb?(err)
# The live content of DiffSyncFile_client is our in-memory buffer.
class DiffSyncFile_client extends diffsync.DiffSync
constructor:(@server) ->
super(doc:@server.live, id:"file_client")
# Connect the two together
@connect(@server)
@server.connect(@)
# The CodeMirrorDiffSyncHub class represents a downstream
# remote client for this local hub. There may be dozens of these.
# The local hub has no upstream server, except the on-disk file itself.
#
# NOTE: These have *nothing* a priori to do with CodeMirror -- the name is
# historical and should be changed. TODO.
#
class CodeMirrorDiffSyncHub
constructor : (@socket, @session_uuid, @client_id) ->
write_mesg: (event, obj) =>
if not obj?
obj = {}
obj.session_uuid = @session_uuid
mesg = message['codemirror_' + event](obj)
mesg.client_id = @client_id
@socket.write_mesg 'json', mesg
recv_edits : (edit_stack, last_version_ack, cb) =>
@write_mesg 'diffsync',
id : @current_mesg_id
edit_stack : edit_stack
last_version_ack : last_version_ack
cb?()
sync_ready: () =>
@write_mesg('diffsync_ready')
class CodeMirrorSession
constructor: (mesg, cb) ->
@path = mesg.path
@session_uuid = mesg.session_uuid
@_sage_output_cb = {}
@_sage_output_to_input_id = {}
# The downstream clients of this local hub -- these are global hubs that proxy requests on to browser clients
@diffsync_clients = {}
async.series([
(cb) =>
# if File doesn't exist, try to create it.
fs.exists @path, (exists) =>
if exists
cb()
else
fs.open @path,'w', (err, fd) =>
if err
cb(err)
else
fs.close(fd, cb)
(cb) =>
if @path.indexOf('.snapshots/') != -1
@readonly = true
cb()
else
misc_node.is_file_readonly
path : @path
cb : (err, readonly) =>
@readonly = readonly
cb(err)
(cb) =>
# If this is a non-readonly sagews file, create corresponding sage session.
if not @readonly and misc.filename_extension_notilde(@path) == 'sagews'
@process_new_content = @sage_update
@sage_socket(cb)
else
cb()
(cb) =>
# The *actual* file on disk. It's important to create this
# after successfully getting the sage socket, since if we fail to
# get the sage socket we end up creating too many fs.watch's on this file...
@diffsync_fileserver = new DiffSyncFile_server @, (err, content) =>
if err
cb(err); return
@content = content
@diffsync_fileclient = new DiffSyncFile_client(@diffsync_fileserver)
# worksheet freshly loaded from disk -- now ensure no cells appear to be running
# except for the auto cells that we spin up running.
@sage_update(kill:true, auto:true)
@_set_content_and_sync()
cb()
], (err) => cb?(err, @))
##############################
# Sage execution related code
##############################
sage_socket: (cb) => # cb(err, socket)
if @_sage_socket?
try
process.kill(@_sage_socket.pid, 0)
# process is still running fine
cb(false, @_sage_socket)
return
catch e
# sage process is dead.
@_sage_socket = undefined
winston.debug("sage_socket: initalize the newly started sage process")
# If we've already loaded the worksheet, then ensure
# that no cells appear to be running. This is important
# because the worksheet file that we just loaded could have had some
# markup that cells are running.
if @diffsync_fileclient?
@sage_update(kill:true)
# Connect to the local Sage server.
get_sage_socket (err, socket) =>
if err
winston.debug("sage_socket: fail -- #{err}.")
cb(err)
else
winston.debug("sage_socket: successfully opened a Sage session for worksheet '#{@path}'")
@_sage_socket = socket
# Set path to be the same as the file.
mesg = message.execute_code
id : misc.uuid()
code : "os.chdir(salvus.data['path']);__file__=salvus.data['file']"
data : {path: misc.path_split(@path).head, file:abspath(@path)}
preparse : false
socket.write_mesg('json', mesg)
socket.on 'end', () =>
@_sage_socket = undefined
winston.debug("codemirror session #{@session_uuid} sage socket terminated.")
socket.on 'mesg', (type, mesg) =>
#winston.debug("sage session: received message #{type}, #{misc.to_json(mesg)}")
switch type
when 'blob'
sha1 = mesg.uuid
if @diffsync_clients.length == 0
error = 'no global hubs are connected to the local hub, so nowhere to send file'
winston.debug("codemirror session: got blob from sage session -- #{error}")
resp = message.save_blob
error : error
sha1 : sha1
socket.write_mesg('json', resp)
else
winston.debug("codemirror session: got blob from sage session -- forwarding to a random hub")
hub = misc.random_choice_from_obj(@diffsync_clients)
client_id = hub[0]; ds_client = hub[1]
mesg.client_id = client_id
ds_client.remote.socket.write_mesg('blob', mesg)
receive_save_blob_message
sha1 : sha1
cb : (resp) -> socket.write_mesg('json', resp)
## DEBUG -- for testing purposes -- simulate the response message
## handle_save_blob_message(message.save_blob(sha1:sha1,ttl:1000))
when 'json'
# First check for callbacks (e.g., used in interact and things where the
# browser directly asks to evaluate code in this session).
c = @_sage_output_cb[mesg.id]
if c?
c(mesg)
if mesg.done
delete @_sage_output_cb[mesg.id]
return
# Handle code execution in browser messages
if mesg.event == 'execute_javascript'
# winston.debug("got execute_javascript message from sage session #{json(mesg)}")
# Wrap and forward it on as a broadcast message.
mesg.session_uuid = @session_uuid
bcast = message.codemirror_bcast
session_uuid : @session_uuid
mesg : mesg
@client_bcast(undefined, bcast)
return
# Finally, handle output messages
m = {}
for x, y of mesg
if x != 'id' and x != 'event' # the event is always "output"
if x == 'done' # don't bother with done=false
if y
m[x] = y
else
m[x] = y
#winston.debug("sage --> local_hub: '#{json(mesg)}'")
before = @content
@sage_output_mesg(mesg.id, m)
if before != @content
@_set_content_and_sync()
# If we've already loaded the worksheet, submit all auto cells to be evaluated.
if @diffsync_fileclient?
@sage_update(auto:true)
cb(false, @_sage_socket)
_set_content_and_sync: () =>
if @set_content(@content)
# Content actually changed, so suggest to all connected clients to sync.
for id, ds_client of @diffsync_clients
ds_client.remote.sync_ready()
sage_execute_cell: (id) =>
winston.debug("exec request for cell with id: '#{id}'")
@sage_remove_cell_flag(id, diffsync.FLAGS.execute)
{code, output_id} = @sage_initialize_cell_for_execute(id)
winston.debug("exec code '#{code}'; output id='#{output_id}'")
#if diffsync.FLAGS.auto in @sage_get_cell_flagstring(id) and 'auto' not in code
#@sage_remove_cell_flag(id, diffsync.FLAGS.auto)
@set_content(@content)
if code != ""
@_sage_output_to_input_id[output_id] = id
winston.debug("start running -- #{id}")
# Change the cell to "running" mode - this doesn't generate output, so we must explicit force clients
# to sync.
@sage_set_cell_flag(id, diffsync.FLAGS.running)
@sage_set_cell_flag(id, diffsync.FLAGS.this_session)
@_set_content_and_sync()
@sage_socket (err, socket) =>
if err
winston.debug("Error getting sage socket: #{err}")
@sage_output_mesg(output_id, {stderr: "Error getting sage socket (unable to execute code): #{err}"})
@sage_remove_cell_flag(id, diffsync.FLAGS.running)
return
winston.debug("Sending execute message to sage socket.")
socket.write_mesg 'json',
message.execute_code
id : output_id
cell_id : id # extra info -- which cell is running
code : code
preparse : true
# Execute code in the Sage session associated to this sync'd editor session
sage_execute_code: (client_socket, mesg) =>
#winston.debug("sage_execute_code '#{misc.to_json(mesg)}")
client_id = mesg.client_id
@_sage_output_cb[mesg.id] = (resp) =>
resp.client_id = client_id
#winston.debug("sage_execute_code -- got output: #{misc.to_json(resp)}")
client_socket.write_mesg('json', resp)
@sage_socket (err, socket) =>
#winston.debug("sage_execute_code: #{misc.to_json(err)}, #{socket}")
if err
#winston.debug("Error getting sage socket: #{err}")
resp = message.output(stderr: "Error getting sage socket (unable to execute code): #{err}", done:true)
client_socket.write_mesg('json', resp)
else
#winston.debug("sage_execute_code: writing request message -- #{misc.to_json(mesg)}")
mesg.event = 'execute_code' # event that sage session understands
socket.write_mesg('json', mesg)
sage_raw_input: (client_socket, mesg) =>
winston.debug("sage_raw_input '#{misc.to_json(mesg)}")
@sage_socket (err, socket) =>
if err
winston.debug("sage_raw_input: error getting sage socket -- #{err}")
else
socket.write_mesg('json', mesg)
sage_call: (opts) =>
opts = defaults opts,
mesg : required
cb : undefined
f = (resp) =>
opts.cb?(false, resp)
delete @_sage_output_cb[opts.mesg.id] # exactly one response
@sage_socket (err, socket) =>
if err
opts.cb?("error getting sage socket -- #{err}")
else
@_sage_output_cb[opts.mesg.id] = f
socket.write_mesg('json', opts.mesg)
sage_introspect:(client_socket, mesg) =>
mesg.event = 'introspect' # event that sage session understand
@sage_call
mesg : mesg
cb : (err, resp) =>
if err
resp = message.error(error:"Error getting sage socket (unable to introspect): #{err}")
client_socket.write_mesg('json', resp)
else
client_socket.write_mesg('json', resp)
send_signal_to_sage_session: (client_socket, mesg) =>
if @_sage_socket?
process_kill(@_sage_socket.pid, mesg.signal)
if mesg.id? and client_socket?
client_socket.write_mesg('json', message.signal_sent(id:mesg.id))
sage_update: (opts={}) =>
opts = defaults opts,
kill : false # if true, remove all running flags and all this_session flags
auto : false # if true, run all cells that have the auto flag set
if not @content? # document not initialized
return
# Here we:
# - scan the string @content for execution requests.
# - also, if we see a cell UUID that we've seen already, we randomly generate
# a new cell UUID; clients can annoyingly generate non-unique UUID's (e.g., via
# cut and paste) so we fix that.
winston.debug("sage_update")#: opts=#{misc.to_json(opts)}")
i = 0
prev_ids = {}
z = 0
while true
z += 1
if z > 5000
winston.debug("sage_update: ERROR -- hit a possible infinite loop; opts=#{misc.to_json(opts)}")
break
i = @content.indexOf(diffsync.MARKERS.cell, i)
if i == -1
break
j = @content.indexOf(diffsync.MARKERS.cell, i+1)
if j == -1
break # corrupt and is the last one, so not a problem.
id = @content.slice(i+1,i+37)
if misc.is_valid_uuid_string(id)
# if id isn't valid -- due to document corruption or a bug, just skip it rather than get into all kinds of trouble.
# TODO: repair.
if prev_ids[id]?
# oops, repeated "unique" id, so fix it.
id = uuid.v4()
@content = @content.slice(0,i+1) + id + @content.slice(i+37)
# Also, if 'r' in the flags for this cell, remove it since it
# can't possibly be already running (given the repeat).
flags = @content.slice(i+37, j)
if diffsync.FLAGS.running in flags
new_flags = ''
for t in flags
if t != diffsync.FLAGS.running
new_flags += t
@content = @content.slice(0,i+37) + new_flags + @content.slice(j)
prev_ids[id] = true
flags = @content.slice(i+37, j)
if opts.kill or opts.auto
if opts.kill
# worksheet process just killed, so clear certain flags.
new_flags = ''
for t in flags
if t != diffsync.FLAGS.running and t != diffsync.FLAGS.this_session
new_flags += t
#winston.debug("sage_update: kill=true, so changing flags from '#{flags}' to '#{new_flags}'")
if flags != new_flags
@content = @content.slice(0,i+37) + new_flags + @content.slice(j)
if opts.auto and diffsync.FLAGS.auto in flags
# worksheet process being restarted, so run auto cells
@sage_remove_cell_flag(id, diffsync.FLAGS.auto)
@sage_execute_cell(id)
else if diffsync.FLAGS.execute in flags
# normal execute
@sage_execute_cell(id)
# set i to next position after end of line that contained flag we just considered;
# above code may have added flags to this line (but won't have added anything before this line).
i = @content.indexOf('\n',j + 1)
if i == -1
break
sage_output_mesg: (output_id, mesg) =>
cell_id = @_sage_output_to_input_id[output_id]
#winston.debug("output_id=#{output_id}; cell_id=#{cell_id}; map=#{misc.to_json(@_sage_output_to_input_id)}")
if mesg.hide?
# Hide a single component (also, do not record the message itself in the
# document, just its impact).
flag = undefined
if mesg.hide == 'input'
flag = diffsync.FLAGS.hide_input
else if mesg.hide == 'output'
flag = diffsync.FLAGS.hide_output
if flag?
@sage_set_cell_flag(cell_id, flag)
else
winston.debug("invalid hide component: '#{mesg.hide}'")
delete mesg.hide
if mesg.show?
# Show a single component of cell.
flag = undefined
if mesg.show == 'input'
flag = diffsync.FLAGS.hide_input
else if mesg.show == 'output'
flag = diffsync.FLAGS.hide_output
if flag?
@sage_remove_cell_flag(cell_id, flag)
else
winston.debug("invalid hide component: '#{mesg.hide}'")
delete mesg.show
if mesg.auto?
# set or unset whether or not cell is automatically executed on startup of worksheet
if mesg.auto
@sage_set_cell_flag(cell_id, diffsync.FLAGS.auto)
else
@sage_remove_cell_flag(cell_id, diffsync.FLAGS.auto)
if mesg.done? and mesg.done and cell_id?
@sage_remove_cell_flag(cell_id, diffsync.FLAGS.running)
delete @_sage_output_to_input_id[output_id]
delete mesg.done # not needed
if /^\s\s*/.test(mesg.stdout) # final whitespace not needed for proper display
delete mesg.stdout
if /^\s\s*/.test(mesg.stderr)
delete mesg.stderr
if misc.is_empty_object(mesg)
return
if mesg.once? and mesg.once
# only javascript is define once=True
if mesg.javascript?
msg = message.execute_javascript
session_uuid : @session_uuid
code : mesg.javascript.code
coffeescript : mesg.javascript.coffeescript
obj : mesg.obj
cell_id : cell_id
bcast = message.codemirror_bcast
session_uuid : @session_uuid
mesg : msg
@client_bcast(undefined, bcast)
return # once = do *not* want to record this message in the output stream.
i = @content.indexOf(diffsync.MARKERS.output + output_id)
if i == -1
# no such output cell anymore -- ignore (?) -- or we could make such a cell...?
winston.debug("WORKSHEET: no such output cell (ignoring) -- #{output_id}")
return
n = @content.indexOf('\n', i)
if n == -1
winston.debug("WORKSHEET: output cell corrupted (ignoring) -- #{output_id}")
return
if mesg.clear?
# delete all output server side
k = i + (diffsync.MARKERS.output + output_id).length + 1
@content = @content.slice(0, k) + @content.slice(n)
return
if mesg.delete_last?
k = @content.lastIndexOf(diffsync.MARKERS.output, n-2)
@content = @content.slice(0, k+1) + @content.slice(n)
return
@content = @content.slice(0,n) + JSON.stringify(mesg) + diffsync.MARKERS.output + @content.slice(n)
sage_find_cell_meta: (id, start) =>
i = @content.indexOf(diffsync.MARKERS.cell + id, start)
j = @content.indexOf(diffsync.MARKERS.cell, i+1)
if j == -1
return undefined
return {start:i, end:j}
sage_get_cell_flagstring: (id) =>
pos = @sage_find_cell_meta(id)
return @content.slice(pos.start+37, pos.end)
sage_set_cell_flagstring: (id, flags) =>
pos = @sage_find_cell_meta(id)
if pos?
@content = @content.slice(0, pos.start+37) + flags + @content.slice(pos.end)
sage_set_cell_flag: (id, flag) =>
s = @sage_get_cell_flagstring(id)
if flag not in s
@sage_set_cell_flagstring(id, flag + s)
sage_remove_cell_flag: (id, flag) =>
s = @sage_get_cell_flagstring(id)
if flag in s
s = s.replace(new RegExp(flag, "g"), "")
@sage_set_cell_flagstring(id, s)
sage_initialize_cell_for_execute: (id, start) => # start is optional, but can speed finding cell
# Initialize the line of the document for output for the cell with given id.
# We do this by finding where that cell starts, then searching for the start
# of the next cell, deleting any output lines in between, and placing one new line
# for output. This function returns
# - output_id: a newly created id that identifies the new output line.
# - code: the string of code that will be executed by Sage.
# Or, it returns undefined if there is no cell with this id.
cell_start = @content.indexOf(diffsync.MARKERS.cell + id, start)
if cell_start == -1
# there is now no cell with this id.
return
code_start = @content.indexOf(diffsync.MARKERS.cell, cell_start+1)
if code_start == -1
# TODO: cell is mangled: would need to fix...?
return
newline = @content.indexOf('\n', cell_start) # next newline after cell_start
next_cell = @content.indexOf(diffsync.MARKERS.cell, code_start+1)
if newline == -1
# At end of document: append a newline to end of document; this is where the output will go.
# This is a very common special case; it's what we would get typing "2+2[shift-enter]"
# into a blank worksheet.
output_start = @content.length # position where the output will start
# Put some extra newlines in, since it is hard to put input at the bottom of the screen.
@content += '\n\n\n\n\n'
winston.debug("Add a new input cell at the very end (which will be after the output).")
else
while true
next_cell_start = @content.indexOf(diffsync.MARKERS.cell, newline)
if next_cell_start == -1
# This is the last cell, so we end the cell after the last line with no whitespace.
next_cell_start = @content.search(/\s+$/)
if next_cell_start == -1
next_cell_start = @content.length+1
@content += '\n\n\n\n\n'
else
while next_cell_start < @content.length and @content[next_cell_start]!='\n'
next_cell_start += 1
if @content[next_cell_start]!='\n'
@content += '\n\n\n\n\n'
next_cell_start += 1
output = @content.indexOf(diffsync.MARKERS.output, newline)
if output == -1 or output > next_cell_start
# no more output lines to delete
output_start = next_cell_start # this is where the output line will start
break
else
# delete the line of output we just found
output_end = @content.indexOf('\n', output+1)
@content = @content.slice(0, output) + @content.slice(output_end+1)
code = @content.slice(code_start+1, output_start)
output_id = uuid.v4()
if output_start > 0 and @content[output_start-1] != '\n'
output_insert = '\n'
else
output_insert = ''
output_insert += diffsync.MARKERS.output + output_id + diffsync.MARKERS.output + '\n'
if next_cell == -1
# There is no next cell.
output_insert += diffsync.MARKERS.cell + uuid.v4() + diffsync.MARKERS.cell + '\n'
@content = @content.slice(0, output_start) + output_insert + @content.slice(output_start)
return {code:code.trim(), output_id:output_id}
##############################
kill: () =>
# Put any cleanup here...
winston.debug("Killing session #{@session_uuid}")
@sync_filesystem () =>
@diffsync_fileserver.kill()
# TODO: Are any of these deletes needed? I don't know.
delete @content
delete @diffsync_fileclient
delete @diffsync_fileserver
if @_sage_socket?
# send FIN packet so that Sage process may terminate naturally
@_sage_socket.end()
# ... then, brutally kill it if need be (a few seconds later). :-)
if @_sage_socket.pid?
setTimeout( (() => process_kill(@_sage_socket.pid, 9)), 3000 )
set_content: (value) =>
@is_active = true
changed = false
if @content != value
@content = value
changed = true
if @diffsync_fileclient.live != value
@diffsync_fileclient.live = value
changed = true
for id, ds_client of @diffsync_clients
if ds_client.live != value
changed = true
ds_client.live = value
return changed
client_bcast: (socket, mesg) =>
@is_active = true
winston.debug("client_bcast: #{json(mesg)}")
# Forward this message on to all global hubs except the
# one that just sent it to us...
client_id = mesg.client_id
for id, ds_client of @diffsync_clients
if client_id != id
mesg.client_id = id
#winston.debug("BROADCAST: sending message from hub with socket.id=#{socket?.id} to hub with socket.id = #{id}")
ds_client.remote.socket.write_mesg('json', mesg)
client_diffsync: (socket, mesg) =>
@is_active = true
write_mesg = (event, obj) ->
if not obj?
obj = {}
obj.id = mesg.id
socket.write_mesg 'json', message[event](obj)
# Message from some client reporting new edits, thus initiating a sync.
ds_client = @diffsync_clients[mesg.client_id]
if not ds_client?
write_mesg('error', {error:"client #{mesg.client_id} not registered for synchronization"})
return
if @_client_sync_lock # or Math.random() <= .5 # (for testing)
winston.debug("client_diffsync hit a click_sync_lock -- send retry message back")
write_mesg('error', {error:"retry"})
return
if @_filesystem_sync_lock
if @_filesystem_sync_lock < new Date()
@_filesystem_sync_lock = false
else
winston.debug("client_diffsync hit a filesystem_sync_lock -- send retry message back")
write_mesg('error', {error:"retry"})
return
@_client_sync_lock = true
before = @content
ds_client.recv_edits mesg.edit_stack, mesg.last_version_ack, (err) => # TODO: why is this err ignored?
@set_content(ds_client.live)
@_client_sync_lock = false
@process_new_content?()
# Send back our own edits to the global hub.
ds_client.remote.current_mesg_id = mesg.id # used to tag the return message
ds_client.push_edits (err) =>
if err
winston.debug("CodeMirrorSession -- client push_edits returned -- #{err}")
else
changed = (before != @content)
if changed
# We also suggest to other clients to update their state.
@tell_clients_to_update(mesg.client_id)
@update_revision_tracking()
tell_clients_to_update: (exclude) =>
for id, ds_client of @diffsync_clients
if exclude != id
ds_client.remote.sync_ready()
sync_filesystem: (cb) =>
@is_active = true
if @_client_sync_lock # or Math.random() <= .5 # (for testing)
winston.debug("sync_filesystem -- hit client sync lock")
cb?("cannot sync with filesystem while syncing with clients")
return
if @_filesystem_sync_lock
if @_filesystem_sync_lock < new Date()
@_filesystem_sync_lock = false
else
winston.debug("sync_filesystem -- hit filesystem sync lock")
cb?("cannot sync with filesystem; already syncing")
return
before = @content
if not @diffsync_fileclient?
cb?("filesystem sync object (@diffsync_fileclient) no longer defined")
return
@_filesystem_sync_lock = expire_time(10) # lock expires in 10 seconds no matter what -- uncaught exception could require this
@diffsync_fileclient.sync (err) =>
if err
# Example error: 'reset -- checksum mismatch (29089 != 28959)'
winston.debug("@diffsync_fileclient.sync -- returned an error -- #{err}")
@diffsync_fileserver.kill() # stop autosaving and watching files
# Completely recreate diffsync file connection and try to sync once more.
@diffsync_fileserver = new DiffSyncFile_server @, (err, ignore_content) =>
if err
winston.debug("@diffsync_fileclient.sync -- making new server failed: #{err}")
@_filesystem_sync_lock = false
cb?(err); return
@diffsync_fileclient = new DiffSyncFile_client(@diffsync_fileserver)
@diffsync_fileclient.live = @content
@diffsync_fileclient.sync (err) =>
if err
winston.debug("@diffsync_fileclient.sync -- making server worked but re-sync failed -- #{err}")
@_filesystem_sync_lock = false
cb?("codemirror fileclient sync error -- '#{err}'")
else
@_filesystem_sync_lock = false
cb?()
return
if @diffsync_fileclient.live != @content
@set_content(@diffsync_fileclient.live)
# recommend all clients sync
for id, ds_client of @diffsync_clients
ds_client.remote.sync_ready()
@_filesystem_sync_lock = false
cb?()
add_client: (socket, client_id) =>
@is_active = true
ds_client = new diffsync.DiffSync(doc:@content)
ds_client.connect(new CodeMirrorDiffSyncHub(socket, @session_uuid, client_id))
@diffsync_clients[client_id] = ds_client
winston.debug("CodeMirrorSession(#{@path}).add_client(client_id=#{client_id}) -- now we have #{misc.len(@diffsync_clients)} clients.")
# Ensure we do not broadcast to a hub if it has already disconnected.
socket.on 'end', () =>
winston.debug("DISCONNECT: socket connection #{socket.id} from global hub disconected.")
delete @diffsync_clients[client_id]
remove_client: (socket, client_id) =>
delete @diffsync_clients[client_id]
write_to_disk: (socket, mesg) =>
@is_active = true
winston.debug("write_to_disk: #{json(mesg)} -- calling sync_filesystem")
@sync_filesystem (err) =>
if err
resp = message.error(id:mesg.id, error:"Error writing file '#{@path}' to disk -- #{err}")
else
resp = message.codemirror_wrote_to_disk(id:mesg.id, hash:misc.hash_string(@content))
socket.write_mesg('json', resp)
read_from_disk: (socket, mesg) =>
async.series([
(cb) =>
fs.stat (err, stats) =>
if err
cb(err)
else
cb(check_file_size(stats.size))
(cb) =>
fs.readFile @path, (err, data) =>
if err
cb("Error reading file '#{@path}' from disk -- #{err}")
else
value = data.toString()
if value != @content
@set_content(value)
# Tell the global hubs that now might be a good time to do a sync.
for id, ds of @diffsync_clients
ds.remote.sync_ready()
cb()
], (err) =>
if err
socket.write_mesg('json', message.error(id:mesg.id, error:err))
else
socket.write_mesg('json', message.success(id:mesg.id))
)
get_content: (socket, mesg) =>
@is_active = true
socket.write_mesg('json', message.codemirror_content(id:mesg.id, content:@content))
# enable or disable tracking all revisions of the document
revision_tracking: (socket, mesg) =>
winston.debug("revision_tracking for #{@path}: #{mesg.enable}")
d = (m) -> winston.debug("revision_tracking for #{@path}: #{m}")
if mesg.enable
d("enable it")
if @revision_tracking_doc?
d("already enabled")
# already enabled
socket.write_mesg('json', message.success(id:mesg.id))
else
if @readonly
# nothing to do -- silently don't enable (is this a good choice?)
socket.write_mesg('json', message.success(id:mesg.id))
return
# need to enable
d("need to enable")
codemirror_sessions.connect
mesg :
path : revision_tracking_path(@path)
project_id : INFO.project_id # todo -- won't need in long run
cb : (err, session) =>
d("got response -- #{err}")
if err
socket.write_mesg('json', message.error(id:mesg.id, error:err))
else
@revision_tracking_doc = session
socket.write_mesg('json', message.success(id:mesg.id))
@update_revision_tracking()
else
d("disable it")
delete @revision_tracking_doc
socket.write_mesg('json', message.success(id:mesg.id))
# If we are tracking the revision history of this file, add a new entry in that history.
# TODO: add user responsibile for this change as input to this function and as
# a field in the entry object below. NOTE: Be sure to include "changing the file on disk"
# as one of the users, which is *NOT* defined by an account_id.
update_revision_tracking: () =>
if not @revision_tracking_doc?
return
winston.debug("update revision tracking data - #{@path}")
# @revision_tracking_doc.HEAD is the last version of the document we're tracking, as a string.
# In particular, it is NOT in JSON format.
if not @revision_tracking_doc.HEAD?
# Initialize HEAD from the file
if @revision_tracking_doc.content.length == 0
# brand new -- first time.
@revision_tracking_doc.HEAD = @content
@revision_tracking_doc.content = misc.to_json(@content)
else
# we have tracked this file before.
i = @revision_tracking_doc.content.indexOf('\n')
if i == -1
# weird special case: there's no history yet -- just the initial version
@revision_tracking_doc.HEAD = misc.from_json(@revision_tracking_doc.content)
else
# there is a potential longer history; this initial version is the first line:
@revision_tracking_doc.HEAD = misc.from_json(@revision_tracking_doc.content.slice(0,i))
if @revision_tracking_doc.HEAD != @content
# compute diff that transforms @revision_tracking_doc.HEAD to @content
patch = diffsync.dmp.patch_make(@content, @revision_tracking_doc.HEAD)
@revision_tracking_doc.HEAD = @content
# replace the file by new version that has first line equal to JSON version of HEAD,
# and rest all the patches, with our one new patch inserted at the front.
# TODO: redo without doing a split for efficiency.
i = @revision_tracking_doc.content.indexOf('\n')
entry = {patch:diffsync.compress_patch(patch), time:new Date() - 0}
@revision_tracking_doc.content = misc.to_json(@content) + '\n' + \
misc.to_json(entry) + \
(if i != -1 then @revision_tracking_doc.content.slice(i) else "")
# now tell everybody
@revision_tracking_doc._set_content_and_sync()
# save the revision tracking file to disk (but not too frequently)
if not @revision_tracking_save_timer?
f = () =>
delete @revision_tracking_save_timer
@revision_tracking_doc.sync_filesystem()
@revision_tracking_save_timer = setInterval(f, REVISION_TRACKING_SAVE_INTERVAL)
# Collection of all CodeMirror sessions hosted by this local_hub.
class CodeMirrorSessions
constructor: () ->
@_sessions = {by_uuid:{}, by_path:{}, by_project:{}}
connect: (opts) =>
opts = defaults opts,
client_socket : undefined
mesg : required # event of type codemirror_get_session
cb : undefined # cb?(err, session)
mesg = opts.mesg
finish = (session) ->
if not opts.client_socket?
return
session.add_client(opts.client_socket, mesg.client_id)
opts.client_socket.write_mesg 'json', message.codemirror_session
id : mesg.id,
session_uuid : session.session_uuid
path : session.path
content : session.content
readonly : session.readonly
if mesg.session_uuid?
session = @_sessions.by_uuid[mesg.session_uuid]
if session?
finish(session)
opts.cb?(undefined, session)
return
if mesg.path?
session = @_sessions.by_path[mesg.path]
if session?
finish(session)
opts.cb?(undefined, session)
return
mesg.session_uuid = uuid.v4()
new CodeMirrorSession mesg, (err, session) =>
if err
opts.client_socket?.write_mesg('json', message.error(id:mesg.id, error:err))
opts.cb?(err)
else
@add_session_to_cache
session : session
project_id : mesg.project_id
timeout : 3600 # time in seconds (or undefined to not use timer)
finish(session)
opts.cb?(undefined, session)
add_session_to_cache: (opts) =>
opts = defaults opts,
session : required
project_id : undefined
timeout : undefined # or a time in seconds
winston.debug("Adding session #{opts.session.session_uuid} (of project #{opts.project_id}) to cache.")
@_sessions.by_uuid[opts.session.session_uuid] = opts.session
@_sessions.by_path[opts.session.path] = opts.session
if opts.project_id?
if not @_sessions.by_project[opts.project_id]?
@_sessions.by_project[opts.project_id] = {}
@_sessions.by_project[opts.project_id][opts.session.path] = opts.session
destroy = () =>
opts.session.kill()
delete @_sessions.by_uuid[opts.session.session_uuid]
delete @_sessions.by_path[opts.session.path]
x = @_sessions.by_project[opts.project_id]
if x?
delete x[opts.session.path]
if opts.timeout?
destroy_if_inactive = () =>
if not (opts.session.is_active? and opts.session.is_active)
winston.debug("Session #{opts.session.session_uuid} is inactive for #{opts.timeout} seconds; killing.")
destroy()
else
opts.session.is_active = false # it must be changed by the session before the next timer.
# We use setTimeout instead of setInterval, because we want to *ensure* that the
# checks are spaced out over at *least* opts.timeout time.
winston.debug("Starting a new activity check timer for session #{opts.session.session_uuid}.")
setTimeout(destroy_if_inactive, opts.timeout*1000)
setTimeout(destroy_if_inactive, opts.timeout*1000)
# Return object that describes status of CodeMirror sessions for a given project
info: (project_id) =>
obj = {}
X = @_sessions.by_project[project_id]
if X?
for path, session of X
obj[session.session_uuid] = {path : session.path}
return obj
handle_mesg: (client_socket, mesg) =>
winston.debug("CodeMirrorSessions.handle_mesg: '#{json(mesg)}'")
if mesg.event == 'codemirror_get_session'
@connect
client_socket : client_socket
mesg : mesg
return
# all other message types identify the session only by the uuid.
session = @_sessions.by_uuid[mesg.session_uuid]
if not session?
winston.debug("codemirror.handle_mesg -- Unknown CodeMirror session: #{mesg.session_uuid}.")
client_socket.write_mesg('json', message.error(id:mesg.id, error:"Unknown CodeMirror session: #{mesg.session_uuid}."))
return
switch mesg.event
when 'codemirror_diffsync'
session.client_diffsync(client_socket, mesg)
when 'codemirror_bcast'
session.client_bcast(client_socket, mesg)
when 'codemirror_write_to_disk'
session.write_to_disk(client_socket, mesg)
when 'codemirror_read_from_disk'
session.read_from_disk(client_socket, mesg)
when 'codemirror_get_content'
session.get_content(client_socket, mesg)
when 'codemirror_revision_tracking' # enable/disable revision_tracking
session.revision_tracking(client_socket, mesg)
when 'codemirror_execute_code'
session.sage_execute_code(client_socket, mesg)
when 'codemirror_introspect'
session.sage_introspect(client_socket, mesg)
when 'codemirror_send_signal'
session.send_signal_to_sage_session(client_socket, mesg)
when 'codemirror_disconnect'
session.remove_client(client_socket, mesg.client_id)
client_socket.write_mesg('json', message.success(id:mesg.id))
when 'codemirror_sage_raw_input'
session.sage_raw_input(client_socket, mesg)
else
client_socket.write_mesg('json', message.error(id:mesg.id, error:"unknown CodeMirror session event: #{mesg.event}."))
codemirror_sessions = new CodeMirrorSessions()
###############################################
# Connecting to existing session or making a
# new one.
###############################################
connect_to_session = (socket, mesg) ->
winston.debug("connect_to_session -- type='#{mesg.type}'")
switch mesg.type
when 'console'
console_sessions.connect(socket, mesg)
when 'sage'
sage_sessions.connect(socket, mesg)
else
err = message.error(id:mesg.id, error:"Unsupported session type '#{mesg.type}'")
socket.write_mesg('json', err)
###############################################
# Kill an existing session.
###############################################
terminate_session = (socket, mesg) ->
cb = (err) ->
if err
mesg = message.error(id:mesg.id, error:err)
socket.write_mesg('json', mesg)
sid = mesg.session_uuid
if console_sessions.session_exists(sid)
console_sessions.terminate_session(sid, cb)
else if sage_sessions.session_exists(sid)
sage_sessions.terminate_session(sid, cb)
else
cb()
###############################################
# Read and write individual files
###############################################
# Read a file located in the given project. This will result in an
# error if the readFile function fails, e.g., if the file doesn't
# exist or the project is not open. We then send the resulting file
# over the socket as a blob message.
#
# Directories get sent as a ".tar.bz2" file.
# TODO: should support -- 'tar', 'tar.bz2', 'tar.gz', 'zip', '7z'. and mesg.archive option!!!
#
read_file_from_project = (socket, mesg) ->
data = undefined
path = abspath(mesg.path)
is_dir = undefined
id = undefined
archive = undefined
stats = undefined
async.series([
(cb) ->
#winston.debug("Determine whether the path '#{path}' is a directory or file.")
fs.stat path, (err, _stats) ->
if err
cb(err)
else
stats = _stats
is_dir = stats.isDirectory()
cb()
(cb) ->
# make sure the file isn't too large
cb(check_file_size(stats.size))
(cb) ->
if is_dir
if mesg.archive != 'tar.bz2'
cb("The only supported directory archive format is tar.bz2")
return
target = temp.path(suffix:'.' + mesg.archive)
#winston.debug("'#{path}' is a directory, so archive it to '#{target}', change path, and read that file")
archive = mesg.archive
if path[path.length-1] == '/' # common nuisance with paths to directories
path = path.slice(0,path.length-1)
split = misc.path_split(path)
path = target
# same patterns also in project.coffee (TODO)
args = ["--exclude=.sagemathcloud*", '--exclude=.forever', '--exclude=.node*', '--exclude=.npm', '--exclude=.sage', '-jcf', target, split.tail]
#winston.debug("tar #{args.join(' ')}")
child_process.execFile 'tar', args, {cwd:split.head}, (err, stdout, stderr) ->
if err
winston.debug("Issue creating tarball: #{err}, #{stdout}, #{stderr}")
cb(err)
else
cb()
else
#winston.debug("It is a file.")
cb()
(cb) ->
#winston.debug("Read the file into memory.")
fs.readFile path, (err, _data) ->
data = _data
cb(err)
(cb) ->
#winston.debug("Compute hash of file.")
id = misc_node.uuidsha1(data)
winston.debug("Hash = #{id}")
cb()
# TODO
# (cb) ->
# winston.debug("Send hash of file to hub to see whether or not we really need to send the file itself; it might already be known.")
# cb()
# (cb) ->
# winston.debug("Get message back from hub -- do we send file or not?")
# cb()
(cb) ->
#winston.debug("Finally, we send the file as a blob back to the hub.")
socket.write_mesg 'json', message.file_read_from_project(id:mesg.id, data_uuid:id, archive:archive)
socket.write_mesg 'blob', {uuid:id, blob:data}
cb()
], (err) ->
if err and err != 'file already known'
socket.write_mesg 'json', message.error(id:mesg.id, error:err)
if is_dir
fs.exists path, (exists) ->
if exists
winston.debug("It was a directory, so remove the temporary archive '#{path}'.")
fs.unlink(path)
)
write_file_to_project = (socket, mesg) ->
data_uuid = mesg.data_uuid
path = abspath(mesg.path)
# Listen for the blob containing the actual content that we will write.
write_file = (type, value) ->
if type == 'blob' and value.uuid == data_uuid
socket.removeListener 'mesg', write_file
async.series([
(cb) ->
ensure_containing_directory_exists(path, cb)
(cb) ->
#winston.debug('writing the file')
fs.writeFile(path, value.blob, cb)
], (err) ->
if err
#winston.debug("error writing file -- #{err}")
socket.write_mesg 'json', message.error(id:mesg.id, error:err)
else
#winston.debug("wrote file '#{path}' fine")
socket.write_mesg 'json', message.file_written_to_project(id:mesg.id)
)
socket.on 'mesg', write_file
###############################################
# Printing an individual file to pdf
###############################################
print_sagews = (opts) ->
opts = defaults opts,
path : required
outfile : required
title : required
author : required
date : required
contents : required
extra_data : undefined # extra data that is useful for displaying certain things in the worksheet.
timeout : 90
cb : required
extra_data_file = undefined
args = [opts.path, '--outfile', opts.outfile, '--title', opts.title, '--author', opts.author,'--date', opts.date, '--contents', opts.contents]
async.series([
(cb) ->
if not opts.extra_data?
cb(); return
extra_data_file = temp.path() + '.json'
args.push('--extra_data_file')
args.push(extra_data_file)
# NOTE: extra_data is a string that is *already* in JSON format.
fs.writeFile(extra_data_file, opts.extra_data, cb)
(cb) ->
# run the converter script
misc_node.execute_code
command : "sagews2pdf.py"
args : args
err_on_exit : false
bash : false
timeout : opts.timeout
cb : cb
], (err) =>
if extra_data_file?
fs.unlink(extra_data_file) # no need to wait for completion before calling opts.cb
opts.cb(err)
)
print_to_pdf = (socket, mesg) ->
ext = misc.filename_extension(mesg.path)
if ext
pdf = "#{mesg.path.slice(0,mesg.path.length-ext.length)}pdf"
else
pdf = mesg.path + '.pdf'
async.series([
(cb) ->
switch ext
when 'sagews'
print_sagews
path : mesg.path
outfile : pdf
title : mesg.options.title
author : mesg.options.author
date : mesg.options.date
contents : mesg.options.contents
extra_data : mesg.options.extra_data
timeout : mesg.options.timeout
cb : cb
else
cb("unable to print file of type '#{ext}'")
], (err) ->
if err
socket.write_mesg('json', message.error(id:mesg.id, error:err))
else
socket.write_mesg('json', message.printed_to_pdf(id:mesg.id, path:pdf))
)
###############################################
# Info
###############################################
session_info = (project_id) ->
return {
'sage_sessions' : sage_sessions.info(project_id)
'console_sessions' : console_sessions.info(project_id)
'file_sessions' : codemirror_sessions.info(project_id)
}
###############################################
# Manage Jupyter server
###############################################
jupyter_port_queue = []
jupyter_port = (socket, mesg) ->
winston.debug("jupyter_port")
jupyter_port_queue.push({socket:socket, mesg:mesg})
if jupyter_port_queue.length > 1
return
misc_node.execute_code
command : "ipython-notebook"
args : ['start']
err_on_exit : true
bash : false
timeout : 60
ulimit_timeout : false # very important -- so doesn't kill consoles after 60 seconds cputime!
cb : (err, out) ->
if not err
try
info = misc.from_json(out.stdout)
port = info?.port
if not port?
err = "unable to start -- no port; info=#{misc.to_json(out)}"
else
catch e
err = "error parsing ipython-notebook startup output -- #{e}, {misc.to_json(out)}"
if err
error = "error starting Jupyter -- #{err}"
for x in jupyter_port_queue
err_mesg = message.error
id : x.mesg.id
error : error
x.socket.write_mesg('json', err_mesg)
else
for x in jupyter_port_queue
resp = message.jupyter_port
port : port
id : x.mesg.id
x.socket.write_mesg('json', resp)
jupyter_port_queue = []
###############################################
# Execute a command line or block of BASH
###############################################
project_exec = (socket, mesg) ->
winston.debug("project_exec")
if mesg.command == "ipython-notebook"
socket.write_mesg("json", message.error(id:mesg.id, error:"old client code -- you may not run ipython-notebook directly"))
return
misc_node.execute_code
command : mesg.command
args : mesg.args
path : abspath(mesg.path)
timeout : mesg.timeout
err_on_exit : mesg.err_on_exit
max_output : mesg.max_output
bash : mesg.bash
cb : (err, out) ->
if err
error = "Error executing command '#{mesg.command}' with args '#{mesg.args}' -- #{err}, #{out?.stdout}, #{out?.stderr}"
if error.indexOf("Connection refused") != -1
error += "-- Email PI:EMAIL:<EMAIL>END_PI if you need external network access, which is disabled by default."
if error.indexOf("=") != -1
error += "-- This is a BASH terminal, not a Sage worksheet. For Sage, use +New and create a Sage worksheet."
err_mesg = message.error
id : mesg.id
error : error
socket.write_mesg('json', err_mesg)
else
#winston.debug(json(out))
socket.write_mesg 'json', message.project_exec_output
id : mesg.id
stdout : out.stdout
stderr : out.stderr
exit_code : out.exit_code
_save_blob_callbacks = {}
receive_save_blob_message = (opts) ->
opts = defaults opts,
sha1 : required
cb : required
timeout : 30 # maximum time in seconds to wait for response message
sha1 = opts.sha1
id = misc.uuid()
if not _save_blob_callbacks[sha1]?
_save_blob_callbacks[sha1] = [[opts.cb, id]]
else
_save_blob_callbacks[sha1].push([opts.cb, id])
# Timeout functionality -- send a response after opts.timeout seconds,
# in case no hub responded.
f = () ->
v = _save_blob_callbacks[sha1]
if v?
mesg = message.save_blob
sha1 : sha1
error : "timed out after local hub waited for #{opts.timeout} seconds"
w = []
for x in v # this is O(n) instead of O(1), but who cares since n is usually 1.
if x[1] == id
x[0](mesg)
else
w.push(x)
if w.length == 0
delete _save_blob_callbacks[sha1]
else
_save_blob_callbacks[sha1] = w
if opts.timeout
setTimeout(f, opts.timeout*1000)
handle_save_blob_message = (mesg) ->
v = _save_blob_callbacks[mesg.sha1]
if v?
for x in v
x[0](mesg)
delete _save_blob_callbacks[mesg.sha1]
###############################################
# Handle a message from the client
###############################################
handle_mesg = (socket, mesg, handler) ->
activity() # record that there was some activity so process doesn't killall
try
winston.debug("Handling '#{json(mesg)}'")
if mesg.event.split('_')[0] == 'codemirror'
codemirror_sessions.handle_mesg(socket, mesg)
return
switch mesg.event
when 'connect_to_session', 'start_session'
# These sessions completely take over this connection, so we better stop listening
# for further control messages on this connection.
socket.removeListener 'mesg', handler
connect_to_session(socket, mesg)
when 'project_session_info'
resp = message.project_session_info
id : mesg.id
project_id : mesg.project_id
info : session_info(mesg.project_id)
socket.write_mesg('json', resp)
when 'jupyter_port'
jupyter_port(socket, mesg)
when 'project_exec'
project_exec(socket, mesg)
when 'read_file_from_project'
read_file_from_project(socket, mesg)
when 'write_file_to_project'
write_file_to_project(socket, mesg)
when 'print_to_pdf'
print_to_pdf(socket, mesg)
when 'send_signal'
process_kill(mesg.pid, mesg.signal)
if mesg.id?
socket.write_mesg('json', message.signal_sent(id:mesg.id))
when 'terminate_session'
terminate_session(socket, mesg)
when 'save_blob'
handle_save_blob_message(mesg)
else
if mesg.id?
err = message.error(id:mesg.id, error:"Local hub received an invalid mesg type '#{mesg.event}'")
socket.write_mesg('json', err)
catch e
winston.debug(new Error().stack)
winston.error "ERROR: '#{e}' handling message '#{json(mesg)}'"
process_kill = (pid, signal) ->
switch signal
when 2
signal = 'SIGINT'
when 3
signal = 'SIGQUIT'
when 9
signal = 'SIGKILL'
else
winston.debug("BUG -- process_kill: only signals 2 (SIGINT), 3 (SIGQUIT), and 9 (SIGKILL) are supported")
return
try
process.kill(pid, signal)
catch e
# it's normal to get an exception when sending a signal... to a process that doesn't exist.
server = net.createServer (socket) ->
winston.debug "PARENT: received connection"
misc_node.unlock_socket socket, secret_token, (err) ->
if err
winston.debug(err)
else
socket.id = uuid.v4()
misc_node.enable_mesg(socket)
handler = (type, mesg) ->
if type == "json" # other types are handled elsewhere in event code.
winston.debug "received control mesg #{json(mesg)}"
handle_mesg(socket, mesg, handler)
socket.on 'mesg', handler
start_tcp_server = (cb) ->
winston.info("starting tcp server...")
server.listen program.port, '0.0.0.0', () ->
winston.info("listening on port #{server.address().port}")
fs.writeFile(abspath("#{DATA}/local_hub.port"), server.address().port, cb)
# use of domain inspired by http://stackoverflow.com/questions/17940895/handle-uncaughtexception-in-express-and-restify
# This addresses an issue where the raw server fails to startup, maybe due to race condition with misc_node.free_port;
# and... in any case if anything uncaught goes wrong starting the raw server or running, this will ensure
# that it gets fixed automatically.
raw_server_domain = require('domain').create()
raw_server_domain.on 'error', (err) ->
winston.debug("got an exception in raw server, so restarting.")
start_raw_server( () -> winston.debug("restarted raw http server") )
start_raw_server = (cb) ->
raw_server_domain.run () ->
winston.info("starting raw server...")
info = INFO
winston.debug("info = #{misc.to_json(info)}")
express = require('express')
raw_server = express()
project_id = info.project_id
misc_node.free_port (err, port) ->
if err
winston.debug("error starting raw server: #{err}")
cb(err); return
fs.writeFile(abspath("#{DATA}/raw.port"), port, cb)
base = "#{info.base_url}/#{project_id}/raw/"
winston.info("raw server (port=#{port}), host='#{info.location.host}', base='#{base}'")
raw_server.configure () ->
raw_server.use(base, express.directory(process.env.HOME, {hidden:true, icons:true}))
raw_server.use(base, express.static(process.env.HOME, {hidden:true}))
# NOTE: It is critical to only listen on the host interface (not localhost), since otherwise other users
# on the same VM could listen in. We firewall connections from the other VM hosts above
# port 1024, so this is safe without authentication. TODO: should we add some sort of auth (?) just in case?
raw_server.listen port, info.location.host, (err) ->
winston.info("err = #{err}")
if err
cb(err); return
fs.writeFile(abspath("#{DATA}/raw.port"), port, cb)
last_activity = undefined
# Call this function to signal that there is activity.
activity = () ->
last_activity = misc.mswalltime()
# Truncate the ~/.sagemathcloud.log if it exceeds a certain length threshhold.
SAGEMATHCLOUD_LOG_THRESH = 5000 # log grows to at most 50% more than this
SAGEMATHCLOUD_LOG_FILE = process.env['HOME'] + '/.sagemathcloud.log'
log_truncate = (cb) ->
data = undefined
winston.info("log_truncate: checking that logfile isn't too long")
exists = undefined
async.series([
(cb) ->
fs.exists SAGEMATHCLOUD_LOG_FILE, (_exists) ->
exists = _exists
cb()
(cb) ->
if not exists
cb(); return
# read the log file
fs.readFile SAGEMATHCLOUD_LOG_FILE, (err, _data) ->
data = _data?.toString() # ? is important, since in case of err _data is not defined.
cb(err)
(cb) ->
if not exists
cb(); return
# if number of lines exceeds 50% more than MAX_LINES
n = misc.count(data, '\n')
if n >= SAGEMATHCLOUD_LOG_THRESH * 1.5
winston.debug("log_truncate: truncating log file to #{SAGEMATHCLOUD_LOG_THRESH} lines")
v = data.split('\n') # the -1 below is since last entry is a blank line
new_data = v.slice(n - SAGEMATHCLOUD_LOG_THRESH, v.length-1).join('\n')
fs.writeFile(SAGEMATHCLOUD_LOG_FILE, new_data, cb)
else
cb()
], cb)
start_log_truncate = (cb) ->
winston.info("start_log_truncate")
f = (c) ->
winston.debug("calling log_truncate")
log_truncate (err) ->
if err
winston.debug("ERROR: problem truncating log -- #{err}")
c()
setInterval(f, 1000*3600*12) # once every 12 hours
f(cb)
# Start listening for connections on the socket.
exports.start_server = start_server = () ->
async.series [start_log_truncate, start_tcp_server, start_raw_server], (err) ->
if err
winston.debug("Error starting a server -- #{err}")
else
winston.debug("Successfully started servers.")
# daemonize it
program = require('commander')
daemon = require("start-stop-daemon")
program.usage('[start/stop/restart/status] [options]')
.option('--pidfile [string]', 'store pid in this file', String, abspath("#{DATA}/local_hub.pid"))
.option('--logfile [string]', 'write log to this file', String, abspath("#{DATA}/local_hub.log"))
.option('--forever_logfile [string]', 'write forever log to this file', String, abspath("#{DATA}/forever_local_hub.log"))
.option('--debug [string]', 'logging debug level (default: "debug"); "" for no debugging output)', String, 'debug')
.parse(process.argv)
if program._name.split('.')[0] == 'local_hub'
if program.debug
winston.remove(winston.transports.Console)
winston.add(winston.transports.Console, {level: program.debug, timestamp:true, colorize:true})
winston.debug "Running as a Daemon"
# run as a server/daemon (otherwise, is being imported as a library)
process.addListener "uncaughtException", (err) ->
winston.debug("BUG ****************************************************************************")
winston.debug("Uncaught exception: " + err)
winston.debug(err.stack)
winston.debug("BUG ****************************************************************************")
if console? and console.trace?
console.trace()
console.log("setting up conf path")
init_confpath()
init_info_json()
# empty the forever logfile -- it doesn't get reset on startup and easily gets huge.
fs.writeFileSync(program.forever_logfile, '')
console.log("start daemon")
daemon({pidFile:program.pidfile, outFile:program.logfile, errFile:program.logfile, logFile:program.forever_logfile, max:1}, start_server)
console.log("after daemon")
|
[
{
"context": "gs[1].username if args[1].username\n\t\t\t@password \t= args[1].password if args[1].password\n\t\t\tif args[1].par",
"end": 785,
"score": 0.9357552528381348,
"start": 781,
"tag": "PASSWORD",
"value": "args"
},
{
"context": "rname if args[1].username\n\t\t\t@password \t=... | sources/coffee/Request.coffee | heschel6/Magic_Experiment | 201 | # Request
class RequestEngine extends Element
_kind : 'RequestEngine'
url : NULL
parameters : NULL
files : NULL
username : NULL
password : NULL
success : NULL
error : NULL
async : yes
response : {}
xhttp : new XMLHttpRequest
constructor: (type, args)->
if not Utils.isString(args[0]) then return null
@url = args[0]
if Utils.isFunction(args[1])
@success = args[1]
@error = args[2] if Utils.isFunction(args[2])
else if Utils.isObject(args[1])
@success = args[1].success if args[1].success
@error = args[1].error if args[1].error
@files = args[1].files if args[1].files
@async = no if args[1].async is no
@then = args[1].then if args[1].then
@username = args[1].username if args[1].username
@password = args[1].password if args[1].password
if args[1].parameters and Utils.isObject(args[1].parameters)
@parameters = args[1].parameters
if Utils.isFunction(args[2])
@success = args[2]
@error = args[3] if Utils.isFunction(args[3])
if @parameters
that = @
@_parameters = Object.keys(@parameters).map((k) ->
encodeURIComponent(k) + '=' + encodeURIComponent(that.parameters[k])
).join('&')
if @files then @setUploadEvents()
@xhttp.onreadystatechange = @responseProcess.bind(this)
if type is 'GET' and @_parameters and @_parameters.length
@url = @url + '?' + @_parameters
@xhttp.open type, @url, @async, @username, @password
if type is 'POST' and @files
@_parameters = new FormData
for item of @parameters
console.log @parameters
@_parameters.append item, @parameters[item]
for item of @files
@_parameters.append item, @files[item]
else if type isnt 'GET'
@xhttp.setRequestHeader 'Content-type', 'application/x-www-form-urlencoded'
@xhttp.send @_parameters
return
setUploadEvents : ->
that = @
@xhttp.upload.addEventListener Event.Progress, (event) ->
event.progress = NULL
event.progress = event.loaded/event.total if event.lengthComputable
that.emit Event.Progress, event
return
@xhttp.upload.addEventListener Event.Loaded, (event) ->
event.progress = 100
that.emit Event.Load, event
return
@xhttp.upload.addEventListener Event.Error, (event) ->
that.emit Event.Error, event
return
@xhttp.upload.addEventListener Event.Abort, (event) ->
that.emit Event.Abort, event
return
setHTTPResponse : ->
if @xhttp.responseText isnt NULL
try
@response.data = JSON.parse(@xhttp.responseText)
catch err
@response.data = @xhttp.responseText
responseProcess : ->
@response.state = @xhttp.readyState
@response.status = @xhttp.status
if @xhttp.readyState is 4
@response.raw = @xhttp.responseText
if @xhttp.status.toString()[0] is '2'
if @success
@setHTTPResponse()
@success @response
@emit Event.Success, @response
else
if @error
@setHTTPResponse()
@error @response
@emit Event.Error, @response
if @then then @then @response
@emit Event.Response, @response
return
onSuccess : (cb) -> @on Event.Success, cb
onError : (cb) -> @on Event.Error, cb
onResponse : (cb) -> @on Event.Response, cb
onProgress : (cb) -> @on Event.Progress, cb
onAbort : (cb) -> @on Event.Abort, cb
onLoad : (cb) -> @on Event.Load, cb
onLoaded : (cb) -> @on Event.Loaded, cb
onDone : (cb) -> @on Event.Loaded, cb
Request =
get : ->
return null if arguments.length is 0
return new RequestEngine('GET', arguments)
send : ->
return null if arguments.length is 0
return new RequestEngine('POST', arguments)
delete : ->
return null if arguments.length is 0
return new RequestEngine('DELETE', arguments)
update : ->
return null if arguments.length is 0
return new RequestEngine('PUT', arguments)
| 60863 | # Request
class RequestEngine extends Element
_kind : 'RequestEngine'
url : NULL
parameters : NULL
files : NULL
username : NULL
password : NULL
success : NULL
error : NULL
async : yes
response : {}
xhttp : new XMLHttpRequest
constructor: (type, args)->
if not Utils.isString(args[0]) then return null
@url = args[0]
if Utils.isFunction(args[1])
@success = args[1]
@error = args[2] if Utils.isFunction(args[2])
else if Utils.isObject(args[1])
@success = args[1].success if args[1].success
@error = args[1].error if args[1].error
@files = args[1].files if args[1].files
@async = no if args[1].async is no
@then = args[1].then if args[1].then
@username = args[1].username if args[1].username
@password = <PASSWORD>[1].<PASSWORD> if args[1].password
if args[1].parameters and Utils.isObject(args[1].parameters)
@parameters = args[1].parameters
if Utils.isFunction(args[2])
@success = args[2]
@error = args[3] if Utils.isFunction(args[3])
if @parameters
that = @
@_parameters = Object.keys(@parameters).map((k) ->
encodeURIComponent(k) + '=' + encodeURIComponent(that.parameters[k])
).join('&')
if @files then @setUploadEvents()
@xhttp.onreadystatechange = @responseProcess.bind(this)
if type is 'GET' and @_parameters and @_parameters.length
@url = @url + '?' + @_parameters
@xhttp.open type, @url, @async, @username, @password
if type is 'POST' and @files
@_parameters = new FormData
for item of @parameters
console.log @parameters
@_parameters.append item, @parameters[item]
for item of @files
@_parameters.append item, @files[item]
else if type isnt 'GET'
@xhttp.setRequestHeader 'Content-type', 'application/x-www-form-urlencoded'
@xhttp.send @_parameters
return
setUploadEvents : ->
that = @
@xhttp.upload.addEventListener Event.Progress, (event) ->
event.progress = NULL
event.progress = event.loaded/event.total if event.lengthComputable
that.emit Event.Progress, event
return
@xhttp.upload.addEventListener Event.Loaded, (event) ->
event.progress = 100
that.emit Event.Load, event
return
@xhttp.upload.addEventListener Event.Error, (event) ->
that.emit Event.Error, event
return
@xhttp.upload.addEventListener Event.Abort, (event) ->
that.emit Event.Abort, event
return
setHTTPResponse : ->
if @xhttp.responseText isnt NULL
try
@response.data = JSON.parse(@xhttp.responseText)
catch err
@response.data = @xhttp.responseText
responseProcess : ->
@response.state = @xhttp.readyState
@response.status = @xhttp.status
if @xhttp.readyState is 4
@response.raw = @xhttp.responseText
if @xhttp.status.toString()[0] is '2'
if @success
@setHTTPResponse()
@success @response
@emit Event.Success, @response
else
if @error
@setHTTPResponse()
@error @response
@emit Event.Error, @response
if @then then @then @response
@emit Event.Response, @response
return
onSuccess : (cb) -> @on Event.Success, cb
onError : (cb) -> @on Event.Error, cb
onResponse : (cb) -> @on Event.Response, cb
onProgress : (cb) -> @on Event.Progress, cb
onAbort : (cb) -> @on Event.Abort, cb
onLoad : (cb) -> @on Event.Load, cb
onLoaded : (cb) -> @on Event.Loaded, cb
onDone : (cb) -> @on Event.Loaded, cb
Request =
get : ->
return null if arguments.length is 0
return new RequestEngine('GET', arguments)
send : ->
return null if arguments.length is 0
return new RequestEngine('POST', arguments)
delete : ->
return null if arguments.length is 0
return new RequestEngine('DELETE', arguments)
update : ->
return null if arguments.length is 0
return new RequestEngine('PUT', arguments)
| true | # Request
class RequestEngine extends Element
_kind : 'RequestEngine'
url : NULL
parameters : NULL
files : NULL
username : NULL
password : NULL
success : NULL
error : NULL
async : yes
response : {}
xhttp : new XMLHttpRequest
constructor: (type, args)->
if not Utils.isString(args[0]) then return null
@url = args[0]
if Utils.isFunction(args[1])
@success = args[1]
@error = args[2] if Utils.isFunction(args[2])
else if Utils.isObject(args[1])
@success = args[1].success if args[1].success
@error = args[1].error if args[1].error
@files = args[1].files if args[1].files
@async = no if args[1].async is no
@then = args[1].then if args[1].then
@username = args[1].username if args[1].username
@password = PI:PASSWORD:<PASSWORD>END_PI[1].PI:PASSWORD:<PASSWORD>END_PI if args[1].password
if args[1].parameters and Utils.isObject(args[1].parameters)
@parameters = args[1].parameters
if Utils.isFunction(args[2])
@success = args[2]
@error = args[3] if Utils.isFunction(args[3])
if @parameters
that = @
@_parameters = Object.keys(@parameters).map((k) ->
encodeURIComponent(k) + '=' + encodeURIComponent(that.parameters[k])
).join('&')
if @files then @setUploadEvents()
@xhttp.onreadystatechange = @responseProcess.bind(this)
if type is 'GET' and @_parameters and @_parameters.length
@url = @url + '?' + @_parameters
@xhttp.open type, @url, @async, @username, @password
if type is 'POST' and @files
@_parameters = new FormData
for item of @parameters
console.log @parameters
@_parameters.append item, @parameters[item]
for item of @files
@_parameters.append item, @files[item]
else if type isnt 'GET'
@xhttp.setRequestHeader 'Content-type', 'application/x-www-form-urlencoded'
@xhttp.send @_parameters
return
setUploadEvents : ->
that = @
@xhttp.upload.addEventListener Event.Progress, (event) ->
event.progress = NULL
event.progress = event.loaded/event.total if event.lengthComputable
that.emit Event.Progress, event
return
@xhttp.upload.addEventListener Event.Loaded, (event) ->
event.progress = 100
that.emit Event.Load, event
return
@xhttp.upload.addEventListener Event.Error, (event) ->
that.emit Event.Error, event
return
@xhttp.upload.addEventListener Event.Abort, (event) ->
that.emit Event.Abort, event
return
setHTTPResponse : ->
if @xhttp.responseText isnt NULL
try
@response.data = JSON.parse(@xhttp.responseText)
catch err
@response.data = @xhttp.responseText
responseProcess : ->
@response.state = @xhttp.readyState
@response.status = @xhttp.status
if @xhttp.readyState is 4
@response.raw = @xhttp.responseText
if @xhttp.status.toString()[0] is '2'
if @success
@setHTTPResponse()
@success @response
@emit Event.Success, @response
else
if @error
@setHTTPResponse()
@error @response
@emit Event.Error, @response
if @then then @then @response
@emit Event.Response, @response
return
onSuccess : (cb) -> @on Event.Success, cb
onError : (cb) -> @on Event.Error, cb
onResponse : (cb) -> @on Event.Response, cb
onProgress : (cb) -> @on Event.Progress, cb
onAbort : (cb) -> @on Event.Abort, cb
onLoad : (cb) -> @on Event.Load, cb
onLoaded : (cb) -> @on Event.Loaded, cb
onDone : (cb) -> @on Event.Loaded, cb
Request =
get : ->
return null if arguments.length is 0
return new RequestEngine('GET', arguments)
send : ->
return null if arguments.length is 0
return new RequestEngine('POST', arguments)
delete : ->
return null if arguments.length is 0
return new RequestEngine('DELETE', arguments)
update : ->
return null if arguments.length is 0
return new RequestEngine('PUT', arguments)
|
[
{
"context": " rich text editing jQuery UI widget\n# (c) 2011 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib",
"end": 79,
"score": 0.9998515844345093,
"start": 66,
"tag": "NAME",
"value": "Henri Bergius"
}
] | src/plugins/overlay.coffee | GerHobbelt/hallo | 682 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 Henri Bergius, IKS Consortium
# Hallo may be freely distributed under the MIT license
#
# -----------------------------------------
#
# Hallo overlay plugin
# (c) 2011 Liip AG, Switzerland
# This plugin may be freely distributed under the MIT license.
#
# The overlay plugin adds an overlay around the editable element.
# It has no direct dependency with other plugins, but requires the
# "floating" hallo option to be false to look nice. Furthermore, the
# toolbar should have the same width as the editable element.
((jQuery) ->
jQuery.widget "IKS.hallooverlay",
options:
editable: null
toolbar: null
uuid: ""
overlay: null
padding: 10
background: null
_create: ->
widget = this
unless @options.bound
@options.bound = true
@options.editable.element.on "halloactivated", (event, data) ->
widget.options.currentEditable = jQuery(event.target)
if !widget.options.visible
widget.showOverlay()
@options.editable.element.on "hallomodified", (event, data) ->
widget.options.currentEditable = jQuery(event.target)
if widget.options.visible
widget.resizeOverlay()
@options.editable.element.on "hallodeactivated", (event, data) ->
widget.options.currentEditable = jQuery(event.target)
if widget.options.visible
widget.hideOverlay()
showOverlay: ->
@options.visible = true
if @options.overlay is null
if jQuery("#halloOverlay").length > 0
@options.overlay = jQuery("#halloOverlay")
else
@options.overlay = jQuery "<div id=\"halloOverlay\"
class=\"halloOverlay\">"
jQuery(document.body).append @options.overlay
@options.overlay.on 'click'
, jQuery.proxy @options.editable.turnOff, @options.editable
@options.overlay.show()
if @options.background is null
if jQuery("#halloBackground").length > 0
@options.background = jQuery("#halloBackground")
else
@options.background = jQuery "<div id=\"halloBackground\"
class=\"halloBackground\">"
jQuery(document.body).append @options.background
@resizeOverlay()
@options.background.show()
unless @options.originalZIndex
@options.originalZIndex = @options.currentEditable.css "z-index"
@options.currentEditable.css 'z-index', '350'
resizeOverlay: ->
offset = @options.currentEditable.offset()
@options.background.css
top: offset.top - @options.padding
left: offset.left - @options.padding
width: @options.currentEditable.width() + 2 * @options.padding
height: @options.currentEditable.height() + 2 * @options.padding
hideOverlay: ->
@options.visible = false
@options.overlay.hide()
@options.background.hide()
@options.currentEditable.css 'z-index', @options.originalZIndex
# Find the closest parent having a background color. If none, returns white.
_findBackgroundColor: (jQueryfield) ->
color = jQueryfield.css "background-color"
if color isnt 'rgba(0, 0, 0, 0)' and color isnt 'transparent'
return color
if jQueryfield.is "body"
return "white"
else
return @_findBackgroundColor jQueryfield.parent()
)(jQuery)
| 58319 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 <NAME>, IKS Consortium
# Hallo may be freely distributed under the MIT license
#
# -----------------------------------------
#
# Hallo overlay plugin
# (c) 2011 Liip AG, Switzerland
# This plugin may be freely distributed under the MIT license.
#
# The overlay plugin adds an overlay around the editable element.
# It has no direct dependency with other plugins, but requires the
# "floating" hallo option to be false to look nice. Furthermore, the
# toolbar should have the same width as the editable element.
((jQuery) ->
jQuery.widget "IKS.hallooverlay",
options:
editable: null
toolbar: null
uuid: ""
overlay: null
padding: 10
background: null
_create: ->
widget = this
unless @options.bound
@options.bound = true
@options.editable.element.on "halloactivated", (event, data) ->
widget.options.currentEditable = jQuery(event.target)
if !widget.options.visible
widget.showOverlay()
@options.editable.element.on "hallomodified", (event, data) ->
widget.options.currentEditable = jQuery(event.target)
if widget.options.visible
widget.resizeOverlay()
@options.editable.element.on "hallodeactivated", (event, data) ->
widget.options.currentEditable = jQuery(event.target)
if widget.options.visible
widget.hideOverlay()
showOverlay: ->
@options.visible = true
if @options.overlay is null
if jQuery("#halloOverlay").length > 0
@options.overlay = jQuery("#halloOverlay")
else
@options.overlay = jQuery "<div id=\"halloOverlay\"
class=\"halloOverlay\">"
jQuery(document.body).append @options.overlay
@options.overlay.on 'click'
, jQuery.proxy @options.editable.turnOff, @options.editable
@options.overlay.show()
if @options.background is null
if jQuery("#halloBackground").length > 0
@options.background = jQuery("#halloBackground")
else
@options.background = jQuery "<div id=\"halloBackground\"
class=\"halloBackground\">"
jQuery(document.body).append @options.background
@resizeOverlay()
@options.background.show()
unless @options.originalZIndex
@options.originalZIndex = @options.currentEditable.css "z-index"
@options.currentEditable.css 'z-index', '350'
resizeOverlay: ->
offset = @options.currentEditable.offset()
@options.background.css
top: offset.top - @options.padding
left: offset.left - @options.padding
width: @options.currentEditable.width() + 2 * @options.padding
height: @options.currentEditable.height() + 2 * @options.padding
hideOverlay: ->
@options.visible = false
@options.overlay.hide()
@options.background.hide()
@options.currentEditable.css 'z-index', @options.originalZIndex
# Find the closest parent having a background color. If none, returns white.
_findBackgroundColor: (jQueryfield) ->
color = jQueryfield.css "background-color"
if color isnt 'rgba(0, 0, 0, 0)' and color isnt 'transparent'
return color
if jQueryfield.is "body"
return "white"
else
return @_findBackgroundColor jQueryfield.parent()
)(jQuery)
| true | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 PI:NAME:<NAME>END_PI, IKS Consortium
# Hallo may be freely distributed under the MIT license
#
# -----------------------------------------
#
# Hallo overlay plugin
# (c) 2011 Liip AG, Switzerland
# This plugin may be freely distributed under the MIT license.
#
# The overlay plugin adds an overlay around the editable element.
# It has no direct dependency with other plugins, but requires the
# "floating" hallo option to be false to look nice. Furthermore, the
# toolbar should have the same width as the editable element.
((jQuery) ->
jQuery.widget "IKS.hallooverlay",
options:
editable: null
toolbar: null
uuid: ""
overlay: null
padding: 10
background: null
_create: ->
widget = this
unless @options.bound
@options.bound = true
@options.editable.element.on "halloactivated", (event, data) ->
widget.options.currentEditable = jQuery(event.target)
if !widget.options.visible
widget.showOverlay()
@options.editable.element.on "hallomodified", (event, data) ->
widget.options.currentEditable = jQuery(event.target)
if widget.options.visible
widget.resizeOverlay()
@options.editable.element.on "hallodeactivated", (event, data) ->
widget.options.currentEditable = jQuery(event.target)
if widget.options.visible
widget.hideOverlay()
showOverlay: ->
@options.visible = true
if @options.overlay is null
if jQuery("#halloOverlay").length > 0
@options.overlay = jQuery("#halloOverlay")
else
@options.overlay = jQuery "<div id=\"halloOverlay\"
class=\"halloOverlay\">"
jQuery(document.body).append @options.overlay
@options.overlay.on 'click'
, jQuery.proxy @options.editable.turnOff, @options.editable
@options.overlay.show()
if @options.background is null
if jQuery("#halloBackground").length > 0
@options.background = jQuery("#halloBackground")
else
@options.background = jQuery "<div id=\"halloBackground\"
class=\"halloBackground\">"
jQuery(document.body).append @options.background
@resizeOverlay()
@options.background.show()
unless @options.originalZIndex
@options.originalZIndex = @options.currentEditable.css "z-index"
@options.currentEditable.css 'z-index', '350'
resizeOverlay: ->
offset = @options.currentEditable.offset()
@options.background.css
top: offset.top - @options.padding
left: offset.left - @options.padding
width: @options.currentEditable.width() + 2 * @options.padding
height: @options.currentEditable.height() + 2 * @options.padding
hideOverlay: ->
@options.visible = false
@options.overlay.hide()
@options.background.hide()
@options.currentEditable.css 'z-index', @options.originalZIndex
# Find the closest parent having a background color. If none, returns white.
_findBackgroundColor: (jQueryfield) ->
color = jQueryfield.css "background-color"
if color isnt 'rgba(0, 0, 0, 0)' and color isnt 'transparent'
return color
if jQueryfield.is "body"
return "white"
else
return @_findBackgroundColor jQueryfield.parent()
)(jQuery)
|
[
{
"context": " an async function as a Promise executor\n# @author Teddy Katz\n###\n'use strict'\n\n#------------------------------",
"end": 96,
"score": 0.999822735786438,
"start": 86,
"tag": "NAME",
"value": "Teddy Katz"
}
] | src/tests/rules/no-async-promise-executor.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview disallow using an async function as a Promise executor
# @author Teddy Katz
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-async-promise-executor'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-async-promise-executor', rule,
valid: [
'new Promise((resolve, reject) => {})'
'new Promise(((resolve, reject) => {}), -> await 1)'
'new Foo((resolve, reject) => await 1)'
]
invalid: [
code: 'new Promise((resolve, reject) -> await 1)'
errors: [
message: 'Promise executor functions should not be async.'
line: 1
column: 13
endLine: 1
endColumn: 41
]
,
code: 'new Promise((resolve, reject) => await 1)'
errors: [
message: 'Promise executor functions should not be async.'
line: 1
column: 13
endLine: 1
endColumn: 41
]
,
code: 'new Promise(((((() => await 1)))))'
errors: [
message: 'Promise executor functions should not be async.'
line: 1
column: 17
endLine: 1
endColumn: 30
]
]
| 11572 | ###*
# @fileoverview disallow using an async function as a Promise executor
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-async-promise-executor'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-async-promise-executor', rule,
valid: [
'new Promise((resolve, reject) => {})'
'new Promise(((resolve, reject) => {}), -> await 1)'
'new Foo((resolve, reject) => await 1)'
]
invalid: [
code: 'new Promise((resolve, reject) -> await 1)'
errors: [
message: 'Promise executor functions should not be async.'
line: 1
column: 13
endLine: 1
endColumn: 41
]
,
code: 'new Promise((resolve, reject) => await 1)'
errors: [
message: 'Promise executor functions should not be async.'
line: 1
column: 13
endLine: 1
endColumn: 41
]
,
code: 'new Promise(((((() => await 1)))))'
errors: [
message: 'Promise executor functions should not be async.'
line: 1
column: 17
endLine: 1
endColumn: 30
]
]
| true | ###*
# @fileoverview disallow using an async function as a Promise executor
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-async-promise-executor'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-async-promise-executor', rule,
valid: [
'new Promise((resolve, reject) => {})'
'new Promise(((resolve, reject) => {}), -> await 1)'
'new Foo((resolve, reject) => await 1)'
]
invalid: [
code: 'new Promise((resolve, reject) -> await 1)'
errors: [
message: 'Promise executor functions should not be async.'
line: 1
column: 13
endLine: 1
endColumn: 41
]
,
code: 'new Promise((resolve, reject) => await 1)'
errors: [
message: 'Promise executor functions should not be async.'
line: 1
column: 13
endLine: 1
endColumn: 41
]
,
code: 'new Promise(((((() => await 1)))))'
errors: [
message: 'Promise executor functions should not be async.'
line: 1
column: 17
endLine: 1
endColumn: 30
]
]
|
[
{
"context": "abelPropertyPath', 'model', () ->\n key = \"model.#{@get('labelPropertyPath')}\"\n Ember.defineProp",
"end": 3403,
"score": 0.8423938751220703,
"start": 3403,
"tag": "KEY",
"value": ""
}
] | addon/components/async-expanding-tree.coffee | tenforce/ember-async-expanding-tree | 0 | `import Ember from 'ember'`
`import layout from '../templates/components/async-expanding-tree'`
`import KeyboardShortcuts from 'ember-keyboard-shortcuts/mixins/component';`
`import TooltipManager from '../mixins/tooltip-manager'`
AsyncExpandingTreeComponent = Ember.Component.extend KeyboardShortcuts, TooltipManager,
keyboardShortcuts: Ember.computed 'disableShortcuts', ->
if @get('disableShortcuts') then return {}
else
{
# open / close current nod #
'shift':
action: 'expand'
global: false
# expand children #
'ctrl+alt+e':
action: 'expandChildren'
global: false
preventDefault: true
'right':
action: 'right'
global: false
'left':
action: 'left'
global: false
'up':
action: 'up'
global: false
'down':
action: 'down'
global: false
}
layout: layout
classNames: ["aet"]
classNameBindings: ["currentSelected:selected", "leafNode:leaf"]
# an array (as per Ember.isArray) of identifier or a single identifier of the selected item(s)
selected: null
# default configuration
config:
# property path to the property that should be used as label
# e.g. model.label.en would be label.en
labelPropertyPath: 'label'
# function that is called with the selected model when the label of the model is clicked
onActivate: (model) ->
# function to retrieve children of the parent object
# this function should return a Promise that returns the children of this item
# this result will be stored in _childrenCache locally in this component
getChildren: (model) ->
model.reload()
# list of concept ids that are expanded
# will auto expand a node in the tree if it's id is cont
# ained in this array
expandedConcepts: []
# max amount (n) of children to be shown before a load more button is presented
# load more button shows an extra n children
showMaxChildren: 50
# component to be rendered before the tree node
# model wil be passed to the component
beforeComponent: null
# component to be rendered after the tree node
# model wil be passed to the component
afterComponent: null
# whether the children of the tree should display the tooltips
showChildrenTooltips: true
# whether default tooltips should be displayed if none are present
showDefaultTooltips: false
# sort order as an array [ 'property1', 'thenproperty2' ]
sortBy: null
fetchChildrenOnInit: false
init: () ->
@_super(arguments)
if @get('fetchChildrenOnInit')
@fetchChildren()
if @get('expandedConcepts')?.contains(@get('model.id')) and not @get('expanded')
@toggleExpandF()
leafNode: Ember.computed '_childrenCache', 'loading', ->
(not @get('loading')) and not @get('_childrenCache.length')
labelPropertyPath: Ember.computed.alias 'config.labelPropertyPath'
getChildren: Ember.computed.alias 'config.getChildren'
expandedConcepts: Ember.computed.alias 'config.expandedConcepts'
showMaxChildren: Ember.computed.alias 'config.showMaxChildren'
beforeComponent: Ember.computed.alias 'config.beforeComponent'
afterComponent: Ember.computed.alias 'config.afterComponent'
# we create a dynamic computed property to check when the value of the label is changed
setLabel: Ember.observer('labelPropertyPath', 'model', () ->
key = "model.#{@get('labelPropertyPath')}"
Ember.defineProperty @, "label",
Ember.computed 'labelPropertyPath', 'model', key, ->
@get("model.#{@get('labelPropertyPath')}")
).on('init')
sortedChildren: []
childrenSorter: Ember.observer '_childrenCache', 'sortchildrenby', 'expanded',( ->
cached = @get '_childrenCache'
# don't bother sorting unless expanded
if not @get 'expanded'
@set 'sortedChildren', cached
return cached
@sortByPromise(cached, @get('sortchildrenby')).then (result) =>
@set 'sortedChildren', result
).on('init')
sortchildrenby: Ember.computed 'labelPropertyPath', 'config.sortBy', ->
sortBy = @get 'config.sortBy'
if sortBy
sortBy
else
[@get('labelPropertyPath')]
childrenFetched: false
childrenSlice: 50
expandable: Ember.computed '_childrenCache', 'loading', ->
(not @get('loading')) and @get('_childrenCache.length')
showLoadMore: Ember.computed '_childrenCache.length', 'childrenSlice', 'loading', ->
(!@get('loading')) && @get('childrenSlice') < @get('_childrenCache.length')
loading: false
tagName: 'li'
fetchChildren: ->
@set('loading', true)
@get('getChildren')(@get('model')).then( (result) =>
@set 'loading', false
@set 'childrenFetched', true
@set '_childrenCache', result
if @get('_childrenCache.length') > 0
@set 'childrenSlice', @get('showMaxChildren')
).catch(=> unless @get('isDestroyed') then @set 'loading', false)
children: Ember.computed 'sortedChildren', 'loading', 'childrenSlice', ->
sorted = @get('sortedChildren')
if not @get('loading') and sorted
sorted.slice(0, @get('childrenSlice'))
else
[]
dirtyObserver: Ember.observer 'model.dirty', ( ->
if @get('model.dirty') is true
@fetchChildren()
@set('model.dirty', false)
).on('init')
toggleExpandF: ->
@toggleProperty('expanded')
if @get('expanded')
@fetchChildren() unless @get('childrenFetched')
@get('expandedConcepts').addObject(@get('model.id'))
else
@get('expandedConcepts').removeObject(@get('model.id'))
configObserver: Ember.observer 'config', 'config.fetchChildren', ->
@get 'config.fetchChildren'
@fetchChildren()
currentSelected: Ember.computed 'model.id', 'selected', ->
selected = @get('selected')
id = @get('model.id')
if Ember.isArray(selected)
if selected?.contains(id)
@scrollToSelected()
return true
else
if selected == id
@scrollToSelected()
return true
return false
scrollToSelected: () ->
if @get 'config.noScroll'
return
Ember.run.later ->
$('html, body').stop().animate(
{'scrollTop': $('.selected').children('.aet-node').children('.aet-label').children('label').offset().top-250},
900,
'swing'
)
shouldExpandChildren: false
inheritedExpanded: false
expanded: Ember.computed 'inheritedExpanded', ->
@get ('inheritedExpanded')
# current level of the tree #
level: 0
nextLevel: Ember.computed 'level', ->
@get('level')+1
actions:
right: ->
if @get('currentSelected')
unless @get('expanded')
@toggleExpandF()
child = this.get('children')[0]
if child then @get('config.onActivate')?(child)
left: ->
if @get('currentSelected')
@sendAction('selectParent')
selectParent: ->
@get('config.onActivate')?(@get('model'))
up: ->
if @get('currentSelected')
@sendAction('selectOlderBrother', @get('index'))
selectOlderBrother: (index) ->
child = this.get('children')[index-1]
if child then @get('config.onActivate')?(child)
else @get('config.onActivate')?(@get('model'))
down: ->
if @get('currentSelected')
@sendAction('selectYoungerBrother', @get('index'))
selectYoungerBrother: (index) ->
child = this.get('children')[index+1]
if child then @get('config.onActivate')?(child)
else @sendAction('selectYoungerBrother', @get('index'))
expandChildren: ->
if @get('currentSelected')
@set('shouldExpandChildren', true)
unless @get('expanded')
@toggleExpandF()
false
expand: ->
if @get('currentSelected')
# Uncomment if we want to open only one level, even if it has been opened before #
###@set('shouldExpandChildren', false)###
@toggleExpandF()
clickItem: ->
@get('config.onActivate')?(@get('model'))
toggleExpand: ->
@toggleExpandF()
loadMoreChildren: ->
if @get('childrenSlice') + @get('showMaxChildren') > @get('_childrenCache.length')
newSlice = @get('_childrenCache.length')
else
newSlice = @get('childrenSlice') + @get('showMaxChildren')
extraSlice = @get('sortedChildren').slice(@get('childrenSlice'), newSlice)
@get('children').pushObjects(extraSlice)
@set('childrenSlice', newSlice)
sortByPromise: (list, path) ->
unless Ember.isArray(path)
path = [path]
if not list
return new Ember.RSVP.Promise (resolve) -> resolve(list)
promises = list.map (item) ->
hash = {}
path.map (key) ->
hash[key] = new Ember.RSVP.Promise (resolve) -> resolve(Ember.get(item, key))
Ember.RSVP.hash hash
Ember.RSVP.all(promises).then (resolutions) ->
toSort = resolutions.map (solutions, index) ->
result = { _sorterItem: list.objectAt(index) }
for key, solution of solutions
result[key] = solution
result
sorted = toSort.sortBy.apply toSort, path
sorted.map (item) ->
item._sorterItem
`export default AsyncExpandingTreeComponent`
| 151332 | `import Ember from 'ember'`
`import layout from '../templates/components/async-expanding-tree'`
`import KeyboardShortcuts from 'ember-keyboard-shortcuts/mixins/component';`
`import TooltipManager from '../mixins/tooltip-manager'`
AsyncExpandingTreeComponent = Ember.Component.extend KeyboardShortcuts, TooltipManager,
keyboardShortcuts: Ember.computed 'disableShortcuts', ->
if @get('disableShortcuts') then return {}
else
{
# open / close current nod #
'shift':
action: 'expand'
global: false
# expand children #
'ctrl+alt+e':
action: 'expandChildren'
global: false
preventDefault: true
'right':
action: 'right'
global: false
'left':
action: 'left'
global: false
'up':
action: 'up'
global: false
'down':
action: 'down'
global: false
}
layout: layout
classNames: ["aet"]
classNameBindings: ["currentSelected:selected", "leafNode:leaf"]
# an array (as per Ember.isArray) of identifier or a single identifier of the selected item(s)
selected: null
# default configuration
config:
# property path to the property that should be used as label
# e.g. model.label.en would be label.en
labelPropertyPath: 'label'
# function that is called with the selected model when the label of the model is clicked
onActivate: (model) ->
# function to retrieve children of the parent object
# this function should return a Promise that returns the children of this item
# this result will be stored in _childrenCache locally in this component
getChildren: (model) ->
model.reload()
# list of concept ids that are expanded
# will auto expand a node in the tree if it's id is cont
# ained in this array
expandedConcepts: []
# max amount (n) of children to be shown before a load more button is presented
# load more button shows an extra n children
showMaxChildren: 50
# component to be rendered before the tree node
# model wil be passed to the component
beforeComponent: null
# component to be rendered after the tree node
# model wil be passed to the component
afterComponent: null
# whether the children of the tree should display the tooltips
showChildrenTooltips: true
# whether default tooltips should be displayed if none are present
showDefaultTooltips: false
# sort order as an array [ 'property1', 'thenproperty2' ]
sortBy: null
fetchChildrenOnInit: false
init: () ->
@_super(arguments)
if @get('fetchChildrenOnInit')
@fetchChildren()
if @get('expandedConcepts')?.contains(@get('model.id')) and not @get('expanded')
@toggleExpandF()
leafNode: Ember.computed '_childrenCache', 'loading', ->
(not @get('loading')) and not @get('_childrenCache.length')
labelPropertyPath: Ember.computed.alias 'config.labelPropertyPath'
getChildren: Ember.computed.alias 'config.getChildren'
expandedConcepts: Ember.computed.alias 'config.expandedConcepts'
showMaxChildren: Ember.computed.alias 'config.showMaxChildren'
beforeComponent: Ember.computed.alias 'config.beforeComponent'
afterComponent: Ember.computed.alias 'config.afterComponent'
# we create a dynamic computed property to check when the value of the label is changed
setLabel: Ember.observer('labelPropertyPath', 'model', () ->
key = "model<KEY>.#{@get('labelPropertyPath')}"
Ember.defineProperty @, "label",
Ember.computed 'labelPropertyPath', 'model', key, ->
@get("model.#{@get('labelPropertyPath')}")
).on('init')
sortedChildren: []
childrenSorter: Ember.observer '_childrenCache', 'sortchildrenby', 'expanded',( ->
cached = @get '_childrenCache'
# don't bother sorting unless expanded
if not @get 'expanded'
@set 'sortedChildren', cached
return cached
@sortByPromise(cached, @get('sortchildrenby')).then (result) =>
@set 'sortedChildren', result
).on('init')
sortchildrenby: Ember.computed 'labelPropertyPath', 'config.sortBy', ->
sortBy = @get 'config.sortBy'
if sortBy
sortBy
else
[@get('labelPropertyPath')]
childrenFetched: false
childrenSlice: 50
expandable: Ember.computed '_childrenCache', 'loading', ->
(not @get('loading')) and @get('_childrenCache.length')
showLoadMore: Ember.computed '_childrenCache.length', 'childrenSlice', 'loading', ->
(!@get('loading')) && @get('childrenSlice') < @get('_childrenCache.length')
loading: false
tagName: 'li'
fetchChildren: ->
@set('loading', true)
@get('getChildren')(@get('model')).then( (result) =>
@set 'loading', false
@set 'childrenFetched', true
@set '_childrenCache', result
if @get('_childrenCache.length') > 0
@set 'childrenSlice', @get('showMaxChildren')
).catch(=> unless @get('isDestroyed') then @set 'loading', false)
children: Ember.computed 'sortedChildren', 'loading', 'childrenSlice', ->
sorted = @get('sortedChildren')
if not @get('loading') and sorted
sorted.slice(0, @get('childrenSlice'))
else
[]
dirtyObserver: Ember.observer 'model.dirty', ( ->
if @get('model.dirty') is true
@fetchChildren()
@set('model.dirty', false)
).on('init')
toggleExpandF: ->
@toggleProperty('expanded')
if @get('expanded')
@fetchChildren() unless @get('childrenFetched')
@get('expandedConcepts').addObject(@get('model.id'))
else
@get('expandedConcepts').removeObject(@get('model.id'))
configObserver: Ember.observer 'config', 'config.fetchChildren', ->
@get 'config.fetchChildren'
@fetchChildren()
currentSelected: Ember.computed 'model.id', 'selected', ->
selected = @get('selected')
id = @get('model.id')
if Ember.isArray(selected)
if selected?.contains(id)
@scrollToSelected()
return true
else
if selected == id
@scrollToSelected()
return true
return false
scrollToSelected: () ->
if @get 'config.noScroll'
return
Ember.run.later ->
$('html, body').stop().animate(
{'scrollTop': $('.selected').children('.aet-node').children('.aet-label').children('label').offset().top-250},
900,
'swing'
)
shouldExpandChildren: false
inheritedExpanded: false
expanded: Ember.computed 'inheritedExpanded', ->
@get ('inheritedExpanded')
# current level of the tree #
level: 0
nextLevel: Ember.computed 'level', ->
@get('level')+1
actions:
right: ->
if @get('currentSelected')
unless @get('expanded')
@toggleExpandF()
child = this.get('children')[0]
if child then @get('config.onActivate')?(child)
left: ->
if @get('currentSelected')
@sendAction('selectParent')
selectParent: ->
@get('config.onActivate')?(@get('model'))
up: ->
if @get('currentSelected')
@sendAction('selectOlderBrother', @get('index'))
selectOlderBrother: (index) ->
child = this.get('children')[index-1]
if child then @get('config.onActivate')?(child)
else @get('config.onActivate')?(@get('model'))
down: ->
if @get('currentSelected')
@sendAction('selectYoungerBrother', @get('index'))
selectYoungerBrother: (index) ->
child = this.get('children')[index+1]
if child then @get('config.onActivate')?(child)
else @sendAction('selectYoungerBrother', @get('index'))
expandChildren: ->
if @get('currentSelected')
@set('shouldExpandChildren', true)
unless @get('expanded')
@toggleExpandF()
false
expand: ->
if @get('currentSelected')
# Uncomment if we want to open only one level, even if it has been opened before #
###@set('shouldExpandChildren', false)###
@toggleExpandF()
clickItem: ->
@get('config.onActivate')?(@get('model'))
toggleExpand: ->
@toggleExpandF()
loadMoreChildren: ->
if @get('childrenSlice') + @get('showMaxChildren') > @get('_childrenCache.length')
newSlice = @get('_childrenCache.length')
else
newSlice = @get('childrenSlice') + @get('showMaxChildren')
extraSlice = @get('sortedChildren').slice(@get('childrenSlice'), newSlice)
@get('children').pushObjects(extraSlice)
@set('childrenSlice', newSlice)
sortByPromise: (list, path) ->
unless Ember.isArray(path)
path = [path]
if not list
return new Ember.RSVP.Promise (resolve) -> resolve(list)
promises = list.map (item) ->
hash = {}
path.map (key) ->
hash[key] = new Ember.RSVP.Promise (resolve) -> resolve(Ember.get(item, key))
Ember.RSVP.hash hash
Ember.RSVP.all(promises).then (resolutions) ->
toSort = resolutions.map (solutions, index) ->
result = { _sorterItem: list.objectAt(index) }
for key, solution of solutions
result[key] = solution
result
sorted = toSort.sortBy.apply toSort, path
sorted.map (item) ->
item._sorterItem
`export default AsyncExpandingTreeComponent`
| true | `import Ember from 'ember'`
`import layout from '../templates/components/async-expanding-tree'`
`import KeyboardShortcuts from 'ember-keyboard-shortcuts/mixins/component';`
`import TooltipManager from '../mixins/tooltip-manager'`
AsyncExpandingTreeComponent = Ember.Component.extend KeyboardShortcuts, TooltipManager,
keyboardShortcuts: Ember.computed 'disableShortcuts', ->
if @get('disableShortcuts') then return {}
else
{
# open / close current nod #
'shift':
action: 'expand'
global: false
# expand children #
'ctrl+alt+e':
action: 'expandChildren'
global: false
preventDefault: true
'right':
action: 'right'
global: false
'left':
action: 'left'
global: false
'up':
action: 'up'
global: false
'down':
action: 'down'
global: false
}
layout: layout
classNames: ["aet"]
classNameBindings: ["currentSelected:selected", "leafNode:leaf"]
# an array (as per Ember.isArray) of identifier or a single identifier of the selected item(s)
selected: null
# default configuration
config:
# property path to the property that should be used as label
# e.g. model.label.en would be label.en
labelPropertyPath: 'label'
# function that is called with the selected model when the label of the model is clicked
onActivate: (model) ->
# function to retrieve children of the parent object
# this function should return a Promise that returns the children of this item
# this result will be stored in _childrenCache locally in this component
getChildren: (model) ->
model.reload()
# list of concept ids that are expanded
# will auto expand a node in the tree if it's id is cont
# ained in this array
expandedConcepts: []
# max amount (n) of children to be shown before a load more button is presented
# load more button shows an extra n children
showMaxChildren: 50
# component to be rendered before the tree node
# model wil be passed to the component
beforeComponent: null
# component to be rendered after the tree node
# model wil be passed to the component
afterComponent: null
# whether the children of the tree should display the tooltips
showChildrenTooltips: true
# whether default tooltips should be displayed if none are present
showDefaultTooltips: false
# sort order as an array [ 'property1', 'thenproperty2' ]
sortBy: null
fetchChildrenOnInit: false
init: () ->
@_super(arguments)
if @get('fetchChildrenOnInit')
@fetchChildren()
if @get('expandedConcepts')?.contains(@get('model.id')) and not @get('expanded')
@toggleExpandF()
leafNode: Ember.computed '_childrenCache', 'loading', ->
(not @get('loading')) and not @get('_childrenCache.length')
labelPropertyPath: Ember.computed.alias 'config.labelPropertyPath'
getChildren: Ember.computed.alias 'config.getChildren'
expandedConcepts: Ember.computed.alias 'config.expandedConcepts'
showMaxChildren: Ember.computed.alias 'config.showMaxChildren'
beforeComponent: Ember.computed.alias 'config.beforeComponent'
afterComponent: Ember.computed.alias 'config.afterComponent'
# we create a dynamic computed property to check when the value of the label is changed
setLabel: Ember.observer('labelPropertyPath', 'model', () ->
key = "modelPI:KEY:<KEY>END_PI.#{@get('labelPropertyPath')}"
Ember.defineProperty @, "label",
Ember.computed 'labelPropertyPath', 'model', key, ->
@get("model.#{@get('labelPropertyPath')}")
).on('init')
sortedChildren: []
childrenSorter: Ember.observer '_childrenCache', 'sortchildrenby', 'expanded',( ->
cached = @get '_childrenCache'
# don't bother sorting unless expanded
if not @get 'expanded'
@set 'sortedChildren', cached
return cached
@sortByPromise(cached, @get('sortchildrenby')).then (result) =>
@set 'sortedChildren', result
).on('init')
sortchildrenby: Ember.computed 'labelPropertyPath', 'config.sortBy', ->
sortBy = @get 'config.sortBy'
if sortBy
sortBy
else
[@get('labelPropertyPath')]
childrenFetched: false
childrenSlice: 50
expandable: Ember.computed '_childrenCache', 'loading', ->
(not @get('loading')) and @get('_childrenCache.length')
showLoadMore: Ember.computed '_childrenCache.length', 'childrenSlice', 'loading', ->
(!@get('loading')) && @get('childrenSlice') < @get('_childrenCache.length')
loading: false
tagName: 'li'
fetchChildren: ->
@set('loading', true)
@get('getChildren')(@get('model')).then( (result) =>
@set 'loading', false
@set 'childrenFetched', true
@set '_childrenCache', result
if @get('_childrenCache.length') > 0
@set 'childrenSlice', @get('showMaxChildren')
).catch(=> unless @get('isDestroyed') then @set 'loading', false)
children: Ember.computed 'sortedChildren', 'loading', 'childrenSlice', ->
sorted = @get('sortedChildren')
if not @get('loading') and sorted
sorted.slice(0, @get('childrenSlice'))
else
[]
dirtyObserver: Ember.observer 'model.dirty', ( ->
if @get('model.dirty') is true
@fetchChildren()
@set('model.dirty', false)
).on('init')
toggleExpandF: ->
@toggleProperty('expanded')
if @get('expanded')
@fetchChildren() unless @get('childrenFetched')
@get('expandedConcepts').addObject(@get('model.id'))
else
@get('expandedConcepts').removeObject(@get('model.id'))
configObserver: Ember.observer 'config', 'config.fetchChildren', ->
@get 'config.fetchChildren'
@fetchChildren()
currentSelected: Ember.computed 'model.id', 'selected', ->
selected = @get('selected')
id = @get('model.id')
if Ember.isArray(selected)
if selected?.contains(id)
@scrollToSelected()
return true
else
if selected == id
@scrollToSelected()
return true
return false
scrollToSelected: () ->
if @get 'config.noScroll'
return
Ember.run.later ->
$('html, body').stop().animate(
{'scrollTop': $('.selected').children('.aet-node').children('.aet-label').children('label').offset().top-250},
900,
'swing'
)
shouldExpandChildren: false
inheritedExpanded: false
expanded: Ember.computed 'inheritedExpanded', ->
@get ('inheritedExpanded')
# current level of the tree #
level: 0
nextLevel: Ember.computed 'level', ->
@get('level')+1
actions:
right: ->
if @get('currentSelected')
unless @get('expanded')
@toggleExpandF()
child = this.get('children')[0]
if child then @get('config.onActivate')?(child)
left: ->
if @get('currentSelected')
@sendAction('selectParent')
selectParent: ->
@get('config.onActivate')?(@get('model'))
up: ->
if @get('currentSelected')
@sendAction('selectOlderBrother', @get('index'))
selectOlderBrother: (index) ->
child = this.get('children')[index-1]
if child then @get('config.onActivate')?(child)
else @get('config.onActivate')?(@get('model'))
down: ->
if @get('currentSelected')
@sendAction('selectYoungerBrother', @get('index'))
selectYoungerBrother: (index) ->
child = this.get('children')[index+1]
if child then @get('config.onActivate')?(child)
else @sendAction('selectYoungerBrother', @get('index'))
expandChildren: ->
if @get('currentSelected')
@set('shouldExpandChildren', true)
unless @get('expanded')
@toggleExpandF()
false
expand: ->
if @get('currentSelected')
# Uncomment if we want to open only one level, even if it has been opened before #
###@set('shouldExpandChildren', false)###
@toggleExpandF()
clickItem: ->
@get('config.onActivate')?(@get('model'))
toggleExpand: ->
@toggleExpandF()
loadMoreChildren: ->
if @get('childrenSlice') + @get('showMaxChildren') > @get('_childrenCache.length')
newSlice = @get('_childrenCache.length')
else
newSlice = @get('childrenSlice') + @get('showMaxChildren')
extraSlice = @get('sortedChildren').slice(@get('childrenSlice'), newSlice)
@get('children').pushObjects(extraSlice)
@set('childrenSlice', newSlice)
sortByPromise: (list, path) ->
unless Ember.isArray(path)
path = [path]
if not list
return new Ember.RSVP.Promise (resolve) -> resolve(list)
promises = list.map (item) ->
hash = {}
path.map (key) ->
hash[key] = new Ember.RSVP.Promise (resolve) -> resolve(Ember.get(item, key))
Ember.RSVP.hash hash
Ember.RSVP.all(promises).then (resolutions) ->
toSort = resolutions.map (solutions, index) ->
result = { _sorterItem: list.objectAt(index) }
for key, solution of solutions
result[key] = solution
result
sorted = toSort.sortBy.apply toSort, path
sorted.map (item) ->
item._sorterItem
`export default AsyncExpandingTreeComponent`
|
[
{
"context": "m =\n _id: 'foo'\n id: 'foo'\n name: 'foo'\n\n component = TestUtils.renderIntoDocument Re",
"end": 191,
"score": 0.9873676896095276,
"start": 188,
"tag": "NAME",
"value": "foo"
}
] | application/test/components/main-test.coffee | CHU-BURA/clone-app-kobito-oss | 215 | require '../spec-helper'
describe "components/main", ->
Main = require '../../lib/components/main'
it "should be rendered", ->
team =
_id: 'foo'
id: 'foo'
name: 'foo'
component = TestUtils.renderIntoDocument React.createFactory(Main) {
selectedItem: null
selectedTeam: team
teams: [team]
items: []
templates: []
logined: false
}
assert component.innerHTML isnt ''
| 64258 | require '../spec-helper'
describe "components/main", ->
Main = require '../../lib/components/main'
it "should be rendered", ->
team =
_id: 'foo'
id: 'foo'
name: '<NAME>'
component = TestUtils.renderIntoDocument React.createFactory(Main) {
selectedItem: null
selectedTeam: team
teams: [team]
items: []
templates: []
logined: false
}
assert component.innerHTML isnt ''
| true | require '../spec-helper'
describe "components/main", ->
Main = require '../../lib/components/main'
it "should be rendered", ->
team =
_id: 'foo'
id: 'foo'
name: 'PI:NAME:<NAME>END_PI'
component = TestUtils.renderIntoDocument React.createFactory(Main) {
selectedItem: null
selectedTeam: team
teams: [team]
items: []
templates: []
logined: false
}
assert component.innerHTML isnt ''
|
[
{
"context": "r disallow usage of \"English\" operators.\n# @author Julian Rosse\n###\n'use strict'\n\n#------------------------------",
"end": 110,
"score": 0.9998530745506287,
"start": 98,
"tag": "NAME",
"value": "Julian Rosse"
}
] | src/tests/rules/english-operators.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview This rule should require or disallow usage of "English" operators.
# @author Julian Rosse
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/english-operators'
{RuleTester} = require 'eslint'
path = require 'path'
error = (op, {args} = {}) ->
{
type:
switch op
when '!', 'not'
'UnaryExpression'
when '&&', '||', 'and', 'or'
'LogicalExpression'
else
'BinaryExpression'
...args
}
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'english-operators', rule,
valid: [
'a and b'
'a or b'
'a is b'
'a isnt b'
'not a'
'!!a'
'"&&"'
'# &&'
'a + b'
,
code: 'a && b'
options: ['never']
,
code: 'a || b'
options: ['never']
,
code: 'a == b'
options: ['never']
,
code: 'a != b'
options: ['never']
,
code: '!a'
options: ['never']
,
code: '!!a'
options: ['never']
]
invalid: [
code: 'a && b'
errors: [error '&&', message: "Prefer the usage of 'and' over '&&'"]
,
code: 'a && b || c'
errors: [error('&&'), error '||']
,
code: 'a == b'
errors: [error '==']
,
code: 'a != b'
errors: [error '!=']
,
code: '!a'
errors: [error '!']
,
code: 'a and b'
options: ['never']
errors: [error 'and']
,
code: 'a or b'
options: ['never']
errors: [error 'or']
,
code: 'a is b'
options: ['never']
errors: [error 'is']
,
code: 'a isnt b'
options: ['never']
errors: [error 'isnt']
,
code: 'not a'
options: ['never']
errors: [error 'not']
]
| 191459 | ###*
# @fileoverview This rule should require or disallow usage of "English" operators.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/english-operators'
{RuleTester} = require 'eslint'
path = require 'path'
error = (op, {args} = {}) ->
{
type:
switch op
when '!', 'not'
'UnaryExpression'
when '&&', '||', 'and', 'or'
'LogicalExpression'
else
'BinaryExpression'
...args
}
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'english-operators', rule,
valid: [
'a and b'
'a or b'
'a is b'
'a isnt b'
'not a'
'!!a'
'"&&"'
'# &&'
'a + b'
,
code: 'a && b'
options: ['never']
,
code: 'a || b'
options: ['never']
,
code: 'a == b'
options: ['never']
,
code: 'a != b'
options: ['never']
,
code: '!a'
options: ['never']
,
code: '!!a'
options: ['never']
]
invalid: [
code: 'a && b'
errors: [error '&&', message: "Prefer the usage of 'and' over '&&'"]
,
code: 'a && b || c'
errors: [error('&&'), error '||']
,
code: 'a == b'
errors: [error '==']
,
code: 'a != b'
errors: [error '!=']
,
code: '!a'
errors: [error '!']
,
code: 'a and b'
options: ['never']
errors: [error 'and']
,
code: 'a or b'
options: ['never']
errors: [error 'or']
,
code: 'a is b'
options: ['never']
errors: [error 'is']
,
code: 'a isnt b'
options: ['never']
errors: [error 'isnt']
,
code: 'not a'
options: ['never']
errors: [error 'not']
]
| true | ###*
# @fileoverview This rule should require or disallow usage of "English" operators.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/english-operators'
{RuleTester} = require 'eslint'
path = require 'path'
error = (op, {args} = {}) ->
{
type:
switch op
when '!', 'not'
'UnaryExpression'
when '&&', '||', 'and', 'or'
'LogicalExpression'
else
'BinaryExpression'
...args
}
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'english-operators', rule,
valid: [
'a and b'
'a or b'
'a is b'
'a isnt b'
'not a'
'!!a'
'"&&"'
'# &&'
'a + b'
,
code: 'a && b'
options: ['never']
,
code: 'a || b'
options: ['never']
,
code: 'a == b'
options: ['never']
,
code: 'a != b'
options: ['never']
,
code: '!a'
options: ['never']
,
code: '!!a'
options: ['never']
]
invalid: [
code: 'a && b'
errors: [error '&&', message: "Prefer the usage of 'and' over '&&'"]
,
code: 'a && b || c'
errors: [error('&&'), error '||']
,
code: 'a == b'
errors: [error '==']
,
code: 'a != b'
errors: [error '!=']
,
code: '!a'
errors: [error '!']
,
code: 'a and b'
options: ['never']
errors: [error 'and']
,
code: 'a or b'
options: ['never']
errors: [error 'or']
,
code: 'a is b'
options: ['never']
errors: [error 'is']
,
code: 'a isnt b'
options: ['never']
errors: [error 'isnt']
,
code: 'not a'
options: ['never']
errors: [error 'not']
]
|
[
{
"context": "ement\n\t@id: \"halloweenLoginAchievement\"\n\t@title: \"HAPPY HALLOWEEN\"\n\t@description: \"HERE'S 3 MYTHRON TREATS TO CELEB",
"end": 287,
"score": 0.9998226761817932,
"start": 272,
"tag": "NAME",
"value": "HAPPY HALLOWEEN"
}
] | app/sdk/achievements/loginBasedAchievements/halloweenLoginAchievement.coffee | willroberts/duelyst | 5 | Achievement = require 'app/sdk/achievements/achievement'
moment = require 'moment'
GiftCrateLookup = require 'app/sdk/giftCrates/giftCrateLookup'
i18next = require('i18next')
class HalloweenLoginAchievement extends Achievement
@id: "halloweenLoginAchievement"
@title: "HAPPY HALLOWEEN"
@description: "HERE'S 3 MYTHRON TREATS TO CELEBRATE"
@progressRequired: 1
@rewards:
giftChests: [GiftCrateLookup.HalloweenLogin]
@enabled: true
@progressForLoggingIn: (currentLoginMoment) ->
if currentLoginMoment != null && currentLoginMoment.isAfter(moment.utc("2018-10-26T11:00-07:00")) and currentLoginMoment.isBefore(moment.utc("2018-11-02T11:00-07:00"))
return 1
else
return 0
@getLoginAchievementStartsMoment: () ->
return moment.utc("2018-10-26T11:00-07:00")
module.exports = HalloweenLoginAchievement
| 3379 | Achievement = require 'app/sdk/achievements/achievement'
moment = require 'moment'
GiftCrateLookup = require 'app/sdk/giftCrates/giftCrateLookup'
i18next = require('i18next')
class HalloweenLoginAchievement extends Achievement
@id: "halloweenLoginAchievement"
@title: "<NAME>"
@description: "HERE'S 3 MYTHRON TREATS TO CELEBRATE"
@progressRequired: 1
@rewards:
giftChests: [GiftCrateLookup.HalloweenLogin]
@enabled: true
@progressForLoggingIn: (currentLoginMoment) ->
if currentLoginMoment != null && currentLoginMoment.isAfter(moment.utc("2018-10-26T11:00-07:00")) and currentLoginMoment.isBefore(moment.utc("2018-11-02T11:00-07:00"))
return 1
else
return 0
@getLoginAchievementStartsMoment: () ->
return moment.utc("2018-10-26T11:00-07:00")
module.exports = HalloweenLoginAchievement
| true | Achievement = require 'app/sdk/achievements/achievement'
moment = require 'moment'
GiftCrateLookup = require 'app/sdk/giftCrates/giftCrateLookup'
i18next = require('i18next')
class HalloweenLoginAchievement extends Achievement
@id: "halloweenLoginAchievement"
@title: "PI:NAME:<NAME>END_PI"
@description: "HERE'S 3 MYTHRON TREATS TO CELEBRATE"
@progressRequired: 1
@rewards:
giftChests: [GiftCrateLookup.HalloweenLogin]
@enabled: true
@progressForLoggingIn: (currentLoginMoment) ->
if currentLoginMoment != null && currentLoginMoment.isAfter(moment.utc("2018-10-26T11:00-07:00")) and currentLoginMoment.isBefore(moment.utc("2018-11-02T11:00-07:00"))
return 1
else
return 0
@getLoginAchievementStartsMoment: () ->
return moment.utc("2018-10-26T11:00-07:00")
module.exports = HalloweenLoginAchievement
|
[
{
"context": "issing parentheses around multilines JSX\n# @author Yannick Croissant\n###\n'use strict'\n\nhas = require 'has'\ndocsUrl = r",
"end": 98,
"score": 0.9998425245285034,
"start": 81,
"tag": "NAME",
"value": "Yannick Croissant"
}
] | src/rules/jsx-wrap-multilines.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Prevent missing parentheses around multilines JSX
# @author Yannick Croissant
###
'use strict'
has = require 'has'
docsUrl = require 'eslint-plugin-react/lib/util/docsUrl'
jsxUtil = require '../util/react/jsx'
# ------------------------------------------------------------------------------
# Constants
# ------------------------------------------------------------------------------
DEFAULTS =
assignment: 'parens'
return: 'parens'
arrow: 'parens'
logical: 'ignore'
prop: 'ignore'
MISSING_PARENS = 'Missing parentheses around multilines JSX'
PARENS_NEW_LINES = 'Parentheses around JSX should be on separate lines'
# ------------------------------------------------------------------------------
# Rule Definition
# ------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'Prevent missing parentheses around multilines JSX'
category: 'Stylistic Issues'
recommended: no
url: docsUrl 'jsx-wrap-multilines'
# fixable: 'code'
schema: [
type: 'object'
# true/false are for backwards compatibility
properties:
assignment:
enum: [yes, no, 'ignore', 'parens', 'parens-new-line']
return:
enum: [yes, no, 'ignore', 'parens', 'parens-new-line']
arrow:
enum: [yes, no, 'ignore', 'parens', 'parens-new-line']
logical:
enum: [yes, no, 'ignore', 'parens', 'parens-new-line']
prop:
enum: [yes, no, 'ignore', 'parens', 'parens-new-line']
additionalProperties: no
]
create: (context) ->
sourceCode = context.getSourceCode()
getOption = (type) ->
userOptions = context.options[0] or {}
return userOptions[type] if has userOptions, type
DEFAULTS[type]
isEnabled = (type) ->
option = getOption type
option and option isnt 'ignore'
isParenthesised = (node) ->
previousToken = sourceCode.getTokenBefore node
nextToken = sourceCode.getTokenAfter node
previousToken and
nextToken and
previousToken.value is '(' and
previousToken.range[1] <= node.range[0] and
nextToken.value is ')' and
nextToken.range[0] >= node.range[1]
needsNewLines = (node) ->
previousToken = sourceCode.getTokenBefore node
nextToken = sourceCode.getTokenAfter node
isParenthesised(node) and
previousToken.loc.end.line is node.loc.start.line and
node.loc.end.line is nextToken.loc.end.line
isMultilines = (node) -> node.loc.start.line isnt node.loc.end.line
report = (
node
message
#fix
) ->
context.report {
node
message
# fix
}
trimTokenBeforeNewline = (node, tokenBefore) ->
# if the token before the jsx is a bracket or curly brace
# we don't want a space between the opening parentheses and the multiline jsx
isBracket = tokenBefore.value in ['{', '[']
"#{tokenBefore.value.trim()}#{if isBracket then '' else ' '}"
check = (node, type) ->
return if not node or not jsxUtil.isJSX node
option = getOption type
if (
option in [yes, 'parens'] and
not isParenthesised(node) and
isMultilines node
)
report node, MISSING_PARENS, (fixer) ->
fixer.replaceText node, "(#{sourceCode.getText node})"
if option is 'parens-new-line' and isMultilines node
unless isParenthesised node
tokenBefore = sourceCode.getTokenBefore node, includeComments: yes
tokenAfter = sourceCode.getTokenAfter node, includeComments: yes
if tokenBefore.loc.end.line < node.loc.start.line
# Strip newline after operator if parens newline is specified
report node, MISSING_PARENS, (fixer) ->
fixer.replaceTextRange(
[tokenBefore.range[0], tokenAfter.range[0]]
"#{trimTokenBeforeNewline(
node
tokenBefore
)}(\n#{sourceCode.getText node}\n)"
)
else
report node, MISSING_PARENS, (fixer) ->
fixer.replaceText node, "(\n#{sourceCode.getText node}\n)"
else if needsNewLines node
report node, PARENS_NEW_LINES, (fixer) ->
fixer.replaceText node, "\n#{sourceCode.getText node}\n"
checkFunction = (node) ->
arrowBody = node.body
type = 'arrow'
if isEnabled type
unless arrowBody.type is 'BlockStatement'
check arrowBody, type
else if (
arrowBody.body.length is 1 and
arrowBody.body[0].type is 'ExpressionStatement'
)
check arrowBody.body[0].expression, type
# --------------------------------------------------------------------------
# Public
# --------------------------------------------------------------------------
AssignmentExpression: (node) ->
type = 'assignment'
return unless isEnabled type
check node.right, type
ReturnStatement: (node) ->
type = 'return'
if isEnabled type then check node.argument, type
'ArrowFunctionExpression:exit': checkFunction
'FunctionExpression:exit': checkFunction
LogicalExpression: (node) ->
type = 'logical'
if isEnabled type then check node.right, type
JSXAttribute: (node) ->
type = 'prop'
if isEnabled(type) and node.value?.type is 'JSXExpressionContainer'
check node.value.expression, type
| 12177 | ###*
# @fileoverview Prevent missing parentheses around multilines JSX
# @author <NAME>
###
'use strict'
has = require 'has'
docsUrl = require 'eslint-plugin-react/lib/util/docsUrl'
jsxUtil = require '../util/react/jsx'
# ------------------------------------------------------------------------------
# Constants
# ------------------------------------------------------------------------------
DEFAULTS =
assignment: 'parens'
return: 'parens'
arrow: 'parens'
logical: 'ignore'
prop: 'ignore'
MISSING_PARENS = 'Missing parentheses around multilines JSX'
PARENS_NEW_LINES = 'Parentheses around JSX should be on separate lines'
# ------------------------------------------------------------------------------
# Rule Definition
# ------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'Prevent missing parentheses around multilines JSX'
category: 'Stylistic Issues'
recommended: no
url: docsUrl 'jsx-wrap-multilines'
# fixable: 'code'
schema: [
type: 'object'
# true/false are for backwards compatibility
properties:
assignment:
enum: [yes, no, 'ignore', 'parens', 'parens-new-line']
return:
enum: [yes, no, 'ignore', 'parens', 'parens-new-line']
arrow:
enum: [yes, no, 'ignore', 'parens', 'parens-new-line']
logical:
enum: [yes, no, 'ignore', 'parens', 'parens-new-line']
prop:
enum: [yes, no, 'ignore', 'parens', 'parens-new-line']
additionalProperties: no
]
create: (context) ->
sourceCode = context.getSourceCode()
getOption = (type) ->
userOptions = context.options[0] or {}
return userOptions[type] if has userOptions, type
DEFAULTS[type]
isEnabled = (type) ->
option = getOption type
option and option isnt 'ignore'
isParenthesised = (node) ->
previousToken = sourceCode.getTokenBefore node
nextToken = sourceCode.getTokenAfter node
previousToken and
nextToken and
previousToken.value is '(' and
previousToken.range[1] <= node.range[0] and
nextToken.value is ')' and
nextToken.range[0] >= node.range[1]
needsNewLines = (node) ->
previousToken = sourceCode.getTokenBefore node
nextToken = sourceCode.getTokenAfter node
isParenthesised(node) and
previousToken.loc.end.line is node.loc.start.line and
node.loc.end.line is nextToken.loc.end.line
isMultilines = (node) -> node.loc.start.line isnt node.loc.end.line
report = (
node
message
#fix
) ->
context.report {
node
message
# fix
}
trimTokenBeforeNewline = (node, tokenBefore) ->
# if the token before the jsx is a bracket or curly brace
# we don't want a space between the opening parentheses and the multiline jsx
isBracket = tokenBefore.value in ['{', '[']
"#{tokenBefore.value.trim()}#{if isBracket then '' else ' '}"
check = (node, type) ->
return if not node or not jsxUtil.isJSX node
option = getOption type
if (
option in [yes, 'parens'] and
not isParenthesised(node) and
isMultilines node
)
report node, MISSING_PARENS, (fixer) ->
fixer.replaceText node, "(#{sourceCode.getText node})"
if option is 'parens-new-line' and isMultilines node
unless isParenthesised node
tokenBefore = sourceCode.getTokenBefore node, includeComments: yes
tokenAfter = sourceCode.getTokenAfter node, includeComments: yes
if tokenBefore.loc.end.line < node.loc.start.line
# Strip newline after operator if parens newline is specified
report node, MISSING_PARENS, (fixer) ->
fixer.replaceTextRange(
[tokenBefore.range[0], tokenAfter.range[0]]
"#{trimTokenBeforeNewline(
node
tokenBefore
)}(\n#{sourceCode.getText node}\n)"
)
else
report node, MISSING_PARENS, (fixer) ->
fixer.replaceText node, "(\n#{sourceCode.getText node}\n)"
else if needsNewLines node
report node, PARENS_NEW_LINES, (fixer) ->
fixer.replaceText node, "\n#{sourceCode.getText node}\n"
checkFunction = (node) ->
arrowBody = node.body
type = 'arrow'
if isEnabled type
unless arrowBody.type is 'BlockStatement'
check arrowBody, type
else if (
arrowBody.body.length is 1 and
arrowBody.body[0].type is 'ExpressionStatement'
)
check arrowBody.body[0].expression, type
# --------------------------------------------------------------------------
# Public
# --------------------------------------------------------------------------
AssignmentExpression: (node) ->
type = 'assignment'
return unless isEnabled type
check node.right, type
ReturnStatement: (node) ->
type = 'return'
if isEnabled type then check node.argument, type
'ArrowFunctionExpression:exit': checkFunction
'FunctionExpression:exit': checkFunction
LogicalExpression: (node) ->
type = 'logical'
if isEnabled type then check node.right, type
JSXAttribute: (node) ->
type = 'prop'
if isEnabled(type) and node.value?.type is 'JSXExpressionContainer'
check node.value.expression, type
| true | ###*
# @fileoverview Prevent missing parentheses around multilines JSX
# @author PI:NAME:<NAME>END_PI
###
'use strict'
has = require 'has'
docsUrl = require 'eslint-plugin-react/lib/util/docsUrl'
jsxUtil = require '../util/react/jsx'
# ------------------------------------------------------------------------------
# Constants
# ------------------------------------------------------------------------------
DEFAULTS =
assignment: 'parens'
return: 'parens'
arrow: 'parens'
logical: 'ignore'
prop: 'ignore'
MISSING_PARENS = 'Missing parentheses around multilines JSX'
PARENS_NEW_LINES = 'Parentheses around JSX should be on separate lines'
# ------------------------------------------------------------------------------
# Rule Definition
# ------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'Prevent missing parentheses around multilines JSX'
category: 'Stylistic Issues'
recommended: no
url: docsUrl 'jsx-wrap-multilines'
# fixable: 'code'
schema: [
type: 'object'
# true/false are for backwards compatibility
properties:
assignment:
enum: [yes, no, 'ignore', 'parens', 'parens-new-line']
return:
enum: [yes, no, 'ignore', 'parens', 'parens-new-line']
arrow:
enum: [yes, no, 'ignore', 'parens', 'parens-new-line']
logical:
enum: [yes, no, 'ignore', 'parens', 'parens-new-line']
prop:
enum: [yes, no, 'ignore', 'parens', 'parens-new-line']
additionalProperties: no
]
create: (context) ->
sourceCode = context.getSourceCode()
getOption = (type) ->
userOptions = context.options[0] or {}
return userOptions[type] if has userOptions, type
DEFAULTS[type]
isEnabled = (type) ->
option = getOption type
option and option isnt 'ignore'
isParenthesised = (node) ->
previousToken = sourceCode.getTokenBefore node
nextToken = sourceCode.getTokenAfter node
previousToken and
nextToken and
previousToken.value is '(' and
previousToken.range[1] <= node.range[0] and
nextToken.value is ')' and
nextToken.range[0] >= node.range[1]
needsNewLines = (node) ->
previousToken = sourceCode.getTokenBefore node
nextToken = sourceCode.getTokenAfter node
isParenthesised(node) and
previousToken.loc.end.line is node.loc.start.line and
node.loc.end.line is nextToken.loc.end.line
isMultilines = (node) -> node.loc.start.line isnt node.loc.end.line
report = (
node
message
#fix
) ->
context.report {
node
message
# fix
}
trimTokenBeforeNewline = (node, tokenBefore) ->
# if the token before the jsx is a bracket or curly brace
# we don't want a space between the opening parentheses and the multiline jsx
isBracket = tokenBefore.value in ['{', '[']
"#{tokenBefore.value.trim()}#{if isBracket then '' else ' '}"
check = (node, type) ->
return if not node or not jsxUtil.isJSX node
option = getOption type
if (
option in [yes, 'parens'] and
not isParenthesised(node) and
isMultilines node
)
report node, MISSING_PARENS, (fixer) ->
fixer.replaceText node, "(#{sourceCode.getText node})"
if option is 'parens-new-line' and isMultilines node
unless isParenthesised node
tokenBefore = sourceCode.getTokenBefore node, includeComments: yes
tokenAfter = sourceCode.getTokenAfter node, includeComments: yes
if tokenBefore.loc.end.line < node.loc.start.line
# Strip newline after operator if parens newline is specified
report node, MISSING_PARENS, (fixer) ->
fixer.replaceTextRange(
[tokenBefore.range[0], tokenAfter.range[0]]
"#{trimTokenBeforeNewline(
node
tokenBefore
)}(\n#{sourceCode.getText node}\n)"
)
else
report node, MISSING_PARENS, (fixer) ->
fixer.replaceText node, "(\n#{sourceCode.getText node}\n)"
else if needsNewLines node
report node, PARENS_NEW_LINES, (fixer) ->
fixer.replaceText node, "\n#{sourceCode.getText node}\n"
checkFunction = (node) ->
arrowBody = node.body
type = 'arrow'
if isEnabled type
unless arrowBody.type is 'BlockStatement'
check arrowBody, type
else if (
arrowBody.body.length is 1 and
arrowBody.body[0].type is 'ExpressionStatement'
)
check arrowBody.body[0].expression, type
# --------------------------------------------------------------------------
# Public
# --------------------------------------------------------------------------
AssignmentExpression: (node) ->
type = 'assignment'
return unless isEnabled type
check node.right, type
ReturnStatement: (node) ->
type = 'return'
if isEnabled type then check node.argument, type
'ArrowFunctionExpression:exit': checkFunction
'FunctionExpression:exit': checkFunction
LogicalExpression: (node) ->
type = 'logical'
if isEnabled type then check node.right, type
JSXAttribute: (node) ->
type = 'prop'
if isEnabled(type) and node.value?.type is 'JSXExpressionContainer'
check node.value.expression, type
|
[
{
"context": "\n\n\tbeforeEach ->\n\t\t@user = {_id:\"!@312431\",email:\"user@email.com\"}\n\t\t@adminUserId = \"123jlkj\"\n\t\t@subscription_id =",
"end": 376,
"score": 0.9999181628227234,
"start": 362,
"tag": "EMAIL",
"value": "user@email.com"
},
{
"context": "312431\",email:\"user... | test/unit/coffee/Subscription/SubscriptionGroupControllerTests.coffee | davidmehren/web-sharelatex | 0 | SandboxedModule = require('sandboxed-module')
should = require('chai').should()
sinon = require 'sinon'
assert = require("chai").assert
modulePath = "../../../../app/js/Features/Subscription/SubscriptionGroupController"
MockResponse = require "../helpers/MockResponse"
describe "SubscriptionGroupController", ->
beforeEach ->
@user = {_id:"!@312431",email:"user@email.com"}
@adminUserId = "123jlkj"
@subscription_id = "123434325412"
@user_email = "bob@gmail.com"
@req =
session:
user:
_id: @adminUserId
email:@user_email
params:
subscription_id:@subscription_id
query:{}
@subscription = {}
@GroupHandler =
addUserToGroup: sinon.stub().callsArgWith(2, null, @user)
removeUserFromGroup: sinon.stub().callsArgWith(2)
isUserPartOfGroup: sinon.stub()
getPopulatedListOfMembers: sinon.stub().callsArgWith(1, null, [@user])
@SubscriptionLocator = getUsersSubscription: sinon.stub().callsArgWith(1, null, @subscription)
@AuthenticationController =
getLoggedInUserId: (req) -> req.session.user._id
getSessionUser: (req) -> req.session.user
@SubscriptionDomainHandler =
findDomainLicenceBySubscriptionId:sinon.stub()
@OneTimeTokenHandler =
getValueFromTokenAndExpire:sinon.stub()
@ErrorsController =
notFound:sinon.stub()
@Controller = SandboxedModule.require modulePath, requires:
"./SubscriptionGroupHandler":@GroupHandler
"logger-sharelatex": log:->
"./SubscriptionLocator": @SubscriptionLocator
"./SubscriptionDomainHandler":@SubscriptionDomainHandler
"../Errors/ErrorController":@ErrorsController
'../Authentication/AuthenticationController': @AuthenticationController
@token = "super-secret-token"
describe "addUserToGroup", ->
it "should use the admin id for the logged in user and take the email address from the body", (done)->
newEmail = " boB@gmaiL.com "
@req.body = email: newEmail
res =
json : (data)=>
@GroupHandler.addUserToGroup.calledWith(@adminUserId, "bob@gmail.com").should.equal true
data.user.should.deep.equal @user
done()
@Controller.addUserToGroup @req, res
describe "removeUserFromGroup", ->
it "should use the admin id for the logged in user and take the user id from the params", (done)->
userIdToRemove = "31231"
@req.params = user_id: userIdToRemove
res =
send : =>
@GroupHandler.removeUserFromGroup.calledWith(@adminUserId, userIdToRemove).should.equal true
done()
@Controller.removeUserFromGroup @req, res
describe "renderSubscriptionGroupAdminPage", ->
it "should redirect you if you don't have a group account", (done)->
@subscription.groupPlan = false
res =
redirect : (path)=>
path.should.equal("/user/subscription")
done()
@Controller.renderSubscriptionGroupAdminPage @req, res
it "should redirect you don't have a subscription", (done)->
@SubscriptionLocator.getUsersSubscription = sinon.stub().callsArgWith(1)
res =
redirect : (path)=>
path.should.equal("/user/subscription")
done()
@Controller.renderSubscriptionGroupAdminPage @req, res
describe "exportGroupCsv", ->
beforeEach ->
@subscription.groupPlan = true
@res = new MockResponse()
@res.contentType = sinon.stub()
@res.header = sinon.stub()
@res.send = sinon.stub()
@Controller.exportGroupCsv @req, @res
it "should set the correct content type on the request", ->
@res.contentType
.calledWith("text/csv")
.should.equal true
it "should name the exported csv file", ->
@res.header
.calledWith(
"Content-Disposition",
"attachment; filename=Group.csv")
.should.equal true
it "should export the correct csv", ->
@res.send
.calledWith("user@email.com\n")
.should.equal true
| 154683 | SandboxedModule = require('sandboxed-module')
should = require('chai').should()
sinon = require 'sinon'
assert = require("chai").assert
modulePath = "../../../../app/js/Features/Subscription/SubscriptionGroupController"
MockResponse = require "../helpers/MockResponse"
describe "SubscriptionGroupController", ->
beforeEach ->
@user = {_id:"!@312431",email:"<EMAIL>"}
@adminUserId = "123jlkj"
@subscription_id = "123434325412"
@user_email = "<EMAIL>"
@req =
session:
user:
_id: @adminUserId
email:@user_email
params:
subscription_id:@subscription_id
query:{}
@subscription = {}
@GroupHandler =
addUserToGroup: sinon.stub().callsArgWith(2, null, @user)
removeUserFromGroup: sinon.stub().callsArgWith(2)
isUserPartOfGroup: sinon.stub()
getPopulatedListOfMembers: sinon.stub().callsArgWith(1, null, [@user])
@SubscriptionLocator = getUsersSubscription: sinon.stub().callsArgWith(1, null, @subscription)
@AuthenticationController =
getLoggedInUserId: (req) -> req.session.user._id
getSessionUser: (req) -> req.session.user
@SubscriptionDomainHandler =
findDomainLicenceBySubscriptionId:sinon.stub()
@OneTimeTokenHandler =
getValueFromTokenAndExpire:sinon.stub()
@ErrorsController =
notFound:sinon.stub()
@Controller = SandboxedModule.require modulePath, requires:
"./SubscriptionGroupHandler":@GroupHandler
"logger-sharelatex": log:->
"./SubscriptionLocator": @SubscriptionLocator
"./SubscriptionDomainHandler":@SubscriptionDomainHandler
"../Errors/ErrorController":@ErrorsController
'../Authentication/AuthenticationController': @AuthenticationController
@token = "<PASSWORD>-token"
describe "addUserToGroup", ->
it "should use the admin id for the logged in user and take the email address from the body", (done)->
newEmail = " <EMAIL> "
@req.body = email: newEmail
res =
json : (data)=>
@GroupHandler.addUserToGroup.calledWith(@adminUserId, "<EMAIL>").should.equal true
data.user.should.deep.equal @user
done()
@Controller.addUserToGroup @req, res
describe "removeUserFromGroup", ->
it "should use the admin id for the logged in user and take the user id from the params", (done)->
userIdToRemove = "31231"
@req.params = user_id: userIdToRemove
res =
send : =>
@GroupHandler.removeUserFromGroup.calledWith(@adminUserId, userIdToRemove).should.equal true
done()
@Controller.removeUserFromGroup @req, res
describe "renderSubscriptionGroupAdminPage", ->
it "should redirect you if you don't have a group account", (done)->
@subscription.groupPlan = false
res =
redirect : (path)=>
path.should.equal("/user/subscription")
done()
@Controller.renderSubscriptionGroupAdminPage @req, res
it "should redirect you don't have a subscription", (done)->
@SubscriptionLocator.getUsersSubscription = sinon.stub().callsArgWith(1)
res =
redirect : (path)=>
path.should.equal("/user/subscription")
done()
@Controller.renderSubscriptionGroupAdminPage @req, res
describe "exportGroupCsv", ->
beforeEach ->
@subscription.groupPlan = true
@res = new MockResponse()
@res.contentType = sinon.stub()
@res.header = sinon.stub()
@res.send = sinon.stub()
@Controller.exportGroupCsv @req, @res
it "should set the correct content type on the request", ->
@res.contentType
.calledWith("text/csv")
.should.equal true
it "should name the exported csv file", ->
@res.header
.calledWith(
"Content-Disposition",
"attachment; filename=Group.csv")
.should.equal true
it "should export the correct csv", ->
@res.send
.calledWith("<EMAIL>\n")
.should.equal true
| true | SandboxedModule = require('sandboxed-module')
should = require('chai').should()
sinon = require 'sinon'
assert = require("chai").assert
modulePath = "../../../../app/js/Features/Subscription/SubscriptionGroupController"
MockResponse = require "../helpers/MockResponse"
describe "SubscriptionGroupController", ->
beforeEach ->
@user = {_id:"!@312431",email:"PI:EMAIL:<EMAIL>END_PI"}
@adminUserId = "123jlkj"
@subscription_id = "123434325412"
@user_email = "PI:EMAIL:<EMAIL>END_PI"
@req =
session:
user:
_id: @adminUserId
email:@user_email
params:
subscription_id:@subscription_id
query:{}
@subscription = {}
@GroupHandler =
addUserToGroup: sinon.stub().callsArgWith(2, null, @user)
removeUserFromGroup: sinon.stub().callsArgWith(2)
isUserPartOfGroup: sinon.stub()
getPopulatedListOfMembers: sinon.stub().callsArgWith(1, null, [@user])
@SubscriptionLocator = getUsersSubscription: sinon.stub().callsArgWith(1, null, @subscription)
@AuthenticationController =
getLoggedInUserId: (req) -> req.session.user._id
getSessionUser: (req) -> req.session.user
@SubscriptionDomainHandler =
findDomainLicenceBySubscriptionId:sinon.stub()
@OneTimeTokenHandler =
getValueFromTokenAndExpire:sinon.stub()
@ErrorsController =
notFound:sinon.stub()
@Controller = SandboxedModule.require modulePath, requires:
"./SubscriptionGroupHandler":@GroupHandler
"logger-sharelatex": log:->
"./SubscriptionLocator": @SubscriptionLocator
"./SubscriptionDomainHandler":@SubscriptionDomainHandler
"../Errors/ErrorController":@ErrorsController
'../Authentication/AuthenticationController': @AuthenticationController
@token = "PI:PASSWORD:<PASSWORD>END_PI-token"
describe "addUserToGroup", ->
it "should use the admin id for the logged in user and take the email address from the body", (done)->
newEmail = " PI:EMAIL:<EMAIL>END_PI "
@req.body = email: newEmail
res =
json : (data)=>
@GroupHandler.addUserToGroup.calledWith(@adminUserId, "PI:EMAIL:<EMAIL>END_PI").should.equal true
data.user.should.deep.equal @user
done()
@Controller.addUserToGroup @req, res
describe "removeUserFromGroup", ->
it "should use the admin id for the logged in user and take the user id from the params", (done)->
userIdToRemove = "31231"
@req.params = user_id: userIdToRemove
res =
send : =>
@GroupHandler.removeUserFromGroup.calledWith(@adminUserId, userIdToRemove).should.equal true
done()
@Controller.removeUserFromGroup @req, res
describe "renderSubscriptionGroupAdminPage", ->
it "should redirect you if you don't have a group account", (done)->
@subscription.groupPlan = false
res =
redirect : (path)=>
path.should.equal("/user/subscription")
done()
@Controller.renderSubscriptionGroupAdminPage @req, res
it "should redirect you don't have a subscription", (done)->
@SubscriptionLocator.getUsersSubscription = sinon.stub().callsArgWith(1)
res =
redirect : (path)=>
path.should.equal("/user/subscription")
done()
@Controller.renderSubscriptionGroupAdminPage @req, res
describe "exportGroupCsv", ->
beforeEach ->
@subscription.groupPlan = true
@res = new MockResponse()
@res.contentType = sinon.stub()
@res.header = sinon.stub()
@res.send = sinon.stub()
@Controller.exportGroupCsv @req, @res
it "should set the correct content type on the request", ->
@res.contentType
.calledWith("text/csv")
.should.equal true
it "should name the exported csv file", ->
@res.header
.calledWith(
"Content-Disposition",
"attachment; filename=Group.csv")
.should.equal true
it "should export the correct csv", ->
@res.send
.calledWith("PI:EMAIL:<EMAIL>END_PI\n")
.should.equal true
|
[
{
"context": "### (c) 2013 Maxim Litvinov ###\n\niw = 20\nih = 20\nCOLORS = 3\ndegree = Math.PI/",
"end": 27,
"score": 0.9997661113739014,
"start": 13,
"tag": "NAME",
"value": "Maxim Litvinov"
}
] | 6/collapse.coffee | metalim/21 | 0 | ### (c) 2013 Maxim Litvinov ###
iw = 20
ih = 20
COLORS = 3
degree = Math.PI/180
styles = [
'red'
'blue'
'gold'
'green'
]
musicPlaying = false
class Game
constructor:->
@canvas = document.getElementById 'canvas'
@ctx = @canvas.getContext '2d'
@ctx.translate 0.5,0.5
@canvas.onmousemove = (e)=>@move e
@canvas.onclick = (e)=>@click e
window.onresize = (e)=>@resize e
@audio = {}
(@audio[name] = new Audio 'audio/'+name+'.wav') for name in ['hit']
@reset()
reset:->
@playing = true
@won = false
@state = []
until @canRemoveAny()
@state = (Math.random()*COLORS|0 for y in [0...ih] for x in [0...iw])
@resize()
resize:->
@w = @canvas.width = @canvas.offsetWidth
@h = @canvas.height = @canvas.offsetHeight
@u = Math.min(@w/iw, @h/ih)&~1
@x0 = (@w-@u*iw)/2|0
@y0 = (@h-@u*ih)/2|0
console.log @w,@h,@u,@x0,@y0
@draw()
move:(e)->
if not @playing
return
offset = $(@canvas).offset()
x = Math.floor((e.pageX - offset.top - @x0)/@u)
y = ih - Math.ceil((e.pageY - offset.top - @y0)/@u)
if x in [0...iw] and y in [0...ih]
@selected =
x:x
y:y
else
@selected = null
@draw()
click:(e)->
if not musicPlaying
musicPlaying = true
audio = $("audio").get(0);
if audio.duration is 0 or audio.paused
audio.load()
audio.play()
if not @playing
@reset()
return
offset = $(@canvas).offset()
x = Math.floor((e.pageX - offset.top - @x0)/@u)
y = ih - Math.ceil((e.pageY - offset.top - @y0)/@u)
if x in [0...@state.length] and y in [0...@state[x].length]
if @tryRemove x,y
@collapse()
if not @canRemoveAny()
@gameover()
if not @state.length
@win()
@draw()
else
@audio.hit.play()
gameover:->
@playing=false
win:->
@playing=false
@won=true
tryRemove:(x,y)->
bak = (c for c in col for col in @state)
res = @remove x,y
if res<3
@state = bak
false
else
true
canRemoveAny:->
for col,x in @state
for c,y in col
bak = (c for c in col for col in @state)
res = @remove x,y
@state = bak
if res>=3
return true
false
remove:(x,y,c=@state[x][y])->
if x in [0...@state.length] and y in [0...ih] and @state[x][y] is c
delete @state[x][y]
1+@remove(x-1,y,c)+@remove(x+1,y,c)+@remove(x,y-1,c)+@remove(x,y+1,c)
else
0
collapse:->
for x of @state
@state[x] = (c for c in @state[x] when c?)
@state = (col for col in @state when col.length)
draw:->
@ctx.clearRect 0,0,@w,@h
@ctx.strokeStyle = 'grey'
@ctx.lineWidth = 1
@ctx.strokeRect @x0,@y0,iw*@u,ih*@u
for col,x in @state
for cell,y in col when cell?
@ctx.fillStyle = styles[cell]
@ctx.beginPath()
@ctx.rect @x0+@u*(x+0.05),@y0+@u*(ih-y-0.95),@u*0.9,@u*0.9
@ctx.fill()
if @selected? and @selected.x is x and @selected.y is y
@ctx.lineWidth = 2
@ctx.stroke()
# then 'gold' else 'black'
#@ctx.strokeStyle =
#
if not @playing
#@ctx.font = 'bold 300% sans-serif'
@ctx.font = 'bold '+(@u*ih*0.1)+'px sans-serif'
@ctx.lineWidth = 2
@ctx.textAlign = 'center'
@ctx.textBaseline = 'middle'
if @won
@ctx.strokeStyle = 'yellow'
@ctx.fillStyle = 'green'
@ctx.fillText 'YOU WIN!',@w/2,@h/2
@ctx.strokeText 'YOU WIN!',@w/2,@h/2
else
@ctx.strokeStyle = 'darkred'
@ctx.fillStyle = 'red'
@ctx.fillText 'GAME OVER',@w/2,@h/2
@ctx.strokeText 'GAME OVER',@w/2,@h/2
$ ->
new Game()
| 163657 | ### (c) 2013 <NAME> ###
iw = 20
ih = 20
COLORS = 3
degree = Math.PI/180
styles = [
'red'
'blue'
'gold'
'green'
]
musicPlaying = false
class Game
constructor:->
@canvas = document.getElementById 'canvas'
@ctx = @canvas.getContext '2d'
@ctx.translate 0.5,0.5
@canvas.onmousemove = (e)=>@move e
@canvas.onclick = (e)=>@click e
window.onresize = (e)=>@resize e
@audio = {}
(@audio[name] = new Audio 'audio/'+name+'.wav') for name in ['hit']
@reset()
reset:->
@playing = true
@won = false
@state = []
until @canRemoveAny()
@state = (Math.random()*COLORS|0 for y in [0...ih] for x in [0...iw])
@resize()
resize:->
@w = @canvas.width = @canvas.offsetWidth
@h = @canvas.height = @canvas.offsetHeight
@u = Math.min(@w/iw, @h/ih)&~1
@x0 = (@w-@u*iw)/2|0
@y0 = (@h-@u*ih)/2|0
console.log @w,@h,@u,@x0,@y0
@draw()
move:(e)->
if not @playing
return
offset = $(@canvas).offset()
x = Math.floor((e.pageX - offset.top - @x0)/@u)
y = ih - Math.ceil((e.pageY - offset.top - @y0)/@u)
if x in [0...iw] and y in [0...ih]
@selected =
x:x
y:y
else
@selected = null
@draw()
click:(e)->
if not musicPlaying
musicPlaying = true
audio = $("audio").get(0);
if audio.duration is 0 or audio.paused
audio.load()
audio.play()
if not @playing
@reset()
return
offset = $(@canvas).offset()
x = Math.floor((e.pageX - offset.top - @x0)/@u)
y = ih - Math.ceil((e.pageY - offset.top - @y0)/@u)
if x in [0...@state.length] and y in [0...@state[x].length]
if @tryRemove x,y
@collapse()
if not @canRemoveAny()
@gameover()
if not @state.length
@win()
@draw()
else
@audio.hit.play()
gameover:->
@playing=false
win:->
@playing=false
@won=true
tryRemove:(x,y)->
bak = (c for c in col for col in @state)
res = @remove x,y
if res<3
@state = bak
false
else
true
canRemoveAny:->
for col,x in @state
for c,y in col
bak = (c for c in col for col in @state)
res = @remove x,y
@state = bak
if res>=3
return true
false
remove:(x,y,c=@state[x][y])->
if x in [0...@state.length] and y in [0...ih] and @state[x][y] is c
delete @state[x][y]
1+@remove(x-1,y,c)+@remove(x+1,y,c)+@remove(x,y-1,c)+@remove(x,y+1,c)
else
0
collapse:->
for x of @state
@state[x] = (c for c in @state[x] when c?)
@state = (col for col in @state when col.length)
draw:->
@ctx.clearRect 0,0,@w,@h
@ctx.strokeStyle = 'grey'
@ctx.lineWidth = 1
@ctx.strokeRect @x0,@y0,iw*@u,ih*@u
for col,x in @state
for cell,y in col when cell?
@ctx.fillStyle = styles[cell]
@ctx.beginPath()
@ctx.rect @x0+@u*(x+0.05),@y0+@u*(ih-y-0.95),@u*0.9,@u*0.9
@ctx.fill()
if @selected? and @selected.x is x and @selected.y is y
@ctx.lineWidth = 2
@ctx.stroke()
# then 'gold' else 'black'
#@ctx.strokeStyle =
#
if not @playing
#@ctx.font = 'bold 300% sans-serif'
@ctx.font = 'bold '+(@u*ih*0.1)+'px sans-serif'
@ctx.lineWidth = 2
@ctx.textAlign = 'center'
@ctx.textBaseline = 'middle'
if @won
@ctx.strokeStyle = 'yellow'
@ctx.fillStyle = 'green'
@ctx.fillText 'YOU WIN!',@w/2,@h/2
@ctx.strokeText 'YOU WIN!',@w/2,@h/2
else
@ctx.strokeStyle = 'darkred'
@ctx.fillStyle = 'red'
@ctx.fillText 'GAME OVER',@w/2,@h/2
@ctx.strokeText 'GAME OVER',@w/2,@h/2
$ ->
new Game()
| true | ### (c) 2013 PI:NAME:<NAME>END_PI ###
iw = 20
ih = 20
COLORS = 3
degree = Math.PI/180
styles = [
'red'
'blue'
'gold'
'green'
]
musicPlaying = false
class Game
constructor:->
@canvas = document.getElementById 'canvas'
@ctx = @canvas.getContext '2d'
@ctx.translate 0.5,0.5
@canvas.onmousemove = (e)=>@move e
@canvas.onclick = (e)=>@click e
window.onresize = (e)=>@resize e
@audio = {}
(@audio[name] = new Audio 'audio/'+name+'.wav') for name in ['hit']
@reset()
reset:->
@playing = true
@won = false
@state = []
until @canRemoveAny()
@state = (Math.random()*COLORS|0 for y in [0...ih] for x in [0...iw])
@resize()
resize:->
@w = @canvas.width = @canvas.offsetWidth
@h = @canvas.height = @canvas.offsetHeight
@u = Math.min(@w/iw, @h/ih)&~1
@x0 = (@w-@u*iw)/2|0
@y0 = (@h-@u*ih)/2|0
console.log @w,@h,@u,@x0,@y0
@draw()
move:(e)->
if not @playing
return
offset = $(@canvas).offset()
x = Math.floor((e.pageX - offset.top - @x0)/@u)
y = ih - Math.ceil((e.pageY - offset.top - @y0)/@u)
if x in [0...iw] and y in [0...ih]
@selected =
x:x
y:y
else
@selected = null
@draw()
click:(e)->
if not musicPlaying
musicPlaying = true
audio = $("audio").get(0);
if audio.duration is 0 or audio.paused
audio.load()
audio.play()
if not @playing
@reset()
return
offset = $(@canvas).offset()
x = Math.floor((e.pageX - offset.top - @x0)/@u)
y = ih - Math.ceil((e.pageY - offset.top - @y0)/@u)
if x in [0...@state.length] and y in [0...@state[x].length]
if @tryRemove x,y
@collapse()
if not @canRemoveAny()
@gameover()
if not @state.length
@win()
@draw()
else
@audio.hit.play()
gameover:->
@playing=false
win:->
@playing=false
@won=true
tryRemove:(x,y)->
bak = (c for c in col for col in @state)
res = @remove x,y
if res<3
@state = bak
false
else
true
canRemoveAny:->
for col,x in @state
for c,y in col
bak = (c for c in col for col in @state)
res = @remove x,y
@state = bak
if res>=3
return true
false
remove:(x,y,c=@state[x][y])->
if x in [0...@state.length] and y in [0...ih] and @state[x][y] is c
delete @state[x][y]
1+@remove(x-1,y,c)+@remove(x+1,y,c)+@remove(x,y-1,c)+@remove(x,y+1,c)
else
0
collapse:->
for x of @state
@state[x] = (c for c in @state[x] when c?)
@state = (col for col in @state when col.length)
draw:->
@ctx.clearRect 0,0,@w,@h
@ctx.strokeStyle = 'grey'
@ctx.lineWidth = 1
@ctx.strokeRect @x0,@y0,iw*@u,ih*@u
for col,x in @state
for cell,y in col when cell?
@ctx.fillStyle = styles[cell]
@ctx.beginPath()
@ctx.rect @x0+@u*(x+0.05),@y0+@u*(ih-y-0.95),@u*0.9,@u*0.9
@ctx.fill()
if @selected? and @selected.x is x and @selected.y is y
@ctx.lineWidth = 2
@ctx.stroke()
# then 'gold' else 'black'
#@ctx.strokeStyle =
#
if not @playing
#@ctx.font = 'bold 300% sans-serif'
@ctx.font = 'bold '+(@u*ih*0.1)+'px sans-serif'
@ctx.lineWidth = 2
@ctx.textAlign = 'center'
@ctx.textBaseline = 'middle'
if @won
@ctx.strokeStyle = 'yellow'
@ctx.fillStyle = 'green'
@ctx.fillText 'YOU WIN!',@w/2,@h/2
@ctx.strokeText 'YOU WIN!',@w/2,@h/2
else
@ctx.strokeStyle = 'darkred'
@ctx.fillStyle = 'red'
@ctx.fillText 'GAME OVER',@w/2,@h/2
@ctx.strokeText 'GAME OVER',@w/2,@h/2
$ ->
new Game()
|
[
{
"context": "expects('hit').never()\n\n @battle.recordMove(@id2, tackle)\n @battle.determineTurnOrder()\n ",
"end": 3813,
"score": 0.9391696453094482,
"start": 3810,
"tag": "USERNAME",
"value": "id2"
},
{
"context": "ttle.getMove(\"Tackle\")\n\n @battle.recordMove... | test/xy/moves.coffee | sarenji/pokebattle-sim | 5 | {Attachment, Status} = require('../../server/xy/attachment')
{Battle} = require('../../server/xy/battle')
{Pokemon} = require('../../server/xy/pokemon')
{Weather} = require('../../shared/weather')
{Move} = require('../../server/xy/move')
util = require '../../server/xy/util'
{Protocol} = require '../../shared/protocol'
{Factory} = require '../factory'
should = require 'should'
{_} = require 'underscore'
shared = require '../shared'
require '../helpers'
describe "XY Moves:", ->
# Test every single move for their primary effects.
shared.testEveryMove(Battle::MoveList, 'xy')
describe "a critical hit", ->
it "multiplies damage by 1.5x", ->
Move::criticalMultiplier.should.equal(1.5)
it "becomes a 50% chance at a +3 CH level", ->
Move::determineCriticalHitFromLevel(3, .49).should.be.true
Move::determineCriticalHitFromLevel(3, .5).should.be.false
it "becomes a 100% chance at a +4 CH level", ->
Move::determineCriticalHitFromLevel(4, .99).should.be.true
Move::determineCriticalHitFromLevel(4, 1.0).should.be.false
describe "a powder move", ->
it "does not affect Grass-types", ->
shared.create.call(this, gen: 'xy')
powderMove = @battle.findMove((m) -> m.hasFlag("powder"))
@p2.types.push("Grass")
mock1 = @sandbox.mock(powderMove).expects('hit').never()
mock2 = @sandbox.mock(powderMove).expects('fail').once()
@battle.performMove(@p1, powderMove)
mock1.verify()
mock2.verify()
it "affects non-Grass-types", ->
shared.create.call(this, gen: 'xy')
powderMove = @battle.findMove((m) -> m.hasFlag("powder"))
@p2.types = [ "Normal" ]
mock1 = @sandbox.mock(powderMove).expects('hit').once()
mock2 = @sandbox.mock(powderMove).expects('fail').never()
@battle.performMove(@p1, powderMove)
mock1.verify()
mock2.verify()
describe "Dragon Pulse", ->
it "has 85 base power now", ->
shared.create.call(this, gen: 'xy')
@battle.getMove('Dragon Pulse').power.should.equal(85)
describe 'Hidden Power', ->
it "always has 60 base power", ->
shared.create.call(this, gen: 'xy')
hiddenPower = @battle.getMove('Hidden Power')
hiddenPower.power.should.equal(60)
hiddenPower.basePower(@battle, @p1, @p2).should.equal(60)
describe "Facade", ->
it "does not cut attack in half when burned", ->
shared.create.call(this, gen: 'xy')
facade = @battle.getMove('Facade')
facade.burnCalculation(@p1).should.equal(1)
@p1.attach(Status.Burn)
facade.burnCalculation(@p1).should.equal(1)
describe "King's Shield", ->
it "protects against attacks", ->
shared.create.call(this, gen: 'xy')
kingsShield = @battle.getMove("King's Shield")
tackle = @battle.getMove("Tackle")
mock = @sandbox.mock(tackle).expects('hit').never()
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
@battle.performMove(@p1, kingsShield)
@battle.performMove(@p2, tackle)
mock.verify()
it "does not protect against non-damaging moves", ->
shared.create.call(this, gen: 'xy')
kingsShield = @battle.getMove("King's Shield")
willOWisp = @battle.getMove("Will-O-Wisp")
mock = @sandbox.mock(willOWisp).expects('hit').once()
@battle.recordMove(@id2, willOWisp)
@battle.determineTurnOrder()
@battle.performMove(@p1, kingsShield)
@battle.performMove(@p2, willOWisp)
mock.verify()
it "does not protect against attacks it is immune to", ->
shared.create.call(this, gen: 'xy')
@p1.types = [ 'Ghost' ]
kingsShield = @battle.getMove("King's Shield")
tackle = @battle.getMove("Tackle")
mock = @sandbox.mock(tackle).expects('hit').never()
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
@battle.performMove(@p1, kingsShield)
@battle.performMove(@p2, tackle)
mock.verify()
@p2.stages.should.containEql(attack: 0)
it "sharply lowers attacker's Attack if move was a contact move", ->
shared.create.call(this, gen: 'xy')
kingsShield = @battle.getMove("King's Shield")
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
@battle.performMove(@p1, kingsShield)
@p2.stages.attack.should.equal(0)
@battle.performMove(@p2, tackle)
@p2.stages.attack.should.equal(-2)
it "does not lower attacker's Attack if move was not a contact move", ->
shared.create.call(this, gen: 'xy')
kingsShield = @battle.getMove("King's Shield")
ember = @battle.getMove("Ember")
@battle.recordMove(@id2, ember)
@battle.determineTurnOrder()
@battle.performMove(@p1, kingsShield)
@p2.stages.attack.should.equal(0)
@battle.performMove(@p2, ember)
@p2.stages.attack.should.equal(0)
describe "Spiky Shield", ->
it "protects against attacks", ->
shared.create.call(this, gen: 'xy')
spikyShield = @battle.getMove("Spiky Shield")
tackle = @battle.getMove("Tackle")
mock = @sandbox.mock(tackle).expects('hit').never()
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
@battle.performMove(@p1, spikyShield)
@battle.performMove(@p2, tackle)
mock.verify()
it "protects against non-damaging moves", ->
shared.create.call(this, gen: 'xy')
spikyShield = @battle.getMove("Spiky Shield")
willOWisp = @battle.getMove("Will-O-Wisp")
mock = @sandbox.mock(willOWisp).expects('hit').never()
@battle.recordMove(@id2, willOWisp)
@battle.determineTurnOrder()
@battle.performMove(@p1, spikyShield)
@battle.performMove(@p2, willOWisp)
mock.verify()
it "does not protect against attacks it is immune to", ->
shared.create.call(this, gen: 'xy')
@p1.types = [ 'Ghost' ]
spikyShield = @battle.getMove("Spiky Shield")
tackle = @battle.getMove("Tackle")
mock = @sandbox.mock(tackle).expects('hit').never()
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
@battle.performMove(@p1, spikyShield)
@battle.performMove(@p2, tackle)
mock.verify()
@p2.stages.should.containEql(attack: 0)
it "damages attacker by 1/8 if move was a contact move", ->
shared.create.call(this, gen: 'xy')
spikyShield = @battle.getMove("Spiky Shield")
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
@battle.performMove(@p1, spikyShield)
@p2.currentHP.should.not.be.lessThan(@p2.stat('hp'))
@battle.performMove(@p2, tackle)
(@p2.stat('hp') - @p2.currentHP).should.equal(@p2.stat('hp') >> 3)
it "does not damage attacker if move was not a contact move", ->
shared.create.call(this, gen: 'xy')
spikyShield = @battle.getMove("Spiky Shield")
ember = @battle.getMove("Ember")
@battle.recordMove(@id2, ember)
@battle.determineTurnOrder()
@battle.performMove(@p1, spikyShield)
@p2.currentHP.should.not.be.lessThan(@p2.stat('hp'))
@battle.performMove(@p2, ember)
@p2.currentHP.should.not.be.lessThan(@p2.stat('hp'))
describe "Sticky Web", ->
shared.shouldFailIfUsedTwice("Sticky Web", gen: 'xy')
it "lowers a pokemon's speed by 1 when switching in", ->
shared.create.call(this, gen: 'xy', team2: (Factory("Magikarp") for x in [0..1]))
stickyWeb = @battle.getMove("Sticky Web")
@battle.performMove(@p1, stickyWeb)
@battle.performSwitch(@p2, 1)
@team2.first().stages.should.containEql(speed: -1)
it "doesn't lower a pokemon's speed by 1 if immune to ground", ->
shared.create.call(this, gen: 'xy', team2: [ Factory("Magikarp"), Factory("Gyarados") ])
stickyWeb = @battle.getMove("Sticky Web")
@battle.performMove(@p1, stickyWeb)
@battle.performSwitch(@p2, 1)
@team2.first().stages.should.containEql(speed: 0)
describe "Rapid Spin", ->
it "removes Sticky Web", ->
shared.create.call(this, gen: 'xy')
stickyWeb = @battle.getMove("Sticky Web")
rapidSpin = @battle.getMove("Rapid Spin")
@battle.performMove(@p1, stickyWeb)
@team2.has(Attachment.StickyWeb).should.be.true
@battle.performMove(@p2, rapidSpin)
@team2.has(Attachment.StickyWeb).should.be.false
describe "Defog", ->
it "removes Sticky Web as well", ->
shared.create.call(this, gen: 'xy')
defog = @battle.getMove("Defog")
@battle.performMove(@p1, @battle.getMove("Sticky Web"))
@p2.team.has(Attachment.StickyWeb).should.be.true
@battle.performMove(@p1, defog)
@p2.team.has(Attachment.StickyWeb).should.be.false
it "removes hazards from both sides of the field now", ->
shared.create.call(this, gen: 'xy')
defog = @battle.getMove("Defog")
@battle.performMove(@p1, @battle.getMove("Sticky Web"))
@battle.performMove(@p2, @battle.getMove("Sticky Web"))
@p1.team.has(Attachment.StickyWeb).should.be.true
@p2.team.has(Attachment.StickyWeb).should.be.true
@battle.performMove(@p1, defog)
@p1.team.has(Attachment.StickyWeb).should.be.false
@p2.team.has(Attachment.StickyWeb).should.be.false
it "removes screens from only the target's side of the field", ->
shared.create.call(this, gen: 'xy')
defog = @battle.getMove("Defog")
@battle.performMove(@p1, @battle.getMove("Reflect"))
@battle.performMove(@p1, @battle.getMove("Light Screen"))
@battle.performMove(@p2, @battle.getMove("Reflect"))
@battle.performMove(@p2, @battle.getMove("Light Screen"))
@p1.team.has(Attachment.Reflect).should.be.true
@p1.team.has(Attachment.LightScreen).should.be.true
@p2.team.has(Attachment.Reflect).should.be.true
@p2.team.has(Attachment.LightScreen).should.be.true
@battle.performMove(@p1, defog)
@p1.team.has(Attachment.Reflect).should.be.true
@p1.team.has(Attachment.LightScreen).should.be.true
@p2.team.has(Attachment.Reflect).should.be.false
@p2.team.has(Attachment.LightScreen).should.be.false
describe "Knock Off", ->
it "has x1.0 power if the pokemon has no item", ->
shared.create.call(this, gen: 'xy')
knockOff = @battle.getMove("Knock Off")
knockOff.basePower(@battle, @p1, @p2).should.equal(knockOff.power)
it "has x1.5 power if the item can be knocked off", ->
shared.create.call this,
gen: 'xy'
team2: [Factory("Magikarp", item: "Leftovers")]
knockOff = @battle.getMove("Knock Off")
basePower = knockOff.basePower(@battle, @p1, @p2)
basePower.should.equal Math.floor(1.5 * knockOff.power)
it "has x1.0 power if the item cannot be knocked off", ->
shared.create.call this,
gen: 'xy'
team2: [Factory("Magikarp", item: "Air Mail")]
knockOff = @battle.getMove("Knock Off")
knockOff.basePower(@battle, @p1, @p2).should.equal(knockOff.power)
it "has x1.5 power if item can be knocked off but owner has Sticky Hold", ->
shared.create.call this,
gen: 'xy'
team2: [Factory("Magikarp", item: "Leftovers", ability: "Sticky Hold")]
knockOff = @battle.getMove("Knock Off")
basePower = knockOff.basePower(@battle, @p1, @p2)
basePower.should.equal Math.floor(1.5 * knockOff.power)
describe "Protect-like moves", ->
it "determines success chance using a power of 3 instead of 2", ->
shared.create.call(this, gen: 'xy')
for x in [0..7]
attachment = @p1.attach(Attachment.ProtectCounter)
attachment.successChance().should.equal Math.pow(3, x)
attachment = @p1.attach(Attachment.ProtectCounter)
attachment.successChance().should.equal Math.pow(2, 32)
describe "Freeze-Dry", ->
it "is 2x effective against Water-types", ->
shared.create.call(this, gen: 'xy')
@p2.types = [ "Water" ]
freezeDry = @battle.getMove('Freeze-Dry')
spy = @sandbox.spy(freezeDry, 'typeEffectiveness')
@battle.performMove(@p1, freezeDry)
spy.returned(2).should.be.true
it "is 2x effective against Water-types with Normalize", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", ability: "Normalize")]
@p2.types = [ "Water" ]
freezeDry = @battle.getMove('Freeze-Dry')
spy = @sandbox.spy(freezeDry, 'typeEffectiveness')
@battle.performMove(@p1, freezeDry)
spy.returned(2).should.be.true
it "is normally effective against other types", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp")]
@p2.types = [ "Fire" ]
freezeDry = @battle.getMove('Freeze-Dry')
spy = @sandbox.spy(freezeDry, 'typeEffectiveness')
@battle.performMove(@p1, freezeDry)
spy.returned(.5).should.be.true
describe "Substitute", ->
it "is bypassed by voice moves", ->
shared.create.call(this, gen: 'xy')
@p2.attach(Attachment.Substitute, hp: (@p1.currentHP >> 2))
voiceMove = @battle.findMove (m) ->
!m.isNonDamaging() && m.hasFlag("sound")
spy = @sandbox.spy(voiceMove, 'hit')
@battle.performMove(@p1, voiceMove)
spy.calledOnce.should.be.true
@p2.currentHP.should.be.lessThan(@p2.stat('hp'))
it "is bypassed by Infiltrator", ->
shared.create.call this,
gen: 'xy'
team1: [ Factory("Magikarp", ability: "Infiltrator")]
@p2.attach(Attachment.Substitute, hp: (@p1.currentHP >> 2))
tackle = @battle.getMove("Tackle")
spy = @sandbox.spy(tackle, 'hit')
@battle.performMove(@p1, tackle)
spy.calledOnce.should.be.true
@p2.currentHP.should.be.lessThan(@p2.stat('hp'))
it "is bypassed by Infiltrator even on status moves", ->
shared.create.call this,
gen: 'xy'
team1: [ Factory("Magikarp", ability: "Infiltrator")]
@p2.attach(Attachment.Substitute, hp: (@p1.currentHP >> 2))
toxic = @battle.getMove("Toxic")
spy = @sandbox.spy(toxic, 'hit')
@battle.performMove(@p1, toxic)
spy.calledOnce.should.be.true
@p2.has(Status.Toxic).should.be.true
it "does not block Knock Off + Infiltrator", ->
shared.create.call this,
gen: 'xy'
team1: [ Factory("Magikarp", ability: "Infiltrator")]
team2: [ Factory("Magikarp", item: "Leftovers")]
@p2.attach(Attachment.Substitute, hp: (@p1.currentHP >> 2))
knockOff = @battle.getMove("Knock Off")
spy = @sandbox.spy(knockOff, 'hit')
@battle.performMove(@p1, knockOff)
spy.calledOnce.should.be.true
@p2.hasItem().should.be.false
it "does not block secondary effects + Infiltrator", ->
shared.create.call this,
gen: 'xy'
team1: [ Factory("Magikarp", ability: "Infiltrator")]
shared.biasRNG.call(this, "next", "secondary effect", 0) # always burn
@p2.attach(Attachment.Substitute, hp: (@p1.currentHP >> 2))
flamethrower = @battle.getMove('Flamethrower')
spy = @sandbox.spy(flamethrower, 'hit')
@battle.performMove(@p1, flamethrower)
spy.calledOnce.should.be.true
@p2.has(Status.Burn).should.be.true
testChargeMove = (moveName, vulnerable) ->
describe moveName, ->
it "chooses the player's next action for them", ->
shared.create.call(this, gen: 'xy')
move = @battle.getMove(moveName)
@p1.moves = [ move ]
@battle.recordMove(@id1, move)
@battle.continueTurn()
@battle.endTurn()
@battle.beginTurn()
@battle.requests.should.not.have.property(@id1)
should.exist(@battle.getAction(@p1))
it "only spends 1 PP for the entire attack", ->
shared.create.call(this, gen: 'xy')
move = @battle.getMove(moveName)
@p1.moves = [ move ]
@p1.resetAllPP()
pp = @p1.pp(move)
@battle.recordMove(@id1, move)
@battle.continueTurn()
@p1.pp(move).should.equal(pp)
@battle.beginTurn()
@battle.continueTurn()
@p1.pp(move).should.equal(pp - 1)
it "skips the charge turn if the user is holding a Power Herb", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", item: "Power Herb")]
move = @battle.getMove(moveName)
@p1.hasItem("Power Herb").should.be.true
mock = @sandbox.mock(move).expects('execute').once()
@battle.recordMove(@id1, move)
@battle.continueTurn()
mock.verify()
@p1.hasItem().should.be.false
if vulnerable?.length?
it "makes target invulnerable to moves", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", evs: {speed: 4})]
move = @battle.getMove(moveName)
swift = @battle.getMove("Swift")
@battle.recordMove(@id1, move)
@battle.recordMove(@id2, swift)
mock = @sandbox.mock(swift).expects('hit').never()
@battle.continueTurn()
mock.verify()
it "makes target invulnerable to moves *after* use", ->
shared.create.call this,
gen: 'xy'
team2: [Factory("Magikarp", evs: {speed: 4})]
move = @battle.getMove(moveName)
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id1, move)
@battle.recordMove(@id2, tackle)
mock = @sandbox.mock(tackle).expects('hit').once()
@battle.continueTurn()
mock.verify()
it "is vulnerable to attacks from a No Guard pokemon", ->
shared.create.call this,
gen: 'xy'
team2: [Factory("Magikarp", ability: "No Guard")]
move = @battle.getMove(moveName)
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id1, move)
@battle.recordMove(@id2, tackle)
mock = @sandbox.mock(tackle).expects('hit').once()
@battle.continueTurn()
mock.verify()
it "is vulnerable to attacks if locked on", ->
shared.create.call(this, gen: 'xy')
@battle.performMove(@p1, @battle.getMove("Lock-On"))
@battle.performMove(@p2, @battle.getMove(moveName))
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id1, tackle)
mock = @sandbox.mock(tackle).expects('hit').once()
@battle.continueTurn()
mock.verify()
for vulnerableMove in vulnerable
it "is vulnerable to #{vulnerableMove}", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", evs: {speed: 4})]
move = @battle.getMove(moveName)
vulnerable = @battle.getMove(vulnerableMove)
@battle.recordMove(@id1, move)
@battle.recordMove(@id2, vulnerable)
mock = @sandbox.mock(vulnerable).expects('hit').once()
@battle.continueTurn()
mock.verify()
else # no vulnerable moves
it "doesn't make target invulnerable to moves", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", evs: {speed: 4})]
move = @battle.getMove(moveName)
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id1, move)
@battle.recordMove(@id2, tackle)
mock = @sandbox.mock(tackle).expects('hit').once()
@battle.continueTurn()
mock.verify()
testChargeMove('Fly', ["Gust", "Thunder", "Twister", "Sky Uppercut", "Hurricane", "Smack Down", "Thousand Arrows"])
testChargeMove('Bounce', ["Gust", "Thunder", "Twister", "Sky Uppercut", "Hurricane", "Smack Down", "Thousand Arrows"])
testChargeMove('Geomancy')
testChargeMove('Phantom Force', [])
describe "Toxic", ->
it "cannot miss when used by a Poison type pokemon", ->
shared.create.call(this, gen: 'xy')
@p1.types = [ "Poison" ]
@p2.types = [ "Normal" ]
shared.biasRNG.call(this, "randInt", 'miss', 101)
toxic = @battle.getMove("Toxic")
toxic.willMiss(@battle, @p1, @p2).should.be.false
describe "Parting Shot", ->
it "reduces the attack and special attack of the target by two stages", ->
shared.create.call(this, gen: 'xy')
@battle.performMove(@p1, @battle.getMove("Parting Shot"))
@p2.stages.should.containEql attack: -1, specialAttack: -1
it "forces the owner to switch", ->
shared.create.call(this, gen: 'xy')
@battle.performMove(@p1, @battle.getMove("Parting Shot"))
@battle.requests.should.have.property @id1
describe "Worry Seed", ->
it "does not change some abilities", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Smeargle")]
team2: [Factory("Aegislash", ability: "Stance Change")]
worrySeed = @battle.getMove("Worry Seed")
mock = @sandbox.mock(worrySeed).expects('fail').once()
@battle.performMove(@p1, worrySeed)
mock.verify()
describe "Simple Beam", ->
it "does not change some abilities", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Smeargle")]
team2: [Factory("Aegislash", ability: "Stance Change")]
simpleBeam = @battle.getMove("Simple Beam")
mock = @sandbox.mock(simpleBeam).expects('fail').once()
@battle.performMove(@p1, simpleBeam)
mock.verify()
testTrappingMove = (name) ->
describe name, ->
it "deals 1/8 of the pokemon's max hp every turn", ->
shared.create.call this,
gen: 'xy'
team2: [Factory("Blissey")]
@battle.performMove(@p1, @battle.getMove(name))
@p2.currentHP = @p2.stat('hp')
@battle.endTurn()
maxHP = @p2.stat('hp')
expected = maxHP - Math.floor(maxHP / 8)
@p2.currentHP.should.equal expected
it "deals 1/6 of the pokemon's max hp every turn if the user is holding a Binding Band", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", item: "Binding Band")]
team2: [Factory("Blissey")]
@battle.performMove(@p1, @battle.getMove(name))
@p2.currentHP = @p2.stat('hp')
@battle.endTurn()
maxHP = @p2.stat('hp')
expected = maxHP - Math.floor(maxHP / 6)
@p2.currentHP.should.equal expected
testTrappingMove "Bind"
testTrappingMove "Clamp"
testTrappingMove "Fire Spin"
testTrappingMove "Infestation"
testTrappingMove "Magma Storm"
testTrappingMove "Sand Tomb"
testTrappingMove "Wrap"
describe "Entrainment", ->
it "does not change some abilities", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", ability: "Swift Swim")]
team2: [Factory("Aegislash", ability: "Stance Change")]
entrainment = @battle.getMove("Entrainment")
mock = @sandbox.mock(entrainment).expects('fail').once()
@battle.performMove(@p1, entrainment)
mock.verify()
describe "Nature Power", ->
it "uses Tri Attack in Wi-Fi battles", ->
shared.create.call(this, gen: 'xy')
naturePower = @battle.getMove('Nature Power')
triAttack = @battle.getMove('Tri Attack')
mock = @sandbox.mock(triAttack).expects('execute').once()
.withArgs(@battle, @p1, [ @p2 ])
@battle.performMove(@p1, naturePower)
mock.verify()
describe "Venom Drench", ->
it "lowers the target's attack, special attack, and speed by 1 stage if it is poisoned", ->
shared.create.call(this, gen: 'xy')
@p2.attach(Status.Poison)
@battle.performMove(@p1, @battle.getMove('Venom Drench'))
@p2.stages.should.containEql attack: -1, specialAttack: -1, speed: -1
it "fails if the target isn't poisoned", ->
shared.create.call(this, gen: 'xy')
venomDrench = @battle.getMove("Venom Drench")
mock = @sandbox.mock(venomDrench).expects('fail').once()
@battle.performMove(@p1, venomDrench)
mock.verify()
describe "Topsy-Turvy", ->
it "reverses the target's boosts", ->
shared.create.call(this, gen: 'xy')
@p2.stages.attack = 2
@p2.stages.defense = -3
@p2.stages.speed = 0
@battle.performMove(@p1, @battle.getMove('Topsy-Turvy'))
@p2.stages.should.containEql attack: -2
@p2.stages.should.containEql defense: 3
@p2.stages.should.containEql speed: 0
it "fails if the target has no boosts", ->
shared.create.call(this, gen: 'xy')
topsyTurvy = @battle.getMove('Topsy-Turvy')
mock = @sandbox.mock(topsyTurvy).expects('fail').once()
@battle.performMove(@p1, topsyTurvy)
mock.verify()
describe "Fell Stinger", ->
it "raises the user's Attack 2 stages if the target faints", ->
shared.create.call(this, gen: 'xy')
@p2.currentHP = 1
@battle.performMove(@p1, @battle.getMove("Fell Stinger"))
@p1.stages.should.containEql attack: 2
it "does not raise the user's Attack 2 stages otherwise", ->
shared.create.call(this, gen: 'xy')
@battle.performMove(@p1, @battle.getMove("Fell Stinger"))
@p1.stages.should.containEql attack: 0
describe "Skill Swap", ->
it "can swap the abilities if they are the same", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", ability: "Swift Swim")]
team2: [Factory("Magikarp", ability: "Swift Swim")]
skillSwap = @battle.getMove("Skill Swap")
mock = @sandbox.mock(skillSwap).expects('fail').never()
@battle.performMove(@p1, skillSwap)
mock.verify()
describe "Metronome", ->
it "reselects if chosen an illegal move", ->
shared.create.call(this, gen: 'xy')
@p1.moves = [ metronome ]
metronome = @battle.getMove("Metronome")
belch = @battle.getMove("Belch")
tackle = @battle.getMove("Tackle")
index = @battle.MoveList.indexOf(belch)
reselectIndex = @battle.MoveList.indexOf(tackle)
shared.biasRNG.call(this, 'randInt', "metronome", index)
shared.biasRNG.call(this, 'randInt', "metronome reselect", reselectIndex)
mock = @sandbox.mock(tackle).expects('execute').once()
@battle.performMove(@p1, metronome)
mock.verify()
testDelayedAttackMove = (moveName, type) ->
describe moveName, ->
it "does not hit substitutes if the user has Infiltrator and is active", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", ability: "Infiltrator")]
move = @battle.getMove(moveName)
@battle.performMove(@p1, move)
@p2.attach(Attachment.Substitute, hp: 1)
@battle.endTurn()
@battle.endTurn()
@p2.has(Attachment.Substitute).should.be.true
@battle.endTurn()
@p2.has(Attachment.Substitute).should.be.true
it "always hits substitutes if the user is not on the field", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", ability: "Infiltrator"), Factory("Magikarp")]
move = @battle.getMove(moveName)
@battle.performMove(@p1, move)
@p2.attach(Attachment.Substitute, hp: 1)
@battle.endTurn()
@battle.performSwitch(@p1, 1)
@battle.endTurn()
@p2.has(Attachment.Substitute).should.be.true
@battle.endTurn()
@p2.has(Attachment.Substitute).should.be.false
testDelayedAttackMove("Future Sight")
testDelayedAttackMove("Doom Desire")
| 207344 | {Attachment, Status} = require('../../server/xy/attachment')
{Battle} = require('../../server/xy/battle')
{Pokemon} = require('../../server/xy/pokemon')
{Weather} = require('../../shared/weather')
{Move} = require('../../server/xy/move')
util = require '../../server/xy/util'
{Protocol} = require '../../shared/protocol'
{Factory} = require '../factory'
should = require 'should'
{_} = require 'underscore'
shared = require '../shared'
require '../helpers'
describe "XY Moves:", ->
# Test every single move for their primary effects.
shared.testEveryMove(Battle::MoveList, 'xy')
describe "a critical hit", ->
it "multiplies damage by 1.5x", ->
Move::criticalMultiplier.should.equal(1.5)
it "becomes a 50% chance at a +3 CH level", ->
Move::determineCriticalHitFromLevel(3, .49).should.be.true
Move::determineCriticalHitFromLevel(3, .5).should.be.false
it "becomes a 100% chance at a +4 CH level", ->
Move::determineCriticalHitFromLevel(4, .99).should.be.true
Move::determineCriticalHitFromLevel(4, 1.0).should.be.false
describe "a powder move", ->
it "does not affect Grass-types", ->
shared.create.call(this, gen: 'xy')
powderMove = @battle.findMove((m) -> m.hasFlag("powder"))
@p2.types.push("Grass")
mock1 = @sandbox.mock(powderMove).expects('hit').never()
mock2 = @sandbox.mock(powderMove).expects('fail').once()
@battle.performMove(@p1, powderMove)
mock1.verify()
mock2.verify()
it "affects non-Grass-types", ->
shared.create.call(this, gen: 'xy')
powderMove = @battle.findMove((m) -> m.hasFlag("powder"))
@p2.types = [ "Normal" ]
mock1 = @sandbox.mock(powderMove).expects('hit').once()
mock2 = @sandbox.mock(powderMove).expects('fail').never()
@battle.performMove(@p1, powderMove)
mock1.verify()
mock2.verify()
describe "Dragon Pulse", ->
it "has 85 base power now", ->
shared.create.call(this, gen: 'xy')
@battle.getMove('Dragon Pulse').power.should.equal(85)
describe 'Hidden Power', ->
it "always has 60 base power", ->
shared.create.call(this, gen: 'xy')
hiddenPower = @battle.getMove('Hidden Power')
hiddenPower.power.should.equal(60)
hiddenPower.basePower(@battle, @p1, @p2).should.equal(60)
describe "Facade", ->
it "does not cut attack in half when burned", ->
shared.create.call(this, gen: 'xy')
facade = @battle.getMove('Facade')
facade.burnCalculation(@p1).should.equal(1)
@p1.attach(Status.Burn)
facade.burnCalculation(@p1).should.equal(1)
describe "King's Shield", ->
it "protects against attacks", ->
shared.create.call(this, gen: 'xy')
kingsShield = @battle.getMove("King's Shield")
tackle = @battle.getMove("Tackle")
mock = @sandbox.mock(tackle).expects('hit').never()
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
@battle.performMove(@p1, kingsShield)
@battle.performMove(@p2, tackle)
mock.verify()
it "does not protect against non-damaging moves", ->
shared.create.call(this, gen: 'xy')
kingsShield = @battle.getMove("King's Shield")
willOWisp = @battle.getMove("Will-O-Wisp")
mock = @sandbox.mock(willOWisp).expects('hit').once()
@battle.recordMove(@id2, willOWisp)
@battle.determineTurnOrder()
@battle.performMove(@p1, kingsShield)
@battle.performMove(@p2, willOWisp)
mock.verify()
it "does not protect against attacks it is immune to", ->
shared.create.call(this, gen: 'xy')
@p1.types = [ 'Ghost' ]
kingsShield = @battle.getMove("King's Shield")
tackle = @battle.getMove("Tackle")
mock = @sandbox.mock(tackle).expects('hit').never()
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
@battle.performMove(@p1, kingsShield)
@battle.performMove(@p2, tackle)
mock.verify()
@p2.stages.should.containEql(attack: 0)
it "sharply lowers attacker's Attack if move was a contact move", ->
shared.create.call(this, gen: 'xy')
kingsShield = @battle.getMove("King's Shield")
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
@battle.performMove(@p1, kingsShield)
@p2.stages.attack.should.equal(0)
@battle.performMove(@p2, tackle)
@p2.stages.attack.should.equal(-2)
it "does not lower attacker's Attack if move was not a contact move", ->
shared.create.call(this, gen: 'xy')
kingsShield = @battle.getMove("King's Shield")
ember = @battle.getMove("Ember")
@battle.recordMove(@id2, ember)
@battle.determineTurnOrder()
@battle.performMove(@p1, kingsShield)
@p2.stages.attack.should.equal(0)
@battle.performMove(@p2, ember)
@p2.stages.attack.should.equal(0)
describe "Spiky Shield", ->
it "protects against attacks", ->
shared.create.call(this, gen: 'xy')
spikyShield = @battle.getMove("Spiky Shield")
tackle = @battle.getMove("Tackle")
mock = @sandbox.mock(tackle).expects('hit').never()
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
@battle.performMove(@p1, spikyShield)
@battle.performMove(@p2, tackle)
mock.verify()
it "protects against non-damaging moves", ->
shared.create.call(this, gen: 'xy')
spikyShield = @battle.getMove("Spiky Shield")
willOWisp = @battle.getMove("Will-O-Wisp")
mock = @sandbox.mock(willOWisp).expects('hit').never()
@battle.recordMove(@id2, willOWisp)
@battle.determineTurnOrder()
@battle.performMove(@p1, spikyShield)
@battle.performMove(@p2, willOWisp)
mock.verify()
it "does not protect against attacks it is immune to", ->
shared.create.call(this, gen: 'xy')
@p1.types = [ 'Ghost' ]
spikyShield = @battle.getMove("Spiky Shield")
tackle = @battle.getMove("Tackle")
mock = @sandbox.mock(tackle).expects('hit').never()
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
@battle.performMove(@p1, spikyShield)
@battle.performMove(@p2, tackle)
mock.verify()
@p2.stages.should.containEql(attack: 0)
it "damages attacker by 1/8 if move was a contact move", ->
shared.create.call(this, gen: 'xy')
spikyShield = @battle.getMove("Spiky Shield")
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
@battle.performMove(@p1, spikyShield)
@p2.currentHP.should.not.be.lessThan(@p2.stat('hp'))
@battle.performMove(@p2, tackle)
(@p2.stat('hp') - @p2.currentHP).should.equal(@p2.stat('hp') >> 3)
it "does not damage attacker if move was not a contact move", ->
shared.create.call(this, gen: 'xy')
spikyShield = @battle.getMove("Spiky Shield")
ember = @battle.getMove("Ember")
@battle.recordMove(@id2, ember)
@battle.determineTurnOrder()
@battle.performMove(@p1, spikyShield)
@p2.currentHP.should.not.be.lessThan(@p2.stat('hp'))
@battle.performMove(@p2, ember)
@p2.currentHP.should.not.be.lessThan(@p2.stat('hp'))
describe "Sticky Web", ->
shared.shouldFailIfUsedTwice("Sticky Web", gen: 'xy')
it "lowers a pokemon's speed by 1 when switching in", ->
shared.create.call(this, gen: 'xy', team2: (Factory("Magikarp") for x in [0..1]))
stickyWeb = @battle.getMove("Sticky Web")
@battle.performMove(@p1, stickyWeb)
@battle.performSwitch(@p2, 1)
@team2.first().stages.should.containEql(speed: -1)
it "doesn't lower a pokemon's speed by 1 if immune to ground", ->
shared.create.call(this, gen: 'xy', team2: [ Factory("Magikarp"), Factory("Gyarados") ])
stickyWeb = @battle.getMove("Sticky Web")
@battle.performMove(@p1, stickyWeb)
@battle.performSwitch(@p2, 1)
@team2.first().stages.should.containEql(speed: 0)
describe "Rapid Spin", ->
it "removes Sticky Web", ->
shared.create.call(this, gen: 'xy')
stickyWeb = @battle.getMove("Sticky Web")
rapidSpin = @battle.getMove("Rapid Spin")
@battle.performMove(@p1, stickyWeb)
@team2.has(Attachment.StickyWeb).should.be.true
@battle.performMove(@p2, rapidSpin)
@team2.has(Attachment.StickyWeb).should.be.false
describe "Defog", ->
it "removes Sticky Web as well", ->
shared.create.call(this, gen: 'xy')
defog = @battle.getMove("Defog")
@battle.performMove(@p1, @battle.getMove("Sticky Web"))
@p2.team.has(Attachment.StickyWeb).should.be.true
@battle.performMove(@p1, defog)
@p2.team.has(Attachment.StickyWeb).should.be.false
it "removes hazards from both sides of the field now", ->
shared.create.call(this, gen: 'xy')
defog = @battle.getMove("Defog")
@battle.performMove(@p1, @battle.getMove("Sticky Web"))
@battle.performMove(@p2, @battle.getMove("Sticky Web"))
@p1.team.has(Attachment.StickyWeb).should.be.true
@p2.team.has(Attachment.StickyWeb).should.be.true
@battle.performMove(@p1, defog)
@p1.team.has(Attachment.StickyWeb).should.be.false
@p2.team.has(Attachment.StickyWeb).should.be.false
it "removes screens from only the target's side of the field", ->
shared.create.call(this, gen: 'xy')
defog = @battle.getMove("Defog")
@battle.performMove(@p1, @battle.getMove("Reflect"))
@battle.performMove(@p1, @battle.getMove("Light Screen"))
@battle.performMove(@p2, @battle.getMove("Reflect"))
@battle.performMove(@p2, @battle.getMove("Light Screen"))
@p1.team.has(Attachment.Reflect).should.be.true
@p1.team.has(Attachment.LightScreen).should.be.true
@p2.team.has(Attachment.Reflect).should.be.true
@p2.team.has(Attachment.LightScreen).should.be.true
@battle.performMove(@p1, defog)
@p1.team.has(Attachment.Reflect).should.be.true
@p1.team.has(Attachment.LightScreen).should.be.true
@p2.team.has(Attachment.Reflect).should.be.false
@p2.team.has(Attachment.LightScreen).should.be.false
describe "Knock Off", ->
it "has x1.0 power if the pokemon has no item", ->
shared.create.call(this, gen: 'xy')
knockOff = @battle.getMove("Knock Off")
knockOff.basePower(@battle, @p1, @p2).should.equal(knockOff.power)
it "has x1.5 power if the item can be knocked off", ->
shared.create.call this,
gen: 'xy'
team2: [Factory("Magikarp", item: "Leftovers")]
knockOff = @battle.getMove("Knock Off")
basePower = knockOff.basePower(@battle, @p1, @p2)
basePower.should.equal Math.floor(1.5 * knockOff.power)
it "has x1.0 power if the item cannot be knocked off", ->
shared.create.call this,
gen: 'xy'
team2: [Factory("Magikarp", item: "Air Mail")]
knockOff = @battle.getMove("Knock Off")
knockOff.basePower(@battle, @p1, @p2).should.equal(knockOff.power)
it "has x1.5 power if item can be knocked off but owner has Sticky Hold", ->
shared.create.call this,
gen: 'xy'
team2: [Factory("Magikarp", item: "Leftovers", ability: "Sticky Hold")]
knockOff = @battle.getMove("Knock Off")
basePower = knockOff.basePower(@battle, @p1, @p2)
basePower.should.equal Math.floor(1.5 * knockOff.power)
describe "Protect-like moves", ->
it "determines success chance using a power of 3 instead of 2", ->
shared.create.call(this, gen: 'xy')
for x in [0..7]
attachment = @p1.attach(Attachment.ProtectCounter)
attachment.successChance().should.equal Math.pow(3, x)
attachment = @p1.attach(Attachment.ProtectCounter)
attachment.successChance().should.equal Math.pow(2, 32)
describe "Freeze-Dry", ->
it "is 2x effective against Water-types", ->
shared.create.call(this, gen: 'xy')
@p2.types = [ "Water" ]
freezeDry = @battle.getMove('Freeze-Dry')
spy = @sandbox.spy(freezeDry, 'typeEffectiveness')
@battle.performMove(@p1, freezeDry)
spy.returned(2).should.be.true
it "is 2x effective against Water-types with Normalize", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", ability: "Normalize")]
@p2.types = [ "Water" ]
freezeDry = @battle.getMove('Freeze-Dry')
spy = @sandbox.spy(freezeDry, 'typeEffectiveness')
@battle.performMove(@p1, freezeDry)
spy.returned(2).should.be.true
it "is normally effective against other types", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp")]
@p2.types = [ "Fire" ]
freezeDry = @battle.getMove('Freeze-Dry')
spy = @sandbox.spy(freezeDry, 'typeEffectiveness')
@battle.performMove(@p1, freezeDry)
spy.returned(.5).should.be.true
describe "Substitute", ->
it "is bypassed by voice moves", ->
shared.create.call(this, gen: 'xy')
@p2.attach(Attachment.Substitute, hp: (@p1.currentHP >> 2))
voiceMove = @battle.findMove (m) ->
!m.isNonDamaging() && m.hasFlag("sound")
spy = @sandbox.spy(voiceMove, 'hit')
@battle.performMove(@p1, voiceMove)
spy.calledOnce.should.be.true
@p2.currentHP.should.be.lessThan(@p2.stat('hp'))
it "is bypassed by Infiltrator", ->
shared.create.call this,
gen: 'xy'
team1: [ Factory("Magikarp", ability: "Infiltrator")]
@p2.attach(Attachment.Substitute, hp: (@p1.currentHP >> 2))
tackle = @battle.getMove("Tackle")
spy = @sandbox.spy(tackle, 'hit')
@battle.performMove(@p1, tackle)
spy.calledOnce.should.be.true
@p2.currentHP.should.be.lessThan(@p2.stat('hp'))
it "is bypassed by Infiltrator even on status moves", ->
shared.create.call this,
gen: 'xy'
team1: [ Factory("Magikarp", ability: "Infiltrator")]
@p2.attach(Attachment.Substitute, hp: (@p1.currentHP >> 2))
toxic = @battle.getMove("Toxic")
spy = @sandbox.spy(toxic, 'hit')
@battle.performMove(@p1, toxic)
spy.calledOnce.should.be.true
@p2.has(Status.Toxic).should.be.true
it "does not block Knock Off + Infiltrator", ->
shared.create.call this,
gen: 'xy'
team1: [ Factory("Magikarp", ability: "Infiltrator")]
team2: [ Factory("Magikarp", item: "Leftovers")]
@p2.attach(Attachment.Substitute, hp: (@p1.currentHP >> 2))
knockOff = @battle.getMove("Knock Off")
spy = @sandbox.spy(knockOff, 'hit')
@battle.performMove(@p1, knockOff)
spy.calledOnce.should.be.true
@p2.hasItem().should.be.false
it "does not block secondary effects + Infiltrator", ->
shared.create.call this,
gen: 'xy'
team1: [ Factory("Magikarp", ability: "Infiltrator")]
shared.biasRNG.call(this, "next", "secondary effect", 0) # always burn
@p2.attach(Attachment.Substitute, hp: (@p1.currentHP >> 2))
flamethrower = @battle.getMove('Flamethrower')
spy = @sandbox.spy(flamethrower, 'hit')
@battle.performMove(@p1, flamethrower)
spy.calledOnce.should.be.true
@p2.has(Status.Burn).should.be.true
testChargeMove = (moveName, vulnerable) ->
describe moveName, ->
it "chooses the player's next action for them", ->
shared.create.call(this, gen: 'xy')
move = @battle.getMove(moveName)
@p1.moves = [ move ]
@battle.recordMove(@id1, move)
@battle.continueTurn()
@battle.endTurn()
@battle.beginTurn()
@battle.requests.should.not.have.property(@id1)
should.exist(@battle.getAction(@p1))
it "only spends 1 PP for the entire attack", ->
shared.create.call(this, gen: 'xy')
move = @battle.getMove(moveName)
@p1.moves = [ move ]
@p1.resetAllPP()
pp = @p1.pp(move)
@battle.recordMove(@id1, move)
@battle.continueTurn()
@p1.pp(move).should.equal(pp)
@battle.beginTurn()
@battle.continueTurn()
@p1.pp(move).should.equal(pp - 1)
it "skips the charge turn if the user is holding a Power Herb", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", item: "Power Herb")]
move = @battle.getMove(moveName)
@p1.hasItem("Power Herb").should.be.true
mock = @sandbox.mock(move).expects('execute').once()
@battle.recordMove(@id1, move)
@battle.continueTurn()
mock.verify()
@p1.hasItem().should.be.false
if vulnerable?.length?
it "makes target invulnerable to moves", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", evs: {speed: 4})]
move = @battle.getMove(moveName)
swift = @battle.getMove("Swift")
@battle.recordMove(@id1, move)
@battle.recordMove(@id2, swift)
mock = @sandbox.mock(swift).expects('hit').never()
@battle.continueTurn()
mock.verify()
it "makes target invulnerable to moves *after* use", ->
shared.create.call this,
gen: 'xy'
team2: [Factory("Magikarp", evs: {speed: 4})]
move = @battle.getMove(moveName)
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id1, move)
@battle.recordMove(@id2, tackle)
mock = @sandbox.mock(tackle).expects('hit').once()
@battle.continueTurn()
mock.verify()
it "is vulnerable to attacks from a No Guard pokemon", ->
shared.create.call this,
gen: 'xy'
team2: [Factory("<NAME>", ability: "No Guard")]
move = @battle.getMove(moveName)
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id1, move)
@battle.recordMove(@id2, tackle)
mock = @sandbox.mock(tackle).expects('hit').once()
@battle.continueTurn()
mock.verify()
it "is vulnerable to attacks if locked on", ->
shared.create.call(this, gen: 'xy')
@battle.performMove(@p1, @battle.getMove("Lock-On"))
@battle.performMove(@p2, @battle.getMove(moveName))
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id1, tackle)
mock = @sandbox.mock(tackle).expects('hit').once()
@battle.continueTurn()
mock.verify()
for vulnerableMove in vulnerable
it "is vulnerable to #{vulnerableMove}", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("<NAME>", evs: {speed: 4})]
move = @battle.getMove(moveName)
vulnerable = @battle.getMove(vulnerableMove)
@battle.recordMove(@id1, move)
@battle.recordMove(@id2, vulnerable)
mock = @sandbox.mock(vulnerable).expects('hit').once()
@battle.continueTurn()
mock.verify()
else # no vulnerable moves
it "doesn't make target invulnerable to moves", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("<NAME>", evs: {speed: 4})]
move = @battle.getMove(moveName)
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id1, move)
@battle.recordMove(@id2, tackle)
mock = @sandbox.mock(tackle).expects('hit').once()
@battle.continueTurn()
mock.verify()
testChargeMove('Fly', ["Gust", "Thunder", "Twister", "Sky Uppercut", "Hurricane", "Smack Down", "Thousand Arrows"])
testChargeMove('Bounce', ["Gust", "Thunder", "Twister", "Sky Uppercut", "Hurricane", "Smack Down", "Thousand Arrows"])
testChargeMove('Geomancy')
testChargeMove('Phantom Force', [])
describe "Toxic", ->
it "cannot miss when used by a Poison type pokemon", ->
shared.create.call(this, gen: 'xy')
@p1.types = [ "Poison" ]
@p2.types = [ "Normal" ]
shared.biasRNG.call(this, "randInt", 'miss', 101)
toxic = @battle.getMove("Toxic")
toxic.willMiss(@battle, @p1, @p2).should.be.false
describe "Parting Shot", ->
it "reduces the attack and special attack of the target by two stages", ->
shared.create.call(this, gen: 'xy')
@battle.performMove(@p1, @battle.getMove("Parting Shot"))
@p2.stages.should.containEql attack: -1, specialAttack: -1
it "forces the owner to switch", ->
shared.create.call(this, gen: 'xy')
@battle.performMove(@p1, @battle.getMove("Parting Shot"))
@battle.requests.should.have.property @id1
describe "Worry Seed", ->
it "does not change some abilities", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Smeargle")]
team2: [Factory("Aegislash", ability: "Stance Change")]
worrySeed = @battle.getMove("Worry Seed")
mock = @sandbox.mock(worrySeed).expects('fail').once()
@battle.performMove(@p1, worrySeed)
mock.verify()
describe "Simple Beam", ->
it "does not change some abilities", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Smeargle")]
team2: [Factory("Aegislash", ability: "Stance Change")]
simpleBeam = @battle.getMove("Simple Beam")
mock = @sandbox.mock(simpleBeam).expects('fail').once()
@battle.performMove(@p1, simpleBeam)
mock.verify()
testTrappingMove = (name) ->
describe name, ->
it "deals 1/8 of the pokemon's max hp every turn", ->
shared.create.call this,
gen: 'xy'
team2: [Factory("Blissey")]
@battle.performMove(@p1, @battle.getMove(name))
@p2.currentHP = @p2.stat('hp')
@battle.endTurn()
maxHP = @p2.stat('hp')
expected = maxHP - Math.floor(maxHP / 8)
@p2.currentHP.should.equal expected
it "deals 1/6 of the pokemon's max hp every turn if the user is holding a Binding Band", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", item: "Binding Band")]
team2: [Factory("Blissey")]
@battle.performMove(@p1, @battle.getMove(name))
@p2.currentHP = @p2.stat('hp')
@battle.endTurn()
maxHP = @p2.stat('hp')
expected = maxHP - Math.floor(maxHP / 6)
@p2.currentHP.should.equal expected
testTrappingMove "Bind"
testTrappingMove "Clamp"
testTrappingMove "Fire Spin"
testTrappingMove "Infestation"
testTrappingMove "Magma Storm"
testTrappingMove "Sand Tomb"
testTrappingMove "Wrap"
describe "Entrainment", ->
it "does not change some abilities", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", ability: "Swift Swim")]
team2: [Factory("Aegislash", ability: "Stance Change")]
entrainment = @battle.getMove("Entrainment")
mock = @sandbox.mock(entrainment).expects('fail').once()
@battle.performMove(@p1, entrainment)
mock.verify()
describe "Nature Power", ->
it "uses Tri Attack in Wi-Fi battles", ->
shared.create.call(this, gen: 'xy')
naturePower = @battle.getMove('Nature Power')
triAttack = @battle.getMove('Tri Attack')
mock = @sandbox.mock(triAttack).expects('execute').once()
.withArgs(@battle, @p1, [ @p2 ])
@battle.performMove(@p1, naturePower)
mock.verify()
describe "Venom Drench", ->
it "lowers the target's attack, special attack, and speed by 1 stage if it is poisoned", ->
shared.create.call(this, gen: 'xy')
@p2.attach(Status.Poison)
@battle.performMove(@p1, @battle.getMove('Venom Drench'))
@p2.stages.should.containEql attack: -1, specialAttack: -1, speed: -1
it "fails if the target isn't poisoned", ->
shared.create.call(this, gen: 'xy')
venomDrench = @battle.getMove("Venom Drench")
mock = @sandbox.mock(venomDrench).expects('fail').once()
@battle.performMove(@p1, venomDrench)
mock.verify()
describe "Topsy-Turvy", ->
it "reverses the target's boosts", ->
shared.create.call(this, gen: 'xy')
@p2.stages.attack = 2
@p2.stages.defense = -3
@p2.stages.speed = 0
@battle.performMove(@p1, @battle.getMove('Topsy-Turvy'))
@p2.stages.should.containEql attack: -2
@p2.stages.should.containEql defense: 3
@p2.stages.should.containEql speed: 0
it "fails if the target has no boosts", ->
shared.create.call(this, gen: 'xy')
topsyTurvy = @battle.getMove('Topsy-Turvy')
mock = @sandbox.mock(topsyTurvy).expects('fail').once()
@battle.performMove(@p1, topsyTurvy)
mock.verify()
describe "Fell Stinger", ->
it "raises the user's Attack 2 stages if the target faints", ->
shared.create.call(this, gen: 'xy')
@p2.currentHP = 1
@battle.performMove(@p1, @battle.getMove("Fell Stinger"))
@p1.stages.should.containEql attack: 2
it "does not raise the user's Attack 2 stages otherwise", ->
shared.create.call(this, gen: 'xy')
@battle.performMove(@p1, @battle.getMove("Fell Stinger"))
@p1.stages.should.containEql attack: 0
describe "Skill Swap", ->
it "can swap the abilities if they are the same", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", ability: "Swift Swim")]
team2: [Factory("Magikarp", ability: "Swift Swim")]
skillSwap = @battle.getMove("Skill Swap")
mock = @sandbox.mock(skillSwap).expects('fail').never()
@battle.performMove(@p1, skillSwap)
mock.verify()
describe "Metronome", ->
it "reselects if chosen an illegal move", ->
shared.create.call(this, gen: 'xy')
@p1.moves = [ metronome ]
metronome = @battle.getMove("Metronome")
belch = @battle.getMove("Belch")
tackle = @battle.getMove("Tackle")
index = @battle.MoveList.indexOf(belch)
reselectIndex = @battle.MoveList.indexOf(tackle)
shared.biasRNG.call(this, 'randInt', "metronome", index)
shared.biasRNG.call(this, 'randInt', "metronome reselect", reselectIndex)
mock = @sandbox.mock(tackle).expects('execute').once()
@battle.performMove(@p1, metronome)
mock.verify()
testDelayedAttackMove = (moveName, type) ->
describe moveName, ->
it "does not hit substitutes if the user has Infiltrator and is active", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", ability: "Infiltrator")]
move = @battle.getMove(moveName)
@battle.performMove(@p1, move)
@p2.attach(Attachment.Substitute, hp: 1)
@battle.endTurn()
@battle.endTurn()
@p2.has(Attachment.Substitute).should.be.true
@battle.endTurn()
@p2.has(Attachment.Substitute).should.be.true
it "always hits substitutes if the user is not on the field", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", ability: "Infiltrator"), Factory("Magikarp")]
move = @battle.getMove(moveName)
@battle.performMove(@p1, move)
@p2.attach(Attachment.Substitute, hp: 1)
@battle.endTurn()
@battle.performSwitch(@p1, 1)
@battle.endTurn()
@p2.has(Attachment.Substitute).should.be.true
@battle.endTurn()
@p2.has(Attachment.Substitute).should.be.false
testDelayedAttackMove("Future Sight")
testDelayedAttackMove("Doom Desire")
| true | {Attachment, Status} = require('../../server/xy/attachment')
{Battle} = require('../../server/xy/battle')
{Pokemon} = require('../../server/xy/pokemon')
{Weather} = require('../../shared/weather')
{Move} = require('../../server/xy/move')
util = require '../../server/xy/util'
{Protocol} = require '../../shared/protocol'
{Factory} = require '../factory'
should = require 'should'
{_} = require 'underscore'
shared = require '../shared'
require '../helpers'
describe "XY Moves:", ->
# Test every single move for their primary effects.
shared.testEveryMove(Battle::MoveList, 'xy')
describe "a critical hit", ->
it "multiplies damage by 1.5x", ->
Move::criticalMultiplier.should.equal(1.5)
it "becomes a 50% chance at a +3 CH level", ->
Move::determineCriticalHitFromLevel(3, .49).should.be.true
Move::determineCriticalHitFromLevel(3, .5).should.be.false
it "becomes a 100% chance at a +4 CH level", ->
Move::determineCriticalHitFromLevel(4, .99).should.be.true
Move::determineCriticalHitFromLevel(4, 1.0).should.be.false
describe "a powder move", ->
it "does not affect Grass-types", ->
shared.create.call(this, gen: 'xy')
powderMove = @battle.findMove((m) -> m.hasFlag("powder"))
@p2.types.push("Grass")
mock1 = @sandbox.mock(powderMove).expects('hit').never()
mock2 = @sandbox.mock(powderMove).expects('fail').once()
@battle.performMove(@p1, powderMove)
mock1.verify()
mock2.verify()
it "affects non-Grass-types", ->
shared.create.call(this, gen: 'xy')
powderMove = @battle.findMove((m) -> m.hasFlag("powder"))
@p2.types = [ "Normal" ]
mock1 = @sandbox.mock(powderMove).expects('hit').once()
mock2 = @sandbox.mock(powderMove).expects('fail').never()
@battle.performMove(@p1, powderMove)
mock1.verify()
mock2.verify()
describe "Dragon Pulse", ->
it "has 85 base power now", ->
shared.create.call(this, gen: 'xy')
@battle.getMove('Dragon Pulse').power.should.equal(85)
describe 'Hidden Power', ->
it "always has 60 base power", ->
shared.create.call(this, gen: 'xy')
hiddenPower = @battle.getMove('Hidden Power')
hiddenPower.power.should.equal(60)
hiddenPower.basePower(@battle, @p1, @p2).should.equal(60)
describe "Facade", ->
it "does not cut attack in half when burned", ->
shared.create.call(this, gen: 'xy')
facade = @battle.getMove('Facade')
facade.burnCalculation(@p1).should.equal(1)
@p1.attach(Status.Burn)
facade.burnCalculation(@p1).should.equal(1)
describe "King's Shield", ->
it "protects against attacks", ->
shared.create.call(this, gen: 'xy')
kingsShield = @battle.getMove("King's Shield")
tackle = @battle.getMove("Tackle")
mock = @sandbox.mock(tackle).expects('hit').never()
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
@battle.performMove(@p1, kingsShield)
@battle.performMove(@p2, tackle)
mock.verify()
it "does not protect against non-damaging moves", ->
shared.create.call(this, gen: 'xy')
kingsShield = @battle.getMove("King's Shield")
willOWisp = @battle.getMove("Will-O-Wisp")
mock = @sandbox.mock(willOWisp).expects('hit').once()
@battle.recordMove(@id2, willOWisp)
@battle.determineTurnOrder()
@battle.performMove(@p1, kingsShield)
@battle.performMove(@p2, willOWisp)
mock.verify()
it "does not protect against attacks it is immune to", ->
shared.create.call(this, gen: 'xy')
@p1.types = [ 'Ghost' ]
kingsShield = @battle.getMove("King's Shield")
tackle = @battle.getMove("Tackle")
mock = @sandbox.mock(tackle).expects('hit').never()
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
@battle.performMove(@p1, kingsShield)
@battle.performMove(@p2, tackle)
mock.verify()
@p2.stages.should.containEql(attack: 0)
it "sharply lowers attacker's Attack if move was a contact move", ->
shared.create.call(this, gen: 'xy')
kingsShield = @battle.getMove("King's Shield")
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
@battle.performMove(@p1, kingsShield)
@p2.stages.attack.should.equal(0)
@battle.performMove(@p2, tackle)
@p2.stages.attack.should.equal(-2)
it "does not lower attacker's Attack if move was not a contact move", ->
shared.create.call(this, gen: 'xy')
kingsShield = @battle.getMove("King's Shield")
ember = @battle.getMove("Ember")
@battle.recordMove(@id2, ember)
@battle.determineTurnOrder()
@battle.performMove(@p1, kingsShield)
@p2.stages.attack.should.equal(0)
@battle.performMove(@p2, ember)
@p2.stages.attack.should.equal(0)
describe "Spiky Shield", ->
it "protects against attacks", ->
shared.create.call(this, gen: 'xy')
spikyShield = @battle.getMove("Spiky Shield")
tackle = @battle.getMove("Tackle")
mock = @sandbox.mock(tackle).expects('hit').never()
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
@battle.performMove(@p1, spikyShield)
@battle.performMove(@p2, tackle)
mock.verify()
it "protects against non-damaging moves", ->
shared.create.call(this, gen: 'xy')
spikyShield = @battle.getMove("Spiky Shield")
willOWisp = @battle.getMove("Will-O-Wisp")
mock = @sandbox.mock(willOWisp).expects('hit').never()
@battle.recordMove(@id2, willOWisp)
@battle.determineTurnOrder()
@battle.performMove(@p1, spikyShield)
@battle.performMove(@p2, willOWisp)
mock.verify()
it "does not protect against attacks it is immune to", ->
shared.create.call(this, gen: 'xy')
@p1.types = [ 'Ghost' ]
spikyShield = @battle.getMove("Spiky Shield")
tackle = @battle.getMove("Tackle")
mock = @sandbox.mock(tackle).expects('hit').never()
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
@battle.performMove(@p1, spikyShield)
@battle.performMove(@p2, tackle)
mock.verify()
@p2.stages.should.containEql(attack: 0)
it "damages attacker by 1/8 if move was a contact move", ->
shared.create.call(this, gen: 'xy')
spikyShield = @battle.getMove("Spiky Shield")
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id2, tackle)
@battle.determineTurnOrder()
@battle.performMove(@p1, spikyShield)
@p2.currentHP.should.not.be.lessThan(@p2.stat('hp'))
@battle.performMove(@p2, tackle)
(@p2.stat('hp') - @p2.currentHP).should.equal(@p2.stat('hp') >> 3)
it "does not damage attacker if move was not a contact move", ->
shared.create.call(this, gen: 'xy')
spikyShield = @battle.getMove("Spiky Shield")
ember = @battle.getMove("Ember")
@battle.recordMove(@id2, ember)
@battle.determineTurnOrder()
@battle.performMove(@p1, spikyShield)
@p2.currentHP.should.not.be.lessThan(@p2.stat('hp'))
@battle.performMove(@p2, ember)
@p2.currentHP.should.not.be.lessThan(@p2.stat('hp'))
describe "Sticky Web", ->
shared.shouldFailIfUsedTwice("Sticky Web", gen: 'xy')
it "lowers a pokemon's speed by 1 when switching in", ->
shared.create.call(this, gen: 'xy', team2: (Factory("Magikarp") for x in [0..1]))
stickyWeb = @battle.getMove("Sticky Web")
@battle.performMove(@p1, stickyWeb)
@battle.performSwitch(@p2, 1)
@team2.first().stages.should.containEql(speed: -1)
it "doesn't lower a pokemon's speed by 1 if immune to ground", ->
shared.create.call(this, gen: 'xy', team2: [ Factory("Magikarp"), Factory("Gyarados") ])
stickyWeb = @battle.getMove("Sticky Web")
@battle.performMove(@p1, stickyWeb)
@battle.performSwitch(@p2, 1)
@team2.first().stages.should.containEql(speed: 0)
describe "Rapid Spin", ->
it "removes Sticky Web", ->
shared.create.call(this, gen: 'xy')
stickyWeb = @battle.getMove("Sticky Web")
rapidSpin = @battle.getMove("Rapid Spin")
@battle.performMove(@p1, stickyWeb)
@team2.has(Attachment.StickyWeb).should.be.true
@battle.performMove(@p2, rapidSpin)
@team2.has(Attachment.StickyWeb).should.be.false
describe "Defog", ->
it "removes Sticky Web as well", ->
shared.create.call(this, gen: 'xy')
defog = @battle.getMove("Defog")
@battle.performMove(@p1, @battle.getMove("Sticky Web"))
@p2.team.has(Attachment.StickyWeb).should.be.true
@battle.performMove(@p1, defog)
@p2.team.has(Attachment.StickyWeb).should.be.false
it "removes hazards from both sides of the field now", ->
shared.create.call(this, gen: 'xy')
defog = @battle.getMove("Defog")
@battle.performMove(@p1, @battle.getMove("Sticky Web"))
@battle.performMove(@p2, @battle.getMove("Sticky Web"))
@p1.team.has(Attachment.StickyWeb).should.be.true
@p2.team.has(Attachment.StickyWeb).should.be.true
@battle.performMove(@p1, defog)
@p1.team.has(Attachment.StickyWeb).should.be.false
@p2.team.has(Attachment.StickyWeb).should.be.false
it "removes screens from only the target's side of the field", ->
shared.create.call(this, gen: 'xy')
defog = @battle.getMove("Defog")
@battle.performMove(@p1, @battle.getMove("Reflect"))
@battle.performMove(@p1, @battle.getMove("Light Screen"))
@battle.performMove(@p2, @battle.getMove("Reflect"))
@battle.performMove(@p2, @battle.getMove("Light Screen"))
@p1.team.has(Attachment.Reflect).should.be.true
@p1.team.has(Attachment.LightScreen).should.be.true
@p2.team.has(Attachment.Reflect).should.be.true
@p2.team.has(Attachment.LightScreen).should.be.true
@battle.performMove(@p1, defog)
@p1.team.has(Attachment.Reflect).should.be.true
@p1.team.has(Attachment.LightScreen).should.be.true
@p2.team.has(Attachment.Reflect).should.be.false
@p2.team.has(Attachment.LightScreen).should.be.false
describe "Knock Off", ->
it "has x1.0 power if the pokemon has no item", ->
shared.create.call(this, gen: 'xy')
knockOff = @battle.getMove("Knock Off")
knockOff.basePower(@battle, @p1, @p2).should.equal(knockOff.power)
it "has x1.5 power if the item can be knocked off", ->
shared.create.call this,
gen: 'xy'
team2: [Factory("Magikarp", item: "Leftovers")]
knockOff = @battle.getMove("Knock Off")
basePower = knockOff.basePower(@battle, @p1, @p2)
basePower.should.equal Math.floor(1.5 * knockOff.power)
it "has x1.0 power if the item cannot be knocked off", ->
shared.create.call this,
gen: 'xy'
team2: [Factory("Magikarp", item: "Air Mail")]
knockOff = @battle.getMove("Knock Off")
knockOff.basePower(@battle, @p1, @p2).should.equal(knockOff.power)
it "has x1.5 power if item can be knocked off but owner has Sticky Hold", ->
shared.create.call this,
gen: 'xy'
team2: [Factory("Magikarp", item: "Leftovers", ability: "Sticky Hold")]
knockOff = @battle.getMove("Knock Off")
basePower = knockOff.basePower(@battle, @p1, @p2)
basePower.should.equal Math.floor(1.5 * knockOff.power)
describe "Protect-like moves", ->
it "determines success chance using a power of 3 instead of 2", ->
shared.create.call(this, gen: 'xy')
for x in [0..7]
attachment = @p1.attach(Attachment.ProtectCounter)
attachment.successChance().should.equal Math.pow(3, x)
attachment = @p1.attach(Attachment.ProtectCounter)
attachment.successChance().should.equal Math.pow(2, 32)
describe "Freeze-Dry", ->
it "is 2x effective against Water-types", ->
shared.create.call(this, gen: 'xy')
@p2.types = [ "Water" ]
freezeDry = @battle.getMove('Freeze-Dry')
spy = @sandbox.spy(freezeDry, 'typeEffectiveness')
@battle.performMove(@p1, freezeDry)
spy.returned(2).should.be.true
it "is 2x effective against Water-types with Normalize", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", ability: "Normalize")]
@p2.types = [ "Water" ]
freezeDry = @battle.getMove('Freeze-Dry')
spy = @sandbox.spy(freezeDry, 'typeEffectiveness')
@battle.performMove(@p1, freezeDry)
spy.returned(2).should.be.true
it "is normally effective against other types", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp")]
@p2.types = [ "Fire" ]
freezeDry = @battle.getMove('Freeze-Dry')
spy = @sandbox.spy(freezeDry, 'typeEffectiveness')
@battle.performMove(@p1, freezeDry)
spy.returned(.5).should.be.true
describe "Substitute", ->
it "is bypassed by voice moves", ->
shared.create.call(this, gen: 'xy')
@p2.attach(Attachment.Substitute, hp: (@p1.currentHP >> 2))
voiceMove = @battle.findMove (m) ->
!m.isNonDamaging() && m.hasFlag("sound")
spy = @sandbox.spy(voiceMove, 'hit')
@battle.performMove(@p1, voiceMove)
spy.calledOnce.should.be.true
@p2.currentHP.should.be.lessThan(@p2.stat('hp'))
it "is bypassed by Infiltrator", ->
shared.create.call this,
gen: 'xy'
team1: [ Factory("Magikarp", ability: "Infiltrator")]
@p2.attach(Attachment.Substitute, hp: (@p1.currentHP >> 2))
tackle = @battle.getMove("Tackle")
spy = @sandbox.spy(tackle, 'hit')
@battle.performMove(@p1, tackle)
spy.calledOnce.should.be.true
@p2.currentHP.should.be.lessThan(@p2.stat('hp'))
it "is bypassed by Infiltrator even on status moves", ->
shared.create.call this,
gen: 'xy'
team1: [ Factory("Magikarp", ability: "Infiltrator")]
@p2.attach(Attachment.Substitute, hp: (@p1.currentHP >> 2))
toxic = @battle.getMove("Toxic")
spy = @sandbox.spy(toxic, 'hit')
@battle.performMove(@p1, toxic)
spy.calledOnce.should.be.true
@p2.has(Status.Toxic).should.be.true
it "does not block Knock Off + Infiltrator", ->
shared.create.call this,
gen: 'xy'
team1: [ Factory("Magikarp", ability: "Infiltrator")]
team2: [ Factory("Magikarp", item: "Leftovers")]
@p2.attach(Attachment.Substitute, hp: (@p1.currentHP >> 2))
knockOff = @battle.getMove("Knock Off")
spy = @sandbox.spy(knockOff, 'hit')
@battle.performMove(@p1, knockOff)
spy.calledOnce.should.be.true
@p2.hasItem().should.be.false
it "does not block secondary effects + Infiltrator", ->
shared.create.call this,
gen: 'xy'
team1: [ Factory("Magikarp", ability: "Infiltrator")]
shared.biasRNG.call(this, "next", "secondary effect", 0) # always burn
@p2.attach(Attachment.Substitute, hp: (@p1.currentHP >> 2))
flamethrower = @battle.getMove('Flamethrower')
spy = @sandbox.spy(flamethrower, 'hit')
@battle.performMove(@p1, flamethrower)
spy.calledOnce.should.be.true
@p2.has(Status.Burn).should.be.true
testChargeMove = (moveName, vulnerable) ->
describe moveName, ->
it "chooses the player's next action for them", ->
shared.create.call(this, gen: 'xy')
move = @battle.getMove(moveName)
@p1.moves = [ move ]
@battle.recordMove(@id1, move)
@battle.continueTurn()
@battle.endTurn()
@battle.beginTurn()
@battle.requests.should.not.have.property(@id1)
should.exist(@battle.getAction(@p1))
it "only spends 1 PP for the entire attack", ->
shared.create.call(this, gen: 'xy')
move = @battle.getMove(moveName)
@p1.moves = [ move ]
@p1.resetAllPP()
pp = @p1.pp(move)
@battle.recordMove(@id1, move)
@battle.continueTurn()
@p1.pp(move).should.equal(pp)
@battle.beginTurn()
@battle.continueTurn()
@p1.pp(move).should.equal(pp - 1)
it "skips the charge turn if the user is holding a Power Herb", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", item: "Power Herb")]
move = @battle.getMove(moveName)
@p1.hasItem("Power Herb").should.be.true
mock = @sandbox.mock(move).expects('execute').once()
@battle.recordMove(@id1, move)
@battle.continueTurn()
mock.verify()
@p1.hasItem().should.be.false
if vulnerable?.length?
it "makes target invulnerable to moves", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", evs: {speed: 4})]
move = @battle.getMove(moveName)
swift = @battle.getMove("Swift")
@battle.recordMove(@id1, move)
@battle.recordMove(@id2, swift)
mock = @sandbox.mock(swift).expects('hit').never()
@battle.continueTurn()
mock.verify()
it "makes target invulnerable to moves *after* use", ->
shared.create.call this,
gen: 'xy'
team2: [Factory("Magikarp", evs: {speed: 4})]
move = @battle.getMove(moveName)
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id1, move)
@battle.recordMove(@id2, tackle)
mock = @sandbox.mock(tackle).expects('hit').once()
@battle.continueTurn()
mock.verify()
it "is vulnerable to attacks from a No Guard pokemon", ->
shared.create.call this,
gen: 'xy'
team2: [Factory("PI:NAME:<NAME>END_PI", ability: "No Guard")]
move = @battle.getMove(moveName)
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id1, move)
@battle.recordMove(@id2, tackle)
mock = @sandbox.mock(tackle).expects('hit').once()
@battle.continueTurn()
mock.verify()
it "is vulnerable to attacks if locked on", ->
shared.create.call(this, gen: 'xy')
@battle.performMove(@p1, @battle.getMove("Lock-On"))
@battle.performMove(@p2, @battle.getMove(moveName))
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id1, tackle)
mock = @sandbox.mock(tackle).expects('hit').once()
@battle.continueTurn()
mock.verify()
for vulnerableMove in vulnerable
it "is vulnerable to #{vulnerableMove}", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("PI:NAME:<NAME>END_PI", evs: {speed: 4})]
move = @battle.getMove(moveName)
vulnerable = @battle.getMove(vulnerableMove)
@battle.recordMove(@id1, move)
@battle.recordMove(@id2, vulnerable)
mock = @sandbox.mock(vulnerable).expects('hit').once()
@battle.continueTurn()
mock.verify()
else # no vulnerable moves
it "doesn't make target invulnerable to moves", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("PI:NAME:<NAME>END_PI", evs: {speed: 4})]
move = @battle.getMove(moveName)
tackle = @battle.getMove("Tackle")
@battle.recordMove(@id1, move)
@battle.recordMove(@id2, tackle)
mock = @sandbox.mock(tackle).expects('hit').once()
@battle.continueTurn()
mock.verify()
testChargeMove('Fly', ["Gust", "Thunder", "Twister", "Sky Uppercut", "Hurricane", "Smack Down", "Thousand Arrows"])
testChargeMove('Bounce', ["Gust", "Thunder", "Twister", "Sky Uppercut", "Hurricane", "Smack Down", "Thousand Arrows"])
testChargeMove('Geomancy')
testChargeMove('Phantom Force', [])
describe "Toxic", ->
it "cannot miss when used by a Poison type pokemon", ->
shared.create.call(this, gen: 'xy')
@p1.types = [ "Poison" ]
@p2.types = [ "Normal" ]
shared.biasRNG.call(this, "randInt", 'miss', 101)
toxic = @battle.getMove("Toxic")
toxic.willMiss(@battle, @p1, @p2).should.be.false
describe "Parting Shot", ->
it "reduces the attack and special attack of the target by two stages", ->
shared.create.call(this, gen: 'xy')
@battle.performMove(@p1, @battle.getMove("Parting Shot"))
@p2.stages.should.containEql attack: -1, specialAttack: -1
it "forces the owner to switch", ->
shared.create.call(this, gen: 'xy')
@battle.performMove(@p1, @battle.getMove("Parting Shot"))
@battle.requests.should.have.property @id1
describe "Worry Seed", ->
it "does not change some abilities", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Smeargle")]
team2: [Factory("Aegislash", ability: "Stance Change")]
worrySeed = @battle.getMove("Worry Seed")
mock = @sandbox.mock(worrySeed).expects('fail').once()
@battle.performMove(@p1, worrySeed)
mock.verify()
describe "Simple Beam", ->
it "does not change some abilities", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Smeargle")]
team2: [Factory("Aegislash", ability: "Stance Change")]
simpleBeam = @battle.getMove("Simple Beam")
mock = @sandbox.mock(simpleBeam).expects('fail').once()
@battle.performMove(@p1, simpleBeam)
mock.verify()
testTrappingMove = (name) ->
describe name, ->
it "deals 1/8 of the pokemon's max hp every turn", ->
shared.create.call this,
gen: 'xy'
team2: [Factory("Blissey")]
@battle.performMove(@p1, @battle.getMove(name))
@p2.currentHP = @p2.stat('hp')
@battle.endTurn()
maxHP = @p2.stat('hp')
expected = maxHP - Math.floor(maxHP / 8)
@p2.currentHP.should.equal expected
it "deals 1/6 of the pokemon's max hp every turn if the user is holding a Binding Band", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", item: "Binding Band")]
team2: [Factory("Blissey")]
@battle.performMove(@p1, @battle.getMove(name))
@p2.currentHP = @p2.stat('hp')
@battle.endTurn()
maxHP = @p2.stat('hp')
expected = maxHP - Math.floor(maxHP / 6)
@p2.currentHP.should.equal expected
testTrappingMove "Bind"
testTrappingMove "Clamp"
testTrappingMove "Fire Spin"
testTrappingMove "Infestation"
testTrappingMove "Magma Storm"
testTrappingMove "Sand Tomb"
testTrappingMove "Wrap"
describe "Entrainment", ->
it "does not change some abilities", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", ability: "Swift Swim")]
team2: [Factory("Aegislash", ability: "Stance Change")]
entrainment = @battle.getMove("Entrainment")
mock = @sandbox.mock(entrainment).expects('fail').once()
@battle.performMove(@p1, entrainment)
mock.verify()
describe "Nature Power", ->
it "uses Tri Attack in Wi-Fi battles", ->
shared.create.call(this, gen: 'xy')
naturePower = @battle.getMove('Nature Power')
triAttack = @battle.getMove('Tri Attack')
mock = @sandbox.mock(triAttack).expects('execute').once()
.withArgs(@battle, @p1, [ @p2 ])
@battle.performMove(@p1, naturePower)
mock.verify()
describe "Venom Drench", ->
it "lowers the target's attack, special attack, and speed by 1 stage if it is poisoned", ->
shared.create.call(this, gen: 'xy')
@p2.attach(Status.Poison)
@battle.performMove(@p1, @battle.getMove('Venom Drench'))
@p2.stages.should.containEql attack: -1, specialAttack: -1, speed: -1
it "fails if the target isn't poisoned", ->
shared.create.call(this, gen: 'xy')
venomDrench = @battle.getMove("Venom Drench")
mock = @sandbox.mock(venomDrench).expects('fail').once()
@battle.performMove(@p1, venomDrench)
mock.verify()
describe "Topsy-Turvy", ->
it "reverses the target's boosts", ->
shared.create.call(this, gen: 'xy')
@p2.stages.attack = 2
@p2.stages.defense = -3
@p2.stages.speed = 0
@battle.performMove(@p1, @battle.getMove('Topsy-Turvy'))
@p2.stages.should.containEql attack: -2
@p2.stages.should.containEql defense: 3
@p2.stages.should.containEql speed: 0
it "fails if the target has no boosts", ->
shared.create.call(this, gen: 'xy')
topsyTurvy = @battle.getMove('Topsy-Turvy')
mock = @sandbox.mock(topsyTurvy).expects('fail').once()
@battle.performMove(@p1, topsyTurvy)
mock.verify()
describe "Fell Stinger", ->
it "raises the user's Attack 2 stages if the target faints", ->
shared.create.call(this, gen: 'xy')
@p2.currentHP = 1
@battle.performMove(@p1, @battle.getMove("Fell Stinger"))
@p1.stages.should.containEql attack: 2
it "does not raise the user's Attack 2 stages otherwise", ->
shared.create.call(this, gen: 'xy')
@battle.performMove(@p1, @battle.getMove("Fell Stinger"))
@p1.stages.should.containEql attack: 0
describe "Skill Swap", ->
it "can swap the abilities if they are the same", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", ability: "Swift Swim")]
team2: [Factory("Magikarp", ability: "Swift Swim")]
skillSwap = @battle.getMove("Skill Swap")
mock = @sandbox.mock(skillSwap).expects('fail').never()
@battle.performMove(@p1, skillSwap)
mock.verify()
describe "Metronome", ->
it "reselects if chosen an illegal move", ->
shared.create.call(this, gen: 'xy')
@p1.moves = [ metronome ]
metronome = @battle.getMove("Metronome")
belch = @battle.getMove("Belch")
tackle = @battle.getMove("Tackle")
index = @battle.MoveList.indexOf(belch)
reselectIndex = @battle.MoveList.indexOf(tackle)
shared.biasRNG.call(this, 'randInt', "metronome", index)
shared.biasRNG.call(this, 'randInt', "metronome reselect", reselectIndex)
mock = @sandbox.mock(tackle).expects('execute').once()
@battle.performMove(@p1, metronome)
mock.verify()
testDelayedAttackMove = (moveName, type) ->
describe moveName, ->
it "does not hit substitutes if the user has Infiltrator and is active", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", ability: "Infiltrator")]
move = @battle.getMove(moveName)
@battle.performMove(@p1, move)
@p2.attach(Attachment.Substitute, hp: 1)
@battle.endTurn()
@battle.endTurn()
@p2.has(Attachment.Substitute).should.be.true
@battle.endTurn()
@p2.has(Attachment.Substitute).should.be.true
it "always hits substitutes if the user is not on the field", ->
shared.create.call this,
gen: 'xy'
team1: [Factory("Magikarp", ability: "Infiltrator"), Factory("Magikarp")]
move = @battle.getMove(moveName)
@battle.performMove(@p1, move)
@p2.attach(Attachment.Substitute, hp: 1)
@battle.endTurn()
@battle.performSwitch(@p1, 1)
@battle.endTurn()
@p2.has(Attachment.Substitute).should.be.true
@battle.endTurn()
@p2.has(Attachment.Substitute).should.be.false
testDelayedAttackMove("Future Sight")
testDelayedAttackMove("Doom Desire")
|
[
{
"context": "'use strict'\n#\n# Ethan Mick\n# 2015\n#\nchildProcess = require('child_process')\n",
"end": 27,
"score": 0.9995296001434326,
"start": 17,
"tag": "NAME",
"value": "Ethan Mick"
}
] | lib/worker.coffee | ethanmick/coffee-mule | 0 | 'use strict'
#
# Ethan Mick
# 2015
#
childProcess = require('child_process')
EventEmitter = require('events').EventEmitter
log = require './log'
class Worker extends EventEmitter
constructor: (file)->
throw Error('A worker MUST have a file to run!') unless file
super()
@process = childProcess.fork(file)
@pid = @process.pid
@status = Worker.STARTING
@process.once 'message', @onReady.bind(this)
onReady: (message)->
if @status is Worker.STARTING
log.debug "Worker #{@pid} ready."
@status = Worker.READY
@emit 'ready', this
onMessage: (callback, message)->
callback(message)
@status = Worker.READY
@emit 'ready', this
send: (message, callback)->
@status = Worker.BUSY
@emit 'busy'
@process.once 'message', @onMessage.bind(this, callback)
@process.send(message)
Worker.STARTING = 'STARTING'
Worker.READY = 'READY'
Worker.BUSY = 'BUSY'
module.exports = Worker
| 54763 | 'use strict'
#
# <NAME>
# 2015
#
childProcess = require('child_process')
EventEmitter = require('events').EventEmitter
log = require './log'
class Worker extends EventEmitter
constructor: (file)->
throw Error('A worker MUST have a file to run!') unless file
super()
@process = childProcess.fork(file)
@pid = @process.pid
@status = Worker.STARTING
@process.once 'message', @onReady.bind(this)
onReady: (message)->
if @status is Worker.STARTING
log.debug "Worker #{@pid} ready."
@status = Worker.READY
@emit 'ready', this
onMessage: (callback, message)->
callback(message)
@status = Worker.READY
@emit 'ready', this
send: (message, callback)->
@status = Worker.BUSY
@emit 'busy'
@process.once 'message', @onMessage.bind(this, callback)
@process.send(message)
Worker.STARTING = 'STARTING'
Worker.READY = 'READY'
Worker.BUSY = 'BUSY'
module.exports = Worker
| true | 'use strict'
#
# PI:NAME:<NAME>END_PI
# 2015
#
childProcess = require('child_process')
EventEmitter = require('events').EventEmitter
log = require './log'
class Worker extends EventEmitter
constructor: (file)->
throw Error('A worker MUST have a file to run!') unless file
super()
@process = childProcess.fork(file)
@pid = @process.pid
@status = Worker.STARTING
@process.once 'message', @onReady.bind(this)
onReady: (message)->
if @status is Worker.STARTING
log.debug "Worker #{@pid} ready."
@status = Worker.READY
@emit 'ready', this
onMessage: (callback, message)->
callback(message)
@status = Worker.READY
@emit 'ready', this
send: (message, callback)->
@status = Worker.BUSY
@emit 'busy'
@process.once 'message', @onMessage.bind(this, callback)
@process.send(message)
Worker.STARTING = 'STARTING'
Worker.READY = 'READY'
Worker.BUSY = 'BUSY'
module.exports = Worker
|
[
{
"context": "'/api/password_reset'\n data: {password: @password, secret: params.secret}\n success: ->\n ",
"end": 337,
"score": 0.9904624223709106,
"start": 328,
"tag": "PASSWORD",
"value": "@password"
}
] | view/src/coffee/auth/password_reset.coffee | ponkotuy/aggregate-exif | 5 | $(document).ready ->
params = fromURLParameter(location.search.slice(1))
console.log(params)
new Vue
el: '#password'
data:
password: ''
retype: ''
methods:
submit: ->
if @password == @retype
API.deleteJSON
url: '/api/password_reset'
data: {password: @password, secret: params.secret}
success: ->
location.href = '/auth/session.html'
else
window.alert('Passwordが一致しません')
| 225563 | $(document).ready ->
params = fromURLParameter(location.search.slice(1))
console.log(params)
new Vue
el: '#password'
data:
password: ''
retype: ''
methods:
submit: ->
if @password == @retype
API.deleteJSON
url: '/api/password_reset'
data: {password: <PASSWORD>, secret: params.secret}
success: ->
location.href = '/auth/session.html'
else
window.alert('Passwordが一致しません')
| true | $(document).ready ->
params = fromURLParameter(location.search.slice(1))
console.log(params)
new Vue
el: '#password'
data:
password: ''
retype: ''
methods:
submit: ->
if @password == @retype
API.deleteJSON
url: '/api/password_reset'
data: {password: PI:PASSWORD:<PASSWORD>END_PI, secret: params.secret}
success: ->
location.href = '/auth/session.html'
else
window.alert('Passwordが一致しません')
|
[
{
"context": "auth:\n user: process.env.MAILER_EMAIL\n pass: process.env.MAILER_PASSWORD\n\n# routes\napp.get '/items', (req, res) ->\n db.it",
"end": 730,
"score": 0.9986076354980469,
"start": 703,
"tag": "PASSWORD",
"value": "process.env.MAILER_PASSWORD"
},
{
"context": "6b7... | server/app.coffee | pennlabs/poorrichardslist | 0 | require('dotenv').load()
Item = require './item'
db = require './db'
express = require 'express'
morgan = require 'morgan'
_ = require 'lodash'
async = require 'async'
cloudinary = require 'cloudinary'
nodemailer = require 'nodemailer'
app = express()
app.use express.static 'public'
app.use morgan 'combined'
bodyParser = require 'body-parser'
parseUrlencoded = bodyParser.urlencoded {extended: false}
app.use(bodyParser.json())
cloudinary.config
cloud_name: process.env.CLOUD_NAME
api_key: process.env.CLOUDINARY_API_KEY
api_secret: process.env.CLOUDINARY_API_SECRET
smtpTransport = nodemailer.createTransport 'SMTP',
service: 'Gmail'
auth:
user: process.env.MAILER_EMAIL
pass: process.env.MAILER_PASSWORD
# routes
app.get '/items', (req, res) ->
db.items.find({}).sort({_id: -1}).toArray (err, items) ->
async.map items,
(item, callback) ->
if "imageIds" of item
item.smallImageUrl = cloudinary.utils.url item.imageIds[0], {
crop: 'fill', width: 533, height: 400 }
db.tags.findByItem item, (err, tags) ->
item.tags = tags
callback null, item
(err, items) ->
res.json items
app.get '/items/:id', (req, res) ->
db.items.findById req.params.id,
(err, item) ->
item.detailImageUrls = _.map item.imageIds, (id) ->
cloudinary.utils.url id, { crop: 'fit', height: 330 }
db.tags.findByItem item, (err, tags) ->
item.tags = tags
res.json item
app.post '/items', parseUrlencoded, (req, res) ->
item = req.body
imageIds = req.body.imageIds
if imageIds and imageIds.length > 0
preloadedFiles = _.map imageIds, (id) ->
new cloudinary.PreloadedFile id
if _.all(preloadedFiles, (pf) -> pf.is_valid())
item.imageIds = _.map preloadedFiles, (pf) -> pf.identifier()
else
throw "Invalid image upload signature"
if req.body.tags
tags = _.map (req.body.tags.split " "), (name) -> {name: name}
else
tags = []
Item.addItem item, tags, (result) ->
res.status(201).json result
app.get '/tags', (req, res) ->
db.tags.find({}).sort({count: -1}).toArray (err, tags) ->
async.map tags,
(tag, callback) ->
db.items.find({tags: tag._id}).toArray (err, items) ->
tag.items = _.map items, (item) -> item._id
callback null, tag
(err, tags) ->
res.json tags
app.get '/tags/:id', (req, res) ->
db.tags.findById req.params.id,
(err, tag) ->
res.json tag
app.delete '/tags/:id', (req, res) ->
db.tags.removeById req.params.id,
(err, result) ->
res.json result
app.post '/email', parseUrlencoded, (req, res) ->
mailOptions =
to: req.body.to
subject: req.body.subject
text: req.body.body
smtpTransport.sendMail mailOptions, (error, response) ->
if error
console.log error
res.end 'error'
else
console.log 'Message sent: ' + response.message
res.end 'success'
# Returns cloudinary credentials for the client to upload images.
# Credentials timeout in an hour. Example below:
# { timestamp: 1426435407,
# signature: 'b646d8d486b74a27c88653ddcd0c05cf4d4f282a',
# api_key: '162536167369695' }
app.get '/cloudinary', (req, res) ->
params = cloudinary.utils.build_upload_params {}
params = cloudinary.utils.process_request_params params, {}
res.json params
module.exports = app
unless module.parent
app.listen 8080, ->
console.log "server started!!"
| 141806 | require('dotenv').load()
Item = require './item'
db = require './db'
express = require 'express'
morgan = require 'morgan'
_ = require 'lodash'
async = require 'async'
cloudinary = require 'cloudinary'
nodemailer = require 'nodemailer'
app = express()
app.use express.static 'public'
app.use morgan 'combined'
bodyParser = require 'body-parser'
parseUrlencoded = bodyParser.urlencoded {extended: false}
app.use(bodyParser.json())
cloudinary.config
cloud_name: process.env.CLOUD_NAME
api_key: process.env.CLOUDINARY_API_KEY
api_secret: process.env.CLOUDINARY_API_SECRET
smtpTransport = nodemailer.createTransport 'SMTP',
service: 'Gmail'
auth:
user: process.env.MAILER_EMAIL
pass: <PASSWORD>
# routes
app.get '/items', (req, res) ->
db.items.find({}).sort({_id: -1}).toArray (err, items) ->
async.map items,
(item, callback) ->
if "imageIds" of item
item.smallImageUrl = cloudinary.utils.url item.imageIds[0], {
crop: 'fill', width: 533, height: 400 }
db.tags.findByItem item, (err, tags) ->
item.tags = tags
callback null, item
(err, items) ->
res.json items
app.get '/items/:id', (req, res) ->
db.items.findById req.params.id,
(err, item) ->
item.detailImageUrls = _.map item.imageIds, (id) ->
cloudinary.utils.url id, { crop: 'fit', height: 330 }
db.tags.findByItem item, (err, tags) ->
item.tags = tags
res.json item
app.post '/items', parseUrlencoded, (req, res) ->
item = req.body
imageIds = req.body.imageIds
if imageIds and imageIds.length > 0
preloadedFiles = _.map imageIds, (id) ->
new cloudinary.PreloadedFile id
if _.all(preloadedFiles, (pf) -> pf.is_valid())
item.imageIds = _.map preloadedFiles, (pf) -> pf.identifier()
else
throw "Invalid image upload signature"
if req.body.tags
tags = _.map (req.body.tags.split " "), (name) -> {name: name}
else
tags = []
Item.addItem item, tags, (result) ->
res.status(201).json result
app.get '/tags', (req, res) ->
db.tags.find({}).sort({count: -1}).toArray (err, tags) ->
async.map tags,
(tag, callback) ->
db.items.find({tags: tag._id}).toArray (err, items) ->
tag.items = _.map items, (item) -> item._id
callback null, tag
(err, tags) ->
res.json tags
app.get '/tags/:id', (req, res) ->
db.tags.findById req.params.id,
(err, tag) ->
res.json tag
app.delete '/tags/:id', (req, res) ->
db.tags.removeById req.params.id,
(err, result) ->
res.json result
app.post '/email', parseUrlencoded, (req, res) ->
mailOptions =
to: req.body.to
subject: req.body.subject
text: req.body.body
smtpTransport.sendMail mailOptions, (error, response) ->
if error
console.log error
res.end 'error'
else
console.log 'Message sent: ' + response.message
res.end 'success'
# Returns cloudinary credentials for the client to upload images.
# Credentials timeout in an hour. Example below:
# { timestamp: 1426435407,
# signature: 'b646d8d486b74a27c88653ddcd0c05cf4d4f282a',
# api_key: '<KEY>7369695' }
app.get '/cloudinary', (req, res) ->
params = cloudinary.utils.build_upload_params {}
params = cloudinary.utils.process_request_params params, {}
res.json params
module.exports = app
unless module.parent
app.listen 8080, ->
console.log "server started!!"
| true | require('dotenv').load()
Item = require './item'
db = require './db'
express = require 'express'
morgan = require 'morgan'
_ = require 'lodash'
async = require 'async'
cloudinary = require 'cloudinary'
nodemailer = require 'nodemailer'
app = express()
app.use express.static 'public'
app.use morgan 'combined'
bodyParser = require 'body-parser'
parseUrlencoded = bodyParser.urlencoded {extended: false}
app.use(bodyParser.json())
cloudinary.config
cloud_name: process.env.CLOUD_NAME
api_key: process.env.CLOUDINARY_API_KEY
api_secret: process.env.CLOUDINARY_API_SECRET
smtpTransport = nodemailer.createTransport 'SMTP',
service: 'Gmail'
auth:
user: process.env.MAILER_EMAIL
pass: PI:PASSWORD:<PASSWORD>END_PI
# routes
app.get '/items', (req, res) ->
db.items.find({}).sort({_id: -1}).toArray (err, items) ->
async.map items,
(item, callback) ->
if "imageIds" of item
item.smallImageUrl = cloudinary.utils.url item.imageIds[0], {
crop: 'fill', width: 533, height: 400 }
db.tags.findByItem item, (err, tags) ->
item.tags = tags
callback null, item
(err, items) ->
res.json items
app.get '/items/:id', (req, res) ->
db.items.findById req.params.id,
(err, item) ->
item.detailImageUrls = _.map item.imageIds, (id) ->
cloudinary.utils.url id, { crop: 'fit', height: 330 }
db.tags.findByItem item, (err, tags) ->
item.tags = tags
res.json item
app.post '/items', parseUrlencoded, (req, res) ->
item = req.body
imageIds = req.body.imageIds
if imageIds and imageIds.length > 0
preloadedFiles = _.map imageIds, (id) ->
new cloudinary.PreloadedFile id
if _.all(preloadedFiles, (pf) -> pf.is_valid())
item.imageIds = _.map preloadedFiles, (pf) -> pf.identifier()
else
throw "Invalid image upload signature"
if req.body.tags
tags = _.map (req.body.tags.split " "), (name) -> {name: name}
else
tags = []
Item.addItem item, tags, (result) ->
res.status(201).json result
app.get '/tags', (req, res) ->
db.tags.find({}).sort({count: -1}).toArray (err, tags) ->
async.map tags,
(tag, callback) ->
db.items.find({tags: tag._id}).toArray (err, items) ->
tag.items = _.map items, (item) -> item._id
callback null, tag
(err, tags) ->
res.json tags
app.get '/tags/:id', (req, res) ->
db.tags.findById req.params.id,
(err, tag) ->
res.json tag
app.delete '/tags/:id', (req, res) ->
db.tags.removeById req.params.id,
(err, result) ->
res.json result
app.post '/email', parseUrlencoded, (req, res) ->
mailOptions =
to: req.body.to
subject: req.body.subject
text: req.body.body
smtpTransport.sendMail mailOptions, (error, response) ->
if error
console.log error
res.end 'error'
else
console.log 'Message sent: ' + response.message
res.end 'success'
# Returns cloudinary credentials for the client to upload images.
# Credentials timeout in an hour. Example below:
# { timestamp: 1426435407,
# signature: 'b646d8d486b74a27c88653ddcd0c05cf4d4f282a',
# api_key: 'PI:KEY:<KEY>END_PI7369695' }
app.get '/cloudinary', (req, res) ->
params = cloudinary.utils.build_upload_params {}
params = cloudinary.utils.process_request_params params, {}
res.json params
module.exports = app
unless module.parent
app.listen 8080, ->
console.log "server started!!"
|
[
{
"context": "}$/\n\t\tprovider: /^[a-zA-Z0-9._\\-]{2,}$/\n\t\tkey: /^[a-zA-Z0-9\\-_]{23,27}$/\n\n\tcheck\n",
"end": 5611,
"score": 0.9513198137283325,
"start": 5589,
"tag": "KEY",
"value": "a-zA-Z0-9\\-_]{23,27}$/"
}
] | src/core/utilities/check.coffee | pmstss/oauthd | 443 | # OAuth daemon
# Copyright (C) 2013 Webshell SAS
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
escapeHtml = (text) ->
map =
'&': '&'
'<': '<'
'>': '>'
'"': '"'
"'": '''
return text.replace /[&<>"']/g, (m) -> map[m]
module.exports = (env) ->
_check = (arg, format, errors) ->
if format instanceof RegExp
return typeof arg == 'string' && arg.match(format)
if Array.isArray(format)
for possibility in format
return true if _check arg, possibility
return false
if typeof format == 'object'
if arg? && typeof arg == 'object'
success = true
for k,v of format
if not _check arg[k], v
if errors?
errors[k] = 'Invalid format'
success = false
else
return false
return success
return false
return !format ||
format == 'any' && arg? ||
format == 'none' && not arg? ||
format == 'null' && arg == null ||
format == 'string' && typeof arg == 'string' ||
format == 'regexp' && arg instanceof RegExp ||
format == 'object' && arg? && typeof arg == 'object' ||
format == 'function' && typeof arg == 'function' ||
format == 'array' && Array.isArray(arg) ||
format == 'number' && (arg instanceof Number || typeof arg == 'number') ||
format == 'int' && (parseFloat(arg) == parseInt(arg)) && !isNaN(arg) ||
format == 'bool' && (arg instanceof Boolean || typeof arg == 'boolean') ||
format == 'date' && arg instanceof Date
_clone = (item) ->
return item if not item?
return Number item if item instanceof Number
return String item if item instanceof String
return Boolean item if item instanceof Boolean
if Array.isArray(item)
result = []
for index, child of item
result[index] = _clone child
return result
if typeof item == "object" && ! item.prototype
result = {}
for i of item
result[i] = _clone item[i]
return result
return item
# Error class
class CheckError extends Error
constructor: ->
Error.captureStackTrace @, @constructor
@message = "Invalid format"
@body = {}
if arguments.length == 1
@message = arguments[0]
else if arguments.length
@status = "fail"
@body[arguments[0]] = arguments[1]
super @message
check: (name, arg, format) ->
@status = "fail"
if arguments.length == 2 # args=name, format=arg
success = _check name, arg, @body
@status = "error" if not Object.keys(@body).length && success == false
return success
o = {}; f = {}
o[name] = arg; f[name] = format
success = _check o, f, @body
@status = "error" if not Object.keys(@body).length && success == false
return success
error: (name, message) ->
if arguments.length == 1
@message = name
@status = "error"
else
@body[name] = message
@status = "fail"
return
failed: -> return Object.keys(@body).length || @status == "error"
# Exports
# overall, check englobes a method given as last argument, and returns a hat function
# this hat function will first check all given arguments, fail if one is not right
# and finally call the hatted fn if they are all right
check = ->
# pops the last arg into checked, arguments loses its last arg
checked = Array.prototype.pop.call arguments, arguments
formats = arguments
return =>
# Here arguments is the array of arguments of the called returned method
# shallow copies the arguments array
args = Array.prototype.slice.call arguments
# pops last value of args, not of arguments (as args is a copy)
callback = args.pop()
# formats is the arguments array of the check method
if args.length != formats.length
# if the arguments count of the second fn is not the same as the the original hat fn
# (without callbacks of course). Means that the arguments given to the function are wrong
return callback new CheckError 'Bad parameters count'
# Creates a new instance of CheckError
error = new CheckError 'Bad parameters format'
# loops through the format parameters
for i,argformat of formats
# error check returns false if the args[i] is not the argformat
if not error.check(args[i], argformat) and not error.failed()
error.error 'Bad parameters format'
# error failed returns true if some argument wasn't in the right format
# here we call callback (the last argument given to the )
return callback error if error.failed()
# if all args were right, call the hatted fn with the original arguments
try
return checked.apply @, arguments
catch e
err = new Error 'Uncaught exception: ' + e.message
err.stack = e.stack if e.stack
return callback err
check.clone = (cloned) -> =>
return cloned.apply @, _clone arguments
check.escape = (str) ->
return str.replace(/[\\\/"']/g, '\\$&').replace /\u0000/g, '\\0'
check.Error = CheckError
check.nullv = {} # this means a null
check.escapeHtml = escapeHtml
check.format =
mail: /^[a-zA-Z0-9._%\-\+]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}$/
provider: /^[a-zA-Z0-9._\-]{2,}$/
key: /^[a-zA-Z0-9\-_]{23,27}$/
check
| 22159 | # OAuth daemon
# Copyright (C) 2013 Webshell SAS
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
escapeHtml = (text) ->
map =
'&': '&'
'<': '<'
'>': '>'
'"': '"'
"'": '''
return text.replace /[&<>"']/g, (m) -> map[m]
module.exports = (env) ->
_check = (arg, format, errors) ->
if format instanceof RegExp
return typeof arg == 'string' && arg.match(format)
if Array.isArray(format)
for possibility in format
return true if _check arg, possibility
return false
if typeof format == 'object'
if arg? && typeof arg == 'object'
success = true
for k,v of format
if not _check arg[k], v
if errors?
errors[k] = 'Invalid format'
success = false
else
return false
return success
return false
return !format ||
format == 'any' && arg? ||
format == 'none' && not arg? ||
format == 'null' && arg == null ||
format == 'string' && typeof arg == 'string' ||
format == 'regexp' && arg instanceof RegExp ||
format == 'object' && arg? && typeof arg == 'object' ||
format == 'function' && typeof arg == 'function' ||
format == 'array' && Array.isArray(arg) ||
format == 'number' && (arg instanceof Number || typeof arg == 'number') ||
format == 'int' && (parseFloat(arg) == parseInt(arg)) && !isNaN(arg) ||
format == 'bool' && (arg instanceof Boolean || typeof arg == 'boolean') ||
format == 'date' && arg instanceof Date
_clone = (item) ->
return item if not item?
return Number item if item instanceof Number
return String item if item instanceof String
return Boolean item if item instanceof Boolean
if Array.isArray(item)
result = []
for index, child of item
result[index] = _clone child
return result
if typeof item == "object" && ! item.prototype
result = {}
for i of item
result[i] = _clone item[i]
return result
return item
# Error class
class CheckError extends Error
constructor: ->
Error.captureStackTrace @, @constructor
@message = "Invalid format"
@body = {}
if arguments.length == 1
@message = arguments[0]
else if arguments.length
@status = "fail"
@body[arguments[0]] = arguments[1]
super @message
check: (name, arg, format) ->
@status = "fail"
if arguments.length == 2 # args=name, format=arg
success = _check name, arg, @body
@status = "error" if not Object.keys(@body).length && success == false
return success
o = {}; f = {}
o[name] = arg; f[name] = format
success = _check o, f, @body
@status = "error" if not Object.keys(@body).length && success == false
return success
error: (name, message) ->
if arguments.length == 1
@message = name
@status = "error"
else
@body[name] = message
@status = "fail"
return
failed: -> return Object.keys(@body).length || @status == "error"
# Exports
# overall, check englobes a method given as last argument, and returns a hat function
# this hat function will first check all given arguments, fail if one is not right
# and finally call the hatted fn if they are all right
check = ->
# pops the last arg into checked, arguments loses its last arg
checked = Array.prototype.pop.call arguments, arguments
formats = arguments
return =>
# Here arguments is the array of arguments of the called returned method
# shallow copies the arguments array
args = Array.prototype.slice.call arguments
# pops last value of args, not of arguments (as args is a copy)
callback = args.pop()
# formats is the arguments array of the check method
if args.length != formats.length
# if the arguments count of the second fn is not the same as the the original hat fn
# (without callbacks of course). Means that the arguments given to the function are wrong
return callback new CheckError 'Bad parameters count'
# Creates a new instance of CheckError
error = new CheckError 'Bad parameters format'
# loops through the format parameters
for i,argformat of formats
# error check returns false if the args[i] is not the argformat
if not error.check(args[i], argformat) and not error.failed()
error.error 'Bad parameters format'
# error failed returns true if some argument wasn't in the right format
# here we call callback (the last argument given to the )
return callback error if error.failed()
# if all args were right, call the hatted fn with the original arguments
try
return checked.apply @, arguments
catch e
err = new Error 'Uncaught exception: ' + e.message
err.stack = e.stack if e.stack
return callback err
check.clone = (cloned) -> =>
return cloned.apply @, _clone arguments
check.escape = (str) ->
return str.replace(/[\\\/"']/g, '\\$&').replace /\u0000/g, '\\0'
check.Error = CheckError
check.nullv = {} # this means a null
check.escapeHtml = escapeHtml
check.format =
mail: /^[a-zA-Z0-9._%\-\+]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}$/
provider: /^[a-zA-Z0-9._\-]{2,}$/
key: /^[<KEY>
check
| true | # OAuth daemon
# Copyright (C) 2013 Webshell SAS
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
escapeHtml = (text) ->
map =
'&': '&'
'<': '<'
'>': '>'
'"': '"'
"'": '''
return text.replace /[&<>"']/g, (m) -> map[m]
module.exports = (env) ->
_check = (arg, format, errors) ->
if format instanceof RegExp
return typeof arg == 'string' && arg.match(format)
if Array.isArray(format)
for possibility in format
return true if _check arg, possibility
return false
if typeof format == 'object'
if arg? && typeof arg == 'object'
success = true
for k,v of format
if not _check arg[k], v
if errors?
errors[k] = 'Invalid format'
success = false
else
return false
return success
return false
return !format ||
format == 'any' && arg? ||
format == 'none' && not arg? ||
format == 'null' && arg == null ||
format == 'string' && typeof arg == 'string' ||
format == 'regexp' && arg instanceof RegExp ||
format == 'object' && arg? && typeof arg == 'object' ||
format == 'function' && typeof arg == 'function' ||
format == 'array' && Array.isArray(arg) ||
format == 'number' && (arg instanceof Number || typeof arg == 'number') ||
format == 'int' && (parseFloat(arg) == parseInt(arg)) && !isNaN(arg) ||
format == 'bool' && (arg instanceof Boolean || typeof arg == 'boolean') ||
format == 'date' && arg instanceof Date
_clone = (item) ->
return item if not item?
return Number item if item instanceof Number
return String item if item instanceof String
return Boolean item if item instanceof Boolean
if Array.isArray(item)
result = []
for index, child of item
result[index] = _clone child
return result
if typeof item == "object" && ! item.prototype
result = {}
for i of item
result[i] = _clone item[i]
return result
return item
# Error class
class CheckError extends Error
constructor: ->
Error.captureStackTrace @, @constructor
@message = "Invalid format"
@body = {}
if arguments.length == 1
@message = arguments[0]
else if arguments.length
@status = "fail"
@body[arguments[0]] = arguments[1]
super @message
check: (name, arg, format) ->
@status = "fail"
if arguments.length == 2 # args=name, format=arg
success = _check name, arg, @body
@status = "error" if not Object.keys(@body).length && success == false
return success
o = {}; f = {}
o[name] = arg; f[name] = format
success = _check o, f, @body
@status = "error" if not Object.keys(@body).length && success == false
return success
error: (name, message) ->
if arguments.length == 1
@message = name
@status = "error"
else
@body[name] = message
@status = "fail"
return
failed: -> return Object.keys(@body).length || @status == "error"
# Exports
# overall, check englobes a method given as last argument, and returns a hat function
# this hat function will first check all given arguments, fail if one is not right
# and finally call the hatted fn if they are all right
check = ->
# pops the last arg into checked, arguments loses its last arg
checked = Array.prototype.pop.call arguments, arguments
formats = arguments
return =>
# Here arguments is the array of arguments of the called returned method
# shallow copies the arguments array
args = Array.prototype.slice.call arguments
# pops last value of args, not of arguments (as args is a copy)
callback = args.pop()
# formats is the arguments array of the check method
if args.length != formats.length
# if the arguments count of the second fn is not the same as the the original hat fn
# (without callbacks of course). Means that the arguments given to the function are wrong
return callback new CheckError 'Bad parameters count'
# Creates a new instance of CheckError
error = new CheckError 'Bad parameters format'
# loops through the format parameters
for i,argformat of formats
# error check returns false if the args[i] is not the argformat
if not error.check(args[i], argformat) and not error.failed()
error.error 'Bad parameters format'
# error failed returns true if some argument wasn't in the right format
# here we call callback (the last argument given to the )
return callback error if error.failed()
# if all args were right, call the hatted fn with the original arguments
try
return checked.apply @, arguments
catch e
err = new Error 'Uncaught exception: ' + e.message
err.stack = e.stack if e.stack
return callback err
check.clone = (cloned) -> =>
return cloned.apply @, _clone arguments
check.escape = (str) ->
return str.replace(/[\\\/"']/g, '\\$&').replace /\u0000/g, '\\0'
check.Error = CheckError
check.nullv = {} # this means a null
check.escapeHtml = escapeHtml
check.format =
mail: /^[a-zA-Z0-9._%\-\+]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}$/
provider: /^[a-zA-Z0-9._\-]{2,}$/
key: /^[PI:KEY:<KEY>END_PI
check
|
[
{
"context": " @model.set(\n value:\n name: 'bilbo'\n email: 'b@shire.net'\n )\n\n ",
"end": 932,
"score": 0.9997248649597168,
"start": 927,
"tag": "NAME",
"value": "bilbo"
},
{
"context": "ue:\n name: 'bilbo'\n email: '... | test/models_test.coffee | dobtco/formrenderer-base | 79 | describe 'FormRenderer.Models.ResponseFieldIdentification', ->
context 'when in a Follow-up Form', ->
beforeEach ->
fr = new FormRenderer Fixtures.FormRendererOptions.FOLLOW_UP_FORM()
@model = fr.formComponents.find (rf) -> rf.field_type == 'identification'
describe '#getValue', ->
it 'returns null even if name/email is present', ->
expect(@model.getValue()).to.equal(null)
describe '#shouldPersistValue', ->
it 'returns false', ->
expect(@model.shouldPersistValue()).to.equal(false)
context 'when not in a Follow-up form', ->
beforeEach ->
fr = new FormRenderer Fixtures.FormRendererOptions.BLANK_IDENTIFIED()
@model = fr.formComponents.find (rf) -> rf.field_type == 'identification'
describe '#getValue', ->
it 'returns the value', ->
expect(@model.getValue()).to.eql({})
@model.set(
value:
name: 'bilbo'
email: 'b@shire.net'
)
expect(@model.getValue()).to.eql({ name: 'bilbo', email: 'b@shire.net' })
describe '#shouldPersistValue', ->
it 'returns true', ->
expect(@model.shouldPersistValue()).to.equal(true)
| 41426 | describe 'FormRenderer.Models.ResponseFieldIdentification', ->
context 'when in a Follow-up Form', ->
beforeEach ->
fr = new FormRenderer Fixtures.FormRendererOptions.FOLLOW_UP_FORM()
@model = fr.formComponents.find (rf) -> rf.field_type == 'identification'
describe '#getValue', ->
it 'returns null even if name/email is present', ->
expect(@model.getValue()).to.equal(null)
describe '#shouldPersistValue', ->
it 'returns false', ->
expect(@model.shouldPersistValue()).to.equal(false)
context 'when not in a Follow-up form', ->
beforeEach ->
fr = new FormRenderer Fixtures.FormRendererOptions.BLANK_IDENTIFIED()
@model = fr.formComponents.find (rf) -> rf.field_type == 'identification'
describe '#getValue', ->
it 'returns the value', ->
expect(@model.getValue()).to.eql({})
@model.set(
value:
name: '<NAME>'
email: '<EMAIL>'
)
expect(@model.getValue()).to.eql({ name: '<NAME>', email: '<EMAIL>' })
describe '#shouldPersistValue', ->
it 'returns true', ->
expect(@model.shouldPersistValue()).to.equal(true)
| true | describe 'FormRenderer.Models.ResponseFieldIdentification', ->
context 'when in a Follow-up Form', ->
beforeEach ->
fr = new FormRenderer Fixtures.FormRendererOptions.FOLLOW_UP_FORM()
@model = fr.formComponents.find (rf) -> rf.field_type == 'identification'
describe '#getValue', ->
it 'returns null even if name/email is present', ->
expect(@model.getValue()).to.equal(null)
describe '#shouldPersistValue', ->
it 'returns false', ->
expect(@model.shouldPersistValue()).to.equal(false)
context 'when not in a Follow-up form', ->
beforeEach ->
fr = new FormRenderer Fixtures.FormRendererOptions.BLANK_IDENTIFIED()
@model = fr.formComponents.find (rf) -> rf.field_type == 'identification'
describe '#getValue', ->
it 'returns the value', ->
expect(@model.getValue()).to.eql({})
@model.set(
value:
name: 'PI:NAME:<NAME>END_PI'
email: 'PI:EMAIL:<EMAIL>END_PI'
)
expect(@model.getValue()).to.eql({ name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI' })
describe '#shouldPersistValue', ->
it 'returns true', ->
expect(@model.shouldPersistValue()).to.equal(true)
|
[
{
"context": "###\nCopyright (c) 2002-2013 \"Neo Technology,\"\nNetwork Engine for Objects in Lund AB [http://n",
"end": 43,
"score": 0.7620598077774048,
"start": 33,
"tag": "NAME",
"value": "Technology"
}
] | community/server/src/main/coffeescript/neo4j/webadmin/modules/databrowser/visualization/models/StyleRules.coffee | rebaze/neo4j | 1 | ###
Copyright (c) 2002-2013 "Neo Technology,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
['./StyleRule'
'ribcage/LocalCollection'],
(StyleRule, LocalCollection) ->
class StyleRules extends LocalCollection
model: StyleRule
comparator : (rule) -> rule.getOrder()
addLast : (rule) =>
if @last()?
rule.setOrder @last().getOrder() + 1
@add(rule)
)
| 39422 | ###
Copyright (c) 2002-2013 "Neo <NAME>,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
['./StyleRule'
'ribcage/LocalCollection'],
(StyleRule, LocalCollection) ->
class StyleRules extends LocalCollection
model: StyleRule
comparator : (rule) -> rule.getOrder()
addLast : (rule) =>
if @last()?
rule.setOrder @last().getOrder() + 1
@add(rule)
)
| true | ###
Copyright (c) 2002-2013 "Neo PI:NAME:<NAME>END_PI,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
['./StyleRule'
'ribcage/LocalCollection'],
(StyleRule, LocalCollection) ->
class StyleRules extends LocalCollection
model: StyleRule
comparator : (rule) -> rule.getOrder()
addLast : (rule) =>
if @last()?
rule.setOrder @last().getOrder() + 1
@add(rule)
)
|
[
{
"context": "/pubhtml\n# https://docs.google.com/spreadsheets/d/1dPG7Xxvk4qnPajTu9jG_uNuz2R5jvjfeaKI-ylX4NXs/edit\n\nP.deal = _index: true, _prefix: false\nP.dea",
"end": 288,
"score": 0.8708161115646362,
"start": 244,
"tag": "KEY",
"value": "1dPG7Xxvk4qnPajTu9jG_uNuz2R5jvjfeaKI-ylX4NXs"
... | worker/src/deal.coffee | oaworks/api | 0 |
# get the big deal data from a sheet and expose it in a website
# https://docs.google.com/spreadsheets/d/e/2PACX-1vQ4frfBvvPOKKFhArpV7cRUG0aAbfGRy214y-xlDG_CsW7kNbL-e8tuRvh8y37F4xc8wjO6FK8SD6UT/pubhtml
# https://docs.google.com/spreadsheets/d/1dPG7Xxvk4qnPajTu9jG_uNuz2R5jvjfeaKI-ylX4NXs/edit
P.deal = _index: true, _prefix: false
P.deal.institution = _index: true, _prefix: false
P.deal.load = () ->
recs = await @src.google.sheets '1dPG7Xxvk4qnPajTu9jG_uNuz2R5jvjfeaKI-ylX4NXs'
institutions = {}
for rec in recs
for tk in ['Institution', 'Publisher', 'Collection', 'Year(s)', 'Length of Agreement', 'Package Price', '2015 Carnegie Basic Classification', 'FTE', 'Source', 'URL', 'Share URL Publicly?', 'Notes']
tl = tk.toLowerCase().replace(/ /g, '').replace('?', '').replace('(','').replace(')','')
rec[tl] = rec[tk]
delete rec[tk]
try
rec.value = parseInt rec.packageprice.replace /[^0-9]/g, ''
if typeof rec.fte is 'string'
try
rec.fte = parseInt rec.fte
catch
delete rec.fte
if typeof rec.notes is 'string' and rec.notes.toLowerCase().includes 'canadian'
rec.gbpvalue = Math.floor rec.value * .57
rec.usdvalue = Math.floor rec.value * .75
else if rec.packageprice.includes '$'
rec.gbpvalue = Math.floor rec.value * .77
rec.usdvalue = Math.floor rec.value
else
rec.gbpvalue = Math.floor rec.value
rec.usdvalue = Math.floor rec.value * 1.3
rec.usdvalue ?= ''
try rec.years = '2013' if rec.years is '2103' # fix what is probably a typo
try delete rec.url if rec.shareurlpublicly.toLowerCase() isnt 'yes'
try delete rec.shareurlpublicly
try rec.collection = 'Unclassified' if rec.collection is ''
try
rec.carnegiebasicclassification = rec['2015carnegiebasicclassification']
delete rec['2015carnegiebasicclassification']
try
institutions[rec.institution] ?= {institution:rec.institution, deals:[], value:0, usdvalue:0, gbpvalue:0}
rdc = JSON.parse JSON.stringify rec
try delete rdc.institution
try
institutions[rec.institution].value += rec.value
institutions[rec.institution].gbpvalue += rec.gbpvalue
institutions[rec.institution].usdvalue += rec.usdvalue
institutions[rec.institution].deals.push rdc
insts = []
for i of institutions
insts.push institutions[i]
await @deal ''
await @deal.institution ''
await @deal recs
await @deal.institution insts
return retrieved: recs.length, institutions: insts.length
| 194338 |
# get the big deal data from a sheet and expose it in a website
# https://docs.google.com/spreadsheets/d/e/2PACX-1vQ4frfBvvPOKKFhArpV7cRUG0aAbfGRy214y-xlDG_CsW7kNbL-e8tuRvh8y37F4xc8wjO6FK8SD6UT/pubhtml
# https://docs.google.com/spreadsheets/d/<KEY>/edit
P.deal = _index: true, _prefix: false
P.deal.institution = _index: true, _prefix: false
P.deal.load = () ->
recs = await @src.google.sheets '1<KEY>'
institutions = {}
for rec in recs
for tk in ['Institution', 'Publisher', 'Collection', 'Year(s)', 'Length of Agreement', 'Package Price', '2015 Carnegie Basic Classification', 'FTE', 'Source', 'URL', 'Share URL Publicly?', 'Notes']
tl = tk.toLowerCase().replace(/ /g, '').replace('?', '').replace('(','').replace(')','')
rec[tl] = rec[tk]
delete rec[tk]
try
rec.value = parseInt rec.packageprice.replace /[^0-9]/g, ''
if typeof rec.fte is 'string'
try
rec.fte = parseInt rec.fte
catch
delete rec.fte
if typeof rec.notes is 'string' and rec.notes.toLowerCase().includes 'canadian'
rec.gbpvalue = Math.floor rec.value * .57
rec.usdvalue = Math.floor rec.value * .75
else if rec.packageprice.includes '$'
rec.gbpvalue = Math.floor rec.value * .77
rec.usdvalue = Math.floor rec.value
else
rec.gbpvalue = Math.floor rec.value
rec.usdvalue = Math.floor rec.value * 1.3
rec.usdvalue ?= ''
try rec.years = '2013' if rec.years is '2103' # fix what is probably a typo
try delete rec.url if rec.shareurlpublicly.toLowerCase() isnt 'yes'
try delete rec.shareurlpublicly
try rec.collection = 'Unclassified' if rec.collection is ''
try
rec.carnegiebasicclassification = rec['2015carnegiebasicclassification']
delete rec['2015carnegiebasicclassification']
try
institutions[rec.institution] ?= {institution:rec.institution, deals:[], value:0, usdvalue:0, gbpvalue:0}
rdc = JSON.parse JSON.stringify rec
try delete rdc.institution
try
institutions[rec.institution].value += rec.value
institutions[rec.institution].gbpvalue += rec.gbpvalue
institutions[rec.institution].usdvalue += rec.usdvalue
institutions[rec.institution].deals.push rdc
insts = []
for i of institutions
insts.push institutions[i]
await @deal ''
await @deal.institution ''
await @deal recs
await @deal.institution insts
return retrieved: recs.length, institutions: insts.length
| true |
# get the big deal data from a sheet and expose it in a website
# https://docs.google.com/spreadsheets/d/e/2PACX-1vQ4frfBvvPOKKFhArpV7cRUG0aAbfGRy214y-xlDG_CsW7kNbL-e8tuRvh8y37F4xc8wjO6FK8SD6UT/pubhtml
# https://docs.google.com/spreadsheets/d/PI:KEY:<KEY>END_PI/edit
P.deal = _index: true, _prefix: false
P.deal.institution = _index: true, _prefix: false
P.deal.load = () ->
recs = await @src.google.sheets '1PI:KEY:<KEY>END_PI'
institutions = {}
for rec in recs
for tk in ['Institution', 'Publisher', 'Collection', 'Year(s)', 'Length of Agreement', 'Package Price', '2015 Carnegie Basic Classification', 'FTE', 'Source', 'URL', 'Share URL Publicly?', 'Notes']
tl = tk.toLowerCase().replace(/ /g, '').replace('?', '').replace('(','').replace(')','')
rec[tl] = rec[tk]
delete rec[tk]
try
rec.value = parseInt rec.packageprice.replace /[^0-9]/g, ''
if typeof rec.fte is 'string'
try
rec.fte = parseInt rec.fte
catch
delete rec.fte
if typeof rec.notes is 'string' and rec.notes.toLowerCase().includes 'canadian'
rec.gbpvalue = Math.floor rec.value * .57
rec.usdvalue = Math.floor rec.value * .75
else if rec.packageprice.includes '$'
rec.gbpvalue = Math.floor rec.value * .77
rec.usdvalue = Math.floor rec.value
else
rec.gbpvalue = Math.floor rec.value
rec.usdvalue = Math.floor rec.value * 1.3
rec.usdvalue ?= ''
try rec.years = '2013' if rec.years is '2103' # fix what is probably a typo
try delete rec.url if rec.shareurlpublicly.toLowerCase() isnt 'yes'
try delete rec.shareurlpublicly
try rec.collection = 'Unclassified' if rec.collection is ''
try
rec.carnegiebasicclassification = rec['2015carnegiebasicclassification']
delete rec['2015carnegiebasicclassification']
try
institutions[rec.institution] ?= {institution:rec.institution, deals:[], value:0, usdvalue:0, gbpvalue:0}
rdc = JSON.parse JSON.stringify rec
try delete rdc.institution
try
institutions[rec.institution].value += rec.value
institutions[rec.institution].gbpvalue += rec.gbpvalue
institutions[rec.institution].usdvalue += rec.usdvalue
institutions[rec.institution].deals.push rdc
insts = []
for i of institutions
insts.push institutions[i]
await @deal ''
await @deal.institution ''
await @deal recs
await @deal.institution insts
return retrieved: recs.length, institutions: insts.length
|
[
{
"context": " sslEnabled: false\n accessKeyId: 'x'\n secretAccessKey: 'x'\n region:",
"end": 2046,
"score": 0.8866257071495056,
"start": 2045,
"tag": "KEY",
"value": "x"
},
{
"context": " accessKeyId: 'x'\n secretAccessKey: 'x'\n ... | test/util.coffee | Ubix/node-dynamodb | 1 | magneto = require 'magneto'
# check if function threw an error
# call done with error when exception is not thrown
# use when task contains async function calls
exports.didThrow = (done, task) =>
try
task()
done new Error "did not throw: #{task.toString()}"
catch e
return
# use when task does not contain async function calls
exports.didThrowDone = (task) =>
return (done) =>
try
task()
done new Error "did not throw: #{task.toString()}"
catch e
done()
# check if function did not throw an error
# call done with error when exception is thrown
# use when task contains async function calls
exports.didNotThrow = (done, task) =>
try
task()
return
catch e
done new Error "did throw: #{task.toString()}"
# use when task does not contain async function calls
exports.didNotThrowDone = (task) =>
return (done) =>
try
task()
done()
catch e
done new Error "did throw: #{task.toString()}"
# execute task in try/catch block
# call done on error
# use when task contains async function calls
exports.tryCatch = (done, task) =>
try
task()
return
catch e
done e
# execute task in try/catch block and follow by done
# call done on error
# use when task does not contain async function calls
exports.tryCatchDone = (done, task) =>
try
task()
done()
catch e
done e
exports.expectError = (done) =>
return (err, res) =>
if err
done()
else
done new Error 'did not return error'
exports.expectNoError = (done) =>
return (err, res) =>
if err
done new Error 'did return error'
else
done()
# start magneto, then execute task followed by done
ddb = null
exports.before = (done, task) =>
set = (ddb) =>
exports.ddb = ddb
task?()
done? null, ddb
if ddb then set ddb
else
port = 4567
magneto.listen port, (err) =>
if err? then done? err
else
spec =
apiVersion: '2011-12-05' #'2012-08-10'
sslEnabled: false
accessKeyId: 'x'
secretAccessKey: 'x'
region: 'x'
endpoint: "http://localhost:#{port}"
ddb = require('../lib/ddb').ddb spec
set ddb
# perform cleanup, then execute task followed by done
exports.after = (done, task) =>
task?()
done?()
| 76509 | magneto = require 'magneto'
# check if function threw an error
# call done with error when exception is not thrown
# use when task contains async function calls
exports.didThrow = (done, task) =>
try
task()
done new Error "did not throw: #{task.toString()}"
catch e
return
# use when task does not contain async function calls
exports.didThrowDone = (task) =>
return (done) =>
try
task()
done new Error "did not throw: #{task.toString()}"
catch e
done()
# check if function did not throw an error
# call done with error when exception is thrown
# use when task contains async function calls
exports.didNotThrow = (done, task) =>
try
task()
return
catch e
done new Error "did throw: #{task.toString()}"
# use when task does not contain async function calls
exports.didNotThrowDone = (task) =>
return (done) =>
try
task()
done()
catch e
done new Error "did throw: #{task.toString()}"
# execute task in try/catch block
# call done on error
# use when task contains async function calls
exports.tryCatch = (done, task) =>
try
task()
return
catch e
done e
# execute task in try/catch block and follow by done
# call done on error
# use when task does not contain async function calls
exports.tryCatchDone = (done, task) =>
try
task()
done()
catch e
done e
exports.expectError = (done) =>
return (err, res) =>
if err
done()
else
done new Error 'did not return error'
exports.expectNoError = (done) =>
return (err, res) =>
if err
done new Error 'did return error'
else
done()
# start magneto, then execute task followed by done
ddb = null
exports.before = (done, task) =>
set = (ddb) =>
exports.ddb = ddb
task?()
done? null, ddb
if ddb then set ddb
else
port = 4567
magneto.listen port, (err) =>
if err? then done? err
else
spec =
apiVersion: '2011-12-05' #'2012-08-10'
sslEnabled: false
accessKeyId: '<KEY>'
secretAccessKey: '<KEY>'
region: 'x'
endpoint: "http://localhost:#{port}"
ddb = require('../lib/ddb').ddb spec
set ddb
# perform cleanup, then execute task followed by done
exports.after = (done, task) =>
task?()
done?()
| true | magneto = require 'magneto'
# check if function threw an error
# call done with error when exception is not thrown
# use when task contains async function calls
exports.didThrow = (done, task) =>
try
task()
done new Error "did not throw: #{task.toString()}"
catch e
return
# use when task does not contain async function calls
exports.didThrowDone = (task) =>
return (done) =>
try
task()
done new Error "did not throw: #{task.toString()}"
catch e
done()
# check if function did not throw an error
# call done with error when exception is thrown
# use when task contains async function calls
exports.didNotThrow = (done, task) =>
try
task()
return
catch e
done new Error "did throw: #{task.toString()}"
# use when task does not contain async function calls
exports.didNotThrowDone = (task) =>
return (done) =>
try
task()
done()
catch e
done new Error "did throw: #{task.toString()}"
# execute task in try/catch block
# call done on error
# use when task contains async function calls
exports.tryCatch = (done, task) =>
try
task()
return
catch e
done e
# execute task in try/catch block and follow by done
# call done on error
# use when task does not contain async function calls
exports.tryCatchDone = (done, task) =>
try
task()
done()
catch e
done e
exports.expectError = (done) =>
return (err, res) =>
if err
done()
else
done new Error 'did not return error'
exports.expectNoError = (done) =>
return (err, res) =>
if err
done new Error 'did return error'
else
done()
# start magneto, then execute task followed by done
ddb = null
exports.before = (done, task) =>
set = (ddb) =>
exports.ddb = ddb
task?()
done? null, ddb
if ddb then set ddb
else
port = 4567
magneto.listen port, (err) =>
if err? then done? err
else
spec =
apiVersion: '2011-12-05' #'2012-08-10'
sslEnabled: false
accessKeyId: 'PI:KEY:<KEY>END_PI'
secretAccessKey: 'PI:KEY:<KEY>END_PI'
region: 'x'
endpoint: "http://localhost:#{port}"
ddb = require('../lib/ddb').ddb spec
set ddb
# perform cleanup, then execute task followed by done
exports.after = (done, task) =>
task?()
done?()
|
[
{
"context": "# Copyright (c) 2018 Natalie Marleny\n# Casing - UI framework for Framer\n# License: MIT",
"end": 36,
"score": 0.9998875260353088,
"start": 21,
"tag": "NAME",
"value": "Natalie Marleny"
},
{
"context": "r Framer\n# License: MIT\n# URL: https://github.com/nataliemarleny/... | FrmrTextInput.coffee | nataliemarleny/Casing | 84 | # Copyright (c) 2018 Natalie Marleny
# Casing - UI framework for Framer
# License: MIT
# URL: https://github.com/nataliemarleny/Casing
# Modified code, originally from: https://github.com/ajimix/Input-Framer
# Thank you ajimix for the amazing code - you rock!
# Extends the LayerStyle class which does the pixel ratio calculations in framer
_inputStyle =
Object.assign({}, Framer.LayerStyle,
calculatePixelRatio = (layer, value) ->
(value * layer.context.pixelMultiplier) + "px"
fontSize: (layer) ->
calculatePixelRatio(layer, layer._properties.fontSize)
lineHeight: (layer) ->
(layer._properties.lineHeight) + "em"
padding: (layer) ->
{ pixelMultiplier } = layer.context
padding = []
paddingValue = layer._properties.padding
# Check if we have a single number as integer
if Number.isInteger(paddingValue)
return calculatePixelRatio(layer, paddingValue)
# If we have multiple values they come as string (e.g. "1 2 3 4")
paddingValues = layer._properties.padding.split(" ")
switch paddingValues.length
when 4
padding.top = parseFloat(paddingValues[0])
padding.right = parseFloat(paddingValues[1])
padding.bottom = parseFloat(paddingValues[2])
padding.left = parseFloat(paddingValues[3])
when 3
padding.top = parseFloat(paddingValues[0])
padding.right = parseFloat(paddingValues[1])
padding.bottom = parseFloat(paddingValues[2])
padding.left = parseFloat(paddingValues[1])
when 2
padding.top = parseFloat(paddingValues[0])
padding.right = parseFloat(paddingValues[1])
padding.bottom = parseFloat(paddingValues[0])
padding.left = parseFloat(paddingValues[1])
else
padding.top = parseFloat(paddingValues[0])
padding.right = parseFloat(paddingValues[0])
padding.bottom = parseFloat(paddingValues[0])
padding.left = parseFloat(paddingValues[0])
# Return as 4-value string (e.g "1px 2px 3px 4px")
"#{padding.top * pixelMultiplier}px #{padding.right * pixelMultiplier}px #{padding.bottom * pixelMultiplier}px #{padding.left * pixelMultiplier}px"
)
class exports.FrmrTextInput extends Layer
constructor: (options = {}) ->
_.defaults options,
width: Screen.width / 2
height: 60
backgroundColor: "white"
fontSize: 30
lineHeight: 1
padding: 10
text: ""
placeholder: ""
type: "text"
autoCorrect: true
autoComplete: true
autoCapitalize: true
spellCheck: true
autofocus: false
textColor: "#000"
fontFamily: "-apple-system"
fontWeight: "500"
tabIndex: 0
textarea: false
enabled: true
super options
# Add additional properties
@_properties.fontSize = options.fontSize
@_properties.lineHeight = options.lineHeight
@_properties.padding = options.padding
@placeholderColor = options.placeholderColor if options.placeholderColor?
@input = document.createElement if options.textarea then 'textarea' else 'input'
@input.id = "input-#{_.now()}"
# Add styling to the input element
_.assign @input.style,
width: _inputStyle["width"](@)
height: _inputStyle["height"](@)
fontSize: _inputStyle["fontSize"](@)
lineHeight: _inputStyle["lineHeight"](@)
outline: "none"
border: "none"
backgroundColor: options.backgroundColor
padding: _inputStyle["padding"](@)
fontFamily: options.fontFamily
color: options.textColor
fontWeight: options.fontWeight
_.assign @input,
value: options.text
type: options.type
placeholder: options.placeholder
@input.setAttribute "tabindex", options.tabindex
@input.setAttribute "autocorrect", if options.autoCorrect then "on" else "off"
@input.setAttribute "autocomplete", if options.autoComplete then "on" else "off"
@input.setAttribute "autocapitalize", if options.autoCapitalize then "on" else "off"
@input.setAttribute "spellcheck", if options.spellCheck then "on" else "off"
if not options.enabled
@input.setAttribute "disabled", true
if options.autofocus
@input.setAttribute "autofocus", true
@form = document.createElement "form"
@form.appendChild @input
@_element.appendChild @form
@backgroundColor = "transparent"
@updatePlaceholderColor options.placeholderColor if @placeholderColor
@define "style",
get: -> @input.style
set: (value) ->
_.extend @input.style, value
@define "value",
get: -> @input.value
set: (value) ->
@input.value = value
updatePlaceholderColor: (color) ->
@placeholderColor = color
if @pageStyle?
document.head.removeChild @pageStyle
@pageStyle = document.createElement "style"
@pageStyle.type = "text/css"
css = "##{@input.id}::-webkit-input-placeholder { color: #{@placeholderColor}; }"
@pageStyle.appendChild(document.createTextNode css)
document.head.appendChild @pageStyle
focus: () ->
@input.focus()
unfocus: () ->
@input.blur()
onFocus: (cb) ->
@input.addEventListener "focus", ->
cb.apply(@)
onUnfocus: (cb) ->
@input.addEventListener "blur", ->
cb.apply(@)
disable: () ->
@input.setAttribute "disabled", true
enable: () =>
@input.removeAttribute "disabled", true
| 186253 | # Copyright (c) 2018 <NAME>
# Casing - UI framework for Framer
# License: MIT
# URL: https://github.com/nataliemarleny/Casing
# Modified code, originally from: https://github.com/ajimix/Input-Framer
# Thank you ajimix for the amazing code - you rock!
# Extends the LayerStyle class which does the pixel ratio calculations in framer
_inputStyle =
Object.assign({}, Framer.LayerStyle,
calculatePixelRatio = (layer, value) ->
(value * layer.context.pixelMultiplier) + "px"
fontSize: (layer) ->
calculatePixelRatio(layer, layer._properties.fontSize)
lineHeight: (layer) ->
(layer._properties.lineHeight) + "em"
padding: (layer) ->
{ pixelMultiplier } = layer.context
padding = []
paddingValue = layer._properties.padding
# Check if we have a single number as integer
if Number.isInteger(paddingValue)
return calculatePixelRatio(layer, paddingValue)
# If we have multiple values they come as string (e.g. "1 2 3 4")
paddingValues = layer._properties.padding.split(" ")
switch paddingValues.length
when 4
padding.top = parseFloat(paddingValues[0])
padding.right = parseFloat(paddingValues[1])
padding.bottom = parseFloat(paddingValues[2])
padding.left = parseFloat(paddingValues[3])
when 3
padding.top = parseFloat(paddingValues[0])
padding.right = parseFloat(paddingValues[1])
padding.bottom = parseFloat(paddingValues[2])
padding.left = parseFloat(paddingValues[1])
when 2
padding.top = parseFloat(paddingValues[0])
padding.right = parseFloat(paddingValues[1])
padding.bottom = parseFloat(paddingValues[0])
padding.left = parseFloat(paddingValues[1])
else
padding.top = parseFloat(paddingValues[0])
padding.right = parseFloat(paddingValues[0])
padding.bottom = parseFloat(paddingValues[0])
padding.left = parseFloat(paddingValues[0])
# Return as 4-value string (e.g "1px 2px 3px 4px")
"#{padding.top * pixelMultiplier}px #{padding.right * pixelMultiplier}px #{padding.bottom * pixelMultiplier}px #{padding.left * pixelMultiplier}px"
)
class exports.FrmrTextInput extends Layer
constructor: (options = {}) ->
_.defaults options,
width: Screen.width / 2
height: 60
backgroundColor: "white"
fontSize: 30
lineHeight: 1
padding: 10
text: ""
placeholder: ""
type: "text"
autoCorrect: true
autoComplete: true
autoCapitalize: true
spellCheck: true
autofocus: false
textColor: "#000"
fontFamily: "-apple-system"
fontWeight: "500"
tabIndex: 0
textarea: false
enabled: true
super options
# Add additional properties
@_properties.fontSize = options.fontSize
@_properties.lineHeight = options.lineHeight
@_properties.padding = options.padding
@placeholderColor = options.placeholderColor if options.placeholderColor?
@input = document.createElement if options.textarea then 'textarea' else 'input'
@input.id = "input-#{_.now()}"
# Add styling to the input element
_.assign @input.style,
width: _inputStyle["width"](@)
height: _inputStyle["height"](@)
fontSize: _inputStyle["fontSize"](@)
lineHeight: _inputStyle["lineHeight"](@)
outline: "none"
border: "none"
backgroundColor: options.backgroundColor
padding: _inputStyle["padding"](@)
fontFamily: options.fontFamily
color: options.textColor
fontWeight: options.fontWeight
_.assign @input,
value: options.text
type: options.type
placeholder: options.placeholder
@input.setAttribute "tabindex", options.tabindex
@input.setAttribute "autocorrect", if options.autoCorrect then "on" else "off"
@input.setAttribute "autocomplete", if options.autoComplete then "on" else "off"
@input.setAttribute "autocapitalize", if options.autoCapitalize then "on" else "off"
@input.setAttribute "spellcheck", if options.spellCheck then "on" else "off"
if not options.enabled
@input.setAttribute "disabled", true
if options.autofocus
@input.setAttribute "autofocus", true
@form = document.createElement "form"
@form.appendChild @input
@_element.appendChild @form
@backgroundColor = "transparent"
@updatePlaceholderColor options.placeholderColor if @placeholderColor
@define "style",
get: -> @input.style
set: (value) ->
_.extend @input.style, value
@define "value",
get: -> @input.value
set: (value) ->
@input.value = value
updatePlaceholderColor: (color) ->
@placeholderColor = color
if @pageStyle?
document.head.removeChild @pageStyle
@pageStyle = document.createElement "style"
@pageStyle.type = "text/css"
css = "##{@input.id}::-webkit-input-placeholder { color: #{@placeholderColor}; }"
@pageStyle.appendChild(document.createTextNode css)
document.head.appendChild @pageStyle
focus: () ->
@input.focus()
unfocus: () ->
@input.blur()
onFocus: (cb) ->
@input.addEventListener "focus", ->
cb.apply(@)
onUnfocus: (cb) ->
@input.addEventListener "blur", ->
cb.apply(@)
disable: () ->
@input.setAttribute "disabled", true
enable: () =>
@input.removeAttribute "disabled", true
| true | # Copyright (c) 2018 PI:NAME:<NAME>END_PI
# Casing - UI framework for Framer
# License: MIT
# URL: https://github.com/nataliemarleny/Casing
# Modified code, originally from: https://github.com/ajimix/Input-Framer
# Thank you ajimix for the amazing code - you rock!
# Extends the LayerStyle class which does the pixel ratio calculations in framer
_inputStyle =
Object.assign({}, Framer.LayerStyle,
calculatePixelRatio = (layer, value) ->
(value * layer.context.pixelMultiplier) + "px"
fontSize: (layer) ->
calculatePixelRatio(layer, layer._properties.fontSize)
lineHeight: (layer) ->
(layer._properties.lineHeight) + "em"
padding: (layer) ->
{ pixelMultiplier } = layer.context
padding = []
paddingValue = layer._properties.padding
# Check if we have a single number as integer
if Number.isInteger(paddingValue)
return calculatePixelRatio(layer, paddingValue)
# If we have multiple values they come as string (e.g. "1 2 3 4")
paddingValues = layer._properties.padding.split(" ")
switch paddingValues.length
when 4
padding.top = parseFloat(paddingValues[0])
padding.right = parseFloat(paddingValues[1])
padding.bottom = parseFloat(paddingValues[2])
padding.left = parseFloat(paddingValues[3])
when 3
padding.top = parseFloat(paddingValues[0])
padding.right = parseFloat(paddingValues[1])
padding.bottom = parseFloat(paddingValues[2])
padding.left = parseFloat(paddingValues[1])
when 2
padding.top = parseFloat(paddingValues[0])
padding.right = parseFloat(paddingValues[1])
padding.bottom = parseFloat(paddingValues[0])
padding.left = parseFloat(paddingValues[1])
else
padding.top = parseFloat(paddingValues[0])
padding.right = parseFloat(paddingValues[0])
padding.bottom = parseFloat(paddingValues[0])
padding.left = parseFloat(paddingValues[0])
# Return as 4-value string (e.g "1px 2px 3px 4px")
"#{padding.top * pixelMultiplier}px #{padding.right * pixelMultiplier}px #{padding.bottom * pixelMultiplier}px #{padding.left * pixelMultiplier}px"
)
class exports.FrmrTextInput extends Layer
constructor: (options = {}) ->
_.defaults options,
width: Screen.width / 2
height: 60
backgroundColor: "white"
fontSize: 30
lineHeight: 1
padding: 10
text: ""
placeholder: ""
type: "text"
autoCorrect: true
autoComplete: true
autoCapitalize: true
spellCheck: true
autofocus: false
textColor: "#000"
fontFamily: "-apple-system"
fontWeight: "500"
tabIndex: 0
textarea: false
enabled: true
super options
# Add additional properties
@_properties.fontSize = options.fontSize
@_properties.lineHeight = options.lineHeight
@_properties.padding = options.padding
@placeholderColor = options.placeholderColor if options.placeholderColor?
@input = document.createElement if options.textarea then 'textarea' else 'input'
@input.id = "input-#{_.now()}"
# Add styling to the input element
_.assign @input.style,
width: _inputStyle["width"](@)
height: _inputStyle["height"](@)
fontSize: _inputStyle["fontSize"](@)
lineHeight: _inputStyle["lineHeight"](@)
outline: "none"
border: "none"
backgroundColor: options.backgroundColor
padding: _inputStyle["padding"](@)
fontFamily: options.fontFamily
color: options.textColor
fontWeight: options.fontWeight
_.assign @input,
value: options.text
type: options.type
placeholder: options.placeholder
@input.setAttribute "tabindex", options.tabindex
@input.setAttribute "autocorrect", if options.autoCorrect then "on" else "off"
@input.setAttribute "autocomplete", if options.autoComplete then "on" else "off"
@input.setAttribute "autocapitalize", if options.autoCapitalize then "on" else "off"
@input.setAttribute "spellcheck", if options.spellCheck then "on" else "off"
if not options.enabled
@input.setAttribute "disabled", true
if options.autofocus
@input.setAttribute "autofocus", true
@form = document.createElement "form"
@form.appendChild @input
@_element.appendChild @form
@backgroundColor = "transparent"
@updatePlaceholderColor options.placeholderColor if @placeholderColor
@define "style",
get: -> @input.style
set: (value) ->
_.extend @input.style, value
@define "value",
get: -> @input.value
set: (value) ->
@input.value = value
updatePlaceholderColor: (color) ->
@placeholderColor = color
if @pageStyle?
document.head.removeChild @pageStyle
@pageStyle = document.createElement "style"
@pageStyle.type = "text/css"
css = "##{@input.id}::-webkit-input-placeholder { color: #{@placeholderColor}; }"
@pageStyle.appendChild(document.createTextNode css)
document.head.appendChild @pageStyle
focus: () ->
@input.focus()
unfocus: () ->
@input.blur()
onFocus: (cb) ->
@input.addEventListener "focus", ->
cb.apply(@)
onUnfocus: (cb) ->
@input.addEventListener "blur", ->
cb.apply(@)
disable: () ->
@input.setAttribute "disabled", true
enable: () =>
@input.removeAttribute "disabled", true
|
[
{
"context": ".logger.info req.body\n ###\n {\n token: \"robot's token\"\n ts: 1355517523\n text: \"!baike 中国\"\n ",
"end": 879,
"score": 0.6589366793632507,
"start": 866,
"tag": "PASSWORD",
"value": "robot's token"
},
{
"context": " channel_name: 'your_chann... | lib/bearychat.coffee | timnew/hutbot-bearychat | 5 | # Hubot dependencies
{Robot, Adapter, TextMessage, Response, User} = require 'hubot'
url = require('url')
class BearyChat extends Adapter
run: ->
@configChatOutgoing()
@configChatIncomming()
@robot.logger.info "#{@robot.name} is online."
@send {}, "#{@robot.name} is online."
@emit 'connected'
configChatOutgoing: ->
parsedUrl = url.parse(process.env.BEARY_CHAT_OUTGOING || '/bearychat/outgoing')
if parsedUrl.protocol? and parsedUrl.protocol != 'https:'
ex = new Error('Chat Outgoing must be https')
@robot.logger.error(ex)
throw ex
@bearyChatOutgoing = parsedUrl.path
@robot.router.post @bearyChatOutgoing, @outgoingRoute
@robot.logger.info('Register Bearychat Outgoing route: %s', @bearyChatOutgoing)
outgoingRoute: (req, res) =>
@robot.logger.info req.body
###
{
token: "robot's token"
ts: 1355517523
text: "!baike 中国"
trigger_word: "!baike"
subdomain: 'your_domain'
channel_name: 'your_channel'
user_name: 'your_name'
}
###
incomingMessage = req.body
user = new User(req.body.user_name)
@receive new TextMessage(user, incomingMessage.text)
res.status(200).end()
configChatIncomming: ->
@bearyChatIncoming = process.env.BEARY_CHAT_INCOMING
unless @bearyChatIncoming?
ex = new Error('bearyChatIncoming is not set')
@robot.logger.error(ex)
throw ex
@robot.logger.info('Register Bearychat Incomming route: %s', @bearyChatIncoming)
send: (user, strings...) ->
@robot.logger.info 'Send message', strings...
message = JSON.stringify
text: strings.join('\n')
@robot.http(@bearyChatIncoming)
.header('Content-Type', 'application/json')
.post(message) (err, res, body) =>
@robot.logger.info body
reply: (user, strings...) ->
@send user, strings...
exports.use = (robot) ->
new BearyChat robot
| 45771 | # Hubot dependencies
{Robot, Adapter, TextMessage, Response, User} = require 'hubot'
url = require('url')
class BearyChat extends Adapter
run: ->
@configChatOutgoing()
@configChatIncomming()
@robot.logger.info "#{@robot.name} is online."
@send {}, "#{@robot.name} is online."
@emit 'connected'
configChatOutgoing: ->
parsedUrl = url.parse(process.env.BEARY_CHAT_OUTGOING || '/bearychat/outgoing')
if parsedUrl.protocol? and parsedUrl.protocol != 'https:'
ex = new Error('Chat Outgoing must be https')
@robot.logger.error(ex)
throw ex
@bearyChatOutgoing = parsedUrl.path
@robot.router.post @bearyChatOutgoing, @outgoingRoute
@robot.logger.info('Register Bearychat Outgoing route: %s', @bearyChatOutgoing)
outgoingRoute: (req, res) =>
@robot.logger.info req.body
###
{
token: "<PASSWORD>"
ts: 1355517523
text: "!baike 中国"
trigger_word: "!baike"
subdomain: 'your_domain'
channel_name: 'your_channel'
user_name: 'your_name'
}
###
incomingMessage = req.body
user = new User(req.body.user_name)
@receive new TextMessage(user, incomingMessage.text)
res.status(200).end()
configChatIncomming: ->
@bearyChatIncoming = process.env.BEARY_CHAT_INCOMING
unless @bearyChatIncoming?
ex = new Error('bearyChatIncoming is not set')
@robot.logger.error(ex)
throw ex
@robot.logger.info('Register Bearychat Incomming route: %s', @bearyChatIncoming)
send: (user, strings...) ->
@robot.logger.info 'Send message', strings...
message = JSON.stringify
text: strings.join('\n')
@robot.http(@bearyChatIncoming)
.header('Content-Type', 'application/json')
.post(message) (err, res, body) =>
@robot.logger.info body
reply: (user, strings...) ->
@send user, strings...
exports.use = (robot) ->
new BearyChat robot
| true | # Hubot dependencies
{Robot, Adapter, TextMessage, Response, User} = require 'hubot'
url = require('url')
class BearyChat extends Adapter
run: ->
@configChatOutgoing()
@configChatIncomming()
@robot.logger.info "#{@robot.name} is online."
@send {}, "#{@robot.name} is online."
@emit 'connected'
configChatOutgoing: ->
parsedUrl = url.parse(process.env.BEARY_CHAT_OUTGOING || '/bearychat/outgoing')
if parsedUrl.protocol? and parsedUrl.protocol != 'https:'
ex = new Error('Chat Outgoing must be https')
@robot.logger.error(ex)
throw ex
@bearyChatOutgoing = parsedUrl.path
@robot.router.post @bearyChatOutgoing, @outgoingRoute
@robot.logger.info('Register Bearychat Outgoing route: %s', @bearyChatOutgoing)
outgoingRoute: (req, res) =>
@robot.logger.info req.body
###
{
token: "PI:PASSWORD:<PASSWORD>END_PI"
ts: 1355517523
text: "!baike 中国"
trigger_word: "!baike"
subdomain: 'your_domain'
channel_name: 'your_channel'
user_name: 'your_name'
}
###
incomingMessage = req.body
user = new User(req.body.user_name)
@receive new TextMessage(user, incomingMessage.text)
res.status(200).end()
configChatIncomming: ->
@bearyChatIncoming = process.env.BEARY_CHAT_INCOMING
unless @bearyChatIncoming?
ex = new Error('bearyChatIncoming is not set')
@robot.logger.error(ex)
throw ex
@robot.logger.info('Register Bearychat Incomming route: %s', @bearyChatIncoming)
send: (user, strings...) ->
@robot.logger.info 'Send message', strings...
message = JSON.stringify
text: strings.join('\n')
@robot.http(@bearyChatIncoming)
.header('Content-Type', 'application/json')
.post(message) (err, res, body) =>
@robot.logger.info body
reply: (user, strings...) ->
@send user, strings...
exports.use = (robot) ->
new BearyChat robot
|
[
{
"context": "->\n kv =\n '''\n \"Call me Ishmael. Some years ago --\n never mind how l",
"end": 8193,
"score": 0.9994717836380005,
"start": 8186,
"tag": "NAME",
"value": "Ishmael"
},
{
"context": "\n world...\"\n ''' : '\... | test/translator.coffee | hu2prod/scriptscript | 1 | assert = require 'assert'
util = require 'fy/test_util'
{_tokenize} = require '../src/tokenizer'
{_parse } = require '../src/grammar'
{_translate, translate} = require '../src/translator'
{_type_inference} = require '../src/type_inference'
full = (t)->
tok = _tokenize(t)
ast = _parse(tok, mode_full:true)
_type_inference ast[0], {}
_translate ast[0], {}
{go} = require '../src/index'
describe 'translator section', ()->
sample_list = """
a
1
1.0
1e6
0x1
0777
(a)
+a
-a
~a
!a
[]
[1]
[1,2]
[a]
{}
{a:1}
a ? b : c
""".split /\n/g #"
for sample in sample_list
do (sample)->
it JSON.stringify(sample), ()->
assert.equal full(sample), sample
# ensure bracket
kv =
'((a))': '(a)'
'((a)+(b))': '((a)+(b))'
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
# bracketed
sample_list = """
typeof a
new a
delete a
a++
a--
""".split /\n/g
for sample in sample_list
do (sample)->
it JSON.stringify(sample), ()->
assert.equal full(sample), "(#{sample})"
describe "bin op", ()->
sample_list = """
a+b
a=b
a<b
a<=b
a>b
a>=b
2*2
2/2
2%2
2<<2
2>>2
2>>>2
""".split /\n/g
for sample in sample_list
do (sample)->
it JSON.stringify(sample), ()->
assert.equal full(sample), "(#{sample})"
kv =
"1**2" : "Math.pow(1, 2)"
"1//2" : "Math.floor(1 / 2)"
"1%%2" : "(_tmp_b=2,(1 % _tmp_b + _tmp_b) % _tmp_b)"
"true and false" : "(true&&false)"
"1 and 2" : "(1&2)"
"true or false" : "(true||false)"
"1 or 2" : "(1|2)"
"true xor false" : "(!!(true^false))"
"1 xor 2" : "(1^2)"
"a**=2" : "a = Math.pow(a, 2)"
"a//=2" : "a = Math.floor(a / 2)"
"a%%=2" : "a = (function(a, b){return (a % b + b) % b})(a, 2)"
"a%%=2" : "a = (_tmp_b=2,(a % _tmp_b + _tmp_b) % _tmp_b)"
"a==b" : "(a===b)"
"a!=b" : "(a!==b)"
"""a = true
a and= false""" : """(a=true);
(a=(a&&false))"""
"""a = 2
a and= 3""" : """(a=2);
(a&=3)"""
"""a = true
a or= false""" : """(a=true);
(a=(a||false))"""
"""a = 2
a or= 3""" : """(a=2);
(a|=3)"""
"""a = true
a xor= false""" : """(a=true);
(a=!!(a^false))"""
"""a = 2
a xor= 3""" : """(a=2);
(a^=3)"""
# "a and= 2" : "(1&=2)"
# "a or= false" : "(true||=false)"
# "a or= 2" : "(1|=2)"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
# kv =
# for k,v of kv
# do (k,v)->
# it JSON.stringify(k)
sample_list = """
a and b
a or b
2 and 3.5
2.2 or 5.8
false and 4
2 or true
'a' and 'b'
false or 8
null and /ab+c/i
7 xor 7.8
5 xor true
undefined xor null
""".split /\n/g
sample_list.append [
"""a=5.8
a or= 3"""
"""a=5
a and= 3.8"""
"""a='a'
a or= /ab+c/i"""
]
for sample in sample_list
do (sample)->
it JSON.stringify(sample) + " throws", ()->
util.throws ()->
full(sample)
describe "pre op", ()->
kv =
"void a" : "null"
"not true": "!true"
"not 1" : "~1"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
sample_list = """
not a
not 'a'
not 1.5
""".split /\n/g
for sample in sample_list
do (sample)->
it JSON.stringify(sample) + " throws", ()->
util.throws ()->
full(sample)
# ###################################################################################################
# STRINGS
# ###################################################################################################
describe "strings", ()->
describe "non-interpolated", ()->
kv =
'""' : '""'
'"abcd"' : '"abcd"'
'"\\""' : '"\\""'
'"\\a"' : '"\\a"'
"''" : '""'
"'abcd'" : '"abcd"'
"'\"'" : '"\\""'
"'\"\"'" : '"\\"\\""'
'""""""' : '""'
"''''''" : '""'
'"""abcd"""' : '"abcd"'
"'''abcd'''" : '"abcd"'
'""" " """' : '" \\" "'
'""" "" """' : '" \\"\\" "'
"'''\"'''" : '"\\""'
"'''\"\"'''" : '"\\"\\""'
"'a\#{b}c'" : '"a\#{b}c"'
"'''a\#{b}c'''" : '"a\#{b}c"'
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
sample_list = """
'''a\#{b}'
'a\#{b}'''
""".split '\n'
for sample in sample_list
do (sample)->
it "#{sample} throws", ()->
util.throws ()->
full(sample)
describe "interpolated", ()->
kv =
'"a#{b+c}d"' : '("a"+(b+c)+"d")'
'"a#{b+c}d#{e+f}g"' : '("a"+(b+c)+"d"+(e+f)+"g")'
'"a#{b+c}d#{e+f}g#{h+i}j"' : '("a"+(b+c)+"d"+(e+f)+"g"+(h+i)+"j")'
'"a{} #{b+c} {} #d"' : '("a{} "+(b+c)+" {} #d")'
'"a{ #{b+c} } # #{d} } #d"' : '("a{ "+(b+c)+" } # "+(d)+" } #d")'
'"""a#{b}c"""' : '("a"+(b)+"c")'
"'''a\#{b}c'''" : '"a#{b}c"'
'"a\\#{#{b}c"' : '("a\\#{"+(b)+"c")'
'"a\\#{a}#{b}c"' : '("a\\#{a}"+(b)+"c")'
'"#{}"' : '("")'
'"a#{}"' : '("a")'
'"#{}b"' : '("b")'
'"a#{}b"' : '("ab")'
'"#{}#{}"' : '("")'
'"#{}#{}#{}"' : '("")'
'"#{}#{}#{}#{}"' : '("")'
'"a#{}#{}"' : '("a")'
'"#{1}#{}"' : '(""+(1))'
'"#{}b#{}"' : '("b")'
'"#{}#{2}"' : '(""+(2))'
'"#{}#{}c"' : '("c")'
'"a#{1}#{}"' : '("a"+(1))'
'"a#{}b#{}"' : '("ab")'
'"a#{}#{2}"' : '("a"+(2))'
'"a#{}#{}c"' : '("ac")'
'"#{1}b#{}"' : '(""+(1)+"b")'
'"#{1}#{2}"' : '(""+(1)+(2))'
'"#{1}#{}c"' : '(""+(1)+"c")'
'"#{1}#{2}c"' : '(""+(1)+(2)+"c")'
'"#{1}b#{}c"' : '(""+(1)+"bc")'
'"a#{1}b#{}c"' : '("a"+(1)+"bc")'
'"a#{}b#{}c"' : '("abc")'
'"#{2+2}#{3-8}"' : '(""+(2+2)+(3-8))'
'"a#{-8}"' : '("a"+(-8))'
'"#{[]}"' : '(""+([]))'
'"""a#{2+2}b"""' : '("a"+(2+2)+"b")'
'""" " #{1}"""' : '(" \\" "+(1))' # double quoute escaped
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
describe "fuckups", ()->
fuckups =
'"#{5 #comment}"' : '(""+(5))'
'"#{5 #{comment}"' : '(""+(5))'
for k, v of fuckups
do (k, v)->
it "#{k} -> #{v}"
sample_list = '''
"""a#{b}"
"a#{b}"""
"a#{{}}"
'''.split '\n'
# Note that "#{{}}" is valid IcedCoffeeScript (though "#{{{}}}" isn't)
for sample in sample_list
do (sample)->
it "#{sample} throws", ()->
util.throws ()->
full(sample)
describe "multiline", ->
kv =
'''
"Call me Ishmael. Some years ago --
never mind how long precisely -- having little
or no money in my purse, and nothing particular
to interest me on shore, I thought I would sail
about a little and see the watery part of the
world..."
''' : '"Call me Ishmael. Some years ago -- never mind how long precisely -- having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world..."'
'''
'Call me Ishmael. Some years ago --
never mind how long precisely -- having little
or no money in my purse, and nothing particular
to interest me on shore, I thought I would sail
about a little and see the watery part of the
world...'
''' : '"Call me Ishmael. Some years ago -- never mind how long precisely -- having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world..."'
'''
"
"
''' : '""'
'''
'
'
''' : '""'
'''
"
abcd
efgh
"
''' : '"abcd efgh"'
'''
'
abcd
efgh
'
''' : '"abcd efgh"'
'''
"
abcd
#{3+3}
efgh
#{5+5}
ijkl
"
''' : '("abcd "+(3+3)+" efgh "+(5+5)+" ijkl")'
'''
"
#{3+3}
efgh
#{5+5}
ijkl
"
''' : '(""+(3+3)+" efgh "+(5+5)+" ijkl")'
'''
"
abcd
#{3+3}
#{5+5}
ijkl
"
''' : '("abcd "+(3+3)+" "+(5+5)+" ijkl")'
'''
"
abcd
#{3+3}
#{5+5}
"
''' : '("abcd "+(3+3)+" "+(5+5))'
'''
"
#{3+3}
"
''' : '(""+(3+3))'
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
describe "heredoc", ->
kv =
'''"""abc
def"""''' : '"abc\\ndef"'
"""'''abc
def'''""" : '"abc\\ndef"'
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
describe "+strings", ->
kv =
'+"123"' : '+"123"'
"+'123'" : '+"123"'
'+"""123"""' : '+"123"'
"+'''123'''" : '+"123"'
'+"#{123}"' : '+(""+(123))'
'+"#{41*3}"' : '+(""+(41*3))'
'+"12#{3}"' : '+("12"+(3))'
'+"12#{1+2}"' : '+("12"+(1+2))'
'+"#{1}23"' : '+(""+(1)+"23")'
'+"#{1}2#{3}"': '+(""+(1)+"2"+(3))'
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
# ###################################################################################################
# REGEXP
# ###################################################################################################
describe "regexp", ()->
describe "non-interpolated", ()->
kv =
'/ab+c/iiiiiiiiiiiiiii' : '/ab+c/iiiiiiiiiiiiiii'
'///ab+c///i' : '/ab+c/i'
'//////' : '/(?:)/' # this is invalid IcedCoffeeScript
'/// / ///' : '/\\//' # escape forward slash
'/// / // ///' : '/\\/\\/\\//' # more forward slashes to be escaped
'/// a b + c ///' : '/ab+c/' # spaces to be ignored
'///\ta\tb\t+\tc\t///' : '/ab+c/' # tabs to be ignored as well
'///ab+c #comment///' : '/ab+c/' # comment
'///ab+c#omment///' : '/ab+c#omment/' # comments should be preceded by whitespace
'///ab+c \\#omment///' : '/ab+c\\#omment/'
'///[#]///' : '/[#]/'
'''///multiline
lalala
tratata///''' : '/multilinelalalatratata/'
'''///multiline
with # a comment
# and
some continuation
///''' : '/multilinewithsomecontinuation/'
'/// ///' : '/(?:)/' # O_O
'''///
///''' : '/(?:)/' # multiline O_O
'''/// # comment
///''' : '/(?:)/' # multiline O_O with comment
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
describe "interpolated", ()->
kv =
'///ab+c\\#{///' : '/ab+c\\#{/' # interpolation escaped
'///ab+c #comment #{2+2} de+f///' : 'RegExp("ab+c"+(2+2)+"de+f")'
'''///ab+c #comment #{2+2} de+f
another line # with a comment
# one more comment #{4+4}///''' : 'RegExp("ab+c"+(2+2)+"de+fanotherline"+(4+4))'
'///a#{1}b///i' : 'RegExp("a"+(1)+"b","i")'
'///a#{1}b///iiii' : 'RegExp("a"+(1)+"b","iiii")'
'///"#{}///' : 'RegExp("\\"")' # double quotes escaped
'////#{}///' : 'RegExp("/")' # forward slashes don't need to be escaped
# The following samples are borrowed from the string interpolation section:
'///a#{b+c}d///' : 'RegExp("a"+(b+c)+"d")'
'///a#{b+c}d#{e+f}g///' : 'RegExp("a"+(b+c)+"d"+(e+f)+"g")'
'///a#{b+c}d#{e+f}g#{h+i}j///' : 'RegExp("a"+(b+c)+"d"+(e+f)+"g"+(h+i)+"j")'
'///a{} #{b+c} {} #d///' : 'RegExp("a{}"+(b+c)+"{}")'
'///a{ #{b+c} } # #{d} } #d///' : 'RegExp("a{"+(b+c)+"}"+(d)+"}")'
'///a\\#{#{b}c///' : 'RegExp("a\\#{"+(b)+"c")'
'///a\\#{a}#{b}c///' : 'RegExp("a\\#{a}"+(b)+"c")'
'///#{}///' : 'RegExp("")' # this is invalid IcedCoffeeScript
'///a#{}///' : 'RegExp("a")'
'///#{}b///' : 'RegExp("b")'
'///a#{}b///' : 'RegExp("ab")'
'///#{}#{}///' : 'RegExp("")' # this is invalid IcedCoffeeScript
'///#{}#{}#{}///' : 'RegExp("")' # this is invalid IcedCoffeeScript
'///#{}#{}#{}#{}///' : 'RegExp("")' # this is invalid IcedCoffeeScript
'///a#{}#{}///' : 'RegExp("a")'
'///#{1}#{}///' : 'RegExp(""+(1))'
'///#{}b#{}///' : 'RegExp("b")'
'///#{}#{2}///' : 'RegExp(""+(2))'
'///#{}#{}c///' : 'RegExp("c")'
'///a#{1}#{}///' : 'RegExp("a"+(1))'
'///a#{}b#{}///' : 'RegExp("ab")'
'///a#{}#{2}///' : 'RegExp("a"+(2))'
'///a#{}#{}c///' : 'RegExp("ac")'
'///#{1}b#{}///' : 'RegExp(""+(1)+"b")'
'///#{1}#{2}///' : 'RegExp(""+(1)+(2))'
'///#{1}#{}c///' : 'RegExp(""+(1)+"c")'
'///#{1}#{2}c///' : 'RegExp(""+(1)+(2)+"c")'
'///#{1}b#{}c///' : 'RegExp(""+(1)+"bc")'
'///a#{1}b#{}c///' : 'RegExp("a"+(1)+"bc")'
'///a#{}b#{}c///' : 'RegExp("abc")'
'///#{2+2}#{3-8}///' : 'RegExp(""+(2+2)+(3-8))'
'///a#{-8}///' : 'RegExp("a"+(-8))'
'///#{[]}///' : 'RegExp(""+([]))'
for k, v of kv
do (k, v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
describe "invalid", ()->
sample_list = '''
/// ////
/// /// ///
///a#{{}}///
'''.split '\n'
# Note that "#{{}}" is valid IcedCoffeeScript (though "#{{{}}}" isn't)
for sample in sample_list
do (sample)->
it "#{sample} throws", ()->
util.throws ()->
full(sample)
# ###################################################################################################
describe "hash", ()->
kv =
"{a}" : "{a:a}"
"a:1" : "{a:1}"
"a:1,b:1" : "{a:1,b:1}"
"{\na:b\nc:d}": "{a:b,c:d}"
# "{(a):b}" : "(_t={},_t[a]=b,_t)"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
describe "array", ()->
kv =
"[\n]" : "[]"
"[\na\nb]" : "[a,b]"
"[0..0]" : "[0]"
"[0..2]" : "[0, 1, 2]"
"[0..20]" : "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]"
"[0..21]" : """
(function() {
var results = [];
for (var i = 0; i <= 21; i++){ results.push(i); }
return results;
})()
"""
"[20..0]" : "[20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]"
"[21..0]" : """
(function() {
var results = [];
for (var i = 21; i >= 0; i--){ results.push(i); }
return results;
})()
"""
"[2.5..4.8]" : "[2.5, 3.5, 4.5]"
"[4.5..1.8]" : "[4.5, 3.5, 2.5]"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
describe "comment", ()->
kv =
"#a" : "//a"
"a#a" : "a//a"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
describe "access", ()->
kv =
"a.b" : "a.b"
"a[b]" : "a[b]"
"a.0" : "a[0]"
"a.1" : "a[1]"
"a.01" : "[a[0],a[1]]"
"a.12" : "[a[1],a[2]]"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
describe "function decl", ()->
kv =
"->" : "(function(){})"
"->a" : """
(function(){
return(a)
})
"""
"()->" : "(function(){})"
"(a)->" : "(function(a){})"
"(a,b)->" : "(function(a, b){})"
"(a,b,c)->" : "(function(a, b, c){})"
"(a,b)->a+b" : """
(function(a, b){
return((a+b))
})
"""
"(a,b=1)->" : """
(function(a, b){
b=b==null?(1):b;
})"""
"(a,b=(1))->" : """
(function(a, b){
b=b==null?(1):b;
})"""
"(a,b=1):number->" : """
(function(a, b){
b=b==null?(1):b;
})"""
"(a)->a" : """
(function(a){
return(a)
})
"""
"(a)->\n a" : """
(function(a){
a
})
"""
"->\n a" : """
(function(){
a
})
"""
"""
->
a=1
b=a
""" : """
(function(){
(a=1);
(b=a)
})
"""
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
# TEMP same
k2 = k.replace "->", "=>"
it JSON.stringify(k2), ()->
assert.equal full(k2), v
# TEMP throws
kv =
"(a:number)->" : "(function(a){})"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
util.throws ()->
full(k)
describe "function call", ()->
kv =
"a(b)": "(a)(b)"
"a(b\n)": "(a)(b)"
# "a(\nb)": "(a)(b)" # BUG
"a(b,c)": "(a)(b, c)"
"a()": "(a)()"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
describe "macro-block", ()->
kv =
"""
if a
b
""" : """
if (a) {
b
}
"""
"""
while a
b
""" : """
while(a) {
b
}
"""
"""
loop
b
""" : """
while(true) {
b
}
"""
# LATER
# """
# c = if a
# b
# """ : """
# if (a) {
# c = b
# }
# """
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
sample_list =
"""
if
b
---
loop a
b
---
wtf a
b
---
wtf
b
""".split /\n?---\n?/
for v in sample_list
do (v)->
it JSON.stringify(v), ()->
util.throws ()->
full(v)
# TEMP impl tests
describe "pipeline", ()->
kv =
"""
[1] | a
""" : """
a = [1]
"""
"""
fn = (t)->t
[1] | fn
""" : """
(fn=(function(t){
return(t)
}));
([1]).map(fn)
"""
"""
fn = (t)->t
([1]) | fn
""" : """
(fn=(function(t){
return(t)
}));
([1]).map(fn)
"""
"""
fn = (t)->t
[1] | fn | b
""" : """
(fn=(function(t){
return(t)
}));
b = ([1]).map(fn)
"""
"""
b = []
fn = (t)->t
[1] | fn | b
""" : """
(b=[]);
(fn=(function(t){
return(t)
}));
b = ([1]).map(fn)
"""
"""
["Hello", "world"] | stdout
""" : """
var ref = (["Hello","world"]);
for (var i = 0, len = ref.length; i < len; i++) {
stdout(ref[i]);
}
"""
"""
[1] | ((a,b)->a+b) | c
""" : """
c = ([1]).reduce((function(a, b){
return((a+b))
}))
"""
# unsafe backet
# """
# [1] | (a,b)->a+b | c
# """ : """
# c = ([1]).reduce((function(a, b){
# return((a+b))
# }))
# """
# async
"""
[1] | ((a,cb)->cb(a)) | c
""" : """
c = ([1]).async_map((function(a, cb){
return((cb)(a))
}))
"""
"""
[1] | ((a,b,cb)->cb(a+b)) | c
""" : """
c = ([1]).async_reduce((function(a, b, cb){
return((cb)((a+b)))
}))
"""
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
sample_list =
"""
1 | a
---
a = 1
[1] | a
---
[1] | (()->1)
---
[1] | ((a,b,c)->a+b+c)
---
[1] | ((a,b,c)->a+b+c+1)
""".split /\n?---\n?/
for v in sample_list
do (v)->
it JSON.stringify(v), ()->
util.throws ()->
full(v)
it 'test translate exception', (done)->
await translate null, {}, defer(err)
assert err?
done()
it 'public endpoint should work', (done)->
await go 'a', {}, defer(err, res)
assert !(err?)
await go 'a КИРИЛИЦА', {}, defer(err, res)
assert err?
await go '1 or true', {}, defer(err, res)
assert err?
await go '1a1', {}, defer(err, res)
assert err?
# LATER not translated
# await go '1+"1"', {}, defer(err, res)
# assert err?
await go '__test_untranslated', {}, defer(err, res)
assert err?
done() | 112965 | assert = require 'assert'
util = require 'fy/test_util'
{_tokenize} = require '../src/tokenizer'
{_parse } = require '../src/grammar'
{_translate, translate} = require '../src/translator'
{_type_inference} = require '../src/type_inference'
full = (t)->
tok = _tokenize(t)
ast = _parse(tok, mode_full:true)
_type_inference ast[0], {}
_translate ast[0], {}
{go} = require '../src/index'
describe 'translator section', ()->
sample_list = """
a
1
1.0
1e6
0x1
0777
(a)
+a
-a
~a
!a
[]
[1]
[1,2]
[a]
{}
{a:1}
a ? b : c
""".split /\n/g #"
for sample in sample_list
do (sample)->
it JSON.stringify(sample), ()->
assert.equal full(sample), sample
# ensure bracket
kv =
'((a))': '(a)'
'((a)+(b))': '((a)+(b))'
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
# bracketed
sample_list = """
typeof a
new a
delete a
a++
a--
""".split /\n/g
for sample in sample_list
do (sample)->
it JSON.stringify(sample), ()->
assert.equal full(sample), "(#{sample})"
describe "bin op", ()->
sample_list = """
a+b
a=b
a<b
a<=b
a>b
a>=b
2*2
2/2
2%2
2<<2
2>>2
2>>>2
""".split /\n/g
for sample in sample_list
do (sample)->
it JSON.stringify(sample), ()->
assert.equal full(sample), "(#{sample})"
kv =
"1**2" : "Math.pow(1, 2)"
"1//2" : "Math.floor(1 / 2)"
"1%%2" : "(_tmp_b=2,(1 % _tmp_b + _tmp_b) % _tmp_b)"
"true and false" : "(true&&false)"
"1 and 2" : "(1&2)"
"true or false" : "(true||false)"
"1 or 2" : "(1|2)"
"true xor false" : "(!!(true^false))"
"1 xor 2" : "(1^2)"
"a**=2" : "a = Math.pow(a, 2)"
"a//=2" : "a = Math.floor(a / 2)"
"a%%=2" : "a = (function(a, b){return (a % b + b) % b})(a, 2)"
"a%%=2" : "a = (_tmp_b=2,(a % _tmp_b + _tmp_b) % _tmp_b)"
"a==b" : "(a===b)"
"a!=b" : "(a!==b)"
"""a = true
a and= false""" : """(a=true);
(a=(a&&false))"""
"""a = 2
a and= 3""" : """(a=2);
(a&=3)"""
"""a = true
a or= false""" : """(a=true);
(a=(a||false))"""
"""a = 2
a or= 3""" : """(a=2);
(a|=3)"""
"""a = true
a xor= false""" : """(a=true);
(a=!!(a^false))"""
"""a = 2
a xor= 3""" : """(a=2);
(a^=3)"""
# "a and= 2" : "(1&=2)"
# "a or= false" : "(true||=false)"
# "a or= 2" : "(1|=2)"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
# kv =
# for k,v of kv
# do (k,v)->
# it JSON.stringify(k)
sample_list = """
a and b
a or b
2 and 3.5
2.2 or 5.8
false and 4
2 or true
'a' and 'b'
false or 8
null and /ab+c/i
7 xor 7.8
5 xor true
undefined xor null
""".split /\n/g
sample_list.append [
"""a=5.8
a or= 3"""
"""a=5
a and= 3.8"""
"""a='a'
a or= /ab+c/i"""
]
for sample in sample_list
do (sample)->
it JSON.stringify(sample) + " throws", ()->
util.throws ()->
full(sample)
describe "pre op", ()->
kv =
"void a" : "null"
"not true": "!true"
"not 1" : "~1"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
sample_list = """
not a
not 'a'
not 1.5
""".split /\n/g
for sample in sample_list
do (sample)->
it JSON.stringify(sample) + " throws", ()->
util.throws ()->
full(sample)
# ###################################################################################################
# STRINGS
# ###################################################################################################
describe "strings", ()->
describe "non-interpolated", ()->
kv =
'""' : '""'
'"abcd"' : '"abcd"'
'"\\""' : '"\\""'
'"\\a"' : '"\\a"'
"''" : '""'
"'abcd'" : '"abcd"'
"'\"'" : '"\\""'
"'\"\"'" : '"\\"\\""'
'""""""' : '""'
"''''''" : '""'
'"""abcd"""' : '"abcd"'
"'''abcd'''" : '"abcd"'
'""" " """' : '" \\" "'
'""" "" """' : '" \\"\\" "'
"'''\"'''" : '"\\""'
"'''\"\"'''" : '"\\"\\""'
"'a\#{b}c'" : '"a\#{b}c"'
"'''a\#{b}c'''" : '"a\#{b}c"'
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
sample_list = """
'''a\#{b}'
'a\#{b}'''
""".split '\n'
for sample in sample_list
do (sample)->
it "#{sample} throws", ()->
util.throws ()->
full(sample)
describe "interpolated", ()->
kv =
'"a#{b+c}d"' : '("a"+(b+c)+"d")'
'"a#{b+c}d#{e+f}g"' : '("a"+(b+c)+"d"+(e+f)+"g")'
'"a#{b+c}d#{e+f}g#{h+i}j"' : '("a"+(b+c)+"d"+(e+f)+"g"+(h+i)+"j")'
'"a{} #{b+c} {} #d"' : '("a{} "+(b+c)+" {} #d")'
'"a{ #{b+c} } # #{d} } #d"' : '("a{ "+(b+c)+" } # "+(d)+" } #d")'
'"""a#{b}c"""' : '("a"+(b)+"c")'
"'''a\#{b}c'''" : '"a#{b}c"'
'"a\\#{#{b}c"' : '("a\\#{"+(b)+"c")'
'"a\\#{a}#{b}c"' : '("a\\#{a}"+(b)+"c")'
'"#{}"' : '("")'
'"a#{}"' : '("a")'
'"#{}b"' : '("b")'
'"a#{}b"' : '("ab")'
'"#{}#{}"' : '("")'
'"#{}#{}#{}"' : '("")'
'"#{}#{}#{}#{}"' : '("")'
'"a#{}#{}"' : '("a")'
'"#{1}#{}"' : '(""+(1))'
'"#{}b#{}"' : '("b")'
'"#{}#{2}"' : '(""+(2))'
'"#{}#{}c"' : '("c")'
'"a#{1}#{}"' : '("a"+(1))'
'"a#{}b#{}"' : '("ab")'
'"a#{}#{2}"' : '("a"+(2))'
'"a#{}#{}c"' : '("ac")'
'"#{1}b#{}"' : '(""+(1)+"b")'
'"#{1}#{2}"' : '(""+(1)+(2))'
'"#{1}#{}c"' : '(""+(1)+"c")'
'"#{1}#{2}c"' : '(""+(1)+(2)+"c")'
'"#{1}b#{}c"' : '(""+(1)+"bc")'
'"a#{1}b#{}c"' : '("a"+(1)+"bc")'
'"a#{}b#{}c"' : '("abc")'
'"#{2+2}#{3-8}"' : '(""+(2+2)+(3-8))'
'"a#{-8}"' : '("a"+(-8))'
'"#{[]}"' : '(""+([]))'
'"""a#{2+2}b"""' : '("a"+(2+2)+"b")'
'""" " #{1}"""' : '(" \\" "+(1))' # double quoute escaped
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
describe "fuckups", ()->
fuckups =
'"#{5 #comment}"' : '(""+(5))'
'"#{5 #{comment}"' : '(""+(5))'
for k, v of fuckups
do (k, v)->
it "#{k} -> #{v}"
sample_list = '''
"""a#{b}"
"a#{b}"""
"a#{{}}"
'''.split '\n'
# Note that "#{{}}" is valid IcedCoffeeScript (though "#{{{}}}" isn't)
for sample in sample_list
do (sample)->
it "#{sample} throws", ()->
util.throws ()->
full(sample)
describe "multiline", ->
kv =
'''
"Call me <NAME>. Some years ago --
never mind how long precisely -- having little
or no money in my purse, and nothing particular
to interest me on shore, I thought I would sail
about a little and see the watery part of the
world..."
''' : '"Call me <NAME>. Some years ago -- never mind how long precisely -- having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world..."'
'''
'Call me <NAME>. Some years ago --
never mind how long precisely -- having little
or no money in my purse, and nothing particular
to interest me on shore, I thought I would sail
about a little and see the watery part of the
world...'
''' : '"Call me <NAME>. Some years ago -- never mind how long precisely -- having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world..."'
'''
"
"
''' : '""'
'''
'
'
''' : '""'
'''
"
abcd
efgh
"
''' : '"abcd efgh"'
'''
'
abcd
efgh
'
''' : '"abcd efgh"'
'''
"
abcd
#{3+3}
efgh
#{5+5}
ijkl
"
''' : '("abcd "+(3+3)+" efgh "+(5+5)+" ijkl")'
'''
"
#{3+3}
efgh
#{5+5}
ijkl
"
''' : '(""+(3+3)+" efgh "+(5+5)+" ijkl")'
'''
"
abcd
#{3+3}
#{5+5}
ijkl
"
''' : '("abcd "+(3+3)+" "+(5+5)+" ijkl")'
'''
"
abcd
#{3+3}
#{5+5}
"
''' : '("abcd "+(3+3)+" "+(5+5))'
'''
"
#{3+3}
"
''' : '(""+(3+3))'
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
describe "heredoc", ->
kv =
'''"""abc
def"""''' : '"abc\\ndef"'
"""'''abc
def'''""" : '"abc\\ndef"'
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
describe "+strings", ->
kv =
'+"123"' : '+"123"'
"+'123'" : '+"123"'
'+"""123"""' : '+"123"'
"+'''123'''" : '+"123"'
'+"#{123}"' : '+(""+(123))'
'+"#{41*3}"' : '+(""+(41*3))'
'+"12#{3}"' : '+("12"+(3))'
'+"12#{1+2}"' : '+("12"+(1+2))'
'+"#{1}23"' : '+(""+(1)+"23")'
'+"#{1}2#{3}"': '+(""+(1)+"2"+(3))'
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
# ###################################################################################################
# REGEXP
# ###################################################################################################
describe "regexp", ()->
describe "non-interpolated", ()->
kv =
'/ab+c/iiiiiiiiiiiiiii' : '/ab+c/iiiiiiiiiiiiiii'
'///ab+c///i' : '/ab+c/i'
'//////' : '/(?:)/' # this is invalid IcedCoffeeScript
'/// / ///' : '/\\//' # escape forward slash
'/// / // ///' : '/\\/\\/\\//' # more forward slashes to be escaped
'/// a b + c ///' : '/ab+c/' # spaces to be ignored
'///\ta\tb\t+\tc\t///' : '/ab+c/' # tabs to be ignored as well
'///ab+c #comment///' : '/ab+c/' # comment
'///ab+c#omment///' : '/ab+c#omment/' # comments should be preceded by whitespace
'///ab+c \\#omment///' : '/ab+c\\#omment/'
'///[#]///' : '/[#]/'
'''///multiline
lalala
tratata///''' : '/multilinelalalatratata/'
'''///multiline
with # a comment
# and
some continuation
///''' : '/multilinewithsomecontinuation/'
'/// ///' : '/(?:)/' # O_O
'''///
///''' : '/(?:)/' # multiline O_O
'''/// # comment
///''' : '/(?:)/' # multiline O_O with comment
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
describe "interpolated", ()->
kv =
'///ab+c\\#{///' : '/ab+c\\#{/' # interpolation escaped
'///ab+c #comment #{2+2} de+f///' : 'RegExp("ab+c"+(2+2)+"de+f")'
'''///ab+c #comment #{2+2} de+f
another line # with a comment
# one more comment #{4+4}///''' : 'RegExp("ab+c"+(2+2)+"de+fanotherline"+(4+4))'
'///a#{1}b///i' : 'RegExp("a"+(1)+"b","i")'
'///a#{1}b///iiii' : 'RegExp("a"+(1)+"b","iiii")'
'///"#{}///' : 'RegExp("\\"")' # double quotes escaped
'////#{}///' : 'RegExp("/")' # forward slashes don't need to be escaped
# The following samples are borrowed from the string interpolation section:
'///a#{b+c}d///' : 'RegExp("a"+(b+c)+"d")'
'///a#{b+c}d#{e+f}g///' : 'RegExp("a"+(b+c)+"d"+(e+f)+"g")'
'///a#{b+c}d#{e+f}g#{h+i}j///' : 'RegExp("a"+(b+c)+"d"+(e+f)+"g"+(h+i)+"j")'
'///a{} #{b+c} {} #d///' : 'RegExp("a{}"+(b+c)+"{}")'
'///a{ #{b+c} } # #{d} } #d///' : 'RegExp("a{"+(b+c)+"}"+(d)+"}")'
'///a\\#{#{b}c///' : 'RegExp("a\\#{"+(b)+"c")'
'///a\\#{a}#{b}c///' : 'RegExp("a\\#{a}"+(b)+"c")'
'///#{}///' : 'RegExp("")' # this is invalid IcedCoffeeScript
'///a#{}///' : 'RegExp("a")'
'///#{}b///' : 'RegExp("b")'
'///a#{}b///' : 'RegExp("ab")'
'///#{}#{}///' : 'RegExp("")' # this is invalid IcedCoffeeScript
'///#{}#{}#{}///' : 'RegExp("")' # this is invalid IcedCoffeeScript
'///#{}#{}#{}#{}///' : 'RegExp("")' # this is invalid IcedCoffeeScript
'///a#{}#{}///' : 'RegExp("a")'
'///#{1}#{}///' : 'RegExp(""+(1))'
'///#{}b#{}///' : 'RegExp("b")'
'///#{}#{2}///' : 'RegExp(""+(2))'
'///#{}#{}c///' : 'RegExp("c")'
'///a#{1}#{}///' : 'RegExp("a"+(1))'
'///a#{}b#{}///' : 'RegExp("ab")'
'///a#{}#{2}///' : 'RegExp("a"+(2))'
'///a#{}#{}c///' : 'RegExp("ac")'
'///#{1}b#{}///' : 'RegExp(""+(1)+"b")'
'///#{1}#{2}///' : 'RegExp(""+(1)+(2))'
'///#{1}#{}c///' : 'RegExp(""+(1)+"c")'
'///#{1}#{2}c///' : 'RegExp(""+(1)+(2)+"c")'
'///#{1}b#{}c///' : 'RegExp(""+(1)+"bc")'
'///a#{1}b#{}c///' : 'RegExp("a"+(1)+"bc")'
'///a#{}b#{}c///' : 'RegExp("abc")'
'///#{2+2}#{3-8}///' : 'RegExp(""+(2+2)+(3-8))'
'///a#{-8}///' : 'RegExp("a"+(-8))'
'///#{[]}///' : 'RegExp(""+([]))'
for k, v of kv
do (k, v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
describe "invalid", ()->
sample_list = '''
/// ////
/// /// ///
///a#{{}}///
'''.split '\n'
# Note that "#{{}}" is valid IcedCoffeeScript (though "#{{{}}}" isn't)
for sample in sample_list
do (sample)->
it "#{sample} throws", ()->
util.throws ()->
full(sample)
# ###################################################################################################
describe "hash", ()->
kv =
"{a}" : "{a:a}"
"a:1" : "{a:1}"
"a:1,b:1" : "{a:1,b:1}"
"{\na:b\nc:d}": "{a:b,c:d}"
# "{(a):b}" : "(_t={},_t[a]=b,_t)"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
describe "array", ()->
kv =
"[\n]" : "[]"
"[\na\nb]" : "[a,b]"
"[0..0]" : "[0]"
"[0..2]" : "[0, 1, 2]"
"[0..20]" : "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]"
"[0..21]" : """
(function() {
var results = [];
for (var i = 0; i <= 21; i++){ results.push(i); }
return results;
})()
"""
"[20..0]" : "[20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]"
"[21..0]" : """
(function() {
var results = [];
for (var i = 21; i >= 0; i--){ results.push(i); }
return results;
})()
"""
"[2.5..4.8]" : "[2.5, 3.5, 4.5]"
"[4.5..1.8]" : "[4.5, 3.5, 2.5]"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
describe "comment", ()->
kv =
"#a" : "//a"
"a#a" : "a//a"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
describe "access", ()->
kv =
"a.b" : "a.b"
"a[b]" : "a[b]"
"a.0" : "a[0]"
"a.1" : "a[1]"
"a.01" : "[a[0],a[1]]"
"a.12" : "[a[1],a[2]]"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
describe "function decl", ()->
kv =
"->" : "(function(){})"
"->a" : """
(function(){
return(a)
})
"""
"()->" : "(function(){})"
"(a)->" : "(function(a){})"
"(a,b)->" : "(function(a, b){})"
"(a,b,c)->" : "(function(a, b, c){})"
"(a,b)->a+b" : """
(function(a, b){
return((a+b))
})
"""
"(a,b=1)->" : """
(function(a, b){
b=b==null?(1):b;
})"""
"(a,b=(1))->" : """
(function(a, b){
b=b==null?(1):b;
})"""
"(a,b=1):number->" : """
(function(a, b){
b=b==null?(1):b;
})"""
"(a)->a" : """
(function(a){
return(a)
})
"""
"(a)->\n a" : """
(function(a){
a
})
"""
"->\n a" : """
(function(){
a
})
"""
"""
->
a=1
b=a
""" : """
(function(){
(a=1);
(b=a)
})
"""
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
# TEMP same
k2 = k.replace "->", "=>"
it JSON.stringify(k2), ()->
assert.equal full(k2), v
# TEMP throws
kv =
"(a:number)->" : "(function(a){})"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
util.throws ()->
full(k)
describe "function call", ()->
kv =
"a(b)": "(a)(b)"
"a(b\n)": "(a)(b)"
# "a(\nb)": "(a)(b)" # BUG
"a(b,c)": "(a)(b, c)"
"a()": "(a)()"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
describe "macro-block", ()->
kv =
"""
if a
b
""" : """
if (a) {
b
}
"""
"""
while a
b
""" : """
while(a) {
b
}
"""
"""
loop
b
""" : """
while(true) {
b
}
"""
# LATER
# """
# c = if a
# b
# """ : """
# if (a) {
# c = b
# }
# """
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
sample_list =
"""
if
b
---
loop a
b
---
wtf a
b
---
wtf
b
""".split /\n?---\n?/
for v in sample_list
do (v)->
it JSON.stringify(v), ()->
util.throws ()->
full(v)
# TEMP impl tests
describe "pipeline", ()->
kv =
"""
[1] | a
""" : """
a = [1]
"""
"""
fn = (t)->t
[1] | fn
""" : """
(fn=(function(t){
return(t)
}));
([1]).map(fn)
"""
"""
fn = (t)->t
([1]) | fn
""" : """
(fn=(function(t){
return(t)
}));
([1]).map(fn)
"""
"""
fn = (t)->t
[1] | fn | b
""" : """
(fn=(function(t){
return(t)
}));
b = ([1]).map(fn)
"""
"""
b = []
fn = (t)->t
[1] | fn | b
""" : """
(b=[]);
(fn=(function(t){
return(t)
}));
b = ([1]).map(fn)
"""
"""
["Hello", "world"] | stdout
""" : """
var ref = (["Hello","world"]);
for (var i = 0, len = ref.length; i < len; i++) {
stdout(ref[i]);
}
"""
"""
[1] | ((a,b)->a+b) | c
""" : """
c = ([1]).reduce((function(a, b){
return((a+b))
}))
"""
# unsafe backet
# """
# [1] | (a,b)->a+b | c
# """ : """
# c = ([1]).reduce((function(a, b){
# return((a+b))
# }))
# """
# async
"""
[1] | ((a,cb)->cb(a)) | c
""" : """
c = ([1]).async_map((function(a, cb){
return((cb)(a))
}))
"""
"""
[1] | ((a,b,cb)->cb(a+b)) | c
""" : """
c = ([1]).async_reduce((function(a, b, cb){
return((cb)((a+b)))
}))
"""
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
sample_list =
"""
1 | a
---
a = 1
[1] | a
---
[1] | (()->1)
---
[1] | ((a,b,c)->a+b+c)
---
[1] | ((a,b,c)->a+b+c+1)
""".split /\n?---\n?/
for v in sample_list
do (v)->
it JSON.stringify(v), ()->
util.throws ()->
full(v)
it 'test translate exception', (done)->
await translate null, {}, defer(err)
assert err?
done()
it 'public endpoint should work', (done)->
await go 'a', {}, defer(err, res)
assert !(err?)
await go 'a КИРИЛИЦА', {}, defer(err, res)
assert err?
await go '1 or true', {}, defer(err, res)
assert err?
await go '1a1', {}, defer(err, res)
assert err?
# LATER not translated
# await go '1+"1"', {}, defer(err, res)
# assert err?
await go '__test_untranslated', {}, defer(err, res)
assert err?
done() | true | assert = require 'assert'
util = require 'fy/test_util'
{_tokenize} = require '../src/tokenizer'
{_parse } = require '../src/grammar'
{_translate, translate} = require '../src/translator'
{_type_inference} = require '../src/type_inference'
full = (t)->
tok = _tokenize(t)
ast = _parse(tok, mode_full:true)
_type_inference ast[0], {}
_translate ast[0], {}
{go} = require '../src/index'
describe 'translator section', ()->
sample_list = """
a
1
1.0
1e6
0x1
0777
(a)
+a
-a
~a
!a
[]
[1]
[1,2]
[a]
{}
{a:1}
a ? b : c
""".split /\n/g #"
for sample in sample_list
do (sample)->
it JSON.stringify(sample), ()->
assert.equal full(sample), sample
# ensure bracket
kv =
'((a))': '(a)'
'((a)+(b))': '((a)+(b))'
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
# bracketed
sample_list = """
typeof a
new a
delete a
a++
a--
""".split /\n/g
for sample in sample_list
do (sample)->
it JSON.stringify(sample), ()->
assert.equal full(sample), "(#{sample})"
describe "bin op", ()->
sample_list = """
a+b
a=b
a<b
a<=b
a>b
a>=b
2*2
2/2
2%2
2<<2
2>>2
2>>>2
""".split /\n/g
for sample in sample_list
do (sample)->
it JSON.stringify(sample), ()->
assert.equal full(sample), "(#{sample})"
kv =
"1**2" : "Math.pow(1, 2)"
"1//2" : "Math.floor(1 / 2)"
"1%%2" : "(_tmp_b=2,(1 % _tmp_b + _tmp_b) % _tmp_b)"
"true and false" : "(true&&false)"
"1 and 2" : "(1&2)"
"true or false" : "(true||false)"
"1 or 2" : "(1|2)"
"true xor false" : "(!!(true^false))"
"1 xor 2" : "(1^2)"
"a**=2" : "a = Math.pow(a, 2)"
"a//=2" : "a = Math.floor(a / 2)"
"a%%=2" : "a = (function(a, b){return (a % b + b) % b})(a, 2)"
"a%%=2" : "a = (_tmp_b=2,(a % _tmp_b + _tmp_b) % _tmp_b)"
"a==b" : "(a===b)"
"a!=b" : "(a!==b)"
"""a = true
a and= false""" : """(a=true);
(a=(a&&false))"""
"""a = 2
a and= 3""" : """(a=2);
(a&=3)"""
"""a = true
a or= false""" : """(a=true);
(a=(a||false))"""
"""a = 2
a or= 3""" : """(a=2);
(a|=3)"""
"""a = true
a xor= false""" : """(a=true);
(a=!!(a^false))"""
"""a = 2
a xor= 3""" : """(a=2);
(a^=3)"""
# "a and= 2" : "(1&=2)"
# "a or= false" : "(true||=false)"
# "a or= 2" : "(1|=2)"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
# kv =
# for k,v of kv
# do (k,v)->
# it JSON.stringify(k)
sample_list = """
a and b
a or b
2 and 3.5
2.2 or 5.8
false and 4
2 or true
'a' and 'b'
false or 8
null and /ab+c/i
7 xor 7.8
5 xor true
undefined xor null
""".split /\n/g
sample_list.append [
"""a=5.8
a or= 3"""
"""a=5
a and= 3.8"""
"""a='a'
a or= /ab+c/i"""
]
for sample in sample_list
do (sample)->
it JSON.stringify(sample) + " throws", ()->
util.throws ()->
full(sample)
describe "pre op", ()->
kv =
"void a" : "null"
"not true": "!true"
"not 1" : "~1"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
sample_list = """
not a
not 'a'
not 1.5
""".split /\n/g
for sample in sample_list
do (sample)->
it JSON.stringify(sample) + " throws", ()->
util.throws ()->
full(sample)
# ###################################################################################################
# STRINGS
# ###################################################################################################
describe "strings", ()->
describe "non-interpolated", ()->
kv =
'""' : '""'
'"abcd"' : '"abcd"'
'"\\""' : '"\\""'
'"\\a"' : '"\\a"'
"''" : '""'
"'abcd'" : '"abcd"'
"'\"'" : '"\\""'
"'\"\"'" : '"\\"\\""'
'""""""' : '""'
"''''''" : '""'
'"""abcd"""' : '"abcd"'
"'''abcd'''" : '"abcd"'
'""" " """' : '" \\" "'
'""" "" """' : '" \\"\\" "'
"'''\"'''" : '"\\""'
"'''\"\"'''" : '"\\"\\""'
"'a\#{b}c'" : '"a\#{b}c"'
"'''a\#{b}c'''" : '"a\#{b}c"'
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
sample_list = """
'''a\#{b}'
'a\#{b}'''
""".split '\n'
for sample in sample_list
do (sample)->
it "#{sample} throws", ()->
util.throws ()->
full(sample)
describe "interpolated", ()->
kv =
'"a#{b+c}d"' : '("a"+(b+c)+"d")'
'"a#{b+c}d#{e+f}g"' : '("a"+(b+c)+"d"+(e+f)+"g")'
'"a#{b+c}d#{e+f}g#{h+i}j"' : '("a"+(b+c)+"d"+(e+f)+"g"+(h+i)+"j")'
'"a{} #{b+c} {} #d"' : '("a{} "+(b+c)+" {} #d")'
'"a{ #{b+c} } # #{d} } #d"' : '("a{ "+(b+c)+" } # "+(d)+" } #d")'
'"""a#{b}c"""' : '("a"+(b)+"c")'
"'''a\#{b}c'''" : '"a#{b}c"'
'"a\\#{#{b}c"' : '("a\\#{"+(b)+"c")'
'"a\\#{a}#{b}c"' : '("a\\#{a}"+(b)+"c")'
'"#{}"' : '("")'
'"a#{}"' : '("a")'
'"#{}b"' : '("b")'
'"a#{}b"' : '("ab")'
'"#{}#{}"' : '("")'
'"#{}#{}#{}"' : '("")'
'"#{}#{}#{}#{}"' : '("")'
'"a#{}#{}"' : '("a")'
'"#{1}#{}"' : '(""+(1))'
'"#{}b#{}"' : '("b")'
'"#{}#{2}"' : '(""+(2))'
'"#{}#{}c"' : '("c")'
'"a#{1}#{}"' : '("a"+(1))'
'"a#{}b#{}"' : '("ab")'
'"a#{}#{2}"' : '("a"+(2))'
'"a#{}#{}c"' : '("ac")'
'"#{1}b#{}"' : '(""+(1)+"b")'
'"#{1}#{2}"' : '(""+(1)+(2))'
'"#{1}#{}c"' : '(""+(1)+"c")'
'"#{1}#{2}c"' : '(""+(1)+(2)+"c")'
'"#{1}b#{}c"' : '(""+(1)+"bc")'
'"a#{1}b#{}c"' : '("a"+(1)+"bc")'
'"a#{}b#{}c"' : '("abc")'
'"#{2+2}#{3-8}"' : '(""+(2+2)+(3-8))'
'"a#{-8}"' : '("a"+(-8))'
'"#{[]}"' : '(""+([]))'
'"""a#{2+2}b"""' : '("a"+(2+2)+"b")'
'""" " #{1}"""' : '(" \\" "+(1))' # double quoute escaped
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
describe "fuckups", ()->
fuckups =
'"#{5 #comment}"' : '(""+(5))'
'"#{5 #{comment}"' : '(""+(5))'
for k, v of fuckups
do (k, v)->
it "#{k} -> #{v}"
sample_list = '''
"""a#{b}"
"a#{b}"""
"a#{{}}"
'''.split '\n'
# Note that "#{{}}" is valid IcedCoffeeScript (though "#{{{}}}" isn't)
for sample in sample_list
do (sample)->
it "#{sample} throws", ()->
util.throws ()->
full(sample)
describe "multiline", ->
kv =
'''
"Call me PI:NAME:<NAME>END_PI. Some years ago --
never mind how long precisely -- having little
or no money in my purse, and nothing particular
to interest me on shore, I thought I would sail
about a little and see the watery part of the
world..."
''' : '"Call me PI:NAME:<NAME>END_PI. Some years ago -- never mind how long precisely -- having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world..."'
'''
'Call me PI:NAME:<NAME>END_PI. Some years ago --
never mind how long precisely -- having little
or no money in my purse, and nothing particular
to interest me on shore, I thought I would sail
about a little and see the watery part of the
world...'
''' : '"Call me PI:NAME:<NAME>END_PI. Some years ago -- never mind how long precisely -- having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world..."'
'''
"
"
''' : '""'
'''
'
'
''' : '""'
'''
"
abcd
efgh
"
''' : '"abcd efgh"'
'''
'
abcd
efgh
'
''' : '"abcd efgh"'
'''
"
abcd
#{3+3}
efgh
#{5+5}
ijkl
"
''' : '("abcd "+(3+3)+" efgh "+(5+5)+" ijkl")'
'''
"
#{3+3}
efgh
#{5+5}
ijkl
"
''' : '(""+(3+3)+" efgh "+(5+5)+" ijkl")'
'''
"
abcd
#{3+3}
#{5+5}
ijkl
"
''' : '("abcd "+(3+3)+" "+(5+5)+" ijkl")'
'''
"
abcd
#{3+3}
#{5+5}
"
''' : '("abcd "+(3+3)+" "+(5+5))'
'''
"
#{3+3}
"
''' : '(""+(3+3))'
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
describe "heredoc", ->
kv =
'''"""abc
def"""''' : '"abc\\ndef"'
"""'''abc
def'''""" : '"abc\\ndef"'
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
describe "+strings", ->
kv =
'+"123"' : '+"123"'
"+'123'" : '+"123"'
'+"""123"""' : '+"123"'
"+'''123'''" : '+"123"'
'+"#{123}"' : '+(""+(123))'
'+"#{41*3}"' : '+(""+(41*3))'
'+"12#{3}"' : '+("12"+(3))'
'+"12#{1+2}"' : '+("12"+(1+2))'
'+"#{1}23"' : '+(""+(1)+"23")'
'+"#{1}2#{3}"': '+(""+(1)+"2"+(3))'
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
# ###################################################################################################
# REGEXP
# ###################################################################################################
describe "regexp", ()->
describe "non-interpolated", ()->
kv =
'/ab+c/iiiiiiiiiiiiiii' : '/ab+c/iiiiiiiiiiiiiii'
'///ab+c///i' : '/ab+c/i'
'//////' : '/(?:)/' # this is invalid IcedCoffeeScript
'/// / ///' : '/\\//' # escape forward slash
'/// / // ///' : '/\\/\\/\\//' # more forward slashes to be escaped
'/// a b + c ///' : '/ab+c/' # spaces to be ignored
'///\ta\tb\t+\tc\t///' : '/ab+c/' # tabs to be ignored as well
'///ab+c #comment///' : '/ab+c/' # comment
'///ab+c#omment///' : '/ab+c#omment/' # comments should be preceded by whitespace
'///ab+c \\#omment///' : '/ab+c\\#omment/'
'///[#]///' : '/[#]/'
'''///multiline
lalala
tratata///''' : '/multilinelalalatratata/'
'''///multiline
with # a comment
# and
some continuation
///''' : '/multilinewithsomecontinuation/'
'/// ///' : '/(?:)/' # O_O
'''///
///''' : '/(?:)/' # multiline O_O
'''/// # comment
///''' : '/(?:)/' # multiline O_O with comment
for k,v of kv
do (k,v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
describe "interpolated", ()->
kv =
'///ab+c\\#{///' : '/ab+c\\#{/' # interpolation escaped
'///ab+c #comment #{2+2} de+f///' : 'RegExp("ab+c"+(2+2)+"de+f")'
'''///ab+c #comment #{2+2} de+f
another line # with a comment
# one more comment #{4+4}///''' : 'RegExp("ab+c"+(2+2)+"de+fanotherline"+(4+4))'
'///a#{1}b///i' : 'RegExp("a"+(1)+"b","i")'
'///a#{1}b///iiii' : 'RegExp("a"+(1)+"b","iiii")'
'///"#{}///' : 'RegExp("\\"")' # double quotes escaped
'////#{}///' : 'RegExp("/")' # forward slashes don't need to be escaped
# The following samples are borrowed from the string interpolation section:
'///a#{b+c}d///' : 'RegExp("a"+(b+c)+"d")'
'///a#{b+c}d#{e+f}g///' : 'RegExp("a"+(b+c)+"d"+(e+f)+"g")'
'///a#{b+c}d#{e+f}g#{h+i}j///' : 'RegExp("a"+(b+c)+"d"+(e+f)+"g"+(h+i)+"j")'
'///a{} #{b+c} {} #d///' : 'RegExp("a{}"+(b+c)+"{}")'
'///a{ #{b+c} } # #{d} } #d///' : 'RegExp("a{"+(b+c)+"}"+(d)+"}")'
'///a\\#{#{b}c///' : 'RegExp("a\\#{"+(b)+"c")'
'///a\\#{a}#{b}c///' : 'RegExp("a\\#{a}"+(b)+"c")'
'///#{}///' : 'RegExp("")' # this is invalid IcedCoffeeScript
'///a#{}///' : 'RegExp("a")'
'///#{}b///' : 'RegExp("b")'
'///a#{}b///' : 'RegExp("ab")'
'///#{}#{}///' : 'RegExp("")' # this is invalid IcedCoffeeScript
'///#{}#{}#{}///' : 'RegExp("")' # this is invalid IcedCoffeeScript
'///#{}#{}#{}#{}///' : 'RegExp("")' # this is invalid IcedCoffeeScript
'///a#{}#{}///' : 'RegExp("a")'
'///#{1}#{}///' : 'RegExp(""+(1))'
'///#{}b#{}///' : 'RegExp("b")'
'///#{}#{2}///' : 'RegExp(""+(2))'
'///#{}#{}c///' : 'RegExp("c")'
'///a#{1}#{}///' : 'RegExp("a"+(1))'
'///a#{}b#{}///' : 'RegExp("ab")'
'///a#{}#{2}///' : 'RegExp("a"+(2))'
'///a#{}#{}c///' : 'RegExp("ac")'
'///#{1}b#{}///' : 'RegExp(""+(1)+"b")'
'///#{1}#{2}///' : 'RegExp(""+(1)+(2))'
'///#{1}#{}c///' : 'RegExp(""+(1)+"c")'
'///#{1}#{2}c///' : 'RegExp(""+(1)+(2)+"c")'
'///#{1}b#{}c///' : 'RegExp(""+(1)+"bc")'
'///a#{1}b#{}c///' : 'RegExp("a"+(1)+"bc")'
'///a#{}b#{}c///' : 'RegExp("abc")'
'///#{2+2}#{3-8}///' : 'RegExp(""+(2+2)+(3-8))'
'///a#{-8}///' : 'RegExp("a"+(-8))'
'///#{[]}///' : 'RegExp(""+([]))'
for k, v of kv
do (k, v)->
it "#{k} -> #{v}", ()->
assert.equal full(k), v
describe "invalid", ()->
sample_list = '''
/// ////
/// /// ///
///a#{{}}///
'''.split '\n'
# Note that "#{{}}" is valid IcedCoffeeScript (though "#{{{}}}" isn't)
for sample in sample_list
do (sample)->
it "#{sample} throws", ()->
util.throws ()->
full(sample)
# ###################################################################################################
describe "hash", ()->
kv =
"{a}" : "{a:a}"
"a:1" : "{a:1}"
"a:1,b:1" : "{a:1,b:1}"
"{\na:b\nc:d}": "{a:b,c:d}"
# "{(a):b}" : "(_t={},_t[a]=b,_t)"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
describe "array", ()->
kv =
"[\n]" : "[]"
"[\na\nb]" : "[a,b]"
"[0..0]" : "[0]"
"[0..2]" : "[0, 1, 2]"
"[0..20]" : "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]"
"[0..21]" : """
(function() {
var results = [];
for (var i = 0; i <= 21; i++){ results.push(i); }
return results;
})()
"""
"[20..0]" : "[20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]"
"[21..0]" : """
(function() {
var results = [];
for (var i = 21; i >= 0; i--){ results.push(i); }
return results;
})()
"""
"[2.5..4.8]" : "[2.5, 3.5, 4.5]"
"[4.5..1.8]" : "[4.5, 3.5, 2.5]"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
describe "comment", ()->
kv =
"#a" : "//a"
"a#a" : "a//a"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
describe "access", ()->
kv =
"a.b" : "a.b"
"a[b]" : "a[b]"
"a.0" : "a[0]"
"a.1" : "a[1]"
"a.01" : "[a[0],a[1]]"
"a.12" : "[a[1],a[2]]"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
describe "function decl", ()->
kv =
"->" : "(function(){})"
"->a" : """
(function(){
return(a)
})
"""
"()->" : "(function(){})"
"(a)->" : "(function(a){})"
"(a,b)->" : "(function(a, b){})"
"(a,b,c)->" : "(function(a, b, c){})"
"(a,b)->a+b" : """
(function(a, b){
return((a+b))
})
"""
"(a,b=1)->" : """
(function(a, b){
b=b==null?(1):b;
})"""
"(a,b=(1))->" : """
(function(a, b){
b=b==null?(1):b;
})"""
"(a,b=1):number->" : """
(function(a, b){
b=b==null?(1):b;
})"""
"(a)->a" : """
(function(a){
return(a)
})
"""
"(a)->\n a" : """
(function(a){
a
})
"""
"->\n a" : """
(function(){
a
})
"""
"""
->
a=1
b=a
""" : """
(function(){
(a=1);
(b=a)
})
"""
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
# TEMP same
k2 = k.replace "->", "=>"
it JSON.stringify(k2), ()->
assert.equal full(k2), v
# TEMP throws
kv =
"(a:number)->" : "(function(a){})"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
util.throws ()->
full(k)
describe "function call", ()->
kv =
"a(b)": "(a)(b)"
"a(b\n)": "(a)(b)"
# "a(\nb)": "(a)(b)" # BUG
"a(b,c)": "(a)(b, c)"
"a()": "(a)()"
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
describe "macro-block", ()->
kv =
"""
if a
b
""" : """
if (a) {
b
}
"""
"""
while a
b
""" : """
while(a) {
b
}
"""
"""
loop
b
""" : """
while(true) {
b
}
"""
# LATER
# """
# c = if a
# b
# """ : """
# if (a) {
# c = b
# }
# """
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
sample_list =
"""
if
b
---
loop a
b
---
wtf a
b
---
wtf
b
""".split /\n?---\n?/
for v in sample_list
do (v)->
it JSON.stringify(v), ()->
util.throws ()->
full(v)
# TEMP impl tests
describe "pipeline", ()->
kv =
"""
[1] | a
""" : """
a = [1]
"""
"""
fn = (t)->t
[1] | fn
""" : """
(fn=(function(t){
return(t)
}));
([1]).map(fn)
"""
"""
fn = (t)->t
([1]) | fn
""" : """
(fn=(function(t){
return(t)
}));
([1]).map(fn)
"""
"""
fn = (t)->t
[1] | fn | b
""" : """
(fn=(function(t){
return(t)
}));
b = ([1]).map(fn)
"""
"""
b = []
fn = (t)->t
[1] | fn | b
""" : """
(b=[]);
(fn=(function(t){
return(t)
}));
b = ([1]).map(fn)
"""
"""
["Hello", "world"] | stdout
""" : """
var ref = (["Hello","world"]);
for (var i = 0, len = ref.length; i < len; i++) {
stdout(ref[i]);
}
"""
"""
[1] | ((a,b)->a+b) | c
""" : """
c = ([1]).reduce((function(a, b){
return((a+b))
}))
"""
# unsafe backet
# """
# [1] | (a,b)->a+b | c
# """ : """
# c = ([1]).reduce((function(a, b){
# return((a+b))
# }))
# """
# async
"""
[1] | ((a,cb)->cb(a)) | c
""" : """
c = ([1]).async_map((function(a, cb){
return((cb)(a))
}))
"""
"""
[1] | ((a,b,cb)->cb(a+b)) | c
""" : """
c = ([1]).async_reduce((function(a, b, cb){
return((cb)((a+b)))
}))
"""
for k,v of kv
do (k,v)->
it JSON.stringify(k), ()->
assert.equal full(k), v
sample_list =
"""
1 | a
---
a = 1
[1] | a
---
[1] | (()->1)
---
[1] | ((a,b,c)->a+b+c)
---
[1] | ((a,b,c)->a+b+c+1)
""".split /\n?---\n?/
for v in sample_list
do (v)->
it JSON.stringify(v), ()->
util.throws ()->
full(v)
it 'test translate exception', (done)->
await translate null, {}, defer(err)
assert err?
done()
it 'public endpoint should work', (done)->
await go 'a', {}, defer(err, res)
assert !(err?)
await go 'a КИРИЛИЦА', {}, defer(err, res)
assert err?
await go '1 or true', {}, defer(err, res)
assert err?
await go '1a1', {}, defer(err, res)
assert err?
# LATER not translated
# await go '1+"1"', {}, defer(err, res)
# assert err?
await go '__test_untranslated', {}, defer(err, res)
assert err?
done() |
[
{
"context": "115904image.png?Expires=1509061432&OSSAccessKeyId=JZJNf7zIXqCHwLpT&Signature=D2M2dGI/2ckE4Bm2wlsZa9WMDg8%3D'\n # ",
"end": 1756,
"score": 0.9994732141494751,
"start": 1740,
"tag": "KEY",
"value": "JZJNf7zIXqCHwLpT"
},
{
"context": "oad-1072823.jpg?Expires=1509061432... | site/assets/_coffee/page-demo.coffee | qinyang912/simditor | 2 |
$ ->
Simditor.locale = 'en-US'
toolbar= [
'title',
'undo',
'redo',
'formatPaint',
'clear-format',
'bold',
'italic',
'underline',
'strikethrough',
'font-family',
'fontScale',
'color',
'background',
'time-stamp',
'line-height',
'checkbox'
'|',
'ol',
'ul',
'blockquote',
'code',
'table',
'|',
'link',
'image',
'attach',
'hr',
'|',
'indent',
'outdent',
'alignment'
]
mobileToolbar=["bold","underline","strikethrough","color","ul","ol"]
toolbar = mobileToolbar if mobilecheck()
editor = new Simditor
textarea: $('#txt-content')
placeholder: '这里输入文字...'
toolbar: toolbar
pasteImage: true
defaultImage: 'assets/images/image.png'
upload: if location.search == '?upload' then {url: '/upload'} else false,
defaultLinkHref: 'https://www.rishiqing.com'
attachHtml = Simditor.UnSelectionBlock.getAttachHtml
previewFile: false
viewPath: 'http:www.baidu.com'
bucket: 'rishiqing-file'
file:
name: 'dddd.png'
filePath: '34123413dddd.png'
realPath: 'http:www.baidu.com'
id: 12341
globalLinkHtml = Simditor.UnSelectionBlock.getGlobalLinkHtml
file:
name: 'woqu'
id: 1
type: 'doc'
taskBlockHtml = Simditor.UnSelectionBlock.getTaskBlockHtml
setting:
preContent: 'time'
taskContent: ['note', 'starTrend']
info:
title: '自动填充日程任务'
subTitle: '筛选结果:今天、已完成'
# imgHtml = Simditor.UnSelectionBlock.getImgHtml
# file:
# id: 1
# realPath: 'https://rishiqing-file.oss-cn-beijing.aliyuncs.com/150884150442420160306115904image.png?Expires=1509061432&OSSAccessKeyId=JZJNf7zIXqCHwLpT&Signature=D2M2dGI/2ckE4Bm2wlsZa9WMDg8%3D'
# name: 'image'
# bucket: 'rishiqing-file'
# filePath: ''
# imgHtml2 = Simditor.UnSelectionBlock.getImgHtml
# file:
# id: 2
# realPath: 'https://rishiqing-file.oss-cn-beijing.aliyuncs.com/1508828568224road-1072823.jpg?Expires=1509061432&OSSAccessKeyId=JZJNf7zIXqCHwLpT&Signature=PHm3EfluZYRwxMEk1luF9/T6/%2BA%3D'
# name: 'image'
# bucket: 'rishiqing-file'
# filePath: ''
editor.setValue(editor.getValue())
$preview = $('#preview')
if $preview.length > 0
editor.on 'valuechanged', (e) ->
$preview.html editor.getValue()
| 42184 |
$ ->
Simditor.locale = 'en-US'
toolbar= [
'title',
'undo',
'redo',
'formatPaint',
'clear-format',
'bold',
'italic',
'underline',
'strikethrough',
'font-family',
'fontScale',
'color',
'background',
'time-stamp',
'line-height',
'checkbox'
'|',
'ol',
'ul',
'blockquote',
'code',
'table',
'|',
'link',
'image',
'attach',
'hr',
'|',
'indent',
'outdent',
'alignment'
]
mobileToolbar=["bold","underline","strikethrough","color","ul","ol"]
toolbar = mobileToolbar if mobilecheck()
editor = new Simditor
textarea: $('#txt-content')
placeholder: '这里输入文字...'
toolbar: toolbar
pasteImage: true
defaultImage: 'assets/images/image.png'
upload: if location.search == '?upload' then {url: '/upload'} else false,
defaultLinkHref: 'https://www.rishiqing.com'
attachHtml = Simditor.UnSelectionBlock.getAttachHtml
previewFile: false
viewPath: 'http:www.baidu.com'
bucket: 'rishiqing-file'
file:
name: 'dddd.png'
filePath: '34123413dddd.png'
realPath: 'http:www.baidu.com'
id: 12341
globalLinkHtml = Simditor.UnSelectionBlock.getGlobalLinkHtml
file:
name: 'woqu'
id: 1
type: 'doc'
taskBlockHtml = Simditor.UnSelectionBlock.getTaskBlockHtml
setting:
preContent: 'time'
taskContent: ['note', 'starTrend']
info:
title: '自动填充日程任务'
subTitle: '筛选结果:今天、已完成'
# imgHtml = Simditor.UnSelectionBlock.getImgHtml
# file:
# id: 1
# realPath: 'https://rishiqing-file.oss-cn-beijing.aliyuncs.com/150884150442420160306115904image.png?Expires=1509061432&OSSAccessKeyId=<KEY>&Signature=D2M2dGI/2ckE4Bm2wlsZa9WMDg8%3D'
# name: 'image'
# bucket: 'rishiqing-file'
# filePath: ''
# imgHtml2 = Simditor.UnSelectionBlock.getImgHtml
# file:
# id: 2
# realPath: 'https://rishiqing-file.oss-cn-beijing.aliyuncs.com/1508828568224road-1072823.jpg?Expires=1509061432&OSSAccessKeyId=<KEY>&Signature=PHm3EfluZYRwxMEk1luF9/T6/%2BA%3D'
# name: 'image'
# bucket: 'rishiqing-file'
# filePath: ''
editor.setValue(editor.getValue())
$preview = $('#preview')
if $preview.length > 0
editor.on 'valuechanged', (e) ->
$preview.html editor.getValue()
| true |
$ ->
Simditor.locale = 'en-US'
toolbar= [
'title',
'undo',
'redo',
'formatPaint',
'clear-format',
'bold',
'italic',
'underline',
'strikethrough',
'font-family',
'fontScale',
'color',
'background',
'time-stamp',
'line-height',
'checkbox'
'|',
'ol',
'ul',
'blockquote',
'code',
'table',
'|',
'link',
'image',
'attach',
'hr',
'|',
'indent',
'outdent',
'alignment'
]
mobileToolbar=["bold","underline","strikethrough","color","ul","ol"]
toolbar = mobileToolbar if mobilecheck()
editor = new Simditor
textarea: $('#txt-content')
placeholder: '这里输入文字...'
toolbar: toolbar
pasteImage: true
defaultImage: 'assets/images/image.png'
upload: if location.search == '?upload' then {url: '/upload'} else false,
defaultLinkHref: 'https://www.rishiqing.com'
attachHtml = Simditor.UnSelectionBlock.getAttachHtml
previewFile: false
viewPath: 'http:www.baidu.com'
bucket: 'rishiqing-file'
file:
name: 'dddd.png'
filePath: '34123413dddd.png'
realPath: 'http:www.baidu.com'
id: 12341
globalLinkHtml = Simditor.UnSelectionBlock.getGlobalLinkHtml
file:
name: 'woqu'
id: 1
type: 'doc'
taskBlockHtml = Simditor.UnSelectionBlock.getTaskBlockHtml
setting:
preContent: 'time'
taskContent: ['note', 'starTrend']
info:
title: '自动填充日程任务'
subTitle: '筛选结果:今天、已完成'
# imgHtml = Simditor.UnSelectionBlock.getImgHtml
# file:
# id: 1
# realPath: 'https://rishiqing-file.oss-cn-beijing.aliyuncs.com/150884150442420160306115904image.png?Expires=1509061432&OSSAccessKeyId=PI:KEY:<KEY>END_PI&Signature=D2M2dGI/2ckE4Bm2wlsZa9WMDg8%3D'
# name: 'image'
# bucket: 'rishiqing-file'
# filePath: ''
# imgHtml2 = Simditor.UnSelectionBlock.getImgHtml
# file:
# id: 2
# realPath: 'https://rishiqing-file.oss-cn-beijing.aliyuncs.com/1508828568224road-1072823.jpg?Expires=1509061432&OSSAccessKeyId=PI:KEY:<KEY>END_PI&Signature=PHm3EfluZYRwxMEk1luF9/T6/%2BA%3D'
# name: 'image'
# bucket: 'rishiqing-file'
# filePath: ''
editor.setValue(editor.getValue())
$preview = $('#preview')
if $preview.length > 0
editor.on 'valuechanged', (e) ->
$preview.html editor.getValue()
|
[
{
"context": "#\t> File Name: message.coffee\n#\t> Author: LY\n#\t> Mail: ly.franky@gmail.com\n#\t> Created Time: F",
"end": 44,
"score": 0.9981566667556763,
"start": 42,
"tag": "USERNAME",
"value": "LY"
},
{
"context": "File Name: message.coffee\n#\t> Author: LY\n#\t> Mail: ly.frank... | server/db/models/message.coffee | wiiliamking/miac-website | 0 | # > File Name: message.coffee
# > Author: LY
# > Mail: ly.franky@gmail.com
# > Created Time: Friday, November 28, 2014 PM04:26:00 CST
mongoose = require 'mongoose'
Schema = mongoose.Schema
ObjectId = Schema.Types.ObjectId
MessageSchema = new Schema
replyTo: ObjectId
type: String
content: String
createdBy: ObjectId
createdAt: { type: Date, default: Date.now }
MessageModel = mongoose.model 'MessageModel', MessageSchema
###
* create a message in MessageModel with replyTo, type, content and user's id
* @param replyTo: the ObjectId that the message is replying to, it could be article's id or discussion's id or message's id,etc
* @param type: the message's type, 'comment' or 'reply'
* @param createdBy: user's id, to memorize who create the message
* @param callback: the callback function that would execute when function ended
###
MessageModel.createMessage = (replyTo, type, content, createdBy, callback)->
MessageModel.create
replyTo: replyTo
type: type
content: content
createdBy: createdBy
, callback
###
* drop all the messages in MessageModel
* @param callback: the callback function that would execute when function ended
###
MessageModel.drop = (callback)->
MessageModel.remove {}, ->
callback()
module.exports = MessageModel
| 154609 | # > File Name: message.coffee
# > Author: LY
# > Mail: <EMAIL>
# > Created Time: Friday, November 28, 2014 PM04:26:00 CST
mongoose = require 'mongoose'
Schema = mongoose.Schema
ObjectId = Schema.Types.ObjectId
MessageSchema = new Schema
replyTo: ObjectId
type: String
content: String
createdBy: ObjectId
createdAt: { type: Date, default: Date.now }
MessageModel = mongoose.model 'MessageModel', MessageSchema
###
* create a message in MessageModel with replyTo, type, content and user's id
* @param replyTo: the ObjectId that the message is replying to, it could be article's id or discussion's id or message's id,etc
* @param type: the message's type, 'comment' or 'reply'
* @param createdBy: user's id, to memorize who create the message
* @param callback: the callback function that would execute when function ended
###
MessageModel.createMessage = (replyTo, type, content, createdBy, callback)->
MessageModel.create
replyTo: replyTo
type: type
content: content
createdBy: createdBy
, callback
###
* drop all the messages in MessageModel
* @param callback: the callback function that would execute when function ended
###
MessageModel.drop = (callback)->
MessageModel.remove {}, ->
callback()
module.exports = MessageModel
| true | # > File Name: message.coffee
# > Author: LY
# > Mail: PI:EMAIL:<EMAIL>END_PI
# > Created Time: Friday, November 28, 2014 PM04:26:00 CST
mongoose = require 'mongoose'
Schema = mongoose.Schema
ObjectId = Schema.Types.ObjectId
MessageSchema = new Schema
replyTo: ObjectId
type: String
content: String
createdBy: ObjectId
createdAt: { type: Date, default: Date.now }
MessageModel = mongoose.model 'MessageModel', MessageSchema
###
* create a message in MessageModel with replyTo, type, content and user's id
* @param replyTo: the ObjectId that the message is replying to, it could be article's id or discussion's id or message's id,etc
* @param type: the message's type, 'comment' or 'reply'
* @param createdBy: user's id, to memorize who create the message
* @param callback: the callback function that would execute when function ended
###
MessageModel.createMessage = (replyTo, type, content, createdBy, callback)->
MessageModel.create
replyTo: replyTo
type: type
content: content
createdBy: createdBy
, callback
###
* drop all the messages in MessageModel
* @param callback: the callback function that would execute when function ended
###
MessageModel.drop = (callback)->
MessageModel.remove {}, ->
callback()
module.exports = MessageModel
|
[
{
"context": " requestBody = {\n emails: ['test@test.com']\n }\n request.post { ur",
"end": 9151,
"score": 0.9998992681503296,
"start": 9138,
"tag": "EMAIL",
"value": "test@test.com"
}
] | test/server/functional/course_instance.spec.coffee | SaintRamzes/codecombat | 1 | async = require 'async'
config = require '../../../server_config'
require '../common'
stripe = require('stripe')(config.stripe.secretKey)
# TODO: add permissiosn tests
describe 'CourseInstance', ->
courseInstanceCreateURL = getURL('/db/course_instance/-/create')
courseInstanceRedeemURL = getURL('/db/course_instance/-/redeem_prepaid')
userURL = getURL('/db/user')
createCourseInstances = (user, courseID, seats, token, done) ->
name = createName 'course instance '
requestBody =
courseID: courseID
name: name
seats: seats
stripe:
token: token
request.post {uri: courseInstanceCreateURL, json: requestBody }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(201)
CourseInstance.find {name: name}, (err, courseInstances) ->
expect(err).toBeNull()
makeCourseInstanceVerifyFn = (courseInstance) ->
(done) ->
expect(courseInstance.get('name')).toEqual(name)
expect(courseInstance.get('ownerID')).toEqual(user.get('_id'))
expect(courseInstance.get('members')).toContain(user.get('_id'))
query = {$and: [{creator: user.get('_id')}]}
query.$and.push {'properties.courseIDs': {$in: [courseID]}} if courseID
Prepaid.find query, (err, prepaids) ->
expect(err).toBeNull()
return done(err) if err
expect(prepaids?.length).toEqual(1)
return done() unless prepaids?.length > 0
expect(prepaids[0].get('type')).toEqual('course')
expect(prepaids[0].get('maxRedeemers')).toEqual(seats) if seats
# TODO: verify Payment
done(err)
tasks = []
for courseInstance in courseInstances
tasks.push makeCourseInstanceVerifyFn(courseInstance)
async.parallel tasks, (err) =>
return done(err) if err
done(err, courseInstances)
it 'Clear database', (done) ->
clearModels [User, Course, CourseInstance, Prepaid], (err) ->
throw err if err
done()
describe 'Single courses', ->
it 'Create for free course 1 seat', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 1, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
done()
it 'Create for free course no seats', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
name = createName 'course instance '
requestBody =
courseID: course.get('_id')
name: createName('course instance ')
request.post {uri: courseInstanceCreateURL, json: requestBody }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(422)
done()
it 'Create for free course no token', (done) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 2, null, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
done()
it 'Create for paid course 1 seat', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 7000, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 1, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
expect(prepaid.get('maxRedeemers')).toEqual(1)
expect(prepaid.get('properties')?.courseIDs).toEqual([course.get('_id')])
done()
it 'Create for paid course 50 seats', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 7000, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 50, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
expect(prepaid.get('maxRedeemers')).toEqual(50)
expect(prepaid.get('properties')?.courseIDs).toEqual([course.get('_id')])
done()
it 'Create for paid course no token', (done) ->
loginNewUser (user1) ->
createCourse 7000, (err, course) ->
expect(err).toBeNull()
return done(err) if err
name = createName 'course instance '
requestBody =
courseID: course.get('_id')
name: createName('course instance ')
seats: 1
request.post {uri: courseInstanceCreateURL, json: requestBody }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(422)
done()
it 'Create for paid course -1 seats', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 7000, (err, course) ->
expect(err).toBeNull()
return done(err) if err
name = createName 'course instance '
requestBody =
courseID: course.get('_id')
name: createName('course instance ')
seats: -1
request.post {uri: courseInstanceCreateURL, json: requestBody }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(422)
done()
describe 'All Courses', ->
it 'Create for 50 seats', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 7000, (err, course1) ->
expect(err).toBeNull()
return done(err) if err
createCourse 7000, (err, course2) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, null, 50, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
Course.find {}, (err, courses) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(courses.length)
Prepaid.find creator: user1.get('_id'), (err, prepaids) ->
expect(err).toBeNull()
return done(err) if err
expect(prepaids.length).toEqual(1)
return done('no prepaids found') unless prepaids?.length > 0
prepaid = prepaids[0]
expect(prepaid.get('maxRedeemers')).toEqual(50)
expect(prepaid.get('properties')?.courseIDs?.length).toEqual(courses.length)
done()
describe 'Invite to course', ->
it 'takes a list of emails and sends invites', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 1, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
inviteStudentsURL = getURL("/db/course_instance/#{courseInstances[0]._id}/invite_students")
requestBody = {
emails: ['test@test.com']
}
request.post { uri: inviteStudentsURL, json: requestBody }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(200)
done()
describe 'Redeem prepaid code', ->
it 'Redeem prepaid code for an instance of max 2', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 2, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
loginNewUser (user2) ->
request.post {uri: courseInstanceRedeemURL, json: {prepaidCode: prepaid.get('code')} }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(200)
# Check prepaid
Prepaid.findById prepaid.id, (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
expect(prepaid.get('redeemers')?.length).toEqual(1)
expect(prepaid.get('redeemers')[0].date).toBeLessThan(new Date())
expect(prepaid.get('redeemers')[0].userID).toEqual(user2.get('_id'))
# Check course instance
CourseInstance.findById courseInstances[0].id, (err, courseInstance) ->
expect(err).toBeNull()
return done(err) if err
members = courseInstance.get('members')
expect(members?.length).toEqual(2)
# TODO: must be a better way to check membership
usersFound = 0
for memberID in members
usersFound++ if memberID.equals(user1.get('_id'))
usersFound++ if memberID.equals(user2.get('_id'))
expect(usersFound).toEqual(2)
done()
it 'Redeem full prepaid code for on instance of max 1', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 1, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
loginNewUser (user2) ->
request.post {uri: courseInstanceRedeemURL, json: {prepaidCode: prepaid.get('code')} }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(200)
loginNewUser (user3) ->
request.post {uri: courseInstanceRedeemURL, json: {prepaidCode: prepaid.get('code')} }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(403)
done()
it 'Redeem 50 count course prepaid codes 51 times, in parallel', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
seatCount = 50
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), seatCount, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
forbiddenResults = 0
makeRedeemCall = ->
(callback) ->
loginNewUser (user2) ->
request.post {uri: courseInstanceRedeemURL, json: {prepaidCode: prepaid.get('code')} }, (err, res) ->
expect(err).toBeNull()
if res.statusCode is 403
forbiddenResults++
else
expect(res.statusCode).toBe(200)
callback err
tasks = (makeRedeemCall() for i in [1..seatCount+1])
async.parallel tasks, (err, results) ->
expect(err?).toEqual(false)
expect(forbiddenResults).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
expect(prepaid.get('redeemers')?.length).toEqual(prepaid.get('maxRedeemers'))
done()
it 'Redeem prepaid code twice', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 2, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
loginNewUser (user2) ->
# Redeem once
request.post {uri: courseInstanceRedeemURL, json: {prepaidCode: prepaid.get('code')} }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(200)
# Redeem twice
request.post {uri: courseInstanceRedeemURL, json: {prepaidCode: prepaid.get('code')} }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(200)
done()
| 193879 | async = require 'async'
config = require '../../../server_config'
require '../common'
stripe = require('stripe')(config.stripe.secretKey)
# TODO: add permissiosn tests
describe 'CourseInstance', ->
courseInstanceCreateURL = getURL('/db/course_instance/-/create')
courseInstanceRedeemURL = getURL('/db/course_instance/-/redeem_prepaid')
userURL = getURL('/db/user')
createCourseInstances = (user, courseID, seats, token, done) ->
name = createName 'course instance '
requestBody =
courseID: courseID
name: name
seats: seats
stripe:
token: token
request.post {uri: courseInstanceCreateURL, json: requestBody }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(201)
CourseInstance.find {name: name}, (err, courseInstances) ->
expect(err).toBeNull()
makeCourseInstanceVerifyFn = (courseInstance) ->
(done) ->
expect(courseInstance.get('name')).toEqual(name)
expect(courseInstance.get('ownerID')).toEqual(user.get('_id'))
expect(courseInstance.get('members')).toContain(user.get('_id'))
query = {$and: [{creator: user.get('_id')}]}
query.$and.push {'properties.courseIDs': {$in: [courseID]}} if courseID
Prepaid.find query, (err, prepaids) ->
expect(err).toBeNull()
return done(err) if err
expect(prepaids?.length).toEqual(1)
return done() unless prepaids?.length > 0
expect(prepaids[0].get('type')).toEqual('course')
expect(prepaids[0].get('maxRedeemers')).toEqual(seats) if seats
# TODO: verify Payment
done(err)
tasks = []
for courseInstance in courseInstances
tasks.push makeCourseInstanceVerifyFn(courseInstance)
async.parallel tasks, (err) =>
return done(err) if err
done(err, courseInstances)
it 'Clear database', (done) ->
clearModels [User, Course, CourseInstance, Prepaid], (err) ->
throw err if err
done()
describe 'Single courses', ->
it 'Create for free course 1 seat', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 1, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
done()
it 'Create for free course no seats', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
name = createName 'course instance '
requestBody =
courseID: course.get('_id')
name: createName('course instance ')
request.post {uri: courseInstanceCreateURL, json: requestBody }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(422)
done()
it 'Create for free course no token', (done) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 2, null, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
done()
it 'Create for paid course 1 seat', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 7000, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 1, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
expect(prepaid.get('maxRedeemers')).toEqual(1)
expect(prepaid.get('properties')?.courseIDs).toEqual([course.get('_id')])
done()
it 'Create for paid course 50 seats', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 7000, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 50, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
expect(prepaid.get('maxRedeemers')).toEqual(50)
expect(prepaid.get('properties')?.courseIDs).toEqual([course.get('_id')])
done()
it 'Create for paid course no token', (done) ->
loginNewUser (user1) ->
createCourse 7000, (err, course) ->
expect(err).toBeNull()
return done(err) if err
name = createName 'course instance '
requestBody =
courseID: course.get('_id')
name: createName('course instance ')
seats: 1
request.post {uri: courseInstanceCreateURL, json: requestBody }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(422)
done()
it 'Create for paid course -1 seats', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 7000, (err, course) ->
expect(err).toBeNull()
return done(err) if err
name = createName 'course instance '
requestBody =
courseID: course.get('_id')
name: createName('course instance ')
seats: -1
request.post {uri: courseInstanceCreateURL, json: requestBody }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(422)
done()
describe 'All Courses', ->
it 'Create for 50 seats', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 7000, (err, course1) ->
expect(err).toBeNull()
return done(err) if err
createCourse 7000, (err, course2) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, null, 50, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
Course.find {}, (err, courses) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(courses.length)
Prepaid.find creator: user1.get('_id'), (err, prepaids) ->
expect(err).toBeNull()
return done(err) if err
expect(prepaids.length).toEqual(1)
return done('no prepaids found') unless prepaids?.length > 0
prepaid = prepaids[0]
expect(prepaid.get('maxRedeemers')).toEqual(50)
expect(prepaid.get('properties')?.courseIDs?.length).toEqual(courses.length)
done()
describe 'Invite to course', ->
it 'takes a list of emails and sends invites', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 1, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
inviteStudentsURL = getURL("/db/course_instance/#{courseInstances[0]._id}/invite_students")
requestBody = {
emails: ['<EMAIL>']
}
request.post { uri: inviteStudentsURL, json: requestBody }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(200)
done()
describe 'Redeem prepaid code', ->
it 'Redeem prepaid code for an instance of max 2', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 2, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
loginNewUser (user2) ->
request.post {uri: courseInstanceRedeemURL, json: {prepaidCode: prepaid.get('code')} }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(200)
# Check prepaid
Prepaid.findById prepaid.id, (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
expect(prepaid.get('redeemers')?.length).toEqual(1)
expect(prepaid.get('redeemers')[0].date).toBeLessThan(new Date())
expect(prepaid.get('redeemers')[0].userID).toEqual(user2.get('_id'))
# Check course instance
CourseInstance.findById courseInstances[0].id, (err, courseInstance) ->
expect(err).toBeNull()
return done(err) if err
members = courseInstance.get('members')
expect(members?.length).toEqual(2)
# TODO: must be a better way to check membership
usersFound = 0
for memberID in members
usersFound++ if memberID.equals(user1.get('_id'))
usersFound++ if memberID.equals(user2.get('_id'))
expect(usersFound).toEqual(2)
done()
it 'Redeem full prepaid code for on instance of max 1', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 1, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
loginNewUser (user2) ->
request.post {uri: courseInstanceRedeemURL, json: {prepaidCode: prepaid.get('code')} }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(200)
loginNewUser (user3) ->
request.post {uri: courseInstanceRedeemURL, json: {prepaidCode: prepaid.get('code')} }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(403)
done()
it 'Redeem 50 count course prepaid codes 51 times, in parallel', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
seatCount = 50
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), seatCount, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
forbiddenResults = 0
makeRedeemCall = ->
(callback) ->
loginNewUser (user2) ->
request.post {uri: courseInstanceRedeemURL, json: {prepaidCode: prepaid.get('code')} }, (err, res) ->
expect(err).toBeNull()
if res.statusCode is 403
forbiddenResults++
else
expect(res.statusCode).toBe(200)
callback err
tasks = (makeRedeemCall() for i in [1..seatCount+1])
async.parallel tasks, (err, results) ->
expect(err?).toEqual(false)
expect(forbiddenResults).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
expect(prepaid.get('redeemers')?.length).toEqual(prepaid.get('maxRedeemers'))
done()
it 'Redeem prepaid code twice', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 2, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
loginNewUser (user2) ->
# Redeem once
request.post {uri: courseInstanceRedeemURL, json: {prepaidCode: prepaid.get('code')} }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(200)
# Redeem twice
request.post {uri: courseInstanceRedeemURL, json: {prepaidCode: prepaid.get('code')} }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(200)
done()
| true | async = require 'async'
config = require '../../../server_config'
require '../common'
stripe = require('stripe')(config.stripe.secretKey)
# TODO: add permissiosn tests
describe 'CourseInstance', ->
courseInstanceCreateURL = getURL('/db/course_instance/-/create')
courseInstanceRedeemURL = getURL('/db/course_instance/-/redeem_prepaid')
userURL = getURL('/db/user')
createCourseInstances = (user, courseID, seats, token, done) ->
name = createName 'course instance '
requestBody =
courseID: courseID
name: name
seats: seats
stripe:
token: token
request.post {uri: courseInstanceCreateURL, json: requestBody }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(201)
CourseInstance.find {name: name}, (err, courseInstances) ->
expect(err).toBeNull()
makeCourseInstanceVerifyFn = (courseInstance) ->
(done) ->
expect(courseInstance.get('name')).toEqual(name)
expect(courseInstance.get('ownerID')).toEqual(user.get('_id'))
expect(courseInstance.get('members')).toContain(user.get('_id'))
query = {$and: [{creator: user.get('_id')}]}
query.$and.push {'properties.courseIDs': {$in: [courseID]}} if courseID
Prepaid.find query, (err, prepaids) ->
expect(err).toBeNull()
return done(err) if err
expect(prepaids?.length).toEqual(1)
return done() unless prepaids?.length > 0
expect(prepaids[0].get('type')).toEqual('course')
expect(prepaids[0].get('maxRedeemers')).toEqual(seats) if seats
# TODO: verify Payment
done(err)
tasks = []
for courseInstance in courseInstances
tasks.push makeCourseInstanceVerifyFn(courseInstance)
async.parallel tasks, (err) =>
return done(err) if err
done(err, courseInstances)
it 'Clear database', (done) ->
clearModels [User, Course, CourseInstance, Prepaid], (err) ->
throw err if err
done()
describe 'Single courses', ->
it 'Create for free course 1 seat', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 1, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
done()
it 'Create for free course no seats', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
name = createName 'course instance '
requestBody =
courseID: course.get('_id')
name: createName('course instance ')
request.post {uri: courseInstanceCreateURL, json: requestBody }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(422)
done()
it 'Create for free course no token', (done) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 2, null, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
done()
it 'Create for paid course 1 seat', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 7000, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 1, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
expect(prepaid.get('maxRedeemers')).toEqual(1)
expect(prepaid.get('properties')?.courseIDs).toEqual([course.get('_id')])
done()
it 'Create for paid course 50 seats', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 7000, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 50, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
expect(prepaid.get('maxRedeemers')).toEqual(50)
expect(prepaid.get('properties')?.courseIDs).toEqual([course.get('_id')])
done()
it 'Create for paid course no token', (done) ->
loginNewUser (user1) ->
createCourse 7000, (err, course) ->
expect(err).toBeNull()
return done(err) if err
name = createName 'course instance '
requestBody =
courseID: course.get('_id')
name: createName('course instance ')
seats: 1
request.post {uri: courseInstanceCreateURL, json: requestBody }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(422)
done()
it 'Create for paid course -1 seats', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 7000, (err, course) ->
expect(err).toBeNull()
return done(err) if err
name = createName 'course instance '
requestBody =
courseID: course.get('_id')
name: createName('course instance ')
seats: -1
request.post {uri: courseInstanceCreateURL, json: requestBody }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(422)
done()
describe 'All Courses', ->
it 'Create for 50 seats', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 7000, (err, course1) ->
expect(err).toBeNull()
return done(err) if err
createCourse 7000, (err, course2) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, null, 50, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
Course.find {}, (err, courses) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(courses.length)
Prepaid.find creator: user1.get('_id'), (err, prepaids) ->
expect(err).toBeNull()
return done(err) if err
expect(prepaids.length).toEqual(1)
return done('no prepaids found') unless prepaids?.length > 0
prepaid = prepaids[0]
expect(prepaid.get('maxRedeemers')).toEqual(50)
expect(prepaid.get('properties')?.courseIDs?.length).toEqual(courses.length)
done()
describe 'Invite to course', ->
it 'takes a list of emails and sends invites', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 1, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
inviteStudentsURL = getURL("/db/course_instance/#{courseInstances[0]._id}/invite_students")
requestBody = {
emails: ['PI:EMAIL:<EMAIL>END_PI']
}
request.post { uri: inviteStudentsURL, json: requestBody }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(200)
done()
describe 'Redeem prepaid code', ->
it 'Redeem prepaid code for an instance of max 2', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 2, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
loginNewUser (user2) ->
request.post {uri: courseInstanceRedeemURL, json: {prepaidCode: prepaid.get('code')} }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(200)
# Check prepaid
Prepaid.findById prepaid.id, (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
expect(prepaid.get('redeemers')?.length).toEqual(1)
expect(prepaid.get('redeemers')[0].date).toBeLessThan(new Date())
expect(prepaid.get('redeemers')[0].userID).toEqual(user2.get('_id'))
# Check course instance
CourseInstance.findById courseInstances[0].id, (err, courseInstance) ->
expect(err).toBeNull()
return done(err) if err
members = courseInstance.get('members')
expect(members?.length).toEqual(2)
# TODO: must be a better way to check membership
usersFound = 0
for memberID in members
usersFound++ if memberID.equals(user1.get('_id'))
usersFound++ if memberID.equals(user2.get('_id'))
expect(usersFound).toEqual(2)
done()
it 'Redeem full prepaid code for on instance of max 1', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 1, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
loginNewUser (user2) ->
request.post {uri: courseInstanceRedeemURL, json: {prepaidCode: prepaid.get('code')} }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(200)
loginNewUser (user3) ->
request.post {uri: courseInstanceRedeemURL, json: {prepaidCode: prepaid.get('code')} }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(403)
done()
it 'Redeem 50 count course prepaid codes 51 times, in parallel', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
seatCount = 50
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), seatCount, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
forbiddenResults = 0
makeRedeemCall = ->
(callback) ->
loginNewUser (user2) ->
request.post {uri: courseInstanceRedeemURL, json: {prepaidCode: prepaid.get('code')} }, (err, res) ->
expect(err).toBeNull()
if res.statusCode is 403
forbiddenResults++
else
expect(res.statusCode).toBe(200)
callback err
tasks = (makeRedeemCall() for i in [1..seatCount+1])
async.parallel tasks, (err, results) ->
expect(err?).toEqual(false)
expect(forbiddenResults).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
expect(prepaid.get('redeemers')?.length).toEqual(prepaid.get('maxRedeemers'))
done()
it 'Redeem prepaid code twice', (done) ->
stripe.tokens.create {
card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' }
}, (err, token) ->
loginNewUser (user1) ->
createCourse 0, (err, course) ->
expect(err).toBeNull()
return done(err) if err
createCourseInstances user1, course.get('_id'), 2, token.id, (err, courseInstances) ->
expect(err).toBeNull()
return done(err) if err
expect(courseInstances.length).toEqual(1)
Prepaid.findById courseInstances[0].get('prepaidID'), (err, prepaid) ->
expect(err).toBeNull()
return done(err) if err
loginNewUser (user2) ->
# Redeem once
request.post {uri: courseInstanceRedeemURL, json: {prepaidCode: prepaid.get('code')} }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(200)
# Redeem twice
request.post {uri: courseInstanceRedeemURL, json: {prepaidCode: prepaid.get('code')} }, (err, res) ->
expect(err).toBeNull()
expect(res.statusCode).toBe(200)
done()
|
[
{
"context": "{}) ->\n @owner = owner\n @name = key = name\n @type = options.type || \"String\"\n if t",
"end": 122,
"score": 0.9381466507911682,
"start": 118,
"tag": "NAME",
"value": "name"
}
] | src/tower/model/attribute.coffee | hussainmuzzamil/tower | 1 | class Tower.Model.Attribute
constructor: (owner, name, options = {}) ->
@owner = owner
@name = key = name
@type = options.type || "String"
if typeof @type != "string"
@type = "Array"
@_default = options.default
@_encode = options.encode
@_decode = options.decode
if Tower.accessors
Object.defineProperty @owner.prototype, name,
enumerable: true
configurable: true
get: -> @get(key)
set: (value) -> @set(key, value)
defaultValue: (record) ->
_default = @_default
if Tower.Support.Object.isArray(_default)
_default.concat()
else if Tower.Support.Object.isHash(_default)
Tower.Support.Object.extend({}, _default)
else if typeof(_default) == "function"
_default.call(record)
else
_default
encode: (value, binding) ->
@code @_encode, value, binding
decode: (value, binding) ->
@code @_decode, value, binding
code: (type, value, binding) ->
switch type
when "string"
binding[type].call binding[type], value
when "function"
type.call _encode, value
else
value
module.exports = Tower.Model.Attribute
| 53099 | class Tower.Model.Attribute
constructor: (owner, name, options = {}) ->
@owner = owner
@name = key = <NAME>
@type = options.type || "String"
if typeof @type != "string"
@type = "Array"
@_default = options.default
@_encode = options.encode
@_decode = options.decode
if Tower.accessors
Object.defineProperty @owner.prototype, name,
enumerable: true
configurable: true
get: -> @get(key)
set: (value) -> @set(key, value)
defaultValue: (record) ->
_default = @_default
if Tower.Support.Object.isArray(_default)
_default.concat()
else if Tower.Support.Object.isHash(_default)
Tower.Support.Object.extend({}, _default)
else if typeof(_default) == "function"
_default.call(record)
else
_default
encode: (value, binding) ->
@code @_encode, value, binding
decode: (value, binding) ->
@code @_decode, value, binding
code: (type, value, binding) ->
switch type
when "string"
binding[type].call binding[type], value
when "function"
type.call _encode, value
else
value
module.exports = Tower.Model.Attribute
| true | class Tower.Model.Attribute
constructor: (owner, name, options = {}) ->
@owner = owner
@name = key = PI:NAME:<NAME>END_PI
@type = options.type || "String"
if typeof @type != "string"
@type = "Array"
@_default = options.default
@_encode = options.encode
@_decode = options.decode
if Tower.accessors
Object.defineProperty @owner.prototype, name,
enumerable: true
configurable: true
get: -> @get(key)
set: (value) -> @set(key, value)
defaultValue: (record) ->
_default = @_default
if Tower.Support.Object.isArray(_default)
_default.concat()
else if Tower.Support.Object.isHash(_default)
Tower.Support.Object.extend({}, _default)
else if typeof(_default) == "function"
_default.call(record)
else
_default
encode: (value, binding) ->
@code @_encode, value, binding
decode: (value, binding) ->
@code @_decode, value, binding
code: (type, value, binding) ->
switch type
when "string"
binding[type].call binding[type], value
when "function"
type.call _encode, value
else
value
module.exports = Tower.Model.Attribute
|
[
{
"context": " assert.equal(result, \"integration_public_key|c9f15b74b0d98635cd182c51e2703cffa83388c3\")\n\n describe \"sampleNotification\", ->\n it \"re",
"end": 582,
"score": 0.9996453523635864,
"start": 542,
"tag": "KEY",
"value": "c9f15b74b0d98635cd182c51e2703cffa83388c3"
}
] | spec/unit/braintree/webhook_notification_gateway_spec.coffee | StreamCo/braintree_node | 0 | require('../../spec_helper')
{ValidationErrorCodes} = require('../../../lib/braintree/validation_error_codes')
{WebhookNotification} = require('../../../lib/braintree')
{Dispute} = require('../../../lib/braintree/dispute')
{errorTypes} = require('../../../lib/braintree')
describe "WebhookNotificationGateway", ->
describe "verify", ->
it "creates a verification string for the challenge", ->
result = specHelper.defaultGateway.webhookNotification.verify("verification_token")
assert.equal(result, "integration_public_key|c9f15b74b0d98635cd182c51e2703cffa83388c3")
describe "sampleNotification", ->
it "returns a parsable signature and payload", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.SubscriptionWentPastDue)
assert.equal(webhookNotification.subscription.id, "my_id")
assert.ok(webhookNotification.timestamp?)
done()
it "retries a payload with a newline", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload.replace(/\n$/,''), (err, webhookNotification) ->
assert.equal(err, null)
assert.equal(webhookNotification.kind, WebhookNotification.Kind.SubscriptionWentPastDue)
assert.equal(webhookNotification.subscription.id, "my_id")
assert.ok(webhookNotification.timestamp?)
done()
it "returns an errback with InvalidSignatureError when signature is invalid", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse "bad_signature", bt_payload, (err, webhookNotification) ->
assert.equal(err.type, errorTypes.invalidSignatureError)
done()
it "returns an errback with InvalidSignatureError when the public key does not match", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse "bad#{bt_signature}", bt_payload, (err, webhookNotification) ->
assert.equal(err.type, errorTypes.invalidSignatureError)
assert.equal(err.message, "no matching public key")
done()
it "returns an errback with InvalidSignatureError when the signature is modified", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse "#{bt_signature}bad", bt_payload, (err, webhookNotification) ->
assert.equal(err.type, errorTypes.invalidSignatureError)
done()
it "returns an errback with InvalidSignatureError when the payload is modified", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, "bad#{bt_payload}", (err, webhookNotification) ->
assert.equal(err.type, errorTypes.invalidSignatureError)
assert.equal(err.message, "signature does not match payload - one has been modified")
done()
it "returns an errback with InvalidSignatureError when the payload contains invalid characters", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
bt_payload = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+=/\n"
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(err.type, errorTypes.invalidSignatureError)
assert.notEqual(err.message, "payload contains illegal characters")
done()
it "allows all valid characters", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, "^& bad ,* chars @!", (err, webhookNotification) ->
assert.equal(err.type, errorTypes.invalidSignatureError)
assert.equal(err.message, "payload contains illegal characters")
done()
it "returns a parsable signature and payload for merchant account approvals", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubMerchantAccountApproved,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.SubMerchantAccountApproved)
assert.equal(webhookNotification.merchantAccount.id, "my_id")
assert.ok(webhookNotification.timestamp?)
done()
it "returns a parsable signature and payload for merchant account declines", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubMerchantAccountDeclined,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.SubMerchantAccountDeclined)
assert.equal(webhookNotification.merchantAccount.id, "my_id")
assert.equal(webhookNotification.errors.for("merchantAccount").on("base")[0].code, ValidationErrorCodes.MerchantAccount.ApplicantDetails.DeclinedOFAC)
assert.equal(webhookNotification.message, "Credit score is too low")
assert.ok(webhookNotification.timestamp?)
done()
it "returns a parsable signature and payload for disbursed transaction", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.TransactionDisbursed,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.TransactionDisbursed)
assert.equal(webhookNotification.transaction.id, "my_id")
assert.equal(webhookNotification.transaction.amount, '100')
assert.ok(webhookNotification.transaction.disbursementDetails.disbursementDate?)
done()
it "returns a parsable signature and payload for dispute opened", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.DisputeOpened,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.DisputeOpened)
assert.equal(Dispute.Status.Open, webhookNotification.dispute.status)
done()
it "returns a parsable signature and payload for dispute lost", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.DisputeLost,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.DisputeLost)
assert.equal(Dispute.Status.Lost, webhookNotification.dispute.status)
done()
it "returns a parsable signature and payload for dispute won", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.DisputeWon,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.DisputeWon)
assert.equal(Dispute.Status.Won, webhookNotification.dispute.status)
done()
it "returns a parsable signature and payload for a disbursed webhook", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.Disbursement,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.Disbursement)
assert.equal(webhookNotification.disbursement.id, "my_id")
assert.equal(webhookNotification.disbursement.amount, "100.00")
assert.equal(webhookNotification.disbursement.transactionIds[0], "afv56j")
assert.equal(webhookNotification.disbursement.transactionIds[1], "kj8hjk")
assert.equal(webhookNotification.disbursement.success, true)
assert.equal(webhookNotification.disbursement.retry, false)
assert.equal(webhookNotification.disbursement.disbursementDate, "2014-02-10")
assert.equal(webhookNotification.disbursement.merchantAccount.id, "merchant_account_token")
assert.equal(webhookNotification.disbursement.merchantAccount.currencyIsoCode, "USD")
assert.equal(webhookNotification.disbursement.merchantAccount.subMerchantAccount, false)
assert.equal(webhookNotification.disbursement.merchantAccount.status, "active")
done()
it "returns a parsable signature and payload for disbursement exception webhook", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.DisbursementException,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.DisbursementException)
assert.equal(webhookNotification.disbursement.id, "my_id")
assert.equal(webhookNotification.disbursement.amount, "100.00")
assert.equal(webhookNotification.disbursement.transactionIds[0], "afv56j")
assert.equal(webhookNotification.disbursement.transactionIds[1], "kj8hjk")
assert.equal(webhookNotification.disbursement.success, false)
assert.equal(webhookNotification.disbursement.retry, false)
assert.equal(webhookNotification.disbursement.disbursementDate, "2014-02-10")
assert.equal(webhookNotification.disbursement.exceptionMessage, "bank_rejected")
assert.equal(webhookNotification.disbursement.followUpAction, "update_funding_information")
assert.equal(webhookNotification.disbursement.merchantAccount.id, "merchant_account_token")
assert.equal(webhookNotification.disbursement.merchantAccount.currencyIsoCode, "USD")
assert.equal(webhookNotification.disbursement.merchantAccount.subMerchantAccount, false)
assert.equal(webhookNotification.disbursement.merchantAccount.status, "active")
done()
it "builds a sample notification for a partner merchant connected webhook", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.PartnerMerchantConnected,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.PartnerMerchantConnected)
assert.equal(webhookNotification.partnerMerchant.publicKey, 'public_key')
assert.equal(webhookNotification.partnerMerchant.privateKey, 'private_key')
assert.equal(webhookNotification.partnerMerchant.clientSideEncryptionKey, 'cse_key')
assert.equal(webhookNotification.partnerMerchant.merchantPublicId, 'public_id')
assert.equal(webhookNotification.partnerMerchant.partnerMerchantId, 'abc123')
assert.ok(webhookNotification.timestamp?)
done()
it "builds a sample notification for a partner merchant disconnected webhook", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.PartnerMerchantDisconnected,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.PartnerMerchantDisconnected)
assert.equal(webhookNotification.partnerMerchant.partnerMerchantId, 'abc123')
assert.ok(webhookNotification.timestamp?)
done()
it "builds a sample notification for a partner merchant declined webhook", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.PartnerMerchantDeclined,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.PartnerMerchantDeclined)
assert.equal(webhookNotification.partnerMerchant.partnerMerchantId, 'abc123')
assert.ok(webhookNotification.timestamp?)
done()
| 118281 | require('../../spec_helper')
{ValidationErrorCodes} = require('../../../lib/braintree/validation_error_codes')
{WebhookNotification} = require('../../../lib/braintree')
{Dispute} = require('../../../lib/braintree/dispute')
{errorTypes} = require('../../../lib/braintree')
describe "WebhookNotificationGateway", ->
describe "verify", ->
it "creates a verification string for the challenge", ->
result = specHelper.defaultGateway.webhookNotification.verify("verification_token")
assert.equal(result, "integration_public_key|<KEY>")
describe "sampleNotification", ->
it "returns a parsable signature and payload", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.SubscriptionWentPastDue)
assert.equal(webhookNotification.subscription.id, "my_id")
assert.ok(webhookNotification.timestamp?)
done()
it "retries a payload with a newline", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload.replace(/\n$/,''), (err, webhookNotification) ->
assert.equal(err, null)
assert.equal(webhookNotification.kind, WebhookNotification.Kind.SubscriptionWentPastDue)
assert.equal(webhookNotification.subscription.id, "my_id")
assert.ok(webhookNotification.timestamp?)
done()
it "returns an errback with InvalidSignatureError when signature is invalid", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse "bad_signature", bt_payload, (err, webhookNotification) ->
assert.equal(err.type, errorTypes.invalidSignatureError)
done()
it "returns an errback with InvalidSignatureError when the public key does not match", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse "bad#{bt_signature}", bt_payload, (err, webhookNotification) ->
assert.equal(err.type, errorTypes.invalidSignatureError)
assert.equal(err.message, "no matching public key")
done()
it "returns an errback with InvalidSignatureError when the signature is modified", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse "#{bt_signature}bad", bt_payload, (err, webhookNotification) ->
assert.equal(err.type, errorTypes.invalidSignatureError)
done()
it "returns an errback with InvalidSignatureError when the payload is modified", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, "bad#{bt_payload}", (err, webhookNotification) ->
assert.equal(err.type, errorTypes.invalidSignatureError)
assert.equal(err.message, "signature does not match payload - one has been modified")
done()
it "returns an errback with InvalidSignatureError when the payload contains invalid characters", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
bt_payload = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+=/\n"
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(err.type, errorTypes.invalidSignatureError)
assert.notEqual(err.message, "payload contains illegal characters")
done()
it "allows all valid characters", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, "^& bad ,* chars @!", (err, webhookNotification) ->
assert.equal(err.type, errorTypes.invalidSignatureError)
assert.equal(err.message, "payload contains illegal characters")
done()
it "returns a parsable signature and payload for merchant account approvals", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubMerchantAccountApproved,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.SubMerchantAccountApproved)
assert.equal(webhookNotification.merchantAccount.id, "my_id")
assert.ok(webhookNotification.timestamp?)
done()
it "returns a parsable signature and payload for merchant account declines", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubMerchantAccountDeclined,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.SubMerchantAccountDeclined)
assert.equal(webhookNotification.merchantAccount.id, "my_id")
assert.equal(webhookNotification.errors.for("merchantAccount").on("base")[0].code, ValidationErrorCodes.MerchantAccount.ApplicantDetails.DeclinedOFAC)
assert.equal(webhookNotification.message, "Credit score is too low")
assert.ok(webhookNotification.timestamp?)
done()
it "returns a parsable signature and payload for disbursed transaction", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.TransactionDisbursed,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.TransactionDisbursed)
assert.equal(webhookNotification.transaction.id, "my_id")
assert.equal(webhookNotification.transaction.amount, '100')
assert.ok(webhookNotification.transaction.disbursementDetails.disbursementDate?)
done()
it "returns a parsable signature and payload for dispute opened", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.DisputeOpened,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.DisputeOpened)
assert.equal(Dispute.Status.Open, webhookNotification.dispute.status)
done()
it "returns a parsable signature and payload for dispute lost", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.DisputeLost,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.DisputeLost)
assert.equal(Dispute.Status.Lost, webhookNotification.dispute.status)
done()
it "returns a parsable signature and payload for dispute won", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.DisputeWon,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.DisputeWon)
assert.equal(Dispute.Status.Won, webhookNotification.dispute.status)
done()
it "returns a parsable signature and payload for a disbursed webhook", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.Disbursement,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.Disbursement)
assert.equal(webhookNotification.disbursement.id, "my_id")
assert.equal(webhookNotification.disbursement.amount, "100.00")
assert.equal(webhookNotification.disbursement.transactionIds[0], "afv56j")
assert.equal(webhookNotification.disbursement.transactionIds[1], "kj8hjk")
assert.equal(webhookNotification.disbursement.success, true)
assert.equal(webhookNotification.disbursement.retry, false)
assert.equal(webhookNotification.disbursement.disbursementDate, "2014-02-10")
assert.equal(webhookNotification.disbursement.merchantAccount.id, "merchant_account_token")
assert.equal(webhookNotification.disbursement.merchantAccount.currencyIsoCode, "USD")
assert.equal(webhookNotification.disbursement.merchantAccount.subMerchantAccount, false)
assert.equal(webhookNotification.disbursement.merchantAccount.status, "active")
done()
it "returns a parsable signature and payload for disbursement exception webhook", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.DisbursementException,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.DisbursementException)
assert.equal(webhookNotification.disbursement.id, "my_id")
assert.equal(webhookNotification.disbursement.amount, "100.00")
assert.equal(webhookNotification.disbursement.transactionIds[0], "afv56j")
assert.equal(webhookNotification.disbursement.transactionIds[1], "kj8hjk")
assert.equal(webhookNotification.disbursement.success, false)
assert.equal(webhookNotification.disbursement.retry, false)
assert.equal(webhookNotification.disbursement.disbursementDate, "2014-02-10")
assert.equal(webhookNotification.disbursement.exceptionMessage, "bank_rejected")
assert.equal(webhookNotification.disbursement.followUpAction, "update_funding_information")
assert.equal(webhookNotification.disbursement.merchantAccount.id, "merchant_account_token")
assert.equal(webhookNotification.disbursement.merchantAccount.currencyIsoCode, "USD")
assert.equal(webhookNotification.disbursement.merchantAccount.subMerchantAccount, false)
assert.equal(webhookNotification.disbursement.merchantAccount.status, "active")
done()
it "builds a sample notification for a partner merchant connected webhook", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.PartnerMerchantConnected,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.PartnerMerchantConnected)
assert.equal(webhookNotification.partnerMerchant.publicKey, 'public_key')
assert.equal(webhookNotification.partnerMerchant.privateKey, 'private_key')
assert.equal(webhookNotification.partnerMerchant.clientSideEncryptionKey, 'cse_key')
assert.equal(webhookNotification.partnerMerchant.merchantPublicId, 'public_id')
assert.equal(webhookNotification.partnerMerchant.partnerMerchantId, 'abc123')
assert.ok(webhookNotification.timestamp?)
done()
it "builds a sample notification for a partner merchant disconnected webhook", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.PartnerMerchantDisconnected,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.PartnerMerchantDisconnected)
assert.equal(webhookNotification.partnerMerchant.partnerMerchantId, 'abc123')
assert.ok(webhookNotification.timestamp?)
done()
it "builds a sample notification for a partner merchant declined webhook", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.PartnerMerchantDeclined,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.PartnerMerchantDeclined)
assert.equal(webhookNotification.partnerMerchant.partnerMerchantId, 'abc123')
assert.ok(webhookNotification.timestamp?)
done()
| true | require('../../spec_helper')
{ValidationErrorCodes} = require('../../../lib/braintree/validation_error_codes')
{WebhookNotification} = require('../../../lib/braintree')
{Dispute} = require('../../../lib/braintree/dispute')
{errorTypes} = require('../../../lib/braintree')
describe "WebhookNotificationGateway", ->
describe "verify", ->
it "creates a verification string for the challenge", ->
result = specHelper.defaultGateway.webhookNotification.verify("verification_token")
assert.equal(result, "integration_public_key|PI:KEY:<KEY>END_PI")
describe "sampleNotification", ->
it "returns a parsable signature and payload", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.SubscriptionWentPastDue)
assert.equal(webhookNotification.subscription.id, "my_id")
assert.ok(webhookNotification.timestamp?)
done()
it "retries a payload with a newline", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload.replace(/\n$/,''), (err, webhookNotification) ->
assert.equal(err, null)
assert.equal(webhookNotification.kind, WebhookNotification.Kind.SubscriptionWentPastDue)
assert.equal(webhookNotification.subscription.id, "my_id")
assert.ok(webhookNotification.timestamp?)
done()
it "returns an errback with InvalidSignatureError when signature is invalid", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse "bad_signature", bt_payload, (err, webhookNotification) ->
assert.equal(err.type, errorTypes.invalidSignatureError)
done()
it "returns an errback with InvalidSignatureError when the public key does not match", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse "bad#{bt_signature}", bt_payload, (err, webhookNotification) ->
assert.equal(err.type, errorTypes.invalidSignatureError)
assert.equal(err.message, "no matching public key")
done()
it "returns an errback with InvalidSignatureError when the signature is modified", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse "#{bt_signature}bad", bt_payload, (err, webhookNotification) ->
assert.equal(err.type, errorTypes.invalidSignatureError)
done()
it "returns an errback with InvalidSignatureError when the payload is modified", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, "bad#{bt_payload}", (err, webhookNotification) ->
assert.equal(err.type, errorTypes.invalidSignatureError)
assert.equal(err.message, "signature does not match payload - one has been modified")
done()
it "returns an errback with InvalidSignatureError when the payload contains invalid characters", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
bt_payload = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+=/\n"
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(err.type, errorTypes.invalidSignatureError)
assert.notEqual(err.message, "payload contains illegal characters")
done()
it "allows all valid characters", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, "^& bad ,* chars @!", (err, webhookNotification) ->
assert.equal(err.type, errorTypes.invalidSignatureError)
assert.equal(err.message, "payload contains illegal characters")
done()
it "returns a parsable signature and payload for merchant account approvals", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubMerchantAccountApproved,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.SubMerchantAccountApproved)
assert.equal(webhookNotification.merchantAccount.id, "my_id")
assert.ok(webhookNotification.timestamp?)
done()
it "returns a parsable signature and payload for merchant account declines", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.SubMerchantAccountDeclined,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.SubMerchantAccountDeclined)
assert.equal(webhookNotification.merchantAccount.id, "my_id")
assert.equal(webhookNotification.errors.for("merchantAccount").on("base")[0].code, ValidationErrorCodes.MerchantAccount.ApplicantDetails.DeclinedOFAC)
assert.equal(webhookNotification.message, "Credit score is too low")
assert.ok(webhookNotification.timestamp?)
done()
it "returns a parsable signature and payload for disbursed transaction", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.TransactionDisbursed,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.TransactionDisbursed)
assert.equal(webhookNotification.transaction.id, "my_id")
assert.equal(webhookNotification.transaction.amount, '100')
assert.ok(webhookNotification.transaction.disbursementDetails.disbursementDate?)
done()
it "returns a parsable signature and payload for dispute opened", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.DisputeOpened,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.DisputeOpened)
assert.equal(Dispute.Status.Open, webhookNotification.dispute.status)
done()
it "returns a parsable signature and payload for dispute lost", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.DisputeLost,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.DisputeLost)
assert.equal(Dispute.Status.Lost, webhookNotification.dispute.status)
done()
it "returns a parsable signature and payload for dispute won", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.DisputeWon,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.DisputeWon)
assert.equal(Dispute.Status.Won, webhookNotification.dispute.status)
done()
it "returns a parsable signature and payload for a disbursed webhook", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.Disbursement,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.Disbursement)
assert.equal(webhookNotification.disbursement.id, "my_id")
assert.equal(webhookNotification.disbursement.amount, "100.00")
assert.equal(webhookNotification.disbursement.transactionIds[0], "afv56j")
assert.equal(webhookNotification.disbursement.transactionIds[1], "kj8hjk")
assert.equal(webhookNotification.disbursement.success, true)
assert.equal(webhookNotification.disbursement.retry, false)
assert.equal(webhookNotification.disbursement.disbursementDate, "2014-02-10")
assert.equal(webhookNotification.disbursement.merchantAccount.id, "merchant_account_token")
assert.equal(webhookNotification.disbursement.merchantAccount.currencyIsoCode, "USD")
assert.equal(webhookNotification.disbursement.merchantAccount.subMerchantAccount, false)
assert.equal(webhookNotification.disbursement.merchantAccount.status, "active")
done()
it "returns a parsable signature and payload for disbursement exception webhook", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.DisbursementException,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.DisbursementException)
assert.equal(webhookNotification.disbursement.id, "my_id")
assert.equal(webhookNotification.disbursement.amount, "100.00")
assert.equal(webhookNotification.disbursement.transactionIds[0], "afv56j")
assert.equal(webhookNotification.disbursement.transactionIds[1], "kj8hjk")
assert.equal(webhookNotification.disbursement.success, false)
assert.equal(webhookNotification.disbursement.retry, false)
assert.equal(webhookNotification.disbursement.disbursementDate, "2014-02-10")
assert.equal(webhookNotification.disbursement.exceptionMessage, "bank_rejected")
assert.equal(webhookNotification.disbursement.followUpAction, "update_funding_information")
assert.equal(webhookNotification.disbursement.merchantAccount.id, "merchant_account_token")
assert.equal(webhookNotification.disbursement.merchantAccount.currencyIsoCode, "USD")
assert.equal(webhookNotification.disbursement.merchantAccount.subMerchantAccount, false)
assert.equal(webhookNotification.disbursement.merchantAccount.status, "active")
done()
it "builds a sample notification for a partner merchant connected webhook", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.PartnerMerchantConnected,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.PartnerMerchantConnected)
assert.equal(webhookNotification.partnerMerchant.publicKey, 'public_key')
assert.equal(webhookNotification.partnerMerchant.privateKey, 'private_key')
assert.equal(webhookNotification.partnerMerchant.clientSideEncryptionKey, 'cse_key')
assert.equal(webhookNotification.partnerMerchant.merchantPublicId, 'public_id')
assert.equal(webhookNotification.partnerMerchant.partnerMerchantId, 'abc123')
assert.ok(webhookNotification.timestamp?)
done()
it "builds a sample notification for a partner merchant disconnected webhook", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.PartnerMerchantDisconnected,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.PartnerMerchantDisconnected)
assert.equal(webhookNotification.partnerMerchant.partnerMerchantId, 'abc123')
assert.ok(webhookNotification.timestamp?)
done()
it "builds a sample notification for a partner merchant declined webhook", (done) ->
{bt_signature, bt_payload} = specHelper.defaultGateway.webhookTesting.sampleNotification(
WebhookNotification.Kind.PartnerMerchantDeclined,
"my_id"
)
specHelper.defaultGateway.webhookNotification.parse bt_signature, bt_payload, (err, webhookNotification) ->
assert.equal(webhookNotification.kind, WebhookNotification.Kind.PartnerMerchantDeclined)
assert.equal(webhookNotification.partnerMerchant.partnerMerchantId, 'abc123')
assert.ok(webhookNotification.timestamp?)
done()
|
[
{
"context": ":\n _cls: 'Drug'\n name: 'trastuzumab'\n amount: 2.3\n start_date: ",
"end": 2523,
"score": 0.9990450739860535,
"start": 2512,
"tag": "NAME",
"value": "trastuzumab"
},
{
"context": ":\n _cls: 'Drug'\n ... | src/subject/subject.data.spec.coffee | ohsu-qin/qiprofile | 0 | `import * as _ from "lodash"`
`import moment from "moment"`
`import REST from "../rest/rest.coffee"`
`import Subject from "./subject.data.coffee"`
###*
* The {{#crossLink "Subject"}}{{/crossLink}} validator.
*
* Note: image load cannot be unit-tested, since it requires an
* active browser.
*
* @module subject
* @class SubjectSpec
###
describe 'The Subject data utility', ->
# The fetched subject
subject = null
# The mock subject REST response.
mock =
json: ->
_id: 's1'
project: 'QIN_Test'
collection: 'Breast'
number: 1
birth_date: moment('Aug 21, 1986', 'MMM DD, YYYY').valueOf()
encounters: [
{
_cls: 'Session'
number: 1
acquisition_date: moment('Jul 1, 2013', 'MMM DD, YYYY').valueOf()
detail: 'sd1'
modelings: [
resource: 'pk_01'
protocol: 'mp1'
source:
registration: 'rp1'
result:
delta_k_trans:
name: "path/to/first/delta_k_trans.nii.gz"
average: 2.3
label_map:
name: "path/to/first/delta_k_trans_color.nii.gz"
color_table: "path/to/color_table.txt"
]
}
{
_cls: 'Session'
number: 2
acquisition_date: moment('Aug 1, 2013', 'MMM DD, YYYY').valueOf()
detail: 'sd2'
modelings: [
resource: 'pk_02'
protocol: 'mp1'
source:
registration: 'rp1'
result:
delta_k_trans:
name: "path/to/second/delta_k_trans.nii.gz"
average: 2.4
label_map:
name: "path/to/second/delta_k_trans_color.nii.gz"
color_table: "path/to/color_table.txt"
]
}
{
_cls: 'BreastSurgery'
date: moment('Jul 12, 2013', 'MMM DD, YYYY').valueOf()
pathology:
_cls: 'PathologyReport'
tumors: [
_cls: 'BreastPathology'
tnm:
size:
prefix: 'p'
tumor_size: 3
]
}
]
treatments: [
treatment_type: 'neodjuvant'
start_date: moment('Jun 4, 2013', 'MMM DD, YYYY').valueOf()
end_date: moment('Jul 16, 2013', 'MMM DD, YYYY').valueOf()
dosages: [
{
agent:
_cls: 'Drug'
name: 'trastuzumab'
amount: 2.3
start_date: moment('Jun 4, 2013', 'MMM DD, YYYY').valueOf()
duration: 20
}
{
agent:
_cls: 'Drug'
name: 'pertuzumab'
amount: 4.1
start_date: moment('Jun 16, 2013', 'MMM DD, YYYY').valueOf()
duration: 30
}
]
]
beforeEach ->
data = REST.transformResponse(mock)
subject = Subject.extend(data)
describe 'Demographics', ->
# Validate the birth date.
it 'should anonymize the subject birth date', ->
expect(subject.birthDate, "The subject is missing a birth date")
.to.exist
expect(subject.birthDate.valueOf(), "The subject birth date is" +
" incorrect")
.to.equal(moment('Jul 7, 1986', 'MMM DD, YYYY').valueOf())
describe 'Clinical', ->
# Validate the clinical encounters.
it 'should set the clinical encounters', ->
expect(subject.clinicalEncounters,
"The subject is missing clinical encounters")
.to.exist
expect(subject.clinicalEncounters.length,
"The subject clinical encounters length is incorrect")
.to.equal(1)
describe 'Encounter', ->
encounter = null
beforeEach ->
encounter = subject.clinicalEncounters[0]
it 'should set the clinical encounter title', ->
expect(encounter.title, "The encounter is missing a title").to.exist
expect(encounter.title, "The encounter title is incorrect")
.to.equal('Surgery')
it 'should set the clinical encounter age', ->
expect(encounter.title, "The encounter is missing a title").to.exist
expect(encounter.title, "The encounter title is incorrect")
.to.equal('Surgery')
# Validate the treatments.
it 'should extend the subject treatments', ->
expect(subject.treatments, "The subject is missing treatments")
.to.exist
expect(subject.treatments.length, "The subject encounters length" +
" is incorrect").to.equal(1)
describe 'Treatment', ->
treatment = null
mockTreatment = null
beforeEach ->
treatment = subject.treatments[0]
mockTreatment = mock.json().treatments[0]
it 'should have a type', ->
expect(treatment.treatmentType, "The treatment type is missing").to.exist
expect(treatment.treatmentType, "The treatment type is incorrect")
.to.equal(mockTreatment.treatment_type)
it 'should have a start data', ->
expect(treatment.start_date.valueOf(),
"Treatment start date is incorrect")
.to.equal(mockTreatment.start_date)
it 'should have dosages', ->
expect(treatment.dosages, "The treatment dosages is missing")
.to.exist.and.not.be.empty
expect(treatment.dosages.length, "The treatment dosages count is incorrect")
.to.equal(2)
describe 'Dosage', ->
dosage = null
mockDosage = null
beforeEach ->
dosage = treatment.dosages[0]
mockDosage = mockTreatment.dosages[0]
it 'should have an agent', ->
expect(dosage.agent, "The dosage agent is missing").to.exist
expect(dosage.agent.name, "The dosage agent name is missing").to.exist
it 'should have a start date', ->
expect(dosage.start_date.valueOf(), "The treatment dosage start date" +
" is incorrect")
.to.equal(mockDosage.start_date)
it 'should have a duration', ->
expect(dosage.duration, "The treatment dosage duration is incorrect")
.to.equal(mockDosage.duration)
describe 'Session', ->
# Validate the sessions (without detail).
it 'should have a subject session', ->
expect(subject.sessions, "The subject is missing sessions").to.exist
expect(subject.sessions.length, "The subject session count is" +
" incorrect")
.to.equal(2)
it 'should set the subject multiSession flag', ->
expect(subject.isMultiSession(), "The subject multi-session flag" +
" is incorrect")
.to.be.true
it 'should set the session number', ->
sessionNbr = subject.sessions[0].number
expect(sessionNbr, "The session is missing a number").to.exist
expect(sessionNbr, "The subject session number is incorrect")
.to.equal(1)
| 53438 | `import * as _ from "lodash"`
`import moment from "moment"`
`import REST from "../rest/rest.coffee"`
`import Subject from "./subject.data.coffee"`
###*
* The {{#crossLink "Subject"}}{{/crossLink}} validator.
*
* Note: image load cannot be unit-tested, since it requires an
* active browser.
*
* @module subject
* @class SubjectSpec
###
describe 'The Subject data utility', ->
# The fetched subject
subject = null
# The mock subject REST response.
mock =
json: ->
_id: 's1'
project: 'QIN_Test'
collection: 'Breast'
number: 1
birth_date: moment('Aug 21, 1986', 'MMM DD, YYYY').valueOf()
encounters: [
{
_cls: 'Session'
number: 1
acquisition_date: moment('Jul 1, 2013', 'MMM DD, YYYY').valueOf()
detail: 'sd1'
modelings: [
resource: 'pk_01'
protocol: 'mp1'
source:
registration: 'rp1'
result:
delta_k_trans:
name: "path/to/first/delta_k_trans.nii.gz"
average: 2.3
label_map:
name: "path/to/first/delta_k_trans_color.nii.gz"
color_table: "path/to/color_table.txt"
]
}
{
_cls: 'Session'
number: 2
acquisition_date: moment('Aug 1, 2013', 'MMM DD, YYYY').valueOf()
detail: 'sd2'
modelings: [
resource: 'pk_02'
protocol: 'mp1'
source:
registration: 'rp1'
result:
delta_k_trans:
name: "path/to/second/delta_k_trans.nii.gz"
average: 2.4
label_map:
name: "path/to/second/delta_k_trans_color.nii.gz"
color_table: "path/to/color_table.txt"
]
}
{
_cls: 'BreastSurgery'
date: moment('Jul 12, 2013', 'MMM DD, YYYY').valueOf()
pathology:
_cls: 'PathologyReport'
tumors: [
_cls: 'BreastPathology'
tnm:
size:
prefix: 'p'
tumor_size: 3
]
}
]
treatments: [
treatment_type: 'neodjuvant'
start_date: moment('Jun 4, 2013', 'MMM DD, YYYY').valueOf()
end_date: moment('Jul 16, 2013', 'MMM DD, YYYY').valueOf()
dosages: [
{
agent:
_cls: 'Drug'
name: '<NAME>'
amount: 2.3
start_date: moment('Jun 4, 2013', 'MMM DD, YYYY').valueOf()
duration: 20
}
{
agent:
_cls: 'Drug'
name: '<NAME>'
amount: 4.1
start_date: moment('Jun 16, 2013', 'MMM DD, YYYY').valueOf()
duration: 30
}
]
]
beforeEach ->
data = REST.transformResponse(mock)
subject = Subject.extend(data)
describe 'Demographics', ->
# Validate the birth date.
it 'should anonymize the subject birth date', ->
expect(subject.birthDate, "The subject is missing a birth date")
.to.exist
expect(subject.birthDate.valueOf(), "The subject birth date is" +
" incorrect")
.to.equal(moment('Jul 7, 1986', 'MMM DD, YYYY').valueOf())
describe 'Clinical', ->
# Validate the clinical encounters.
it 'should set the clinical encounters', ->
expect(subject.clinicalEncounters,
"The subject is missing clinical encounters")
.to.exist
expect(subject.clinicalEncounters.length,
"The subject clinical encounters length is incorrect")
.to.equal(1)
describe 'Encounter', ->
encounter = null
beforeEach ->
encounter = subject.clinicalEncounters[0]
it 'should set the clinical encounter title', ->
expect(encounter.title, "The encounter is missing a title").to.exist
expect(encounter.title, "The encounter title is incorrect")
.to.equal('Surgery')
it 'should set the clinical encounter age', ->
expect(encounter.title, "The encounter is missing a title").to.exist
expect(encounter.title, "The encounter title is incorrect")
.to.equal('Surgery')
# Validate the treatments.
it 'should extend the subject treatments', ->
expect(subject.treatments, "The subject is missing treatments")
.to.exist
expect(subject.treatments.length, "The subject encounters length" +
" is incorrect").to.equal(1)
describe 'Treatment', ->
treatment = null
mockTreatment = null
beforeEach ->
treatment = subject.treatments[0]
mockTreatment = mock.json().treatments[0]
it 'should have a type', ->
expect(treatment.treatmentType, "The treatment type is missing").to.exist
expect(treatment.treatmentType, "The treatment type is incorrect")
.to.equal(mockTreatment.treatment_type)
it 'should have a start data', ->
expect(treatment.start_date.valueOf(),
"Treatment start date is incorrect")
.to.equal(mockTreatment.start_date)
it 'should have dosages', ->
expect(treatment.dosages, "The treatment dosages is missing")
.to.exist.and.not.be.empty
expect(treatment.dosages.length, "The treatment dosages count is incorrect")
.to.equal(2)
describe 'Dosage', ->
dosage = null
mockDosage = null
beforeEach ->
dosage = treatment.dosages[0]
mockDosage = mockTreatment.dosages[0]
it 'should have an agent', ->
expect(dosage.agent, "The dosage agent is missing").to.exist
expect(dosage.agent.name, "The dosage agent name is missing").to.exist
it 'should have a start date', ->
expect(dosage.start_date.valueOf(), "The treatment dosage start date" +
" is incorrect")
.to.equal(mockDosage.start_date)
it 'should have a duration', ->
expect(dosage.duration, "The treatment dosage duration is incorrect")
.to.equal(mockDosage.duration)
describe 'Session', ->
# Validate the sessions (without detail).
it 'should have a subject session', ->
expect(subject.sessions, "The subject is missing sessions").to.exist
expect(subject.sessions.length, "The subject session count is" +
" incorrect")
.to.equal(2)
it 'should set the subject multiSession flag', ->
expect(subject.isMultiSession(), "The subject multi-session flag" +
" is incorrect")
.to.be.true
it 'should set the session number', ->
sessionNbr = subject.sessions[0].number
expect(sessionNbr, "The session is missing a number").to.exist
expect(sessionNbr, "The subject session number is incorrect")
.to.equal(1)
| true | `import * as _ from "lodash"`
`import moment from "moment"`
`import REST from "../rest/rest.coffee"`
`import Subject from "./subject.data.coffee"`
###*
* The {{#crossLink "Subject"}}{{/crossLink}} validator.
*
* Note: image load cannot be unit-tested, since it requires an
* active browser.
*
* @module subject
* @class SubjectSpec
###
describe 'The Subject data utility', ->
# The fetched subject
subject = null
# The mock subject REST response.
mock =
json: ->
_id: 's1'
project: 'QIN_Test'
collection: 'Breast'
number: 1
birth_date: moment('Aug 21, 1986', 'MMM DD, YYYY').valueOf()
encounters: [
{
_cls: 'Session'
number: 1
acquisition_date: moment('Jul 1, 2013', 'MMM DD, YYYY').valueOf()
detail: 'sd1'
modelings: [
resource: 'pk_01'
protocol: 'mp1'
source:
registration: 'rp1'
result:
delta_k_trans:
name: "path/to/first/delta_k_trans.nii.gz"
average: 2.3
label_map:
name: "path/to/first/delta_k_trans_color.nii.gz"
color_table: "path/to/color_table.txt"
]
}
{
_cls: 'Session'
number: 2
acquisition_date: moment('Aug 1, 2013', 'MMM DD, YYYY').valueOf()
detail: 'sd2'
modelings: [
resource: 'pk_02'
protocol: 'mp1'
source:
registration: 'rp1'
result:
delta_k_trans:
name: "path/to/second/delta_k_trans.nii.gz"
average: 2.4
label_map:
name: "path/to/second/delta_k_trans_color.nii.gz"
color_table: "path/to/color_table.txt"
]
}
{
_cls: 'BreastSurgery'
date: moment('Jul 12, 2013', 'MMM DD, YYYY').valueOf()
pathology:
_cls: 'PathologyReport'
tumors: [
_cls: 'BreastPathology'
tnm:
size:
prefix: 'p'
tumor_size: 3
]
}
]
treatments: [
treatment_type: 'neodjuvant'
start_date: moment('Jun 4, 2013', 'MMM DD, YYYY').valueOf()
end_date: moment('Jul 16, 2013', 'MMM DD, YYYY').valueOf()
dosages: [
{
agent:
_cls: 'Drug'
name: 'PI:NAME:<NAME>END_PI'
amount: 2.3
start_date: moment('Jun 4, 2013', 'MMM DD, YYYY').valueOf()
duration: 20
}
{
agent:
_cls: 'Drug'
name: 'PI:NAME:<NAME>END_PI'
amount: 4.1
start_date: moment('Jun 16, 2013', 'MMM DD, YYYY').valueOf()
duration: 30
}
]
]
beforeEach ->
data = REST.transformResponse(mock)
subject = Subject.extend(data)
describe 'Demographics', ->
# Validate the birth date.
it 'should anonymize the subject birth date', ->
expect(subject.birthDate, "The subject is missing a birth date")
.to.exist
expect(subject.birthDate.valueOf(), "The subject birth date is" +
" incorrect")
.to.equal(moment('Jul 7, 1986', 'MMM DD, YYYY').valueOf())
describe 'Clinical', ->
# Validate the clinical encounters.
it 'should set the clinical encounters', ->
expect(subject.clinicalEncounters,
"The subject is missing clinical encounters")
.to.exist
expect(subject.clinicalEncounters.length,
"The subject clinical encounters length is incorrect")
.to.equal(1)
describe 'Encounter', ->
encounter = null
beforeEach ->
encounter = subject.clinicalEncounters[0]
it 'should set the clinical encounter title', ->
expect(encounter.title, "The encounter is missing a title").to.exist
expect(encounter.title, "The encounter title is incorrect")
.to.equal('Surgery')
it 'should set the clinical encounter age', ->
expect(encounter.title, "The encounter is missing a title").to.exist
expect(encounter.title, "The encounter title is incorrect")
.to.equal('Surgery')
# Validate the treatments.
it 'should extend the subject treatments', ->
expect(subject.treatments, "The subject is missing treatments")
.to.exist
expect(subject.treatments.length, "The subject encounters length" +
" is incorrect").to.equal(1)
describe 'Treatment', ->
treatment = null
mockTreatment = null
beforeEach ->
treatment = subject.treatments[0]
mockTreatment = mock.json().treatments[0]
it 'should have a type', ->
expect(treatment.treatmentType, "The treatment type is missing").to.exist
expect(treatment.treatmentType, "The treatment type is incorrect")
.to.equal(mockTreatment.treatment_type)
it 'should have a start data', ->
expect(treatment.start_date.valueOf(),
"Treatment start date is incorrect")
.to.equal(mockTreatment.start_date)
it 'should have dosages', ->
expect(treatment.dosages, "The treatment dosages is missing")
.to.exist.and.not.be.empty
expect(treatment.dosages.length, "The treatment dosages count is incorrect")
.to.equal(2)
describe 'Dosage', ->
dosage = null
mockDosage = null
beforeEach ->
dosage = treatment.dosages[0]
mockDosage = mockTreatment.dosages[0]
it 'should have an agent', ->
expect(dosage.agent, "The dosage agent is missing").to.exist
expect(dosage.agent.name, "The dosage agent name is missing").to.exist
it 'should have a start date', ->
expect(dosage.start_date.valueOf(), "The treatment dosage start date" +
" is incorrect")
.to.equal(mockDosage.start_date)
it 'should have a duration', ->
expect(dosage.duration, "The treatment dosage duration is incorrect")
.to.equal(mockDosage.duration)
describe 'Session', ->
# Validate the sessions (without detail).
it 'should have a subject session', ->
expect(subject.sessions, "The subject is missing sessions").to.exist
expect(subject.sessions.length, "The subject session count is" +
" incorrect")
.to.equal(2)
it 'should set the subject multiSession flag', ->
expect(subject.isMultiSession(), "The subject multi-session flag" +
" is incorrect")
.to.be.true
it 'should set the session number', ->
sessionNbr = subject.sessions[0].number
expect(sessionNbr, "The session is missing a number").to.exist
expect(sessionNbr, "The subject session number is incorrect")
.to.equal(1)
|
[
{
"context": "->\n counts = [\n {key: ['id1', 'bar'], value: 1},\n {key: 'id2',",
"end": 4843,
"score": 0.8544619083404541,
"start": 4840,
"tag": "KEY",
"value": "id1"
},
{
"context": " counts = [\n {key: ['id1', 'bar'], ... | src/tests/server/blip/test_search_result_processor.coffee | LaPingvino/rizzoma | 88 | testCase = require('nodeunit').testCase
sinon = require('sinon-plus')
dataprovider = require('dataprovider')
BlipSearchResultProcessor = require('../../../server/blip/search_result_processor').BlipSearchResultProcessor
CouchBlipProcessor = require('../../../server/blip/couch_processor').CouchBlipProcessor
BlipModel = require('../../../server/blip/models').BlipModel
CouchWaveProcessor = require('../../../server/wave/couch_processor').CouchWaveProcessor
WaveModel = require('../../../server/wave/models').WaveModel
UserCouchProcessor = require('../../../server/user/couch_processor').UserCouchProcessor
module.exports =
BlipSearchResultProcessorTest: testCase
setUp: (callback) ->
callback()
tearDown: (callback) ->
callback()
testGetItem: (test) ->
prcocessorMock = sinon.mock(BlipSearchResultProcessor)
prcocessorMock
.expects('_hasAllPtag')
.once()
.withArgs('tags')
.returns(true)
prcocessorMock
.expects('_isFollow')
.once()
.withArgs({wave_url: 'foo', groupdate: 'bar'}, 'user')
.returns(true)
testCode = (done, changed, expected) ->
res = BlipSearchResultProcessor._getItem({wave_url: 'foo', groupdate: 'bar'}, changed, 'user', 'tags')
test.deepEqual(res, expected)
sinon.verifyAll()
sinon.restoreAll()
done()
dataprovider(test, [
[true, {waveId: 'foo', changeDate: 'bar', follow: true}]
[false, {waveId: 'foo'}]
], testCode)
testIsFollow: (test) ->
testCode = (done, ptags, expected) ->
res = BlipSearchResultProcessor._isFollow({ptags}, {id: '0_u_15'})
test.equal(res, expected)
done()
dataprovider(test, [
[[1024, 9727, 7463], true]
[[1024, 9726, 7463], false]
], testCode)
testGetChangedItems: (test) ->
prcocessorMock = sinon.mock(BlipSearchResultProcessor)
prcocessorMock
.expects('_getWavesAndStuffIds')
.once()
.withArgs('ids')
.callsArgWith(1, null, 'waves', 'blipsIds', 'creatorsIds')
blipProcessorMock = sinon.mock(CouchBlipProcessor)
blipProcessorMock
.expects('getByIdsAsDict')
.once()
.withArgs('blipsIds')
.callsArgWith(1, null, 'blips')
userProcessorMock = sinon.mock(UserCouchProcessor)
userProcessorMock
.expects('getByIdsAsDict')
.once()
.withArgs('creatorsIds')
.callsArgWith(1, null, 'creators')
prcocessorMock
.expects('_getReadBlipCounts')
.once()
.withArgs('ids', 'userId')
.callsArgWith(2, null, 'readBlips')
prcocessorMock
.expects('_getTotalBlipCounts')
.once()
.withArgs('ids')
.callsArgWith(1, null, 'totalBlips')
prcocessorMock
.expects('_compileItems')
.once()
.withArgs('waves', 'blips', 'creators', 'readBlips', 'totalBlips')
.callsArgWith(5, null, 'foo')
BlipSearchResultProcessor._getChangedItems('ids', {id: 'userId'}, 'tags', (err, res) ->
test.equal(null, err)
test.equal('foo', res)
sinon.verifyAll()
sinon.restoreAll()
test.done()
)
testGetWavesAndStuffIds: (test) ->
wave = new WaveModel()
wave.rootBlipId = 'blipId'
waveMock = sinon.mock(wave)
.expects('getFirstParticipantWithRole')
.once()
.returns({id: 'creatorId'})
prcocessorMock = sinon.mock(CouchWaveProcessor)
prcocessorMock
.expects('getByIdsAsDict')
.once()
.withArgs('ids')
.callsArgWith(1, null, {foo: wave})
BlipSearchResultProcessor._getWavesAndStuffIds('ids', (err, waves, rootBlipsIds, creatoresIds) ->
test.equal(null, err)
test.deepEqual({foo: wave}, waves)
test.deepEqual(['blipId'], rootBlipsIds)
test.deepEqual(['creatorId'], creatoresIds)
sinon.verifyAll()
sinon.restoreAll()
test.done()
)
testConvertCountsToDict: (test) ->
counts = [
{key: ['id1', 'bar'], value: 1},
{key: 'id2', value: 2},
{key: ['id3'], value: 3}
]
res = BlipSearchResultProcessor._convertCountsToDict(counts)
test.deepEqual({
'id1': 1
'id2': 2
'id3': 3
}, res)
test.done()
testComplileChangedWavesInfo: (test) ->
wave = new WaveModel()
wave.rootBlipId = 'blipId'
waveMock = sinon.mock(wave)
waveMock
.expects('getFirstParticipantWithRole')
.once()
.returns({id: 'creatorId'})
blip = new BlipModel()
blipMock = sinon.mock(blip)
blipMock
.expects('getTitle')
.once()
.returns('foo')
blipMock
.expects('getSnippet')
.once()
.returns('bar')
waves = {waveId: wave}
blips = {blipId: blip}
creators = {creatorId: {name: 'name', avatar: 'avatar'}}
readBlipsStat = {waveId: 5}
totalBlipsStat = {waveId: 20}
BlipSearchResultProcessor._compileItems(waves, blips, creators, readBlipsStat, totalBlipsStat, (err, items) ->
test.deepEqual({waveId: {
title: 'foo'
snippet: 'bar'
avatar: 'avatar'
name: 'name'
totalBlipCount: 20
totalUnreadBlipCount: 15
}}, items)
sinon.verifyAll()
sinon.restoreAll()
test.done()
)
| 202826 | testCase = require('nodeunit').testCase
sinon = require('sinon-plus')
dataprovider = require('dataprovider')
BlipSearchResultProcessor = require('../../../server/blip/search_result_processor').BlipSearchResultProcessor
CouchBlipProcessor = require('../../../server/blip/couch_processor').CouchBlipProcessor
BlipModel = require('../../../server/blip/models').BlipModel
CouchWaveProcessor = require('../../../server/wave/couch_processor').CouchWaveProcessor
WaveModel = require('../../../server/wave/models').WaveModel
UserCouchProcessor = require('../../../server/user/couch_processor').UserCouchProcessor
module.exports =
BlipSearchResultProcessorTest: testCase
setUp: (callback) ->
callback()
tearDown: (callback) ->
callback()
testGetItem: (test) ->
prcocessorMock = sinon.mock(BlipSearchResultProcessor)
prcocessorMock
.expects('_hasAllPtag')
.once()
.withArgs('tags')
.returns(true)
prcocessorMock
.expects('_isFollow')
.once()
.withArgs({wave_url: 'foo', groupdate: 'bar'}, 'user')
.returns(true)
testCode = (done, changed, expected) ->
res = BlipSearchResultProcessor._getItem({wave_url: 'foo', groupdate: 'bar'}, changed, 'user', 'tags')
test.deepEqual(res, expected)
sinon.verifyAll()
sinon.restoreAll()
done()
dataprovider(test, [
[true, {waveId: 'foo', changeDate: 'bar', follow: true}]
[false, {waveId: 'foo'}]
], testCode)
testIsFollow: (test) ->
testCode = (done, ptags, expected) ->
res = BlipSearchResultProcessor._isFollow({ptags}, {id: '0_u_15'})
test.equal(res, expected)
done()
dataprovider(test, [
[[1024, 9727, 7463], true]
[[1024, 9726, 7463], false]
], testCode)
testGetChangedItems: (test) ->
prcocessorMock = sinon.mock(BlipSearchResultProcessor)
prcocessorMock
.expects('_getWavesAndStuffIds')
.once()
.withArgs('ids')
.callsArgWith(1, null, 'waves', 'blipsIds', 'creatorsIds')
blipProcessorMock = sinon.mock(CouchBlipProcessor)
blipProcessorMock
.expects('getByIdsAsDict')
.once()
.withArgs('blipsIds')
.callsArgWith(1, null, 'blips')
userProcessorMock = sinon.mock(UserCouchProcessor)
userProcessorMock
.expects('getByIdsAsDict')
.once()
.withArgs('creatorsIds')
.callsArgWith(1, null, 'creators')
prcocessorMock
.expects('_getReadBlipCounts')
.once()
.withArgs('ids', 'userId')
.callsArgWith(2, null, 'readBlips')
prcocessorMock
.expects('_getTotalBlipCounts')
.once()
.withArgs('ids')
.callsArgWith(1, null, 'totalBlips')
prcocessorMock
.expects('_compileItems')
.once()
.withArgs('waves', 'blips', 'creators', 'readBlips', 'totalBlips')
.callsArgWith(5, null, 'foo')
BlipSearchResultProcessor._getChangedItems('ids', {id: 'userId'}, 'tags', (err, res) ->
test.equal(null, err)
test.equal('foo', res)
sinon.verifyAll()
sinon.restoreAll()
test.done()
)
testGetWavesAndStuffIds: (test) ->
wave = new WaveModel()
wave.rootBlipId = 'blipId'
waveMock = sinon.mock(wave)
.expects('getFirstParticipantWithRole')
.once()
.returns({id: 'creatorId'})
prcocessorMock = sinon.mock(CouchWaveProcessor)
prcocessorMock
.expects('getByIdsAsDict')
.once()
.withArgs('ids')
.callsArgWith(1, null, {foo: wave})
BlipSearchResultProcessor._getWavesAndStuffIds('ids', (err, waves, rootBlipsIds, creatoresIds) ->
test.equal(null, err)
test.deepEqual({foo: wave}, waves)
test.deepEqual(['blipId'], rootBlipsIds)
test.deepEqual(['creatorId'], creatoresIds)
sinon.verifyAll()
sinon.restoreAll()
test.done()
)
testConvertCountsToDict: (test) ->
counts = [
{key: ['<KEY>', '<KEY>'], value: 1},
{key: 'id<KEY>', value: 2},
{key: ['<KEY>'], value: 3}
]
res = BlipSearchResultProcessor._convertCountsToDict(counts)
test.deepEqual({
'id1': 1
'id2': 2
'id3': 3
}, res)
test.done()
testComplileChangedWavesInfo: (test) ->
wave = new WaveModel()
wave.rootBlipId = 'blipId'
waveMock = sinon.mock(wave)
waveMock
.expects('getFirstParticipantWithRole')
.once()
.returns({id: 'creatorId'})
blip = new BlipModel()
blipMock = sinon.mock(blip)
blipMock
.expects('getTitle')
.once()
.returns('foo')
blipMock
.expects('getSnippet')
.once()
.returns('bar')
waves = {waveId: wave}
blips = {blipId: blip}
creators = {creatorId: {name: 'name', avatar: 'avatar'}}
readBlipsStat = {waveId: 5}
totalBlipsStat = {waveId: 20}
BlipSearchResultProcessor._compileItems(waves, blips, creators, readBlipsStat, totalBlipsStat, (err, items) ->
test.deepEqual({waveId: {
title: 'foo'
snippet: 'bar'
avatar: 'avatar'
name: 'name'
totalBlipCount: 20
totalUnreadBlipCount: 15
}}, items)
sinon.verifyAll()
sinon.restoreAll()
test.done()
)
| true | testCase = require('nodeunit').testCase
sinon = require('sinon-plus')
dataprovider = require('dataprovider')
BlipSearchResultProcessor = require('../../../server/blip/search_result_processor').BlipSearchResultProcessor
CouchBlipProcessor = require('../../../server/blip/couch_processor').CouchBlipProcessor
BlipModel = require('../../../server/blip/models').BlipModel
CouchWaveProcessor = require('../../../server/wave/couch_processor').CouchWaveProcessor
WaveModel = require('../../../server/wave/models').WaveModel
UserCouchProcessor = require('../../../server/user/couch_processor').UserCouchProcessor
module.exports =
BlipSearchResultProcessorTest: testCase
setUp: (callback) ->
callback()
tearDown: (callback) ->
callback()
testGetItem: (test) ->
prcocessorMock = sinon.mock(BlipSearchResultProcessor)
prcocessorMock
.expects('_hasAllPtag')
.once()
.withArgs('tags')
.returns(true)
prcocessorMock
.expects('_isFollow')
.once()
.withArgs({wave_url: 'foo', groupdate: 'bar'}, 'user')
.returns(true)
testCode = (done, changed, expected) ->
res = BlipSearchResultProcessor._getItem({wave_url: 'foo', groupdate: 'bar'}, changed, 'user', 'tags')
test.deepEqual(res, expected)
sinon.verifyAll()
sinon.restoreAll()
done()
dataprovider(test, [
[true, {waveId: 'foo', changeDate: 'bar', follow: true}]
[false, {waveId: 'foo'}]
], testCode)
testIsFollow: (test) ->
testCode = (done, ptags, expected) ->
res = BlipSearchResultProcessor._isFollow({ptags}, {id: '0_u_15'})
test.equal(res, expected)
done()
dataprovider(test, [
[[1024, 9727, 7463], true]
[[1024, 9726, 7463], false]
], testCode)
testGetChangedItems: (test) ->
prcocessorMock = sinon.mock(BlipSearchResultProcessor)
prcocessorMock
.expects('_getWavesAndStuffIds')
.once()
.withArgs('ids')
.callsArgWith(1, null, 'waves', 'blipsIds', 'creatorsIds')
blipProcessorMock = sinon.mock(CouchBlipProcessor)
blipProcessorMock
.expects('getByIdsAsDict')
.once()
.withArgs('blipsIds')
.callsArgWith(1, null, 'blips')
userProcessorMock = sinon.mock(UserCouchProcessor)
userProcessorMock
.expects('getByIdsAsDict')
.once()
.withArgs('creatorsIds')
.callsArgWith(1, null, 'creators')
prcocessorMock
.expects('_getReadBlipCounts')
.once()
.withArgs('ids', 'userId')
.callsArgWith(2, null, 'readBlips')
prcocessorMock
.expects('_getTotalBlipCounts')
.once()
.withArgs('ids')
.callsArgWith(1, null, 'totalBlips')
prcocessorMock
.expects('_compileItems')
.once()
.withArgs('waves', 'blips', 'creators', 'readBlips', 'totalBlips')
.callsArgWith(5, null, 'foo')
BlipSearchResultProcessor._getChangedItems('ids', {id: 'userId'}, 'tags', (err, res) ->
test.equal(null, err)
test.equal('foo', res)
sinon.verifyAll()
sinon.restoreAll()
test.done()
)
testGetWavesAndStuffIds: (test) ->
wave = new WaveModel()
wave.rootBlipId = 'blipId'
waveMock = sinon.mock(wave)
.expects('getFirstParticipantWithRole')
.once()
.returns({id: 'creatorId'})
prcocessorMock = sinon.mock(CouchWaveProcessor)
prcocessorMock
.expects('getByIdsAsDict')
.once()
.withArgs('ids')
.callsArgWith(1, null, {foo: wave})
BlipSearchResultProcessor._getWavesAndStuffIds('ids', (err, waves, rootBlipsIds, creatoresIds) ->
test.equal(null, err)
test.deepEqual({foo: wave}, waves)
test.deepEqual(['blipId'], rootBlipsIds)
test.deepEqual(['creatorId'], creatoresIds)
sinon.verifyAll()
sinon.restoreAll()
test.done()
)
testConvertCountsToDict: (test) ->
counts = [
{key: ['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI'], value: 1},
{key: 'idPI:KEY:<KEY>END_PI', value: 2},
{key: ['PI:KEY:<KEY>END_PI'], value: 3}
]
res = BlipSearchResultProcessor._convertCountsToDict(counts)
test.deepEqual({
'id1': 1
'id2': 2
'id3': 3
}, res)
test.done()
testComplileChangedWavesInfo: (test) ->
wave = new WaveModel()
wave.rootBlipId = 'blipId'
waveMock = sinon.mock(wave)
waveMock
.expects('getFirstParticipantWithRole')
.once()
.returns({id: 'creatorId'})
blip = new BlipModel()
blipMock = sinon.mock(blip)
blipMock
.expects('getTitle')
.once()
.returns('foo')
blipMock
.expects('getSnippet')
.once()
.returns('bar')
waves = {waveId: wave}
blips = {blipId: blip}
creators = {creatorId: {name: 'name', avatar: 'avatar'}}
readBlipsStat = {waveId: 5}
totalBlipsStat = {waveId: 20}
BlipSearchResultProcessor._compileItems(waves, blips, creators, readBlipsStat, totalBlipsStat, (err, items) ->
test.deepEqual({waveId: {
title: 'foo'
snippet: 'bar'
avatar: 'avatar'
name: 'name'
totalBlipCount: 20
totalUnreadBlipCount: 15
}}, items)
sinon.verifyAll()
sinon.restoreAll()
test.done()
)
|
[
{
"context": " Returns results from 4chan board.\n#\n# Author:\n# Juan Pablo Ortiz <pablasso@gmail.com>\n\nmain_site = \"http://boards.",
"end": 221,
"score": 0.999886691570282,
"start": 205,
"tag": "NAME",
"value": "Juan Pablo Ortiz"
},
{
"context": "om 4chan board.\n#\n# Author:\... | src/4chan.coffee | pablasso/hubot-4chan | 0 | # Description:
# 4chan integration with Hubot.
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot 4chan me <board> [limit] - Returns results from 4chan board.
#
# Author:
# Juan Pablo Ortiz <pablasso@gmail.com>
main_site = "http://boards.4chan.org/"
lookup_site = "http://a.4cdn.org/"
images_site = "http://i.4cdn.org/"
module.exports = (robot)->
robot.respond /4chan me ([a-z0-9]+)( [0-9]+)?/i, (message)->
lookup_4chan message, (text)->
message.send text
lookup_4chan = (message, response_handler)->
top = parseInt message.match[2] || 15
board = message.match[1]
location = "#{lookup_site}#{board}/1.json"
message.http( location ).get() (error, response, body)->
return response_handler "Sorry, something went wrong" if error
return response_handler "4chan doesn't know what you're talking about" if response.statusCode == 404
return response_handler "4chan doesn't want anyone to go there any more." if response.statusCode == 403
threads = JSON.parse(body).threads
count = 0
for thread in threads
count++
continue if thread.posts.length == 0
post = thread.posts[0]
image = "#{images_site}#{board}/#{post.tim}#{post.ext}"
link = "#{main_site}#{board}/thread/#{post.no}/#{post.semantic_url}"
text = "#{image} - #{post.com} - #{link}"
response_handler text
break if count == top
| 190746 | # Description:
# 4chan integration with Hubot.
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot 4chan me <board> [limit] - Returns results from 4chan board.
#
# Author:
# <NAME> <<EMAIL>>
main_site = "http://boards.4chan.org/"
lookup_site = "http://a.4cdn.org/"
images_site = "http://i.4cdn.org/"
module.exports = (robot)->
robot.respond /4chan me ([a-z0-9]+)( [0-9]+)?/i, (message)->
lookup_4chan message, (text)->
message.send text
lookup_4chan = (message, response_handler)->
top = parseInt message.match[2] || 15
board = message.match[1]
location = "#{lookup_site}#{board}/1.json"
message.http( location ).get() (error, response, body)->
return response_handler "Sorry, something went wrong" if error
return response_handler "4chan doesn't know what you're talking about" if response.statusCode == 404
return response_handler "4chan doesn't want anyone to go there any more." if response.statusCode == 403
threads = JSON.parse(body).threads
count = 0
for thread in threads
count++
continue if thread.posts.length == 0
post = thread.posts[0]
image = "#{images_site}#{board}/#{post.tim}#{post.ext}"
link = "#{main_site}#{board}/thread/#{post.no}/#{post.semantic_url}"
text = "#{image} - #{post.com} - #{link}"
response_handler text
break if count == top
| true | # Description:
# 4chan integration with Hubot.
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot 4chan me <board> [limit] - Returns results from 4chan board.
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
main_site = "http://boards.4chan.org/"
lookup_site = "http://a.4cdn.org/"
images_site = "http://i.4cdn.org/"
module.exports = (robot)->
robot.respond /4chan me ([a-z0-9]+)( [0-9]+)?/i, (message)->
lookup_4chan message, (text)->
message.send text
lookup_4chan = (message, response_handler)->
top = parseInt message.match[2] || 15
board = message.match[1]
location = "#{lookup_site}#{board}/1.json"
message.http( location ).get() (error, response, body)->
return response_handler "Sorry, something went wrong" if error
return response_handler "4chan doesn't know what you're talking about" if response.statusCode == 404
return response_handler "4chan doesn't want anyone to go there any more." if response.statusCode == 403
threads = JSON.parse(body).threads
count = 0
for thread in threads
count++
continue if thread.posts.length == 0
post = thread.posts[0]
image = "#{images_site}#{board}/#{post.tim}#{post.ext}"
link = "#{main_site}#{board}/thread/#{post.no}/#{post.semantic_url}"
text = "#{image} - #{post.com} - #{link}"
response_handler text
break if count == top
|
[
{
"context": "ng hints...\"\n exitOnEscape: true\n # FIXME(smblott) Global link hints is currently insufficiently re",
"end": 2835,
"score": 0.9996422529220581,
"start": 2828,
"tag": "USERNAME",
"value": "smblott"
},
{
"context": ".sendMessage \"exit\", isSuccess: false\n\n ... | content_scripts/link_hints.coffee | FrankSalmick/vimium | 0 | #
# This implements link hinting. Typing "F" will enter link-hinting mode, where all clickable items on the
# page have a hint marker displayed containing a sequence of letters. Typing those letters will select a link.
#
# In our 'default' mode, the characters we use to show link hints are a user-configurable option. By default
# they're the home row. The CSS which is used on the link hints is also a configurable option.
#
# In 'filter' mode, our link hints are numbers, and the user can narrow down the range of possibilities by
# typing the text of the link itself.
#
# The "name" property below is a short-form name to appear in the link-hints mode's name. It's for debug only.
#
isMac = KeyboardUtils.platform == "Mac"
OPEN_IN_CURRENT_TAB =
name: "curr-tab"
indicator: "Open link in current tab"
OPEN_IN_NEW_BG_TAB =
name: "bg-tab"
indicator: "Open link in new tab"
clickModifiers: metaKey: isMac, ctrlKey: not isMac
OPEN_IN_NEW_FG_TAB =
name: "fg-tab"
indicator: "Open link in new tab and switch to it"
clickModifiers: shiftKey: true, metaKey: isMac, ctrlKey: not isMac
OPEN_WITH_QUEUE =
name: "queue"
indicator: "Open multiple links in new tabs"
clickModifiers: metaKey: isMac, ctrlKey: not isMac
COPY_LINK_URL =
name: "link"
indicator: "Copy link URL to Clipboard"
linkActivator: (link) ->
if link.href?
url = link.href
url = url[7..] if url[...7] == "mailto:"
HUD.copyToClipboard url
url = url[0..25] + "...." if 28 < url.length
HUD.showForDuration "Yanked #{url}", 2000
else
HUD.showForDuration "No link to yank.", 2000
OPEN_INCOGNITO =
name: "incognito"
indicator: "Open link in incognito window"
linkActivator: (link) -> chrome.runtime.sendMessage handler: 'openUrlInIncognito', url: link.href
DOWNLOAD_LINK_URL =
name: "download"
indicator: "Download link URL"
clickModifiers: altKey: true, ctrlKey: false, metaKey: false
availableModes = [OPEN_IN_CURRENT_TAB, OPEN_IN_NEW_BG_TAB, OPEN_IN_NEW_FG_TAB, OPEN_WITH_QUEUE, COPY_LINK_URL,
OPEN_INCOGNITO, DOWNLOAD_LINK_URL]
HintCoordinator =
onExit: []
localHints: null
cacheAllKeydownEvents: null
sendMessage: (messageType, request = {}) ->
Frame.postMessage "linkHintsMessage", extend request, {messageType}
prepareToActivateMode: (mode, onExit) ->
# We need to communicate with the background page (and other frames) to initiate link-hints mode. To
# prevent other Vimium commands from being triggered before link-hints mode is launched, we install a
# temporary mode to block (and cache) keyboard events.
@cacheAllKeydownEvents = cacheAllKeydownEvents = new CacheAllKeydownEvents
name: "link-hints/suppress-keyboard-events"
singleton: "link-hints-mode"
indicator: "Collecting hints..."
exitOnEscape: true
# FIXME(smblott) Global link hints is currently insufficiently reliable. If the mode above is left in
# place, then Vimium blocks. As a temporary measure, we install a timer to remove it.
Utils.setTimeout 1000, -> cacheAllKeydownEvents.exit() if cacheAllKeydownEvents?.modeIsActive
@onExit = [onExit]
@sendMessage "prepareToActivateMode",
modeIndex: availableModes.indexOf(mode), isVimiumHelpDialog: window.isVimiumHelpDialog
# Hint descriptors are global. They include all of the information necessary for each frame to determine
# whether and when a hint from *any* frame is selected. They include the following properties:
# frameId: the frame id of this hint's local frame
# localIndex: the index in @localHints for the full hint descriptor for this hint
# linkText: the link's text for filtered hints (this is null for alphabet hints)
getHintDescriptors: ({modeIndex, isVimiumHelpDialog}) ->
# Ensure that the document is ready and that the settings are loaded.
DomUtils.documentReady => Settings.onLoaded =>
requireHref = availableModes[modeIndex] in [COPY_LINK_URL, OPEN_INCOGNITO]
# If link hints is launched within the help dialog, then we only offer hints from that frame. This
# improves the usability of the help dialog on the options page (particularly for selecting command
# names).
@localHints =
if isVimiumHelpDialog and not window.isVimiumHelpDialog
[]
else
LocalHints.getLocalHints requireHref
@localHintDescriptors = @localHints.map ({linkText}, localIndex) -> {frameId, localIndex, linkText}
@sendMessage "postHintDescriptors", hintDescriptors: @localHintDescriptors
# We activate LinkHintsMode() in every frame and provide every frame with exactly the same hint descriptors.
# We also propagate the key state between frames. Therefore, the hint-selection process proceeds in lock
# step in every frame, and @linkHintsMode is in the same state in every frame.
activateMode: ({hintDescriptors, modeIndex, originatingFrameId}) ->
# We do not receive the frame's own hint descritors back from the background page. Instead, we merge them
# with the hint descriptors from other frames here.
[hintDescriptors[frameId], @localHintDescriptors] = [@localHintDescriptors, null]
hintDescriptors = [].concat (hintDescriptors[fId] for fId in (fId for own fId of hintDescriptors).sort())...
# Ensure that the document is ready and that the settings are loaded.
DomUtils.documentReady => Settings.onLoaded =>
@cacheAllKeydownEvents.exit() if @cacheAllKeydownEvents?.modeIsActive
@onExit = [] unless frameId == originatingFrameId
@linkHintsMode = new LinkHintsMode hintDescriptors, availableModes[modeIndex]
# Replay keydown events which we missed (but for filtered hints only).
@cacheAllKeydownEvents?.replayKeydownEvents() if Settings.get "filterLinkHints"
@cacheAllKeydownEvents = null
@linkHintsMode # Return this (for tests).
# The following messages are exchanged between frames while link-hints mode is active.
updateKeyState: (request) -> @linkHintsMode.updateKeyState request
rotateHints: -> @linkHintsMode.rotateHints()
setOpenLinkMode: ({modeIndex}) -> @linkHintsMode.setOpenLinkMode availableModes[modeIndex], false
activateActiveHintMarker: -> @linkHintsMode.activateLink @linkHintsMode.markerMatcher.activeHintMarker
getLocalHintMarker: (hint) -> if hint.frameId == frameId then @localHints[hint.localIndex] else null
exit: ({isSuccess}) ->
@linkHintsMode?.deactivateMode()
@onExit.pop() isSuccess while 0 < @onExit.length
@linkHintsMode = @localHints = null
LinkHints =
activateMode: (count = 1, {mode}) ->
mode ?= OPEN_IN_CURRENT_TAB
if 0 < count or mode is OPEN_WITH_QUEUE
HintCoordinator.prepareToActivateMode mode, (isSuccess) ->
if isSuccess
# Wait for the next tick to allow the previous mode to exit. It might yet generate a click event,
# which would cause our new mode to exit immediately.
Utils.nextTick -> LinkHints.activateMode count-1, {mode}
activateModeToOpenInNewTab: (count) -> @activateMode count, mode: OPEN_IN_NEW_BG_TAB
activateModeToOpenInNewForegroundTab: (count) -> @activateMode count, mode: OPEN_IN_NEW_FG_TAB
activateModeToCopyLinkUrl: (count) -> @activateMode count, mode: COPY_LINK_URL
activateModeWithQueue: -> @activateMode 1, mode: OPEN_WITH_QUEUE
activateModeToOpenIncognito: (count) -> @activateMode count, mode: OPEN_INCOGNITO
activateModeToDownloadLink: (count) -> @activateMode count, mode: DOWNLOAD_LINK_URL
class LinkHintsMode
hintMarkerContainingDiv: null
# One of the enums listed at the top of this file.
mode: undefined
# Function that does the appropriate action on the selected link.
linkActivator: undefined
# The link-hints "mode" (in the key-handler, indicator sense).
hintMode: null
# A count of the number of Tab presses since the last non-Tab keyboard event.
tabCount: 0
constructor: (hintDescriptors, @mode = OPEN_IN_CURRENT_TAB) ->
# We need documentElement to be ready in order to append links.
return unless document.documentElement
if hintDescriptors.length == 0
HUD.showForDuration "No links to select.", 2000
return
# This count is used to rank equal-scoring hints when sorting, thereby making JavaScript's sort stable.
@stableSortCount = 0
@hintMarkers = (@createMarkerFor desc for desc in hintDescriptors)
@markerMatcher = new (if Settings.get "filterLinkHints" then FilterHints else AlphabetHints)
@markerMatcher.fillInMarkers @hintMarkers, @.getNextZIndex.bind this
@hintMode = new Mode
name: "hint/#{@mode.name}"
indicator: false
singleton: "link-hints-mode"
suppressAllKeyboardEvents: true
suppressTrailingKeyEvents: true
exitOnEscape: true
exitOnClick: true
keydown: @onKeyDownInMode.bind this
@hintMode.onExit (event) =>
if event?.type == "click" or (event?.type == "keydown" and
(KeyboardUtils.isEscape(event) or KeyboardUtils.isBackspace event))
HintCoordinator.sendMessage "exit", isSuccess: false
# Note(philc): Append these markers as top level children instead of as child nodes to the link itself,
# because some clickable elements cannot contain children, e.g. submit buttons.
@hintMarkerContainingDiv = DomUtils.addElementList (marker for marker in @hintMarkers when marker.isLocalMarker),
id: "vimiumHintMarkerContainer", className: "vimiumReset"
@setIndicator()
setOpenLinkMode: (@mode, shouldPropagateToOtherFrames = true) ->
if shouldPropagateToOtherFrames
HintCoordinator.sendMessage "setOpenLinkMode", modeIndex: availableModes.indexOf @mode
else
@setIndicator()
setIndicator: ->
if windowIsFocused()
typedCharacters = @markerMatcher.linkTextKeystrokeQueue?.join("") ? ""
indicator = @mode.indicator + (if typedCharacters then ": \"#{typedCharacters}\"" else "") + "."
@hintMode.setIndicator indicator
getNextZIndex: do ->
# This is the starting z-index value; it produces z-index values which are greater than all of the other
# z-index values used by Vimium.
baseZIndex = 2140000000
-> baseZIndex += 1
#
# Creates a link marker for the given link.
#
createMarkerFor: (desc) ->
marker =
if desc.frameId == frameId
localHintDescriptor = HintCoordinator.getLocalHintMarker desc
el = DomUtils.createElement "div"
el.rect = localHintDescriptor.rect
el.style.left = el.rect.left + "px"
el.style.top = el.rect.top + "px"
# Each hint marker is assigned a different z-index.
el.style.zIndex = @getNextZIndex()
extend el,
className: "vimiumReset internalVimiumHintMarker vimiumHintMarker"
showLinkText: localHintDescriptor.showLinkText
localHintDescriptor: localHintDescriptor
else
{}
extend marker,
hintDescriptor: desc
isLocalMarker: desc.frameId == frameId
linkText: desc.linkText
stableSortCount: ++@stableSortCount
# Handles all keyboard events.
onKeyDownInMode: (event) ->
return if event.repeat
# NOTE(smblott) The modifier behaviour here applies only to alphabet hints.
if event.key in ["Control", "Shift"] and not Settings.get("filterLinkHints") and
@mode in [ OPEN_IN_CURRENT_TAB, OPEN_WITH_QUEUE, OPEN_IN_NEW_BG_TAB, OPEN_IN_NEW_FG_TAB ]
# Toggle whether to open the link in a new or current tab.
previousMode = @mode
key = event.key
switch key
when "Shift"
@setOpenLinkMode(if @mode is OPEN_IN_CURRENT_TAB then OPEN_IN_NEW_BG_TAB else OPEN_IN_CURRENT_TAB)
when "Control"
@setOpenLinkMode(if @mode is OPEN_IN_NEW_FG_TAB then OPEN_IN_NEW_BG_TAB else OPEN_IN_NEW_FG_TAB)
handlerId = @hintMode.push
keyup: (event) =>
if event.key == key
handlerStack.remove()
@setOpenLinkMode previousMode
true # Continue bubbling the event.
else if KeyboardUtils.isBackspace event
if @markerMatcher.popKeyChar()
@tabCount = 0
@updateVisibleMarkers()
else
# Exit via @hintMode.exit(), so that the LinkHints.activate() "onExit" callback sees the key event and
# knows not to restart hints mode.
@hintMode.exit event
else if event.key == "Enter"
# Activate the active hint, if there is one. Only FilterHints uses an active hint.
HintCoordinator.sendMessage "activateActiveHintMarker" if @markerMatcher.activeHintMarker
else if event.key == "Tab"
if event.shiftKey then @tabCount-- else @tabCount++
@updateVisibleMarkers()
else if event.key == " " and @markerMatcher.shouldRotateHints event
HintCoordinator.sendMessage "rotateHints"
else
unless event.repeat
keyChar =
if Settings.get "filterLinkHints"
KeyboardUtils.getKeyChar(event)
else
KeyboardUtils.getKeyChar(event).toLowerCase()
if keyChar
keyChar = " " if keyChar == "space"
if keyChar.length == 1
@tabCount = 0
@markerMatcher.pushKeyChar keyChar
@updateVisibleMarkers()
else
return handlerStack.suppressPropagation
handlerStack.suppressEvent
updateVisibleMarkers: ->
{hintKeystrokeQueue, linkTextKeystrokeQueue} = @markerMatcher
HintCoordinator.sendMessage "updateKeyState",
{hintKeystrokeQueue, linkTextKeystrokeQueue, tabCount: @tabCount}
updateKeyState: ({hintKeystrokeQueue, linkTextKeystrokeQueue, tabCount}) ->
extend @markerMatcher, {hintKeystrokeQueue, linkTextKeystrokeQueue}
{linksMatched, userMightOverType} = @markerMatcher.getMatchingHints @hintMarkers, tabCount, this.getNextZIndex.bind this
if linksMatched.length == 0
@deactivateMode()
else if linksMatched.length == 1
@activateLink linksMatched[0], userMightOverType
else
@hideMarker marker for marker in @hintMarkers
@showMarker matched, @markerMatcher.hintKeystrokeQueue.length for matched in linksMatched
@setIndicator()
# Rotate the hints' z-index values so that hidden hints become visible.
rotateHints: do ->
markerOverlapsStack = (marker, stack) ->
for otherMarker in stack
return true if Rect.intersects marker.markerRect, otherMarker.markerRect
false
->
# Get local, visible hint markers.
localHintMarkers = @hintMarkers.filter (marker) ->
marker.isLocalMarker and marker.style.display != "none"
# Fill in the markers' rects, if necessary.
marker.markerRect ?= marker.getClientRects()[0] for marker in localHintMarkers
# Calculate the overlapping groups of hints. We call each group a "stack". This is O(n^2).
stacks = []
for marker in localHintMarkers
stackForThisMarker = null
stacks =
for stack in stacks
markerOverlapsThisStack = markerOverlapsStack marker, stack
if markerOverlapsThisStack and not stackForThisMarker?
# We've found an existing stack for this marker.
stack.push marker
stackForThisMarker = stack
else if markerOverlapsThisStack and stackForThisMarker?
# This marker overlaps a second (or subsequent) stack; merge that stack into stackForThisMarker
# and discard it.
stackForThisMarker.push stack...
continue # Discard this stack.
else
stack # Keep this stack.
stacks.push [marker] unless stackForThisMarker?
# Rotate the z-indexes within each stack.
for stack in stacks
if 1 < stack.length
zIndexes = (marker.style.zIndex for marker in stack)
zIndexes.push zIndexes[0]
marker.style.zIndex = zIndexes[index + 1] for marker, index in stack
null # Prevent Coffeescript from building an unnecessary array.
# When only one hint remains, activate it in the appropriate way. The current frame may or may not contain
# the matched link, and may or may not have the focus. The resulting four cases are accounted for here by
# selectively pushing the appropriate HintCoordinator.onExit handlers.
activateLink: (linkMatched, userMightOverType = false) ->
@removeHintMarkers()
if linkMatched.isLocalMarker
localHintDescriptor = linkMatched.localHintDescriptor
clickEl = localHintDescriptor.element
HintCoordinator.onExit.push (isSuccess) =>
if isSuccess
if localHintDescriptor.reason == "Frame."
Utils.nextTick -> focusThisFrame highlight: true
else if localHintDescriptor.reason == "Scroll."
# Tell the scroller that this is the activated element.
handlerStack.bubbleEvent (if Utils.isFirefox() then "click" else "DOMActivate"), target: clickEl
else if localHintDescriptor.reason == "Open."
clickEl.open = !clickEl.open
else if DomUtils.isSelectable clickEl
window.focus()
DomUtils.simulateSelect clickEl
else
clickActivator = (modifiers) -> (link) -> DomUtils.simulateClick link, modifiers
linkActivator = @mode.linkActivator ? clickActivator @mode.clickModifiers
# Note(gdh1995): Here we should allow special elements to get focus,
# <select>: latest Chrome refuses `mousedown` event, and we can only
# focus it to let user press space to activate the popup menu
# <object> & <embed>: for Flash games which have their own key event handlers
# since we have been able to blur them by pressing `Escape`
if clickEl.nodeName.toLowerCase() in ["input", "select", "object", "embed"]
clickEl.focus()
linkActivator clickEl
# If flash elements are created, then this function can be used later to remove them.
removeFlashElements = ->
if linkMatched.isLocalMarker
{top: viewportTop, left: viewportLeft} = DomUtils.getViewportTopLeft()
flashElements = for rect in clickEl.getClientRects()
DomUtils.addFlashRect Rect.translate rect, viewportLeft, viewportTop
removeFlashElements = -> DomUtils.removeElement flashEl for flashEl in flashElements
# If we're using a keyboard blocker, then the frame with the focus sends the "exit" message, otherwise the
# frame containing the matched link does.
if userMightOverType
HintCoordinator.onExit.push removeFlashElements
if windowIsFocused()
callback = (isSuccess) -> HintCoordinator.sendMessage "exit", {isSuccess}
if Settings.get "waitForEnterForFilteredHints"
new WaitForEnter callback
else
new TypingProtector 200, callback
else if linkMatched.isLocalMarker
Utils.setTimeout 400, removeFlashElements
HintCoordinator.sendMessage "exit", isSuccess: true
#
# Shows the marker, highlighting matchingCharCount characters.
#
showMarker: (linkMarker, matchingCharCount) ->
return unless linkMarker.isLocalMarker
linkMarker.style.display = ""
for j in [0...linkMarker.childNodes.length]
if (j < matchingCharCount)
linkMarker.childNodes[j].classList.add("matchingCharacter")
else
linkMarker.childNodes[j].classList.remove("matchingCharacter")
hideMarker: (linkMarker) -> linkMarker.style.display = "none" if linkMarker.isLocalMarker
deactivateMode: ->
@removeHintMarkers()
@hintMode?.exit()
removeHintMarkers: ->
DomUtils.removeElement @hintMarkerContainingDiv if @hintMarkerContainingDiv
@hintMarkerContainingDiv = null
# Use characters for hints, and do not filter links by their text.
class AlphabetHints
constructor: ->
@linkHintCharacters = Settings.get("linkHintCharacters").toLowerCase()
@hintKeystrokeQueue = []
fillInMarkers: (hintMarkers) ->
hintStrings = @hintStrings(hintMarkers.length)
for marker, idx in hintMarkers
marker.hintString = hintStrings[idx]
marker.innerHTML = spanWrap(marker.hintString.toUpperCase()) if marker.isLocalMarker
#
# Returns a list of hint strings which will uniquely identify the given number of links. The hint strings
# may be of different lengths.
#
hintStrings: (linkCount) ->
hints = [""]
offset = 0
while hints.length - offset < linkCount or hints.length == 1
hint = hints[offset++]
hints.push ch + hint for ch in @linkHintCharacters
hints = hints[offset...offset+linkCount]
# Shuffle the hints so that they're scattered; hints starting with the same character and short hints are
# spread evenly throughout the array.
return hints.sort().map (str) -> str.reverse()
getMatchingHints: (hintMarkers) ->
matchString = @hintKeystrokeQueue.join ""
linksMatched: hintMarkers.filter (linkMarker) -> linkMarker.hintString.startsWith matchString
pushKeyChar: (keyChar) ->
@hintKeystrokeQueue.push keyChar
popKeyChar: -> @hintKeystrokeQueue.pop()
# For alphabet hints, <Space> always rotates the hints, regardless of modifiers.
shouldRotateHints: -> true
# Use characters for hints, and also filter links by their text.
class FilterHints
constructor: ->
@linkHintNumbers = Settings.get("linkHintNumbers").toUpperCase()
@hintKeystrokeQueue = []
@linkTextKeystrokeQueue = []
@activeHintMarker = null
# The regexp for splitting typed text and link texts. We split on sequences of non-word characters and
# link-hint numbers.
@splitRegexp = new RegExp "[\\W#{Utils.escapeRegexSpecialCharacters @linkHintNumbers}]+"
generateHintString: (linkHintNumber) ->
base = @linkHintNumbers.length
hint = []
while 0 < linkHintNumber
hint.push @linkHintNumbers[Math.floor linkHintNumber % base]
linkHintNumber = Math.floor linkHintNumber / base
hint.reverse().join ""
renderMarker: (marker) ->
linkText = marker.linkText
linkText = "#{linkText[..32]}..." if 35 < linkText.length
marker.innerHTML = spanWrap(marker.hintString +
(if marker.showLinkText then ": " + linkText else ""))
fillInMarkers: (hintMarkers, getNextZIndex) ->
@renderMarker marker for marker in hintMarkers when marker.isLocalMarker
# We use @getMatchingHints() here (although we know that all of the hints will match) to get an order on
# the hints and highlight the first one.
@getMatchingHints hintMarkers, 0, getNextZIndex
getMatchingHints: (hintMarkers, tabCount, getNextZIndex) ->
# At this point, linkTextKeystrokeQueue and hintKeystrokeQueue have been updated to reflect the latest
# input. Use them to filter the link hints accordingly.
matchString = @hintKeystrokeQueue.join ""
linksMatched = @filterLinkHints hintMarkers
linksMatched = linksMatched.filter (linkMarker) -> linkMarker.hintString.startsWith matchString
# Visually highlight of the active hint (that is, the one that will be activated if the user
# types <Enter>).
tabCount = ((linksMatched.length * Math.abs tabCount) + tabCount) % linksMatched.length
@activeHintMarker?.classList?.remove "vimiumActiveHintMarker"
@activeHintMarker = linksMatched[tabCount]
@activeHintMarker?.classList?.add "vimiumActiveHintMarker"
@activeHintMarker?.style?.zIndex = getNextZIndex()
linksMatched: linksMatched
userMightOverType: @hintKeystrokeQueue.length == 0 and 0 < @linkTextKeystrokeQueue.length
pushKeyChar: (keyChar) ->
if 0 <= @linkHintNumbers.indexOf keyChar
@hintKeystrokeQueue.push keyChar
else if keyChar.toLowerCase() != keyChar and @linkHintNumbers.toLowerCase() != @linkHintNumbers.toUpperCase()
# The the keyChar is upper case and the link hint "numbers" contain characters (e.g. [a-zA-Z]). We don't want
# some upper-case letters matching hints (above) and some matching text (below), so we ignore such keys.
return
# We only accept <Space> and characters which are not used for splitting (e.g. "a", "b", etc., but not "-").
else if keyChar == " " or not @splitRegexp.test keyChar
# Since we might renumber the hints, we should reset the current hintKeyStrokeQueue.
@hintKeystrokeQueue = []
@linkTextKeystrokeQueue.push keyChar.toLowerCase()
popKeyChar: ->
@hintKeystrokeQueue.pop() or @linkTextKeystrokeQueue.pop()
# Filter link hints by search string, renumbering the hints as necessary.
filterLinkHints: (hintMarkers) ->
scoreFunction = @scoreLinkHint @linkTextKeystrokeQueue.join ""
matchingHintMarkers =
hintMarkers
.filter (linkMarker) =>
linkMarker.score = scoreFunction linkMarker
0 == @linkTextKeystrokeQueue.length or 0 < linkMarker.score
.sort (a, b) ->
if b.score == a.score then b.stableSortCount - a.stableSortCount else b.score - a.score
if matchingHintMarkers.length == 0 and @hintKeystrokeQueue.length == 0 and 0 < @linkTextKeystrokeQueue.length
# We don't accept typed text which doesn't match any hints.
@linkTextKeystrokeQueue.pop()
@filterLinkHints hintMarkers
else
linkHintNumber = 1
for linkMarker in matchingHintMarkers
linkMarker.hintString = @generateHintString linkHintNumber++
@renderMarker linkMarker
linkMarker
# Assign a score to a filter match (higher is better). We assign a higher score for matches at the start of
# a word, and a considerably higher score still for matches which are whole words.
scoreLinkHint: (linkSearchString) ->
searchWords = linkSearchString.trim().toLowerCase().split @splitRegexp
(linkMarker) =>
return 0 unless 0 < searchWords.length
# We only keep non-empty link words. Empty link words cannot be matched, and leading empty link words
# disrupt the scoring of matches at the start of the text.
linkWords = linkMarker.linkWords ?= linkMarker.linkText.toLowerCase().split(@splitRegexp).filter (term) -> term
searchWordScores =
for searchWord in searchWords
linkWordScores =
for linkWord, idx in linkWords
position = linkWord.indexOf searchWord
if position < 0
0 # No match.
else if position == 0 and searchWord.length == linkWord.length
if idx == 0 then 8 else 4 # Whole-word match.
else if position == 0
if idx == 0 then 6 else 2 # Match at the start of a word.
else
1 # 0 < position; other match.
Math.max linkWordScores...
if 0 in searchWordScores
0
else
addFunc = (a,b) -> a + b
score = searchWordScores.reduce addFunc, 0
# Prefer matches in shorter texts. To keep things balanced for links without any text, we just weight
# them as if their length was 100 (so, quite long).
score / Math.log 1 + (linkMarker.linkText.length || 100)
# For filtered hints, we require a modifier (because <Space> on its own is a token separator).
shouldRotateHints: (event) ->
event.ctrlKey or event.altKey or event.metaKey or event.shiftKey
#
# Make each hint character a span, so that we can highlight the typed characters as you type them.
#
spanWrap = (hintString) ->
innerHTML = []
for char in hintString
innerHTML.push("<span class='vimiumReset'>" + char + "</span>")
innerHTML.join("")
LocalHints =
#
# Determine whether the element is visible and clickable. If it is, find the rect bounding the element in
# the viewport. There may be more than one part of element which is clickable (for example, if it's an
# image), therefore we always return a array of element/rect pairs (which may also be a singleton or empty).
#
getVisibleClickable: (element) ->
# Get the tag name. However, `element.tagName` can be an element (not a string, see #2035), so we guard
# against that.
tagName = element.tagName.toLowerCase?() ? ""
isClickable = false
onlyHasTabIndex = false
possibleFalsePositive = false
visibleElements = []
reason = null
# Insert area elements that provide click functionality to an img.
if tagName == "img"
mapName = element.getAttribute "usemap"
if mapName
imgClientRects = element.getClientRects()
mapName = mapName.replace(/^#/, "").replace("\"", "\\\"")
map = document.querySelector "map[name=\"#{mapName}\"]"
if map and imgClientRects.length > 0
areas = map.getElementsByTagName "area"
areasAndRects = DomUtils.getClientRectsForAreas imgClientRects[0], areas
visibleElements.push areasAndRects...
# Check aria properties to see if the element should be ignored.
if (element.getAttribute("aria-hidden")?.toLowerCase() in ["", "true"] or
element.getAttribute("aria-disabled")?.toLowerCase() in ["", "true"])
return [] # This element should never have a link hint.
# Check for AngularJS listeners on the element.
@checkForAngularJs ?= do ->
angularElements = document.getElementsByClassName "ng-scope"
if angularElements.length == 0
-> false
else
ngAttributes = []
for prefix in [ '', 'data-', 'x-' ]
for separator in [ '-', ':', '_' ]
ngAttributes.push "#{prefix}ng#{separator}click"
(element) ->
for attribute in ngAttributes
return true if element.hasAttribute attribute
false
isClickable ||= @checkForAngularJs element
# Check for attributes that make an element clickable regardless of its tagName.
if element.hasAttribute("onclick") or
(role = element.getAttribute "role") and role.toLowerCase() in [
"button" , "tab" , "link", "checkbox", "menuitem", "menuitemcheckbox", "menuitemradio"
] or
(contentEditable = element.getAttribute "contentEditable") and
contentEditable.toLowerCase() in ["", "contenteditable", "true"]
isClickable = true
# Check for jsaction event listeners on the element.
if not isClickable and element.hasAttribute "jsaction"
jsactionRules = element.getAttribute("jsaction").split(";")
for jsactionRule in jsactionRules
ruleSplit = jsactionRule.trim().split ":"
if 1 <= ruleSplit.length <= 2
[eventType, namespace, actionName ] =
if ruleSplit.length == 1
["click", ruleSplit[0].trim().split(".")..., "_"]
else
[ruleSplit[0], ruleSplit[1].trim().split(".")..., "_"]
isClickable ||= eventType == "click" and namespace != "none" and actionName != "_"
# Check for tagNames which are natively clickable.
switch tagName
when "a"
isClickable = true
when "textarea"
isClickable ||= not element.disabled and not element.readOnly
when "input"
isClickable ||= not (element.getAttribute("type")?.toLowerCase() == "hidden" or
element.disabled or
(element.readOnly and DomUtils.isSelectable element))
when "button", "select"
isClickable ||= not element.disabled
when "object", "embed"
isClickable = true
when "label"
isClickable ||= element.control? and not element.control.disabled and
(@getVisibleClickable element.control).length == 0
when "body"
isClickable ||=
if element == document.body and not windowIsFocused() and
window.innerWidth > 3 and window.innerHeight > 3 and
document.body?.tagName.toLowerCase() != "frameset"
reason = "Frame."
isClickable ||=
if element == document.body and windowIsFocused() and Scroller.isScrollableElement element
reason = "Scroll."
when "img"
isClickable ||= element.style.cursor in ["zoom-in", "zoom-out"]
when "div", "ol", "ul"
isClickable ||=
if element.clientHeight < element.scrollHeight and Scroller.isScrollableElement element
reason = "Scroll."
when "details"
isClickable = true
reason = "Open."
# NOTE(smblott) Disabled pending resolution of #2997.
# # Detect elements with "click" listeners installed with `addEventListener()`.
# isClickable ||= element.hasAttribute "_vimium-has-onclick-listener"
# An element with a class name containing the text "button" might be clickable. However, real clickables
# are often wrapped in elements with such class names. So, when we find clickables based only on their
# class name, we mark them as unreliable.
if not isClickable and 0 <= element.getAttribute("class")?.toLowerCase().indexOf "button"
possibleFalsePositive = isClickable = true
# Elements with tabindex are sometimes useful, but usually not. We can treat them as second class
# citizens when it improves UX, so take special note of them.
tabIndexValue = element.getAttribute("tabindex")
tabIndex = if tabIndexValue then parseInt tabIndexValue else -1
unless isClickable or tabIndex < 0 or isNaN(tabIndex)
isClickable = onlyHasTabIndex = true
if isClickable
clientRect = DomUtils.getVisibleClientRect element, true
if clientRect != null
visibleElements.push {element: element, rect: clientRect, secondClassCitizen: onlyHasTabIndex,
possibleFalsePositive, reason}
visibleElements
#
# Returns element at a given (x,y) with an optional root element.
# If the returned element is a shadow root, call the function use that recursively
# until we hit an actual element.
#
getElementFromPoint: (x, y, root = document, stack = []) ->
element = if root.elementsFromPoint then root.elementsFromPoint(x, y)[0] else root.elementFromPoint(x, y)
if stack.indexOf(element) != -1
return element
stack.push(element)
if element and element.shadowRoot
return LocalHints.getElementFromPoint(x, y, element.shadowRoot, stack)
return element
#
# Returns all clickable elements that are not hidden and are in the current viewport, along with rectangles
# at which (parts of) the elements are displayed.
# In the process, we try to find rects where elements do not overlap so that link hints are unambiguous.
# Because of this, the rects returned will frequently *NOT* be equivalent to the rects for the whole
# element.
#
getLocalHints: (requireHref) ->
# We need documentElement to be ready in order to find links.
return [] unless document.documentElement
# Find all elements, recursing into shadow DOM if present.
getAllElements = (root, elements = []) ->
for element in root.querySelectorAll "*"
elements.push element
if element.shadowRoot
getAllElements(element.shadowRoot, elements)
elements
elements = getAllElements document.documentElement
visibleElements = []
# The order of elements here is important; they should appear in the order they are in the DOM, so that
# we can work out which element is on top when multiple elements overlap. Detecting elements in this loop
# is the sensible, efficient way to ensure this happens.
# NOTE(mrmr1993): Our previous method (combined XPath and DOM traversal for jsaction) couldn't provide
# this, so it's necessary to check whether elements are clickable in order, as we do below.
for element in elements
unless requireHref and not element.href
visibleElement = @getVisibleClickable element
visibleElements.push visibleElement...
# Traverse the DOM from descendants to ancestors, so later elements show above earlier elements.
visibleElements = visibleElements.reverse()
# Filter out suspected false positives. A false positive is taken to be an element marked as a possible
# false positive for which a close descendant is already clickable. False positives tend to be close
# together in the DOM, so - to keep the cost down - we only search nearby elements. NOTE(smblott): The
# visible elements have already been reversed, so we're visiting descendants before their ancestors.
descendantsToCheck = [1..3] # This determines how many descendants we're willing to consider.
visibleElements =
for element, position in visibleElements
continue if element.possibleFalsePositive and do ->
index = Math.max 0, position - 6 # This determines how far back we're willing to look.
while index < position
candidateDescendant = visibleElements[index].element
for _ in descendantsToCheck
candidateDescendant = candidateDescendant?.parentElement
return true if candidateDescendant == element.element
index += 1
false # This is not a false positive.
element
# This loop will check if any corner or center of element is clickable
# document.elementFromPoint will find an element at a x,y location.
# Node.contain checks to see if an element contains another. note: someNode.contains(someNode) === true
# If we do not find our element as a descendant of any element we find, assume it's completely covered.
localHints = nonOverlappingElements = []
while visibleElement = visibleElements.pop()
if visibleElement.secondClassCitizen
continue
rect = visibleElement.rect
element = visibleElement.element
# Check middle of element first, as this is perhaps most likely to return true.
elementFromMiddlePoint = LocalHints.getElementFromPoint(rect.left + (rect.width * 0.5), rect.top + (rect.height * 0.5))
if elementFromMiddlePoint && (element.contains(elementFromMiddlePoint) or elementFromMiddlePoint.contains(element))
nonOverlappingElements.push visibleElement
continue
# If not in middle, try corners.
# Adjusting the rect by 0.1 towards the upper left, which empirically fixes some cases where another
# element would've been found instead. NOTE(philc): This isn't well explained. Originated in #2251.
verticalCoordinates = [rect.top + 0.1, rect.bottom - 0.1]
horizontalCoordinates = [rect.left + 0.1, rect.right - 0.1]
foundElement = false
for verticalCoordinate in verticalCoordinates
for horizontalCoordinate in horizontalCoordinates
elementFromPoint = LocalHints.getElementFromPoint(verticalCoordinate, horizontalCoordinate)
if elementFromPoint && (element.contains(elementFromPoint) or elementFromPoint.contains(element))
foundElement = true
break
if foundElement
nonOverlappingElements.push visibleElement
break;
# Position the rects within the window.
{top, left} = DomUtils.getViewportTopLeft()
for hint in nonOverlappingElements
hint.rect.top += top
hint.rect.left += left
if Settings.get "filterLinkHints"
extend hint, @generateLinkText hint for hint in localHints
localHints
generateLinkText: (hint) ->
element = hint.element
linkText = ""
showLinkText = false
# toLowerCase is necessary as html documents return "IMG" and xhtml documents return "img"
nodeName = element.nodeName.toLowerCase()
if nodeName == "input"
if element.labels? and element.labels.length > 0
linkText = element.labels[0].textContent.trim()
# Remove trailing ":" commonly found in labels.
if linkText[linkText.length-1] == ":"
linkText = linkText[...linkText.length-1]
showLinkText = true
else if element.getAttribute("type")?.toLowerCase() == "file"
linkText = "Choose File"
else if element.type != "password"
linkText = element.value
if not linkText and 'placeholder' of element
linkText = element.placeholder
# Check if there is an image embedded in the <a> tag.
else if nodeName == "a" and not element.textContent.trim() and
element.firstElementChild and
element.firstElementChild.nodeName.toLowerCase() == "img"
linkText = element.firstElementChild.alt || element.firstElementChild.title
showLinkText = true if linkText
else if hint.reason?
linkText = hint.reason
showLinkText = true
else if 0 < element.textContent.length
linkText = element.textContent[...256]
else if element.hasAttribute "title"
linkText = element.getAttribute "title"
else
linkText = element.innerHTML[...256]
{linkText: linkText.trim(), showLinkText}
# Suppress all keyboard events until the user stops typing for sufficiently long.
class TypingProtector extends Mode
constructor: (delay, callback) ->
@timer = Utils.setTimeout delay, => @exit()
resetExitTimer = (event) =>
clearTimeout @timer
@timer = Utils.setTimeout delay, => @exit()
super
name: "hint/typing-protector"
suppressAllKeyboardEvents: true
keydown: resetExitTimer
keypress: resetExitTimer
@onExit ->
callback true # true -> isSuccess.
class WaitForEnter extends Mode
constructor: (callback) ->
super
name: "hint/wait-for-enter"
suppressAllKeyboardEvents: true
indicator: "Hit <Enter> to proceed..."
@push
keydown: (event) =>
if event.key == "Enter"
@exit()
callback true # true -> isSuccess.
else if KeyboardUtils.isEscape event
@exit()
callback false # false -> isSuccess.
root = exports ? (window.root ?= {})
root.LinkHints = LinkHints
root.HintCoordinator = HintCoordinator
# For tests:
extend root, {LinkHintsMode, LocalHints, AlphabetHints, WaitForEnter}
extend window, root unless exports?
| 214053 | #
# This implements link hinting. Typing "F" will enter link-hinting mode, where all clickable items on the
# page have a hint marker displayed containing a sequence of letters. Typing those letters will select a link.
#
# In our 'default' mode, the characters we use to show link hints are a user-configurable option. By default
# they're the home row. The CSS which is used on the link hints is also a configurable option.
#
# In 'filter' mode, our link hints are numbers, and the user can narrow down the range of possibilities by
# typing the text of the link itself.
#
# The "name" property below is a short-form name to appear in the link-hints mode's name. It's for debug only.
#
isMac = KeyboardUtils.platform == "Mac"
OPEN_IN_CURRENT_TAB =
name: "curr-tab"
indicator: "Open link in current tab"
OPEN_IN_NEW_BG_TAB =
name: "bg-tab"
indicator: "Open link in new tab"
clickModifiers: metaKey: isMac, ctrlKey: not isMac
OPEN_IN_NEW_FG_TAB =
name: "fg-tab"
indicator: "Open link in new tab and switch to it"
clickModifiers: shiftKey: true, metaKey: isMac, ctrlKey: not isMac
OPEN_WITH_QUEUE =
name: "queue"
indicator: "Open multiple links in new tabs"
clickModifiers: metaKey: isMac, ctrlKey: not isMac
COPY_LINK_URL =
name: "link"
indicator: "Copy link URL to Clipboard"
linkActivator: (link) ->
if link.href?
url = link.href
url = url[7..] if url[...7] == "mailto:"
HUD.copyToClipboard url
url = url[0..25] + "...." if 28 < url.length
HUD.showForDuration "Yanked #{url}", 2000
else
HUD.showForDuration "No link to yank.", 2000
OPEN_INCOGNITO =
name: "incognito"
indicator: "Open link in incognito window"
linkActivator: (link) -> chrome.runtime.sendMessage handler: 'openUrlInIncognito', url: link.href
DOWNLOAD_LINK_URL =
name: "download"
indicator: "Download link URL"
clickModifiers: altKey: true, ctrlKey: false, metaKey: false
availableModes = [OPEN_IN_CURRENT_TAB, OPEN_IN_NEW_BG_TAB, OPEN_IN_NEW_FG_TAB, OPEN_WITH_QUEUE, COPY_LINK_URL,
OPEN_INCOGNITO, DOWNLOAD_LINK_URL]
HintCoordinator =
onExit: []
localHints: null
cacheAllKeydownEvents: null
sendMessage: (messageType, request = {}) ->
Frame.postMessage "linkHintsMessage", extend request, {messageType}
prepareToActivateMode: (mode, onExit) ->
# We need to communicate with the background page (and other frames) to initiate link-hints mode. To
# prevent other Vimium commands from being triggered before link-hints mode is launched, we install a
# temporary mode to block (and cache) keyboard events.
@cacheAllKeydownEvents = cacheAllKeydownEvents = new CacheAllKeydownEvents
name: "link-hints/suppress-keyboard-events"
singleton: "link-hints-mode"
indicator: "Collecting hints..."
exitOnEscape: true
# FIXME(smblott) Global link hints is currently insufficiently reliable. If the mode above is left in
# place, then Vimium blocks. As a temporary measure, we install a timer to remove it.
Utils.setTimeout 1000, -> cacheAllKeydownEvents.exit() if cacheAllKeydownEvents?.modeIsActive
@onExit = [onExit]
@sendMessage "prepareToActivateMode",
modeIndex: availableModes.indexOf(mode), isVimiumHelpDialog: window.isVimiumHelpDialog
# Hint descriptors are global. They include all of the information necessary for each frame to determine
# whether and when a hint from *any* frame is selected. They include the following properties:
# frameId: the frame id of this hint's local frame
# localIndex: the index in @localHints for the full hint descriptor for this hint
# linkText: the link's text for filtered hints (this is null for alphabet hints)
getHintDescriptors: ({modeIndex, isVimiumHelpDialog}) ->
# Ensure that the document is ready and that the settings are loaded.
DomUtils.documentReady => Settings.onLoaded =>
requireHref = availableModes[modeIndex] in [COPY_LINK_URL, OPEN_INCOGNITO]
# If link hints is launched within the help dialog, then we only offer hints from that frame. This
# improves the usability of the help dialog on the options page (particularly for selecting command
# names).
@localHints =
if isVimiumHelpDialog and not window.isVimiumHelpDialog
[]
else
LocalHints.getLocalHints requireHref
@localHintDescriptors = @localHints.map ({linkText}, localIndex) -> {frameId, localIndex, linkText}
@sendMessage "postHintDescriptors", hintDescriptors: @localHintDescriptors
# We activate LinkHintsMode() in every frame and provide every frame with exactly the same hint descriptors.
# We also propagate the key state between frames. Therefore, the hint-selection process proceeds in lock
# step in every frame, and @linkHintsMode is in the same state in every frame.
activateMode: ({hintDescriptors, modeIndex, originatingFrameId}) ->
# We do not receive the frame's own hint descritors back from the background page. Instead, we merge them
# with the hint descriptors from other frames here.
[hintDescriptors[frameId], @localHintDescriptors] = [@localHintDescriptors, null]
hintDescriptors = [].concat (hintDescriptors[fId] for fId in (fId for own fId of hintDescriptors).sort())...
# Ensure that the document is ready and that the settings are loaded.
DomUtils.documentReady => Settings.onLoaded =>
@cacheAllKeydownEvents.exit() if @cacheAllKeydownEvents?.modeIsActive
@onExit = [] unless frameId == originatingFrameId
@linkHintsMode = new LinkHintsMode hintDescriptors, availableModes[modeIndex]
# Replay keydown events which we missed (but for filtered hints only).
@cacheAllKeydownEvents?.replayKeydownEvents() if Settings.get "filterLinkHints"
@cacheAllKeydownEvents = null
@linkHintsMode # Return this (for tests).
# The following messages are exchanged between frames while link-hints mode is active.
updateKeyState: (request) -> @linkHintsMode.updateKeyState request
rotateHints: -> @linkHintsMode.rotateHints()
setOpenLinkMode: ({modeIndex}) -> @linkHintsMode.setOpenLinkMode availableModes[modeIndex], false
activateActiveHintMarker: -> @linkHintsMode.activateLink @linkHintsMode.markerMatcher.activeHintMarker
getLocalHintMarker: (hint) -> if hint.frameId == frameId then @localHints[hint.localIndex] else null
exit: ({isSuccess}) ->
@linkHintsMode?.deactivateMode()
@onExit.pop() isSuccess while 0 < @onExit.length
@linkHintsMode = @localHints = null
LinkHints =
activateMode: (count = 1, {mode}) ->
mode ?= OPEN_IN_CURRENT_TAB
if 0 < count or mode is OPEN_WITH_QUEUE
HintCoordinator.prepareToActivateMode mode, (isSuccess) ->
if isSuccess
# Wait for the next tick to allow the previous mode to exit. It might yet generate a click event,
# which would cause our new mode to exit immediately.
Utils.nextTick -> LinkHints.activateMode count-1, {mode}
activateModeToOpenInNewTab: (count) -> @activateMode count, mode: OPEN_IN_NEW_BG_TAB
activateModeToOpenInNewForegroundTab: (count) -> @activateMode count, mode: OPEN_IN_NEW_FG_TAB
activateModeToCopyLinkUrl: (count) -> @activateMode count, mode: COPY_LINK_URL
activateModeWithQueue: -> @activateMode 1, mode: OPEN_WITH_QUEUE
activateModeToOpenIncognito: (count) -> @activateMode count, mode: OPEN_INCOGNITO
activateModeToDownloadLink: (count) -> @activateMode count, mode: DOWNLOAD_LINK_URL
class LinkHintsMode
hintMarkerContainingDiv: null
# One of the enums listed at the top of this file.
mode: undefined
# Function that does the appropriate action on the selected link.
linkActivator: undefined
# The link-hints "mode" (in the key-handler, indicator sense).
hintMode: null
# A count of the number of Tab presses since the last non-Tab keyboard event.
tabCount: 0
constructor: (hintDescriptors, @mode = OPEN_IN_CURRENT_TAB) ->
# We need documentElement to be ready in order to append links.
return unless document.documentElement
if hintDescriptors.length == 0
HUD.showForDuration "No links to select.", 2000
return
# This count is used to rank equal-scoring hints when sorting, thereby making JavaScript's sort stable.
@stableSortCount = 0
@hintMarkers = (@createMarkerFor desc for desc in hintDescriptors)
@markerMatcher = new (if Settings.get "filterLinkHints" then FilterHints else AlphabetHints)
@markerMatcher.fillInMarkers @hintMarkers, @.getNextZIndex.bind this
@hintMode = new Mode
name: "hint/#{@mode.name}"
indicator: false
singleton: "link-hints-mode"
suppressAllKeyboardEvents: true
suppressTrailingKeyEvents: true
exitOnEscape: true
exitOnClick: true
keydown: @onKeyDownInMode.bind this
@hintMode.onExit (event) =>
if event?.type == "click" or (event?.type == "keydown" and
(KeyboardUtils.isEscape(event) or KeyboardUtils.isBackspace event))
HintCoordinator.sendMessage "exit", isSuccess: false
# Note(<NAME>): Append these markers as top level children instead of as child nodes to the link itself,
# because some clickable elements cannot contain children, e.g. submit buttons.
@hintMarkerContainingDiv = DomUtils.addElementList (marker for marker in @hintMarkers when marker.isLocalMarker),
id: "vimiumHintMarkerContainer", className: "vimiumReset"
@setIndicator()
setOpenLinkMode: (@mode, shouldPropagateToOtherFrames = true) ->
if shouldPropagateToOtherFrames
HintCoordinator.sendMessage "setOpenLinkMode", modeIndex: availableModes.indexOf @mode
else
@setIndicator()
setIndicator: ->
if windowIsFocused()
typedCharacters = @markerMatcher.linkTextKeystrokeQueue?.join("") ? ""
indicator = @mode.indicator + (if typedCharacters then ": \"#{typedCharacters}\"" else "") + "."
@hintMode.setIndicator indicator
getNextZIndex: do ->
# This is the starting z-index value; it produces z-index values which are greater than all of the other
# z-index values used by Vimium.
baseZIndex = 2140000000
-> baseZIndex += 1
#
# Creates a link marker for the given link.
#
createMarkerFor: (desc) ->
marker =
if desc.frameId == frameId
localHintDescriptor = HintCoordinator.getLocalHintMarker desc
el = DomUtils.createElement "div"
el.rect = localHintDescriptor.rect
el.style.left = el.rect.left + "px"
el.style.top = el.rect.top + "px"
# Each hint marker is assigned a different z-index.
el.style.zIndex = @getNextZIndex()
extend el,
className: "vimiumReset internalVimiumHintMarker vimiumHintMarker"
showLinkText: localHintDescriptor.showLinkText
localHintDescriptor: localHintDescriptor
else
{}
extend marker,
hintDescriptor: desc
isLocalMarker: desc.frameId == frameId
linkText: desc.linkText
stableSortCount: ++@stableSortCount
# Handles all keyboard events.
onKeyDownInMode: (event) ->
return if event.repeat
# NOTE(smblott) The modifier behaviour here applies only to alphabet hints.
if event.key in ["Control", "Shift"] and not Settings.get("filterLinkHints") and
@mode in [ OPEN_IN_CURRENT_TAB, OPEN_WITH_QUEUE, OPEN_IN_NEW_BG_TAB, OPEN_IN_NEW_FG_TAB ]
# Toggle whether to open the link in a new or current tab.
previousMode = @mode
key = event.key
switch key
when "Shift"
@setOpenLinkMode(if @mode is OPEN_IN_CURRENT_TAB then OPEN_IN_NEW_BG_TAB else OPEN_IN_CURRENT_TAB)
when "Control"
@setOpenLinkMode(if @mode is OPEN_IN_NEW_FG_TAB then OPEN_IN_NEW_BG_TAB else OPEN_IN_NEW_FG_TAB)
handlerId = @hintMode.push
keyup: (event) =>
if event.key == key
handlerStack.remove()
@setOpenLinkMode previousMode
true # Continue bubbling the event.
else if KeyboardUtils.isBackspace event
if @markerMatcher.popKeyChar()
@tabCount = 0
@updateVisibleMarkers()
else
# Exit via @hintMode.exit(), so that the LinkHints.activate() "onExit" callback sees the key event and
# knows not to restart hints mode.
@hintMode.exit event
else if event.key == "Enter"
# Activate the active hint, if there is one. Only FilterHints uses an active hint.
HintCoordinator.sendMessage "activateActiveHintMarker" if @markerMatcher.activeHintMarker
else if event.key == "Tab"
if event.shiftKey then @tabCount-- else @tabCount++
@updateVisibleMarkers()
else if event.key == " " and @markerMatcher.shouldRotateHints event
HintCoordinator.sendMessage "rotateHints"
else
unless event.repeat
keyChar =
if Settings.get "filterLinkHints"
KeyboardUtils.getKeyChar(event)
else
KeyboardUtils.getKeyChar(event).toLowerCase()
if keyChar
keyChar = " " if keyChar == "space"
if keyChar.length == 1
@tabCount = 0
@markerMatcher.pushKeyChar keyChar
@updateVisibleMarkers()
else
return handlerStack.suppressPropagation
handlerStack.suppressEvent
updateVisibleMarkers: ->
{hintKeystrokeQueue, linkTextKeystrokeQueue} = @markerMatcher
HintCoordinator.sendMessage "updateKeyState",
{hintKeystrokeQueue, linkTextKeystrokeQueue, tabCount: @tabCount}
updateKeyState: ({hintKeystrokeQueue, linkTextKeystrokeQueue, tabCount}) ->
extend @markerMatcher, {hintKeystrokeQueue, linkTextKeystrokeQueue}
{linksMatched, userMightOverType} = @markerMatcher.getMatchingHints @hintMarkers, tabCount, this.getNextZIndex.bind this
if linksMatched.length == 0
@deactivateMode()
else if linksMatched.length == 1
@activateLink linksMatched[0], userMightOverType
else
@hideMarker marker for marker in @hintMarkers
@showMarker matched, @markerMatcher.hintKeystrokeQueue.length for matched in linksMatched
@setIndicator()
# Rotate the hints' z-index values so that hidden hints become visible.
rotateHints: do ->
markerOverlapsStack = (marker, stack) ->
for otherMarker in stack
return true if Rect.intersects marker.markerRect, otherMarker.markerRect
false
->
# Get local, visible hint markers.
localHintMarkers = @hintMarkers.filter (marker) ->
marker.isLocalMarker and marker.style.display != "none"
# Fill in the markers' rects, if necessary.
marker.markerRect ?= marker.getClientRects()[0] for marker in localHintMarkers
# Calculate the overlapping groups of hints. We call each group a "stack". This is O(n^2).
stacks = []
for marker in localHintMarkers
stackForThisMarker = null
stacks =
for stack in stacks
markerOverlapsThisStack = markerOverlapsStack marker, stack
if markerOverlapsThisStack and not stackForThisMarker?
# We've found an existing stack for this marker.
stack.push marker
stackForThisMarker = stack
else if markerOverlapsThisStack and stackForThisMarker?
# This marker overlaps a second (or subsequent) stack; merge that stack into stackForThisMarker
# and discard it.
stackForThisMarker.push stack...
continue # Discard this stack.
else
stack # Keep this stack.
stacks.push [marker] unless stackForThisMarker?
# Rotate the z-indexes within each stack.
for stack in stacks
if 1 < stack.length
zIndexes = (marker.style.zIndex for marker in stack)
zIndexes.push zIndexes[0]
marker.style.zIndex = zIndexes[index + 1] for marker, index in stack
null # Prevent Coffeescript from building an unnecessary array.
# When only one hint remains, activate it in the appropriate way. The current frame may or may not contain
# the matched link, and may or may not have the focus. The resulting four cases are accounted for here by
# selectively pushing the appropriate HintCoordinator.onExit handlers.
activateLink: (linkMatched, userMightOverType = false) ->
@removeHintMarkers()
if linkMatched.isLocalMarker
localHintDescriptor = linkMatched.localHintDescriptor
clickEl = localHintDescriptor.element
HintCoordinator.onExit.push (isSuccess) =>
if isSuccess
if localHintDescriptor.reason == "Frame."
Utils.nextTick -> focusThisFrame highlight: true
else if localHintDescriptor.reason == "Scroll."
# Tell the scroller that this is the activated element.
handlerStack.bubbleEvent (if Utils.isFirefox() then "click" else "DOMActivate"), target: clickEl
else if localHintDescriptor.reason == "Open."
clickEl.open = !clickEl.open
else if DomUtils.isSelectable clickEl
window.focus()
DomUtils.simulateSelect clickEl
else
clickActivator = (modifiers) -> (link) -> DomUtils.simulateClick link, modifiers
linkActivator = @mode.linkActivator ? clickActivator @mode.clickModifiers
# Note(gdh1995): Here we should allow special elements to get focus,
# <select>: latest Chrome refuses `mousedown` event, and we can only
# focus it to let user press space to activate the popup menu
# <object> & <embed>: for Flash games which have their own key event handlers
# since we have been able to blur them by pressing `Escape`
if clickEl.nodeName.toLowerCase() in ["input", "select", "object", "embed"]
clickEl.focus()
linkActivator clickEl
# If flash elements are created, then this function can be used later to remove them.
removeFlashElements = ->
if linkMatched.isLocalMarker
{top: viewportTop, left: viewportLeft} = DomUtils.getViewportTopLeft()
flashElements = for rect in clickEl.getClientRects()
DomUtils.addFlashRect Rect.translate rect, viewportLeft, viewportTop
removeFlashElements = -> DomUtils.removeElement flashEl for flashEl in flashElements
# If we're using a keyboard blocker, then the frame with the focus sends the "exit" message, otherwise the
# frame containing the matched link does.
if userMightOverType
HintCoordinator.onExit.push removeFlashElements
if windowIsFocused()
callback = (isSuccess) -> HintCoordinator.sendMessage "exit", {isSuccess}
if Settings.get "waitForEnterForFilteredHints"
new WaitForEnter callback
else
new TypingProtector 200, callback
else if linkMatched.isLocalMarker
Utils.setTimeout 400, removeFlashElements
HintCoordinator.sendMessage "exit", isSuccess: true
#
# Shows the marker, highlighting matchingCharCount characters.
#
showMarker: (linkMarker, matchingCharCount) ->
return unless linkMarker.isLocalMarker
linkMarker.style.display = ""
for j in [0...linkMarker.childNodes.length]
if (j < matchingCharCount)
linkMarker.childNodes[j].classList.add("matchingCharacter")
else
linkMarker.childNodes[j].classList.remove("matchingCharacter")
hideMarker: (linkMarker) -> linkMarker.style.display = "none" if linkMarker.isLocalMarker
deactivateMode: ->
@removeHintMarkers()
@hintMode?.exit()
removeHintMarkers: ->
DomUtils.removeElement @hintMarkerContainingDiv if @hintMarkerContainingDiv
@hintMarkerContainingDiv = null
# Use characters for hints, and do not filter links by their text.
class AlphabetHints
constructor: ->
@linkHintCharacters = Settings.get("linkHintCharacters").toLowerCase()
@hintKeystrokeQueue = []
fillInMarkers: (hintMarkers) ->
hintStrings = @hintStrings(hintMarkers.length)
for marker, idx in hintMarkers
marker.hintString = hintStrings[idx]
marker.innerHTML = spanWrap(marker.hintString.toUpperCase()) if marker.isLocalMarker
#
# Returns a list of hint strings which will uniquely identify the given number of links. The hint strings
# may be of different lengths.
#
hintStrings: (linkCount) ->
hints = [""]
offset = 0
while hints.length - offset < linkCount or hints.length == 1
hint = hints[offset++]
hints.push ch + hint for ch in @linkHintCharacters
hints = hints[offset...offset+linkCount]
# Shuffle the hints so that they're scattered; hints starting with the same character and short hints are
# spread evenly throughout the array.
return hints.sort().map (str) -> str.reverse()
getMatchingHints: (hintMarkers) ->
matchString = @hintKeystrokeQueue.join ""
linksMatched: hintMarkers.filter (linkMarker) -> linkMarker.hintString.startsWith matchString
pushKeyChar: (keyChar) ->
@hintKeystrokeQueue.push keyChar
popKeyChar: -> @hintKeystrokeQueue.pop()
# For alphabet hints, <Space> always rotates the hints, regardless of modifiers.
shouldRotateHints: -> true
# Use characters for hints, and also filter links by their text.
class FilterHints
constructor: ->
@linkHintNumbers = Settings.get("linkHintNumbers").toUpperCase()
@hintKeystrokeQueue = []
@linkTextKeystrokeQueue = []
@activeHintMarker = null
# The regexp for splitting typed text and link texts. We split on sequences of non-word characters and
# link-hint numbers.
@splitRegexp = new RegExp "[\\W#{Utils.escapeRegexSpecialCharacters @linkHintNumbers}]+"
generateHintString: (linkHintNumber) ->
base = @linkHintNumbers.length
hint = []
while 0 < linkHintNumber
hint.push @linkHintNumbers[Math.floor linkHintNumber % base]
linkHintNumber = Math.floor linkHintNumber / base
hint.reverse().join ""
renderMarker: (marker) ->
linkText = marker.linkText
linkText = "#{linkText[..32]}..." if 35 < linkText.length
marker.innerHTML = spanWrap(marker.hintString +
(if marker.showLinkText then ": " + linkText else ""))
fillInMarkers: (hintMarkers, getNextZIndex) ->
@renderMarker marker for marker in hintMarkers when marker.isLocalMarker
# We use @getMatchingHints() here (although we know that all of the hints will match) to get an order on
# the hints and highlight the first one.
@getMatchingHints hintMarkers, 0, getNextZIndex
getMatchingHints: (hintMarkers, tabCount, getNextZIndex) ->
# At this point, linkTextKeystrokeQueue and hintKeystrokeQueue have been updated to reflect the latest
# input. Use them to filter the link hints accordingly.
matchString = @hintKeystrokeQueue.join ""
linksMatched = @filterLinkHints hintMarkers
linksMatched = linksMatched.filter (linkMarker) -> linkMarker.hintString.startsWith matchString
# Visually highlight of the active hint (that is, the one that will be activated if the user
# types <Enter>).
tabCount = ((linksMatched.length * Math.abs tabCount) + tabCount) % linksMatched.length
@activeHintMarker?.classList?.remove "vimiumActiveHintMarker"
@activeHintMarker = linksMatched[tabCount]
@activeHintMarker?.classList?.add "vimiumActiveHintMarker"
@activeHintMarker?.style?.zIndex = getNextZIndex()
linksMatched: linksMatched
userMightOverType: @hintKeystrokeQueue.length == 0 and 0 < @linkTextKeystrokeQueue.length
pushKeyChar: (keyChar) ->
if 0 <= @linkHintNumbers.indexOf keyChar
@hintKeystrokeQueue.push keyChar
else if keyChar.toLowerCase() != keyChar and @linkHintNumbers.toLowerCase() != @linkHintNumbers.toUpperCase()
# The the keyChar is upper case and the link hint "numbers" contain characters (e.g. [a-zA-Z]). We don't want
# some upper-case letters matching hints (above) and some matching text (below), so we ignore such keys.
return
# We only accept <Space> and characters which are not used for splitting (e.g. "a", "b", etc., but not "-").
else if keyChar == " " or not @splitRegexp.test keyChar
# Since we might renumber the hints, we should reset the current hintKeyStrokeQueue.
@hintKeystrokeQueue = []
@linkTextKeystrokeQueue.push keyChar.toLowerCase()
popKeyChar: ->
@hintKeystrokeQueue.pop() or @linkTextKeystrokeQueue.pop()
# Filter link hints by search string, renumbering the hints as necessary.
filterLinkHints: (hintMarkers) ->
scoreFunction = @scoreLinkHint @linkTextKeystrokeQueue.join ""
matchingHintMarkers =
hintMarkers
.filter (linkMarker) =>
linkMarker.score = scoreFunction linkMarker
0 == @linkTextKeystrokeQueue.length or 0 < linkMarker.score
.sort (a, b) ->
if b.score == a.score then b.stableSortCount - a.stableSortCount else b.score - a.score
if matchingHintMarkers.length == 0 and @hintKeystrokeQueue.length == 0 and 0 < @linkTextKeystrokeQueue.length
# We don't accept typed text which doesn't match any hints.
@linkTextKeystrokeQueue.pop()
@filterLinkHints hintMarkers
else
linkHintNumber = 1
for linkMarker in matchingHintMarkers
linkMarker.hintString = @generateHintString linkHintNumber++
@renderMarker linkMarker
linkMarker
# Assign a score to a filter match (higher is better). We assign a higher score for matches at the start of
# a word, and a considerably higher score still for matches which are whole words.
scoreLinkHint: (linkSearchString) ->
searchWords = linkSearchString.trim().toLowerCase().split @splitRegexp
(linkMarker) =>
return 0 unless 0 < searchWords.length
# We only keep non-empty link words. Empty link words cannot be matched, and leading empty link words
# disrupt the scoring of matches at the start of the text.
linkWords = linkMarker.linkWords ?= linkMarker.linkText.toLowerCase().split(@splitRegexp).filter (term) -> term
searchWordScores =
for searchWord in searchWords
linkWordScores =
for linkWord, idx in linkWords
position = linkWord.indexOf searchWord
if position < 0
0 # No match.
else if position == 0 and searchWord.length == linkWord.length
if idx == 0 then 8 else 4 # Whole-word match.
else if position == 0
if idx == 0 then 6 else 2 # Match at the start of a word.
else
1 # 0 < position; other match.
Math.max linkWordScores...
if 0 in searchWordScores
0
else
addFunc = (a,b) -> a + b
score = searchWordScores.reduce addFunc, 0
# Prefer matches in shorter texts. To keep things balanced for links without any text, we just weight
# them as if their length was 100 (so, quite long).
score / Math.log 1 + (linkMarker.linkText.length || 100)
# For filtered hints, we require a modifier (because <Space> on its own is a token separator).
shouldRotateHints: (event) ->
event.ctrlKey or event.altKey or event.metaKey or event.shiftKey
#
# Make each hint character a span, so that we can highlight the typed characters as you type them.
#
spanWrap = (hintString) ->
innerHTML = []
for char in hintString
innerHTML.push("<span class='vimiumReset'>" + char + "</span>")
innerHTML.join("")
LocalHints =
#
# Determine whether the element is visible and clickable. If it is, find the rect bounding the element in
# the viewport. There may be more than one part of element which is clickable (for example, if it's an
# image), therefore we always return a array of element/rect pairs (which may also be a singleton or empty).
#
getVisibleClickable: (element) ->
# Get the tag name. However, `element.tagName` can be an element (not a string, see #2035), so we guard
# against that.
tagName = element.tagName.toLowerCase?() ? ""
isClickable = false
onlyHasTabIndex = false
possibleFalsePositive = false
visibleElements = []
reason = null
# Insert area elements that provide click functionality to an img.
if tagName == "img"
mapName = element.getAttribute "usemap"
if mapName
imgClientRects = element.getClientRects()
mapName = mapName.replace(/^#/, "").replace("\"", "\\\"")
map = document.querySelector "map[name=\"#{mapName}\"]"
if map and imgClientRects.length > 0
areas = map.getElementsByTagName "area"
areasAndRects = DomUtils.getClientRectsForAreas imgClientRects[0], areas
visibleElements.push areasAndRects...
# Check aria properties to see if the element should be ignored.
if (element.getAttribute("aria-hidden")?.toLowerCase() in ["", "true"] or
element.getAttribute("aria-disabled")?.toLowerCase() in ["", "true"])
return [] # This element should never have a link hint.
# Check for AngularJS listeners on the element.
@checkForAngularJs ?= do ->
angularElements = document.getElementsByClassName "ng-scope"
if angularElements.length == 0
-> false
else
ngAttributes = []
for prefix in [ '', 'data-', 'x-' ]
for separator in [ '-', ':', '_' ]
ngAttributes.push "#{prefix}ng#{separator}click"
(element) ->
for attribute in ngAttributes
return true if element.hasAttribute attribute
false
isClickable ||= @checkForAngularJs element
# Check for attributes that make an element clickable regardless of its tagName.
if element.hasAttribute("onclick") or
(role = element.getAttribute "role") and role.toLowerCase() in [
"button" , "tab" , "link", "checkbox", "menuitem", "menuitemcheckbox", "menuitemradio"
] or
(contentEditable = element.getAttribute "contentEditable") and
contentEditable.toLowerCase() in ["", "contenteditable", "true"]
isClickable = true
# Check for jsaction event listeners on the element.
if not isClickable and element.hasAttribute "jsaction"
jsactionRules = element.getAttribute("jsaction").split(";")
for jsactionRule in jsactionRules
ruleSplit = jsactionRule.trim().split ":"
if 1 <= ruleSplit.length <= 2
[eventType, namespace, actionName ] =
if ruleSplit.length == 1
["click", ruleSplit[0].trim().split(".")..., "_"]
else
[ruleSplit[0], ruleSplit[1].trim().split(".")..., "_"]
isClickable ||= eventType == "click" and namespace != "none" and actionName != "_"
# Check for tagNames which are natively clickable.
switch tagName
when "a"
isClickable = true
when "textarea"
isClickable ||= not element.disabled and not element.readOnly
when "input"
isClickable ||= not (element.getAttribute("type")?.toLowerCase() == "hidden" or
element.disabled or
(element.readOnly and DomUtils.isSelectable element))
when "button", "select"
isClickable ||= not element.disabled
when "object", "embed"
isClickable = true
when "label"
isClickable ||= element.control? and not element.control.disabled and
(@getVisibleClickable element.control).length == 0
when "body"
isClickable ||=
if element == document.body and not windowIsFocused() and
window.innerWidth > 3 and window.innerHeight > 3 and
document.body?.tagName.toLowerCase() != "frameset"
reason = "Frame."
isClickable ||=
if element == document.body and windowIsFocused() and Scroller.isScrollableElement element
reason = "Scroll."
when "img"
isClickable ||= element.style.cursor in ["zoom-in", "zoom-out"]
when "div", "ol", "ul"
isClickable ||=
if element.clientHeight < element.scrollHeight and Scroller.isScrollableElement element
reason = "Scroll."
when "details"
isClickable = true
reason = "Open."
# NOTE(smblott) Disabled pending resolution of #2997.
# # Detect elements with "click" listeners installed with `addEventListener()`.
# isClickable ||= element.hasAttribute "_vimium-has-onclick-listener"
# An element with a class name containing the text "button" might be clickable. However, real clickables
# are often wrapped in elements with such class names. So, when we find clickables based only on their
# class name, we mark them as unreliable.
if not isClickable and 0 <= element.getAttribute("class")?.toLowerCase().indexOf "button"
possibleFalsePositive = isClickable = true
# Elements with tabindex are sometimes useful, but usually not. We can treat them as second class
# citizens when it improves UX, so take special note of them.
tabIndexValue = element.getAttribute("tabindex")
tabIndex = if tabIndexValue then parseInt tabIndexValue else -1
unless isClickable or tabIndex < 0 or isNaN(tabIndex)
isClickable = onlyHasTabIndex = true
if isClickable
clientRect = DomUtils.getVisibleClientRect element, true
if clientRect != null
visibleElements.push {element: element, rect: clientRect, secondClassCitizen: onlyHasTabIndex,
possibleFalsePositive, reason}
visibleElements
#
# Returns element at a given (x,y) with an optional root element.
# If the returned element is a shadow root, call the function use that recursively
# until we hit an actual element.
#
getElementFromPoint: (x, y, root = document, stack = []) ->
element = if root.elementsFromPoint then root.elementsFromPoint(x, y)[0] else root.elementFromPoint(x, y)
if stack.indexOf(element) != -1
return element
stack.push(element)
if element and element.shadowRoot
return LocalHints.getElementFromPoint(x, y, element.shadowRoot, stack)
return element
#
# Returns all clickable elements that are not hidden and are in the current viewport, along with rectangles
# at which (parts of) the elements are displayed.
# In the process, we try to find rects where elements do not overlap so that link hints are unambiguous.
# Because of this, the rects returned will frequently *NOT* be equivalent to the rects for the whole
# element.
#
getLocalHints: (requireHref) ->
# We need documentElement to be ready in order to find links.
return [] unless document.documentElement
# Find all elements, recursing into shadow DOM if present.
getAllElements = (root, elements = []) ->
for element in root.querySelectorAll "*"
elements.push element
if element.shadowRoot
getAllElements(element.shadowRoot, elements)
elements
elements = getAllElements document.documentElement
visibleElements = []
# The order of elements here is important; they should appear in the order they are in the DOM, so that
# we can work out which element is on top when multiple elements overlap. Detecting elements in this loop
# is the sensible, efficient way to ensure this happens.
# NOTE(mrmr1993): Our previous method (combined XPath and DOM traversal for jsaction) couldn't provide
# this, so it's necessary to check whether elements are clickable in order, as we do below.
for element in elements
unless requireHref and not element.href
visibleElement = @getVisibleClickable element
visibleElements.push visibleElement...
# Traverse the DOM from descendants to ancestors, so later elements show above earlier elements.
visibleElements = visibleElements.reverse()
# Filter out suspected false positives. A false positive is taken to be an element marked as a possible
# false positive for which a close descendant is already clickable. False positives tend to be close
# together in the DOM, so - to keep the cost down - we only search nearby elements. NOTE(smblott): The
# visible elements have already been reversed, so we're visiting descendants before their ancestors.
descendantsToCheck = [1..3] # This determines how many descendants we're willing to consider.
visibleElements =
for element, position in visibleElements
continue if element.possibleFalsePositive and do ->
index = Math.max 0, position - 6 # This determines how far back we're willing to look.
while index < position
candidateDescendant = visibleElements[index].element
for _ in descendantsToCheck
candidateDescendant = candidateDescendant?.parentElement
return true if candidateDescendant == element.element
index += 1
false # This is not a false positive.
element
# This loop will check if any corner or center of element is clickable
# document.elementFromPoint will find an element at a x,y location.
# Node.contain checks to see if an element contains another. note: someNode.contains(someNode) === true
# If we do not find our element as a descendant of any element we find, assume it's completely covered.
localHints = nonOverlappingElements = []
while visibleElement = visibleElements.pop()
if visibleElement.secondClassCitizen
continue
rect = visibleElement.rect
element = visibleElement.element
# Check middle of element first, as this is perhaps most likely to return true.
elementFromMiddlePoint = LocalHints.getElementFromPoint(rect.left + (rect.width * 0.5), rect.top + (rect.height * 0.5))
if elementFromMiddlePoint && (element.contains(elementFromMiddlePoint) or elementFromMiddlePoint.contains(element))
nonOverlappingElements.push visibleElement
continue
# If not in middle, try corners.
# Adjusting the rect by 0.1 towards the upper left, which empirically fixes some cases where another
# element would've been found instead. NOTE(philc): This isn't well explained. Originated in #2251.
verticalCoordinates = [rect.top + 0.1, rect.bottom - 0.1]
horizontalCoordinates = [rect.left + 0.1, rect.right - 0.1]
foundElement = false
for verticalCoordinate in verticalCoordinates
for horizontalCoordinate in horizontalCoordinates
elementFromPoint = LocalHints.getElementFromPoint(verticalCoordinate, horizontalCoordinate)
if elementFromPoint && (element.contains(elementFromPoint) or elementFromPoint.contains(element))
foundElement = true
break
if foundElement
nonOverlappingElements.push visibleElement
break;
# Position the rects within the window.
{top, left} = DomUtils.getViewportTopLeft()
for hint in nonOverlappingElements
hint.rect.top += top
hint.rect.left += left
if Settings.get "filterLinkHints"
extend hint, @generateLinkText hint for hint in localHints
localHints
generateLinkText: (hint) ->
element = hint.element
linkText = ""
showLinkText = false
# toLowerCase is necessary as html documents return "IMG" and xhtml documents return "img"
nodeName = element.nodeName.toLowerCase()
if nodeName == "input"
if element.labels? and element.labels.length > 0
linkText = element.labels[0].textContent.trim()
# Remove trailing ":" commonly found in labels.
if linkText[linkText.length-1] == ":"
linkText = linkText[...linkText.length-1]
showLinkText = true
else if element.getAttribute("type")?.toLowerCase() == "file"
linkText = "Choose File"
else if element.type != "password"
linkText = element.value
if not linkText and 'placeholder' of element
linkText = element.placeholder
# Check if there is an image embedded in the <a> tag.
else if nodeName == "a" and not element.textContent.trim() and
element.firstElementChild and
element.firstElementChild.nodeName.toLowerCase() == "img"
linkText = element.firstElementChild.alt || element.firstElementChild.title
showLinkText = true if linkText
else if hint.reason?
linkText = hint.reason
showLinkText = true
else if 0 < element.textContent.length
linkText = element.textContent[...256]
else if element.hasAttribute "title"
linkText = element.getAttribute "title"
else
linkText = element.innerHTML[...256]
{linkText: linkText.trim(), showLinkText}
# Suppress all keyboard events until the user stops typing for sufficiently long.
class TypingProtector extends Mode
constructor: (delay, callback) ->
@timer = Utils.setTimeout delay, => @exit()
resetExitTimer = (event) =>
clearTimeout @timer
@timer = Utils.setTimeout delay, => @exit()
super
name: "hint/typing-protector"
suppressAllKeyboardEvents: true
keydown: resetExitTimer
keypress: resetExitTimer
@onExit ->
callback true # true -> isSuccess.
class WaitForEnter extends Mode
constructor: (callback) ->
super
name: "hint/wait-for-enter"
suppressAllKeyboardEvents: true
indicator: "Hit <Enter> to proceed..."
@push
keydown: (event) =>
if event.key == "Enter"
@exit()
callback true # true -> isSuccess.
else if KeyboardUtils.isEscape event
@exit()
callback false # false -> isSuccess.
root = exports ? (window.root ?= {})
root.LinkHints = LinkHints
root.HintCoordinator = HintCoordinator
# For tests:
extend root, {LinkHintsMode, LocalHints, AlphabetHints, WaitForEnter}
extend window, root unless exports?
| true | #
# This implements link hinting. Typing "F" will enter link-hinting mode, where all clickable items on the
# page have a hint marker displayed containing a sequence of letters. Typing those letters will select a link.
#
# In our 'default' mode, the characters we use to show link hints are a user-configurable option. By default
# they're the home row. The CSS which is used on the link hints is also a configurable option.
#
# In 'filter' mode, our link hints are numbers, and the user can narrow down the range of possibilities by
# typing the text of the link itself.
#
# The "name" property below is a short-form name to appear in the link-hints mode's name. It's for debug only.
#
isMac = KeyboardUtils.platform == "Mac"
OPEN_IN_CURRENT_TAB =
name: "curr-tab"
indicator: "Open link in current tab"
OPEN_IN_NEW_BG_TAB =
name: "bg-tab"
indicator: "Open link in new tab"
clickModifiers: metaKey: isMac, ctrlKey: not isMac
OPEN_IN_NEW_FG_TAB =
name: "fg-tab"
indicator: "Open link in new tab and switch to it"
clickModifiers: shiftKey: true, metaKey: isMac, ctrlKey: not isMac
OPEN_WITH_QUEUE =
name: "queue"
indicator: "Open multiple links in new tabs"
clickModifiers: metaKey: isMac, ctrlKey: not isMac
COPY_LINK_URL =
name: "link"
indicator: "Copy link URL to Clipboard"
linkActivator: (link) ->
if link.href?
url = link.href
url = url[7..] if url[...7] == "mailto:"
HUD.copyToClipboard url
url = url[0..25] + "...." if 28 < url.length
HUD.showForDuration "Yanked #{url}", 2000
else
HUD.showForDuration "No link to yank.", 2000
OPEN_INCOGNITO =
name: "incognito"
indicator: "Open link in incognito window"
linkActivator: (link) -> chrome.runtime.sendMessage handler: 'openUrlInIncognito', url: link.href
DOWNLOAD_LINK_URL =
name: "download"
indicator: "Download link URL"
clickModifiers: altKey: true, ctrlKey: false, metaKey: false
availableModes = [OPEN_IN_CURRENT_TAB, OPEN_IN_NEW_BG_TAB, OPEN_IN_NEW_FG_TAB, OPEN_WITH_QUEUE, COPY_LINK_URL,
OPEN_INCOGNITO, DOWNLOAD_LINK_URL]
HintCoordinator =
onExit: []
localHints: null
cacheAllKeydownEvents: null
sendMessage: (messageType, request = {}) ->
Frame.postMessage "linkHintsMessage", extend request, {messageType}
prepareToActivateMode: (mode, onExit) ->
# We need to communicate with the background page (and other frames) to initiate link-hints mode. To
# prevent other Vimium commands from being triggered before link-hints mode is launched, we install a
# temporary mode to block (and cache) keyboard events.
@cacheAllKeydownEvents = cacheAllKeydownEvents = new CacheAllKeydownEvents
name: "link-hints/suppress-keyboard-events"
singleton: "link-hints-mode"
indicator: "Collecting hints..."
exitOnEscape: true
# FIXME(smblott) Global link hints is currently insufficiently reliable. If the mode above is left in
# place, then Vimium blocks. As a temporary measure, we install a timer to remove it.
Utils.setTimeout 1000, -> cacheAllKeydownEvents.exit() if cacheAllKeydownEvents?.modeIsActive
@onExit = [onExit]
@sendMessage "prepareToActivateMode",
modeIndex: availableModes.indexOf(mode), isVimiumHelpDialog: window.isVimiumHelpDialog
# Hint descriptors are global. They include all of the information necessary for each frame to determine
# whether and when a hint from *any* frame is selected. They include the following properties:
# frameId: the frame id of this hint's local frame
# localIndex: the index in @localHints for the full hint descriptor for this hint
# linkText: the link's text for filtered hints (this is null for alphabet hints)
getHintDescriptors: ({modeIndex, isVimiumHelpDialog}) ->
# Ensure that the document is ready and that the settings are loaded.
DomUtils.documentReady => Settings.onLoaded =>
requireHref = availableModes[modeIndex] in [COPY_LINK_URL, OPEN_INCOGNITO]
# If link hints is launched within the help dialog, then we only offer hints from that frame. This
# improves the usability of the help dialog on the options page (particularly for selecting command
# names).
@localHints =
if isVimiumHelpDialog and not window.isVimiumHelpDialog
[]
else
LocalHints.getLocalHints requireHref
@localHintDescriptors = @localHints.map ({linkText}, localIndex) -> {frameId, localIndex, linkText}
@sendMessage "postHintDescriptors", hintDescriptors: @localHintDescriptors
# We activate LinkHintsMode() in every frame and provide every frame with exactly the same hint descriptors.
# We also propagate the key state between frames. Therefore, the hint-selection process proceeds in lock
# step in every frame, and @linkHintsMode is in the same state in every frame.
activateMode: ({hintDescriptors, modeIndex, originatingFrameId}) ->
# We do not receive the frame's own hint descritors back from the background page. Instead, we merge them
# with the hint descriptors from other frames here.
[hintDescriptors[frameId], @localHintDescriptors] = [@localHintDescriptors, null]
hintDescriptors = [].concat (hintDescriptors[fId] for fId in (fId for own fId of hintDescriptors).sort())...
# Ensure that the document is ready and that the settings are loaded.
DomUtils.documentReady => Settings.onLoaded =>
@cacheAllKeydownEvents.exit() if @cacheAllKeydownEvents?.modeIsActive
@onExit = [] unless frameId == originatingFrameId
@linkHintsMode = new LinkHintsMode hintDescriptors, availableModes[modeIndex]
# Replay keydown events which we missed (but for filtered hints only).
@cacheAllKeydownEvents?.replayKeydownEvents() if Settings.get "filterLinkHints"
@cacheAllKeydownEvents = null
@linkHintsMode # Return this (for tests).
# The following messages are exchanged between frames while link-hints mode is active.
updateKeyState: (request) -> @linkHintsMode.updateKeyState request
rotateHints: -> @linkHintsMode.rotateHints()
setOpenLinkMode: ({modeIndex}) -> @linkHintsMode.setOpenLinkMode availableModes[modeIndex], false
activateActiveHintMarker: -> @linkHintsMode.activateLink @linkHintsMode.markerMatcher.activeHintMarker
getLocalHintMarker: (hint) -> if hint.frameId == frameId then @localHints[hint.localIndex] else null
exit: ({isSuccess}) ->
@linkHintsMode?.deactivateMode()
@onExit.pop() isSuccess while 0 < @onExit.length
@linkHintsMode = @localHints = null
LinkHints =
activateMode: (count = 1, {mode}) ->
mode ?= OPEN_IN_CURRENT_TAB
if 0 < count or mode is OPEN_WITH_QUEUE
HintCoordinator.prepareToActivateMode mode, (isSuccess) ->
if isSuccess
# Wait for the next tick to allow the previous mode to exit. It might yet generate a click event,
# which would cause our new mode to exit immediately.
Utils.nextTick -> LinkHints.activateMode count-1, {mode}
activateModeToOpenInNewTab: (count) -> @activateMode count, mode: OPEN_IN_NEW_BG_TAB
activateModeToOpenInNewForegroundTab: (count) -> @activateMode count, mode: OPEN_IN_NEW_FG_TAB
activateModeToCopyLinkUrl: (count) -> @activateMode count, mode: COPY_LINK_URL
activateModeWithQueue: -> @activateMode 1, mode: OPEN_WITH_QUEUE
activateModeToOpenIncognito: (count) -> @activateMode count, mode: OPEN_INCOGNITO
activateModeToDownloadLink: (count) -> @activateMode count, mode: DOWNLOAD_LINK_URL
class LinkHintsMode
hintMarkerContainingDiv: null
# One of the enums listed at the top of this file.
mode: undefined
# Function that does the appropriate action on the selected link.
linkActivator: undefined
# The link-hints "mode" (in the key-handler, indicator sense).
hintMode: null
# A count of the number of Tab presses since the last non-Tab keyboard event.
tabCount: 0
constructor: (hintDescriptors, @mode = OPEN_IN_CURRENT_TAB) ->
# We need documentElement to be ready in order to append links.
return unless document.documentElement
if hintDescriptors.length == 0
HUD.showForDuration "No links to select.", 2000
return
# This count is used to rank equal-scoring hints when sorting, thereby making JavaScript's sort stable.
@stableSortCount = 0
@hintMarkers = (@createMarkerFor desc for desc in hintDescriptors)
@markerMatcher = new (if Settings.get "filterLinkHints" then FilterHints else AlphabetHints)
@markerMatcher.fillInMarkers @hintMarkers, @.getNextZIndex.bind this
@hintMode = new Mode
name: "hint/#{@mode.name}"
indicator: false
singleton: "link-hints-mode"
suppressAllKeyboardEvents: true
suppressTrailingKeyEvents: true
exitOnEscape: true
exitOnClick: true
keydown: @onKeyDownInMode.bind this
@hintMode.onExit (event) =>
if event?.type == "click" or (event?.type == "keydown" and
(KeyboardUtils.isEscape(event) or KeyboardUtils.isBackspace event))
HintCoordinator.sendMessage "exit", isSuccess: false
# Note(PI:NAME:<NAME>END_PI): Append these markers as top level children instead of as child nodes to the link itself,
# because some clickable elements cannot contain children, e.g. submit buttons.
@hintMarkerContainingDiv = DomUtils.addElementList (marker for marker in @hintMarkers when marker.isLocalMarker),
id: "vimiumHintMarkerContainer", className: "vimiumReset"
@setIndicator()
setOpenLinkMode: (@mode, shouldPropagateToOtherFrames = true) ->
if shouldPropagateToOtherFrames
HintCoordinator.sendMessage "setOpenLinkMode", modeIndex: availableModes.indexOf @mode
else
@setIndicator()
setIndicator: ->
if windowIsFocused()
typedCharacters = @markerMatcher.linkTextKeystrokeQueue?.join("") ? ""
indicator = @mode.indicator + (if typedCharacters then ": \"#{typedCharacters}\"" else "") + "."
@hintMode.setIndicator indicator
getNextZIndex: do ->
# This is the starting z-index value; it produces z-index values which are greater than all of the other
# z-index values used by Vimium.
baseZIndex = 2140000000
-> baseZIndex += 1
#
# Creates a link marker for the given link.
#
createMarkerFor: (desc) ->
marker =
if desc.frameId == frameId
localHintDescriptor = HintCoordinator.getLocalHintMarker desc
el = DomUtils.createElement "div"
el.rect = localHintDescriptor.rect
el.style.left = el.rect.left + "px"
el.style.top = el.rect.top + "px"
# Each hint marker is assigned a different z-index.
el.style.zIndex = @getNextZIndex()
extend el,
className: "vimiumReset internalVimiumHintMarker vimiumHintMarker"
showLinkText: localHintDescriptor.showLinkText
localHintDescriptor: localHintDescriptor
else
{}
extend marker,
hintDescriptor: desc
isLocalMarker: desc.frameId == frameId
linkText: desc.linkText
stableSortCount: ++@stableSortCount
# Handles all keyboard events.
onKeyDownInMode: (event) ->
return if event.repeat
# NOTE(smblott) The modifier behaviour here applies only to alphabet hints.
if event.key in ["Control", "Shift"] and not Settings.get("filterLinkHints") and
@mode in [ OPEN_IN_CURRENT_TAB, OPEN_WITH_QUEUE, OPEN_IN_NEW_BG_TAB, OPEN_IN_NEW_FG_TAB ]
# Toggle whether to open the link in a new or current tab.
previousMode = @mode
key = event.key
switch key
when "Shift"
@setOpenLinkMode(if @mode is OPEN_IN_CURRENT_TAB then OPEN_IN_NEW_BG_TAB else OPEN_IN_CURRENT_TAB)
when "Control"
@setOpenLinkMode(if @mode is OPEN_IN_NEW_FG_TAB then OPEN_IN_NEW_BG_TAB else OPEN_IN_NEW_FG_TAB)
handlerId = @hintMode.push
keyup: (event) =>
if event.key == key
handlerStack.remove()
@setOpenLinkMode previousMode
true # Continue bubbling the event.
else if KeyboardUtils.isBackspace event
if @markerMatcher.popKeyChar()
@tabCount = 0
@updateVisibleMarkers()
else
# Exit via @hintMode.exit(), so that the LinkHints.activate() "onExit" callback sees the key event and
# knows not to restart hints mode.
@hintMode.exit event
else if event.key == "Enter"
# Activate the active hint, if there is one. Only FilterHints uses an active hint.
HintCoordinator.sendMessage "activateActiveHintMarker" if @markerMatcher.activeHintMarker
else if event.key == "Tab"
if event.shiftKey then @tabCount-- else @tabCount++
@updateVisibleMarkers()
else if event.key == " " and @markerMatcher.shouldRotateHints event
HintCoordinator.sendMessage "rotateHints"
else
unless event.repeat
keyChar =
if Settings.get "filterLinkHints"
KeyboardUtils.getKeyChar(event)
else
KeyboardUtils.getKeyChar(event).toLowerCase()
if keyChar
keyChar = " " if keyChar == "space"
if keyChar.length == 1
@tabCount = 0
@markerMatcher.pushKeyChar keyChar
@updateVisibleMarkers()
else
return handlerStack.suppressPropagation
handlerStack.suppressEvent
updateVisibleMarkers: ->
{hintKeystrokeQueue, linkTextKeystrokeQueue} = @markerMatcher
HintCoordinator.sendMessage "updateKeyState",
{hintKeystrokeQueue, linkTextKeystrokeQueue, tabCount: @tabCount}
updateKeyState: ({hintKeystrokeQueue, linkTextKeystrokeQueue, tabCount}) ->
extend @markerMatcher, {hintKeystrokeQueue, linkTextKeystrokeQueue}
{linksMatched, userMightOverType} = @markerMatcher.getMatchingHints @hintMarkers, tabCount, this.getNextZIndex.bind this
if linksMatched.length == 0
@deactivateMode()
else if linksMatched.length == 1
@activateLink linksMatched[0], userMightOverType
else
@hideMarker marker for marker in @hintMarkers
@showMarker matched, @markerMatcher.hintKeystrokeQueue.length for matched in linksMatched
@setIndicator()
# Rotate the hints' z-index values so that hidden hints become visible.
rotateHints: do ->
markerOverlapsStack = (marker, stack) ->
for otherMarker in stack
return true if Rect.intersects marker.markerRect, otherMarker.markerRect
false
->
# Get local, visible hint markers.
localHintMarkers = @hintMarkers.filter (marker) ->
marker.isLocalMarker and marker.style.display != "none"
# Fill in the markers' rects, if necessary.
marker.markerRect ?= marker.getClientRects()[0] for marker in localHintMarkers
# Calculate the overlapping groups of hints. We call each group a "stack". This is O(n^2).
stacks = []
for marker in localHintMarkers
stackForThisMarker = null
stacks =
for stack in stacks
markerOverlapsThisStack = markerOverlapsStack marker, stack
if markerOverlapsThisStack and not stackForThisMarker?
# We've found an existing stack for this marker.
stack.push marker
stackForThisMarker = stack
else if markerOverlapsThisStack and stackForThisMarker?
# This marker overlaps a second (or subsequent) stack; merge that stack into stackForThisMarker
# and discard it.
stackForThisMarker.push stack...
continue # Discard this stack.
else
stack # Keep this stack.
stacks.push [marker] unless stackForThisMarker?
# Rotate the z-indexes within each stack.
for stack in stacks
if 1 < stack.length
zIndexes = (marker.style.zIndex for marker in stack)
zIndexes.push zIndexes[0]
marker.style.zIndex = zIndexes[index + 1] for marker, index in stack
null # Prevent Coffeescript from building an unnecessary array.
# When only one hint remains, activate it in the appropriate way. The current frame may or may not contain
# the matched link, and may or may not have the focus. The resulting four cases are accounted for here by
# selectively pushing the appropriate HintCoordinator.onExit handlers.
activateLink: (linkMatched, userMightOverType = false) ->
@removeHintMarkers()
if linkMatched.isLocalMarker
localHintDescriptor = linkMatched.localHintDescriptor
clickEl = localHintDescriptor.element
HintCoordinator.onExit.push (isSuccess) =>
if isSuccess
if localHintDescriptor.reason == "Frame."
Utils.nextTick -> focusThisFrame highlight: true
else if localHintDescriptor.reason == "Scroll."
# Tell the scroller that this is the activated element.
handlerStack.bubbleEvent (if Utils.isFirefox() then "click" else "DOMActivate"), target: clickEl
else if localHintDescriptor.reason == "Open."
clickEl.open = !clickEl.open
else if DomUtils.isSelectable clickEl
window.focus()
DomUtils.simulateSelect clickEl
else
clickActivator = (modifiers) -> (link) -> DomUtils.simulateClick link, modifiers
linkActivator = @mode.linkActivator ? clickActivator @mode.clickModifiers
# Note(gdh1995): Here we should allow special elements to get focus,
# <select>: latest Chrome refuses `mousedown` event, and we can only
# focus it to let user press space to activate the popup menu
# <object> & <embed>: for Flash games which have their own key event handlers
# since we have been able to blur them by pressing `Escape`
if clickEl.nodeName.toLowerCase() in ["input", "select", "object", "embed"]
clickEl.focus()
linkActivator clickEl
# If flash elements are created, then this function can be used later to remove them.
removeFlashElements = ->
if linkMatched.isLocalMarker
{top: viewportTop, left: viewportLeft} = DomUtils.getViewportTopLeft()
flashElements = for rect in clickEl.getClientRects()
DomUtils.addFlashRect Rect.translate rect, viewportLeft, viewportTop
removeFlashElements = -> DomUtils.removeElement flashEl for flashEl in flashElements
# If we're using a keyboard blocker, then the frame with the focus sends the "exit" message, otherwise the
# frame containing the matched link does.
if userMightOverType
HintCoordinator.onExit.push removeFlashElements
if windowIsFocused()
callback = (isSuccess) -> HintCoordinator.sendMessage "exit", {isSuccess}
if Settings.get "waitForEnterForFilteredHints"
new WaitForEnter callback
else
new TypingProtector 200, callback
else if linkMatched.isLocalMarker
Utils.setTimeout 400, removeFlashElements
HintCoordinator.sendMessage "exit", isSuccess: true
#
# Shows the marker, highlighting matchingCharCount characters.
#
showMarker: (linkMarker, matchingCharCount) ->
return unless linkMarker.isLocalMarker
linkMarker.style.display = ""
for j in [0...linkMarker.childNodes.length]
if (j < matchingCharCount)
linkMarker.childNodes[j].classList.add("matchingCharacter")
else
linkMarker.childNodes[j].classList.remove("matchingCharacter")
hideMarker: (linkMarker) -> linkMarker.style.display = "none" if linkMarker.isLocalMarker
deactivateMode: ->
@removeHintMarkers()
@hintMode?.exit()
removeHintMarkers: ->
DomUtils.removeElement @hintMarkerContainingDiv if @hintMarkerContainingDiv
@hintMarkerContainingDiv = null
# Use characters for hints, and do not filter links by their text.
class AlphabetHints
constructor: ->
@linkHintCharacters = Settings.get("linkHintCharacters").toLowerCase()
@hintKeystrokeQueue = []
fillInMarkers: (hintMarkers) ->
hintStrings = @hintStrings(hintMarkers.length)
for marker, idx in hintMarkers
marker.hintString = hintStrings[idx]
marker.innerHTML = spanWrap(marker.hintString.toUpperCase()) if marker.isLocalMarker
#
# Returns a list of hint strings which will uniquely identify the given number of links. The hint strings
# may be of different lengths.
#
hintStrings: (linkCount) ->
hints = [""]
offset = 0
while hints.length - offset < linkCount or hints.length == 1
hint = hints[offset++]
hints.push ch + hint for ch in @linkHintCharacters
hints = hints[offset...offset+linkCount]
# Shuffle the hints so that they're scattered; hints starting with the same character and short hints are
# spread evenly throughout the array.
return hints.sort().map (str) -> str.reverse()
getMatchingHints: (hintMarkers) ->
matchString = @hintKeystrokeQueue.join ""
linksMatched: hintMarkers.filter (linkMarker) -> linkMarker.hintString.startsWith matchString
pushKeyChar: (keyChar) ->
@hintKeystrokeQueue.push keyChar
popKeyChar: -> @hintKeystrokeQueue.pop()
# For alphabet hints, <Space> always rotates the hints, regardless of modifiers.
shouldRotateHints: -> true
# Use characters for hints, and also filter links by their text.
class FilterHints
constructor: ->
@linkHintNumbers = Settings.get("linkHintNumbers").toUpperCase()
@hintKeystrokeQueue = []
@linkTextKeystrokeQueue = []
@activeHintMarker = null
# The regexp for splitting typed text and link texts. We split on sequences of non-word characters and
# link-hint numbers.
@splitRegexp = new RegExp "[\\W#{Utils.escapeRegexSpecialCharacters @linkHintNumbers}]+"
generateHintString: (linkHintNumber) ->
base = @linkHintNumbers.length
hint = []
while 0 < linkHintNumber
hint.push @linkHintNumbers[Math.floor linkHintNumber % base]
linkHintNumber = Math.floor linkHintNumber / base
hint.reverse().join ""
renderMarker: (marker) ->
linkText = marker.linkText
linkText = "#{linkText[..32]}..." if 35 < linkText.length
marker.innerHTML = spanWrap(marker.hintString +
(if marker.showLinkText then ": " + linkText else ""))
fillInMarkers: (hintMarkers, getNextZIndex) ->
@renderMarker marker for marker in hintMarkers when marker.isLocalMarker
# We use @getMatchingHints() here (although we know that all of the hints will match) to get an order on
# the hints and highlight the first one.
@getMatchingHints hintMarkers, 0, getNextZIndex
getMatchingHints: (hintMarkers, tabCount, getNextZIndex) ->
# At this point, linkTextKeystrokeQueue and hintKeystrokeQueue have been updated to reflect the latest
# input. Use them to filter the link hints accordingly.
matchString = @hintKeystrokeQueue.join ""
linksMatched = @filterLinkHints hintMarkers
linksMatched = linksMatched.filter (linkMarker) -> linkMarker.hintString.startsWith matchString
# Visually highlight of the active hint (that is, the one that will be activated if the user
# types <Enter>).
tabCount = ((linksMatched.length * Math.abs tabCount) + tabCount) % linksMatched.length
@activeHintMarker?.classList?.remove "vimiumActiveHintMarker"
@activeHintMarker = linksMatched[tabCount]
@activeHintMarker?.classList?.add "vimiumActiveHintMarker"
@activeHintMarker?.style?.zIndex = getNextZIndex()
linksMatched: linksMatched
userMightOverType: @hintKeystrokeQueue.length == 0 and 0 < @linkTextKeystrokeQueue.length
pushKeyChar: (keyChar) ->
if 0 <= @linkHintNumbers.indexOf keyChar
@hintKeystrokeQueue.push keyChar
else if keyChar.toLowerCase() != keyChar and @linkHintNumbers.toLowerCase() != @linkHintNumbers.toUpperCase()
# The the keyChar is upper case and the link hint "numbers" contain characters (e.g. [a-zA-Z]). We don't want
# some upper-case letters matching hints (above) and some matching text (below), so we ignore such keys.
return
# We only accept <Space> and characters which are not used for splitting (e.g. "a", "b", etc., but not "-").
else if keyChar == " " or not @splitRegexp.test keyChar
# Since we might renumber the hints, we should reset the current hintKeyStrokeQueue.
@hintKeystrokeQueue = []
@linkTextKeystrokeQueue.push keyChar.toLowerCase()
popKeyChar: ->
@hintKeystrokeQueue.pop() or @linkTextKeystrokeQueue.pop()
# Filter link hints by search string, renumbering the hints as necessary.
filterLinkHints: (hintMarkers) ->
scoreFunction = @scoreLinkHint @linkTextKeystrokeQueue.join ""
matchingHintMarkers =
hintMarkers
.filter (linkMarker) =>
linkMarker.score = scoreFunction linkMarker
0 == @linkTextKeystrokeQueue.length or 0 < linkMarker.score
.sort (a, b) ->
if b.score == a.score then b.stableSortCount - a.stableSortCount else b.score - a.score
if matchingHintMarkers.length == 0 and @hintKeystrokeQueue.length == 0 and 0 < @linkTextKeystrokeQueue.length
# We don't accept typed text which doesn't match any hints.
@linkTextKeystrokeQueue.pop()
@filterLinkHints hintMarkers
else
linkHintNumber = 1
for linkMarker in matchingHintMarkers
linkMarker.hintString = @generateHintString linkHintNumber++
@renderMarker linkMarker
linkMarker
# Assign a score to a filter match (higher is better). We assign a higher score for matches at the start of
# a word, and a considerably higher score still for matches which are whole words.
scoreLinkHint: (linkSearchString) ->
searchWords = linkSearchString.trim().toLowerCase().split @splitRegexp
(linkMarker) =>
return 0 unless 0 < searchWords.length
# We only keep non-empty link words. Empty link words cannot be matched, and leading empty link words
# disrupt the scoring of matches at the start of the text.
linkWords = linkMarker.linkWords ?= linkMarker.linkText.toLowerCase().split(@splitRegexp).filter (term) -> term
searchWordScores =
for searchWord in searchWords
linkWordScores =
for linkWord, idx in linkWords
position = linkWord.indexOf searchWord
if position < 0
0 # No match.
else if position == 0 and searchWord.length == linkWord.length
if idx == 0 then 8 else 4 # Whole-word match.
else if position == 0
if idx == 0 then 6 else 2 # Match at the start of a word.
else
1 # 0 < position; other match.
Math.max linkWordScores...
if 0 in searchWordScores
0
else
addFunc = (a,b) -> a + b
score = searchWordScores.reduce addFunc, 0
# Prefer matches in shorter texts. To keep things balanced for links without any text, we just weight
# them as if their length was 100 (so, quite long).
score / Math.log 1 + (linkMarker.linkText.length || 100)
# For filtered hints, we require a modifier (because <Space> on its own is a token separator).
shouldRotateHints: (event) ->
event.ctrlKey or event.altKey or event.metaKey or event.shiftKey
#
# Make each hint character a span, so that we can highlight the typed characters as you type them.
#
spanWrap = (hintString) ->
innerHTML = []
for char in hintString
innerHTML.push("<span class='vimiumReset'>" + char + "</span>")
innerHTML.join("")
LocalHints =
#
# Determine whether the element is visible and clickable. If it is, find the rect bounding the element in
# the viewport. There may be more than one part of element which is clickable (for example, if it's an
# image), therefore we always return a array of element/rect pairs (which may also be a singleton or empty).
#
getVisibleClickable: (element) ->
# Get the tag name. However, `element.tagName` can be an element (not a string, see #2035), so we guard
# against that.
tagName = element.tagName.toLowerCase?() ? ""
isClickable = false
onlyHasTabIndex = false
possibleFalsePositive = false
visibleElements = []
reason = null
# Insert area elements that provide click functionality to an img.
if tagName == "img"
mapName = element.getAttribute "usemap"
if mapName
imgClientRects = element.getClientRects()
mapName = mapName.replace(/^#/, "").replace("\"", "\\\"")
map = document.querySelector "map[name=\"#{mapName}\"]"
if map and imgClientRects.length > 0
areas = map.getElementsByTagName "area"
areasAndRects = DomUtils.getClientRectsForAreas imgClientRects[0], areas
visibleElements.push areasAndRects...
# Check aria properties to see if the element should be ignored.
if (element.getAttribute("aria-hidden")?.toLowerCase() in ["", "true"] or
element.getAttribute("aria-disabled")?.toLowerCase() in ["", "true"])
return [] # This element should never have a link hint.
# Check for AngularJS listeners on the element.
@checkForAngularJs ?= do ->
angularElements = document.getElementsByClassName "ng-scope"
if angularElements.length == 0
-> false
else
ngAttributes = []
for prefix in [ '', 'data-', 'x-' ]
for separator in [ '-', ':', '_' ]
ngAttributes.push "#{prefix}ng#{separator}click"
(element) ->
for attribute in ngAttributes
return true if element.hasAttribute attribute
false
isClickable ||= @checkForAngularJs element
# Check for attributes that make an element clickable regardless of its tagName.
if element.hasAttribute("onclick") or
(role = element.getAttribute "role") and role.toLowerCase() in [
"button" , "tab" , "link", "checkbox", "menuitem", "menuitemcheckbox", "menuitemradio"
] or
(contentEditable = element.getAttribute "contentEditable") and
contentEditable.toLowerCase() in ["", "contenteditable", "true"]
isClickable = true
# Check for jsaction event listeners on the element.
if not isClickable and element.hasAttribute "jsaction"
jsactionRules = element.getAttribute("jsaction").split(";")
for jsactionRule in jsactionRules
ruleSplit = jsactionRule.trim().split ":"
if 1 <= ruleSplit.length <= 2
[eventType, namespace, actionName ] =
if ruleSplit.length == 1
["click", ruleSplit[0].trim().split(".")..., "_"]
else
[ruleSplit[0], ruleSplit[1].trim().split(".")..., "_"]
isClickable ||= eventType == "click" and namespace != "none" and actionName != "_"
# Check for tagNames which are natively clickable.
switch tagName
when "a"
isClickable = true
when "textarea"
isClickable ||= not element.disabled and not element.readOnly
when "input"
isClickable ||= not (element.getAttribute("type")?.toLowerCase() == "hidden" or
element.disabled or
(element.readOnly and DomUtils.isSelectable element))
when "button", "select"
isClickable ||= not element.disabled
when "object", "embed"
isClickable = true
when "label"
isClickable ||= element.control? and not element.control.disabled and
(@getVisibleClickable element.control).length == 0
when "body"
isClickable ||=
if element == document.body and not windowIsFocused() and
window.innerWidth > 3 and window.innerHeight > 3 and
document.body?.tagName.toLowerCase() != "frameset"
reason = "Frame."
isClickable ||=
if element == document.body and windowIsFocused() and Scroller.isScrollableElement element
reason = "Scroll."
when "img"
isClickable ||= element.style.cursor in ["zoom-in", "zoom-out"]
when "div", "ol", "ul"
isClickable ||=
if element.clientHeight < element.scrollHeight and Scroller.isScrollableElement element
reason = "Scroll."
when "details"
isClickable = true
reason = "Open."
# NOTE(smblott) Disabled pending resolution of #2997.
# # Detect elements with "click" listeners installed with `addEventListener()`.
# isClickable ||= element.hasAttribute "_vimium-has-onclick-listener"
# An element with a class name containing the text "button" might be clickable. However, real clickables
# are often wrapped in elements with such class names. So, when we find clickables based only on their
# class name, we mark them as unreliable.
if not isClickable and 0 <= element.getAttribute("class")?.toLowerCase().indexOf "button"
possibleFalsePositive = isClickable = true
# Elements with tabindex are sometimes useful, but usually not. We can treat them as second class
# citizens when it improves UX, so take special note of them.
tabIndexValue = element.getAttribute("tabindex")
tabIndex = if tabIndexValue then parseInt tabIndexValue else -1
unless isClickable or tabIndex < 0 or isNaN(tabIndex)
isClickable = onlyHasTabIndex = true
if isClickable
clientRect = DomUtils.getVisibleClientRect element, true
if clientRect != null
visibleElements.push {element: element, rect: clientRect, secondClassCitizen: onlyHasTabIndex,
possibleFalsePositive, reason}
visibleElements
#
# Returns element at a given (x,y) with an optional root element.
# If the returned element is a shadow root, call the function use that recursively
# until we hit an actual element.
#
getElementFromPoint: (x, y, root = document, stack = []) ->
element = if root.elementsFromPoint then root.elementsFromPoint(x, y)[0] else root.elementFromPoint(x, y)
if stack.indexOf(element) != -1
return element
stack.push(element)
if element and element.shadowRoot
return LocalHints.getElementFromPoint(x, y, element.shadowRoot, stack)
return element
#
# Returns all clickable elements that are not hidden and are in the current viewport, along with rectangles
# at which (parts of) the elements are displayed.
# In the process, we try to find rects where elements do not overlap so that link hints are unambiguous.
# Because of this, the rects returned will frequently *NOT* be equivalent to the rects for the whole
# element.
#
getLocalHints: (requireHref) ->
# We need documentElement to be ready in order to find links.
return [] unless document.documentElement
# Find all elements, recursing into shadow DOM if present.
getAllElements = (root, elements = []) ->
for element in root.querySelectorAll "*"
elements.push element
if element.shadowRoot
getAllElements(element.shadowRoot, elements)
elements
elements = getAllElements document.documentElement
visibleElements = []
# The order of elements here is important; they should appear in the order they are in the DOM, so that
# we can work out which element is on top when multiple elements overlap. Detecting elements in this loop
# is the sensible, efficient way to ensure this happens.
# NOTE(mrmr1993): Our previous method (combined XPath and DOM traversal for jsaction) couldn't provide
# this, so it's necessary to check whether elements are clickable in order, as we do below.
for element in elements
unless requireHref and not element.href
visibleElement = @getVisibleClickable element
visibleElements.push visibleElement...
# Traverse the DOM from descendants to ancestors, so later elements show above earlier elements.
visibleElements = visibleElements.reverse()
# Filter out suspected false positives. A false positive is taken to be an element marked as a possible
# false positive for which a close descendant is already clickable. False positives tend to be close
# together in the DOM, so - to keep the cost down - we only search nearby elements. NOTE(smblott): The
# visible elements have already been reversed, so we're visiting descendants before their ancestors.
descendantsToCheck = [1..3] # This determines how many descendants we're willing to consider.
visibleElements =
for element, position in visibleElements
continue if element.possibleFalsePositive and do ->
index = Math.max 0, position - 6 # This determines how far back we're willing to look.
while index < position
candidateDescendant = visibleElements[index].element
for _ in descendantsToCheck
candidateDescendant = candidateDescendant?.parentElement
return true if candidateDescendant == element.element
index += 1
false # This is not a false positive.
element
# This loop will check if any corner or center of element is clickable
# document.elementFromPoint will find an element at a x,y location.
# Node.contain checks to see if an element contains another. note: someNode.contains(someNode) === true
# If we do not find our element as a descendant of any element we find, assume it's completely covered.
localHints = nonOverlappingElements = []
while visibleElement = visibleElements.pop()
if visibleElement.secondClassCitizen
continue
rect = visibleElement.rect
element = visibleElement.element
# Check middle of element first, as this is perhaps most likely to return true.
elementFromMiddlePoint = LocalHints.getElementFromPoint(rect.left + (rect.width * 0.5), rect.top + (rect.height * 0.5))
if elementFromMiddlePoint && (element.contains(elementFromMiddlePoint) or elementFromMiddlePoint.contains(element))
nonOverlappingElements.push visibleElement
continue
# If not in middle, try corners.
# Adjusting the rect by 0.1 towards the upper left, which empirically fixes some cases where another
# element would've been found instead. NOTE(philc): This isn't well explained. Originated in #2251.
verticalCoordinates = [rect.top + 0.1, rect.bottom - 0.1]
horizontalCoordinates = [rect.left + 0.1, rect.right - 0.1]
foundElement = false
for verticalCoordinate in verticalCoordinates
for horizontalCoordinate in horizontalCoordinates
elementFromPoint = LocalHints.getElementFromPoint(verticalCoordinate, horizontalCoordinate)
if elementFromPoint && (element.contains(elementFromPoint) or elementFromPoint.contains(element))
foundElement = true
break
if foundElement
nonOverlappingElements.push visibleElement
break;
# Position the rects within the window.
{top, left} = DomUtils.getViewportTopLeft()
for hint in nonOverlappingElements
hint.rect.top += top
hint.rect.left += left
if Settings.get "filterLinkHints"
extend hint, @generateLinkText hint for hint in localHints
localHints
generateLinkText: (hint) ->
element = hint.element
linkText = ""
showLinkText = false
# toLowerCase is necessary as html documents return "IMG" and xhtml documents return "img"
nodeName = element.nodeName.toLowerCase()
if nodeName == "input"
if element.labels? and element.labels.length > 0
linkText = element.labels[0].textContent.trim()
# Remove trailing ":" commonly found in labels.
if linkText[linkText.length-1] == ":"
linkText = linkText[...linkText.length-1]
showLinkText = true
else if element.getAttribute("type")?.toLowerCase() == "file"
linkText = "Choose File"
else if element.type != "password"
linkText = element.value
if not linkText and 'placeholder' of element
linkText = element.placeholder
# Check if there is an image embedded in the <a> tag.
else if nodeName == "a" and not element.textContent.trim() and
element.firstElementChild and
element.firstElementChild.nodeName.toLowerCase() == "img"
linkText = element.firstElementChild.alt || element.firstElementChild.title
showLinkText = true if linkText
else if hint.reason?
linkText = hint.reason
showLinkText = true
else if 0 < element.textContent.length
linkText = element.textContent[...256]
else if element.hasAttribute "title"
linkText = element.getAttribute "title"
else
linkText = element.innerHTML[...256]
{linkText: linkText.trim(), showLinkText}
# Suppress all keyboard events until the user stops typing for sufficiently long.
class TypingProtector extends Mode
constructor: (delay, callback) ->
@timer = Utils.setTimeout delay, => @exit()
resetExitTimer = (event) =>
clearTimeout @timer
@timer = Utils.setTimeout delay, => @exit()
super
name: "hint/typing-protector"
suppressAllKeyboardEvents: true
keydown: resetExitTimer
keypress: resetExitTimer
@onExit ->
callback true # true -> isSuccess.
class WaitForEnter extends Mode
constructor: (callback) ->
super
name: "hint/wait-for-enter"
suppressAllKeyboardEvents: true
indicator: "Hit <Enter> to proceed..."
@push
keydown: (event) =>
if event.key == "Enter"
@exit()
callback true # true -> isSuccess.
else if KeyboardUtils.isEscape event
@exit()
callback false # false -> isSuccess.
root = exports ? (window.root ?= {})
root.LinkHints = LinkHints
root.HintCoordinator = HintCoordinator
# For tests:
extend root, {LinkHintsMode, LocalHints, AlphabetHints, WaitForEnter}
extend window, root unless exports?
|
[
{
"context": "romise()\n\n @_make_request( \"login\", { username: username, password: password } )\n .done( ( data ) => df",
"end": 3912,
"score": 0.998796820640564,
"start": 3904,
"tag": "USERNAME",
"value": "username"
},
{
"context": "_request( \"login\", { username: username... | src/session.coffee | mikesimons/nibbana | 12 | uuid = require( 'node-uuid' )
jq = require( 'jquery' )
util = require( './util' )
constants = require( './constants' )
EntityMap = require( './entity_map' )
class Session
constructor: ( storage ) ->
@base_url = "https://api.nirvanahq.com/"
@authtoken = false
@common_url_params =
api: "rest"
requestid: () -> uuid.v4()
clienttime: () => util.unix_time()
authtoken: () => @authtoken
appid: "nirvanahqjs"
appversion: 0
@method_map =
login:
method: 'POST'
data:
method: "auth.new"
u: ( params ) -> params.username || throw new Error( "Username required to login" )
p: ( params ) -> params.password || throw new Error( "MD5 hash of password required to login" )
gmtoffset: new Date().getTimezoneOffset() / -60
logout:
method: 'POST'
data:
method: "auth.destroy"
everything:
method: 'GET'
url_params:
method: "everything"
since: ( params ) -> params.since || 0
save_task:
method: 'POST'
data:
method: "task.save"
save_tag:
method: 'POST'
data:
method: "tag.save"
@storage = storage
if @storage.has( "authtoken" )
@authenticate( @storage.get( "authtoken" ) )
# Internal method to handle common logic of throwing an error from the API.
_request_error: ( message, deferred ) ->
return ( data ) =>
deferred.reject() if deferred
throw new Error "#{message} (#{data.status} : #{data.statusText})"
# Internal method to handle common logic of making a request to the API.
_make_request: ( mapped_method, params ) ->
# All requests have common data to them which is defined in @common_url_params.
url_params = jq.extend( {}, @common_url_params )
# Mapping defines execution parameters and validates arguments.
mapping = @method_map[ mapped_method ]
# Merge common url params with method specific params.
if mapping.url_params
url_params[ k ] = v for k, v of mapping.url_params
# Some params require computation / are time sensitive so we apply any parameters that are functions here.
url_params[ k ] = v( params ) for k, v of url_params when typeof v == "function"
# opts we'll be passing to jQuery.
jqdata =
type: mapping.method
# If we've an array of params we want to use batch mode of API
if params.length != undefined
jqdata.contentType = "application/json"
payload = []
for param in params
data = if mapping.data then jq.extend( {}, mapping.data ) else {}
data[k] = v for k, v of param
data[k] = v( param ) for k, v of data when typeof v == "function"
payload.push data
payload = JSON.stringify( payload )
url_params.api = "json"
else
payload = if mapping.data then jq.extend( {}, mapping.data ) else {}
payload[k] = v for k, v of params
payload[k] = v( params ) for k, v of data when typeof v == "function"
jqdata.data = payload
jqdata.url = "#{@base_url}?#{jq.param(url_params)}"
# Finally we make the request.
# Unhelpfully the API will return 200 for a server application type error (invalid param or such) so we handle that.
jq.ajax( jqdata )
.done( (response) ->
if response.results && response.results[0].error
throw new Error "#{response.results[0].error.code} : #{response.results[0].error.message}"
)
authenticate: ( username, password, opts = {} ) ->
dfd = new jq.Deferred
dfd.done ( token ) => @authtoken = token
dfd.done ( token ) => @storage.set( "authtoken", token, false )
# The automatic preload will show if a given authtoken is valid or not.
if !password
dfd.resolve( username )
return @authenticated = dfd.promise()
@_make_request( "login", { username: username, password: password } )
.done( ( data ) => dfd.resolve( data.result[0].auth.token ) )
.fail( @_request_error( "Could not authenticate!", dfd ) )
return @authenticated = dfd.promise()
destroy: () ->
@_make_request( "logout" )
.done( => @authtoken = null )
.done( => @storage.remove( "authtoken" ) )
.fail( @_request_error("Could not logout!") )
store: ( model, dirty = true ) ->
@storage.set( model.store_key(), model, dirty )
sync: () ->
dfd = new jq.Deferred
task_dfd = new jq.Deferred
tag_dfd = new jq.Deferred
dirty = @storage.dirty
payloads =
task: []
tag: []
for k in dirty
data = @storage.get( k ).get_data()
delete data.__internal_type
key = if data.type == constants.task.type.TASK || data.type == constants.task.type.PROJECT then "task" else "tag"
payloads[ key ].push data
if payloads.task.length > 0
@_make_request( "save_task", payloads.task )
.done ( data ) =>
@_cache_results( data.results )
task_dfd.resolve( data )
else
task_dfd.resolve()
if payloads.tag.length > 0
@_make_request( "save_tag", payloads.tag )
.done ( data ) =>
@_cache_results( data.results )
tag_dfd.resolve( data )
else
tag_dfd.resolve()
jq.when( tag_dfd, task_dfd )
.then =>
@storage.clear_dirty()
dfd.resolve()
return dfd.promise()
needs_sync: () ->
@session.storage.dirty.length > 0
update: ( since = null ) ->
since = @storage.get( "last_update" ) || 0 if since == null
dfd = new jq.Deferred
success = ( data ) =>
@storage.set( "last_update", util.unix_time(), false )
@_cache_results( data.results )
dfd.resolve( data.results )
@_make_request( "everything", { since: since } )
.done( success )
.fail( @_request_error( "Could not fetch data!", dfd ) )
return dfd.promise()
_cache_results: ( results ) ->
for r in results
if r.user
m =
get_data: -> r.user
store_key: -> "user-#{r.user.id}"
else if r.task && r.task.type
m = new EntityMap["task#{r.task.type}"]( r.task )
else if r.tag && r.tag.type
m = new EntityMap["tag#{r.tag.type}"]( r.tag )
else
continue
@store( m, false )
module.exports = Session | 181237 | uuid = require( 'node-uuid' )
jq = require( 'jquery' )
util = require( './util' )
constants = require( './constants' )
EntityMap = require( './entity_map' )
class Session
constructor: ( storage ) ->
@base_url = "https://api.nirvanahq.com/"
@authtoken = false
@common_url_params =
api: "rest"
requestid: () -> uuid.v4()
clienttime: () => util.unix_time()
authtoken: () => @authtoken
appid: "nirvanahqjs"
appversion: 0
@method_map =
login:
method: 'POST'
data:
method: "auth.new"
u: ( params ) -> params.username || throw new Error( "Username required to login" )
p: ( params ) -> params.password || throw new Error( "MD5 hash of password required to login" )
gmtoffset: new Date().getTimezoneOffset() / -60
logout:
method: 'POST'
data:
method: "auth.destroy"
everything:
method: 'GET'
url_params:
method: "everything"
since: ( params ) -> params.since || 0
save_task:
method: 'POST'
data:
method: "task.save"
save_tag:
method: 'POST'
data:
method: "tag.save"
@storage = storage
if @storage.has( "authtoken" )
@authenticate( @storage.get( "authtoken" ) )
# Internal method to handle common logic of throwing an error from the API.
_request_error: ( message, deferred ) ->
return ( data ) =>
deferred.reject() if deferred
throw new Error "#{message} (#{data.status} : #{data.statusText})"
# Internal method to handle common logic of making a request to the API.
_make_request: ( mapped_method, params ) ->
# All requests have common data to them which is defined in @common_url_params.
url_params = jq.extend( {}, @common_url_params )
# Mapping defines execution parameters and validates arguments.
mapping = @method_map[ mapped_method ]
# Merge common url params with method specific params.
if mapping.url_params
url_params[ k ] = v for k, v of mapping.url_params
# Some params require computation / are time sensitive so we apply any parameters that are functions here.
url_params[ k ] = v( params ) for k, v of url_params when typeof v == "function"
# opts we'll be passing to jQuery.
jqdata =
type: mapping.method
# If we've an array of params we want to use batch mode of API
if params.length != undefined
jqdata.contentType = "application/json"
payload = []
for param in params
data = if mapping.data then jq.extend( {}, mapping.data ) else {}
data[k] = v for k, v of param
data[k] = v( param ) for k, v of data when typeof v == "function"
payload.push data
payload = JSON.stringify( payload )
url_params.api = "json"
else
payload = if mapping.data then jq.extend( {}, mapping.data ) else {}
payload[k] = v for k, v of params
payload[k] = v( params ) for k, v of data when typeof v == "function"
jqdata.data = payload
jqdata.url = "#{@base_url}?#{jq.param(url_params)}"
# Finally we make the request.
# Unhelpfully the API will return 200 for a server application type error (invalid param or such) so we handle that.
jq.ajax( jqdata )
.done( (response) ->
if response.results && response.results[0].error
throw new Error "#{response.results[0].error.code} : #{response.results[0].error.message}"
)
authenticate: ( username, password, opts = {} ) ->
dfd = new jq.Deferred
dfd.done ( token ) => @authtoken = token
dfd.done ( token ) => @storage.set( "authtoken", token, false )
# The automatic preload will show if a given authtoken is valid or not.
if !password
dfd.resolve( username )
return @authenticated = dfd.promise()
@_make_request( "login", { username: username, password: <PASSWORD> } )
.done( ( data ) => dfd.resolve( data.result[0].auth.token ) )
.fail( @_request_error( "Could not authenticate!", dfd ) )
return @authenticated = dfd.promise()
destroy: () ->
@_make_request( "logout" )
.done( => @authtoken = null )
.done( => @storage.remove( "authtoken" ) )
.fail( @_request_error("Could not logout!") )
store: ( model, dirty = true ) ->
@storage.set( model.store_key(), model, dirty )
sync: () ->
dfd = new jq.Deferred
task_dfd = new jq.Deferred
tag_dfd = new jq.Deferred
dirty = @storage.dirty
payloads =
task: []
tag: []
for k in dirty
data = @storage.get( k ).get_data()
delete data.__internal_type
key = if data.type == constants.task.type.TASK || data.type == constants.task.type.PROJECT then "<KEY>" else "<KEY>"
payloads[ key ].push data
if payloads.task.length > 0
@_make_request( "save_task", payloads.task )
.done ( data ) =>
@_cache_results( data.results )
task_dfd.resolve( data )
else
task_dfd.resolve()
if payloads.tag.length > 0
@_make_request( "save_tag", payloads.tag )
.done ( data ) =>
@_cache_results( data.results )
tag_dfd.resolve( data )
else
tag_dfd.resolve()
jq.when( tag_dfd, task_dfd )
.then =>
@storage.clear_dirty()
dfd.resolve()
return dfd.promise()
needs_sync: () ->
@session.storage.dirty.length > 0
update: ( since = null ) ->
since = @storage.get( "last_update" ) || 0 if since == null
dfd = new jq.Deferred
success = ( data ) =>
@storage.set( "last_update", util.unix_time(), false )
@_cache_results( data.results )
dfd.resolve( data.results )
@_make_request( "everything", { since: since } )
.done( success )
.fail( @_request_error( "Could not fetch data!", dfd ) )
return dfd.promise()
_cache_results: ( results ) ->
for r in results
if r.user
m =
get_data: -> r.user
store_key: -> "<KEY>
else if r.task && r.task.type
m = new EntityMap["task#{r.task.type}"]( r.task )
else if r.tag && r.tag.type
m = new EntityMap["tag#{r.tag.type}"]( r.tag )
else
continue
@store( m, false )
module.exports = Session | true | uuid = require( 'node-uuid' )
jq = require( 'jquery' )
util = require( './util' )
constants = require( './constants' )
EntityMap = require( './entity_map' )
class Session
constructor: ( storage ) ->
@base_url = "https://api.nirvanahq.com/"
@authtoken = false
@common_url_params =
api: "rest"
requestid: () -> uuid.v4()
clienttime: () => util.unix_time()
authtoken: () => @authtoken
appid: "nirvanahqjs"
appversion: 0
@method_map =
login:
method: 'POST'
data:
method: "auth.new"
u: ( params ) -> params.username || throw new Error( "Username required to login" )
p: ( params ) -> params.password || throw new Error( "MD5 hash of password required to login" )
gmtoffset: new Date().getTimezoneOffset() / -60
logout:
method: 'POST'
data:
method: "auth.destroy"
everything:
method: 'GET'
url_params:
method: "everything"
since: ( params ) -> params.since || 0
save_task:
method: 'POST'
data:
method: "task.save"
save_tag:
method: 'POST'
data:
method: "tag.save"
@storage = storage
if @storage.has( "authtoken" )
@authenticate( @storage.get( "authtoken" ) )
# Internal method to handle common logic of throwing an error from the API.
_request_error: ( message, deferred ) ->
return ( data ) =>
deferred.reject() if deferred
throw new Error "#{message} (#{data.status} : #{data.statusText})"
# Internal method to handle common logic of making a request to the API.
_make_request: ( mapped_method, params ) ->
# All requests have common data to them which is defined in @common_url_params.
url_params = jq.extend( {}, @common_url_params )
# Mapping defines execution parameters and validates arguments.
mapping = @method_map[ mapped_method ]
# Merge common url params with method specific params.
if mapping.url_params
url_params[ k ] = v for k, v of mapping.url_params
# Some params require computation / are time sensitive so we apply any parameters that are functions here.
url_params[ k ] = v( params ) for k, v of url_params when typeof v == "function"
# opts we'll be passing to jQuery.
jqdata =
type: mapping.method
# If we've an array of params we want to use batch mode of API
if params.length != undefined
jqdata.contentType = "application/json"
payload = []
for param in params
data = if mapping.data then jq.extend( {}, mapping.data ) else {}
data[k] = v for k, v of param
data[k] = v( param ) for k, v of data when typeof v == "function"
payload.push data
payload = JSON.stringify( payload )
url_params.api = "json"
else
payload = if mapping.data then jq.extend( {}, mapping.data ) else {}
payload[k] = v for k, v of params
payload[k] = v( params ) for k, v of data when typeof v == "function"
jqdata.data = payload
jqdata.url = "#{@base_url}?#{jq.param(url_params)}"
# Finally we make the request.
# Unhelpfully the API will return 200 for a server application type error (invalid param or such) so we handle that.
jq.ajax( jqdata )
.done( (response) ->
if response.results && response.results[0].error
throw new Error "#{response.results[0].error.code} : #{response.results[0].error.message}"
)
authenticate: ( username, password, opts = {} ) ->
dfd = new jq.Deferred
dfd.done ( token ) => @authtoken = token
dfd.done ( token ) => @storage.set( "authtoken", token, false )
# The automatic preload will show if a given authtoken is valid or not.
if !password
dfd.resolve( username )
return @authenticated = dfd.promise()
@_make_request( "login", { username: username, password: PI:PASSWORD:<PASSWORD>END_PI } )
.done( ( data ) => dfd.resolve( data.result[0].auth.token ) )
.fail( @_request_error( "Could not authenticate!", dfd ) )
return @authenticated = dfd.promise()
destroy: () ->
@_make_request( "logout" )
.done( => @authtoken = null )
.done( => @storage.remove( "authtoken" ) )
.fail( @_request_error("Could not logout!") )
store: ( model, dirty = true ) ->
@storage.set( model.store_key(), model, dirty )
sync: () ->
dfd = new jq.Deferred
task_dfd = new jq.Deferred
tag_dfd = new jq.Deferred
dirty = @storage.dirty
payloads =
task: []
tag: []
for k in dirty
data = @storage.get( k ).get_data()
delete data.__internal_type
key = if data.type == constants.task.type.TASK || data.type == constants.task.type.PROJECT then "PI:KEY:<KEY>END_PI" else "PI:KEY:<KEY>END_PI"
payloads[ key ].push data
if payloads.task.length > 0
@_make_request( "save_task", payloads.task )
.done ( data ) =>
@_cache_results( data.results )
task_dfd.resolve( data )
else
task_dfd.resolve()
if payloads.tag.length > 0
@_make_request( "save_tag", payloads.tag )
.done ( data ) =>
@_cache_results( data.results )
tag_dfd.resolve( data )
else
tag_dfd.resolve()
jq.when( tag_dfd, task_dfd )
.then =>
@storage.clear_dirty()
dfd.resolve()
return dfd.promise()
needs_sync: () ->
@session.storage.dirty.length > 0
update: ( since = null ) ->
since = @storage.get( "last_update" ) || 0 if since == null
dfd = new jq.Deferred
success = ( data ) =>
@storage.set( "last_update", util.unix_time(), false )
@_cache_results( data.results )
dfd.resolve( data.results )
@_make_request( "everything", { since: since } )
.done( success )
.fail( @_request_error( "Could not fetch data!", dfd ) )
return dfd.promise()
_cache_results: ( results ) ->
for r in results
if r.user
m =
get_data: -> r.user
store_key: -> "PI:KEY:<KEY>END_PI
else if r.task && r.task.type
m = new EntityMap["task#{r.task.type}"]( r.task )
else if r.tag && r.tag.type
m = new EntityMap["tag#{r.tag.type}"]( r.tag )
else
continue
@store( m, false )
module.exports = Session |
[
{
"context": "#\n# Copyright (c) 2014 by Maximilian Schüßler. See LICENSE for details.\n#\n# NOTE: RUN via `apm ",
"end": 45,
"score": 0.9998536109924316,
"start": 26,
"tag": "NAME",
"value": "Maximilian Schüßler"
}
] | spec/coffeedocs-spec.coffee | nmccready/coffeedocs | 0 | #
# Copyright (c) 2014 by Maximilian Schüßler. See LICENSE for details.
#
# NOTE: RUN via `apm test` not `npm test`
CoffeeDocs = require '../lib/coffeedocs'
{expect} = require 'chai'
describe 'CoffeeDocs', ->
[editor, coffeedocs] = []
beforeEach ->
coffeedocs = new CoffeeDocs()
waitsForPromise ->
atom.workspace.open('testfile.txt').then (o) -> editor = o
describe 'when we try to generate function documentation', ->
it 'detects the lines with functions correctly', ->
expect(coffeedocs.isFunctionDef(editor, 0)).to.be.equal(true)
expect(coffeedocs.isFunctionDef(editor, 1)).to.be.equal(true)
expect(coffeedocs.isFunctionDef(editor, 2)).to.be.equal(true)
expect(coffeedocs.isFunctionDef(editor, 3)).to.be.equal(false)
expect(coffeedocs.isFunctionDef(editor, 4)).to.be.equal(true)
expect(coffeedocs.isFunctionDef(editor, 5)).to.be.equal(true)
expect(coffeedocs.isFunctionDef(editor, 6)).to.be.equal(true)
it 'returns the right function names', ->
expect(coffeedocs.getFunctionDef(editor, 0).name).to.be.equal('luke')
expect(coffeedocs.getFunctionDef(editor, 1).name).to.be.equal('yoda')
expect(coffeedocs.getFunctionDef(editor, 2).name).to.be.equal('obiwan')
expect(coffeedocs.getFunctionDef(editor, 4).name).to.be.equal('quigon')
expect(coffeedocs.getFunctionDef(editor, 5).name).to.be.equal('windu')
expect(coffeedocs.getFunctionDef(editor, 6).name).to.be.equal('anakin')
it 'returns the right function arguments or none if there are none', ->
expect(coffeedocs.getFunctionDef(editor, 0).args).to.be.eql([])
expect(coffeedocs.getFunctionDef(editor, 1).args).to.be.eql(['arg1'])
expect(coffeedocs.getFunctionDef(editor, 2).args).to.be.eql(['arg1','arg2','arg3'])
expect(coffeedocs.getFunctionDef(editor, 4).args).to.be.eql([])
expect(coffeedocs.getFunctionDef(editor, 5).args).to.be.eql(['arg1'])
expect(coffeedocs.getFunctionDef(editor, 6).args).to.be.eql(['arg1','arg2','arg3'])
describe 'when we try to generate class documentation', ->
helper = (row) -> coffeedocs.getClassDef(editor, row)
describe 'when the line contains an anonymous class', ->
it 'parses it', ->
expect(helper(7)).to.be.eql({name: null, 'extends': null})
describe 'when the line contains a named class', ->
it 'parses it', ->
expect(helper(8)).to.be.eql({name: 'Vader', 'extends': null})
describe 'when the line contains a named subclass', ->
it 'parses it', ->
expect(helper(9)).to.be.eql({name: 'Vader', 'extends': 'Luke'})
| 22021 | #
# Copyright (c) 2014 by <NAME>. See LICENSE for details.
#
# NOTE: RUN via `apm test` not `npm test`
CoffeeDocs = require '../lib/coffeedocs'
{expect} = require 'chai'
describe 'CoffeeDocs', ->
[editor, coffeedocs] = []
beforeEach ->
coffeedocs = new CoffeeDocs()
waitsForPromise ->
atom.workspace.open('testfile.txt').then (o) -> editor = o
describe 'when we try to generate function documentation', ->
it 'detects the lines with functions correctly', ->
expect(coffeedocs.isFunctionDef(editor, 0)).to.be.equal(true)
expect(coffeedocs.isFunctionDef(editor, 1)).to.be.equal(true)
expect(coffeedocs.isFunctionDef(editor, 2)).to.be.equal(true)
expect(coffeedocs.isFunctionDef(editor, 3)).to.be.equal(false)
expect(coffeedocs.isFunctionDef(editor, 4)).to.be.equal(true)
expect(coffeedocs.isFunctionDef(editor, 5)).to.be.equal(true)
expect(coffeedocs.isFunctionDef(editor, 6)).to.be.equal(true)
it 'returns the right function names', ->
expect(coffeedocs.getFunctionDef(editor, 0).name).to.be.equal('luke')
expect(coffeedocs.getFunctionDef(editor, 1).name).to.be.equal('yoda')
expect(coffeedocs.getFunctionDef(editor, 2).name).to.be.equal('obiwan')
expect(coffeedocs.getFunctionDef(editor, 4).name).to.be.equal('quigon')
expect(coffeedocs.getFunctionDef(editor, 5).name).to.be.equal('windu')
expect(coffeedocs.getFunctionDef(editor, 6).name).to.be.equal('anakin')
it 'returns the right function arguments or none if there are none', ->
expect(coffeedocs.getFunctionDef(editor, 0).args).to.be.eql([])
expect(coffeedocs.getFunctionDef(editor, 1).args).to.be.eql(['arg1'])
expect(coffeedocs.getFunctionDef(editor, 2).args).to.be.eql(['arg1','arg2','arg3'])
expect(coffeedocs.getFunctionDef(editor, 4).args).to.be.eql([])
expect(coffeedocs.getFunctionDef(editor, 5).args).to.be.eql(['arg1'])
expect(coffeedocs.getFunctionDef(editor, 6).args).to.be.eql(['arg1','arg2','arg3'])
describe 'when we try to generate class documentation', ->
helper = (row) -> coffeedocs.getClassDef(editor, row)
describe 'when the line contains an anonymous class', ->
it 'parses it', ->
expect(helper(7)).to.be.eql({name: null, 'extends': null})
describe 'when the line contains a named class', ->
it 'parses it', ->
expect(helper(8)).to.be.eql({name: 'Vader', 'extends': null})
describe 'when the line contains a named subclass', ->
it 'parses it', ->
expect(helper(9)).to.be.eql({name: 'Vader', 'extends': 'Luke'})
| true | #
# Copyright (c) 2014 by PI:NAME:<NAME>END_PI. See LICENSE for details.
#
# NOTE: RUN via `apm test` not `npm test`
CoffeeDocs = require '../lib/coffeedocs'
{expect} = require 'chai'
describe 'CoffeeDocs', ->
[editor, coffeedocs] = []
beforeEach ->
coffeedocs = new CoffeeDocs()
waitsForPromise ->
atom.workspace.open('testfile.txt').then (o) -> editor = o
describe 'when we try to generate function documentation', ->
it 'detects the lines with functions correctly', ->
expect(coffeedocs.isFunctionDef(editor, 0)).to.be.equal(true)
expect(coffeedocs.isFunctionDef(editor, 1)).to.be.equal(true)
expect(coffeedocs.isFunctionDef(editor, 2)).to.be.equal(true)
expect(coffeedocs.isFunctionDef(editor, 3)).to.be.equal(false)
expect(coffeedocs.isFunctionDef(editor, 4)).to.be.equal(true)
expect(coffeedocs.isFunctionDef(editor, 5)).to.be.equal(true)
expect(coffeedocs.isFunctionDef(editor, 6)).to.be.equal(true)
it 'returns the right function names', ->
expect(coffeedocs.getFunctionDef(editor, 0).name).to.be.equal('luke')
expect(coffeedocs.getFunctionDef(editor, 1).name).to.be.equal('yoda')
expect(coffeedocs.getFunctionDef(editor, 2).name).to.be.equal('obiwan')
expect(coffeedocs.getFunctionDef(editor, 4).name).to.be.equal('quigon')
expect(coffeedocs.getFunctionDef(editor, 5).name).to.be.equal('windu')
expect(coffeedocs.getFunctionDef(editor, 6).name).to.be.equal('anakin')
it 'returns the right function arguments or none if there are none', ->
expect(coffeedocs.getFunctionDef(editor, 0).args).to.be.eql([])
expect(coffeedocs.getFunctionDef(editor, 1).args).to.be.eql(['arg1'])
expect(coffeedocs.getFunctionDef(editor, 2).args).to.be.eql(['arg1','arg2','arg3'])
expect(coffeedocs.getFunctionDef(editor, 4).args).to.be.eql([])
expect(coffeedocs.getFunctionDef(editor, 5).args).to.be.eql(['arg1'])
expect(coffeedocs.getFunctionDef(editor, 6).args).to.be.eql(['arg1','arg2','arg3'])
describe 'when we try to generate class documentation', ->
helper = (row) -> coffeedocs.getClassDef(editor, row)
describe 'when the line contains an anonymous class', ->
it 'parses it', ->
expect(helper(7)).to.be.eql({name: null, 'extends': null})
describe 'when the line contains a named class', ->
it 'parses it', ->
expect(helper(8)).to.be.eql({name: 'Vader', 'extends': null})
describe 'when the line contains a named subclass', ->
it 'parses it', ->
expect(helper(9)).to.be.eql({name: 'Vader', 'extends': 'Luke'})
|
[
{
"context": "###\nknockback-inspector.js 0.1.0\n(c) 2012 Kevin Malakoff.\nKnockback-Inspector.js is freely distributable u",
"end": 56,
"score": 0.9998703002929688,
"start": 42,
"tag": "NAME",
"value": "Kevin Malakoff"
},
{
"context": "ng for full license details:\n https://github.... | tutorials/coffeescript/step1/src/lib/kbi_core.coffee | kmalakoff/knockback-inspector | 1 | ###
knockback-inspector.js 0.1.0
(c) 2012 Kevin Malakoff.
Knockback-Inspector.js is freely distributable under the MIT license.
See the following for full license details:
https://github.com/kmalakoff/knockback-inspector/blob/master/LICENSE
Dependencies: Knockout.js, Underscore.js, Backbone.js, and Knockback.js.
###
@kbi or={}
@kbi.VERSION = '0.1.0' | 91781 | ###
knockback-inspector.js 0.1.0
(c) 2012 <NAME>.
Knockback-Inspector.js is freely distributable under the MIT license.
See the following for full license details:
https://github.com/kmalakoff/knockback-inspector/blob/master/LICENSE
Dependencies: Knockout.js, Underscore.js, Backbone.js, and Knockback.js.
###
@kbi or={}
@kbi.VERSION = '0.1.0' | true | ###
knockback-inspector.js 0.1.0
(c) 2012 PI:NAME:<NAME>END_PI.
Knockback-Inspector.js is freely distributable under the MIT license.
See the following for full license details:
https://github.com/kmalakoff/knockback-inspector/blob/master/LICENSE
Dependencies: Knockout.js, Underscore.js, Backbone.js, and Knockback.js.
###
@kbi or={}
@kbi.VERSION = '0.1.0' |
[
{
"context": " (location, key, value) ->\n supportedKeys = [ 'message' ]\n\n unless key in supportedKeys\n throw n",
"end": 1569,
"score": 0.8321295976638794,
"start": 1562,
"tag": "KEY",
"value": "message"
}
] | packages/litexa/src/parser/monetization.coffee | fboerncke/litexa | 34 | ###
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
###
lib = module.exports.lib = {}
class lib.BuyInSkillProductStatement
constructor: (referenceName) ->
@referenceName = referenceName
toLambda: (output, indent, options) ->
# @TODO: add warning if context.directives is not empty
# purchase directive must be the only directive in the response
output.push "#{indent}buildBuyInSkillProductDirective(context, \"#{@referenceName}\");"
class lib.CancelInSkillProductStatement
constructor: (referenceName) ->
@referenceName = referenceName
toLambda: (output, indent, options) ->
# @TODO: add warning if context.directives is not empty
# purchase directive must be the only directive in the response
output.push "#{indent}buildCancelInSkillProductDirective(context, \"#{@referenceName}\");"
class lib.UpsellInSkillProductStatement
constructor: (referenceName) ->
@referenceName = referenceName
@attributes = { message: '' }
toLambda: (output, indent, options) ->
# @TODO: add warning if context.directives is not empty
# purchase directive must be the only directive in the response
output.push "#{indent}buildUpsellInSkillProductDirective(context, \"#{@referenceName}\", \"#{@attributes.message}\");"
pushAttribute: (location, key, value) ->
supportedKeys = [ 'message' ]
unless key in supportedKeys
throw new lib.ParserError(location, "Attribute '#{key}' not supported > supported keys are: #{JSON.stringify(supportedKeys)}")
@attributes[key] = value
| 209309 | ###
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
###
lib = module.exports.lib = {}
class lib.BuyInSkillProductStatement
constructor: (referenceName) ->
@referenceName = referenceName
toLambda: (output, indent, options) ->
# @TODO: add warning if context.directives is not empty
# purchase directive must be the only directive in the response
output.push "#{indent}buildBuyInSkillProductDirective(context, \"#{@referenceName}\");"
class lib.CancelInSkillProductStatement
constructor: (referenceName) ->
@referenceName = referenceName
toLambda: (output, indent, options) ->
# @TODO: add warning if context.directives is not empty
# purchase directive must be the only directive in the response
output.push "#{indent}buildCancelInSkillProductDirective(context, \"#{@referenceName}\");"
class lib.UpsellInSkillProductStatement
constructor: (referenceName) ->
@referenceName = referenceName
@attributes = { message: '' }
toLambda: (output, indent, options) ->
# @TODO: add warning if context.directives is not empty
# purchase directive must be the only directive in the response
output.push "#{indent}buildUpsellInSkillProductDirective(context, \"#{@referenceName}\", \"#{@attributes.message}\");"
pushAttribute: (location, key, value) ->
supportedKeys = [ '<KEY>' ]
unless key in supportedKeys
throw new lib.ParserError(location, "Attribute '#{key}' not supported > supported keys are: #{JSON.stringify(supportedKeys)}")
@attributes[key] = value
| true | ###
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
###
lib = module.exports.lib = {}
class lib.BuyInSkillProductStatement
constructor: (referenceName) ->
@referenceName = referenceName
toLambda: (output, indent, options) ->
# @TODO: add warning if context.directives is not empty
# purchase directive must be the only directive in the response
output.push "#{indent}buildBuyInSkillProductDirective(context, \"#{@referenceName}\");"
class lib.CancelInSkillProductStatement
constructor: (referenceName) ->
@referenceName = referenceName
toLambda: (output, indent, options) ->
# @TODO: add warning if context.directives is not empty
# purchase directive must be the only directive in the response
output.push "#{indent}buildCancelInSkillProductDirective(context, \"#{@referenceName}\");"
class lib.UpsellInSkillProductStatement
constructor: (referenceName) ->
@referenceName = referenceName
@attributes = { message: '' }
toLambda: (output, indent, options) ->
# @TODO: add warning if context.directives is not empty
# purchase directive must be the only directive in the response
output.push "#{indent}buildUpsellInSkillProductDirective(context, \"#{@referenceName}\", \"#{@attributes.message}\");"
pushAttribute: (location, key, value) ->
supportedKeys = [ 'PI:KEY:<KEY>END_PI' ]
unless key in supportedKeys
throw new lib.ParserError(location, "Attribute '#{key}' not supported > supported keys are: #{JSON.stringify(supportedKeys)}")
@attributes[key] = value
|
[
{
"context": ":\"30\"},\"45\":\"http://www.google.com\",\"46\":\"\",\"47\":\"foo@bar.com\",\"48\":{\"country\":\"GB\",\"street\":\"123 main st\"},\"49",
"end": 889,
"score": 0.9998801946640015,
"start": 878,
"tag": "EMAIL",
"value": "foo@bar.com"
},
{
"context": "ut')\n $('.fr_res... | render/test/get_value_gm_test.coffee | johan--/Encuestas | 1 | # This is a "Gold master" test. If you need to update these constants, you can do so
# by manually clicking through the kitchen sink form in the Chrome dev console and running:
#
# copy(JSON.stringify($('[data-formrenderer]').data('form-renderer').getValue()))
#
# ...which will copy the stringified JSON to your clipboard. You should then manually verify
# the output, and if you're satisfied, you can finally update the constant.
EXPECTED_BLANK_VALUES = '{"37":{"0":false,"1":false},"44":{"am_pm":"AM"},"46":"","48":{"country":"US"},"49":{"0":["",""],"1":["",""]}}'
EXPECTED_PRESENT_VALUES = '{"35":"foo","36":"bar","37":{"0":"on","1":false},"39":"Choice #2","40":"Choice #2","41":{"dollars":"12","cents":"99"},"42":"123","43":{"month":"12","day":"30","year":"2014"},"44":{"am_pm":"PM","hours":"6","minutes":"01","seconds":"30"},"45":"http://www.google.com","46":"","47":"foo@bar.com","48":{"country":"GB","street":"123 main st"},"49":{"0":["hey",""],"1":["","nay"]},"50":{"lat":"40.7700118","lng":"-73.9800453"}}'
before ->
$('body').html('<div data-formrenderer />')
describe '#getValue', ->
before ->
@fr = new FormRenderer Fixtures.FormRendererOptions.KITCHEN_SINK()
@fieldCid
it 'renders ok', ->
expect(@fr).to.be.ok
it 'serializes the blank values', ->
expect(JSON.stringify(@fr.getValue())).to.equal(EXPECTED_BLANK_VALUES)
it 'serializes present values', (done) ->
$('.fr_response_field_text input').val('foo').trigger('input')
$('.fr_response_field_paragraph textarea').val('bar').trigger('input')
$('.fr_response_field_checkboxes input').first().click().trigger('change')
$('.fr_response_field_radio input').last().click().trigger('change')
$('.fr_response_field_dropdown select').val('Choice #2').trigger('change')
$('.fr_response_field_price input').first().val('12').trigger('input')
$('.fr_response_field_price input').last().val('99').trigger('input')
$('.fr_response_field_number input').last().val('123').trigger('input')
$('.fr_response_field_date input').eq(0).val('12').trigger('input')
$('.fr_response_field_date input').eq(1).val('30').trigger('input')
$('.fr_response_field_date input').eq(2).val('2014').trigger('input')
$('.fr_response_field_time input').eq(0).val('6').trigger('input')
$('.fr_response_field_time input').eq(1).val('01').trigger('input')
$('.fr_response_field_time input').eq(2).val('30').trigger('input')
$('.fr_response_field_time select').val('PM').trigger('change')
$('.fr_response_field_website input').val('http://www.google.com').trigger('input')
$('.fr_response_field_email input').val('foo@bar.com').trigger('input')
$('.fr_response_field_address input').eq(0).val('123 main st').trigger('input')
$('.fr_response_field_address select').val('GB').trigger('change')
$('.fr_response_field_table textarea').eq(0).val('hey').trigger('input')
$('.fr_response_field_table textarea').eq(3).val('nay').trigger('input')
# @todo file, mapmarker
$('.fr_response_field_map_marker .fr_map_cover').click()
expect(JSON.stringify(@fr.getValue())).to.equal(EXPECTED_PRESENT_VALUES)
done()
| 3398 | # This is a "Gold master" test. If you need to update these constants, you can do so
# by manually clicking through the kitchen sink form in the Chrome dev console and running:
#
# copy(JSON.stringify($('[data-formrenderer]').data('form-renderer').getValue()))
#
# ...which will copy the stringified JSON to your clipboard. You should then manually verify
# the output, and if you're satisfied, you can finally update the constant.
EXPECTED_BLANK_VALUES = '{"37":{"0":false,"1":false},"44":{"am_pm":"AM"},"46":"","48":{"country":"US"},"49":{"0":["",""],"1":["",""]}}'
EXPECTED_PRESENT_VALUES = '{"35":"foo","36":"bar","37":{"0":"on","1":false},"39":"Choice #2","40":"Choice #2","41":{"dollars":"12","cents":"99"},"42":"123","43":{"month":"12","day":"30","year":"2014"},"44":{"am_pm":"PM","hours":"6","minutes":"01","seconds":"30"},"45":"http://www.google.com","46":"","47":"<EMAIL>","48":{"country":"GB","street":"123 main st"},"49":{"0":["hey",""],"1":["","nay"]},"50":{"lat":"40.7700118","lng":"-73.9800453"}}'
before ->
$('body').html('<div data-formrenderer />')
describe '#getValue', ->
before ->
@fr = new FormRenderer Fixtures.FormRendererOptions.KITCHEN_SINK()
@fieldCid
it 'renders ok', ->
expect(@fr).to.be.ok
it 'serializes the blank values', ->
expect(JSON.stringify(@fr.getValue())).to.equal(EXPECTED_BLANK_VALUES)
it 'serializes present values', (done) ->
$('.fr_response_field_text input').val('foo').trigger('input')
$('.fr_response_field_paragraph textarea').val('bar').trigger('input')
$('.fr_response_field_checkboxes input').first().click().trigger('change')
$('.fr_response_field_radio input').last().click().trigger('change')
$('.fr_response_field_dropdown select').val('Choice #2').trigger('change')
$('.fr_response_field_price input').first().val('12').trigger('input')
$('.fr_response_field_price input').last().val('99').trigger('input')
$('.fr_response_field_number input').last().val('123').trigger('input')
$('.fr_response_field_date input').eq(0).val('12').trigger('input')
$('.fr_response_field_date input').eq(1).val('30').trigger('input')
$('.fr_response_field_date input').eq(2).val('2014').trigger('input')
$('.fr_response_field_time input').eq(0).val('6').trigger('input')
$('.fr_response_field_time input').eq(1).val('01').trigger('input')
$('.fr_response_field_time input').eq(2).val('30').trigger('input')
$('.fr_response_field_time select').val('PM').trigger('change')
$('.fr_response_field_website input').val('http://www.google.com').trigger('input')
$('.fr_response_field_email input').val('<EMAIL>').trigger('input')
$('.fr_response_field_address input').eq(0).val('123 main st').trigger('input')
$('.fr_response_field_address select').val('GB').trigger('change')
$('.fr_response_field_table textarea').eq(0).val('hey').trigger('input')
$('.fr_response_field_table textarea').eq(3).val('nay').trigger('input')
# @todo file, mapmarker
$('.fr_response_field_map_marker .fr_map_cover').click()
expect(JSON.stringify(@fr.getValue())).to.equal(EXPECTED_PRESENT_VALUES)
done()
| true | # This is a "Gold master" test. If you need to update these constants, you can do so
# by manually clicking through the kitchen sink form in the Chrome dev console and running:
#
# copy(JSON.stringify($('[data-formrenderer]').data('form-renderer').getValue()))
#
# ...which will copy the stringified JSON to your clipboard. You should then manually verify
# the output, and if you're satisfied, you can finally update the constant.
EXPECTED_BLANK_VALUES = '{"37":{"0":false,"1":false},"44":{"am_pm":"AM"},"46":"","48":{"country":"US"},"49":{"0":["",""],"1":["",""]}}'
EXPECTED_PRESENT_VALUES = '{"35":"foo","36":"bar","37":{"0":"on","1":false},"39":"Choice #2","40":"Choice #2","41":{"dollars":"12","cents":"99"},"42":"123","43":{"month":"12","day":"30","year":"2014"},"44":{"am_pm":"PM","hours":"6","minutes":"01","seconds":"30"},"45":"http://www.google.com","46":"","47":"PI:EMAIL:<EMAIL>END_PI","48":{"country":"GB","street":"123 main st"},"49":{"0":["hey",""],"1":["","nay"]},"50":{"lat":"40.7700118","lng":"-73.9800453"}}'
before ->
$('body').html('<div data-formrenderer />')
describe '#getValue', ->
before ->
@fr = new FormRenderer Fixtures.FormRendererOptions.KITCHEN_SINK()
@fieldCid
it 'renders ok', ->
expect(@fr).to.be.ok
it 'serializes the blank values', ->
expect(JSON.stringify(@fr.getValue())).to.equal(EXPECTED_BLANK_VALUES)
it 'serializes present values', (done) ->
$('.fr_response_field_text input').val('foo').trigger('input')
$('.fr_response_field_paragraph textarea').val('bar').trigger('input')
$('.fr_response_field_checkboxes input').first().click().trigger('change')
$('.fr_response_field_radio input').last().click().trigger('change')
$('.fr_response_field_dropdown select').val('Choice #2').trigger('change')
$('.fr_response_field_price input').first().val('12').trigger('input')
$('.fr_response_field_price input').last().val('99').trigger('input')
$('.fr_response_field_number input').last().val('123').trigger('input')
$('.fr_response_field_date input').eq(0).val('12').trigger('input')
$('.fr_response_field_date input').eq(1).val('30').trigger('input')
$('.fr_response_field_date input').eq(2).val('2014').trigger('input')
$('.fr_response_field_time input').eq(0).val('6').trigger('input')
$('.fr_response_field_time input').eq(1).val('01').trigger('input')
$('.fr_response_field_time input').eq(2).val('30').trigger('input')
$('.fr_response_field_time select').val('PM').trigger('change')
$('.fr_response_field_website input').val('http://www.google.com').trigger('input')
$('.fr_response_field_email input').val('PI:EMAIL:<EMAIL>END_PI').trigger('input')
$('.fr_response_field_address input').eq(0).val('123 main st').trigger('input')
$('.fr_response_field_address select').val('GB').trigger('change')
$('.fr_response_field_table textarea').eq(0).val('hey').trigger('input')
$('.fr_response_field_table textarea').eq(3).val('nay').trigger('input')
# @todo file, mapmarker
$('.fr_response_field_map_marker .fr_map_cover').click()
expect(JSON.stringify(@fr.getValue())).to.equal(EXPECTED_PRESENT_VALUES)
done()
|
[
{
"context": "edit-name'\n view.$(click).click()\n value = 'Peter Bishop' if value is null\n view.$(field).text value\n ",
"end": 577,
"score": 0.9996816515922546,
"start": 565,
"tag": "NAME",
"value": "Peter Bishop"
},
{
"context": "d not be tracked globally\n view.$(fi... | mixins/views/editable.spec.coffee | kpunith8/gringotts | 0 | import Chaplin from 'chaplin'
import ValidateModelMock from '../../lib/mocks/validate-model-mock'
import EditableViewMock from '../../lib/mocks/editable-view-mock'
describe 'Editable', ->
model = null
view = null
success = null
error = null
errorClass = undefined
opts = null
customOpts = null
enter = null
field = null
click = null
value = null
event = null
# TODO: this is a duplicate from editable-callbacks-test
setupEditableBefore = ->
field ||= '.name-field'
click ||= '.edit-name'
view.$(click).click()
value = 'Peter Bishop' if value is null
view.$(field).text value
e = if event is null then enter else event
view.$(field).trigger e
setupEditableAfter = ->
# FIXME: since error state is tracked globally it has to be reset after
# each test. it should not be tracked globally
view.$(field).text('Peter Bishop').trigger enter
click = null
field = null
beforeEach ->
sinon.stub document, 'execCommand'
model = new ValidateModelMock
name: 'Olivia Dunham'
email: 'odunhameffbeeeye.com'
url: 'http://dunham.com'
view = new EditableViewMock {model}
success = sinon.spy()
error = sinon.spy()
opts = _.extend {
success
error
errorClass
}, customOpts
view.setupEditable '.edit-name', '.name-field', opts
enter = $.Event 'keydown', keyCode: 13
afterEach ->
enter = null
view.dispose()
model.dispose()
model = null
view = null
opts = null
document.execCommand.restore()
it 'should attache a click handler', ->
view.$('.edit-name').click()
expect(view.$field()).to.have.attr 'contenteditable'
expect(document.execCommand).to.have.been.called
context 'optional model defined', ->
otherModel = null
before ->
otherModel = new ValidateModelMock test: 'test'
sinon.spy otherModel, 'validate'
customOpts =
model: otherModel
beforeEach setupEditableBefore
afterEach setupEditableAfter
after ->
customOpts = null
otherModel.dispose()
otherModel = null
it 'should make editable', ->
expect(otherModel.validate).to.have.been.called
context 'editing the name field', ->
beforeEach ->
sinon.spy model, 'validate'
beforeEach setupEditableBefore
afterEach setupEditableAfter
context 'then pressing enter', ->
it 'should persist the data', ->
expect(view.$field()).to.contain 'Peter Bishop'
expect(success).to.have.been.called
expect(view.$field()).to.not.have.attr 'contenteditable'
it 'should validate using the model', ->
expect(model.validate).to.have.been.called
context 'then pressing escape', ->
before ->
event = $.Event 'keydown', keyCode: 27
after ->
event = null
it 'should revert the data', ->
expect(view.$field()).to.contain 'Olivia Dunham'
expect(success).not.to.have.been.called
expect(view.$field()).to.not.have.attr 'contenteditable'
expect(model.validationError).to.be.null
context 'then causing blur', ->
before ->
event = $.Event 'blur'
after ->
event = null
it 'should persist the data', ->
expect(view.$field()).to.contain 'Peter Bishop'
expect(success).to.have.been.called
expect(view.$field()).to.not.have.attr 'contenteditable'
it 'should not have an href', ->
expect(view.$field()).not.to.have.attr 'href'
context 'with a paste', ->
before ->
event = $.Event 'paste'
event.originalEvent =
clipboardData: {getData: -> 'sesame'}
preventDefault: ->
after ->
event = null
it 'should insert the copied text', ->
expect(document.execCommand).to.have.been.calledWith(
'insertHTML', no, 'sesame'
)
context 'with an invalid value', ->
expectNotRevertData = ->
expect(success).not.to.have.been.called
expect(error).to.have.been.called
expect(view.$field()).to.have.text ''
expect(view.$field()).to.have.class 'error-input'
expect(view.$field()).to.have.attr 'contenteditable', 'true'
expect(view.$field()).to.have.attr 'data-toggle', 'tooltip'
expect(view.$field()).to.have.attr 'data-original-title',
'attribute is empty'
before ->
value = ''
after ->
value = null
context 'then pressing enter', ->
expectNoError = ->
expect(view.$field()).to.not.have.class 'error-input'
expect(view.$field()).to.not.have.attr 'contenteditable'
expect(view.$field()).to.not.have.attr 'data-toggle'
expect(view.$field()).to.not.have.attr 'data-original-title'
expect(model.validationError).to.not.exist
it 'should not revert the data', ->
expectNotRevertData.call this
context 'then fixing the error', ->
beforeEach ->
view.$field().text('Walter Bishop').trigger enter
it 'should remove the error class and saves', ->
expect(success).to.have.been.called
expect(error).to.have.been.calledOnce
expectNoError.call this
context 'then canceling edit', ->
beforeEach ->
escape = $.Event 'keydown', keyCode: 27
view.$field().trigger escape
it 'should remove the error class and reverts', ->
expect(view.$field()).to.contain 'Olivia Dunham'
expect(success).to.not.have.been.called
expectNoError.call this
context 'then causing blur', ->
before ->
event = $.Event 'blur'
after ->
event = null
it 'should revert the data', ->
expectNotRevertData.call this
context 'and a custom error class', ->
before ->
errorClass = 'my-error'
after ->
errorClass = undefined
context 'then pressing enter', ->
it 'should attache the custom class', ->
expect(view.$field()).to.have.class 'my-error'
context 'and multiple editable views', ->
model2 = null
view2 = null
beforeEach ->
model2 = new ValidateModelMock name: 'Phillip Broyles'
view2 = new EditableViewMock model: model2
view2.setupEditable '.edit-name', '.name-field'
view2.$('.edit-name').click()
# Non-DOM fragments don't propagate a blur event on click.
view.$('.name-field').blur()
afterEach ->
view2 = null
model2 = null
# Focus from makeEditable click triggers another blur.
it 'should keep the original and does not focus the second one', ->
# Original is with updated value.
expect(view.$field()).to.have.attr 'contenteditable'
expect(view.$field()).to.have.class 'error-input'
expect(view.$field()).to.have.text ''
# Second view is being edited.
expect(view2.$field()).to.have.attr 'contenteditable'
expect(view2.$field()).to.not.have.class 'error-input'
expect(view2.$field()).to.contain 'Phillip Broyles'
describe 'with the same value', ->
before ->
value = 'Olivia Dunham'
after ->
value = null
context 'then pressing enter', ->
it 'should do nothing', ->
expect(view.$field()).to.contain 'Olivia Dunham'
expect(success).not.to.have.been.called
expect(view.$field()).to.not.have.attr 'contenteditable'
context 'with a numeric value', ->
before ->
value = '1001'
after ->
value = null
context 'then pressing enter', ->
it 'should convert it to a number', ->
expect(view.$field()).to.contain '1001'
expect(success).to.have.been.called
args = success.lastCall.args[0]
expect(args).to.have.property 'value', 1001
context 'editing an email field', ->
beforeEach ->
view.setupEditable '.edit-email', '.email-field'
view.$('.edit-email').click()
view.$('.email-field').text 'olivia.dunham@effbeeeye.com'
view.$('.email-field').trigger enter
it 'should update the href', ->
expect(view.$ '.email-field').to.have.attr('href')
.and.to.equal 'mailto:olivia.dunham@effbeeeye.com'
context 'editing a URL field', ->
url = null
beforeEach ->
view.setupEditable '.edit-url', '.url-field'
view.$('.edit-url').click()
view.$('.url-field').text(url or 'http://olivia.com')
view.$('.url-field').trigger enter
it 'should update the href', ->
expect(view.$ '.url-field').to.have.attr('href')
.and.to.equal 'http://olivia.com'
context 'without a protocol', ->
before ->
url = 'olivia.com'
after ->
url = null
it 'should make the href protocol relative', ->
expect(view.$ '.url-field').to.have.attr('href')
.and.to.equal '//olivia.com'
| 222747 | import Chaplin from 'chaplin'
import ValidateModelMock from '../../lib/mocks/validate-model-mock'
import EditableViewMock from '../../lib/mocks/editable-view-mock'
describe 'Editable', ->
model = null
view = null
success = null
error = null
errorClass = undefined
opts = null
customOpts = null
enter = null
field = null
click = null
value = null
event = null
# TODO: this is a duplicate from editable-callbacks-test
setupEditableBefore = ->
field ||= '.name-field'
click ||= '.edit-name'
view.$(click).click()
value = '<NAME>' if value is null
view.$(field).text value
e = if event is null then enter else event
view.$(field).trigger e
setupEditableAfter = ->
# FIXME: since error state is tracked globally it has to be reset after
# each test. it should not be tracked globally
view.$(field).text('<NAME>').trigger enter
click = null
field = null
beforeEach ->
sinon.stub document, 'execCommand'
model = new ValidateModelMock
name: '<NAME>'
email: 'odunhameffbeeeye.com'
url: 'http://dunham.com'
view = new EditableViewMock {model}
success = sinon.spy()
error = sinon.spy()
opts = _.extend {
success
error
errorClass
}, customOpts
view.setupEditable '.edit-name', '.name-field', opts
enter = $.Event 'keydown', keyCode: 13
afterEach ->
enter = null
view.dispose()
model.dispose()
model = null
view = null
opts = null
document.execCommand.restore()
it 'should attache a click handler', ->
view.$('.edit-name').click()
expect(view.$field()).to.have.attr 'contenteditable'
expect(document.execCommand).to.have.been.called
context 'optional model defined', ->
otherModel = null
before ->
otherModel = new ValidateModelMock test: 'test'
sinon.spy otherModel, 'validate'
customOpts =
model: otherModel
beforeEach setupEditableBefore
afterEach setupEditableAfter
after ->
customOpts = null
otherModel.dispose()
otherModel = null
it 'should make editable', ->
expect(otherModel.validate).to.have.been.called
context 'editing the name field', ->
beforeEach ->
sinon.spy model, 'validate'
beforeEach setupEditableBefore
afterEach setupEditableAfter
context 'then pressing enter', ->
it 'should persist the data', ->
expect(view.$field()).to.contain '<NAME>'
expect(success).to.have.been.called
expect(view.$field()).to.not.have.attr 'contenteditable'
it 'should validate using the model', ->
expect(model.validate).to.have.been.called
context 'then pressing escape', ->
before ->
event = $.Event 'keydown', keyCode: 27
after ->
event = null
it 'should revert the data', ->
expect(view.$field()).to.contain '<NAME>'
expect(success).not.to.have.been.called
expect(view.$field()).to.not.have.attr 'contenteditable'
expect(model.validationError).to.be.null
context 'then causing blur', ->
before ->
event = $.Event 'blur'
after ->
event = null
it 'should persist the data', ->
expect(view.$field()).to.contain '<NAME>'
expect(success).to.have.been.called
expect(view.$field()).to.not.have.attr 'contenteditable'
it 'should not have an href', ->
expect(view.$field()).not.to.have.attr 'href'
context 'with a paste', ->
before ->
event = $.Event 'paste'
event.originalEvent =
clipboardData: {getData: -> 'sesame'}
preventDefault: ->
after ->
event = null
it 'should insert the copied text', ->
expect(document.execCommand).to.have.been.calledWith(
'insertHTML', no, 'sesame'
)
context 'with an invalid value', ->
expectNotRevertData = ->
expect(success).not.to.have.been.called
expect(error).to.have.been.called
expect(view.$field()).to.have.text ''
expect(view.$field()).to.have.class 'error-input'
expect(view.$field()).to.have.attr 'contenteditable', 'true'
expect(view.$field()).to.have.attr 'data-toggle', 'tooltip'
expect(view.$field()).to.have.attr 'data-original-title',
'attribute is empty'
before ->
value = ''
after ->
value = null
context 'then pressing enter', ->
expectNoError = ->
expect(view.$field()).to.not.have.class 'error-input'
expect(view.$field()).to.not.have.attr 'contenteditable'
expect(view.$field()).to.not.have.attr 'data-toggle'
expect(view.$field()).to.not.have.attr 'data-original-title'
expect(model.validationError).to.not.exist
it 'should not revert the data', ->
expectNotRevertData.call this
context 'then fixing the error', ->
beforeEach ->
view.$field().text('<NAME>').trigger enter
it 'should remove the error class and saves', ->
expect(success).to.have.been.called
expect(error).to.have.been.calledOnce
expectNoError.call this
context 'then canceling edit', ->
beforeEach ->
escape = $.Event 'keydown', keyCode: 27
view.$field().trigger escape
it 'should remove the error class and reverts', ->
expect(view.$field()).to.contain '<NAME>'
expect(success).to.not.have.been.called
expectNoError.call this
context 'then causing blur', ->
before ->
event = $.Event 'blur'
after ->
event = null
it 'should revert the data', ->
expectNotRevertData.call this
context 'and a custom error class', ->
before ->
errorClass = 'my-error'
after ->
errorClass = undefined
context 'then pressing enter', ->
it 'should attache the custom class', ->
expect(view.$field()).to.have.class 'my-error'
context 'and multiple editable views', ->
model2 = null
view2 = null
beforeEach ->
model2 = new ValidateModelMock name: '<NAME>'
view2 = new EditableViewMock model: model2
view2.setupEditable '.edit-name', '.name-field'
view2.$('.edit-name').click()
# Non-DOM fragments don't propagate a blur event on click.
view.$('.name-field').blur()
afterEach ->
view2 = null
model2 = null
# Focus from makeEditable click triggers another blur.
it 'should keep the original and does not focus the second one', ->
# Original is with updated value.
expect(view.$field()).to.have.attr 'contenteditable'
expect(view.$field()).to.have.class 'error-input'
expect(view.$field()).to.have.text ''
# Second view is being edited.
expect(view2.$field()).to.have.attr 'contenteditable'
expect(view2.$field()).to.not.have.class 'error-input'
expect(view2.$field()).to.contain '<NAME>'
describe 'with the same value', ->
before ->
value = '<NAME>'
after ->
value = null
context 'then pressing enter', ->
it 'should do nothing', ->
expect(view.$field()).to.contain '<NAME>'
expect(success).not.to.have.been.called
expect(view.$field()).to.not.have.attr 'contenteditable'
context 'with a numeric value', ->
before ->
value = '1001'
after ->
value = null
context 'then pressing enter', ->
it 'should convert it to a number', ->
expect(view.$field()).to.contain '1001'
expect(success).to.have.been.called
args = success.lastCall.args[0]
expect(args).to.have.property 'value', 1001
context 'editing an email field', ->
beforeEach ->
view.setupEditable '.edit-email', '.email-field'
view.$('.edit-email').click()
view.$('.email-field').text '<EMAIL>'
view.$('.email-field').trigger enter
it 'should update the href', ->
expect(view.$ '.email-field').to.have.attr('href')
.and.to.equal 'mailto:<EMAIL>'
context 'editing a URL field', ->
url = null
beforeEach ->
view.setupEditable '.edit-url', '.url-field'
view.$('.edit-url').click()
view.$('.url-field').text(url or 'http://olivia.com')
view.$('.url-field').trigger enter
it 'should update the href', ->
expect(view.$ '.url-field').to.have.attr('href')
.and.to.equal 'http://olivia.com'
context 'without a protocol', ->
before ->
url = 'olivia.com'
after ->
url = null
it 'should make the href protocol relative', ->
expect(view.$ '.url-field').to.have.attr('href')
.and.to.equal '//olivia.com'
| true | import Chaplin from 'chaplin'
import ValidateModelMock from '../../lib/mocks/validate-model-mock'
import EditableViewMock from '../../lib/mocks/editable-view-mock'
describe 'Editable', ->
model = null
view = null
success = null
error = null
errorClass = undefined
opts = null
customOpts = null
enter = null
field = null
click = null
value = null
event = null
# TODO: this is a duplicate from editable-callbacks-test
setupEditableBefore = ->
field ||= '.name-field'
click ||= '.edit-name'
view.$(click).click()
value = 'PI:NAME:<NAME>END_PI' if value is null
view.$(field).text value
e = if event is null then enter else event
view.$(field).trigger e
setupEditableAfter = ->
# FIXME: since error state is tracked globally it has to be reset after
# each test. it should not be tracked globally
view.$(field).text('PI:NAME:<NAME>END_PI').trigger enter
click = null
field = null
beforeEach ->
sinon.stub document, 'execCommand'
model = new ValidateModelMock
name: 'PI:NAME:<NAME>END_PI'
email: 'odunhameffbeeeye.com'
url: 'http://dunham.com'
view = new EditableViewMock {model}
success = sinon.spy()
error = sinon.spy()
opts = _.extend {
success
error
errorClass
}, customOpts
view.setupEditable '.edit-name', '.name-field', opts
enter = $.Event 'keydown', keyCode: 13
afterEach ->
enter = null
view.dispose()
model.dispose()
model = null
view = null
opts = null
document.execCommand.restore()
it 'should attache a click handler', ->
view.$('.edit-name').click()
expect(view.$field()).to.have.attr 'contenteditable'
expect(document.execCommand).to.have.been.called
context 'optional model defined', ->
otherModel = null
before ->
otherModel = new ValidateModelMock test: 'test'
sinon.spy otherModel, 'validate'
customOpts =
model: otherModel
beforeEach setupEditableBefore
afterEach setupEditableAfter
after ->
customOpts = null
otherModel.dispose()
otherModel = null
it 'should make editable', ->
expect(otherModel.validate).to.have.been.called
context 'editing the name field', ->
beforeEach ->
sinon.spy model, 'validate'
beforeEach setupEditableBefore
afterEach setupEditableAfter
context 'then pressing enter', ->
it 'should persist the data', ->
expect(view.$field()).to.contain 'PI:NAME:<NAME>END_PI'
expect(success).to.have.been.called
expect(view.$field()).to.not.have.attr 'contenteditable'
it 'should validate using the model', ->
expect(model.validate).to.have.been.called
context 'then pressing escape', ->
before ->
event = $.Event 'keydown', keyCode: 27
after ->
event = null
it 'should revert the data', ->
expect(view.$field()).to.contain 'PI:NAME:<NAME>END_PI'
expect(success).not.to.have.been.called
expect(view.$field()).to.not.have.attr 'contenteditable'
expect(model.validationError).to.be.null
context 'then causing blur', ->
before ->
event = $.Event 'blur'
after ->
event = null
it 'should persist the data', ->
expect(view.$field()).to.contain 'PI:NAME:<NAME>END_PI'
expect(success).to.have.been.called
expect(view.$field()).to.not.have.attr 'contenteditable'
it 'should not have an href', ->
expect(view.$field()).not.to.have.attr 'href'
context 'with a paste', ->
before ->
event = $.Event 'paste'
event.originalEvent =
clipboardData: {getData: -> 'sesame'}
preventDefault: ->
after ->
event = null
it 'should insert the copied text', ->
expect(document.execCommand).to.have.been.calledWith(
'insertHTML', no, 'sesame'
)
context 'with an invalid value', ->
expectNotRevertData = ->
expect(success).not.to.have.been.called
expect(error).to.have.been.called
expect(view.$field()).to.have.text ''
expect(view.$field()).to.have.class 'error-input'
expect(view.$field()).to.have.attr 'contenteditable', 'true'
expect(view.$field()).to.have.attr 'data-toggle', 'tooltip'
expect(view.$field()).to.have.attr 'data-original-title',
'attribute is empty'
before ->
value = ''
after ->
value = null
context 'then pressing enter', ->
expectNoError = ->
expect(view.$field()).to.not.have.class 'error-input'
expect(view.$field()).to.not.have.attr 'contenteditable'
expect(view.$field()).to.not.have.attr 'data-toggle'
expect(view.$field()).to.not.have.attr 'data-original-title'
expect(model.validationError).to.not.exist
it 'should not revert the data', ->
expectNotRevertData.call this
context 'then fixing the error', ->
beforeEach ->
view.$field().text('PI:NAME:<NAME>END_PI').trigger enter
it 'should remove the error class and saves', ->
expect(success).to.have.been.called
expect(error).to.have.been.calledOnce
expectNoError.call this
context 'then canceling edit', ->
beforeEach ->
escape = $.Event 'keydown', keyCode: 27
view.$field().trigger escape
it 'should remove the error class and reverts', ->
expect(view.$field()).to.contain 'PI:NAME:<NAME>END_PI'
expect(success).to.not.have.been.called
expectNoError.call this
context 'then causing blur', ->
before ->
event = $.Event 'blur'
after ->
event = null
it 'should revert the data', ->
expectNotRevertData.call this
context 'and a custom error class', ->
before ->
errorClass = 'my-error'
after ->
errorClass = undefined
context 'then pressing enter', ->
it 'should attache the custom class', ->
expect(view.$field()).to.have.class 'my-error'
context 'and multiple editable views', ->
model2 = null
view2 = null
beforeEach ->
model2 = new ValidateModelMock name: 'PI:NAME:<NAME>END_PI'
view2 = new EditableViewMock model: model2
view2.setupEditable '.edit-name', '.name-field'
view2.$('.edit-name').click()
# Non-DOM fragments don't propagate a blur event on click.
view.$('.name-field').blur()
afterEach ->
view2 = null
model2 = null
# Focus from makeEditable click triggers another blur.
it 'should keep the original and does not focus the second one', ->
# Original is with updated value.
expect(view.$field()).to.have.attr 'contenteditable'
expect(view.$field()).to.have.class 'error-input'
expect(view.$field()).to.have.text ''
# Second view is being edited.
expect(view2.$field()).to.have.attr 'contenteditable'
expect(view2.$field()).to.not.have.class 'error-input'
expect(view2.$field()).to.contain 'PI:NAME:<NAME>END_PI'
describe 'with the same value', ->
before ->
value = 'PI:NAME:<NAME>END_PI'
after ->
value = null
context 'then pressing enter', ->
it 'should do nothing', ->
expect(view.$field()).to.contain 'PI:NAME:<NAME>END_PI'
expect(success).not.to.have.been.called
expect(view.$field()).to.not.have.attr 'contenteditable'
context 'with a numeric value', ->
before ->
value = '1001'
after ->
value = null
context 'then pressing enter', ->
it 'should convert it to a number', ->
expect(view.$field()).to.contain '1001'
expect(success).to.have.been.called
args = success.lastCall.args[0]
expect(args).to.have.property 'value', 1001
context 'editing an email field', ->
beforeEach ->
view.setupEditable '.edit-email', '.email-field'
view.$('.edit-email').click()
view.$('.email-field').text 'PI:EMAIL:<EMAIL>END_PI'
view.$('.email-field').trigger enter
it 'should update the href', ->
expect(view.$ '.email-field').to.have.attr('href')
.and.to.equal 'mailto:PI:EMAIL:<EMAIL>END_PI'
context 'editing a URL field', ->
url = null
beforeEach ->
view.setupEditable '.edit-url', '.url-field'
view.$('.edit-url').click()
view.$('.url-field').text(url or 'http://olivia.com')
view.$('.url-field').trigger enter
it 'should update the href', ->
expect(view.$ '.url-field').to.have.attr('href')
.and.to.equal 'http://olivia.com'
context 'without a protocol', ->
before ->
url = 'olivia.com'
after ->
url = null
it 'should make the href protocol relative', ->
expect(view.$ '.url-field').to.have.attr('href')
.and.to.equal '//olivia.com'
|
[
{
"context": " the specified status and message.\n#\n# Author:\n# roidrage, raventools\n\nmodule.exports = (robot) ->\n baseUr",
"end": 1096,
"score": 0.9997379183769226,
"start": 1088,
"tag": "USERNAME",
"value": "roidrage"
},
{
"context": "fied status and message.\n#\n# Author:\... | src/statuspage.coffee | vend/hubot-statuspage | 1 | # Description:
# Interaction with the StatusPage.io API to open and update incidents, change component status.
#
# Configuration:
# HUBOT_STATUS_PAGE_ID - Required
# HUBOT_STATUS_PAGE_TOKEN - Required
# HUBOT_STATUS_PAGE_TWITTER_ENABLED - Optional: 't' or 'f'
# HUBOT_STATUS_PAGE_SHOW_WORKING - Optional: '1' or nothing
#
# Commands:
# hubot status? - Display an overall status of all components
# hubot status <component>? - Display the status of a single component
# hubot status <component> (degraded performance|partial outage|major outage|operational) - Set the status for a component. You can also use degraded, partial or major as shortcuts.
# hubot status incidents - Show all unresolved incidents
# hubot status open (investigating|identified|monitoring|resolved) <name>: <message> - Create a new incident using the specified name and message, setting it to the desired status (investigating, etc.). The message can be omitted
# hubot status update <status> <message> - Update the latest open incident with the specified status and message.
#
# Author:
# roidrage, raventools
module.exports = (robot) ->
baseUrl = "https://api.statuspage.io/v1/pages/#{process.env.HUBOT_STATUS_PAGE_ID}"
authHeader = Authorization: "OAuth #{process.env.HUBOT_STATUS_PAGE_TOKEN}"
componentStatuses =
degraded: 'degraded performance',
major: 'major outage',
partial: 'partial outage'
if process.env.HUBOT_STATUS_PAGE_TWITTER_ENABLED == 't'
send_twitter_update = 't'
else
send_twitter_update = 'f'
robot.respond /(?:status|statuspage) incidents\??/i, (msg) ->
msg.http("#{baseUrl}/incidents.json").headers(authHeader).get() (err, res, body) ->
response = JSON.parse body
if response.error
msg.send "Error talking to StatusPage.io: #{response.error}"
else
unresolvedIncidents = response.filter (incident) ->
incident.status != "resolved" and incident.status != "postmortem" and incident.status != "completed"
if unresolvedIncidents.length == 0
msg.send "All clear, no unresolved incidents!"
else
msg.send "Unresolved incidents:"
for incident in unresolvedIncidents
do (incident) ->
msg.send "#{incident.name} (Status: #{incident.status}, Created: #{incident.created_at})"
robot.respond /(?:status|statuspage) update (investigating|identified|monitoring|resolved) (.+)/i, (msg) ->
msg.http("#{baseUrl}/incidents.json").headers(authHeader).get() (err, res, body) ->
response = JSON.parse body
if response.error
msg.send "Error talking to StatusPage.io: #{response.error}"
else
unresolvedIncidents = response.filter (incident) ->
!incident.backfilled and incident.status != "resolved" and incident.status != "postmortem" and incident.status != "completed" and incident.status != "scheduled"
if unresolvedIncidents.length == 0
msg.send "Sorry, there are no unresolved incidents."
else
incidentId = unresolvedIncidents[0].id
incident =
status: msg.match[1]
message: msg.match[2]
wants_twitter_update: send_twitter_update
params =
incident: incident
msg.http("#{baseUrl}/incidents/#{incidentId}.json").headers(authHeader).patch(JSON.stringify params) (err, res, body) ->
response = JSON.parse body
if response.error
msg.send "Error updating incident #{unresolvedIncidents[0].name}: #{response.error}"
else
msg.send "Updated incident \"#{unresolvedIncidents[0].name}\""
robot.respond /(?:status|statuspage) open (investigating|identified|monitoring|resolved) ([^:]+)(: ?(.+))?/i, (msg) ->
if msg.match.length == 5
name = msg.match[2]
message = msg.match[4]
else
name = msg.match[2]
incident =
status: msg.match[1]
wants_twitter_update: send_twitter_update
message: message
name: name
params = {incident: incident}
msg.http("#{baseUrl}/incidents.json")
.headers(authHeader)
.post(JSON.stringify params) (err, response, body) ->
response = JSON.parse body
if response.error
msg.send "Error updating incident \"#{name}\": #{response.error}"
else
msg.send "Created incident \"#{name}\""
robot.respond /(?:status|statuspage)\?$/i, (msg) ->
msg.http("#{baseUrl}/components.json")
.headers(authHeader)
.get() (err, res, body) ->
components = JSON.parse body
working_components = components.filter (component) ->
component.status == 'operational'
broken_components = components.filter (component) ->
component.status != 'operational'
if broken_components.length == 0
msg.send "All systems operational!"
else
msg.send "There are currently #{broken_components.length} components in a degraded state"
if broken_components.length > 0
msg.send "\nBroken Components:\n-------------\n"
msg.send ("#{component.name}: #{component.status.replace(/_/g, ' ')}" for component in broken_components).join("\n") + "\n"
if working_components.length > 0 && process.env.HUBOT_STATUS_PAGE_SHOW_WORKING == '1'
msg.send "\nWorking Components:\n-------------\n"
msg.send ("#{component.name}" for component in working_components).join("\n") + "\n"
robot.respond /(?:status|statuspage) ((?!(incidents|open|update|resolve|create))(\S ?)+)\?$/i, (msg) ->
msg.http("#{baseUrl}/components.json")
.headers(authHeader)
.get() (err, res, body) ->
response = JSON.parse body
components = response.filter (component) ->
component.name == msg.match[1]
if components.length == 0
msg.send "Sorry, the component \"#{msg.match[1]}\" doesn't exist. I know of these components: #{(component.name for component in response).join(", ")}."
else
msg.send "Status of #{msg.match[1]}: #{components[0].status.replace(/_/g, " ")}"
robot.respond /(?:status|statuspage) ((\S ?)+) (major( outage)?|degraded( performance)?|partial( outage)?|operational)/i, (msg) ->
componentName = msg.match[1]
status = msg.match[3]
status = componentStatuses[status] || status
msg.http("#{baseUrl}/components.json")
.headers(authHeader)
.get() (err, res, body) ->
response = JSON.parse body
if response.error
msg.send "Error talking to StatusPage.io: #{response.error}"
else
components = response.filter (component) ->
component.name == componentName
if components.length == 0
msg.send "Couldn't find a component named #{componentName}"
else
component = components[0]
requestStatus = status.replace /[ ]/g, "_"
params = {component: {status: requestStatus}}
msg.http("#{baseUrl}/components/#{component.id}.json")
.headers(authHeader)
.patch(JSON.stringify params) (err, res, body) ->
response = JSON.parse body
if response.error
msg.send "Error setting the status for #{component}: #{response.error}"
else
msg.send "Status for #{componentName} is now #{status} (was: #{component.status})"
| 123022 | # Description:
# Interaction with the StatusPage.io API to open and update incidents, change component status.
#
# Configuration:
# HUBOT_STATUS_PAGE_ID - Required
# HUBOT_STATUS_PAGE_TOKEN - Required
# HUBOT_STATUS_PAGE_TWITTER_ENABLED - Optional: 't' or 'f'
# HUBOT_STATUS_PAGE_SHOW_WORKING - Optional: '1' or nothing
#
# Commands:
# hubot status? - Display an overall status of all components
# hubot status <component>? - Display the status of a single component
# hubot status <component> (degraded performance|partial outage|major outage|operational) - Set the status for a component. You can also use degraded, partial or major as shortcuts.
# hubot status incidents - Show all unresolved incidents
# hubot status open (investigating|identified|monitoring|resolved) <name>: <message> - Create a new incident using the specified name and message, setting it to the desired status (investigating, etc.). The message can be omitted
# hubot status update <status> <message> - Update the latest open incident with the specified status and message.
#
# Author:
# roidrage, raventools
module.exports = (robot) ->
baseUrl = "https://api.statuspage.io/v1/pages/#{process.env.HUBOT_STATUS_PAGE_ID}"
authHeader = Authorization: "OAuth #{process.env.HUBOT_STATUS_PAGE_TOKEN}"
componentStatuses =
degraded: 'degraded performance',
major: 'major outage',
partial: 'partial outage'
if process.env.HUBOT_STATUS_PAGE_TWITTER_ENABLED == 't'
send_twitter_update = 't'
else
send_twitter_update = 'f'
robot.respond /(?:status|statuspage) incidents\??/i, (msg) ->
msg.http("#{baseUrl}/incidents.json").headers(authHeader).get() (err, res, body) ->
response = JSON.parse body
if response.error
msg.send "Error talking to StatusPage.io: #{response.error}"
else
unresolvedIncidents = response.filter (incident) ->
incident.status != "resolved" and incident.status != "postmortem" and incident.status != "completed"
if unresolvedIncidents.length == 0
msg.send "All clear, no unresolved incidents!"
else
msg.send "Unresolved incidents:"
for incident in unresolvedIncidents
do (incident) ->
msg.send "#{incident.name} (Status: #{incident.status}, Created: #{incident.created_at})"
robot.respond /(?:status|statuspage) update (investigating|identified|monitoring|resolved) (.+)/i, (msg) ->
msg.http("#{baseUrl}/incidents.json").headers(authHeader).get() (err, res, body) ->
response = JSON.parse body
if response.error
msg.send "Error talking to StatusPage.io: #{response.error}"
else
unresolvedIncidents = response.filter (incident) ->
!incident.backfilled and incident.status != "resolved" and incident.status != "postmortem" and incident.status != "completed" and incident.status != "scheduled"
if unresolvedIncidents.length == 0
msg.send "Sorry, there are no unresolved incidents."
else
incidentId = unresolvedIncidents[0].id
incident =
status: msg.match[1]
message: msg.match[2]
wants_twitter_update: send_twitter_update
params =
incident: incident
msg.http("#{baseUrl}/incidents/#{incidentId}.json").headers(authHeader).patch(JSON.stringify params) (err, res, body) ->
response = JSON.parse body
if response.error
msg.send "Error updating incident #{unresolvedIncidents[0].name}: #{response.error}"
else
msg.send "Updated incident \"#{unresolvedIncidents[0].name}\""
robot.respond /(?:status|statuspage) open (investigating|identified|monitoring|resolved) ([^:]+)(: ?(.+))?/i, (msg) ->
if msg.match.length == 5
name = msg.match[2]
message = msg.match[4]
else
name = msg.match[2]
incident =
status: msg.match[1]
wants_twitter_update: send_twitter_update
message: message
name: <NAME>
params = {incident: incident}
msg.http("#{baseUrl}/incidents.json")
.headers(authHeader)
.post(JSON.stringify params) (err, response, body) ->
response = JSON.parse body
if response.error
msg.send "Error updating incident \"#{name}\": #{response.error}"
else
msg.send "Created incident \"#{name}\""
robot.respond /(?:status|statuspage)\?$/i, (msg) ->
msg.http("#{baseUrl}/components.json")
.headers(authHeader)
.get() (err, res, body) ->
components = JSON.parse body
working_components = components.filter (component) ->
component.status == 'operational'
broken_components = components.filter (component) ->
component.status != 'operational'
if broken_components.length == 0
msg.send "All systems operational!"
else
msg.send "There are currently #{broken_components.length} components in a degraded state"
if broken_components.length > 0
msg.send "\nBroken Components:\n-------------\n"
msg.send ("#{component.name}: #{component.status.replace(/_/g, ' ')}" for component in broken_components).join("\n") + "\n"
if working_components.length > 0 && process.env.HUBOT_STATUS_PAGE_SHOW_WORKING == '1'
msg.send "\nWorking Components:\n-------------\n"
msg.send ("#{component.name}" for component in working_components).join("\n") + "\n"
robot.respond /(?:status|statuspage) ((?!(incidents|open|update|resolve|create))(\S ?)+)\?$/i, (msg) ->
msg.http("#{baseUrl}/components.json")
.headers(authHeader)
.get() (err, res, body) ->
response = JSON.parse body
components = response.filter (component) ->
component.name == msg.match[1]
if components.length == 0
msg.send "Sorry, the component \"#{msg.match[1]}\" doesn't exist. I know of these components: #{(component.name for component in response).join(", ")}."
else
msg.send "Status of #{msg.match[1]}: #{components[0].status.replace(/_/g, " ")}"
robot.respond /(?:status|statuspage) ((\S ?)+) (major( outage)?|degraded( performance)?|partial( outage)?|operational)/i, (msg) ->
componentName = msg.match[1]
status = msg.match[3]
status = componentStatuses[status] || status
msg.http("#{baseUrl}/components.json")
.headers(authHeader)
.get() (err, res, body) ->
response = JSON.parse body
if response.error
msg.send "Error talking to StatusPage.io: #{response.error}"
else
components = response.filter (component) ->
component.name == componentName
if components.length == 0
msg.send "Couldn't find a component named #{componentName}"
else
component = components[0]
requestStatus = status.replace /[ ]/g, "_"
params = {component: {status: requestStatus}}
msg.http("#{baseUrl}/components/#{component.id}.json")
.headers(authHeader)
.patch(JSON.stringify params) (err, res, body) ->
response = JSON.parse body
if response.error
msg.send "Error setting the status for #{component}: #{response.error}"
else
msg.send "Status for #{componentName} is now #{status} (was: #{component.status})"
| true | # Description:
# Interaction with the StatusPage.io API to open and update incidents, change component status.
#
# Configuration:
# HUBOT_STATUS_PAGE_ID - Required
# HUBOT_STATUS_PAGE_TOKEN - Required
# HUBOT_STATUS_PAGE_TWITTER_ENABLED - Optional: 't' or 'f'
# HUBOT_STATUS_PAGE_SHOW_WORKING - Optional: '1' or nothing
#
# Commands:
# hubot status? - Display an overall status of all components
# hubot status <component>? - Display the status of a single component
# hubot status <component> (degraded performance|partial outage|major outage|operational) - Set the status for a component. You can also use degraded, partial or major as shortcuts.
# hubot status incidents - Show all unresolved incidents
# hubot status open (investigating|identified|monitoring|resolved) <name>: <message> - Create a new incident using the specified name and message, setting it to the desired status (investigating, etc.). The message can be omitted
# hubot status update <status> <message> - Update the latest open incident with the specified status and message.
#
# Author:
# roidrage, raventools
module.exports = (robot) ->
baseUrl = "https://api.statuspage.io/v1/pages/#{process.env.HUBOT_STATUS_PAGE_ID}"
authHeader = Authorization: "OAuth #{process.env.HUBOT_STATUS_PAGE_TOKEN}"
componentStatuses =
degraded: 'degraded performance',
major: 'major outage',
partial: 'partial outage'
if process.env.HUBOT_STATUS_PAGE_TWITTER_ENABLED == 't'
send_twitter_update = 't'
else
send_twitter_update = 'f'
robot.respond /(?:status|statuspage) incidents\??/i, (msg) ->
msg.http("#{baseUrl}/incidents.json").headers(authHeader).get() (err, res, body) ->
response = JSON.parse body
if response.error
msg.send "Error talking to StatusPage.io: #{response.error}"
else
unresolvedIncidents = response.filter (incident) ->
incident.status != "resolved" and incident.status != "postmortem" and incident.status != "completed"
if unresolvedIncidents.length == 0
msg.send "All clear, no unresolved incidents!"
else
msg.send "Unresolved incidents:"
for incident in unresolvedIncidents
do (incident) ->
msg.send "#{incident.name} (Status: #{incident.status}, Created: #{incident.created_at})"
robot.respond /(?:status|statuspage) update (investigating|identified|monitoring|resolved) (.+)/i, (msg) ->
msg.http("#{baseUrl}/incidents.json").headers(authHeader).get() (err, res, body) ->
response = JSON.parse body
if response.error
msg.send "Error talking to StatusPage.io: #{response.error}"
else
unresolvedIncidents = response.filter (incident) ->
!incident.backfilled and incident.status != "resolved" and incident.status != "postmortem" and incident.status != "completed" and incident.status != "scheduled"
if unresolvedIncidents.length == 0
msg.send "Sorry, there are no unresolved incidents."
else
incidentId = unresolvedIncidents[0].id
incident =
status: msg.match[1]
message: msg.match[2]
wants_twitter_update: send_twitter_update
params =
incident: incident
msg.http("#{baseUrl}/incidents/#{incidentId}.json").headers(authHeader).patch(JSON.stringify params) (err, res, body) ->
response = JSON.parse body
if response.error
msg.send "Error updating incident #{unresolvedIncidents[0].name}: #{response.error}"
else
msg.send "Updated incident \"#{unresolvedIncidents[0].name}\""
robot.respond /(?:status|statuspage) open (investigating|identified|monitoring|resolved) ([^:]+)(: ?(.+))?/i, (msg) ->
if msg.match.length == 5
name = msg.match[2]
message = msg.match[4]
else
name = msg.match[2]
incident =
status: msg.match[1]
wants_twitter_update: send_twitter_update
message: message
name: PI:NAME:<NAME>END_PI
params = {incident: incident}
msg.http("#{baseUrl}/incidents.json")
.headers(authHeader)
.post(JSON.stringify params) (err, response, body) ->
response = JSON.parse body
if response.error
msg.send "Error updating incident \"#{name}\": #{response.error}"
else
msg.send "Created incident \"#{name}\""
robot.respond /(?:status|statuspage)\?$/i, (msg) ->
msg.http("#{baseUrl}/components.json")
.headers(authHeader)
.get() (err, res, body) ->
components = JSON.parse body
working_components = components.filter (component) ->
component.status == 'operational'
broken_components = components.filter (component) ->
component.status != 'operational'
if broken_components.length == 0
msg.send "All systems operational!"
else
msg.send "There are currently #{broken_components.length} components in a degraded state"
if broken_components.length > 0
msg.send "\nBroken Components:\n-------------\n"
msg.send ("#{component.name}: #{component.status.replace(/_/g, ' ')}" for component in broken_components).join("\n") + "\n"
if working_components.length > 0 && process.env.HUBOT_STATUS_PAGE_SHOW_WORKING == '1'
msg.send "\nWorking Components:\n-------------\n"
msg.send ("#{component.name}" for component in working_components).join("\n") + "\n"
robot.respond /(?:status|statuspage) ((?!(incidents|open|update|resolve|create))(\S ?)+)\?$/i, (msg) ->
msg.http("#{baseUrl}/components.json")
.headers(authHeader)
.get() (err, res, body) ->
response = JSON.parse body
components = response.filter (component) ->
component.name == msg.match[1]
if components.length == 0
msg.send "Sorry, the component \"#{msg.match[1]}\" doesn't exist. I know of these components: #{(component.name for component in response).join(", ")}."
else
msg.send "Status of #{msg.match[1]}: #{components[0].status.replace(/_/g, " ")}"
robot.respond /(?:status|statuspage) ((\S ?)+) (major( outage)?|degraded( performance)?|partial( outage)?|operational)/i, (msg) ->
componentName = msg.match[1]
status = msg.match[3]
status = componentStatuses[status] || status
msg.http("#{baseUrl}/components.json")
.headers(authHeader)
.get() (err, res, body) ->
response = JSON.parse body
if response.error
msg.send "Error talking to StatusPage.io: #{response.error}"
else
components = response.filter (component) ->
component.name == componentName
if components.length == 0
msg.send "Couldn't find a component named #{componentName}"
else
component = components[0]
requestStatus = status.replace /[ ]/g, "_"
params = {component: {status: requestStatus}}
msg.http("#{baseUrl}/components/#{component.id}.json")
.headers(authHeader)
.patch(JSON.stringify params) (err, res, body) ->
response = JSON.parse body
if response.error
msg.send "Error setting the status for #{component}: #{response.error}"
else
msg.send "Status for #{componentName} is now #{status} (was: #{component.status})"
|
[
{
"context": " ->\n @emitter = new Emitter\n @defaultKey = 'Text'\n @scope = 'workspace'\n @todos = []\n\n onDi",
"end": 269,
"score": 0.9328815340995789,
"start": 265,
"tag": "KEY",
"value": "Text"
}
] | lib/todo-collection.coffee | dsandstrom/atom-todo-show | 0 | path = require 'path'
{Emitter} = require 'atom'
TodoModel = require './todo-model'
TodosMarkdown = require './todo-markdown'
TodoRegex = require './todo-regex'
module.exports =
class TodoCollection
constructor: ->
@emitter = new Emitter
@defaultKey = 'Text'
@scope = 'workspace'
@todos = []
onDidAddTodo: (cb) -> @emitter.on 'did-add-todo', cb
onDidRemoveTodo: (cb) -> @emitter.on 'did-remove-todo', cb
onDidClear: (cb) -> @emitter.on 'did-clear-todos', cb
onDidStartSearch: (cb) -> @emitter.on 'did-start-search', cb
onDidSearchPaths: (cb) -> @emitter.on 'did-search-paths', cb
onDidFinishSearch: (cb) -> @emitter.on 'did-finish-search', cb
onDidCancelSearch: (cb) -> @emitter.on 'did-cancel-search', cb
onDidFailSearch: (cb) -> @emitter.on 'did-fail-search', cb
onDidSortTodos: (cb) -> @emitter.on 'did-sort-todos', cb
onDidFilterTodos: (cb) -> @emitter.on 'did-filter-todos', cb
onDidChangeSearchScope: (cb) -> @emitter.on 'did-change-scope', cb
clear: ->
@cancelSearch()
@todos = []
@emitter.emit 'did-clear-todos'
addTodo: (todo) ->
return if @alreadyExists(todo)
@todos.push(todo)
@emitter.emit 'did-add-todo', todo
getTodos: -> @todos
getTodosCount: -> @todos.length
getState: -> @searching
sortTodos: ({sortBy, sortAsc} = {}) ->
sortBy ?= @defaultKey
# Save history of new sort elements
if @searches?[@searches.length - 1].sortBy isnt sortBy
@searches ?= []
@searches.push {sortBy, sortAsc}
else
@searches[@searches.length - 1] = {sortBy, sortAsc}
@todos = @todos.sort((todoA, todoB) =>
@todoSorter(todoA, todoB, sortBy, sortAsc)
)
return @filterTodos(@filter) if @filter
@emitter.emit 'did-sort-todos', @todos
todoSorter: (todoA, todoB, sortBy, sortAsc) ->
[sortBy2, sortAsc2] = [sortBy, sortAsc]
aVal = todoA.get(sortBy2)
bVal = todoB.get(sortBy2)
if aVal is bVal
# Use previous sorts to make a 2-level stable sort
if search = @searches?[@searches.length - 2]
[sortBy2, sortAsc2] = [search.sortBy, search.sortAsc]
else
sortBy2 = @defaultKey
[aVal, bVal] = [todoA.get(sortBy2), todoB.get(sortBy2)]
# Sort type in the defined order, as number or normal string sort
if sortBy2 is 'Type'
findTheseTodos = atom.config.get('todo-show.findTheseTodos')
comp = findTheseTodos.indexOf(aVal) - findTheseTodos.indexOf(bVal)
else if todoA.keyIsNumber(sortBy2)
comp = parseInt(aVal) - parseInt(bVal)
else
comp = aVal.localeCompare(bVal)
if sortAsc2 then comp else -comp
filterTodos: (filter) ->
if @filter = filter
result = @todos.filter (todo) ->
todo.contains(filter)
else
result = @todos
@emitter.emit 'did-filter-todos', result
getAvailableTableItems: -> @availableItems
setAvailableTableItems: (@availableItems) ->
getSearchScope: -> @scope
setSearchScope: (scope) ->
@emitter.emit 'did-change-scope', @scope = scope
toggleSearchScope: ->
scope = switch @scope
when 'workspace' then 'project'
when 'project' then 'open'
when 'open' then 'active'
else 'workspace'
@setSearchScope(scope)
scope
alreadyExists: (newTodo) ->
properties = ['range', 'path']
@todos.some (todo) ->
properties.every (prop) ->
true if todo[prop] is newTodo[prop]
# Scan project workspace for the TodoRegex object
# returns a promise that the scan generates
fetchRegexItem: (todoRegex, activeProjectOnly) ->
options =
paths: @getSearchPaths()
onPathsSearched: (nPaths) =>
@emitter.emit 'did-search-paths', nPaths if @searching
atom.workspace.scan todoRegex.regexp, options, (result, error) =>
console.debug error.message if error
return unless result
return if activeProjectOnly and not @activeProjectHas(result.filePath)
for match in result.matches
@addTodo new TodoModel(
all: match.lineText
text: match.matchText
loc: result.filePath
position: match.range
regex: todoRegex.regex
regexp: todoRegex.regexp
)
# Scan open files for the TodoRegex object
fetchOpenRegexItem: (todoRegex, activeEditorOnly) ->
editors = []
if activeEditorOnly
if editor = atom.workspace.getPanes()[0]?.getActiveEditor()
editors = [editor]
else
editors = atom.workspace.getTextEditors()
for editor in editors
editor.scan todoRegex.regexp, (match, error) =>
console.debug error.message if error
return unless match
range = [
[match.range.start.row, match.range.start.column]
[match.range.end.row, match.range.end.column]
]
@addTodo new TodoModel(
all: match.lineText
text: match.matchText
loc: editor.getPath()
position: range
regex: todoRegex.regex
regexp: todoRegex.regexp
)
# No async operations, so just return a resolved promise
Promise.resolve()
search: ->
@clear()
@searching = true
@emitter.emit 'did-start-search'
todoRegex = new TodoRegex(
atom.config.get('todo-show.findUsingRegex')
atom.config.get('todo-show.findTheseTodos')
)
if todoRegex.error
@emitter.emit 'did-fail-search', "Invalid todo search regex"
return
@searchPromise = switch @scope
when 'open' then @fetchOpenRegexItem(todoRegex, false)
when 'active' then @fetchOpenRegexItem(todoRegex, true)
when 'project' then @fetchRegexItem(todoRegex, true)
else @fetchRegexItem(todoRegex)
@searchPromise.then (result) =>
@searching = false
if result is 'cancelled'
@emitter.emit 'did-cancel-search'
else
@emitter.emit 'did-finish-search'
.catch (reason) =>
@searching = false
@emitter.emit 'did-fail-search', reason
getSearchPaths: ->
ignores = atom.config.get('todo-show.ignoreThesePaths')
return ['*'] unless ignores?
if Object.prototype.toString.call(ignores) isnt '[object Array]'
@emitter.emit 'did-fail-search', "ignoreThesePaths must be an array"
return ['*']
"!#{ignore}" for ignore in ignores
activeProjectHas: (filePath = '') ->
return unless project = @getActiveProject()
filePath.indexOf(project) is 0
getActiveProject: ->
return @activeProject if @activeProject
@activeProject = project if project = @getFallbackProject()
getFallbackProject: ->
for item in atom.workspace.getPaneItems()
if project = @projectForFile(item.getPath?())
return project
project if project = atom.project.getPaths()[0]
getActiveProjectName: ->
return 'no active project' unless project = @getActiveProject()
projectName = path.basename(project)
if projectName is 'undefined' then "no active project" else projectName
setActiveProject: (filePath) ->
lastProject = @activeProject
@activeProject = project if project = @projectForFile(filePath)
return false unless lastProject
lastProject isnt @activeProject
projectForFile: (filePath) ->
return if typeof filePath isnt 'string'
project if project = atom.project.relativizePath(filePath)[0]
getMarkdown: ->
todosMarkdown = new TodosMarkdown
todosMarkdown.markdown @getTodos()
cancelSearch: ->
@searchPromise?.cancel?()
# TODO: Previous searches are not saved yet!
getPreviousSearch: ->
sortBy = localStorage.getItem 'todo-show.previous-sortBy'
setPreviousSearch: (search) ->
localStorage.setItem 'todo-show.previous-search', search
| 28552 | path = require 'path'
{Emitter} = require 'atom'
TodoModel = require './todo-model'
TodosMarkdown = require './todo-markdown'
TodoRegex = require './todo-regex'
module.exports =
class TodoCollection
constructor: ->
@emitter = new Emitter
@defaultKey = '<KEY>'
@scope = 'workspace'
@todos = []
onDidAddTodo: (cb) -> @emitter.on 'did-add-todo', cb
onDidRemoveTodo: (cb) -> @emitter.on 'did-remove-todo', cb
onDidClear: (cb) -> @emitter.on 'did-clear-todos', cb
onDidStartSearch: (cb) -> @emitter.on 'did-start-search', cb
onDidSearchPaths: (cb) -> @emitter.on 'did-search-paths', cb
onDidFinishSearch: (cb) -> @emitter.on 'did-finish-search', cb
onDidCancelSearch: (cb) -> @emitter.on 'did-cancel-search', cb
onDidFailSearch: (cb) -> @emitter.on 'did-fail-search', cb
onDidSortTodos: (cb) -> @emitter.on 'did-sort-todos', cb
onDidFilterTodos: (cb) -> @emitter.on 'did-filter-todos', cb
onDidChangeSearchScope: (cb) -> @emitter.on 'did-change-scope', cb
clear: ->
@cancelSearch()
@todos = []
@emitter.emit 'did-clear-todos'
addTodo: (todo) ->
return if @alreadyExists(todo)
@todos.push(todo)
@emitter.emit 'did-add-todo', todo
getTodos: -> @todos
getTodosCount: -> @todos.length
getState: -> @searching
sortTodos: ({sortBy, sortAsc} = {}) ->
sortBy ?= @defaultKey
# Save history of new sort elements
if @searches?[@searches.length - 1].sortBy isnt sortBy
@searches ?= []
@searches.push {sortBy, sortAsc}
else
@searches[@searches.length - 1] = {sortBy, sortAsc}
@todos = @todos.sort((todoA, todoB) =>
@todoSorter(todoA, todoB, sortBy, sortAsc)
)
return @filterTodos(@filter) if @filter
@emitter.emit 'did-sort-todos', @todos
todoSorter: (todoA, todoB, sortBy, sortAsc) ->
[sortBy2, sortAsc2] = [sortBy, sortAsc]
aVal = todoA.get(sortBy2)
bVal = todoB.get(sortBy2)
if aVal is bVal
# Use previous sorts to make a 2-level stable sort
if search = @searches?[@searches.length - 2]
[sortBy2, sortAsc2] = [search.sortBy, search.sortAsc]
else
sortBy2 = @defaultKey
[aVal, bVal] = [todoA.get(sortBy2), todoB.get(sortBy2)]
# Sort type in the defined order, as number or normal string sort
if sortBy2 is 'Type'
findTheseTodos = atom.config.get('todo-show.findTheseTodos')
comp = findTheseTodos.indexOf(aVal) - findTheseTodos.indexOf(bVal)
else if todoA.keyIsNumber(sortBy2)
comp = parseInt(aVal) - parseInt(bVal)
else
comp = aVal.localeCompare(bVal)
if sortAsc2 then comp else -comp
filterTodos: (filter) ->
if @filter = filter
result = @todos.filter (todo) ->
todo.contains(filter)
else
result = @todos
@emitter.emit 'did-filter-todos', result
getAvailableTableItems: -> @availableItems
setAvailableTableItems: (@availableItems) ->
getSearchScope: -> @scope
setSearchScope: (scope) ->
@emitter.emit 'did-change-scope', @scope = scope
toggleSearchScope: ->
scope = switch @scope
when 'workspace' then 'project'
when 'project' then 'open'
when 'open' then 'active'
else 'workspace'
@setSearchScope(scope)
scope
alreadyExists: (newTodo) ->
properties = ['range', 'path']
@todos.some (todo) ->
properties.every (prop) ->
true if todo[prop] is newTodo[prop]
# Scan project workspace for the TodoRegex object
# returns a promise that the scan generates
fetchRegexItem: (todoRegex, activeProjectOnly) ->
options =
paths: @getSearchPaths()
onPathsSearched: (nPaths) =>
@emitter.emit 'did-search-paths', nPaths if @searching
atom.workspace.scan todoRegex.regexp, options, (result, error) =>
console.debug error.message if error
return unless result
return if activeProjectOnly and not @activeProjectHas(result.filePath)
for match in result.matches
@addTodo new TodoModel(
all: match.lineText
text: match.matchText
loc: result.filePath
position: match.range
regex: todoRegex.regex
regexp: todoRegex.regexp
)
# Scan open files for the TodoRegex object
fetchOpenRegexItem: (todoRegex, activeEditorOnly) ->
editors = []
if activeEditorOnly
if editor = atom.workspace.getPanes()[0]?.getActiveEditor()
editors = [editor]
else
editors = atom.workspace.getTextEditors()
for editor in editors
editor.scan todoRegex.regexp, (match, error) =>
console.debug error.message if error
return unless match
range = [
[match.range.start.row, match.range.start.column]
[match.range.end.row, match.range.end.column]
]
@addTodo new TodoModel(
all: match.lineText
text: match.matchText
loc: editor.getPath()
position: range
regex: todoRegex.regex
regexp: todoRegex.regexp
)
# No async operations, so just return a resolved promise
Promise.resolve()
search: ->
@clear()
@searching = true
@emitter.emit 'did-start-search'
todoRegex = new TodoRegex(
atom.config.get('todo-show.findUsingRegex')
atom.config.get('todo-show.findTheseTodos')
)
if todoRegex.error
@emitter.emit 'did-fail-search', "Invalid todo search regex"
return
@searchPromise = switch @scope
when 'open' then @fetchOpenRegexItem(todoRegex, false)
when 'active' then @fetchOpenRegexItem(todoRegex, true)
when 'project' then @fetchRegexItem(todoRegex, true)
else @fetchRegexItem(todoRegex)
@searchPromise.then (result) =>
@searching = false
if result is 'cancelled'
@emitter.emit 'did-cancel-search'
else
@emitter.emit 'did-finish-search'
.catch (reason) =>
@searching = false
@emitter.emit 'did-fail-search', reason
getSearchPaths: ->
ignores = atom.config.get('todo-show.ignoreThesePaths')
return ['*'] unless ignores?
if Object.prototype.toString.call(ignores) isnt '[object Array]'
@emitter.emit 'did-fail-search', "ignoreThesePaths must be an array"
return ['*']
"!#{ignore}" for ignore in ignores
activeProjectHas: (filePath = '') ->
return unless project = @getActiveProject()
filePath.indexOf(project) is 0
getActiveProject: ->
return @activeProject if @activeProject
@activeProject = project if project = @getFallbackProject()
getFallbackProject: ->
for item in atom.workspace.getPaneItems()
if project = @projectForFile(item.getPath?())
return project
project if project = atom.project.getPaths()[0]
getActiveProjectName: ->
return 'no active project' unless project = @getActiveProject()
projectName = path.basename(project)
if projectName is 'undefined' then "no active project" else projectName
setActiveProject: (filePath) ->
lastProject = @activeProject
@activeProject = project if project = @projectForFile(filePath)
return false unless lastProject
lastProject isnt @activeProject
projectForFile: (filePath) ->
return if typeof filePath isnt 'string'
project if project = atom.project.relativizePath(filePath)[0]
getMarkdown: ->
todosMarkdown = new TodosMarkdown
todosMarkdown.markdown @getTodos()
cancelSearch: ->
@searchPromise?.cancel?()
# TODO: Previous searches are not saved yet!
getPreviousSearch: ->
sortBy = localStorage.getItem 'todo-show.previous-sortBy'
setPreviousSearch: (search) ->
localStorage.setItem 'todo-show.previous-search', search
| true | path = require 'path'
{Emitter} = require 'atom'
TodoModel = require './todo-model'
TodosMarkdown = require './todo-markdown'
TodoRegex = require './todo-regex'
module.exports =
class TodoCollection
constructor: ->
@emitter = new Emitter
@defaultKey = 'PI:KEY:<KEY>END_PI'
@scope = 'workspace'
@todos = []
onDidAddTodo: (cb) -> @emitter.on 'did-add-todo', cb
onDidRemoveTodo: (cb) -> @emitter.on 'did-remove-todo', cb
onDidClear: (cb) -> @emitter.on 'did-clear-todos', cb
onDidStartSearch: (cb) -> @emitter.on 'did-start-search', cb
onDidSearchPaths: (cb) -> @emitter.on 'did-search-paths', cb
onDidFinishSearch: (cb) -> @emitter.on 'did-finish-search', cb
onDidCancelSearch: (cb) -> @emitter.on 'did-cancel-search', cb
onDidFailSearch: (cb) -> @emitter.on 'did-fail-search', cb
onDidSortTodos: (cb) -> @emitter.on 'did-sort-todos', cb
onDidFilterTodos: (cb) -> @emitter.on 'did-filter-todos', cb
onDidChangeSearchScope: (cb) -> @emitter.on 'did-change-scope', cb
clear: ->
@cancelSearch()
@todos = []
@emitter.emit 'did-clear-todos'
addTodo: (todo) ->
return if @alreadyExists(todo)
@todos.push(todo)
@emitter.emit 'did-add-todo', todo
getTodos: -> @todos
getTodosCount: -> @todos.length
getState: -> @searching
sortTodos: ({sortBy, sortAsc} = {}) ->
sortBy ?= @defaultKey
# Save history of new sort elements
if @searches?[@searches.length - 1].sortBy isnt sortBy
@searches ?= []
@searches.push {sortBy, sortAsc}
else
@searches[@searches.length - 1] = {sortBy, sortAsc}
@todos = @todos.sort((todoA, todoB) =>
@todoSorter(todoA, todoB, sortBy, sortAsc)
)
return @filterTodos(@filter) if @filter
@emitter.emit 'did-sort-todos', @todos
todoSorter: (todoA, todoB, sortBy, sortAsc) ->
[sortBy2, sortAsc2] = [sortBy, sortAsc]
aVal = todoA.get(sortBy2)
bVal = todoB.get(sortBy2)
if aVal is bVal
# Use previous sorts to make a 2-level stable sort
if search = @searches?[@searches.length - 2]
[sortBy2, sortAsc2] = [search.sortBy, search.sortAsc]
else
sortBy2 = @defaultKey
[aVal, bVal] = [todoA.get(sortBy2), todoB.get(sortBy2)]
# Sort type in the defined order, as number or normal string sort
if sortBy2 is 'Type'
findTheseTodos = atom.config.get('todo-show.findTheseTodos')
comp = findTheseTodos.indexOf(aVal) - findTheseTodos.indexOf(bVal)
else if todoA.keyIsNumber(sortBy2)
comp = parseInt(aVal) - parseInt(bVal)
else
comp = aVal.localeCompare(bVal)
if sortAsc2 then comp else -comp
filterTodos: (filter) ->
if @filter = filter
result = @todos.filter (todo) ->
todo.contains(filter)
else
result = @todos
@emitter.emit 'did-filter-todos', result
getAvailableTableItems: -> @availableItems
setAvailableTableItems: (@availableItems) ->
getSearchScope: -> @scope
setSearchScope: (scope) ->
@emitter.emit 'did-change-scope', @scope = scope
toggleSearchScope: ->
scope = switch @scope
when 'workspace' then 'project'
when 'project' then 'open'
when 'open' then 'active'
else 'workspace'
@setSearchScope(scope)
scope
alreadyExists: (newTodo) ->
properties = ['range', 'path']
@todos.some (todo) ->
properties.every (prop) ->
true if todo[prop] is newTodo[prop]
# Scan project workspace for the TodoRegex object
# returns a promise that the scan generates
fetchRegexItem: (todoRegex, activeProjectOnly) ->
options =
paths: @getSearchPaths()
onPathsSearched: (nPaths) =>
@emitter.emit 'did-search-paths', nPaths if @searching
atom.workspace.scan todoRegex.regexp, options, (result, error) =>
console.debug error.message if error
return unless result
return if activeProjectOnly and not @activeProjectHas(result.filePath)
for match in result.matches
@addTodo new TodoModel(
all: match.lineText
text: match.matchText
loc: result.filePath
position: match.range
regex: todoRegex.regex
regexp: todoRegex.regexp
)
# Scan open files for the TodoRegex object
fetchOpenRegexItem: (todoRegex, activeEditorOnly) ->
editors = []
if activeEditorOnly
if editor = atom.workspace.getPanes()[0]?.getActiveEditor()
editors = [editor]
else
editors = atom.workspace.getTextEditors()
for editor in editors
editor.scan todoRegex.regexp, (match, error) =>
console.debug error.message if error
return unless match
range = [
[match.range.start.row, match.range.start.column]
[match.range.end.row, match.range.end.column]
]
@addTodo new TodoModel(
all: match.lineText
text: match.matchText
loc: editor.getPath()
position: range
regex: todoRegex.regex
regexp: todoRegex.regexp
)
# No async operations, so just return a resolved promise
Promise.resolve()
search: ->
@clear()
@searching = true
@emitter.emit 'did-start-search'
todoRegex = new TodoRegex(
atom.config.get('todo-show.findUsingRegex')
atom.config.get('todo-show.findTheseTodos')
)
if todoRegex.error
@emitter.emit 'did-fail-search', "Invalid todo search regex"
return
@searchPromise = switch @scope
when 'open' then @fetchOpenRegexItem(todoRegex, false)
when 'active' then @fetchOpenRegexItem(todoRegex, true)
when 'project' then @fetchRegexItem(todoRegex, true)
else @fetchRegexItem(todoRegex)
@searchPromise.then (result) =>
@searching = false
if result is 'cancelled'
@emitter.emit 'did-cancel-search'
else
@emitter.emit 'did-finish-search'
.catch (reason) =>
@searching = false
@emitter.emit 'did-fail-search', reason
getSearchPaths: ->
ignores = atom.config.get('todo-show.ignoreThesePaths')
return ['*'] unless ignores?
if Object.prototype.toString.call(ignores) isnt '[object Array]'
@emitter.emit 'did-fail-search', "ignoreThesePaths must be an array"
return ['*']
"!#{ignore}" for ignore in ignores
activeProjectHas: (filePath = '') ->
return unless project = @getActiveProject()
filePath.indexOf(project) is 0
getActiveProject: ->
return @activeProject if @activeProject
@activeProject = project if project = @getFallbackProject()
getFallbackProject: ->
for item in atom.workspace.getPaneItems()
if project = @projectForFile(item.getPath?())
return project
project if project = atom.project.getPaths()[0]
getActiveProjectName: ->
return 'no active project' unless project = @getActiveProject()
projectName = path.basename(project)
if projectName is 'undefined' then "no active project" else projectName
setActiveProject: (filePath) ->
lastProject = @activeProject
@activeProject = project if project = @projectForFile(filePath)
return false unless lastProject
lastProject isnt @activeProject
projectForFile: (filePath) ->
return if typeof filePath isnt 'string'
project if project = atom.project.relativizePath(filePath)[0]
getMarkdown: ->
todosMarkdown = new TodosMarkdown
todosMarkdown.markdown @getTodos()
cancelSearch: ->
@searchPromise?.cancel?()
# TODO: Previous searches are not saved yet!
getPreviousSearch: ->
sortBy = localStorage.getItem 'todo-show.previous-sortBy'
setPreviousSearch: (search) ->
localStorage.setItem 'todo-show.previous-search', search
|
[
{
"context": "---------------------------------------\nauthor: [Takeharu Oshida](http://about.me/takeharu.oshida)\nversion: 0.1\nli",
"end": 97,
"score": 0.9998948574066162,
"start": 82,
"tag": "NAME",
"value": "Takeharu Oshida"
},
{
"context": "------\nauthor: [Takeharu Oshida](ht... | src/coffee/client/slideBaseClient.coffee | georgeOsdDev/SlideBase | 0 | ###
SlideBaseClient.js
------------------------------------------------
author: [Takeharu Oshida](http://about.me/takeharu.oshida)
version: 0.1
licence: [MIT](http://opensource.org/licenses/mit-license.php)
###
console.log "This is Client Side Script"
#*****************************
# Namespace
#*****************************
window.sbClient =
admin:false
lock:false
page:
current:0
last:null
Model:{}
Collection:{}
View:{}
Instances:{}
option:
animation:''
theme:'default'
plugins:{}
pushMethods:
'move':true
isDisplayHelp:false
userList:{}
init: (opts={}) ->
# set option
_.each opts, (val,key)->
sbClient.option[key] = val
# create slideBase
wrap = document.createElement 'div'
wrap.id = 'wrap'
wrap.display = 'none'
ctl = document.createElement 'div'
ctl.id = 'ctl'
$(ctl)
.addClass('ctl')
.append "<button class='btn' id='back'>←</button><button class='btn' id='next'>→</button>"
help = document.createElement('div')
help.id = 'help'
$(help)
.addClass('help hide')
.append("<h4 id='usage'><span id='close'>✖</span> Usage</h4>")
$('body')
.append(wrap)
.append(ctl)
.append(help)
$('#close').bind 'click', ->
$('#help').addClass('hide')
sbClient.isDisplayHelp = false
@Instances.slideView = new sbClient.View.Slide()
# @Instances.pluginView = new sbClient.View.Plugin()
#*****************************
# Client Methods
#*****************************
resizeSlide: ->
$('.slide').each ->
$(@).css
'height': $(window).height() - 72
'width': $(window).width() - 72
execEmit:(name,data) ->
console.log "execEmit "+name
obj =
name:'plugin'
plugin:
name:name
data:data
$('body').trigger 'execEmit', obj
isEnableServerPush:(method) ->
@pushMethods[method]
isEnablePlugin:(obj) ->
if not obj.plugin or not obj.plugin.name then return false
@isEnableServerPush obj.plugin.name
move:(obj) ->
if @isEnableServerPush 'move'
@Instances.slideView.trigger 'execMove',obj.data
setUserList:(userList) ->
@userList = userList
nextSlide:(slide) ->
tmp = document.createElement 'div'
tmp.id = "slide_#{slide.get 'page'}"
$(tmp)
.addClass(slide.get('class'))
.addClass('slide current')
.append(slide.get('elements'))
simpleMove:(slide) ->
next = @nextSlide(slide)
$('#wrap')
.empty()
.removeClass()
.append(next)
@resizeSlide()
@lock = false
fadeMove:(slide) ->
next = @nextSlide(slide)
$('#wrap').fadeOut 250,->
$('#wrap')
.empty()
.removeClass()
.append(next)
sbClient.resizeSlide()
$('#wrap').fadeIn 500, ->
@lock = false
positionMove:(x,y,z,direction,nextpage) ->
if direction < 0 then direction +=1
$('#wrap > .slide').each (i,e) ->
# initposi
xx = (x * (i - nextpage))
yy = (y * (i - nextpage))
zz = (z * (i - nextpage))
css = "transform":"translate3d(#{xx}px,#{yy}px,#{zz}px)"
$(e).css css
horizontalMove:(direction,nextpage) ->
@positionMove $(window).width(), 0, 0, direction, nextpage
@lock = false
verticalMove:(direction,nextpage) ->
@positionMove 0, $(window).height(), 0, direction, nextpage
@lock = false
#*****************************
# Presentation Backbone
#*****************************
# Model:slide page
sbClient.Model.Slide = Backbone.Model.extend
elements:''
class:''
page:''
# Collection:all slide pages
sbClient.Collection.Slides = Backbone.Collection.extend
model: sbClient.Model.Slide
fetch: ->
self = @
_($('section')).each (section,index) ->
slide = new sbClient.Model.Slide
elements:$(section).contents()
class:$(section).attr('class')
page:index
self.add slide
$(section).remove()
sbClient.page.last = self.length
self.trigger 'ready'
# View: SlideView render per slide
sbClient.View.Slide = Backbone.View.extend
el:$('body')
initialize: ->
self = @
self.collection = new sbClient.Collection.Slides()
_.bindAll @, 'render','dispHelp','moveSlide','handleKey'
# Bind key event
self.$el.bind 'keydown', self.handleKey
# Bind swipe event
self.$el.bind 'swipeleft', self.moveSlide 1
self.$el.bind 'swiperight', self.moveSlide -1
# Bind click event
$('#next').bind 'click', ->
self.moveSlide 1
$('#back').bind 'click', ->
self.moveSlide -1
# Bind server push
self.on 'execMove',(event) ->
args = Array.prototype.slice.apply arguments
data = args[0]
if data.currentPage is sbClient.page.current then self.moveSlide data.direction
self.collection.on 'ready',->
self.render()
self.collection.fetch()
render: ->
self = @
append = (className,page,css) ->
slide = (self.collection.where page:page)[0]
id = slide.get 'page'
tmp = document.createElement 'div'
tmp.id = "slide_#{id}"
$(tmp)
.addClass(className)
.addClass(slide.get('class'))
.append(slide.get('elements'))
if css then $(tmp).css css
sbClient.resizeSlide()
$("#wrap").append $(tmp)
appendAll = (x,y,z) ->
self.collection.each (slide, i) ->
css =
"transform":"translate3d(#{x*i}px,#{y*i}px,#{z*i}px)"
if i is 0
append "slide current transform", 0, css
location.hash = i
else
append "slide transform", i, css
switch sbClient.option.animation
when 'horizontal'
appendAll $(window).width(), 0, 0
break
when 'vertical'
appendAll 0, $(window).height(), 0
break
when 'fade'
append 'slide current',0
break
else
# TODO
# Enable aditional animation with plugin
append 'slide current',0
sbClient.lock = false
handleKey: (event) ->
code = event.keyCode || event.which
ctrl = event.ctrlKey
alt = event.altKey
shift = event.shiftKey
cmd = event.metaKey
if (code is 32) or (code is 39) # space or arrow-right
if sbClient.isDisplayHelp then return
event.preventDefault
@moveSlide 1
if (code is 8) or (code is 37) # delete or arrow-left
if sbClient.isDisplayHelp then return
event.preventDefault
@moveSlide(-1)
if (ctrl or cmd) and shift and code is 191
event.preventDefault
@dispHelp()
moveSlide: (direction) ->
self = @
if sbClient.lock then return
nextpage = sbClient.page.current+direction
next = self.collection.at nextpage
if next
obj =
name:'move'
data:
direction:direction
currentPage:sbClient.page.current
$('body').trigger 'execEmit', obj
sbClient.lock = true
switch sbClient.option.animation
when 'horizontal'
sbClient.horizontalMove direction,nextpage
break
when 'vertical'
sbClient.verticalMove direction,nextpage
break
when 'fade'
sbClient.fadeMove next
break
else
# TODO
# Enable aditional animation with plugin
sbClient.simpleMove next
sbClient.page.current = nextpage
location.hash = sbClient.page.current
sbClient.lock = false
dispHelp: ->
console.log "Help!"
if sbClient.isDisplayHelp
$('#help').removeClass('disp')
.addClass('hide')
sbClient.isDisplayHelp = false
else
$('#help').removeClass('hide')
.addClass('disp')
sbClient.isDisplayHelp = true
#*****************************
# Plugins setting Backbone
#*****************************
# Model:slide Plugin
sbClient.Model.Plugin = Backbone.Model.extend
defaults:
id: ''
name: ''
callback: ''
element: ''
initialScript: ->
initialize:->
self = @
$ ->
name = self.get 'name'
sbClient.plugins[name] = self
sbClient.pushMethods[name] = true
$('#help').append self.get('element')
script = self.get('initialScript') || {}
script()
# # Collection:all plugins
# sbClient.Collection.Plugins = Backbone.Collection.extend
# model: sbClient.Model.Slide
# # View: plugins
# sbClient.View.Plugin = Backbone.View.extend
# el: $('#help')
# initialize: ->
# self = @
# self.collection = new sbClient.Collection.Plugins()
# _.bindAll @, 'render'
# self.collection.on 'add',(plugin) ->
# self.render plugin
# render: (plugin)->
# $('#help').append plugin.get 'element'
# script = plugin.get('initialScript') || {}
# script()
#*****************************
# socket.IO setting
#*****************************
socket = io?.connect "http://#{location.host}"
socket?.on 'error', (reason) ->
console.error 'Unable to connect Socket.IO', reason
socket?.on 'connect', ->
console.log 'client connected'
# Message From Clients to Server
$('body').on 'execEmit', (event,obj) ->
socket.emit obj.name, obj
# Message From Server to Clients
socket.on 'users', (userList) ->
sbClient.setUserList userList
socket.on 'move', (obj) ->
sbClient.move obj
socket.on 'plugin', (obj) ->
if sbClient.isEnablePlugin obj
func = sbClient.plugins[obj.plugin.name].get("callback") || {}
func(obj.data)
socket.on 'disconnect', ->
# disable event
$('body').off 'execEmit'
console.log 'disconnected Bye!'
#*****************************
# DOM ready
#*****************************
$ ->
sbClient.resizeSlide()
$(window).bind 'resize',->
sbClient.resizeSlide()
$('a').bind 'click', (e) ->
e.stopPropagation()
e.preventDefault()
window.open @href, '_blank'
| 119825 | ###
SlideBaseClient.js
------------------------------------------------
author: [<NAME>](http://about.me/takeharu.oshida)
version: 0.1
licence: [MIT](http://opensource.org/licenses/mit-license.php)
###
console.log "This is Client Side Script"
#*****************************
# Namespace
#*****************************
window.sbClient =
admin:false
lock:false
page:
current:0
last:null
Model:{}
Collection:{}
View:{}
Instances:{}
option:
animation:''
theme:'default'
plugins:{}
pushMethods:
'move':true
isDisplayHelp:false
userList:{}
init: (opts={}) ->
# set option
_.each opts, (val,key)->
sbClient.option[key] = val
# create slideBase
wrap = document.createElement 'div'
wrap.id = 'wrap'
wrap.display = 'none'
ctl = document.createElement 'div'
ctl.id = 'ctl'
$(ctl)
.addClass('ctl')
.append "<button class='btn' id='back'>←</button><button class='btn' id='next'>→</button>"
help = document.createElement('div')
help.id = 'help'
$(help)
.addClass('help hide')
.append("<h4 id='usage'><span id='close'>✖</span> Usage</h4>")
$('body')
.append(wrap)
.append(ctl)
.append(help)
$('#close').bind 'click', ->
$('#help').addClass('hide')
sbClient.isDisplayHelp = false
@Instances.slideView = new sbClient.View.Slide()
# @Instances.pluginView = new sbClient.View.Plugin()
#*****************************
# Client Methods
#*****************************
resizeSlide: ->
$('.slide').each ->
$(@).css
'height': $(window).height() - 72
'width': $(window).width() - 72
execEmit:(name,data) ->
console.log "execEmit "+name
obj =
name:'plugin'
plugin:
name:name
data:data
$('body').trigger 'execEmit', obj
isEnableServerPush:(method) ->
@pushMethods[method]
isEnablePlugin:(obj) ->
if not obj.plugin or not obj.plugin.name then return false
@isEnableServerPush obj.plugin.name
move:(obj) ->
if @isEnableServerPush 'move'
@Instances.slideView.trigger 'execMove',obj.data
setUserList:(userList) ->
@userList = userList
nextSlide:(slide) ->
tmp = document.createElement 'div'
tmp.id = "slide_#{slide.get 'page'}"
$(tmp)
.addClass(slide.get('class'))
.addClass('slide current')
.append(slide.get('elements'))
simpleMove:(slide) ->
next = @nextSlide(slide)
$('#wrap')
.empty()
.removeClass()
.append(next)
@resizeSlide()
@lock = false
fadeMove:(slide) ->
next = @nextSlide(slide)
$('#wrap').fadeOut 250,->
$('#wrap')
.empty()
.removeClass()
.append(next)
sbClient.resizeSlide()
$('#wrap').fadeIn 500, ->
@lock = false
positionMove:(x,y,z,direction,nextpage) ->
if direction < 0 then direction +=1
$('#wrap > .slide').each (i,e) ->
# initposi
xx = (x * (i - nextpage))
yy = (y * (i - nextpage))
zz = (z * (i - nextpage))
css = "transform":"translate3d(#{xx}px,#{yy}px,#{zz}px)"
$(e).css css
horizontalMove:(direction,nextpage) ->
@positionMove $(window).width(), 0, 0, direction, nextpage
@lock = false
verticalMove:(direction,nextpage) ->
@positionMove 0, $(window).height(), 0, direction, nextpage
@lock = false
#*****************************
# Presentation Backbone
#*****************************
# Model:slide page
sbClient.Model.Slide = Backbone.Model.extend
elements:''
class:''
page:''
# Collection:all slide pages
sbClient.Collection.Slides = Backbone.Collection.extend
model: sbClient.Model.Slide
fetch: ->
self = @
_($('section')).each (section,index) ->
slide = new sbClient.Model.Slide
elements:$(section).contents()
class:$(section).attr('class')
page:index
self.add slide
$(section).remove()
sbClient.page.last = self.length
self.trigger 'ready'
# View: SlideView render per slide
sbClient.View.Slide = Backbone.View.extend
el:$('body')
initialize: ->
self = @
self.collection = new sbClient.Collection.Slides()
_.bindAll @, 'render','dispHelp','moveSlide','handleKey'
# Bind key event
self.$el.bind 'keydown', self.handleKey
# Bind swipe event
self.$el.bind 'swipeleft', self.moveSlide 1
self.$el.bind 'swiperight', self.moveSlide -1
# Bind click event
$('#next').bind 'click', ->
self.moveSlide 1
$('#back').bind 'click', ->
self.moveSlide -1
# Bind server push
self.on 'execMove',(event) ->
args = Array.prototype.slice.apply arguments
data = args[0]
if data.currentPage is sbClient.page.current then self.moveSlide data.direction
self.collection.on 'ready',->
self.render()
self.collection.fetch()
render: ->
self = @
append = (className,page,css) ->
slide = (self.collection.where page:page)[0]
id = slide.get 'page'
tmp = document.createElement 'div'
tmp.id = "slide_#{id}"
$(tmp)
.addClass(className)
.addClass(slide.get('class'))
.append(slide.get('elements'))
if css then $(tmp).css css
sbClient.resizeSlide()
$("#wrap").append $(tmp)
appendAll = (x,y,z) ->
self.collection.each (slide, i) ->
css =
"transform":"translate3d(#{x*i}px,#{y*i}px,#{z*i}px)"
if i is 0
append "slide current transform", 0, css
location.hash = i
else
append "slide transform", i, css
switch sbClient.option.animation
when 'horizontal'
appendAll $(window).width(), 0, 0
break
when 'vertical'
appendAll 0, $(window).height(), 0
break
when 'fade'
append 'slide current',0
break
else
# TODO
# Enable aditional animation with plugin
append 'slide current',0
sbClient.lock = false
handleKey: (event) ->
code = event.keyCode || event.which
ctrl = event.ctrlKey
alt = event.altKey
shift = event.shiftKey
cmd = event.metaKey
if (code is 32) or (code is 39) # space or arrow-right
if sbClient.isDisplayHelp then return
event.preventDefault
@moveSlide 1
if (code is 8) or (code is 37) # delete or arrow-left
if sbClient.isDisplayHelp then return
event.preventDefault
@moveSlide(-1)
if (ctrl or cmd) and shift and code is 191
event.preventDefault
@dispHelp()
moveSlide: (direction) ->
self = @
if sbClient.lock then return
nextpage = sbClient.page.current+direction
next = self.collection.at nextpage
if next
obj =
name:'move'
data:
direction:direction
currentPage:sbClient.page.current
$('body').trigger 'execEmit', obj
sbClient.lock = true
switch sbClient.option.animation
when 'horizontal'
sbClient.horizontalMove direction,nextpage
break
when 'vertical'
sbClient.verticalMove direction,nextpage
break
when 'fade'
sbClient.fadeMove next
break
else
# TODO
# Enable aditional animation with plugin
sbClient.simpleMove next
sbClient.page.current = nextpage
location.hash = sbClient.page.current
sbClient.lock = false
dispHelp: ->
console.log "Help!"
if sbClient.isDisplayHelp
$('#help').removeClass('disp')
.addClass('hide')
sbClient.isDisplayHelp = false
else
$('#help').removeClass('hide')
.addClass('disp')
sbClient.isDisplayHelp = true
#*****************************
# Plugins setting Backbone
#*****************************
# Model:slide Plugin
sbClient.Model.Plugin = Backbone.Model.extend
defaults:
id: ''
name: ''
callback: ''
element: ''
initialScript: ->
initialize:->
self = @
$ ->
name = self.get 'name'
sbClient.plugins[name] = self
sbClient.pushMethods[name] = true
$('#help').append self.get('element')
script = self.get('initialScript') || {}
script()
# # Collection:all plugins
# sbClient.Collection.Plugins = Backbone.Collection.extend
# model: sbClient.Model.Slide
# # View: plugins
# sbClient.View.Plugin = Backbone.View.extend
# el: $('#help')
# initialize: ->
# self = @
# self.collection = new sbClient.Collection.Plugins()
# _.bindAll @, 'render'
# self.collection.on 'add',(plugin) ->
# self.render plugin
# render: (plugin)->
# $('#help').append plugin.get 'element'
# script = plugin.get('initialScript') || {}
# script()
#*****************************
# socket.IO setting
#*****************************
socket = io?.connect "http://#{location.host}"
socket?.on 'error', (reason) ->
console.error 'Unable to connect Socket.IO', reason
socket?.on 'connect', ->
console.log 'client connected'
# Message From Clients to Server
$('body').on 'execEmit', (event,obj) ->
socket.emit obj.name, obj
# Message From Server to Clients
socket.on 'users', (userList) ->
sbClient.setUserList userList
socket.on 'move', (obj) ->
sbClient.move obj
socket.on 'plugin', (obj) ->
if sbClient.isEnablePlugin obj
func = sbClient.plugins[obj.plugin.name].get("callback") || {}
func(obj.data)
socket.on 'disconnect', ->
# disable event
$('body').off 'execEmit'
console.log 'disconnected Bye!'
#*****************************
# DOM ready
#*****************************
$ ->
sbClient.resizeSlide()
$(window).bind 'resize',->
sbClient.resizeSlide()
$('a').bind 'click', (e) ->
e.stopPropagation()
e.preventDefault()
window.open @href, '_blank'
| true | ###
SlideBaseClient.js
------------------------------------------------
author: [PI:NAME:<NAME>END_PI](http://about.me/takeharu.oshida)
version: 0.1
licence: [MIT](http://opensource.org/licenses/mit-license.php)
###
console.log "This is Client Side Script"
#*****************************
# Namespace
#*****************************
window.sbClient =
admin:false
lock:false
page:
current:0
last:null
Model:{}
Collection:{}
View:{}
Instances:{}
option:
animation:''
theme:'default'
plugins:{}
pushMethods:
'move':true
isDisplayHelp:false
userList:{}
init: (opts={}) ->
# set option
_.each opts, (val,key)->
sbClient.option[key] = val
# create slideBase
wrap = document.createElement 'div'
wrap.id = 'wrap'
wrap.display = 'none'
ctl = document.createElement 'div'
ctl.id = 'ctl'
$(ctl)
.addClass('ctl')
.append "<button class='btn' id='back'>←</button><button class='btn' id='next'>→</button>"
help = document.createElement('div')
help.id = 'help'
$(help)
.addClass('help hide')
.append("<h4 id='usage'><span id='close'>✖</span> Usage</h4>")
$('body')
.append(wrap)
.append(ctl)
.append(help)
$('#close').bind 'click', ->
$('#help').addClass('hide')
sbClient.isDisplayHelp = false
@Instances.slideView = new sbClient.View.Slide()
# @Instances.pluginView = new sbClient.View.Plugin()
#*****************************
# Client Methods
#*****************************
resizeSlide: ->
$('.slide').each ->
$(@).css
'height': $(window).height() - 72
'width': $(window).width() - 72
execEmit:(name,data) ->
console.log "execEmit "+name
obj =
name:'plugin'
plugin:
name:name
data:data
$('body').trigger 'execEmit', obj
isEnableServerPush:(method) ->
@pushMethods[method]
isEnablePlugin:(obj) ->
if not obj.plugin or not obj.plugin.name then return false
@isEnableServerPush obj.plugin.name
move:(obj) ->
if @isEnableServerPush 'move'
@Instances.slideView.trigger 'execMove',obj.data
setUserList:(userList) ->
@userList = userList
nextSlide:(slide) ->
tmp = document.createElement 'div'
tmp.id = "slide_#{slide.get 'page'}"
$(tmp)
.addClass(slide.get('class'))
.addClass('slide current')
.append(slide.get('elements'))
simpleMove:(slide) ->
next = @nextSlide(slide)
$('#wrap')
.empty()
.removeClass()
.append(next)
@resizeSlide()
@lock = false
fadeMove:(slide) ->
next = @nextSlide(slide)
$('#wrap').fadeOut 250,->
$('#wrap')
.empty()
.removeClass()
.append(next)
sbClient.resizeSlide()
$('#wrap').fadeIn 500, ->
@lock = false
positionMove:(x,y,z,direction,nextpage) ->
if direction < 0 then direction +=1
$('#wrap > .slide').each (i,e) ->
# initposi
xx = (x * (i - nextpage))
yy = (y * (i - nextpage))
zz = (z * (i - nextpage))
css = "transform":"translate3d(#{xx}px,#{yy}px,#{zz}px)"
$(e).css css
horizontalMove:(direction,nextpage) ->
@positionMove $(window).width(), 0, 0, direction, nextpage
@lock = false
verticalMove:(direction,nextpage) ->
@positionMove 0, $(window).height(), 0, direction, nextpage
@lock = false
#*****************************
# Presentation Backbone
#*****************************
# Model:slide page
sbClient.Model.Slide = Backbone.Model.extend
elements:''
class:''
page:''
# Collection:all slide pages
sbClient.Collection.Slides = Backbone.Collection.extend
model: sbClient.Model.Slide
fetch: ->
self = @
_($('section')).each (section,index) ->
slide = new sbClient.Model.Slide
elements:$(section).contents()
class:$(section).attr('class')
page:index
self.add slide
$(section).remove()
sbClient.page.last = self.length
self.trigger 'ready'
# View: SlideView render per slide
sbClient.View.Slide = Backbone.View.extend
el:$('body')
initialize: ->
self = @
self.collection = new sbClient.Collection.Slides()
_.bindAll @, 'render','dispHelp','moveSlide','handleKey'
# Bind key event
self.$el.bind 'keydown', self.handleKey
# Bind swipe event
self.$el.bind 'swipeleft', self.moveSlide 1
self.$el.bind 'swiperight', self.moveSlide -1
# Bind click event
$('#next').bind 'click', ->
self.moveSlide 1
$('#back').bind 'click', ->
self.moveSlide -1
# Bind server push
self.on 'execMove',(event) ->
args = Array.prototype.slice.apply arguments
data = args[0]
if data.currentPage is sbClient.page.current then self.moveSlide data.direction
self.collection.on 'ready',->
self.render()
self.collection.fetch()
render: ->
self = @
append = (className,page,css) ->
slide = (self.collection.where page:page)[0]
id = slide.get 'page'
tmp = document.createElement 'div'
tmp.id = "slide_#{id}"
$(tmp)
.addClass(className)
.addClass(slide.get('class'))
.append(slide.get('elements'))
if css then $(tmp).css css
sbClient.resizeSlide()
$("#wrap").append $(tmp)
appendAll = (x,y,z) ->
self.collection.each (slide, i) ->
css =
"transform":"translate3d(#{x*i}px,#{y*i}px,#{z*i}px)"
if i is 0
append "slide current transform", 0, css
location.hash = i
else
append "slide transform", i, css
switch sbClient.option.animation
when 'horizontal'
appendAll $(window).width(), 0, 0
break
when 'vertical'
appendAll 0, $(window).height(), 0
break
when 'fade'
append 'slide current',0
break
else
# TODO
# Enable aditional animation with plugin
append 'slide current',0
sbClient.lock = false
handleKey: (event) ->
code = event.keyCode || event.which
ctrl = event.ctrlKey
alt = event.altKey
shift = event.shiftKey
cmd = event.metaKey
if (code is 32) or (code is 39) # space or arrow-right
if sbClient.isDisplayHelp then return
event.preventDefault
@moveSlide 1
if (code is 8) or (code is 37) # delete or arrow-left
if sbClient.isDisplayHelp then return
event.preventDefault
@moveSlide(-1)
if (ctrl or cmd) and shift and code is 191
event.preventDefault
@dispHelp()
moveSlide: (direction) ->
self = @
if sbClient.lock then return
nextpage = sbClient.page.current+direction
next = self.collection.at nextpage
if next
obj =
name:'move'
data:
direction:direction
currentPage:sbClient.page.current
$('body').trigger 'execEmit', obj
sbClient.lock = true
switch sbClient.option.animation
when 'horizontal'
sbClient.horizontalMove direction,nextpage
break
when 'vertical'
sbClient.verticalMove direction,nextpage
break
when 'fade'
sbClient.fadeMove next
break
else
# TODO
# Enable aditional animation with plugin
sbClient.simpleMove next
sbClient.page.current = nextpage
location.hash = sbClient.page.current
sbClient.lock = false
dispHelp: ->
console.log "Help!"
if sbClient.isDisplayHelp
$('#help').removeClass('disp')
.addClass('hide')
sbClient.isDisplayHelp = false
else
$('#help').removeClass('hide')
.addClass('disp')
sbClient.isDisplayHelp = true
#*****************************
# Plugins setting Backbone
#*****************************
# Model:slide Plugin
sbClient.Model.Plugin = Backbone.Model.extend
defaults:
id: ''
name: ''
callback: ''
element: ''
initialScript: ->
initialize:->
self = @
$ ->
name = self.get 'name'
sbClient.plugins[name] = self
sbClient.pushMethods[name] = true
$('#help').append self.get('element')
script = self.get('initialScript') || {}
script()
# # Collection:all plugins
# sbClient.Collection.Plugins = Backbone.Collection.extend
# model: sbClient.Model.Slide
# # View: plugins
# sbClient.View.Plugin = Backbone.View.extend
# el: $('#help')
# initialize: ->
# self = @
# self.collection = new sbClient.Collection.Plugins()
# _.bindAll @, 'render'
# self.collection.on 'add',(plugin) ->
# self.render plugin
# render: (plugin)->
# $('#help').append plugin.get 'element'
# script = plugin.get('initialScript') || {}
# script()
#*****************************
# socket.IO setting
#*****************************
socket = io?.connect "http://#{location.host}"
socket?.on 'error', (reason) ->
console.error 'Unable to connect Socket.IO', reason
socket?.on 'connect', ->
console.log 'client connected'
# Message From Clients to Server
$('body').on 'execEmit', (event,obj) ->
socket.emit obj.name, obj
# Message From Server to Clients
socket.on 'users', (userList) ->
sbClient.setUserList userList
socket.on 'move', (obj) ->
sbClient.move obj
socket.on 'plugin', (obj) ->
if sbClient.isEnablePlugin obj
func = sbClient.plugins[obj.plugin.name].get("callback") || {}
func(obj.data)
socket.on 'disconnect', ->
# disable event
$('body').off 'execEmit'
console.log 'disconnected Bye!'
#*****************************
# DOM ready
#*****************************
$ ->
sbClient.resizeSlide()
$(window).bind 'resize',->
sbClient.resizeSlide()
$('a').bind 'click', (e) ->
e.stopPropagation()
e.preventDefault()
window.open @href, '_blank'
|
[
{
"context": "on: (name, boolean=undefined) ->\n settingsKey = \"minimap.plugins.#{name}\"\n if boolean?\n ato",
"end": 2411,
"score": 0.6651837229728699,
"start": 2410,
"tag": "KEY",
"value": "\""
},
{
"context": ": (name, boolean=undefined) ->\n settingsKey = \"minima... | atom/packages/minimap/lib/mixins/plugin-management.coffee | ericeslinger/dotfiles | 3 | Mixin = require 'mixto'
{CompositeDisposable} = require 'event-kit'
# Public: Provides methods to manage minimap plugins.
#
# Minimap plugins are Atom packages that will augment the minimap.
# They have a secondary activation cycle going on constrained by the minimap
# package activation. A minimap plugin life cycle will generally look like this:
#
# 1. The plugin module is activated by Atom through the `activate` method
# 2. The plugin then register itself as a minimap plugin using `registerPlugin`
# 3. The plugin is activated/deactivated according to the minimap settings.
# 4. On the plugin module deactivation, the plugin must unregisters itself
# from the minimap using the `unregisterPlugin`.
module.exports =
class PluginManagement extends Mixin
### Public ###
# Returns the {Minimap} service API object.
provideMinimapServiceV1: -> this
# Internal: Stores the minimap plugins with their identifying name as key.
plugins: {}
# Internal: Stores the minimap plugins subscriptions with their identifying
# name as key.
pluginsSubscriptions: {}
# Registers a minimap `plugin` with the given `name`.
#
# name - The identifying {String} name of the plugin.
# It will be used as activation settings name as well
# as the key to unregister the module.
# plugin - The plugin {Object} to register.
registerPlugin: (name, plugin) ->
@plugins[name] = plugin
@pluginsSubscriptions[name] = new CompositeDisposable
event = {name, plugin}
@emitter.emit('did-add-plugin', event)
@registerPluginControls(name, plugin) if atom.config.get('minimap.displayPluginsControls')
@updatesPluginActivationState(name)
# Unregisters a plugin from the minimap.
#
# name - The identifying {String} name of the plugin to unregister.
unregisterPlugin: (name) ->
plugin = @plugins[name]
@unregisterPluginControls(name) if atom.config.get('minimap.displayPluginsControls')
delete @plugins[name]
event = {name, plugin}
@emitter.emit('did-remove-plugin', event)
# Toggles the specified plugin activation state.
#
# name - The {String} name of the plugin.
# boolean - An optional {Boolean} to set the activation state of the plugin.
# If ommitted the new plugin state will be the the inverse of its
# current state.
togglePluginActivation: (name, boolean=undefined) ->
settingsKey = "minimap.plugins.#{name}"
if boolean?
atom.config.set settingsKey, boolean
else
atom.config.set settingsKey, not atom.config.get(settingsKey)
@updatesPluginActivationState(name)
# Deactivates all the plugins registered in the minimap package so far.
deactivateAllPlugins: ->
plugin.deactivatePlugin() for name, plugin of @plugins
# Internal: Updates the plugin activation state according to the current
# config.
#
# name - The identifying {String} name of the plugin.
updatesPluginActivationState: (name) ->
plugin = @plugins[name]
pluginActive = plugin.isActive()
settingActive = atom.config.get("minimap.plugins.#{name}")
event = {name, plugin}
if settingActive and not pluginActive
plugin.activatePlugin()
@emitter.emit('did-activate-plugin', event)
else if pluginActive and not settingActive
plugin.deactivatePlugin()
@emitter.emit('did-deactivate-plugin', event)
# Internal: When the `minimap.displayPluginsControls` setting is toggled,
# this function will register the commands and setting to manage the plugin
# activation from the minimap settings.
#
# name - The identifying {String} name of the plugin.
# plugin - The plugin {Object}.
registerPluginControls: (name, plugin) ->
settingsKey = "minimap.plugins.#{name}"
@config.plugins.properties[name] =
type: 'boolean'
default: true
atom.config.set(settingsKey, true) unless atom.config.get(settingsKey)?
@pluginsSubscriptions[name].add atom.config.observe settingsKey, =>
@updatesPluginActivationState(name)
commands = {}
commands["minimap:toggle-#{name}"] = => @togglePluginActivation(name)
@pluginsSubscriptions[name].add atom.commands.add 'atom-workspace', commands
# Internal: When the `minimap.displayPluginsControls` setting is toggled,
# this function will unregister the commands and setting that was created
# previously.
#
# name - The identifying {String} name of the plugin.
unregisterPluginControls: (name) ->
@pluginsSubscriptions[name].dispose()
delete @pluginsSubscriptions[name]
delete @config.plugins.properties[name]
| 193599 | Mixin = require 'mixto'
{CompositeDisposable} = require 'event-kit'
# Public: Provides methods to manage minimap plugins.
#
# Minimap plugins are Atom packages that will augment the minimap.
# They have a secondary activation cycle going on constrained by the minimap
# package activation. A minimap plugin life cycle will generally look like this:
#
# 1. The plugin module is activated by Atom through the `activate` method
# 2. The plugin then register itself as a minimap plugin using `registerPlugin`
# 3. The plugin is activated/deactivated according to the minimap settings.
# 4. On the plugin module deactivation, the plugin must unregisters itself
# from the minimap using the `unregisterPlugin`.
module.exports =
class PluginManagement extends Mixin
### Public ###
# Returns the {Minimap} service API object.
provideMinimapServiceV1: -> this
# Internal: Stores the minimap plugins with their identifying name as key.
plugins: {}
# Internal: Stores the minimap plugins subscriptions with their identifying
# name as key.
pluginsSubscriptions: {}
# Registers a minimap `plugin` with the given `name`.
#
# name - The identifying {String} name of the plugin.
# It will be used as activation settings name as well
# as the key to unregister the module.
# plugin - The plugin {Object} to register.
registerPlugin: (name, plugin) ->
@plugins[name] = plugin
@pluginsSubscriptions[name] = new CompositeDisposable
event = {name, plugin}
@emitter.emit('did-add-plugin', event)
@registerPluginControls(name, plugin) if atom.config.get('minimap.displayPluginsControls')
@updatesPluginActivationState(name)
# Unregisters a plugin from the minimap.
#
# name - The identifying {String} name of the plugin to unregister.
unregisterPlugin: (name) ->
plugin = @plugins[name]
@unregisterPluginControls(name) if atom.config.get('minimap.displayPluginsControls')
delete @plugins[name]
event = {name, plugin}
@emitter.emit('did-remove-plugin', event)
# Toggles the specified plugin activation state.
#
# name - The {String} name of the plugin.
# boolean - An optional {Boolean} to set the activation state of the plugin.
# If ommitted the new plugin state will be the the inverse of its
# current state.
togglePluginActivation: (name, boolean=undefined) ->
settingsKey = <KEY> <KEY>
if boolean?
atom.config.set settingsKey, boolean
else
atom.config.set settingsKey, not atom.config.get(settingsKey)
@updatesPluginActivationState(name)
# Deactivates all the plugins registered in the minimap package so far.
deactivateAllPlugins: ->
plugin.deactivatePlugin() for name, plugin of @plugins
# Internal: Updates the plugin activation state according to the current
# config.
#
# name - The identifying {String} name of the plugin.
updatesPluginActivationState: (name) ->
plugin = @plugins[name]
pluginActive = plugin.isActive()
settingActive = atom.config.get("minimap.plugins.#{name}")
event = {name, plugin}
if settingActive and not pluginActive
plugin.activatePlugin()
@emitter.emit('did-activate-plugin', event)
else if pluginActive and not settingActive
plugin.deactivatePlugin()
@emitter.emit('did-deactivate-plugin', event)
# Internal: When the `minimap.displayPluginsControls` setting is toggled,
# this function will register the commands and setting to manage the plugin
# activation from the minimap settings.
#
# name - The identifying {String} name of the plugin.
# plugin - The plugin {Object}.
registerPluginControls: (name, plugin) ->
settingsKey = "<KEY>
@config.plugins.properties[name] =
type: 'boolean'
default: true
atom.config.set(settingsKey, true) unless atom.config.get(settingsKey)?
@pluginsSubscriptions[name].add atom.config.observe settingsKey, =>
@updatesPluginActivationState(name)
commands = {}
commands["minimap:toggle-#{name}"] = => @togglePluginActivation(name)
@pluginsSubscriptions[name].add atom.commands.add 'atom-workspace', commands
# Internal: When the `minimap.displayPluginsControls` setting is toggled,
# this function will unregister the commands and setting that was created
# previously.
#
# name - The identifying {String} name of the plugin.
unregisterPluginControls: (name) ->
@pluginsSubscriptions[name].dispose()
delete @pluginsSubscriptions[name]
delete @config.plugins.properties[name]
| true | Mixin = require 'mixto'
{CompositeDisposable} = require 'event-kit'
# Public: Provides methods to manage minimap plugins.
#
# Minimap plugins are Atom packages that will augment the minimap.
# They have a secondary activation cycle going on constrained by the minimap
# package activation. A minimap plugin life cycle will generally look like this:
#
# 1. The plugin module is activated by Atom through the `activate` method
# 2. The plugin then register itself as a minimap plugin using `registerPlugin`
# 3. The plugin is activated/deactivated according to the minimap settings.
# 4. On the plugin module deactivation, the plugin must unregisters itself
# from the minimap using the `unregisterPlugin`.
module.exports =
class PluginManagement extends Mixin
### Public ###
# Returns the {Minimap} service API object.
provideMinimapServiceV1: -> this
# Internal: Stores the minimap plugins with their identifying name as key.
plugins: {}
# Internal: Stores the minimap plugins subscriptions with their identifying
# name as key.
pluginsSubscriptions: {}
# Registers a minimap `plugin` with the given `name`.
#
# name - The identifying {String} name of the plugin.
# It will be used as activation settings name as well
# as the key to unregister the module.
# plugin - The plugin {Object} to register.
registerPlugin: (name, plugin) ->
@plugins[name] = plugin
@pluginsSubscriptions[name] = new CompositeDisposable
event = {name, plugin}
@emitter.emit('did-add-plugin', event)
@registerPluginControls(name, plugin) if atom.config.get('minimap.displayPluginsControls')
@updatesPluginActivationState(name)
# Unregisters a plugin from the minimap.
#
# name - The identifying {String} name of the plugin to unregister.
unregisterPlugin: (name) ->
plugin = @plugins[name]
@unregisterPluginControls(name) if atom.config.get('minimap.displayPluginsControls')
delete @plugins[name]
event = {name, plugin}
@emitter.emit('did-remove-plugin', event)
# Toggles the specified plugin activation state.
#
# name - The {String} name of the plugin.
# boolean - An optional {Boolean} to set the activation state of the plugin.
# If ommitted the new plugin state will be the the inverse of its
# current state.
togglePluginActivation: (name, boolean=undefined) ->
settingsKey = PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI
if boolean?
atom.config.set settingsKey, boolean
else
atom.config.set settingsKey, not atom.config.get(settingsKey)
@updatesPluginActivationState(name)
# Deactivates all the plugins registered in the minimap package so far.
deactivateAllPlugins: ->
plugin.deactivatePlugin() for name, plugin of @plugins
# Internal: Updates the plugin activation state according to the current
# config.
#
# name - The identifying {String} name of the plugin.
updatesPluginActivationState: (name) ->
plugin = @plugins[name]
pluginActive = plugin.isActive()
settingActive = atom.config.get("minimap.plugins.#{name}")
event = {name, plugin}
if settingActive and not pluginActive
plugin.activatePlugin()
@emitter.emit('did-activate-plugin', event)
else if pluginActive and not settingActive
plugin.deactivatePlugin()
@emitter.emit('did-deactivate-plugin', event)
# Internal: When the `minimap.displayPluginsControls` setting is toggled,
# this function will register the commands and setting to manage the plugin
# activation from the minimap settings.
#
# name - The identifying {String} name of the plugin.
# plugin - The plugin {Object}.
registerPluginControls: (name, plugin) ->
settingsKey = "PI:KEY:<KEY>END_PI
@config.plugins.properties[name] =
type: 'boolean'
default: true
atom.config.set(settingsKey, true) unless atom.config.get(settingsKey)?
@pluginsSubscriptions[name].add atom.config.observe settingsKey, =>
@updatesPluginActivationState(name)
commands = {}
commands["minimap:toggle-#{name}"] = => @togglePluginActivation(name)
@pluginsSubscriptions[name].add atom.commands.add 'atom-workspace', commands
# Internal: When the `minimap.displayPluginsControls` setting is toggled,
# this function will unregister the commands and setting that was created
# previously.
#
# name - The identifying {String} name of the plugin.
unregisterPluginControls: (name) ->
@pluginsSubscriptions[name].dispose()
delete @pluginsSubscriptions[name]
delete @config.plugins.properties[name]
|
[
{
"context": "tion: false\n\n @nested = new @TestNested(name: 'bob')\n @apple1 = new @TestNested(name: 'apple1')\n ",
"end": 837,
"score": 0.5620597004890442,
"start": 834,
"tag": "NAME",
"value": "bob"
},
{
"context": " ->\n @transaction.get('testNested').set('name', 'jim')\n... | tests/batman/model/transaction_test.coffee | davidcornu/batman | 0 | #= require associations/polymorphic_association_helper
QUnit.module "Batman.Model::transaction",
setup: ->
scope = this
window.PolymorphicAssociationHelpers.baseSetup.apply(scope)
class @TestNested extends Batman.Model
@resourceName: 'testNested'
@persist Batman.RestStorage
@belongsTo 'testModel', namespace: scope
@encode 'name'
class @TestModel extends Batman.Model
@resourceName: 'test'
@persist Batman.RestStorage
@encode 'banana'
@validate 'banana', presence: true
@validate 'money', numeric: true, allowBlank: true
@hasOne 'testNested', namespace: scope
@hasMany 'apples', name: 'TestNested', namespace: scope
@hasMany 'oranges', name: 'TestNested', namespace: scope, includeInTransaction: false
@nested = new @TestNested(name: 'bob')
@apple1 = new @TestNested(name: 'apple1')
@apple2 = new @TestNested(name: 'apple2')
@apples = new Batman.AssociationSet()
@apples.add(@apple1)
@apples.add(@apple2)
@base = new @TestModel(testNested: @nested, apples: @apples)
@nested.set 'testModel', @base
@apple1.set 'testModel', @base
@apple2.set 'testModel', @base
@transaction = @base.transaction()
test 'properties can be excluded from transactions', ->
ok @transaction.get('attributes.apples.length'), "included associations are present"
ok @transaction.get('attributes.oranges') is undefined, "excluded associations are undefined"
test 'changes made to the base object do not affect the transaction', ->
@base.set('banana', 'rama')
ok !@transaction.get('banana')
test 'changes made to the transaction object do not affect the base', ->
@transaction.set('banana', 'rama')
ok !@base.get('banana')
test 'applyChanges applies the changes in the transaction object to the base', ->
@transaction.set('banana', 'rama')
@transaction.applyChanges()
equal @base.get('banana'), 'rama'
test 'save applies the changes in the transaction object and saves the object', ->
s = sinon.stub(Batman.Model.prototype, '_doStorageOperation', (callback) -> callback?(null, this))
@transaction.set('banana', 'rama')
@transaction.save()
s.restore()
equal @base.get('banana'), 'rama'
test 'errors on the transaction object are not applied to the base object', ->
@transaction.validate()
equal @transaction.get('errors.length'), 1
equal @base.get('errors.length'), 0
test 'errors on the transaction object are not applied to the base object after save', ->
s = sinon.stub(Batman.Model.prototype, 'save', (callback) => callback?(@transaction.get('errors'), this))
@transaction.validate()
equal @transaction.get('errors.length'), 1
equal @base.get('errors.length'), 0
@transaction.save()
equal @transaction.get('errors.length'), 1
equal @base.get('errors.length'), 0
@transaction.set('money', 'banana tree')
@transaction.validate()
s.restore()
equal @transaction.get('errors.length'), 2
equal @base.get('errors.length'), 0
test 'errors on the base object are applied to the transaction on save', ->
@transaction.save()
equal @transaction.get('errors.length'), 1
test 'empty hasManys still get a transaction', ->
newTransaction = (new @TestModel).transaction()
transactionApples = newTransaction.get('apples')
ok transactionApples.get('length') == 0, "its empty"
ok transactionApples.length == 0, "it also responds to JS .length"
ok transactionApples.isTransaction, "its a transaction"
test 'nested models get their own transaction in a hasOne', ->
ok @base.get('testNested') == @nested
ok @transaction.get('testNested') != @nested
test 'nested models get their own transaction in a hasMany', ->
ok @base.get('testNested') == @nested
ok @transaction.get('apples').first != @apple1
test 'removing nested models doesnt affect the base until applyChanges', ->
firstTransactionApple = @transaction.get('apples.first')
@transaction.get('apples').remove(firstTransactionApple)
ok @base.get('apples.length') == 2, 'the item isnt removed from the base'
ok @transaction.get('apples.length') == 1, 'the item is removed from the transaction'
@transaction.applyChanges()
ok @base.get('apples.length') == 1, 'the item is removed'
ok @transaction.get('apples.length') == 1, 'the item is still gone from the transaction'
test 'removed items are tracked and attached to the original associationSet', ->
firstApple = @base.get('apples.first')
firstTransactionApple = @transaction.get('apples.first')
@transaction.get('apples').remove(firstTransactionApple)
@transaction.applyChanges()
ok @base.get('apples.removedItems.length') == 1
ok @base.get('apples.removedItems.first') == firstApple, 'the removed original is in removedItems'
@transaction.get('apples').add(firstApple)
@transaction.applyChanges()
ok @base.get('apples.removedItems.length') == 0, 'returning an item makes it not removed anymore'
test 'items loaded after `transaction()` are still in the transaction set', ->
newBase = new @TestModel(id: 51)
newTransaction = newBase.transaction()
ok newTransaction.get('apples.length') == 0
newBase.get('apples').add new @TestNested(id: 9, test_model_id: 51)
ok newTransaction.get('apples.length') == 1, 'the item was loaded'
ok newTransaction.get('apples.first.id') == 9, 'its the right item'
test 'adding nested models doesnt affect the base until applyChanges', ->
@transaction.get('apples').add(new @TestModel(name: 'apple3'))
ok @base.get('apples.length') == 2
ok @transaction.get('apples.length') == 3
@transaction.applyChanges()
ok @base.get('apples.length') == 3, 'the item is added'
ok @transaction.get('apples.length') == 3, 'the item is still in the transaction'
test 'nested model transactions get properly applied', ->
@transaction.get('testNested').set('name', 'jim')
@transaction.set('banana', 'rama')
@transaction.applyChanges()
equal @base.get('banana'), 'rama'
equal @nested.get('name'), 'jim'
test 'nested model transactions get properly saved', ->
@transaction.get('testNested').set('name', 'jim')
@transaction.get('apples.first').set('name', 'peach1')
@transaction.set('banana', 'rama')
@transaction.save()
equal @base.get('banana'), 'rama'
equal @nested.get('name'), 'jim'
equal @base.get('apples.first.name'), 'peach1'
test 'nested model transactions block sets from modifying the original', ->
@transaction.get('testNested').set('name', 'jim')
@transaction.get('apples.first').set('name', 'peach1')
@transaction.set('banana', 'rama')
equal @base.get('banana'), undefined
equal @nested.get('name'), 'bob'
equal @apple1.get('name'), 'apple1'
test 'recursive nested model transactions get properly loaded and applied', ->
transaction = @base.transaction()
ok transaction == transaction.get('testNested.testModel')
transaction.get('testNested').set('name', 'jim')
transaction.get('testNested.testModel').set('banana', 'rama')
transaction.applyChanges()
equal @base.get('banana'), 'rama'
equal @nested.get('name'), 'jim'
test 'recursive nested hasOne model transactions get properly saved', ->
transaction = @base.transaction()
transaction.get('testNested').set('name', 'jim')
transaction.get('testNested.testModel').set('banana', 'rama')
transaction.save()
equal @base.get('banana'), 'rama'
equal @nested.get('name'), 'jim'
test 'recursive nested toMany transactions get properly saved', ->
transaction = @base.transaction()
transaction.get('apples.first').set('name', 'apple3')
transaction.get('apples.first.testModel').set('banana', 'rama')
transaction.save()
equal @base.get('banana'), 'rama'
equal @base.get('apples.first.name'), 'apple3'
test 'recursive nested hasOne model transactions block sets from modifying the original', ->
transaction = @base.transaction()
transaction.get('testNested').set('name', 'jim')
transaction.get('testNested.testModel').set('banana', 'rama')
equal @base.get('banana'), undefined
equal @nested.get('name'), 'bob'
test 'recursive nested hasMany model transactions block sets from modifying the original', ->
transaction = @base.transaction()
transaction.get('apples.first').set('name', 'apple3')
transaction.get('apples.first.testModel').set('banana', 'rama')
equal @base.get('banana'), undefined
equal @nested.get('name'), 'bob'
equal @apple1.get('name'), 'apple1'
asyncTest 'polymorphic association sets get transactions', 8, ->
@Store.find 1, (err, store) =>
throw err if err
store.get('metafields')
delay =>
transaction = store.transaction()
metafieldsTransaction = transaction.get('metafields')
ok metafieldsTransaction.get('association').constructor == Batman.PolymorphicHasManyAssociation, 'its actually polymorphic'
ok metafieldsTransaction.isTransaction, 'Its actually a transaction'
metafieldsTransaction.add(new @Metafield)
ok metafieldsTransaction.get('length'), 3
ok store.get('metafields.length'), 2, 'New items arent added'
metafieldsTransaction.get('first').set('key', 'Transaction metafield')
ok metafieldsTransaction.get('first.key') == 'Transaction metafield'
ok store.get('metafields.first.key') != "Transaction metafield", 'item changes arent made'
metafieldsTransaction.applyChanges()
ok store.get('metafields.length'), 3, 'new items are added'
ok store.get('metafields.first.key') == "Transaction metafield", 'item changes are applied'
| 126237 | #= require associations/polymorphic_association_helper
QUnit.module "Batman.Model::transaction",
setup: ->
scope = this
window.PolymorphicAssociationHelpers.baseSetup.apply(scope)
class @TestNested extends Batman.Model
@resourceName: 'testNested'
@persist Batman.RestStorage
@belongsTo 'testModel', namespace: scope
@encode 'name'
class @TestModel extends Batman.Model
@resourceName: 'test'
@persist Batman.RestStorage
@encode 'banana'
@validate 'banana', presence: true
@validate 'money', numeric: true, allowBlank: true
@hasOne 'testNested', namespace: scope
@hasMany 'apples', name: 'TestNested', namespace: scope
@hasMany 'oranges', name: 'TestNested', namespace: scope, includeInTransaction: false
@nested = new @TestNested(name: '<NAME>')
@apple1 = new @TestNested(name: 'apple1')
@apple2 = new @TestNested(name: 'apple2')
@apples = new Batman.AssociationSet()
@apples.add(@apple1)
@apples.add(@apple2)
@base = new @TestModel(testNested: @nested, apples: @apples)
@nested.set 'testModel', @base
@apple1.set 'testModel', @base
@apple2.set 'testModel', @base
@transaction = @base.transaction()
test 'properties can be excluded from transactions', ->
ok @transaction.get('attributes.apples.length'), "included associations are present"
ok @transaction.get('attributes.oranges') is undefined, "excluded associations are undefined"
test 'changes made to the base object do not affect the transaction', ->
@base.set('banana', 'rama')
ok !@transaction.get('banana')
test 'changes made to the transaction object do not affect the base', ->
@transaction.set('banana', 'rama')
ok !@base.get('banana')
test 'applyChanges applies the changes in the transaction object to the base', ->
@transaction.set('banana', 'rama')
@transaction.applyChanges()
equal @base.get('banana'), 'rama'
test 'save applies the changes in the transaction object and saves the object', ->
s = sinon.stub(Batman.Model.prototype, '_doStorageOperation', (callback) -> callback?(null, this))
@transaction.set('banana', 'rama')
@transaction.save()
s.restore()
equal @base.get('banana'), 'rama'
test 'errors on the transaction object are not applied to the base object', ->
@transaction.validate()
equal @transaction.get('errors.length'), 1
equal @base.get('errors.length'), 0
test 'errors on the transaction object are not applied to the base object after save', ->
s = sinon.stub(Batman.Model.prototype, 'save', (callback) => callback?(@transaction.get('errors'), this))
@transaction.validate()
equal @transaction.get('errors.length'), 1
equal @base.get('errors.length'), 0
@transaction.save()
equal @transaction.get('errors.length'), 1
equal @base.get('errors.length'), 0
@transaction.set('money', 'banana tree')
@transaction.validate()
s.restore()
equal @transaction.get('errors.length'), 2
equal @base.get('errors.length'), 0
test 'errors on the base object are applied to the transaction on save', ->
@transaction.save()
equal @transaction.get('errors.length'), 1
test 'empty hasManys still get a transaction', ->
newTransaction = (new @TestModel).transaction()
transactionApples = newTransaction.get('apples')
ok transactionApples.get('length') == 0, "its empty"
ok transactionApples.length == 0, "it also responds to JS .length"
ok transactionApples.isTransaction, "its a transaction"
test 'nested models get their own transaction in a hasOne', ->
ok @base.get('testNested') == @nested
ok @transaction.get('testNested') != @nested
test 'nested models get their own transaction in a hasMany', ->
ok @base.get('testNested') == @nested
ok @transaction.get('apples').first != @apple1
test 'removing nested models doesnt affect the base until applyChanges', ->
firstTransactionApple = @transaction.get('apples.first')
@transaction.get('apples').remove(firstTransactionApple)
ok @base.get('apples.length') == 2, 'the item isnt removed from the base'
ok @transaction.get('apples.length') == 1, 'the item is removed from the transaction'
@transaction.applyChanges()
ok @base.get('apples.length') == 1, 'the item is removed'
ok @transaction.get('apples.length') == 1, 'the item is still gone from the transaction'
test 'removed items are tracked and attached to the original associationSet', ->
firstApple = @base.get('apples.first')
firstTransactionApple = @transaction.get('apples.first')
@transaction.get('apples').remove(firstTransactionApple)
@transaction.applyChanges()
ok @base.get('apples.removedItems.length') == 1
ok @base.get('apples.removedItems.first') == firstApple, 'the removed original is in removedItems'
@transaction.get('apples').add(firstApple)
@transaction.applyChanges()
ok @base.get('apples.removedItems.length') == 0, 'returning an item makes it not removed anymore'
test 'items loaded after `transaction()` are still in the transaction set', ->
newBase = new @TestModel(id: 51)
newTransaction = newBase.transaction()
ok newTransaction.get('apples.length') == 0
newBase.get('apples').add new @TestNested(id: 9, test_model_id: 51)
ok newTransaction.get('apples.length') == 1, 'the item was loaded'
ok newTransaction.get('apples.first.id') == 9, 'its the right item'
test 'adding nested models doesnt affect the base until applyChanges', ->
@transaction.get('apples').add(new @TestModel(name: 'apple3'))
ok @base.get('apples.length') == 2
ok @transaction.get('apples.length') == 3
@transaction.applyChanges()
ok @base.get('apples.length') == 3, 'the item is added'
ok @transaction.get('apples.length') == 3, 'the item is still in the transaction'
test 'nested model transactions get properly applied', ->
@transaction.get('testNested').set('name', '<NAME>')
@transaction.set('banana', 'rama')
@transaction.applyChanges()
equal @base.get('banana'), 'rama'
equal @nested.get('name'), '<NAME>'
test 'nested model transactions get properly saved', ->
@transaction.get('testNested').set('name', '<NAME>')
@transaction.get('apples.first').set('name', '<NAME>')
@transaction.set('banana', 'rama')
@transaction.save()
equal @base.get('banana'), 'rama'
equal @nested.get('name'), '<NAME>'
equal @base.get('apples.first.name'), '<NAME>'
test 'nested model transactions block sets from modifying the original', ->
@transaction.get('testNested').set('name', '<NAME>')
@transaction.get('apples.first').set('name', '<NAME>')
@transaction.set('banana', 'rama')
equal @base.get('banana'), undefined
equal @nested.get('name'), '<NAME>'
equal @apple1.get('name'), 'apple1'
test 'recursive nested model transactions get properly loaded and applied', ->
transaction = @base.transaction()
ok transaction == transaction.get('testNested.testModel')
transaction.get('testNested').set('name', '<NAME>')
transaction.get('testNested.testModel').set('banana', 'rama')
transaction.applyChanges()
equal @base.get('banana'), 'rama'
equal @nested.get('name'), '<NAME>'
test 'recursive nested hasOne model transactions get properly saved', ->
transaction = @base.transaction()
transaction.get('testNested').set('name', '<NAME>')
transaction.get('testNested.testModel').set('banana', 'rama')
transaction.save()
equal @base.get('banana'), 'rama'
equal @nested.get('name'), '<NAME>'
test 'recursive nested toMany transactions get properly saved', ->
transaction = @base.transaction()
transaction.get('apples.first').set('name', 'apple3')
transaction.get('apples.first.testModel').set('banana', 'rama')
transaction.save()
equal @base.get('banana'), 'rama'
equal @base.get('apples.first.name'), 'apple3'
test 'recursive nested hasOne model transactions block sets from modifying the original', ->
transaction = @base.transaction()
transaction.get('testNested').set('name', '<NAME>')
transaction.get('testNested.testModel').set('banana', 'rama')
equal @base.get('banana'), undefined
equal @nested.get('name'), '<NAME>'
test 'recursive nested hasMany model transactions block sets from modifying the original', ->
transaction = @base.transaction()
transaction.get('apples.first').set('name', 'apple3')
transaction.get('apples.first.testModel').set('banana', 'rama')
equal @base.get('banana'), undefined
equal @nested.get('name'), '<NAME>'
equal @apple1.get('name'), 'apple1'
asyncTest 'polymorphic association sets get transactions', 8, ->
@Store.find 1, (err, store) =>
throw err if err
store.get('metafields')
delay =>
transaction = store.transaction()
metafieldsTransaction = transaction.get('metafields')
ok metafieldsTransaction.get('association').constructor == Batman.PolymorphicHasManyAssociation, 'its actually polymorphic'
ok metafieldsTransaction.isTransaction, 'Its actually a transaction'
metafieldsTransaction.add(new @Metafield)
ok metafieldsTransaction.get('length'), 3
ok store.get('metafields.length'), 2, 'New items arent added'
metafieldsTransaction.get('first').set('key', 'Transaction metafield')
ok metafieldsTransaction.get('first.key') == 'Transaction metafield'
ok store.get('metafields.first.key') != "Transaction metafield", 'item changes arent made'
metafieldsTransaction.applyChanges()
ok store.get('metafields.length'), 3, 'new items are added'
ok store.get('metafields.first.key') == "Transaction metafield", 'item changes are applied'
| true | #= require associations/polymorphic_association_helper
QUnit.module "Batman.Model::transaction",
setup: ->
scope = this
window.PolymorphicAssociationHelpers.baseSetup.apply(scope)
class @TestNested extends Batman.Model
@resourceName: 'testNested'
@persist Batman.RestStorage
@belongsTo 'testModel', namespace: scope
@encode 'name'
class @TestModel extends Batman.Model
@resourceName: 'test'
@persist Batman.RestStorage
@encode 'banana'
@validate 'banana', presence: true
@validate 'money', numeric: true, allowBlank: true
@hasOne 'testNested', namespace: scope
@hasMany 'apples', name: 'TestNested', namespace: scope
@hasMany 'oranges', name: 'TestNested', namespace: scope, includeInTransaction: false
@nested = new @TestNested(name: 'PI:NAME:<NAME>END_PI')
@apple1 = new @TestNested(name: 'apple1')
@apple2 = new @TestNested(name: 'apple2')
@apples = new Batman.AssociationSet()
@apples.add(@apple1)
@apples.add(@apple2)
@base = new @TestModel(testNested: @nested, apples: @apples)
@nested.set 'testModel', @base
@apple1.set 'testModel', @base
@apple2.set 'testModel', @base
@transaction = @base.transaction()
test 'properties can be excluded from transactions', ->
ok @transaction.get('attributes.apples.length'), "included associations are present"
ok @transaction.get('attributes.oranges') is undefined, "excluded associations are undefined"
test 'changes made to the base object do not affect the transaction', ->
@base.set('banana', 'rama')
ok !@transaction.get('banana')
test 'changes made to the transaction object do not affect the base', ->
@transaction.set('banana', 'rama')
ok !@base.get('banana')
test 'applyChanges applies the changes in the transaction object to the base', ->
@transaction.set('banana', 'rama')
@transaction.applyChanges()
equal @base.get('banana'), 'rama'
test 'save applies the changes in the transaction object and saves the object', ->
s = sinon.stub(Batman.Model.prototype, '_doStorageOperation', (callback) -> callback?(null, this))
@transaction.set('banana', 'rama')
@transaction.save()
s.restore()
equal @base.get('banana'), 'rama'
test 'errors on the transaction object are not applied to the base object', ->
@transaction.validate()
equal @transaction.get('errors.length'), 1
equal @base.get('errors.length'), 0
test 'errors on the transaction object are not applied to the base object after save', ->
s = sinon.stub(Batman.Model.prototype, 'save', (callback) => callback?(@transaction.get('errors'), this))
@transaction.validate()
equal @transaction.get('errors.length'), 1
equal @base.get('errors.length'), 0
@transaction.save()
equal @transaction.get('errors.length'), 1
equal @base.get('errors.length'), 0
@transaction.set('money', 'banana tree')
@transaction.validate()
s.restore()
equal @transaction.get('errors.length'), 2
equal @base.get('errors.length'), 0
test 'errors on the base object are applied to the transaction on save', ->
@transaction.save()
equal @transaction.get('errors.length'), 1
test 'empty hasManys still get a transaction', ->
newTransaction = (new @TestModel).transaction()
transactionApples = newTransaction.get('apples')
ok transactionApples.get('length') == 0, "its empty"
ok transactionApples.length == 0, "it also responds to JS .length"
ok transactionApples.isTransaction, "its a transaction"
test 'nested models get their own transaction in a hasOne', ->
ok @base.get('testNested') == @nested
ok @transaction.get('testNested') != @nested
test 'nested models get their own transaction in a hasMany', ->
ok @base.get('testNested') == @nested
ok @transaction.get('apples').first != @apple1
test 'removing nested models doesnt affect the base until applyChanges', ->
firstTransactionApple = @transaction.get('apples.first')
@transaction.get('apples').remove(firstTransactionApple)
ok @base.get('apples.length') == 2, 'the item isnt removed from the base'
ok @transaction.get('apples.length') == 1, 'the item is removed from the transaction'
@transaction.applyChanges()
ok @base.get('apples.length') == 1, 'the item is removed'
ok @transaction.get('apples.length') == 1, 'the item is still gone from the transaction'
test 'removed items are tracked and attached to the original associationSet', ->
firstApple = @base.get('apples.first')
firstTransactionApple = @transaction.get('apples.first')
@transaction.get('apples').remove(firstTransactionApple)
@transaction.applyChanges()
ok @base.get('apples.removedItems.length') == 1
ok @base.get('apples.removedItems.first') == firstApple, 'the removed original is in removedItems'
@transaction.get('apples').add(firstApple)
@transaction.applyChanges()
ok @base.get('apples.removedItems.length') == 0, 'returning an item makes it not removed anymore'
test 'items loaded after `transaction()` are still in the transaction set', ->
newBase = new @TestModel(id: 51)
newTransaction = newBase.transaction()
ok newTransaction.get('apples.length') == 0
newBase.get('apples').add new @TestNested(id: 9, test_model_id: 51)
ok newTransaction.get('apples.length') == 1, 'the item was loaded'
ok newTransaction.get('apples.first.id') == 9, 'its the right item'
test 'adding nested models doesnt affect the base until applyChanges', ->
@transaction.get('apples').add(new @TestModel(name: 'apple3'))
ok @base.get('apples.length') == 2
ok @transaction.get('apples.length') == 3
@transaction.applyChanges()
ok @base.get('apples.length') == 3, 'the item is added'
ok @transaction.get('apples.length') == 3, 'the item is still in the transaction'
test 'nested model transactions get properly applied', ->
@transaction.get('testNested').set('name', 'PI:NAME:<NAME>END_PI')
@transaction.set('banana', 'rama')
@transaction.applyChanges()
equal @base.get('banana'), 'rama'
equal @nested.get('name'), 'PI:NAME:<NAME>END_PI'
test 'nested model transactions get properly saved', ->
@transaction.get('testNested').set('name', 'PI:NAME:<NAME>END_PI')
@transaction.get('apples.first').set('name', 'PI:NAME:<NAME>END_PI')
@transaction.set('banana', 'rama')
@transaction.save()
equal @base.get('banana'), 'rama'
equal @nested.get('name'), 'PI:NAME:<NAME>END_PI'
equal @base.get('apples.first.name'), 'PI:NAME:<NAME>END_PI'
test 'nested model transactions block sets from modifying the original', ->
@transaction.get('testNested').set('name', 'PI:NAME:<NAME>END_PI')
@transaction.get('apples.first').set('name', 'PI:NAME:<NAME>END_PI')
@transaction.set('banana', 'rama')
equal @base.get('banana'), undefined
equal @nested.get('name'), 'PI:NAME:<NAME>END_PI'
equal @apple1.get('name'), 'apple1'
test 'recursive nested model transactions get properly loaded and applied', ->
transaction = @base.transaction()
ok transaction == transaction.get('testNested.testModel')
transaction.get('testNested').set('name', 'PI:NAME:<NAME>END_PI')
transaction.get('testNested.testModel').set('banana', 'rama')
transaction.applyChanges()
equal @base.get('banana'), 'rama'
equal @nested.get('name'), 'PI:NAME:<NAME>END_PI'
test 'recursive nested hasOne model transactions get properly saved', ->
transaction = @base.transaction()
transaction.get('testNested').set('name', 'PI:NAME:<NAME>END_PI')
transaction.get('testNested.testModel').set('banana', 'rama')
transaction.save()
equal @base.get('banana'), 'rama'
equal @nested.get('name'), 'PI:NAME:<NAME>END_PI'
test 'recursive nested toMany transactions get properly saved', ->
transaction = @base.transaction()
transaction.get('apples.first').set('name', 'apple3')
transaction.get('apples.first.testModel').set('banana', 'rama')
transaction.save()
equal @base.get('banana'), 'rama'
equal @base.get('apples.first.name'), 'apple3'
test 'recursive nested hasOne model transactions block sets from modifying the original', ->
transaction = @base.transaction()
transaction.get('testNested').set('name', 'PI:NAME:<NAME>END_PI')
transaction.get('testNested.testModel').set('banana', 'rama')
equal @base.get('banana'), undefined
equal @nested.get('name'), 'PI:NAME:<NAME>END_PI'
test 'recursive nested hasMany model transactions block sets from modifying the original', ->
transaction = @base.transaction()
transaction.get('apples.first').set('name', 'apple3')
transaction.get('apples.first.testModel').set('banana', 'rama')
equal @base.get('banana'), undefined
equal @nested.get('name'), 'PI:NAME:<NAME>END_PI'
equal @apple1.get('name'), 'apple1'
asyncTest 'polymorphic association sets get transactions', 8, ->
@Store.find 1, (err, store) =>
throw err if err
store.get('metafields')
delay =>
transaction = store.transaction()
metafieldsTransaction = transaction.get('metafields')
ok metafieldsTransaction.get('association').constructor == Batman.PolymorphicHasManyAssociation, 'its actually polymorphic'
ok metafieldsTransaction.isTransaction, 'Its actually a transaction'
metafieldsTransaction.add(new @Metafield)
ok metafieldsTransaction.get('length'), 3
ok store.get('metafields.length'), 2, 'New items arent added'
metafieldsTransaction.get('first').set('key', 'Transaction metafield')
ok metafieldsTransaction.get('first.key') == 'Transaction metafield'
ok store.get('metafields.first.key') != "Transaction metafield", 'item changes arent made'
metafieldsTransaction.applyChanges()
ok store.get('metafields.length'), 3, 'new items are added'
ok store.get('metafields.first.key') == "Transaction metafield", 'item changes are applied'
|
[
{
"context": " <LoadMoreMessagesMarker\n key=\"loadafter-#{currentMessage.get 'id'}\"\n channelId=",
"end": 2513,
"score": 0.8054803013801575,
"start": 2507,
"tag": "KEY",
"value": "after-"
},
{
"context": " <LoadMoreMessagesMarker\n key=\... | client/activity/lib/components/chatlist/index.coffee | ezgikaysi/koding | 1 | kd = require 'kd'
React = require 'kd-react'
ReactDOM = require 'react-dom'
moment = require 'moment'
immutable = require 'immutable'
ChatListItem = require 'activity/components/chatlistitem'
DateMarker = require 'activity/components/datemarker'
NewMessageMarker = require 'activity/components/newmessagemarker'
LoadMoreMessagesMarker = require 'activity/components/loadmoremessagesmarker'
Waypoint = require 'react-waypoint'
ImmutableRenderMixin = require 'react-immutable-render-mixin'
findScrollableParent = require 'app/util/findScrollableParent'
module.exports = class ChatList extends React.Component
@propTypes =
messages : React.PropTypes.object
showItemMenu : React.PropTypes.bool
channelId : React.PropTypes.string
channelName : React.PropTypes.string
unreadCount : React.PropTypes.number
isMessagesLoading : React.PropTypes.bool
selectedMessageId : React.PropTypes.string
onGlance : React.PropTypes.func
@defaultProps =
messages : immutable.List()
showItemMenu : yes
channelId : ''
channelName : ''
unreadCount : 0
isMessagesLoading : no
selectedMessageId : null
onGlance : kd.noop
handleResize: ->
@updateDateMarkersPosition()
componentDidMount: ->
kd.singletons.windowController.addFocusListener @bound 'handleFocus'
@cacheDateMarkers()
@scrollableParent = findScrollableParent ReactDOM.findDOMNode this
window.addEventListener 'resize', @bound 'handleResize'
componentDidUpdate: -> @cacheDateMarkers()
componentWillUnmount: ->
window.removeEventListener 'resize', @bound 'handleResize'
glance: ->
@props.onGlance() if kd.singletons.windowController.isFocused()
handleFocus: (focused) ->
@glance() if focused and @props.unreadCount
onGlancerEnter: -> @glance()
getBeforeMarkers: (currentMessage, prevMessage, index) ->
currentMessageMoment = moment currentMessage.get 'createdAt'
if prevMessage
prevMessageMoment = moment prevMessage.get 'createdAt'
{ messages, unreadCount, channelId, isMessagesLoading } = @props
markers = []
if loaderMarkers = currentMessage.get 'loaderMarkers'
if beforeMarker = loaderMarkers.get 'before'
markers.push \
<LoadMoreMessagesMarker
key="loadafter-#{currentMessage.get 'id'}"
channelId={channelId}
messageId={currentMessage.get 'id'}
position="before"
autoload={beforeMarker.get 'autoload'}
timestamp={currentMessage.get 'createdAt'}/>
switch
# if this is first message put a date marker no matter what.
when not prevMessage
markers.push \
<DateMarker
key={currentMessage.get 'createdAt'}
date={currentMessage.get 'createdAt'} />
# if day of previous message is not the same with current one, put a date
# marker.
when not currentMessageMoment.isSame prevMessageMoment, 'day'
markers.push \
<DateMarker
key={currentMessage.get 'createdAt'}
date={currentMessage.get 'createdAt'} />
# put new message marker on top of other messages if unread count is
# greater than currently loaded messages.
newMessageIndex = Math.max 0, messages.size - unreadCount
if newMessageIndex is index
markers.push <NewMessageMarker />
# put glancer waypoint only if all the unread messages are loaded, and on
# the screen. Once it enters to the screen, it will glance the channel.
if index is messages.size - unreadCount and not isMessagesLoading
markers.push <Waypoint
onEnter={@bound 'onGlancerEnter'}
scrollableParent={@scrollableParent}
fireOnRapidScroll=no />
return markers
getAfterMarkers: (currentMessage, prevMessage, index) ->
{ channelId } = @props
markers = []
if loaderMarkers = currentMessage.get 'loaderMarkers'
if afterMarker = loaderMarkers.get 'after'
markers.push \
<LoadMoreMessagesMarker
key="loadafter-#{currentMessage.get 'id'}"
channelId={channelId}
messageId={currentMessage.get 'id'}
position="after"
autoload={afterMarker.get 'autoload'}
timestamp={currentMessage.get 'createdAt'} />
return markers
cacheDateMarkers: ->
filter = Array.prototype.filter
container = ReactDOM.findDOMNode this
markers = container.querySelectorAll '.DateMarker'
@dateMarkers = filter.call markers, (node) ->
return node.className.indexOf('DateMarker-fixed') is -1
updateDateMarkersPosition: ->
return unless @scrollableParent
{ scrollTop, offsetHeight } = @scrollableParent
return unless scrollTop and offsetHeight
left = @scrollableParent.getBoundingClientRect().left
@dateMarkers.forEach (dateMarker) ->
{ offsetTop, offsetWidth } = dateMarker
fixedMarker = dateMarker.querySelector '.DateMarker-fixed'
if offsetTop >= scrollTop
fixedMarker.style.display = 'none'
else if scrollTop > offsetTop
fixedMarker.style.left = "#{left}px"
fixedMarker.style.width = "#{offsetWidth}px"
fixedMarker.style.display = 'block'
renderChildren: ->
{ messages, showItemMenu, channelName } = @props
{ channelId, selectedMessageId } = @props
lastDifferentOwnerId = null
prevMessage = null
lastMessageCreatedAt = null
timeDiff = 0
isLessThanFiveMinutes = no
children = messages.toList().reduce (children, message, i) =>
itemProps =
key : message.get 'id'
message : message
showItemMenu : showItemMenu
channelName : channelName
channelId : channelId
createdAt = message.get 'createdAt'
timeDiff = new Date(createdAt).getTime() - lastMessageCreatedAt if lastMessageCreatedAt
isLessThanFiveMinutes = timeDiff < (5 * 60 * 1000)
if selectedMessageId is message.get 'id'
itemProps['isSelected'] = yes
children = children.concat @getBeforeMarkers message, prevMessage, i
accountId = message.get 'accountId'
isSameOwnerId = lastDifferentOwnerId and lastDifferentOwnerId is accountId
isSimpleItem = isSameOwnerId and isLessThanFiveMinutes
children.push \
<ChatListItem.Container {...itemProps } isSimple={isSimpleItem} />
unless isSimpleItem
lastDifferentOwnerId = message.get 'accountId'
lastMessageCreatedAt = new Date(createdAt).getTime()
children = children.concat @getAfterMarkers message, prevMessage, i
prevMessage = message
return children
, []
render: ->
<div className={kd.utils.curry 'ChatList', @props.className}>
{@renderChildren()}
</div>
ChatList.include [ ImmutableRenderMixin ]
| 166782 | kd = require 'kd'
React = require 'kd-react'
ReactDOM = require 'react-dom'
moment = require 'moment'
immutable = require 'immutable'
ChatListItem = require 'activity/components/chatlistitem'
DateMarker = require 'activity/components/datemarker'
NewMessageMarker = require 'activity/components/newmessagemarker'
LoadMoreMessagesMarker = require 'activity/components/loadmoremessagesmarker'
Waypoint = require 'react-waypoint'
ImmutableRenderMixin = require 'react-immutable-render-mixin'
findScrollableParent = require 'app/util/findScrollableParent'
module.exports = class ChatList extends React.Component
@propTypes =
messages : React.PropTypes.object
showItemMenu : React.PropTypes.bool
channelId : React.PropTypes.string
channelName : React.PropTypes.string
unreadCount : React.PropTypes.number
isMessagesLoading : React.PropTypes.bool
selectedMessageId : React.PropTypes.string
onGlance : React.PropTypes.func
@defaultProps =
messages : immutable.List()
showItemMenu : yes
channelId : ''
channelName : ''
unreadCount : 0
isMessagesLoading : no
selectedMessageId : null
onGlance : kd.noop
handleResize: ->
@updateDateMarkersPosition()
componentDidMount: ->
kd.singletons.windowController.addFocusListener @bound 'handleFocus'
@cacheDateMarkers()
@scrollableParent = findScrollableParent ReactDOM.findDOMNode this
window.addEventListener 'resize', @bound 'handleResize'
componentDidUpdate: -> @cacheDateMarkers()
componentWillUnmount: ->
window.removeEventListener 'resize', @bound 'handleResize'
glance: ->
@props.onGlance() if kd.singletons.windowController.isFocused()
handleFocus: (focused) ->
@glance() if focused and @props.unreadCount
onGlancerEnter: -> @glance()
getBeforeMarkers: (currentMessage, prevMessage, index) ->
currentMessageMoment = moment currentMessage.get 'createdAt'
if prevMessage
prevMessageMoment = moment prevMessage.get 'createdAt'
{ messages, unreadCount, channelId, isMessagesLoading } = @props
markers = []
if loaderMarkers = currentMessage.get 'loaderMarkers'
if beforeMarker = loaderMarkers.get 'before'
markers.push \
<LoadMoreMessagesMarker
key="load<KEY>#{currentMessage.get 'id'}"
channelId={channelId}
messageId={currentMessage.get 'id'}
position="before"
autoload={beforeMarker.get 'autoload'}
timestamp={currentMessage.get 'createdAt'}/>
switch
# if this is first message put a date marker no matter what.
when not prevMessage
markers.push \
<DateMarker
key={currentMessage.get 'createdAt'}
date={currentMessage.get 'createdAt'} />
# if day of previous message is not the same with current one, put a date
# marker.
when not currentMessageMoment.isSame prevMessageMoment, 'day'
markers.push \
<DateMarker
key={currentMessage.get 'createdAt'}
date={currentMessage.get 'createdAt'} />
# put new message marker on top of other messages if unread count is
# greater than currently loaded messages.
newMessageIndex = Math.max 0, messages.size - unreadCount
if newMessageIndex is index
markers.push <NewMessageMarker />
# put glancer waypoint only if all the unread messages are loaded, and on
# the screen. Once it enters to the screen, it will glance the channel.
if index is messages.size - unreadCount and not isMessagesLoading
markers.push <Waypoint
onEnter={@bound 'onGlancerEnter'}
scrollableParent={@scrollableParent}
fireOnRapidScroll=no />
return markers
getAfterMarkers: (currentMessage, prevMessage, index) ->
{ channelId } = @props
markers = []
if loaderMarkers = currentMessage.get 'loaderMarkers'
if afterMarker = loaderMarkers.get 'after'
markers.push \
<LoadMoreMessagesMarker
key="<KEY>currentMessage.get 'id'}"
channelId={channelId}
messageId={currentMessage.get 'id'}
position="after"
autoload={afterMarker.get 'autoload'}
timestamp={currentMessage.get 'createdAt'} />
return markers
cacheDateMarkers: ->
filter = Array.prototype.filter
container = ReactDOM.findDOMNode this
markers = container.querySelectorAll '.DateMarker'
@dateMarkers = filter.call markers, (node) ->
return node.className.indexOf('DateMarker-fixed') is -1
updateDateMarkersPosition: ->
return unless @scrollableParent
{ scrollTop, offsetHeight } = @scrollableParent
return unless scrollTop and offsetHeight
left = @scrollableParent.getBoundingClientRect().left
@dateMarkers.forEach (dateMarker) ->
{ offsetTop, offsetWidth } = dateMarker
fixedMarker = dateMarker.querySelector '.DateMarker-fixed'
if offsetTop >= scrollTop
fixedMarker.style.display = 'none'
else if scrollTop > offsetTop
fixedMarker.style.left = "#{left}px"
fixedMarker.style.width = "#{offsetWidth}px"
fixedMarker.style.display = 'block'
renderChildren: ->
{ messages, showItemMenu, channelName } = @props
{ channelId, selectedMessageId } = @props
lastDifferentOwnerId = null
prevMessage = null
lastMessageCreatedAt = null
timeDiff = 0
isLessThanFiveMinutes = no
children = messages.toList().reduce (children, message, i) =>
itemProps =
key : message.get 'id'
message : message
showItemMenu : showItemMenu
channelName : channelName
channelId : channelId
createdAt = message.get 'createdAt'
timeDiff = new Date(createdAt).getTime() - lastMessageCreatedAt if lastMessageCreatedAt
isLessThanFiveMinutes = timeDiff < (5 * 60 * 1000)
if selectedMessageId is message.get 'id'
itemProps['isSelected'] = yes
children = children.concat @getBeforeMarkers message, prevMessage, i
accountId = message.get 'accountId'
isSameOwnerId = lastDifferentOwnerId and lastDifferentOwnerId is accountId
isSimpleItem = isSameOwnerId and isLessThanFiveMinutes
children.push \
<ChatListItem.Container {...itemProps } isSimple={isSimpleItem} />
unless isSimpleItem
lastDifferentOwnerId = message.get 'accountId'
lastMessageCreatedAt = new Date(createdAt).getTime()
children = children.concat @getAfterMarkers message, prevMessage, i
prevMessage = message
return children
, []
render: ->
<div className={kd.utils.curry 'ChatList', @props.className}>
{@renderChildren()}
</div>
ChatList.include [ ImmutableRenderMixin ]
| true | kd = require 'kd'
React = require 'kd-react'
ReactDOM = require 'react-dom'
moment = require 'moment'
immutable = require 'immutable'
ChatListItem = require 'activity/components/chatlistitem'
DateMarker = require 'activity/components/datemarker'
NewMessageMarker = require 'activity/components/newmessagemarker'
LoadMoreMessagesMarker = require 'activity/components/loadmoremessagesmarker'
Waypoint = require 'react-waypoint'
ImmutableRenderMixin = require 'react-immutable-render-mixin'
findScrollableParent = require 'app/util/findScrollableParent'
module.exports = class ChatList extends React.Component
@propTypes =
messages : React.PropTypes.object
showItemMenu : React.PropTypes.bool
channelId : React.PropTypes.string
channelName : React.PropTypes.string
unreadCount : React.PropTypes.number
isMessagesLoading : React.PropTypes.bool
selectedMessageId : React.PropTypes.string
onGlance : React.PropTypes.func
@defaultProps =
messages : immutable.List()
showItemMenu : yes
channelId : ''
channelName : ''
unreadCount : 0
isMessagesLoading : no
selectedMessageId : null
onGlance : kd.noop
handleResize: ->
@updateDateMarkersPosition()
componentDidMount: ->
kd.singletons.windowController.addFocusListener @bound 'handleFocus'
@cacheDateMarkers()
@scrollableParent = findScrollableParent ReactDOM.findDOMNode this
window.addEventListener 'resize', @bound 'handleResize'
componentDidUpdate: -> @cacheDateMarkers()
componentWillUnmount: ->
window.removeEventListener 'resize', @bound 'handleResize'
glance: ->
@props.onGlance() if kd.singletons.windowController.isFocused()
handleFocus: (focused) ->
@glance() if focused and @props.unreadCount
onGlancerEnter: -> @glance()
getBeforeMarkers: (currentMessage, prevMessage, index) ->
currentMessageMoment = moment currentMessage.get 'createdAt'
if prevMessage
prevMessageMoment = moment prevMessage.get 'createdAt'
{ messages, unreadCount, channelId, isMessagesLoading } = @props
markers = []
if loaderMarkers = currentMessage.get 'loaderMarkers'
if beforeMarker = loaderMarkers.get 'before'
markers.push \
<LoadMoreMessagesMarker
key="loadPI:KEY:<KEY>END_PI#{currentMessage.get 'id'}"
channelId={channelId}
messageId={currentMessage.get 'id'}
position="before"
autoload={beforeMarker.get 'autoload'}
timestamp={currentMessage.get 'createdAt'}/>
switch
# if this is first message put a date marker no matter what.
when not prevMessage
markers.push \
<DateMarker
key={currentMessage.get 'createdAt'}
date={currentMessage.get 'createdAt'} />
# if day of previous message is not the same with current one, put a date
# marker.
when not currentMessageMoment.isSame prevMessageMoment, 'day'
markers.push \
<DateMarker
key={currentMessage.get 'createdAt'}
date={currentMessage.get 'createdAt'} />
# put new message marker on top of other messages if unread count is
# greater than currently loaded messages.
newMessageIndex = Math.max 0, messages.size - unreadCount
if newMessageIndex is index
markers.push <NewMessageMarker />
# put glancer waypoint only if all the unread messages are loaded, and on
# the screen. Once it enters to the screen, it will glance the channel.
if index is messages.size - unreadCount and not isMessagesLoading
markers.push <Waypoint
onEnter={@bound 'onGlancerEnter'}
scrollableParent={@scrollableParent}
fireOnRapidScroll=no />
return markers
getAfterMarkers: (currentMessage, prevMessage, index) ->
{ channelId } = @props
markers = []
if loaderMarkers = currentMessage.get 'loaderMarkers'
if afterMarker = loaderMarkers.get 'after'
markers.push \
<LoadMoreMessagesMarker
key="PI:KEY:<KEY>END_PIcurrentMessage.get 'id'}"
channelId={channelId}
messageId={currentMessage.get 'id'}
position="after"
autoload={afterMarker.get 'autoload'}
timestamp={currentMessage.get 'createdAt'} />
return markers
cacheDateMarkers: ->
filter = Array.prototype.filter
container = ReactDOM.findDOMNode this
markers = container.querySelectorAll '.DateMarker'
@dateMarkers = filter.call markers, (node) ->
return node.className.indexOf('DateMarker-fixed') is -1
updateDateMarkersPosition: ->
return unless @scrollableParent
{ scrollTop, offsetHeight } = @scrollableParent
return unless scrollTop and offsetHeight
left = @scrollableParent.getBoundingClientRect().left
@dateMarkers.forEach (dateMarker) ->
{ offsetTop, offsetWidth } = dateMarker
fixedMarker = dateMarker.querySelector '.DateMarker-fixed'
if offsetTop >= scrollTop
fixedMarker.style.display = 'none'
else if scrollTop > offsetTop
fixedMarker.style.left = "#{left}px"
fixedMarker.style.width = "#{offsetWidth}px"
fixedMarker.style.display = 'block'
renderChildren: ->
{ messages, showItemMenu, channelName } = @props
{ channelId, selectedMessageId } = @props
lastDifferentOwnerId = null
prevMessage = null
lastMessageCreatedAt = null
timeDiff = 0
isLessThanFiveMinutes = no
children = messages.toList().reduce (children, message, i) =>
itemProps =
key : message.get 'id'
message : message
showItemMenu : showItemMenu
channelName : channelName
channelId : channelId
createdAt = message.get 'createdAt'
timeDiff = new Date(createdAt).getTime() - lastMessageCreatedAt if lastMessageCreatedAt
isLessThanFiveMinutes = timeDiff < (5 * 60 * 1000)
if selectedMessageId is message.get 'id'
itemProps['isSelected'] = yes
children = children.concat @getBeforeMarkers message, prevMessage, i
accountId = message.get 'accountId'
isSameOwnerId = lastDifferentOwnerId and lastDifferentOwnerId is accountId
isSimpleItem = isSameOwnerId and isLessThanFiveMinutes
children.push \
<ChatListItem.Container {...itemProps } isSimple={isSimpleItem} />
unless isSimpleItem
lastDifferentOwnerId = message.get 'accountId'
lastMessageCreatedAt = new Date(createdAt).getTime()
children = children.concat @getAfterMarkers message, prevMessage, i
prevMessage = message
return children
, []
render: ->
<div className={kd.utils.curry 'ChatList', @props.className}>
{@renderChildren()}
</div>
ChatList.include [ ImmutableRenderMixin ]
|
[
{
"context": " \"version\": \"0.3.0\",\n \"maintainer\": \"Pierre-Alexis Ciavaldini <pierre-alexis@ciavaldini.fr>\",\n \"descript",
"end": 127,
"score": 0.9998784065246582,
"start": 103,
"tag": "NAME",
"value": "Pierre-Alexis Ciavaldini"
},
{
"context": "\n ... | package-manifest.cson | pciavald/draft-reMarkable | 0 | {
"info": {
"package-name": "rm-draft",
"version": "0.3.0",
"maintainer": "Pierre-Alexis Ciavaldini <pierre-alexis@ciavaldini.fr>",
"description": "A launcher for the reMarkable tablet, which wraps around the standard interface.",
"depends": "rm-button-capture"
},
"data": {
"opt": {
"bin": {
"draft": "build/draft"
},
"etc": {
"draft": "src/extra-files/draft",
"systemd": {
"draft.service": "src/extra-files/draft.service"
}
}
}
},
}
| 105450 | {
"info": {
"package-name": "rm-draft",
"version": "0.3.0",
"maintainer": "<NAME> <<EMAIL>>",
"description": "A launcher for the reMarkable tablet, which wraps around the standard interface.",
"depends": "rm-button-capture"
},
"data": {
"opt": {
"bin": {
"draft": "build/draft"
},
"etc": {
"draft": "src/extra-files/draft",
"systemd": {
"draft.service": "src/extra-files/draft.service"
}
}
}
},
}
| true | {
"info": {
"package-name": "rm-draft",
"version": "0.3.0",
"maintainer": "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>",
"description": "A launcher for the reMarkable tablet, which wraps around the standard interface.",
"depends": "rm-button-capture"
},
"data": {
"opt": {
"bin": {
"draft": "build/draft"
},
"etc": {
"draft": "src/extra-files/draft",
"systemd": {
"draft.service": "src/extra-files/draft.service"
}
}
}
},
}
|
[
{
"context": "& node build.js'\n '''\n API.mail.send\n from: 'sysadmin@cottagelabs.com'\n to: 'mark@cottagelabs.com'\n subject: 'Git",
"end": 671,
"score": 0.999926745891571,
"start": 647,
"tag": "EMAIL",
"value": "sysadmin@cottagelabs.com"
},
{
"context": "end\n from: ... | server/hook.coffee | leviathanindustries/noddy | 2 |
# write any hooks here as endpoints that other services can push events to
API.add 'hook', post: () -> return API.hook this.bodyParams
API.add 'hook/github', post: () -> return API.hook.github this.bodyParams
API.hook = (opts) ->
'''try
ln = opts.repository.full_name.toLowerCase()
br = opts.ref.split('/').pop().toLowerCase()
base = '/home/cloo/' + (if br is 'develop' then 'dev' else 'live') + '/'
if ln in ['cottagelabs/jct', 'cottagelabs/jct_api'] and br in ['develop'] # 'master'
dir = base + 'jct/' + ln.split('/').pop()
cmd = 'git pull origin ' + br + ' && node build.js'
'''
API.mail.send
from: 'sysadmin@cottagelabs.com'
to: 'mark@cottagelabs.com'
subject: 'Githook'
text: JSON.stringify opts, '', 2
return true
# for any github webhook action, catch it and trigger something here, which can be configured in settings
# when these hook URLs are hit, they woudl also need to be called on the specific machine
# that can action them - e.g. the specific dev API machine, or specific local API machine
# and it then controls roll-out to cluster machines where necessary
# https://developer.github.com/webhooks/
# https://developer.github.com/v3/activity/events/types/#pushevent
API.hook.github = (opts) ->
if opts.ref? and opts.repository?
repo = opts.repository.full_name # will be like leviathanindustries/noddy, not just the repo name
if API.settings.hook?.github?[repo]? or API.settings.hook?.github?[repo.split('/').pop()]?
settings = API.settings.hook.github[repo] ? API.settings.hook.github[repo.split('/').pop()]
if opts.ref_type is 'branch' and settings.branches
branch = opts.ref
folder = if settings.branches is true then (if settings[branch]?.folder? then settings[branch].folder else settings.folder + '/' + branch) else settings.branches + '/' + branch
# create the folder for this branch if not existing yet
# if such a folder does not already exist. And then git clone the repo into it
# and then switch to the new branch
else
# for now everything else is assumed to be a git push, requiring a local pull
branch = opts.ref.split('/').pop()
folder = if branch is 'master' then settings.folder else (if settings.branches is true then settings.folder else settings.branches) + '/' + branch
# execute a pull in the specified folder of the branch in question
# move into the folder first if necessary - may also need to create
# also, may need to check out the branch if necessary
# creating branches into folders is designed to allow for lots of different dev versions of sites to be running at different API addresses
# so these different versions may also need the settings out of some other folder - e.g if there is a live site
# running off master, then the live one will have live settings, but if there is a dev site running off develop,
# then there is likely a dev settings file in the local develop folder somewhere, and these won't come with the branch
# pull because settings quite often contain secrets that are only typed in on the running machine.
# so, need a way to pull the right settings file when trying to deploy a branch that isn't master of the main dev one...
# but also needs to work without knowing the name of the branches, as any branch name could be used later
if false
# if the above fails, e.g. there is something in the folder stopping the pull from succeeding,
# catch that info and send a warning somewhere
else if settings.post or settings[branch]?.post?
post = settings.post ? settings[branch].post
# execute whatever command is specified in settings.post, e.g. could be node build.js
# could also be a deploy command, to push the changes out to the cluster
# if the executed command fails, send a warning somewhere
| 123921 |
# write any hooks here as endpoints that other services can push events to
API.add 'hook', post: () -> return API.hook this.bodyParams
API.add 'hook/github', post: () -> return API.hook.github this.bodyParams
API.hook = (opts) ->
'''try
ln = opts.repository.full_name.toLowerCase()
br = opts.ref.split('/').pop().toLowerCase()
base = '/home/cloo/' + (if br is 'develop' then 'dev' else 'live') + '/'
if ln in ['cottagelabs/jct', 'cottagelabs/jct_api'] and br in ['develop'] # 'master'
dir = base + 'jct/' + ln.split('/').pop()
cmd = 'git pull origin ' + br + ' && node build.js'
'''
API.mail.send
from: '<EMAIL>'
to: '<EMAIL>'
subject: 'Githook'
text: JSON.stringify opts, '', 2
return true
# for any github webhook action, catch it and trigger something here, which can be configured in settings
# when these hook URLs are hit, they woudl also need to be called on the specific machine
# that can action them - e.g. the specific dev API machine, or specific local API machine
# and it then controls roll-out to cluster machines where necessary
# https://developer.github.com/webhooks/
# https://developer.github.com/v3/activity/events/types/#pushevent
API.hook.github = (opts) ->
if opts.ref? and opts.repository?
repo = opts.repository.full_name # will be like leviathanindustries/noddy, not just the repo name
if API.settings.hook?.github?[repo]? or API.settings.hook?.github?[repo.split('/').pop()]?
settings = API.settings.hook.github[repo] ? API.settings.hook.github[repo.split('/').pop()]
if opts.ref_type is 'branch' and settings.branches
branch = opts.ref
folder = if settings.branches is true then (if settings[branch]?.folder? then settings[branch].folder else settings.folder + '/' + branch) else settings.branches + '/' + branch
# create the folder for this branch if not existing yet
# if such a folder does not already exist. And then git clone the repo into it
# and then switch to the new branch
else
# for now everything else is assumed to be a git push, requiring a local pull
branch = opts.ref.split('/').pop()
folder = if branch is 'master' then settings.folder else (if settings.branches is true then settings.folder else settings.branches) + '/' + branch
# execute a pull in the specified folder of the branch in question
# move into the folder first if necessary - may also need to create
# also, may need to check out the branch if necessary
# creating branches into folders is designed to allow for lots of different dev versions of sites to be running at different API addresses
# so these different versions may also need the settings out of some other folder - e.g if there is a live site
# running off master, then the live one will have live settings, but if there is a dev site running off develop,
# then there is likely a dev settings file in the local develop folder somewhere, and these won't come with the branch
# pull because settings quite often contain secrets that are only typed in on the running machine.
# so, need a way to pull the right settings file when trying to deploy a branch that isn't master of the main dev one...
# but also needs to work without knowing the name of the branches, as any branch name could be used later
if false
# if the above fails, e.g. there is something in the folder stopping the pull from succeeding,
# catch that info and send a warning somewhere
else if settings.post or settings[branch]?.post?
post = settings.post ? settings[branch].post
# execute whatever command is specified in settings.post, e.g. could be node build.js
# could also be a deploy command, to push the changes out to the cluster
# if the executed command fails, send a warning somewhere
| true |
# write any hooks here as endpoints that other services can push events to
API.add 'hook', post: () -> return API.hook this.bodyParams
API.add 'hook/github', post: () -> return API.hook.github this.bodyParams
API.hook = (opts) ->
'''try
ln = opts.repository.full_name.toLowerCase()
br = opts.ref.split('/').pop().toLowerCase()
base = '/home/cloo/' + (if br is 'develop' then 'dev' else 'live') + '/'
if ln in ['cottagelabs/jct', 'cottagelabs/jct_api'] and br in ['develop'] # 'master'
dir = base + 'jct/' + ln.split('/').pop()
cmd = 'git pull origin ' + br + ' && node build.js'
'''
API.mail.send
from: 'PI:EMAIL:<EMAIL>END_PI'
to: 'PI:EMAIL:<EMAIL>END_PI'
subject: 'Githook'
text: JSON.stringify opts, '', 2
return true
# for any github webhook action, catch it and trigger something here, which can be configured in settings
# when these hook URLs are hit, they woudl also need to be called on the specific machine
# that can action them - e.g. the specific dev API machine, or specific local API machine
# and it then controls roll-out to cluster machines where necessary
# https://developer.github.com/webhooks/
# https://developer.github.com/v3/activity/events/types/#pushevent
API.hook.github = (opts) ->
if opts.ref? and opts.repository?
repo = opts.repository.full_name # will be like leviathanindustries/noddy, not just the repo name
if API.settings.hook?.github?[repo]? or API.settings.hook?.github?[repo.split('/').pop()]?
settings = API.settings.hook.github[repo] ? API.settings.hook.github[repo.split('/').pop()]
if opts.ref_type is 'branch' and settings.branches
branch = opts.ref
folder = if settings.branches is true then (if settings[branch]?.folder? then settings[branch].folder else settings.folder + '/' + branch) else settings.branches + '/' + branch
# create the folder for this branch if not existing yet
# if such a folder does not already exist. And then git clone the repo into it
# and then switch to the new branch
else
# for now everything else is assumed to be a git push, requiring a local pull
branch = opts.ref.split('/').pop()
folder = if branch is 'master' then settings.folder else (if settings.branches is true then settings.folder else settings.branches) + '/' + branch
# execute a pull in the specified folder of the branch in question
# move into the folder first if necessary - may also need to create
# also, may need to check out the branch if necessary
# creating branches into folders is designed to allow for lots of different dev versions of sites to be running at different API addresses
# so these different versions may also need the settings out of some other folder - e.g if there is a live site
# running off master, then the live one will have live settings, but if there is a dev site running off develop,
# then there is likely a dev settings file in the local develop folder somewhere, and these won't come with the branch
# pull because settings quite often contain secrets that are only typed in on the running machine.
# so, need a way to pull the right settings file when trying to deploy a branch that isn't master of the main dev one...
# but also needs to work without knowing the name of the branches, as any branch name could be used later
if false
# if the above fails, e.g. there is something in the folder stopping the pull from succeeding,
# catch that info and send a warning somewhere
else if settings.post or settings[branch]?.post?
post = settings.post ? settings[branch].post
# execute whatever command is specified in settings.post, e.g. could be node build.js
# could also be a deploy command, to push the changes out to the cluster
# if the executed command fails, send a warning somewhere
|
[
{
"context": "true\n ipa:\n principal: 'admin'\n password: 'admin_pw'\n # referer: 'https://freeipa.nikita.local/ipa",
"end": 93,
"score": 0.9991524815559387,
"start": 85,
"tag": "PASSWORD",
"value": "admin_pw"
},
{
"context": "sh: [\n null\n ,\n sudo: true\n ssh:... | packages/ipa/env/ipa/test.coffee | DanielJohnHarty/node-nikita | 1 |
module.exports =
tags:
ipa: true
ipa:
principal: 'admin'
password: 'admin_pw'
# referer: 'https://freeipa.nikita.local/ipa/xml'
url: 'https://freeipa.nikita.local/ipa/session/json'
ssh: [
null
,
sudo: true
ssh: host: '127.0.0.1', username: 'nikita'
]
| 10399 |
module.exports =
tags:
ipa: true
ipa:
principal: 'admin'
password: '<PASSWORD>'
# referer: 'https://freeipa.nikita.local/ipa/xml'
url: 'https://freeipa.nikita.local/ipa/session/json'
ssh: [
null
,
sudo: true
ssh: host: '127.0.0.1', username: 'nikita'
]
| true |
module.exports =
tags:
ipa: true
ipa:
principal: 'admin'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
# referer: 'https://freeipa.nikita.local/ipa/xml'
url: 'https://freeipa.nikita.local/ipa/session/json'
ssh: [
null
,
sudo: true
ssh: host: '127.0.0.1', username: 'nikita'
]
|
[
{
"context": "0].get 'name'\n assert.equal name.first, \"John\"\n name.first = 'WRONG NAME'\n cb",
"end": 1253,
"score": 0.9998026490211487,
"start": 1249,
"tag": "NAME",
"value": "John"
},
{
"context": "0].get 'name'\n assert.equal name.first, \"J... | test/mock.coffee | Clever/clever-js | 10 | _ = require 'underscore'
assert = require 'assert'
async = require 'async'
Clever = require "#{__dirname}/../index"
highland = require 'highland'
describe "require('clever/mock') [API KEY] [MOCK DATA DIR]", ->
before ->
@clever = require("#{__dirname}/../mock") 'api key', "#{__dirname}/mock_data"
it "supports streaming GETs", (done) ->
highland(@clever.Student.find().stream()).invoke("toJSON").collect().toCallback (err, data) ->
assert.ifError err
assert.deepEqual data, require("#{__dirname}/mock_data/students")
done()
it "supports count", (done) ->
@clever.Student.find().count().exec (err, count) ->
assert.ifError err
assert.equal count, require("#{__dirname}/mock_data/students").length
done()
it "supports non-streaming GETs", (done) ->
@clever.Student.find().exec (err, data) ->
assert.ifError err
assert.deepEqual _(data).invoke('toJSON'), require("#{__dirname}/mock_data/students")
done()
it "deep copies data", (done) ->
async.waterfall [
(cb_wf) =>
@clever.Student.find().exec (err, students) ->
assert.ifError err
name = students[0].get 'name'
assert.equal name.first, "John"
name.first = 'WRONG NAME'
cb_wf()
(cb_wf) =>
@clever.Student.find().exec (err, students) ->
assert.ifError err
name = students[0].get 'name'
assert.equal name.first, "John"
cb_wf()
], done
describe 'findById', ->
_.each ['51a5a56f4867bbdf51054055', '51a5a56f4867bbdf51054054'], (id) ->
it "finds a student", (done) ->
@clever.Student.findById id, (err, student) ->
assert.ifError err
assert.equal student.get('id'), id
done()
it "returns undefined if the id is not found", (done) ->
@clever.Student.findById 'not an existing id', (err, student) ->
assert.ifError err
assert not student, 'Expected student to be undefined'
done()
| 81438 | _ = require 'underscore'
assert = require 'assert'
async = require 'async'
Clever = require "#{__dirname}/../index"
highland = require 'highland'
describe "require('clever/mock') [API KEY] [MOCK DATA DIR]", ->
before ->
@clever = require("#{__dirname}/../mock") 'api key', "#{__dirname}/mock_data"
it "supports streaming GETs", (done) ->
highland(@clever.Student.find().stream()).invoke("toJSON").collect().toCallback (err, data) ->
assert.ifError err
assert.deepEqual data, require("#{__dirname}/mock_data/students")
done()
it "supports count", (done) ->
@clever.Student.find().count().exec (err, count) ->
assert.ifError err
assert.equal count, require("#{__dirname}/mock_data/students").length
done()
it "supports non-streaming GETs", (done) ->
@clever.Student.find().exec (err, data) ->
assert.ifError err
assert.deepEqual _(data).invoke('toJSON'), require("#{__dirname}/mock_data/students")
done()
it "deep copies data", (done) ->
async.waterfall [
(cb_wf) =>
@clever.Student.find().exec (err, students) ->
assert.ifError err
name = students[0].get 'name'
assert.equal name.first, "<NAME>"
name.first = 'WRONG NAME'
cb_wf()
(cb_wf) =>
@clever.Student.find().exec (err, students) ->
assert.ifError err
name = students[0].get 'name'
assert.equal name.first, "<NAME>"
cb_wf()
], done
describe 'findById', ->
_.each ['51a5a56f4867bbdf51054055', '51a5a56f4867bbdf51054054'], (id) ->
it "finds a student", (done) ->
@clever.Student.findById id, (err, student) ->
assert.ifError err
assert.equal student.get('id'), id
done()
it "returns undefined if the id is not found", (done) ->
@clever.Student.findById 'not an existing id', (err, student) ->
assert.ifError err
assert not student, 'Expected student to be undefined'
done()
| true | _ = require 'underscore'
assert = require 'assert'
async = require 'async'
Clever = require "#{__dirname}/../index"
highland = require 'highland'
describe "require('clever/mock') [API KEY] [MOCK DATA DIR]", ->
before ->
@clever = require("#{__dirname}/../mock") 'api key', "#{__dirname}/mock_data"
it "supports streaming GETs", (done) ->
highland(@clever.Student.find().stream()).invoke("toJSON").collect().toCallback (err, data) ->
assert.ifError err
assert.deepEqual data, require("#{__dirname}/mock_data/students")
done()
it "supports count", (done) ->
@clever.Student.find().count().exec (err, count) ->
assert.ifError err
assert.equal count, require("#{__dirname}/mock_data/students").length
done()
it "supports non-streaming GETs", (done) ->
@clever.Student.find().exec (err, data) ->
assert.ifError err
assert.deepEqual _(data).invoke('toJSON'), require("#{__dirname}/mock_data/students")
done()
it "deep copies data", (done) ->
async.waterfall [
(cb_wf) =>
@clever.Student.find().exec (err, students) ->
assert.ifError err
name = students[0].get 'name'
assert.equal name.first, "PI:NAME:<NAME>END_PI"
name.first = 'WRONG NAME'
cb_wf()
(cb_wf) =>
@clever.Student.find().exec (err, students) ->
assert.ifError err
name = students[0].get 'name'
assert.equal name.first, "PI:NAME:<NAME>END_PI"
cb_wf()
], done
describe 'findById', ->
_.each ['51a5a56f4867bbdf51054055', '51a5a56f4867bbdf51054054'], (id) ->
it "finds a student", (done) ->
@clever.Student.findById id, (err, student) ->
assert.ifError err
assert.equal student.get('id'), id
done()
it "returns undefined if the id is not found", (done) ->
@clever.Student.findById 'not an existing id', (err, student) ->
assert.ifError err
assert not student, 'Expected student to be undefined'
done()
|
[
{
"context": "s: { type: 'string' }\n }\n }\n data = { name: 'Bob', numbers: ['401-401-1337', ['123-456-7890']], 'a",
"end": 620,
"score": 0.9998031258583069,
"start": 617,
"tag": "NAME",
"value": "Bob"
}
] | test/keyboard/arrow-keys.coffee | lgr7/codecombattreema | 66 | do ->
leftArrowPress = ($el) -> keyDown($el, 37)
upArrowPress = ($el) -> keyDown($el, 38)
rightArrowPress = ($el) -> keyDown($el, 39)
downArrowPress = ($el) -> keyDown($el, 40)
expectOneSelected = (t) ->
selected = treema.getSelectedTreemas()
expect(selected.length).toBe(1)
expect(t).toBeDefined()
expect(selected[0].$el[0]).toBe(t.$el[0]) if t and selected.length is 1
schema = {
type: 'object',
properties: {
name: { type: 'string' }
numbers: { type: 'array', items: { type: ['string', 'array'] } }
address: { type: 'string' }
}
}
data = { name: 'Bob', numbers: ['401-401-1337', ['123-456-7890']], 'address': 'Mars' }
treema = TreemaNode.make(null, {data: data, schema: schema})
treema.build()
nameTreema = treema.childrenTreemas.name
phoneTreema = treema.childrenTreemas.numbers
addressTreema = treema.childrenTreemas.address
beforeEach ->
treema.deselectAll()
phoneTreema.close()
describe 'Down arrow key press', ->
it 'selects the top row if nothing is selected', ->
expect(treema.getSelectedTreemas().length).toBe(0)
downArrowPress(treema.$el)
expect(nameTreema.isSelected()).toBeTruthy()
it 'skips past closed collections', ->
expect(treema.getSelectedTreemas().length).toBe(0)
downArrowPress(treema.$el)
expectOneSelected(nameTreema)
downArrowPress(treema.$el)
expectOneSelected(phoneTreema)
downArrowPress(treema.$el)
expectOneSelected(addressTreema)
it 'traverses open collections', ->
expect(treema.getSelectedTreemas().length).toBe(0)
phoneTreema.open()
downArrowPress(treema.$el)
expectOneSelected(nameTreema)
downArrowPress(treema.$el)
expectOneSelected(phoneTreema)
downArrowPress(treema.$el)
expectOneSelected(phoneTreema.childrenTreemas[0])
# downArrowPress(treema.$el)
# expectOneSelected(phoneTreema.childrenTreemas[1])
# downArrowPress(treema.$el)
# expectOneSelected(addressTreema)
it 'does nothing if the last treema is selected', ->
expect(treema.getSelectedTreemas().length).toBe(0)
addressTreema.select()
expectOneSelected(addressTreema)
downArrowPress(treema.$el)
expectOneSelected(nameTreema)
describe 'Up arrow key press', ->
it 'selects the bottom row if nothing is selected', ->
expect(treema.getSelectedTreemas().length).toBe(0)
upArrowPress(treema.$el)
expect(addressTreema.isSelected()).toBeTruthy()
it 'skips past closed collections', ->
expect(treema.getSelectedTreemas().length).toBe(0)
upArrowPress(treema.$el)
expectOneSelected(addressTreema)
upArrowPress(treema.$el)
expectOneSelected(phoneTreema)
upArrowPress(treema.$el)
expectOneSelected(nameTreema)
it 'traverses open collections', ->
expect(treema.getSelectedTreemas().length).toBe(0)
phoneTreema.open()
upArrowPress(treema.$el)
expectOneSelected(addressTreema)
upArrowPress(treema.$el)
expectOneSelected(phoneTreema.childrenTreemas[1])
upArrowPress(treema.$el)
expectOneSelected(phoneTreema.childrenTreemas[0])
upArrowPress(treema.$el)
expectOneSelected(phoneTreema)
upArrowPress(treema.$el)
expectOneSelected(nameTreema)
it 'wraps around if the first treema is selected', ->
nameTreema.select()
expectOneSelected(nameTreema)
upArrowPress(treema.$el)
expectOneSelected(addressTreema)
describe 'Right arrow key press', ->
it 'does nothing if the selected row isn\'t a collection', ->
nameTreema.select()
expectOneSelected(nameTreema)
rightArrowPress(treema.$el)
expectOneSelected(nameTreema)
it 'opens a collection if a collection is selected', ->
expect(phoneTreema.isClosed()).toBeTruthy()
phoneTreema.select()
rightArrowPress(treema.$el)
expect(phoneTreema.isOpen()).toBeTruthy()
expectOneSelected(phoneTreema)
describe 'Left arrow key press', ->
it 'closes an open, selected collection', ->
phoneTreema.open()
phoneTreema.select()
leftArrowPress(treema.$el)
expect(phoneTreema.isClosed()).toBeTruthy()
expectOneSelected(phoneTreema)
it 'closes the selection if it can be closed, otherwise moves the selection up a level', ->
phoneTreema.open()
phoneTreema.childrenTreemas[0].select()
leftArrowPress(treema.$el)
expect(phoneTreema.isOpen()).toBeTruthy()
expectOneSelected(phoneTreema)
leftArrowPress(treema.$el)
expect(phoneTreema.isClosed()).toBeTruthy()
expectOneSelected(phoneTreema)
it 'affects one collection at a time, deepest first', ->
phoneTreema.open()
phoneTreema.childrenTreemas[1].open()
phoneTreema.childrenTreemas[1].childrenTreemas[0].select()
leftArrowPress(treema.$el)
expect(phoneTreema.childrenTreemas[1].isOpen()).toBeTruthy()
expect(phoneTreema.isOpen()).toBeTruthy()
expectOneSelected(phoneTreema.childrenTreemas[1])
leftArrowPress(treema.$el)
expect(phoneTreema.childrenTreemas[1].isClosed()).toBeTruthy()
expect(phoneTreema.isOpen()).toBeTruthy()
expectOneSelected(phoneTreema.childrenTreemas[1])
leftArrowPress(treema.$el)
expect(phoneTreema.isOpen()).toBeTruthy()
expectOneSelected(phoneTreema)
leftArrowPress(treema.$el)
expect(phoneTreema.isClosed()).toBeTruthy()
expectOneSelected(phoneTreema) | 169869 | do ->
leftArrowPress = ($el) -> keyDown($el, 37)
upArrowPress = ($el) -> keyDown($el, 38)
rightArrowPress = ($el) -> keyDown($el, 39)
downArrowPress = ($el) -> keyDown($el, 40)
expectOneSelected = (t) ->
selected = treema.getSelectedTreemas()
expect(selected.length).toBe(1)
expect(t).toBeDefined()
expect(selected[0].$el[0]).toBe(t.$el[0]) if t and selected.length is 1
schema = {
type: 'object',
properties: {
name: { type: 'string' }
numbers: { type: 'array', items: { type: ['string', 'array'] } }
address: { type: 'string' }
}
}
data = { name: '<NAME>', numbers: ['401-401-1337', ['123-456-7890']], 'address': 'Mars' }
treema = TreemaNode.make(null, {data: data, schema: schema})
treema.build()
nameTreema = treema.childrenTreemas.name
phoneTreema = treema.childrenTreemas.numbers
addressTreema = treema.childrenTreemas.address
beforeEach ->
treema.deselectAll()
phoneTreema.close()
describe 'Down arrow key press', ->
it 'selects the top row if nothing is selected', ->
expect(treema.getSelectedTreemas().length).toBe(0)
downArrowPress(treema.$el)
expect(nameTreema.isSelected()).toBeTruthy()
it 'skips past closed collections', ->
expect(treema.getSelectedTreemas().length).toBe(0)
downArrowPress(treema.$el)
expectOneSelected(nameTreema)
downArrowPress(treema.$el)
expectOneSelected(phoneTreema)
downArrowPress(treema.$el)
expectOneSelected(addressTreema)
it 'traverses open collections', ->
expect(treema.getSelectedTreemas().length).toBe(0)
phoneTreema.open()
downArrowPress(treema.$el)
expectOneSelected(nameTreema)
downArrowPress(treema.$el)
expectOneSelected(phoneTreema)
downArrowPress(treema.$el)
expectOneSelected(phoneTreema.childrenTreemas[0])
# downArrowPress(treema.$el)
# expectOneSelected(phoneTreema.childrenTreemas[1])
# downArrowPress(treema.$el)
# expectOneSelected(addressTreema)
it 'does nothing if the last treema is selected', ->
expect(treema.getSelectedTreemas().length).toBe(0)
addressTreema.select()
expectOneSelected(addressTreema)
downArrowPress(treema.$el)
expectOneSelected(nameTreema)
describe 'Up arrow key press', ->
it 'selects the bottom row if nothing is selected', ->
expect(treema.getSelectedTreemas().length).toBe(0)
upArrowPress(treema.$el)
expect(addressTreema.isSelected()).toBeTruthy()
it 'skips past closed collections', ->
expect(treema.getSelectedTreemas().length).toBe(0)
upArrowPress(treema.$el)
expectOneSelected(addressTreema)
upArrowPress(treema.$el)
expectOneSelected(phoneTreema)
upArrowPress(treema.$el)
expectOneSelected(nameTreema)
it 'traverses open collections', ->
expect(treema.getSelectedTreemas().length).toBe(0)
phoneTreema.open()
upArrowPress(treema.$el)
expectOneSelected(addressTreema)
upArrowPress(treema.$el)
expectOneSelected(phoneTreema.childrenTreemas[1])
upArrowPress(treema.$el)
expectOneSelected(phoneTreema.childrenTreemas[0])
upArrowPress(treema.$el)
expectOneSelected(phoneTreema)
upArrowPress(treema.$el)
expectOneSelected(nameTreema)
it 'wraps around if the first treema is selected', ->
nameTreema.select()
expectOneSelected(nameTreema)
upArrowPress(treema.$el)
expectOneSelected(addressTreema)
describe 'Right arrow key press', ->
it 'does nothing if the selected row isn\'t a collection', ->
nameTreema.select()
expectOneSelected(nameTreema)
rightArrowPress(treema.$el)
expectOneSelected(nameTreema)
it 'opens a collection if a collection is selected', ->
expect(phoneTreema.isClosed()).toBeTruthy()
phoneTreema.select()
rightArrowPress(treema.$el)
expect(phoneTreema.isOpen()).toBeTruthy()
expectOneSelected(phoneTreema)
describe 'Left arrow key press', ->
it 'closes an open, selected collection', ->
phoneTreema.open()
phoneTreema.select()
leftArrowPress(treema.$el)
expect(phoneTreema.isClosed()).toBeTruthy()
expectOneSelected(phoneTreema)
it 'closes the selection if it can be closed, otherwise moves the selection up a level', ->
phoneTreema.open()
phoneTreema.childrenTreemas[0].select()
leftArrowPress(treema.$el)
expect(phoneTreema.isOpen()).toBeTruthy()
expectOneSelected(phoneTreema)
leftArrowPress(treema.$el)
expect(phoneTreema.isClosed()).toBeTruthy()
expectOneSelected(phoneTreema)
it 'affects one collection at a time, deepest first', ->
phoneTreema.open()
phoneTreema.childrenTreemas[1].open()
phoneTreema.childrenTreemas[1].childrenTreemas[0].select()
leftArrowPress(treema.$el)
expect(phoneTreema.childrenTreemas[1].isOpen()).toBeTruthy()
expect(phoneTreema.isOpen()).toBeTruthy()
expectOneSelected(phoneTreema.childrenTreemas[1])
leftArrowPress(treema.$el)
expect(phoneTreema.childrenTreemas[1].isClosed()).toBeTruthy()
expect(phoneTreema.isOpen()).toBeTruthy()
expectOneSelected(phoneTreema.childrenTreemas[1])
leftArrowPress(treema.$el)
expect(phoneTreema.isOpen()).toBeTruthy()
expectOneSelected(phoneTreema)
leftArrowPress(treema.$el)
expect(phoneTreema.isClosed()).toBeTruthy()
expectOneSelected(phoneTreema) | true | do ->
leftArrowPress = ($el) -> keyDown($el, 37)
upArrowPress = ($el) -> keyDown($el, 38)
rightArrowPress = ($el) -> keyDown($el, 39)
downArrowPress = ($el) -> keyDown($el, 40)
expectOneSelected = (t) ->
selected = treema.getSelectedTreemas()
expect(selected.length).toBe(1)
expect(t).toBeDefined()
expect(selected[0].$el[0]).toBe(t.$el[0]) if t and selected.length is 1
schema = {
type: 'object',
properties: {
name: { type: 'string' }
numbers: { type: 'array', items: { type: ['string', 'array'] } }
address: { type: 'string' }
}
}
data = { name: 'PI:NAME:<NAME>END_PI', numbers: ['401-401-1337', ['123-456-7890']], 'address': 'Mars' }
treema = TreemaNode.make(null, {data: data, schema: schema})
treema.build()
nameTreema = treema.childrenTreemas.name
phoneTreema = treema.childrenTreemas.numbers
addressTreema = treema.childrenTreemas.address
beforeEach ->
treema.deselectAll()
phoneTreema.close()
describe 'Down arrow key press', ->
it 'selects the top row if nothing is selected', ->
expect(treema.getSelectedTreemas().length).toBe(0)
downArrowPress(treema.$el)
expect(nameTreema.isSelected()).toBeTruthy()
it 'skips past closed collections', ->
expect(treema.getSelectedTreemas().length).toBe(0)
downArrowPress(treema.$el)
expectOneSelected(nameTreema)
downArrowPress(treema.$el)
expectOneSelected(phoneTreema)
downArrowPress(treema.$el)
expectOneSelected(addressTreema)
it 'traverses open collections', ->
expect(treema.getSelectedTreemas().length).toBe(0)
phoneTreema.open()
downArrowPress(treema.$el)
expectOneSelected(nameTreema)
downArrowPress(treema.$el)
expectOneSelected(phoneTreema)
downArrowPress(treema.$el)
expectOneSelected(phoneTreema.childrenTreemas[0])
# downArrowPress(treema.$el)
# expectOneSelected(phoneTreema.childrenTreemas[1])
# downArrowPress(treema.$el)
# expectOneSelected(addressTreema)
it 'does nothing if the last treema is selected', ->
expect(treema.getSelectedTreemas().length).toBe(0)
addressTreema.select()
expectOneSelected(addressTreema)
downArrowPress(treema.$el)
expectOneSelected(nameTreema)
describe 'Up arrow key press', ->
it 'selects the bottom row if nothing is selected', ->
expect(treema.getSelectedTreemas().length).toBe(0)
upArrowPress(treema.$el)
expect(addressTreema.isSelected()).toBeTruthy()
it 'skips past closed collections', ->
expect(treema.getSelectedTreemas().length).toBe(0)
upArrowPress(treema.$el)
expectOneSelected(addressTreema)
upArrowPress(treema.$el)
expectOneSelected(phoneTreema)
upArrowPress(treema.$el)
expectOneSelected(nameTreema)
it 'traverses open collections', ->
expect(treema.getSelectedTreemas().length).toBe(0)
phoneTreema.open()
upArrowPress(treema.$el)
expectOneSelected(addressTreema)
upArrowPress(treema.$el)
expectOneSelected(phoneTreema.childrenTreemas[1])
upArrowPress(treema.$el)
expectOneSelected(phoneTreema.childrenTreemas[0])
upArrowPress(treema.$el)
expectOneSelected(phoneTreema)
upArrowPress(treema.$el)
expectOneSelected(nameTreema)
it 'wraps around if the first treema is selected', ->
nameTreema.select()
expectOneSelected(nameTreema)
upArrowPress(treema.$el)
expectOneSelected(addressTreema)
describe 'Right arrow key press', ->
it 'does nothing if the selected row isn\'t a collection', ->
nameTreema.select()
expectOneSelected(nameTreema)
rightArrowPress(treema.$el)
expectOneSelected(nameTreema)
it 'opens a collection if a collection is selected', ->
expect(phoneTreema.isClosed()).toBeTruthy()
phoneTreema.select()
rightArrowPress(treema.$el)
expect(phoneTreema.isOpen()).toBeTruthy()
expectOneSelected(phoneTreema)
describe 'Left arrow key press', ->
it 'closes an open, selected collection', ->
phoneTreema.open()
phoneTreema.select()
leftArrowPress(treema.$el)
expect(phoneTreema.isClosed()).toBeTruthy()
expectOneSelected(phoneTreema)
it 'closes the selection if it can be closed, otherwise moves the selection up a level', ->
phoneTreema.open()
phoneTreema.childrenTreemas[0].select()
leftArrowPress(treema.$el)
expect(phoneTreema.isOpen()).toBeTruthy()
expectOneSelected(phoneTreema)
leftArrowPress(treema.$el)
expect(phoneTreema.isClosed()).toBeTruthy()
expectOneSelected(phoneTreema)
it 'affects one collection at a time, deepest first', ->
phoneTreema.open()
phoneTreema.childrenTreemas[1].open()
phoneTreema.childrenTreemas[1].childrenTreemas[0].select()
leftArrowPress(treema.$el)
expect(phoneTreema.childrenTreemas[1].isOpen()).toBeTruthy()
expect(phoneTreema.isOpen()).toBeTruthy()
expectOneSelected(phoneTreema.childrenTreemas[1])
leftArrowPress(treema.$el)
expect(phoneTreema.childrenTreemas[1].isClosed()).toBeTruthy()
expect(phoneTreema.isOpen()).toBeTruthy()
expectOneSelected(phoneTreema.childrenTreemas[1])
leftArrowPress(treema.$el)
expect(phoneTreema.isOpen()).toBeTruthy()
expectOneSelected(phoneTreema)
leftArrowPress(treema.$el)
expect(phoneTreema.isClosed()).toBeTruthy()
expectOneSelected(phoneTreema) |
[
{
"context": "Url = \"http://fanyi.youdao.com\"\nconfig.keyfrom = \"fanyiweb\"\nconfig.key = null\nconfig.translate = \"on\"\n",
"end": 206,
"score": 0.9992896318435669,
"start": 198,
"tag": "KEY",
"value": "fanyiweb"
}
] | public/src/coffee/common/config.coffee | chenqunfeng/CQFWord | 0 | config = exports
config.url = "http://fanyi.youdao.com/openapi.do"
config.type = "data"
config.doctype = "json"
config.version = 1.1
config.relatedUrl = "http://fanyi.youdao.com"
config.keyfrom = "fanyiweb"
config.key = null
config.translate = "on"
| 142080 | config = exports
config.url = "http://fanyi.youdao.com/openapi.do"
config.type = "data"
config.doctype = "json"
config.version = 1.1
config.relatedUrl = "http://fanyi.youdao.com"
config.keyfrom = "<KEY>"
config.key = null
config.translate = "on"
| true | config = exports
config.url = "http://fanyi.youdao.com/openapi.do"
config.type = "data"
config.doctype = "json"
config.version = 1.1
config.relatedUrl = "http://fanyi.youdao.com"
config.keyfrom = "PI:KEY:<KEY>END_PI"
config.key = null
config.translate = "on"
|
[
{
"context": "#\n# grunt-jinja\n# https://github.com/matthewwithanm/grunt-jinja\n#\n# Copyright (c) 2013 Matthew Trette",
"end": 51,
"score": 0.9995275139808655,
"start": 37,
"tag": "USERNAME",
"value": "matthewwithanm"
},
{
"context": "/matthewwithanm/grunt-jinja\n#\n# Copyright (c)... | Gruntfile.coffee | gruntjs-updater/grunt-jinja-extend | 0 | #
# grunt-jinja
# https://github.com/matthewwithanm/grunt-jinja
#
# Copyright (c) 2013 Matthew Tretter
# Licensed under the MIT license.
#
path = require 'path'
module.exports = (grunt) ->
# Project configuration.
grunt.initConfig
# Before generating any new files, remove any previously-created files.
clean:
tests: ['tmp']
# Configuration to be run (and then tested).
jinja:
simple:
options:
templateDirs: [path.join __dirname, 'test/fixtures/simple/']
files:
'tmp/simple/index.html': 'test/fixtures/simple/index.html'
context:
options:
templateDirs: [path.join __dirname, 'test/fixtures/context/templates/']
contextRoot: path.join __dirname, 'test/fixtures/context/template-context/'
files:
'tmp/context/index.html': 'test/fixtures/context/templates/index.html'
# Unit tests.
nodeunit:
tests: ['test/*_test.*']
# Actually load this plugin's task(s).
grunt.loadTasks 'tasks'
# These plugins provide necessary tasks.
grunt.loadNpmTasks 'grunt-contrib-clean'
grunt.loadNpmTasks 'grunt-contrib-nodeunit'
# Whenever the "test" task is run, first clean the "tmp" dir, then run this
# plugin's task(s), then test the result.
grunt.registerTask 'test', ['clean', 'jinja', 'nodeunit']
# By default, lint and run all tests.
grunt.registerTask 'default', ['test']
| 4663 | #
# grunt-jinja
# https://github.com/matthewwithanm/grunt-jinja
#
# Copyright (c) 2013 <NAME>
# Licensed under the MIT license.
#
path = require 'path'
module.exports = (grunt) ->
# Project configuration.
grunt.initConfig
# Before generating any new files, remove any previously-created files.
clean:
tests: ['tmp']
# Configuration to be run (and then tested).
jinja:
simple:
options:
templateDirs: [path.join __dirname, 'test/fixtures/simple/']
files:
'tmp/simple/index.html': 'test/fixtures/simple/index.html'
context:
options:
templateDirs: [path.join __dirname, 'test/fixtures/context/templates/']
contextRoot: path.join __dirname, 'test/fixtures/context/template-context/'
files:
'tmp/context/index.html': 'test/fixtures/context/templates/index.html'
# Unit tests.
nodeunit:
tests: ['test/*_test.*']
# Actually load this plugin's task(s).
grunt.loadTasks 'tasks'
# These plugins provide necessary tasks.
grunt.loadNpmTasks 'grunt-contrib-clean'
grunt.loadNpmTasks 'grunt-contrib-nodeunit'
# Whenever the "test" task is run, first clean the "tmp" dir, then run this
# plugin's task(s), then test the result.
grunt.registerTask 'test', ['clean', 'jinja', 'nodeunit']
# By default, lint and run all tests.
grunt.registerTask 'default', ['test']
| true | #
# grunt-jinja
# https://github.com/matthewwithanm/grunt-jinja
#
# Copyright (c) 2013 PI:NAME:<NAME>END_PI
# Licensed under the MIT license.
#
path = require 'path'
module.exports = (grunt) ->
# Project configuration.
grunt.initConfig
# Before generating any new files, remove any previously-created files.
clean:
tests: ['tmp']
# Configuration to be run (and then tested).
jinja:
simple:
options:
templateDirs: [path.join __dirname, 'test/fixtures/simple/']
files:
'tmp/simple/index.html': 'test/fixtures/simple/index.html'
context:
options:
templateDirs: [path.join __dirname, 'test/fixtures/context/templates/']
contextRoot: path.join __dirname, 'test/fixtures/context/template-context/'
files:
'tmp/context/index.html': 'test/fixtures/context/templates/index.html'
# Unit tests.
nodeunit:
tests: ['test/*_test.*']
# Actually load this plugin's task(s).
grunt.loadTasks 'tasks'
# These plugins provide necessary tasks.
grunt.loadNpmTasks 'grunt-contrib-clean'
grunt.loadNpmTasks 'grunt-contrib-nodeunit'
# Whenever the "test" task is run, first clean the "tmp" dir, then run this
# plugin's task(s), then test the result.
grunt.registerTask 'test', ['clean', 'jinja', 'nodeunit']
# By default, lint and run all tests.
grunt.registerTask 'default', ['test']
|
[
{
"context": "###\n# Victor Loux <v.loux@qmul.ac.uk\n###\n\n\n### UTILITY FUNCTION & V",
"end": 17,
"score": 0.9998637437820435,
"start": 6,
"tag": "NAME",
"value": "Victor Loux"
},
{
"context": "###\n# Victor Loux <v.loux@qmul.ac.uk\n###\n\n\n### UTILITY FUNCTION & VARIABLES ###\n\n... | js/index.coffee | victorloux/data-audio-workstation | 1 | ###
# Victor Loux <v.loux@qmul.ac.uk
###
### UTILITY FUNCTION & VARIABLES ###
# Status
isLoading = true
stopped = true
nextTimeout = null
# Tracks the current position
currentBeat = 0
totalBeats = 29
speed = 1/4
velocity = 127
# This will hold our list of instruments & datasets
instrumentList = datasetList = null
###*
* Re-maps a number from one range to another.
* Equivalent to the map function in Arduino and Processing
###
mapTo = (value, inMin, inMax, outMin, outMax, capped = false) ->
newVal = (value - inMin) * (outMax - outMin) / (inMax - inMin) + outMin
if capped
if newVal > outMax then newVal = outMax
if newVal < outMin then newVal = outMin
return newVal
###*
* Starts and stops the loading indicator at the top, and set a 'lock'
* variable that will prevent playback until things are loaded
###
startLoadingIndicator = ->
isLoading = true
$(".loaded-indicator").removeClass("loaded").text "Loading…"
$('body').css('cursor', 'wait')
stopLoadingIndicator = ->
isLoading = false
$(".loaded-indicator").addClass("loaded").text "All loaded."
$('body').css('cursor', 'default')
###*
* Dynamically loads an instrument from the soundfont directory
* @param {string} instrumentName Name of the instrument as in the soundfont
###
loadInstrument = (instrumentName) ->
MIDI.loadResource
instrument: instrumentName
onprogress: (state, progress) ->
startLoadingIndicator()
# console.log state, progress
onsuccess: ->
stopLoadingIndicator()
###*
* Dynamically loads a dataset, and then fills a table in the current track
* @param {string} datasetName Name of the JSON dataset
* @param {DOMObject} track Track <article> where the table should be added
###
loadDataset = (datasetName, track) ->
$.getJSON "data/#{ datasetName }.json", (data) ->
# Empty the current table
track.find(".data").empty()
# Take the first item and figure out the keys available
# in this dataset. (normally all items will be the
# same length/have the same properties).
fields = _.keys(data[0])
i = 0
# For every field we have
for fieldName in fields
# For all items in data, this gets
# the value of array items that have this field name
values = _.pluck(data, fieldName)
# create a <tr> (table row)
tr = $("<tr>")
# Add a header to that row
# (th = table header, will be ignored when reading)
tr.append "<th><span>#{fieldName}</span></th>"
# For each value, wrap it in <td> tags (a cell)
# and append the whole thing to our tr
tr.append(_.map values, (item) ->
return "<td><span>#{item}</span></td>")
# add some data to this, while we have the values
# eg the min/max possible value, this will be useful later
# for mapping a value to a note
# but first convert all to numeric
values = _.map values, (item) ->
return Number.parseFloat item, 10
tr.attr("data-max", _.max(values))
tr.attr("data-min", _.min(values))
# Always highlight the 2nd (index 1) row
if i == 1
tr.find("th").addClass("currentRow")
# then add all this to the .data table
track.find(".data").append(tr)
i++
track.find("[name='skip']").trigger("change")
#also recalculate the height of headers
# (because they're positioned absolutely and not statically in CSS,
# their height is not modified)
# 190 (height of a track) divided by the number of headers
headers = track.find('th')
numberOfHeaders = headers.length
headers.css({
"height": (190 / numberOfHeaders) + "px"
"line-height": (190 / numberOfHeaders) + "px"
})
# we trigger a scroll event, to make sure the controls are re-positioned
$(window).scroll()
setSkipValue = (skipValue, track) ->
track.find(".data td.skip").remove() # reset skipped beats
newCells = Array(skipValue + 1).join("""<td class="skip"></td>""")
track.find(".data td").after(newCells)
track.find(".skip-numeric").text(skipValue)
updateTotalBeatsCount()
setShiftValue = (shiftValue, track) ->
# reset shifted beats
track.find(".data td.shifted-positive").remove()
track.find(".data-shifted-negative tr").each (i) ->
$(this).find("td").insertAfter(track.find(".data tr:eq(#{i}) th"))
track.find(".data-shifted-negative").empty()
# if we shift positively, add new cells at the beginning to the row
# these will work the same as skipped beats
if shiftValue > 0
newCells = Array(shiftValue + 1).join("""<td class="shifted-positive"></td>""")
track.find(".data th").after(newCells)
# if we shift negatively, then virtually delete these beats
else if shiftValue < 0
# find the n first cells in each row, for this
# slice the selection; and abs() because shiftValue is negative
# then move them to the .data table
track.find(".data tr").each (i) ->
cells = $(this).find("td").slice(0, Math.abs(shiftValue))
track.find(".data-shifted-negative").append("<tr>")
cells.appendTo(track.find(".data-shifted-negative tr").filter(":last"))
# update the numeric counter (easier to see than the range slider)
if shiftValue > 0 then shiftValue = "+" + shiftValue # add a + if >0
track.find(".shift-numeric").text(shiftValue)
updateTotalBeatsCount()
addTrack = ->
track = $("""
<article class="track">
<div class="controls">
<a href="#" class="delete"><span class="icon icon-bin"></span></a>
<select name="datasets"></select>
<label>
<span>Instrument</span>
<select name="instruments"></select>
</label>
<label>
<span>Conversion</span>
<select name="conversion">
<option value="chord">Chord conversion</option>
<option value="scale">Map on a scale</option>
<option value="map_value">Map to note</option>
<option value="direct_to_midi">Direct to MIDI</option>
</select>
</label>
<label>
<span>Velocity</span>
<input type="range" min="0" max="127" value="127" name="velocity" />
</label>
<label>
<span>Skip beats (<em class="skip-numeric">0</em>)</span>
<input type="range" min="0" max="6" value="0" name="skip" />
</label>
<label>
<span>Shift beats (<em class="shift-numeric">0</em>)</span>
<input type="range" min="-8" max="8" value="0" name="shift" />
</label>
</div>
<div class="data-holder">
<table class="data-shifted-negative"></table>
<table class="data"></table>
</div>
</article>""")
track.appendTo $(".tracks")
# if we already loaded the list of instruments somewhere else, copy it
# if not then it will be added to the initial tracks usually
if $("select[name='instruments']").length > 0
track.find("select[name='instruments']").append instrumentList
if $("select[name='datasets']").length > 0
track.find("select[name='datasets']").append $("select[name='datasets']").first().html()
track.find("select[name='datasets']").trigger("change") # load first one
# we trigger a scroll event, to make sure the controls are re-positioned
$(window).scroll()
updateTotalBeatsCount()
### FUNCTIONS FOR PLAYBACK ###
# This will block/stop the execution inside play();
# because it's asynchronous we can read that value
# inside our play loop
stop = ->
stopped = true
$("#playpause span").attr("class", "icon icon-play2")
# Clear the timer for the next beat
if nextTimeout isnt null
clearTimeout nextTimeout
###*
* Starts the playback. This is a recursive function
* that will call itself at every beat, and each time
* will figure the current beat and send it to playBeat.
###
play = ->
if stopped && currentBeat >= totalBeats
rewind()
stopped = false
# Changes the button icon to pause
$("#playpause span").attr("class", "icon icon-pause")
# block playback if we're not done loading
if isLoading
return stop()
# Play the current beat
playBeat(currentBeat)
# Call this function again in n milliseconds using a timer
# the variable 'speed' is in second, we need ms so we multiply by 1000
# and then x2 to have a delay
#
# We put that timer in the nextTimeout variable,
# so that we can clear that timer to stop the playback
nextTimeout = setTimeout(play, speed * 1000)
# We move onto the next beat, for the next iteration...
currentBeat++
# ..but if that reaches the end of the 'song', then rewind and stop
if currentBeat + 1 > totalBeats
rewind()
###*
* Puts the playhead back to zero and scroll back there
###
rewind = ->
currentBeat = 0
updateBeatCounter()
$(window).scrollLeft(0)
# Clears the markers
$(".currentBeat").removeClass("currentBeat")
###*
* Checks the length of all tracks and picks the shortest
* This will be when the playhead stops, because otherwise
* we'll miss notes
###
updateTotalBeatsCount = ->
lengths = []
# for each row
$('tr').each ->
# find the number of cells, and push it in the array
lengths.push $(this).find('td').length
# Update the total beats length
totalBeats = _.min(lengths)
# This should be re-triggered at the same time the beat
# counts change
recalculateTracksWidth()
updateBeatCounter()
###*
* Updates the beat counter at the top
###
updateBeatCounter = ->
$(".beats").text("#{ currentBeat + 1 } / #{ totalBeats }")
# Resize the width of tracks div
# so that the background is long enough to fill it
# (otherwise it remains = to the page's length)
recalculateTracksWidth = ->
widths = []
$('.data').each ->
widths.push $(this).width()
# add the current window width to the list,
# in case we have shorter datasets
widths.push $(window).width()
# resize the track and add some margin (for the headers)
$('.tracks').width(_.max(widths)) + 120
###*
* Plays all the notes of a given beat.
* It goes through every track, and for each one,
* finds the current data point, converts it to notes/chords,
* and play it in a new channel with the given parameters (instrument,
* velocity, etc.)
###
playBeat = (beat) ->
channel = 0 # Start at channel 0
cell = null
updateBeatCounter()
# Remove the green check on previously played beat
$(".currentBeat").removeClass("currentBeat")
$(".track").each ->
# Find the settings in the track
instrumentName = $(this).find("select[name='instruments']").val()
velocity = $(this).find("input[name='velocity']").val()
velocity = Number.parseInt(velocity, 10)
conversionType = $(this).find("select[name='conversion']").val()
# Figure out which line of the dataset we will be using
# for this we need to find the index of .currentRow out of all <td>
# dataline will be the 0-based index of the row to use
allFields = $(this).find("th")
selectedField = allFields.filter(".currentRow")
dataLine = allFields.index(selectedField)
#keep a reference to the previous cell (for positioning purposes)
previousCell = cell
# find the cell we'll use
# within the table (.data) then find
# the nth <tr> (row) where n = dataLine (row of data we're using)
# and within that row, the nth column (<td>) which is the
# current beat
cell = $(this).find(".data tr:eq(#{ dataLine }) td:eq(#{beat})")
# if the cell does not exist (shorter dataset)
if cell.length == 0
cell = previousCell
return
# Add a class to this cell to show it's currently playing
cell.addClass("currentBeat")
# If this cell is being skipped or shifted then don't try to play it
if cell.hasClass("skip") or cell.hasClass("shifted-positive")
return
# Parse the value of the cell into a number
value = cell.text()
value = Number.parseFloat(value, 10)
chordValue = convertValueToNote(value, conversionType, cell.parent('tr'))
# Re-convert to an integer
chordValue = _.map chordValue, Math.round
### Play the note using MIDI.js ###
# Set the volume of that channel to the max
# (note: this cannot actually be changed per channel due to a bug
# in MIDI.js, see https://github.com/mudcube/MIDI.js/issues/46
# so we set the first to 127 regardless)
MIDI.setVolume channel, 127
# Set the desired instrument to that channel
MIDI.programChange channel, MIDI.GM.byName[instrumentName].number
# Set the start/end of that note
# MIDI.noteOn channel, noteValue, velocity, 0
MIDI.chordOn channel, chordValue, velocity, 0
MIDI.chordOff channel, chordValue, velocity, speed
# Increment the channel number for the next track
channel++
# When we're done with all the tracks
# Use the Y position of the last cell selected
# and scroll there, to keep the view in line the playhead
cellPosition = cell.position().left
# Math.max(0, …) to ensure we don't get a negative value if we're too far left
# we take the position of the cell, plus half the width of the screen
$(window).scrollLeft(Math.max(0, cellPosition - $(window).width() / 2))
# MIDI notes (starting on octave 4; there's 12 notes per octave
# so we add/remove multiples of 12 to add/remove an octave, from octave 0 to 10)
notes = {
C: 48
Cs: 49
D: 50
Ds: 51
E: 52
F: 53
Fs: 54
G: 55
Gs: 56
A: 57
As: 58
B: 59
}
convertValueToNote = (value, conversionType, trContext) ->
# Get the domain (min, max) of the data for certain conversions, as we will mainly
# want to show the difference between the lower and higher points
# This gives us a base reference for pitch, velocity etc.
min = Number.parseFloat trContext.data("min"), 10
max = Number.parseFloat trContext.data("max"), 10
# avoid a bug where nothing plays if all values are the same
# (e.g. the metronome "dataset")
if min == max
max = max + 1
switch conversionType
when 'chord'
chords = [
[ notes['C'], notes['E'], notes['G'] ]
[ notes['D'], notes['Fs'], notes['A'] ]
[ notes['E'], notes['Gs'], notes['B'] ]
[ notes['F'], notes['A'], notes['C'] ]
[ notes['G'], notes['B'], notes['D'] ]
[ notes['A'], notes['Cs'], notes['E'] ]
[ notes['As'], notes['C'], notes['E'] ]
[ (notes['C'] + 12), (notes['E'] + 12), (notes['G'] + 12) ]
]
octave = mapTo(value, min, max, -1, 3, true) | 0
chordNum = mapTo(value, min, max, 0, chords.length, true) | 0
chordToUse = chords[chordNum]
chordToUse = _.map chordToUse, (n) -> n + (octave * 12)
return chordToUse
when 'scale'
# Mysolidian scale
scale = [
notes['C']
notes['D']
notes['E']
notes['F']
notes['G']
notes['A']
notes['As']
notes['C']
]
octave = mapTo(value, min, max, -2, 2, true) | 0 #((value / scale.length | 0) % 10)
normalisedValue = mapTo(value, min, max, 0, scale.length, true) | 0
note = scale[normalisedValue] + (octave * 12)
return [ note ]
when 'map_value'
# Maps a value from C4 to B1
return [ mapTo(value, min, max, 60, 83, true) ]
when 'direct_to_midi'
# directly return our value
return [value]
# On page load (this is equivalent to DOMContentLoaded for jQuery)
$ ->
# Give an initial "loading...' message (defined in utils)
startLoadingIndicator()
# Add a first track
addTrack()
# When scrolling, this will keep the controls of the track to the left
# (I don't use position:fixed in CSS because that keeps it fixed on
# both axes, whereas I only need the X axis)
$(window).scroll ->
# its sets the 'left' css property to the current X scroll value
# same for the headings of tables
$(".controls, .data th").css "left", $(this).scrollLeft()
$(window).resize recalculateTracksWidth
# Start by loading up MIDI.js
# with a correct plugin (+ a default instrument)
MIDI.loadPlugin
soundfontUrl: "bower_components/midi-js-soundfonts/FluidR3_GM/"
instrument: "acoustic_grand_piano"
onprogress: (state, progress) ->
# console.log state, progress
onsuccess: ->
stopLoadingIndicator()
# Loads the list of all possible instruments (it's in a separate JSON)
$.getJSON "instruments.json", (data) ->
# Callback: it is loaded, add each item to an <option> tag
items = []
$.each data, (groupName, instrArray) ->
items.push """<optgroup label="#{ groupName }">"""
$.each instrArray, (instrCode, instrName) ->
items.push """<option value="#{ instrCode }">#{ instrName }</option>"""
items.push """</optgroup>"""
# then add these <option> tags to every <select> that's already in place
# (if we add tracks later it will be copied from existing tracks)
instrumentList = items.join("")
$("select[name='instruments']").append instrumentList
stopLoadingIndicator()
# Loads the list of all possible datasets (in a separate JSON)
$.getJSON "datasets.json", (data) ->
# Callback: when this is loaded, add each item to an <option> tag
items = []
$.each data, (groupName, setsArray) ->
items.push """<optgroup label="#{ groupName }">"""
$.each setsArray, (datasetCode, datasetName) ->
items.push """<option value="#{ datasetCode }">#{ datasetName }</option>"""
items.push """</optgroup>"""
# then add these <option> tags to every <select> that's already in place
# (if we add tracks later it will be copied from existing tracks)
datasetList = items.join("")
$("select[name='datasets']").append datasetList
stopLoadingIndicator()
$("select[name='datasets']").trigger("change") # load first one
### Event handlers ###
# Add a track when the + button is clicked
$(".add-track").on "click", addTrack
# Stop or start the track when the play/pause button is clicked
$("#playpause").on "click", ->
if stopped then play()
else stop()
$("#rewind").on "click", rewind
# Load an instrument when the dropdown changes
$(".tracks").on "change", "select[name='instruments']", ->
loadInstrument $(this).val()
# Load a dataset when the dropdown changes
$(".tracks").on "change", "select[name='datasets']", ->
loadDataset $(this).val(), $(this).parents(".track").first()
# Change the number of beats to skip for a dataset
$(".tracks").on "change", "input[name='skip']", ->
setSkipValue(Number.parseInt($(this).val(), 10), $(this).parents(".track").first())
# Change the number of beats to skip for a dataset
$(".tracks").on "change", "input[name='shift']", ->
setShiftValue(Number.parseInt($(this).val(), 10), $(this).parents(".track").first())
# Removes a track
$(".tracks").on "click", ".delete", (e) ->
e.preventDefault()
if confirm("Do you really want to delete this track?")
$(this).parents(".track").remove()
recalculateTracksWidth()
updateTotalBeatsCount()
# Modify the speed of the track (in the header)
$("#speed").on "change", ->
speed = Number.parseFloat $(this).val(), 10
# Plays/pauses when the space bar is pressed
$(window).keypress (e) ->
if (e.keyCode == 0 || e.keyCode == 32)
$("#playpause").click()
# Changes the active row in a dataset
$(".tracks").on "click", "th", ->
$(this).parents(".data").find("th.currentRow").removeClass("currentRow")
$(this).addClass("currentRow")
| 170342 | ###
# <NAME> <<EMAIL>
###
### UTILITY FUNCTION & VARIABLES ###
# Status
isLoading = true
stopped = true
nextTimeout = null
# Tracks the current position
currentBeat = 0
totalBeats = 29
speed = 1/4
velocity = 127
# This will hold our list of instruments & datasets
instrumentList = datasetList = null
###*
* Re-maps a number from one range to another.
* Equivalent to the map function in Arduino and Processing
###
mapTo = (value, inMin, inMax, outMin, outMax, capped = false) ->
newVal = (value - inMin) * (outMax - outMin) / (inMax - inMin) + outMin
if capped
if newVal > outMax then newVal = outMax
if newVal < outMin then newVal = outMin
return newVal
###*
* Starts and stops the loading indicator at the top, and set a 'lock'
* variable that will prevent playback until things are loaded
###
startLoadingIndicator = ->
isLoading = true
$(".loaded-indicator").removeClass("loaded").text "Loading…"
$('body').css('cursor', 'wait')
stopLoadingIndicator = ->
isLoading = false
$(".loaded-indicator").addClass("loaded").text "All loaded."
$('body').css('cursor', 'default')
###*
* Dynamically loads an instrument from the soundfont directory
* @param {string} instrumentName Name of the instrument as in the soundfont
###
loadInstrument = (instrumentName) ->
MIDI.loadResource
instrument: instrumentName
onprogress: (state, progress) ->
startLoadingIndicator()
# console.log state, progress
onsuccess: ->
stopLoadingIndicator()
###*
* Dynamically loads a dataset, and then fills a table in the current track
* @param {string} datasetName Name of the JSON dataset
* @param {DOMObject} track Track <article> where the table should be added
###
loadDataset = (datasetName, track) ->
$.getJSON "data/#{ datasetName }.json", (data) ->
# Empty the current table
track.find(".data").empty()
# Take the first item and figure out the keys available
# in this dataset. (normally all items will be the
# same length/have the same properties).
fields = _.keys(data[0])
i = 0
# For every field we have
for fieldName in fields
# For all items in data, this gets
# the value of array items that have this field name
values = _.pluck(data, fieldName)
# create a <tr> (table row)
tr = $("<tr>")
# Add a header to that row
# (th = table header, will be ignored when reading)
tr.append "<th><span>#{fieldName}</span></th>"
# For each value, wrap it in <td> tags (a cell)
# and append the whole thing to our tr
tr.append(_.map values, (item) ->
return "<td><span>#{item}</span></td>")
# add some data to this, while we have the values
# eg the min/max possible value, this will be useful later
# for mapping a value to a note
# but first convert all to numeric
values = _.map values, (item) ->
return Number.parseFloat item, 10
tr.attr("data-max", _.max(values))
tr.attr("data-min", _.min(values))
# Always highlight the 2nd (index 1) row
if i == 1
tr.find("th").addClass("currentRow")
# then add all this to the .data table
track.find(".data").append(tr)
i++
track.find("[name='skip']").trigger("change")
#also recalculate the height of headers
# (because they're positioned absolutely and not statically in CSS,
# their height is not modified)
# 190 (height of a track) divided by the number of headers
headers = track.find('th')
numberOfHeaders = headers.length
headers.css({
"height": (190 / numberOfHeaders) + "px"
"line-height": (190 / numberOfHeaders) + "px"
})
# we trigger a scroll event, to make sure the controls are re-positioned
$(window).scroll()
setSkipValue = (skipValue, track) ->
track.find(".data td.skip").remove() # reset skipped beats
newCells = Array(skipValue + 1).join("""<td class="skip"></td>""")
track.find(".data td").after(newCells)
track.find(".skip-numeric").text(skipValue)
updateTotalBeatsCount()
setShiftValue = (shiftValue, track) ->
# reset shifted beats
track.find(".data td.shifted-positive").remove()
track.find(".data-shifted-negative tr").each (i) ->
$(this).find("td").insertAfter(track.find(".data tr:eq(#{i}) th"))
track.find(".data-shifted-negative").empty()
# if we shift positively, add new cells at the beginning to the row
# these will work the same as skipped beats
if shiftValue > 0
newCells = Array(shiftValue + 1).join("""<td class="shifted-positive"></td>""")
track.find(".data th").after(newCells)
# if we shift negatively, then virtually delete these beats
else if shiftValue < 0
# find the n first cells in each row, for this
# slice the selection; and abs() because shiftValue is negative
# then move them to the .data table
track.find(".data tr").each (i) ->
cells = $(this).find("td").slice(0, Math.abs(shiftValue))
track.find(".data-shifted-negative").append("<tr>")
cells.appendTo(track.find(".data-shifted-negative tr").filter(":last"))
# update the numeric counter (easier to see than the range slider)
if shiftValue > 0 then shiftValue = "+" + shiftValue # add a + if >0
track.find(".shift-numeric").text(shiftValue)
updateTotalBeatsCount()
addTrack = ->
track = $("""
<article class="track">
<div class="controls">
<a href="#" class="delete"><span class="icon icon-bin"></span></a>
<select name="datasets"></select>
<label>
<span>Instrument</span>
<select name="instruments"></select>
</label>
<label>
<span>Conversion</span>
<select name="conversion">
<option value="chord">Chord conversion</option>
<option value="scale">Map on a scale</option>
<option value="map_value">Map to note</option>
<option value="direct_to_midi">Direct to MIDI</option>
</select>
</label>
<label>
<span>Velocity</span>
<input type="range" min="0" max="127" value="127" name="velocity" />
</label>
<label>
<span>Skip beats (<em class="skip-numeric">0</em>)</span>
<input type="range" min="0" max="6" value="0" name="skip" />
</label>
<label>
<span>Shift beats (<em class="shift-numeric">0</em>)</span>
<input type="range" min="-8" max="8" value="0" name="shift" />
</label>
</div>
<div class="data-holder">
<table class="data-shifted-negative"></table>
<table class="data"></table>
</div>
</article>""")
track.appendTo $(".tracks")
# if we already loaded the list of instruments somewhere else, copy it
# if not then it will be added to the initial tracks usually
if $("select[name='instruments']").length > 0
track.find("select[name='instruments']").append instrumentList
if $("select[name='datasets']").length > 0
track.find("select[name='datasets']").append $("select[name='datasets']").first().html()
track.find("select[name='datasets']").trigger("change") # load first one
# we trigger a scroll event, to make sure the controls are re-positioned
$(window).scroll()
updateTotalBeatsCount()
### FUNCTIONS FOR PLAYBACK ###
# This will block/stop the execution inside play();
# because it's asynchronous we can read that value
# inside our play loop
stop = ->
stopped = true
$("#playpause span").attr("class", "icon icon-play2")
# Clear the timer for the next beat
if nextTimeout isnt null
clearTimeout nextTimeout
###*
* Starts the playback. This is a recursive function
* that will call itself at every beat, and each time
* will figure the current beat and send it to playBeat.
###
play = ->
if stopped && currentBeat >= totalBeats
rewind()
stopped = false
# Changes the button icon to pause
$("#playpause span").attr("class", "icon icon-pause")
# block playback if we're not done loading
if isLoading
return stop()
# Play the current beat
playBeat(currentBeat)
# Call this function again in n milliseconds using a timer
# the variable 'speed' is in second, we need ms so we multiply by 1000
# and then x2 to have a delay
#
# We put that timer in the nextTimeout variable,
# so that we can clear that timer to stop the playback
nextTimeout = setTimeout(play, speed * 1000)
# We move onto the next beat, for the next iteration...
currentBeat++
# ..but if that reaches the end of the 'song', then rewind and stop
if currentBeat + 1 > totalBeats
rewind()
###*
* Puts the playhead back to zero and scroll back there
###
rewind = ->
currentBeat = 0
updateBeatCounter()
$(window).scrollLeft(0)
# Clears the markers
$(".currentBeat").removeClass("currentBeat")
###*
* Checks the length of all tracks and picks the shortest
* This will be when the playhead stops, because otherwise
* we'll miss notes
###
updateTotalBeatsCount = ->
lengths = []
# for each row
$('tr').each ->
# find the number of cells, and push it in the array
lengths.push $(this).find('td').length
# Update the total beats length
totalBeats = _.min(lengths)
# This should be re-triggered at the same time the beat
# counts change
recalculateTracksWidth()
updateBeatCounter()
###*
* Updates the beat counter at the top
###
updateBeatCounter = ->
$(".beats").text("#{ currentBeat + 1 } / #{ totalBeats }")
# Resize the width of tracks div
# so that the background is long enough to fill it
# (otherwise it remains = to the page's length)
recalculateTracksWidth = ->
widths = []
$('.data').each ->
widths.push $(this).width()
# add the current window width to the list,
# in case we have shorter datasets
widths.push $(window).width()
# resize the track and add some margin (for the headers)
$('.tracks').width(_.max(widths)) + 120
###*
* Plays all the notes of a given beat.
* It goes through every track, and for each one,
* finds the current data point, converts it to notes/chords,
* and play it in a new channel with the given parameters (instrument,
* velocity, etc.)
###
playBeat = (beat) ->
channel = 0 # Start at channel 0
cell = null
updateBeatCounter()
# Remove the green check on previously played beat
$(".currentBeat").removeClass("currentBeat")
$(".track").each ->
# Find the settings in the track
instrumentName = $(this).find("select[name='instruments']").val()
velocity = $(this).find("input[name='velocity']").val()
velocity = Number.parseInt(velocity, 10)
conversionType = $(this).find("select[name='conversion']").val()
# Figure out which line of the dataset we will be using
# for this we need to find the index of .currentRow out of all <td>
# dataline will be the 0-based index of the row to use
allFields = $(this).find("th")
selectedField = allFields.filter(".currentRow")
dataLine = allFields.index(selectedField)
#keep a reference to the previous cell (for positioning purposes)
previousCell = cell
# find the cell we'll use
# within the table (.data) then find
# the nth <tr> (row) where n = dataLine (row of data we're using)
# and within that row, the nth column (<td>) which is the
# current beat
cell = $(this).find(".data tr:eq(#{ dataLine }) td:eq(#{beat})")
# if the cell does not exist (shorter dataset)
if cell.length == 0
cell = previousCell
return
# Add a class to this cell to show it's currently playing
cell.addClass("currentBeat")
# If this cell is being skipped or shifted then don't try to play it
if cell.hasClass("skip") or cell.hasClass("shifted-positive")
return
# Parse the value of the cell into a number
value = cell.text()
value = Number.parseFloat(value, 10)
chordValue = convertValueToNote(value, conversionType, cell.parent('tr'))
# Re-convert to an integer
chordValue = _.map chordValue, Math.round
### Play the note using MIDI.js ###
# Set the volume of that channel to the max
# (note: this cannot actually be changed per channel due to a bug
# in MIDI.js, see https://github.com/mudcube/MIDI.js/issues/46
# so we set the first to 127 regardless)
MIDI.setVolume channel, 127
# Set the desired instrument to that channel
MIDI.programChange channel, MIDI.GM.byName[instrumentName].number
# Set the start/end of that note
# MIDI.noteOn channel, noteValue, velocity, 0
MIDI.chordOn channel, chordValue, velocity, 0
MIDI.chordOff channel, chordValue, velocity, speed
# Increment the channel number for the next track
channel++
# When we're done with all the tracks
# Use the Y position of the last cell selected
# and scroll there, to keep the view in line the playhead
cellPosition = cell.position().left
# Math.max(0, …) to ensure we don't get a negative value if we're too far left
# we take the position of the cell, plus half the width of the screen
$(window).scrollLeft(Math.max(0, cellPosition - $(window).width() / 2))
# MIDI notes (starting on octave 4; there's 12 notes per octave
# so we add/remove multiples of 12 to add/remove an octave, from octave 0 to 10)
notes = {
C: 48
Cs: 49
D: 50
Ds: 51
E: 52
F: 53
Fs: 54
G: 55
Gs: 56
A: 57
As: 58
B: 59
}
convertValueToNote = (value, conversionType, trContext) ->
# Get the domain (min, max) of the data for certain conversions, as we will mainly
# want to show the difference between the lower and higher points
# This gives us a base reference for pitch, velocity etc.
min = Number.parseFloat trContext.data("min"), 10
max = Number.parseFloat trContext.data("max"), 10
# avoid a bug where nothing plays if all values are the same
# (e.g. the metronome "dataset")
if min == max
max = max + 1
switch conversionType
when 'chord'
chords = [
[ notes['C'], notes['E'], notes['G'] ]
[ notes['D'], notes['Fs'], notes['A'] ]
[ notes['E'], notes['Gs'], notes['B'] ]
[ notes['F'], notes['A'], notes['C'] ]
[ notes['G'], notes['B'], notes['D'] ]
[ notes['A'], notes['Cs'], notes['E'] ]
[ notes['As'], notes['C'], notes['E'] ]
[ (notes['C'] + 12), (notes['E'] + 12), (notes['G'] + 12) ]
]
octave = mapTo(value, min, max, -1, 3, true) | 0
chordNum = mapTo(value, min, max, 0, chords.length, true) | 0
chordToUse = chords[chordNum]
chordToUse = _.map chordToUse, (n) -> n + (octave * 12)
return chordToUse
when 'scale'
# Mysolidian scale
scale = [
notes['C']
notes['D']
notes['E']
notes['F']
notes['G']
notes['A']
notes['As']
notes['C']
]
octave = mapTo(value, min, max, -2, 2, true) | 0 #((value / scale.length | 0) % 10)
normalisedValue = mapTo(value, min, max, 0, scale.length, true) | 0
note = scale[normalisedValue] + (octave * 12)
return [ note ]
when 'map_value'
# Maps a value from C4 to B1
return [ mapTo(value, min, max, 60, 83, true) ]
when 'direct_to_midi'
# directly return our value
return [value]
# On page load (this is equivalent to DOMContentLoaded for jQuery)
$ ->
# Give an initial "loading...' message (defined in utils)
startLoadingIndicator()
# Add a first track
addTrack()
# When scrolling, this will keep the controls of the track to the left
# (I don't use position:fixed in CSS because that keeps it fixed on
# both axes, whereas I only need the X axis)
$(window).scroll ->
# its sets the 'left' css property to the current X scroll value
# same for the headings of tables
$(".controls, .data th").css "left", $(this).scrollLeft()
$(window).resize recalculateTracksWidth
# Start by loading up MIDI.js
# with a correct plugin (+ a default instrument)
MIDI.loadPlugin
soundfontUrl: "bower_components/midi-js-soundfonts/FluidR3_GM/"
instrument: "acoustic_grand_piano"
onprogress: (state, progress) ->
# console.log state, progress
onsuccess: ->
stopLoadingIndicator()
# Loads the list of all possible instruments (it's in a separate JSON)
$.getJSON "instruments.json", (data) ->
# Callback: it is loaded, add each item to an <option> tag
items = []
$.each data, (groupName, instrArray) ->
items.push """<optgroup label="#{ groupName }">"""
$.each instrArray, (instrCode, instrName) ->
items.push """<option value="#{ instrCode }">#{ instrName }</option>"""
items.push """</optgroup>"""
# then add these <option> tags to every <select> that's already in place
# (if we add tracks later it will be copied from existing tracks)
instrumentList = items.join("")
$("select[name='instruments']").append instrumentList
stopLoadingIndicator()
# Loads the list of all possible datasets (in a separate JSON)
$.getJSON "datasets.json", (data) ->
# Callback: when this is loaded, add each item to an <option> tag
items = []
$.each data, (groupName, setsArray) ->
items.push """<optgroup label="#{ groupName }">"""
$.each setsArray, (datasetCode, datasetName) ->
items.push """<option value="#{ datasetCode }">#{ datasetName }</option>"""
items.push """</optgroup>"""
# then add these <option> tags to every <select> that's already in place
# (if we add tracks later it will be copied from existing tracks)
datasetList = items.join("")
$("select[name='datasets']").append datasetList
stopLoadingIndicator()
$("select[name='datasets']").trigger("change") # load first one
### Event handlers ###
# Add a track when the + button is clicked
$(".add-track").on "click", addTrack
# Stop or start the track when the play/pause button is clicked
$("#playpause").on "click", ->
if stopped then play()
else stop()
$("#rewind").on "click", rewind
# Load an instrument when the dropdown changes
$(".tracks").on "change", "select[name='instruments']", ->
loadInstrument $(this).val()
# Load a dataset when the dropdown changes
$(".tracks").on "change", "select[name='datasets']", ->
loadDataset $(this).val(), $(this).parents(".track").first()
# Change the number of beats to skip for a dataset
$(".tracks").on "change", "input[name='skip']", ->
setSkipValue(Number.parseInt($(this).val(), 10), $(this).parents(".track").first())
# Change the number of beats to skip for a dataset
$(".tracks").on "change", "input[name='shift']", ->
setShiftValue(Number.parseInt($(this).val(), 10), $(this).parents(".track").first())
# Removes a track
$(".tracks").on "click", ".delete", (e) ->
e.preventDefault()
if confirm("Do you really want to delete this track?")
$(this).parents(".track").remove()
recalculateTracksWidth()
updateTotalBeatsCount()
# Modify the speed of the track (in the header)
$("#speed").on "change", ->
speed = Number.parseFloat $(this).val(), 10
# Plays/pauses when the space bar is pressed
$(window).keypress (e) ->
if (e.keyCode == 0 || e.keyCode == 32)
$("#playpause").click()
# Changes the active row in a dataset
$(".tracks").on "click", "th", ->
$(this).parents(".data").find("th.currentRow").removeClass("currentRow")
$(this).addClass("currentRow")
| true | ###
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI
###
### UTILITY FUNCTION & VARIABLES ###
# Status
isLoading = true
stopped = true
nextTimeout = null
# Tracks the current position
currentBeat = 0
totalBeats = 29
speed = 1/4
velocity = 127
# This will hold our list of instruments & datasets
instrumentList = datasetList = null
###*
* Re-maps a number from one range to another.
* Equivalent to the map function in Arduino and Processing
###
mapTo = (value, inMin, inMax, outMin, outMax, capped = false) ->
newVal = (value - inMin) * (outMax - outMin) / (inMax - inMin) + outMin
if capped
if newVal > outMax then newVal = outMax
if newVal < outMin then newVal = outMin
return newVal
###*
* Starts and stops the loading indicator at the top, and set a 'lock'
* variable that will prevent playback until things are loaded
###
startLoadingIndicator = ->
isLoading = true
$(".loaded-indicator").removeClass("loaded").text "Loading…"
$('body').css('cursor', 'wait')
stopLoadingIndicator = ->
isLoading = false
$(".loaded-indicator").addClass("loaded").text "All loaded."
$('body').css('cursor', 'default')
###*
* Dynamically loads an instrument from the soundfont directory
* @param {string} instrumentName Name of the instrument as in the soundfont
###
loadInstrument = (instrumentName) ->
MIDI.loadResource
instrument: instrumentName
onprogress: (state, progress) ->
startLoadingIndicator()
# console.log state, progress
onsuccess: ->
stopLoadingIndicator()
###*
* Dynamically loads a dataset, and then fills a table in the current track
* @param {string} datasetName Name of the JSON dataset
* @param {DOMObject} track Track <article> where the table should be added
###
loadDataset = (datasetName, track) ->
$.getJSON "data/#{ datasetName }.json", (data) ->
# Empty the current table
track.find(".data").empty()
# Take the first item and figure out the keys available
# in this dataset. (normally all items will be the
# same length/have the same properties).
fields = _.keys(data[0])
i = 0
# For every field we have
for fieldName in fields
# For all items in data, this gets
# the value of array items that have this field name
values = _.pluck(data, fieldName)
# create a <tr> (table row)
tr = $("<tr>")
# Add a header to that row
# (th = table header, will be ignored when reading)
tr.append "<th><span>#{fieldName}</span></th>"
# For each value, wrap it in <td> tags (a cell)
# and append the whole thing to our tr
tr.append(_.map values, (item) ->
return "<td><span>#{item}</span></td>")
# add some data to this, while we have the values
# eg the min/max possible value, this will be useful later
# for mapping a value to a note
# but first convert all to numeric
values = _.map values, (item) ->
return Number.parseFloat item, 10
tr.attr("data-max", _.max(values))
tr.attr("data-min", _.min(values))
# Always highlight the 2nd (index 1) row
if i == 1
tr.find("th").addClass("currentRow")
# then add all this to the .data table
track.find(".data").append(tr)
i++
track.find("[name='skip']").trigger("change")
#also recalculate the height of headers
# (because they're positioned absolutely and not statically in CSS,
# their height is not modified)
# 190 (height of a track) divided by the number of headers
headers = track.find('th')
numberOfHeaders = headers.length
headers.css({
"height": (190 / numberOfHeaders) + "px"
"line-height": (190 / numberOfHeaders) + "px"
})
# we trigger a scroll event, to make sure the controls are re-positioned
$(window).scroll()
setSkipValue = (skipValue, track) ->
track.find(".data td.skip").remove() # reset skipped beats
newCells = Array(skipValue + 1).join("""<td class="skip"></td>""")
track.find(".data td").after(newCells)
track.find(".skip-numeric").text(skipValue)
updateTotalBeatsCount()
setShiftValue = (shiftValue, track) ->
# reset shifted beats
track.find(".data td.shifted-positive").remove()
track.find(".data-shifted-negative tr").each (i) ->
$(this).find("td").insertAfter(track.find(".data tr:eq(#{i}) th"))
track.find(".data-shifted-negative").empty()
# if we shift positively, add new cells at the beginning to the row
# these will work the same as skipped beats
if shiftValue > 0
newCells = Array(shiftValue + 1).join("""<td class="shifted-positive"></td>""")
track.find(".data th").after(newCells)
# if we shift negatively, then virtually delete these beats
else if shiftValue < 0
# find the n first cells in each row, for this
# slice the selection; and abs() because shiftValue is negative
# then move them to the .data table
track.find(".data tr").each (i) ->
cells = $(this).find("td").slice(0, Math.abs(shiftValue))
track.find(".data-shifted-negative").append("<tr>")
cells.appendTo(track.find(".data-shifted-negative tr").filter(":last"))
# update the numeric counter (easier to see than the range slider)
if shiftValue > 0 then shiftValue = "+" + shiftValue # add a + if >0
track.find(".shift-numeric").text(shiftValue)
updateTotalBeatsCount()
addTrack = ->
track = $("""
<article class="track">
<div class="controls">
<a href="#" class="delete"><span class="icon icon-bin"></span></a>
<select name="datasets"></select>
<label>
<span>Instrument</span>
<select name="instruments"></select>
</label>
<label>
<span>Conversion</span>
<select name="conversion">
<option value="chord">Chord conversion</option>
<option value="scale">Map on a scale</option>
<option value="map_value">Map to note</option>
<option value="direct_to_midi">Direct to MIDI</option>
</select>
</label>
<label>
<span>Velocity</span>
<input type="range" min="0" max="127" value="127" name="velocity" />
</label>
<label>
<span>Skip beats (<em class="skip-numeric">0</em>)</span>
<input type="range" min="0" max="6" value="0" name="skip" />
</label>
<label>
<span>Shift beats (<em class="shift-numeric">0</em>)</span>
<input type="range" min="-8" max="8" value="0" name="shift" />
</label>
</div>
<div class="data-holder">
<table class="data-shifted-negative"></table>
<table class="data"></table>
</div>
</article>""")
track.appendTo $(".tracks")
# if we already loaded the list of instruments somewhere else, copy it
# if not then it will be added to the initial tracks usually
if $("select[name='instruments']").length > 0
track.find("select[name='instruments']").append instrumentList
if $("select[name='datasets']").length > 0
track.find("select[name='datasets']").append $("select[name='datasets']").first().html()
track.find("select[name='datasets']").trigger("change") # load first one
# we trigger a scroll event, to make sure the controls are re-positioned
$(window).scroll()
updateTotalBeatsCount()
### FUNCTIONS FOR PLAYBACK ###
# This will block/stop the execution inside play();
# because it's asynchronous we can read that value
# inside our play loop
stop = ->
stopped = true
$("#playpause span").attr("class", "icon icon-play2")
# Clear the timer for the next beat
if nextTimeout isnt null
clearTimeout nextTimeout
###*
* Starts the playback. This is a recursive function
* that will call itself at every beat, and each time
* will figure the current beat and send it to playBeat.
###
play = ->
if stopped && currentBeat >= totalBeats
rewind()
stopped = false
# Changes the button icon to pause
$("#playpause span").attr("class", "icon icon-pause")
# block playback if we're not done loading
if isLoading
return stop()
# Play the current beat
playBeat(currentBeat)
# Call this function again in n milliseconds using a timer
# the variable 'speed' is in second, we need ms so we multiply by 1000
# and then x2 to have a delay
#
# We put that timer in the nextTimeout variable,
# so that we can clear that timer to stop the playback
nextTimeout = setTimeout(play, speed * 1000)
# We move onto the next beat, for the next iteration...
currentBeat++
# ..but if that reaches the end of the 'song', then rewind and stop
if currentBeat + 1 > totalBeats
rewind()
###*
* Puts the playhead back to zero and scroll back there
###
rewind = ->
currentBeat = 0
updateBeatCounter()
$(window).scrollLeft(0)
# Clears the markers
$(".currentBeat").removeClass("currentBeat")
###*
* Checks the length of all tracks and picks the shortest
* This will be when the playhead stops, because otherwise
* we'll miss notes
###
updateTotalBeatsCount = ->
lengths = []
# for each row
$('tr').each ->
# find the number of cells, and push it in the array
lengths.push $(this).find('td').length
# Update the total beats length
totalBeats = _.min(lengths)
# This should be re-triggered at the same time the beat
# counts change
recalculateTracksWidth()
updateBeatCounter()
###*
* Updates the beat counter at the top
###
updateBeatCounter = ->
$(".beats").text("#{ currentBeat + 1 } / #{ totalBeats }")
# Resize the width of tracks div
# so that the background is long enough to fill it
# (otherwise it remains = to the page's length)
recalculateTracksWidth = ->
widths = []
$('.data').each ->
widths.push $(this).width()
# add the current window width to the list,
# in case we have shorter datasets
widths.push $(window).width()
# resize the track and add some margin (for the headers)
$('.tracks').width(_.max(widths)) + 120
###*
* Plays all the notes of a given beat.
* It goes through every track, and for each one,
* finds the current data point, converts it to notes/chords,
* and play it in a new channel with the given parameters (instrument,
* velocity, etc.)
###
playBeat = (beat) ->
channel = 0 # Start at channel 0
cell = null
updateBeatCounter()
# Remove the green check on previously played beat
$(".currentBeat").removeClass("currentBeat")
$(".track").each ->
# Find the settings in the track
instrumentName = $(this).find("select[name='instruments']").val()
velocity = $(this).find("input[name='velocity']").val()
velocity = Number.parseInt(velocity, 10)
conversionType = $(this).find("select[name='conversion']").val()
# Figure out which line of the dataset we will be using
# for this we need to find the index of .currentRow out of all <td>
# dataline will be the 0-based index of the row to use
allFields = $(this).find("th")
selectedField = allFields.filter(".currentRow")
dataLine = allFields.index(selectedField)
#keep a reference to the previous cell (for positioning purposes)
previousCell = cell
# find the cell we'll use
# within the table (.data) then find
# the nth <tr> (row) where n = dataLine (row of data we're using)
# and within that row, the nth column (<td>) which is the
# current beat
cell = $(this).find(".data tr:eq(#{ dataLine }) td:eq(#{beat})")
# if the cell does not exist (shorter dataset)
if cell.length == 0
cell = previousCell
return
# Add a class to this cell to show it's currently playing
cell.addClass("currentBeat")
# If this cell is being skipped or shifted then don't try to play it
if cell.hasClass("skip") or cell.hasClass("shifted-positive")
return
# Parse the value of the cell into a number
value = cell.text()
value = Number.parseFloat(value, 10)
chordValue = convertValueToNote(value, conversionType, cell.parent('tr'))
# Re-convert to an integer
chordValue = _.map chordValue, Math.round
### Play the note using MIDI.js ###
# Set the volume of that channel to the max
# (note: this cannot actually be changed per channel due to a bug
# in MIDI.js, see https://github.com/mudcube/MIDI.js/issues/46
# so we set the first to 127 regardless)
MIDI.setVolume channel, 127
# Set the desired instrument to that channel
MIDI.programChange channel, MIDI.GM.byName[instrumentName].number
# Set the start/end of that note
# MIDI.noteOn channel, noteValue, velocity, 0
MIDI.chordOn channel, chordValue, velocity, 0
MIDI.chordOff channel, chordValue, velocity, speed
# Increment the channel number for the next track
channel++
# When we're done with all the tracks
# Use the Y position of the last cell selected
# and scroll there, to keep the view in line the playhead
cellPosition = cell.position().left
# Math.max(0, …) to ensure we don't get a negative value if we're too far left
# we take the position of the cell, plus half the width of the screen
$(window).scrollLeft(Math.max(0, cellPosition - $(window).width() / 2))
# MIDI notes (starting on octave 4; there's 12 notes per octave
# so we add/remove multiples of 12 to add/remove an octave, from octave 0 to 10)
notes = {
C: 48
Cs: 49
D: 50
Ds: 51
E: 52
F: 53
Fs: 54
G: 55
Gs: 56
A: 57
As: 58
B: 59
}
convertValueToNote = (value, conversionType, trContext) ->
# Get the domain (min, max) of the data for certain conversions, as we will mainly
# want to show the difference between the lower and higher points
# This gives us a base reference for pitch, velocity etc.
min = Number.parseFloat trContext.data("min"), 10
max = Number.parseFloat trContext.data("max"), 10
# avoid a bug where nothing plays if all values are the same
# (e.g. the metronome "dataset")
if min == max
max = max + 1
switch conversionType
when 'chord'
chords = [
[ notes['C'], notes['E'], notes['G'] ]
[ notes['D'], notes['Fs'], notes['A'] ]
[ notes['E'], notes['Gs'], notes['B'] ]
[ notes['F'], notes['A'], notes['C'] ]
[ notes['G'], notes['B'], notes['D'] ]
[ notes['A'], notes['Cs'], notes['E'] ]
[ notes['As'], notes['C'], notes['E'] ]
[ (notes['C'] + 12), (notes['E'] + 12), (notes['G'] + 12) ]
]
octave = mapTo(value, min, max, -1, 3, true) | 0
chordNum = mapTo(value, min, max, 0, chords.length, true) | 0
chordToUse = chords[chordNum]
chordToUse = _.map chordToUse, (n) -> n + (octave * 12)
return chordToUse
when 'scale'
# Mysolidian scale
scale = [
notes['C']
notes['D']
notes['E']
notes['F']
notes['G']
notes['A']
notes['As']
notes['C']
]
octave = mapTo(value, min, max, -2, 2, true) | 0 #((value / scale.length | 0) % 10)
normalisedValue = mapTo(value, min, max, 0, scale.length, true) | 0
note = scale[normalisedValue] + (octave * 12)
return [ note ]
when 'map_value'
# Maps a value from C4 to B1
return [ mapTo(value, min, max, 60, 83, true) ]
when 'direct_to_midi'
# directly return our value
return [value]
# On page load (this is equivalent to DOMContentLoaded for jQuery)
$ ->
# Give an initial "loading...' message (defined in utils)
startLoadingIndicator()
# Add a first track
addTrack()
# When scrolling, this will keep the controls of the track to the left
# (I don't use position:fixed in CSS because that keeps it fixed on
# both axes, whereas I only need the X axis)
$(window).scroll ->
# its sets the 'left' css property to the current X scroll value
# same for the headings of tables
$(".controls, .data th").css "left", $(this).scrollLeft()
$(window).resize recalculateTracksWidth
# Start by loading up MIDI.js
# with a correct plugin (+ a default instrument)
MIDI.loadPlugin
soundfontUrl: "bower_components/midi-js-soundfonts/FluidR3_GM/"
instrument: "acoustic_grand_piano"
onprogress: (state, progress) ->
# console.log state, progress
onsuccess: ->
stopLoadingIndicator()
# Loads the list of all possible instruments (it's in a separate JSON)
$.getJSON "instruments.json", (data) ->
# Callback: it is loaded, add each item to an <option> tag
items = []
$.each data, (groupName, instrArray) ->
items.push """<optgroup label="#{ groupName }">"""
$.each instrArray, (instrCode, instrName) ->
items.push """<option value="#{ instrCode }">#{ instrName }</option>"""
items.push """</optgroup>"""
# then add these <option> tags to every <select> that's already in place
# (if we add tracks later it will be copied from existing tracks)
instrumentList = items.join("")
$("select[name='instruments']").append instrumentList
stopLoadingIndicator()
# Loads the list of all possible datasets (in a separate JSON)
$.getJSON "datasets.json", (data) ->
# Callback: when this is loaded, add each item to an <option> tag
items = []
$.each data, (groupName, setsArray) ->
items.push """<optgroup label="#{ groupName }">"""
$.each setsArray, (datasetCode, datasetName) ->
items.push """<option value="#{ datasetCode }">#{ datasetName }</option>"""
items.push """</optgroup>"""
# then add these <option> tags to every <select> that's already in place
# (if we add tracks later it will be copied from existing tracks)
datasetList = items.join("")
$("select[name='datasets']").append datasetList
stopLoadingIndicator()
$("select[name='datasets']").trigger("change") # load first one
### Event handlers ###
# Add a track when the + button is clicked
$(".add-track").on "click", addTrack
# Stop or start the track when the play/pause button is clicked
$("#playpause").on "click", ->
if stopped then play()
else stop()
$("#rewind").on "click", rewind
# Load an instrument when the dropdown changes
$(".tracks").on "change", "select[name='instruments']", ->
loadInstrument $(this).val()
# Load a dataset when the dropdown changes
$(".tracks").on "change", "select[name='datasets']", ->
loadDataset $(this).val(), $(this).parents(".track").first()
# Change the number of beats to skip for a dataset
$(".tracks").on "change", "input[name='skip']", ->
setSkipValue(Number.parseInt($(this).val(), 10), $(this).parents(".track").first())
# Change the number of beats to skip for a dataset
$(".tracks").on "change", "input[name='shift']", ->
setShiftValue(Number.parseInt($(this).val(), 10), $(this).parents(".track").first())
# Removes a track
$(".tracks").on "click", ".delete", (e) ->
e.preventDefault()
if confirm("Do you really want to delete this track?")
$(this).parents(".track").remove()
recalculateTracksWidth()
updateTotalBeatsCount()
# Modify the speed of the track (in the header)
$("#speed").on "change", ->
speed = Number.parseFloat $(this).val(), 10
# Plays/pauses when the space bar is pressed
$(window).keypress (e) ->
if (e.keyCode == 0 || e.keyCode == 32)
$("#playpause").click()
# Changes the active row in a dataset
$(".tracks").on "click", "th", ->
$(this).parents(".data").find("th.currentRow").removeClass("currentRow")
$(this).addClass("currentRow")
|
[
{
"context": "serModel = new UserModel\n\nparams = {\n username: 'admin'\n password: 'Ra1234'\n first_name: 'Raghavendra'",
"end": 152,
"score": 0.9956262707710266,
"start": 147,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "odel\n\nparams = {\n username: 'admin'\n passwo... | test/raw_test/add_super_admin_user.coffee | RaghavendhraK/daily_sales | 0 | global.config = require 'config'
UserModel = require '../../src/models/internal_storage/user'
userModel = new UserModel
params = {
username: 'admin'
password: 'Ra1234'
first_name: 'Raghavendra'
last_name: 'Karunanidhi'
role: 'admin'
}
userModel.getOne {username: params.username}, (e, user)->
if e?
console.log e
process.exit(1)
if user?
console.log 'Super admin already created'
process.exit(0)
userModel.create params, (e)->
if e?
console.log e
process.exit(1)
else
console.log 'Super admin user created successfully.'
process.exit(0)
| 41990 | global.config = require 'config'
UserModel = require '../../src/models/internal_storage/user'
userModel = new UserModel
params = {
username: 'admin'
password: '<PASSWORD>'
first_name: '<NAME>'
last_name: '<NAME>'
role: 'admin'
}
userModel.getOne {username: params.username}, (e, user)->
if e?
console.log e
process.exit(1)
if user?
console.log 'Super admin already created'
process.exit(0)
userModel.create params, (e)->
if e?
console.log e
process.exit(1)
else
console.log 'Super admin user created successfully.'
process.exit(0)
| true | global.config = require 'config'
UserModel = require '../../src/models/internal_storage/user'
userModel = new UserModel
params = {
username: 'admin'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
first_name: 'PI:NAME:<NAME>END_PI'
last_name: 'PI:NAME:<NAME>END_PI'
role: 'admin'
}
userModel.getOne {username: params.username}, (e, user)->
if e?
console.log e
process.exit(1)
if user?
console.log 'Super admin already created'
process.exit(0)
userModel.create params, (e)->
if e?
console.log e
process.exit(1)
else
console.log 'Super admin user created successfully.'
process.exit(0)
|
[
{
"context": "an Dictionary and returns example \n#\n# Author:\n# Travis Jeffery (@travisjeffery)\n# Robbie Trencheny (@Robbie)\n#",
"end": 490,
"score": 0.9998903274536133,
"start": 476,
"tag": "NAME",
"value": "Travis Jeffery"
},
{
"context": "nd returns example \n#\n# Author:\... | src/scripts/urban.coffee | Reelhouse/hubot-scripts | 1,450 | # Description:
# Define terms via Urban Dictionary
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot what is <term>? - Searches Urban Dictionary and returns definition
# hubot urban me <term> - Searches Urban Dictionary and returns definition
# hubot urban define me <term> - Searches Urban Dictionary and returns definition
# hubot urban example me <term> - Searches Urban Dictionary and returns example
#
# Author:
# Travis Jeffery (@travisjeffery)
# Robbie Trencheny (@Robbie)
#
# Contributors:
# Benjamin Eidelman (@beneidel)
module.exports = (robot) ->
robot.respond /what ?is ([^\?]*)[\?]*/i, (msg) ->
urbanDict msg, msg.match[1], (found, entry, sounds) ->
if !found
msg.send "I don't know what \"#{msg.match[1]}\" is"
return
msg.send "#{entry.definition}"
if sounds and sounds.length
msg.send "#{sounds.join(' ')}"
robot.respond /(urban)( define)?( example)?( me)? (.*)/i, (msg) ->
urbanDict msg, msg.match[5], (found, entry, sounds) ->
if !found
msg.send "\"#{msg.match[5]}\" not found"
return
if msg.match[3]
msg.send "#{entry.example}"
else
msg.send "#{entry.definition}"
if sounds and sounds.length
msg.send "#{sounds.join(' ')}"
urbanDict = (msg, query, callback) ->
msg.http("http://api.urbandictionary.com/v0/define?term=#{escape(query)}")
.get() (err, res, body) ->
result = JSON.parse(body)
if result.list.length
callback(true, result.list[0], result.sounds)
else
callback(false)
| 55888 | # Description:
# Define terms via Urban Dictionary
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot what is <term>? - Searches Urban Dictionary and returns definition
# hubot urban me <term> - Searches Urban Dictionary and returns definition
# hubot urban define me <term> - Searches Urban Dictionary and returns definition
# hubot urban example me <term> - Searches Urban Dictionary and returns example
#
# Author:
# <NAME> (@travisjeffery)
# <NAME> (@Robbie)
#
# Contributors:
# <NAME> (@beneidel)
module.exports = (robot) ->
robot.respond /what ?is ([^\?]*)[\?]*/i, (msg) ->
urbanDict msg, msg.match[1], (found, entry, sounds) ->
if !found
msg.send "I don't know what \"#{msg.match[1]}\" is"
return
msg.send "#{entry.definition}"
if sounds and sounds.length
msg.send "#{sounds.join(' ')}"
robot.respond /(urban)( define)?( example)?( me)? (.*)/i, (msg) ->
urbanDict msg, msg.match[5], (found, entry, sounds) ->
if !found
msg.send "\"#{msg.match[5]}\" not found"
return
if msg.match[3]
msg.send "#{entry.example}"
else
msg.send "#{entry.definition}"
if sounds and sounds.length
msg.send "#{sounds.join(' ')}"
urbanDict = (msg, query, callback) ->
msg.http("http://api.urbandictionary.com/v0/define?term=#{escape(query)}")
.get() (err, res, body) ->
result = JSON.parse(body)
if result.list.length
callback(true, result.list[0], result.sounds)
else
callback(false)
| true | # Description:
# Define terms via Urban Dictionary
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot what is <term>? - Searches Urban Dictionary and returns definition
# hubot urban me <term> - Searches Urban Dictionary and returns definition
# hubot urban define me <term> - Searches Urban Dictionary and returns definition
# hubot urban example me <term> - Searches Urban Dictionary and returns example
#
# Author:
# PI:NAME:<NAME>END_PI (@travisjeffery)
# PI:NAME:<NAME>END_PI (@Robbie)
#
# Contributors:
# PI:NAME:<NAME>END_PI (@beneidel)
module.exports = (robot) ->
robot.respond /what ?is ([^\?]*)[\?]*/i, (msg) ->
urbanDict msg, msg.match[1], (found, entry, sounds) ->
if !found
msg.send "I don't know what \"#{msg.match[1]}\" is"
return
msg.send "#{entry.definition}"
if sounds and sounds.length
msg.send "#{sounds.join(' ')}"
robot.respond /(urban)( define)?( example)?( me)? (.*)/i, (msg) ->
urbanDict msg, msg.match[5], (found, entry, sounds) ->
if !found
msg.send "\"#{msg.match[5]}\" not found"
return
if msg.match[3]
msg.send "#{entry.example}"
else
msg.send "#{entry.definition}"
if sounds and sounds.length
msg.send "#{sounds.join(' ')}"
urbanDict = (msg, query, callback) ->
msg.http("http://api.urbandictionary.com/v0/define?term=#{escape(query)}")
.get() (err, res, body) ->
result = JSON.parse(body)
if result.list.length
callback(true, result.list[0], result.sounds)
else
callback(false)
|
[
{
"context": "tname.length\n\n key = if dirname is '.' then modname else Path.join(dirname, modname)\n definition = require Path.resolve(compone",
"end": 10172,
"score": 0.8604668974876404,
"start": 10132,
"tag": "KEY",
"value": "modname else Path.join(dirname, modname)"
}
] | source/index.coffee | bocodigitalmedia/boco-ioc | 0 | configure = ({Async, Promise, Glob, Path, EventEmitter, promiseCallback} = {}) ->
if typeof require is 'function'
Async ?= require 'async'
Promise ?= require 'bluebird'
Glob ?= require 'glob'
Path ?= require 'path'
EventEmitter ?= require('events').EventEmitter
promiseCallback ?= (promise, done) ->
fn = if typeof promise.done is 'function' then 'done' else 'then'
resolve = (args...) -> done null, args...
reject = (error) -> done error
promise[fn] resolve, reject
class Exception extends Error
name: null
payload: null
constructor: (payload) ->
return new Exception payload unless @ instanceof Exception
@payload = payload
@name = @constructor.name
Error.captureStackTrace @, @constructor
class ComponentTimedOut extends Exception
constructor: (payload) ->
return new ComponentTimedOut payload unless @ instanceof ComponentTimedOut
super payload
@message = "Component '#{@payload.key}' timed out."
class NotImplemented extends Exception
constructor: (payload) ->
return new NotImplemented payload unless @ instanceof NotImplemented
super payload
@message = "Not implemented."
class ComponentAlreadyDefined extends Exception
constructor: (payload) ->
return new ComponentAlreadyDefined payload unless @ instanceof ComponentAlreadyDefined
super payload
@message = "Component already defined: '#{@payload.key}'."
class ComponentNotDefined extends Exception
constructor: (payload) ->
return new ComponentNotDefined payload unless @ instanceof ComponentNotDefined
super payload
@message = "Component not defined: '#{@payload.key}'."
class ComponentDependenciesNotDefined extends Exception
constructor: (payload) ->
return new ComponentDependenciesNotDefined payload unless @ instanceof ComponentDependenciesNotDefined
super payload
@message = "Component '#{@payload.key}' has undefined dependencies: #{@payload.dependencies.join(',')}."
class ComponentNotAcyclic extends Exception
constructor: (payload) ->
return new ComponentNotAcyclic payload unless @ instanceof ComponentNotAcyclic
super payload
count = @payload.cycles.length
cycles = @payload.cycles
.map((cycle, index) -> "\t#{index}: #{cycle.join '/'}")
.join "\n"
@message = "Component '#{@payload.key}' has #{count} dependency cycle(s):\n#{cycles}"
class Component
key: null
dependencies: null
factory: null
factoryType: null
constructor: (props = {}) ->
@key = props.key
@factoryType = props.factoryType ? null
@dependencies = props.dependencies ? null
@factory = props.factory ? (injections..., done) ->
return done NotImplemented() if typeof done is 'function'
throw NotImplemented()
getDependencyKeys: ->
throw NotImplemented()
guessFactoryType: ->
'async'
getFactoryType: ->
@factoryType ? @guessFactoryType()
injectPromiseFactory: (injections, done) ->
@injectSyncFactory injections, (error, promise) ->
return done error if error?
promiseCallback promise, done
injectAsyncFactory: (injections, done) ->
return done NotImplemented() if typeof done is 'function'
throw NotImplemented()
injectSyncFactory: (injections, done) ->
return done NotImplemented() if typeof done is 'function'
throw NotImplemented()
inject: (injections, done) ->
switch @getFactoryType()
when 'promise' then @injectPromiseFactory injections, done
when 'async' then @injectAsyncFactory injections, done
when 'sync' then @injectSyncFactory injections, done
else throw Error("Cannot inject component, unknown factoryType: '#{@factoryType}'")
class ComponentWithDependenciesArray extends Component
getDependencyKeys: ->
@dependencies ? []
guessFactoryType: ->
return 'sync' if @factory.length is @dependencies.length
return 'async'
injectAsyncFactory: (injections, done) ->
try @factory injections..., done
catch error then done error
injectSyncFactory: (injections, done) ->
try done null, @factory(injections...)
catch error then done error
class ComponentWithDependenciesObject extends Component
getDependencyKeys: ->
({key, val} for own key, val of @dependencies).map ({key, val}) ->
if typeof val is 'string' then val else key
guessFactoryType: ->
return 'sync' if @dependencies.length is 0 and @factory.length is 0
return 'sync' if @factory.length is 1
return 'async'
createInjectionObject: (injections) ->
collectInjections = (memo, key, index) ->
memo[key] = injections[index]
memo
injectionKeys = (key for own key of @dependencies)
injectionObject = injectionKeys.reduce collectInjections, {}
injectionObject
injectSyncFactory: (injections, done) ->
injectionObject = @createInjectionObject injections
try done null, @factory(injectionObject)
catch error then done error
injectAsyncFactory: (injections, done) ->
injectionObject = @createInjectionObject injections
try @factory injectionObject, done
catch error then done error
class ComponentWithoutDependencies extends Component
getDependencyKeys: ->
[]
guessFactoryType: ->
return 'async' if @factory.length is 1
return 'sync'
injectAsyncFactory: (injections, done) ->
try @factory done
catch error then done error
injectSyncFactory: (injections, done) ->
try done null, @factory()
catch error then done error
class Container
components: null
promises: null
componentFactory: null
componentTimeout: null
constructor: (props = {}) ->
@components = props.components ? Object.create(null)
@promises = props.promises ? Object.create(null)
@componentFactory = props.componentFactory ? new ComponentFactory
@componentTimeout = props.componentTimeout ? 30000
@emitter = props.emitter ? new EventEmitter
on: (args...) -> @emitter.on args...
once: (args...) -> @emitter.once args...
removeListener: (args...) -> @emitter.removeListener args...
removeAllListeners: (args...) -> @emitter.removeAllListeners args...
defineComponent: (key, args...) ->
throw ComponentAlreadyDefined {key} if @components[key]?
@components[key] = @componentFactory.construct args...
delete @promises[key]
@emitter.emit "component.defined",
key: key
container: @
createComponentPromise: (key) ->
@emitter.emit "component.resolving",
key: key
container: @
new Promise (resolve, reject) =>
done = (error, result) =>
clearTimeout timeoutId if timeoutId?
if error?
reject error
@emitter.emit 'component.error',
key: key
container: @
error: error
else
resolve result
@emitter.emit 'component.resolved',
key: key
container: @
result: result
timeoutId = setTimeout done.bind(null, ComponentTimedOut({key})), @componentTimeout
component = @components[key]
dependencyKeys = component.getDependencyKeys()
Async.map dependencyKeys, @resolveComponent.bind(@), (error, injections) ->
return done error if error?
component.inject injections, done
isComponentDefined: (key) ->
@components[key]?
assertComponentDefined: (key) ->
throw ComponentNotDefined {key} unless @isComponentDefined(key)
assertComponentDependenciesDefined: (key) ->
component = @components[key]
dependencies = component.getDependencyKeys().filter (key) => !@isComponentDefined(key)
throw ComponentDependenciesNotDefined {key, dependencies} if dependencies.length
getComponentCycles: (key, stack = []) ->
return [stack.concat(key)] if key in stack
component = @components[key]
return [] unless component?
stack = stack.concat key
reduceDependencyCycles = (memo, key) =>
memo.concat @getComponentCycles(key, stack)
dependencyKeys = component.getDependencyKeys()
dependencyKeys.reduce reduceDependencyCycles, []
assertComponentAcyclic: (key) ->
cycles = @getComponentCycles key
throw ComponentNotAcyclic {key, cycles} if cycles.length
validateComponent: (key) ->
@assertComponentDefined key
@assertComponentDependenciesDefined key
@assertComponentAcyclic key
validateComponents: ->
@validateComponent key for own key of @components
resolveComponent: (key, done) ->
unless @promises[key]
try @validateComponent key
catch error then return done error
@promises[key] = @createComponentPromise key
promiseCallback @promises[key], done
class ComponentFactory
construct: ({key, dependencies, depends, factory, factoryType}) ->
dependencies ?= depends
unless dependencies?
return new ComponentWithoutDependencies {key, factory, factoryType}
if Array.isArray dependencies
return new ComponentWithDependenciesArray {key, dependencies, factory, factoryType}
if typeof dependencies is 'object'
return new ComponentWithDependenciesObject {key, dependencies, factory, factoryType}
throw Error "Cannot construct component, invalid dependencies."
class ComponentLoader
load: ({container, componentsDir, pattern}) ->
componentsDir ?= Path.resolve __dirname, "components"
pattern ?= "**/*(*.coffee|*.js)"
Glob.sync(pattern, cwd: componentsDir).forEach (componentPath) ->
dirname = Path.dirname componentPath
filename = Path.basename componentPath
extname = Path.extname componentPath
modname = do ->
filename.slice 0, filename.length - extname.length
key = if dirname is '.' then modname else Path.join(dirname, modname)
definition = require Path.resolve(componentsDir, dirname, filename)
container.defineComponent key, definition
IOC = {
configure,
Container,
ComponentFactory,
Component,
ComponentWithoutDependencies,
ComponentWithDependenciesObject,
ComponentWithDependenciesArray,
Exception,
NotImplemented,
ComponentNotDefined,
ComponentDependenciesNotDefined,
ComponentNotAcyclic,
ComponentAlreadyDefined
ComponentLoader
}
module.exports = configure()
| 202433 | configure = ({Async, Promise, Glob, Path, EventEmitter, promiseCallback} = {}) ->
if typeof require is 'function'
Async ?= require 'async'
Promise ?= require 'bluebird'
Glob ?= require 'glob'
Path ?= require 'path'
EventEmitter ?= require('events').EventEmitter
promiseCallback ?= (promise, done) ->
fn = if typeof promise.done is 'function' then 'done' else 'then'
resolve = (args...) -> done null, args...
reject = (error) -> done error
promise[fn] resolve, reject
class Exception extends Error
name: null
payload: null
constructor: (payload) ->
return new Exception payload unless @ instanceof Exception
@payload = payload
@name = @constructor.name
Error.captureStackTrace @, @constructor
class ComponentTimedOut extends Exception
constructor: (payload) ->
return new ComponentTimedOut payload unless @ instanceof ComponentTimedOut
super payload
@message = "Component '#{@payload.key}' timed out."
class NotImplemented extends Exception
constructor: (payload) ->
return new NotImplemented payload unless @ instanceof NotImplemented
super payload
@message = "Not implemented."
class ComponentAlreadyDefined extends Exception
constructor: (payload) ->
return new ComponentAlreadyDefined payload unless @ instanceof ComponentAlreadyDefined
super payload
@message = "Component already defined: '#{@payload.key}'."
class ComponentNotDefined extends Exception
constructor: (payload) ->
return new ComponentNotDefined payload unless @ instanceof ComponentNotDefined
super payload
@message = "Component not defined: '#{@payload.key}'."
class ComponentDependenciesNotDefined extends Exception
constructor: (payload) ->
return new ComponentDependenciesNotDefined payload unless @ instanceof ComponentDependenciesNotDefined
super payload
@message = "Component '#{@payload.key}' has undefined dependencies: #{@payload.dependencies.join(',')}."
class ComponentNotAcyclic extends Exception
constructor: (payload) ->
return new ComponentNotAcyclic payload unless @ instanceof ComponentNotAcyclic
super payload
count = @payload.cycles.length
cycles = @payload.cycles
.map((cycle, index) -> "\t#{index}: #{cycle.join '/'}")
.join "\n"
@message = "Component '#{@payload.key}' has #{count} dependency cycle(s):\n#{cycles}"
class Component
key: null
dependencies: null
factory: null
factoryType: null
constructor: (props = {}) ->
@key = props.key
@factoryType = props.factoryType ? null
@dependencies = props.dependencies ? null
@factory = props.factory ? (injections..., done) ->
return done NotImplemented() if typeof done is 'function'
throw NotImplemented()
getDependencyKeys: ->
throw NotImplemented()
guessFactoryType: ->
'async'
getFactoryType: ->
@factoryType ? @guessFactoryType()
injectPromiseFactory: (injections, done) ->
@injectSyncFactory injections, (error, promise) ->
return done error if error?
promiseCallback promise, done
injectAsyncFactory: (injections, done) ->
return done NotImplemented() if typeof done is 'function'
throw NotImplemented()
injectSyncFactory: (injections, done) ->
return done NotImplemented() if typeof done is 'function'
throw NotImplemented()
inject: (injections, done) ->
switch @getFactoryType()
when 'promise' then @injectPromiseFactory injections, done
when 'async' then @injectAsyncFactory injections, done
when 'sync' then @injectSyncFactory injections, done
else throw Error("Cannot inject component, unknown factoryType: '#{@factoryType}'")
class ComponentWithDependenciesArray extends Component
getDependencyKeys: ->
@dependencies ? []
guessFactoryType: ->
return 'sync' if @factory.length is @dependencies.length
return 'async'
injectAsyncFactory: (injections, done) ->
try @factory injections..., done
catch error then done error
injectSyncFactory: (injections, done) ->
try done null, @factory(injections...)
catch error then done error
class ComponentWithDependenciesObject extends Component
getDependencyKeys: ->
({key, val} for own key, val of @dependencies).map ({key, val}) ->
if typeof val is 'string' then val else key
guessFactoryType: ->
return 'sync' if @dependencies.length is 0 and @factory.length is 0
return 'sync' if @factory.length is 1
return 'async'
createInjectionObject: (injections) ->
collectInjections = (memo, key, index) ->
memo[key] = injections[index]
memo
injectionKeys = (key for own key of @dependencies)
injectionObject = injectionKeys.reduce collectInjections, {}
injectionObject
injectSyncFactory: (injections, done) ->
injectionObject = @createInjectionObject injections
try done null, @factory(injectionObject)
catch error then done error
injectAsyncFactory: (injections, done) ->
injectionObject = @createInjectionObject injections
try @factory injectionObject, done
catch error then done error
class ComponentWithoutDependencies extends Component
getDependencyKeys: ->
[]
guessFactoryType: ->
return 'async' if @factory.length is 1
return 'sync'
injectAsyncFactory: (injections, done) ->
try @factory done
catch error then done error
injectSyncFactory: (injections, done) ->
try done null, @factory()
catch error then done error
class Container
components: null
promises: null
componentFactory: null
componentTimeout: null
constructor: (props = {}) ->
@components = props.components ? Object.create(null)
@promises = props.promises ? Object.create(null)
@componentFactory = props.componentFactory ? new ComponentFactory
@componentTimeout = props.componentTimeout ? 30000
@emitter = props.emitter ? new EventEmitter
on: (args...) -> @emitter.on args...
once: (args...) -> @emitter.once args...
removeListener: (args...) -> @emitter.removeListener args...
removeAllListeners: (args...) -> @emitter.removeAllListeners args...
defineComponent: (key, args...) ->
throw ComponentAlreadyDefined {key} if @components[key]?
@components[key] = @componentFactory.construct args...
delete @promises[key]
@emitter.emit "component.defined",
key: key
container: @
createComponentPromise: (key) ->
@emitter.emit "component.resolving",
key: key
container: @
new Promise (resolve, reject) =>
done = (error, result) =>
clearTimeout timeoutId if timeoutId?
if error?
reject error
@emitter.emit 'component.error',
key: key
container: @
error: error
else
resolve result
@emitter.emit 'component.resolved',
key: key
container: @
result: result
timeoutId = setTimeout done.bind(null, ComponentTimedOut({key})), @componentTimeout
component = @components[key]
dependencyKeys = component.getDependencyKeys()
Async.map dependencyKeys, @resolveComponent.bind(@), (error, injections) ->
return done error if error?
component.inject injections, done
isComponentDefined: (key) ->
@components[key]?
assertComponentDefined: (key) ->
throw ComponentNotDefined {key} unless @isComponentDefined(key)
assertComponentDependenciesDefined: (key) ->
component = @components[key]
dependencies = component.getDependencyKeys().filter (key) => !@isComponentDefined(key)
throw ComponentDependenciesNotDefined {key, dependencies} if dependencies.length
getComponentCycles: (key, stack = []) ->
return [stack.concat(key)] if key in stack
component = @components[key]
return [] unless component?
stack = stack.concat key
reduceDependencyCycles = (memo, key) =>
memo.concat @getComponentCycles(key, stack)
dependencyKeys = component.getDependencyKeys()
dependencyKeys.reduce reduceDependencyCycles, []
assertComponentAcyclic: (key) ->
cycles = @getComponentCycles key
throw ComponentNotAcyclic {key, cycles} if cycles.length
validateComponent: (key) ->
@assertComponentDefined key
@assertComponentDependenciesDefined key
@assertComponentAcyclic key
validateComponents: ->
@validateComponent key for own key of @components
resolveComponent: (key, done) ->
unless @promises[key]
try @validateComponent key
catch error then return done error
@promises[key] = @createComponentPromise key
promiseCallback @promises[key], done
class ComponentFactory
construct: ({key, dependencies, depends, factory, factoryType}) ->
dependencies ?= depends
unless dependencies?
return new ComponentWithoutDependencies {key, factory, factoryType}
if Array.isArray dependencies
return new ComponentWithDependenciesArray {key, dependencies, factory, factoryType}
if typeof dependencies is 'object'
return new ComponentWithDependenciesObject {key, dependencies, factory, factoryType}
throw Error "Cannot construct component, invalid dependencies."
class ComponentLoader
load: ({container, componentsDir, pattern}) ->
componentsDir ?= Path.resolve __dirname, "components"
pattern ?= "**/*(*.coffee|*.js)"
Glob.sync(pattern, cwd: componentsDir).forEach (componentPath) ->
dirname = Path.dirname componentPath
filename = Path.basename componentPath
extname = Path.extname componentPath
modname = do ->
filename.slice 0, filename.length - extname.length
key = if dirname is '.' then <KEY>
definition = require Path.resolve(componentsDir, dirname, filename)
container.defineComponent key, definition
IOC = {
configure,
Container,
ComponentFactory,
Component,
ComponentWithoutDependencies,
ComponentWithDependenciesObject,
ComponentWithDependenciesArray,
Exception,
NotImplemented,
ComponentNotDefined,
ComponentDependenciesNotDefined,
ComponentNotAcyclic,
ComponentAlreadyDefined
ComponentLoader
}
module.exports = configure()
| true | configure = ({Async, Promise, Glob, Path, EventEmitter, promiseCallback} = {}) ->
if typeof require is 'function'
Async ?= require 'async'
Promise ?= require 'bluebird'
Glob ?= require 'glob'
Path ?= require 'path'
EventEmitter ?= require('events').EventEmitter
promiseCallback ?= (promise, done) ->
fn = if typeof promise.done is 'function' then 'done' else 'then'
resolve = (args...) -> done null, args...
reject = (error) -> done error
promise[fn] resolve, reject
class Exception extends Error
name: null
payload: null
constructor: (payload) ->
return new Exception payload unless @ instanceof Exception
@payload = payload
@name = @constructor.name
Error.captureStackTrace @, @constructor
class ComponentTimedOut extends Exception
constructor: (payload) ->
return new ComponentTimedOut payload unless @ instanceof ComponentTimedOut
super payload
@message = "Component '#{@payload.key}' timed out."
class NotImplemented extends Exception
constructor: (payload) ->
return new NotImplemented payload unless @ instanceof NotImplemented
super payload
@message = "Not implemented."
class ComponentAlreadyDefined extends Exception
constructor: (payload) ->
return new ComponentAlreadyDefined payload unless @ instanceof ComponentAlreadyDefined
super payload
@message = "Component already defined: '#{@payload.key}'."
class ComponentNotDefined extends Exception
constructor: (payload) ->
return new ComponentNotDefined payload unless @ instanceof ComponentNotDefined
super payload
@message = "Component not defined: '#{@payload.key}'."
class ComponentDependenciesNotDefined extends Exception
constructor: (payload) ->
return new ComponentDependenciesNotDefined payload unless @ instanceof ComponentDependenciesNotDefined
super payload
@message = "Component '#{@payload.key}' has undefined dependencies: #{@payload.dependencies.join(',')}."
class ComponentNotAcyclic extends Exception
constructor: (payload) ->
return new ComponentNotAcyclic payload unless @ instanceof ComponentNotAcyclic
super payload
count = @payload.cycles.length
cycles = @payload.cycles
.map((cycle, index) -> "\t#{index}: #{cycle.join '/'}")
.join "\n"
@message = "Component '#{@payload.key}' has #{count} dependency cycle(s):\n#{cycles}"
class Component
key: null
dependencies: null
factory: null
factoryType: null
constructor: (props = {}) ->
@key = props.key
@factoryType = props.factoryType ? null
@dependencies = props.dependencies ? null
@factory = props.factory ? (injections..., done) ->
return done NotImplemented() if typeof done is 'function'
throw NotImplemented()
getDependencyKeys: ->
throw NotImplemented()
guessFactoryType: ->
'async'
getFactoryType: ->
@factoryType ? @guessFactoryType()
injectPromiseFactory: (injections, done) ->
@injectSyncFactory injections, (error, promise) ->
return done error if error?
promiseCallback promise, done
injectAsyncFactory: (injections, done) ->
return done NotImplemented() if typeof done is 'function'
throw NotImplemented()
injectSyncFactory: (injections, done) ->
return done NotImplemented() if typeof done is 'function'
throw NotImplemented()
inject: (injections, done) ->
switch @getFactoryType()
when 'promise' then @injectPromiseFactory injections, done
when 'async' then @injectAsyncFactory injections, done
when 'sync' then @injectSyncFactory injections, done
else throw Error("Cannot inject component, unknown factoryType: '#{@factoryType}'")
class ComponentWithDependenciesArray extends Component
getDependencyKeys: ->
@dependencies ? []
guessFactoryType: ->
return 'sync' if @factory.length is @dependencies.length
return 'async'
injectAsyncFactory: (injections, done) ->
try @factory injections..., done
catch error then done error
injectSyncFactory: (injections, done) ->
try done null, @factory(injections...)
catch error then done error
class ComponentWithDependenciesObject extends Component
getDependencyKeys: ->
({key, val} for own key, val of @dependencies).map ({key, val}) ->
if typeof val is 'string' then val else key
guessFactoryType: ->
return 'sync' if @dependencies.length is 0 and @factory.length is 0
return 'sync' if @factory.length is 1
return 'async'
createInjectionObject: (injections) ->
collectInjections = (memo, key, index) ->
memo[key] = injections[index]
memo
injectionKeys = (key for own key of @dependencies)
injectionObject = injectionKeys.reduce collectInjections, {}
injectionObject
injectSyncFactory: (injections, done) ->
injectionObject = @createInjectionObject injections
try done null, @factory(injectionObject)
catch error then done error
injectAsyncFactory: (injections, done) ->
injectionObject = @createInjectionObject injections
try @factory injectionObject, done
catch error then done error
class ComponentWithoutDependencies extends Component
getDependencyKeys: ->
[]
guessFactoryType: ->
return 'async' if @factory.length is 1
return 'sync'
injectAsyncFactory: (injections, done) ->
try @factory done
catch error then done error
injectSyncFactory: (injections, done) ->
try done null, @factory()
catch error then done error
class Container
components: null
promises: null
componentFactory: null
componentTimeout: null
constructor: (props = {}) ->
@components = props.components ? Object.create(null)
@promises = props.promises ? Object.create(null)
@componentFactory = props.componentFactory ? new ComponentFactory
@componentTimeout = props.componentTimeout ? 30000
@emitter = props.emitter ? new EventEmitter
on: (args...) -> @emitter.on args...
once: (args...) -> @emitter.once args...
removeListener: (args...) -> @emitter.removeListener args...
removeAllListeners: (args...) -> @emitter.removeAllListeners args...
defineComponent: (key, args...) ->
throw ComponentAlreadyDefined {key} if @components[key]?
@components[key] = @componentFactory.construct args...
delete @promises[key]
@emitter.emit "component.defined",
key: key
container: @
createComponentPromise: (key) ->
@emitter.emit "component.resolving",
key: key
container: @
new Promise (resolve, reject) =>
done = (error, result) =>
clearTimeout timeoutId if timeoutId?
if error?
reject error
@emitter.emit 'component.error',
key: key
container: @
error: error
else
resolve result
@emitter.emit 'component.resolved',
key: key
container: @
result: result
timeoutId = setTimeout done.bind(null, ComponentTimedOut({key})), @componentTimeout
component = @components[key]
dependencyKeys = component.getDependencyKeys()
Async.map dependencyKeys, @resolveComponent.bind(@), (error, injections) ->
return done error if error?
component.inject injections, done
isComponentDefined: (key) ->
@components[key]?
assertComponentDefined: (key) ->
throw ComponentNotDefined {key} unless @isComponentDefined(key)
assertComponentDependenciesDefined: (key) ->
component = @components[key]
dependencies = component.getDependencyKeys().filter (key) => !@isComponentDefined(key)
throw ComponentDependenciesNotDefined {key, dependencies} if dependencies.length
getComponentCycles: (key, stack = []) ->
return [stack.concat(key)] if key in stack
component = @components[key]
return [] unless component?
stack = stack.concat key
reduceDependencyCycles = (memo, key) =>
memo.concat @getComponentCycles(key, stack)
dependencyKeys = component.getDependencyKeys()
dependencyKeys.reduce reduceDependencyCycles, []
assertComponentAcyclic: (key) ->
cycles = @getComponentCycles key
throw ComponentNotAcyclic {key, cycles} if cycles.length
validateComponent: (key) ->
@assertComponentDefined key
@assertComponentDependenciesDefined key
@assertComponentAcyclic key
validateComponents: ->
@validateComponent key for own key of @components
resolveComponent: (key, done) ->
unless @promises[key]
try @validateComponent key
catch error then return done error
@promises[key] = @createComponentPromise key
promiseCallback @promises[key], done
class ComponentFactory
construct: ({key, dependencies, depends, factory, factoryType}) ->
dependencies ?= depends
unless dependencies?
return new ComponentWithoutDependencies {key, factory, factoryType}
if Array.isArray dependencies
return new ComponentWithDependenciesArray {key, dependencies, factory, factoryType}
if typeof dependencies is 'object'
return new ComponentWithDependenciesObject {key, dependencies, factory, factoryType}
throw Error "Cannot construct component, invalid dependencies."
class ComponentLoader
load: ({container, componentsDir, pattern}) ->
componentsDir ?= Path.resolve __dirname, "components"
pattern ?= "**/*(*.coffee|*.js)"
Glob.sync(pattern, cwd: componentsDir).forEach (componentPath) ->
dirname = Path.dirname componentPath
filename = Path.basename componentPath
extname = Path.extname componentPath
modname = do ->
filename.slice 0, filename.length - extname.length
key = if dirname is '.' then PI:KEY:<KEY>END_PI
definition = require Path.resolve(componentsDir, dirname, filename)
container.defineComponent key, definition
IOC = {
configure,
Container,
ComponentFactory,
Component,
ComponentWithoutDependencies,
ComponentWithDependenciesObject,
ComponentWithDependenciesArray,
Exception,
NotImplemented,
ComponentNotDefined,
ComponentDependenciesNotDefined,
ComponentNotAcyclic,
ComponentAlreadyDefined
ComponentLoader
}
module.exports = configure()
|
[
{
"context": " -wbl -j \"ajax-cat.js\" -c *.coffee\n# ssh -L 8888:10.10.24.118:80 odchazel@ufallab.ms.mff.cuni.cz\n",
"end": 69,
"score": 0.8909597396850586,
"start": 58,
"tag": "IP_ADDRESS",
"value": "0.10.24.118"
},
{
"context": "-cat.js\" -c *.coffee\n# ssh -L 8888:10.10.24.118:80... | lib/ajax-cat/public/ajax-cat.coffee | hypertornado/ajax-cat | 2 | # coffee -wbl -j "ajax-cat.js" -c *.coffee
# ssh -L 8888:10.10.24.118:80 odchazel@ufallab.ms.mff.cuni.cz
| 179951 | # coffee -wbl -j "ajax-cat.js" -c *.coffee
# ssh -L 8888:10.10.24.118:80 <EMAIL>
| true | # coffee -wbl -j "ajax-cat.js" -c *.coffee
# ssh -L 8888:10.10.24.118:80 PI:EMAIL:<EMAIL>END_PI
|
[
{
"context": ".3.18 Darwin/14.0.0'\n 'Authorization':'oauth 5774b305d2ae4469a2c9258956ea49'\n 'Content-Type':'application/json'\n }\n ",
"end": 508,
"score": 0.9142197370529175,
"start": 478,
"tag": "PASSWORD",
"value": "5774b305d2ae4469a2c9258956ea49"
}
] | lib/pushEvernote.coffee | youqingkui/zhihufav2evernote | 0 | request = require('request')
async = require('async')
makeNote = require('./createNote')
Evernote = require('evernote').Evernote
cheerio = require('cheerio')
crypto = require('crypto')
txErr = require('./txErr')
Task = require('../models/task')
instapush = require('./instapush_notify')
class PushEvernote
constructor:(@url, @noteStore, @noteBook) ->
@headers = {
'User-Agent':'osee2unifiedRelease/332 CFNetwork/711.3.18 Darwin/14.0.0'
'Authorization':'oauth 5774b305d2ae4469a2c9258956ea49'
'Content-Type':'application/json'
}
@resourceArr = []
pushNote:(cb) ->
self = @
async.series [
(callback) ->
self.getContent(callback)
(callback) ->
self.changeContent(callback)
(callback) ->
self.createNote(callback)
(callback) ->
self.changeStatus(callback)
]
,() ->
cb()
changeStatus:(cb) ->
self = @
async.waterfall [
(callback) ->
Task.findOne {url:self.url}, (err, row) ->
return txErr {err:err, fun:'changeStatus', url:self.url}, cb if err
if not row
return txErr {err:'not find url change', fun:'changeStatus', url:self.url}, cb
callback(null, row)
(row) ->
row.status = 2
row.guid = self.guid
row.save (err) ->
return txErr {err:err, fun:'changeStatus-save', url:self.url}, cb if err
cb()
]
getContent:(cb) ->
self = @
op = {
url:self.url
headers:self.headers
gzip:true
}
request.get op, (err, res, body) ->
return txErr {err:err, fun:'getContent'}, cb if err
data = JSON.parse(body)
if data.error
console.log self.url
console.log data
return cb(data.error.message)
self.title = data.question.title.trim().replace("\n", "")
console.log "title ==>", self.title
self.tagArr = []
self.sourceUrl = 'http://www.zhihu.com/question/'+
data.question.id + '/answer/' + data.id
self.content = data.content
self.created = Date.now / 1000
# self.updated = data.updated_time
cb()
# 转换内容
changeContent: (cb) ->
self = @
$ = cheerio.load(self.content, {decodeEntities: false})
$("*")
.map (i, elem) ->
for k, v of elem.attribs
if k != 'data-actualsrc' and k != 'src' and k !='href' and k != 'style'
$(this).removeAttr(k)
if k is 'href'
if !self.checkUrl(v)
$(this).removeAttr(k)
$("iframe").remove()
$("article").each () ->
$(this).replaceWith('<div>'+ $(this).html()+ '</div>')
$("section").each () ->
$(this).replaceWith('<div>'+ $(this).html()+ '</div>')
$("header").each () ->
$(this).replaceWith('<div>'+ $(this).html()+ '</div>')
$("noscript").each () ->
$(this).replaceWith('<div>'+ $(this).html()+ '</div>')
imgs = $("img")
console.log "#{self.title} find img length => #{imgs.length}"
imgsIndex = 0
async.eachLimit imgs, 5, (item, callback) ->
src = $(item).attr('data-actualsrc')
if not src
src = $(item).attr('src')
imgsIndex += 1
console.log "开始获取[#{imgsIndex}, #{self.title}, #{src}]"
self.readImgRes src, (err, resource) ->
return txErr {err:err, title:self.title, url:self.url,fun:'changeContent'}, cb if err
self.resourceArr.push resource
md5 = crypto.createHash('md5')
md5.update(resource.image)
hexHash = md5.digest('hex')
newTag = "<en-media type=#{resource.mime} hash=#{hexHash} />"
$(item).replaceWith(newTag)
callback()
,() ->
console.log "#{self.title} #{imgs.length} imgs down ok"
self.enContent = $.html({xmlMode:true, decodeEntities: true})
cb()
# 创建笔记
createNote: (cb) ->
self = @
makeNote @noteStore, @title, @tagArr, @enContent, @sourceUrl, @resourceArr,
@created, @updated, @noteBook
(err, note) ->
if err
return txErr({err:err, title:self.title}, cb) if err
self.guid = note.guid
console.log "+++++++++++++++++++++++"
console.log "#{note.title} create ok"
console.log "+++++++++++++++++++++++"
instapush(note.title)
cb()
# 读取远程图片
readImgRes: (imgUrl, cb) ->
self = @
op = self.reqOp(imgUrl)
op.encoding = 'binary'
op.timeout = 40000
async.auto
readImg:(callback) ->
request.get op, (err, res, body) ->
return cb(err) if err
mimeType = res.headers['content-type']
if not mimeType
mimeType = 'image/jpeg'
else
mimeType = mimeType.split(';')[0]
callback(null, body, mimeType)
enImg:['readImg', (callback, result) ->
mimeType = result.readImg[1]
image = new Buffer(result.readImg[0], 'binary')
hash = image.toString('base64')
data = new Evernote.Data()
data.size = image.length
data.bodyHash = hash
data.body = image
resource = new Evernote.Resource()
resource.mime = mimeType
resource.data = data
resource.image = image
cb(null, resource)
]
reqOp:(getUrl) ->
options =
url:getUrl
headers:
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36',
return options
checkUrl:(href) ->
strRegex = "^((https|http|ftp|rtsp|mms)?://)"
+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?"
+ "(([0-9]{1,3}/.){3}[0-9]{1,3}" + "|"
+ "([0-9a-z_!~*'()-]+/.)*"
+ "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]/."
+ "[a-z]{2,6})"
+ "(:[0-9]{1,4})?"
+ "((/?)|"
+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"
re = new RegExp(strRegex)
if re.test href
return true
else
return false
module.exports = PushEvernote | 121811 | request = require('request')
async = require('async')
makeNote = require('./createNote')
Evernote = require('evernote').Evernote
cheerio = require('cheerio')
crypto = require('crypto')
txErr = require('./txErr')
Task = require('../models/task')
instapush = require('./instapush_notify')
class PushEvernote
constructor:(@url, @noteStore, @noteBook) ->
@headers = {
'User-Agent':'osee2unifiedRelease/332 CFNetwork/711.3.18 Darwin/14.0.0'
'Authorization':'oauth <PASSWORD>'
'Content-Type':'application/json'
}
@resourceArr = []
pushNote:(cb) ->
self = @
async.series [
(callback) ->
self.getContent(callback)
(callback) ->
self.changeContent(callback)
(callback) ->
self.createNote(callback)
(callback) ->
self.changeStatus(callback)
]
,() ->
cb()
changeStatus:(cb) ->
self = @
async.waterfall [
(callback) ->
Task.findOne {url:self.url}, (err, row) ->
return txErr {err:err, fun:'changeStatus', url:self.url}, cb if err
if not row
return txErr {err:'not find url change', fun:'changeStatus', url:self.url}, cb
callback(null, row)
(row) ->
row.status = 2
row.guid = self.guid
row.save (err) ->
return txErr {err:err, fun:'changeStatus-save', url:self.url}, cb if err
cb()
]
getContent:(cb) ->
self = @
op = {
url:self.url
headers:self.headers
gzip:true
}
request.get op, (err, res, body) ->
return txErr {err:err, fun:'getContent'}, cb if err
data = JSON.parse(body)
if data.error
console.log self.url
console.log data
return cb(data.error.message)
self.title = data.question.title.trim().replace("\n", "")
console.log "title ==>", self.title
self.tagArr = []
self.sourceUrl = 'http://www.zhihu.com/question/'+
data.question.id + '/answer/' + data.id
self.content = data.content
self.created = Date.now / 1000
# self.updated = data.updated_time
cb()
# 转换内容
changeContent: (cb) ->
self = @
$ = cheerio.load(self.content, {decodeEntities: false})
$("*")
.map (i, elem) ->
for k, v of elem.attribs
if k != 'data-actualsrc' and k != 'src' and k !='href' and k != 'style'
$(this).removeAttr(k)
if k is 'href'
if !self.checkUrl(v)
$(this).removeAttr(k)
$("iframe").remove()
$("article").each () ->
$(this).replaceWith('<div>'+ $(this).html()+ '</div>')
$("section").each () ->
$(this).replaceWith('<div>'+ $(this).html()+ '</div>')
$("header").each () ->
$(this).replaceWith('<div>'+ $(this).html()+ '</div>')
$("noscript").each () ->
$(this).replaceWith('<div>'+ $(this).html()+ '</div>')
imgs = $("img")
console.log "#{self.title} find img length => #{imgs.length}"
imgsIndex = 0
async.eachLimit imgs, 5, (item, callback) ->
src = $(item).attr('data-actualsrc')
if not src
src = $(item).attr('src')
imgsIndex += 1
console.log "开始获取[#{imgsIndex}, #{self.title}, #{src}]"
self.readImgRes src, (err, resource) ->
return txErr {err:err, title:self.title, url:self.url,fun:'changeContent'}, cb if err
self.resourceArr.push resource
md5 = crypto.createHash('md5')
md5.update(resource.image)
hexHash = md5.digest('hex')
newTag = "<en-media type=#{resource.mime} hash=#{hexHash} />"
$(item).replaceWith(newTag)
callback()
,() ->
console.log "#{self.title} #{imgs.length} imgs down ok"
self.enContent = $.html({xmlMode:true, decodeEntities: true})
cb()
# 创建笔记
createNote: (cb) ->
self = @
makeNote @noteStore, @title, @tagArr, @enContent, @sourceUrl, @resourceArr,
@created, @updated, @noteBook
(err, note) ->
if err
return txErr({err:err, title:self.title}, cb) if err
self.guid = note.guid
console.log "+++++++++++++++++++++++"
console.log "#{note.title} create ok"
console.log "+++++++++++++++++++++++"
instapush(note.title)
cb()
# 读取远程图片
readImgRes: (imgUrl, cb) ->
self = @
op = self.reqOp(imgUrl)
op.encoding = 'binary'
op.timeout = 40000
async.auto
readImg:(callback) ->
request.get op, (err, res, body) ->
return cb(err) if err
mimeType = res.headers['content-type']
if not mimeType
mimeType = 'image/jpeg'
else
mimeType = mimeType.split(';')[0]
callback(null, body, mimeType)
enImg:['readImg', (callback, result) ->
mimeType = result.readImg[1]
image = new Buffer(result.readImg[0], 'binary')
hash = image.toString('base64')
data = new Evernote.Data()
data.size = image.length
data.bodyHash = hash
data.body = image
resource = new Evernote.Resource()
resource.mime = mimeType
resource.data = data
resource.image = image
cb(null, resource)
]
reqOp:(getUrl) ->
options =
url:getUrl
headers:
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36',
return options
checkUrl:(href) ->
strRegex = "^((https|http|ftp|rtsp|mms)?://)"
+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?"
+ "(([0-9]{1,3}/.){3}[0-9]{1,3}" + "|"
+ "([0-9a-z_!~*'()-]+/.)*"
+ "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]/."
+ "[a-z]{2,6})"
+ "(:[0-9]{1,4})?"
+ "((/?)|"
+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"
re = new RegExp(strRegex)
if re.test href
return true
else
return false
module.exports = PushEvernote | true | request = require('request')
async = require('async')
makeNote = require('./createNote')
Evernote = require('evernote').Evernote
cheerio = require('cheerio')
crypto = require('crypto')
txErr = require('./txErr')
Task = require('../models/task')
instapush = require('./instapush_notify')
class PushEvernote
constructor:(@url, @noteStore, @noteBook) ->
@headers = {
'User-Agent':'osee2unifiedRelease/332 CFNetwork/711.3.18 Darwin/14.0.0'
'Authorization':'oauth PI:PASSWORD:<PASSWORD>END_PI'
'Content-Type':'application/json'
}
@resourceArr = []
pushNote:(cb) ->
self = @
async.series [
(callback) ->
self.getContent(callback)
(callback) ->
self.changeContent(callback)
(callback) ->
self.createNote(callback)
(callback) ->
self.changeStatus(callback)
]
,() ->
cb()
changeStatus:(cb) ->
self = @
async.waterfall [
(callback) ->
Task.findOne {url:self.url}, (err, row) ->
return txErr {err:err, fun:'changeStatus', url:self.url}, cb if err
if not row
return txErr {err:'not find url change', fun:'changeStatus', url:self.url}, cb
callback(null, row)
(row) ->
row.status = 2
row.guid = self.guid
row.save (err) ->
return txErr {err:err, fun:'changeStatus-save', url:self.url}, cb if err
cb()
]
getContent:(cb) ->
self = @
op = {
url:self.url
headers:self.headers
gzip:true
}
request.get op, (err, res, body) ->
return txErr {err:err, fun:'getContent'}, cb if err
data = JSON.parse(body)
if data.error
console.log self.url
console.log data
return cb(data.error.message)
self.title = data.question.title.trim().replace("\n", "")
console.log "title ==>", self.title
self.tagArr = []
self.sourceUrl = 'http://www.zhihu.com/question/'+
data.question.id + '/answer/' + data.id
self.content = data.content
self.created = Date.now / 1000
# self.updated = data.updated_time
cb()
# 转换内容
changeContent: (cb) ->
self = @
$ = cheerio.load(self.content, {decodeEntities: false})
$("*")
.map (i, elem) ->
for k, v of elem.attribs
if k != 'data-actualsrc' and k != 'src' and k !='href' and k != 'style'
$(this).removeAttr(k)
if k is 'href'
if !self.checkUrl(v)
$(this).removeAttr(k)
$("iframe").remove()
$("article").each () ->
$(this).replaceWith('<div>'+ $(this).html()+ '</div>')
$("section").each () ->
$(this).replaceWith('<div>'+ $(this).html()+ '</div>')
$("header").each () ->
$(this).replaceWith('<div>'+ $(this).html()+ '</div>')
$("noscript").each () ->
$(this).replaceWith('<div>'+ $(this).html()+ '</div>')
imgs = $("img")
console.log "#{self.title} find img length => #{imgs.length}"
imgsIndex = 0
async.eachLimit imgs, 5, (item, callback) ->
src = $(item).attr('data-actualsrc')
if not src
src = $(item).attr('src')
imgsIndex += 1
console.log "开始获取[#{imgsIndex}, #{self.title}, #{src}]"
self.readImgRes src, (err, resource) ->
return txErr {err:err, title:self.title, url:self.url,fun:'changeContent'}, cb if err
self.resourceArr.push resource
md5 = crypto.createHash('md5')
md5.update(resource.image)
hexHash = md5.digest('hex')
newTag = "<en-media type=#{resource.mime} hash=#{hexHash} />"
$(item).replaceWith(newTag)
callback()
,() ->
console.log "#{self.title} #{imgs.length} imgs down ok"
self.enContent = $.html({xmlMode:true, decodeEntities: true})
cb()
# 创建笔记
createNote: (cb) ->
self = @
makeNote @noteStore, @title, @tagArr, @enContent, @sourceUrl, @resourceArr,
@created, @updated, @noteBook
(err, note) ->
if err
return txErr({err:err, title:self.title}, cb) if err
self.guid = note.guid
console.log "+++++++++++++++++++++++"
console.log "#{note.title} create ok"
console.log "+++++++++++++++++++++++"
instapush(note.title)
cb()
# 读取远程图片
readImgRes: (imgUrl, cb) ->
self = @
op = self.reqOp(imgUrl)
op.encoding = 'binary'
op.timeout = 40000
async.auto
readImg:(callback) ->
request.get op, (err, res, body) ->
return cb(err) if err
mimeType = res.headers['content-type']
if not mimeType
mimeType = 'image/jpeg'
else
mimeType = mimeType.split(';')[0]
callback(null, body, mimeType)
enImg:['readImg', (callback, result) ->
mimeType = result.readImg[1]
image = new Buffer(result.readImg[0], 'binary')
hash = image.toString('base64')
data = new Evernote.Data()
data.size = image.length
data.bodyHash = hash
data.body = image
resource = new Evernote.Resource()
resource.mime = mimeType
resource.data = data
resource.image = image
cb(null, resource)
]
reqOp:(getUrl) ->
options =
url:getUrl
headers:
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36',
return options
checkUrl:(href) ->
strRegex = "^((https|http|ftp|rtsp|mms)?://)"
+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?"
+ "(([0-9]{1,3}/.){3}[0-9]{1,3}" + "|"
+ "([0-9a-z_!~*'()-]+/.)*"
+ "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]/."
+ "[a-z]{2,6})"
+ "(:[0-9]{1,4})?"
+ "((/?)|"
+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"
re = new RegExp(strRegex)
if re.test href
return true
else
return false
module.exports = PushEvernote |
[
{
"context": "roduct(id: 10)\n product.updateAttributes {name: \"foobar\", id: 20}\n equal product.get('id'), 20\n equal p",
"end": 1384,
"score": 0.5628182291984558,
"start": 1378,
"tag": "USERNAME",
"value": "foobar"
},
{
"context": " equal product, product.updateAttributes {na... | tests/batman/model/model_test.coffee | amco/batman | 0 | {TestStorageAdapter} = window
QUnit.module "Batman.Model",
setup: ->
class @Product extends Batman.Model
test "constructors should always be called with new", ->
Product = @Product
raises (-> product = Product()),
(message) -> ok message; true
Namespace = Product: Product
raises (-> product = Namespace.Product()),
(message) -> ok message; true
product = new Namespace.Product()
ok product instanceof Product
test "properties can be stored", ->
product = new @Product
product.set('foo', 'bar')
equal product.get('foo'), 'bar'
test "falsey properties can be stored", ->
product = new @Product
product.set('foo', false)
equal product.get('foo'), false
test "primary key is undefined on new models", ->
product = new @Product
ok product.isNew()
ok product.get('isNew')
equal typeof product.get('id'), 'undefined'
test "primary key is 'id' by default", ->
product = new @Product(id: 10)
equal product.get('id'), 10
test "integer string ids should be coerced into integers", 1, ->
product = new @Product(id: "1234")
strictEqual product.get('id'), 1234
test "non-integer string ids should not be coerced", 1, ->
product = new @Product(id: "123d")
strictEqual product.get('id'), "123d"
test "updateAttributes will update a model's attributes", ->
product = new @Product(id: 10)
product.updateAttributes {name: "foobar", id: 20}
equal product.get('id'), 20
equal product.get('name'), "foobar"
test "updateAttributes will returns the updated record", ->
product = new @Product(id: 10)
equal product, product.updateAttributes {name: "foobar", id: 20}
test "createFromJSON will create a record using encoders", ->
@Product.encode 'name', 'id'
product = @Product.createFromJSON(name: 'Test', id: 1, description: ' ')
ok product instanceof @Product
equal product.get('id'), 1
equal product.get('name'), 'Test'
equal product.get('description'), undefined
test "createFromJSON leaves the record clean", ->
@Product.encode 'name', 'id'
product = @Product.createFromJSON(name: 'Test', id: 1, description: ' ')
equal product.get('lifecycle.state'), 'clean'
equal product.get('dirtyKeys').length, 0
test "createFromJSON will return an existing instance if in the identity map", ->
@Product.encode 'name', 'id'
product = @Product.createFromJSON(name: 'Test', id: 1, description: ' ')
otherProduct = @Product.createFromJSON(id: 1)
strictEqual product, otherProduct
test "_makeOrFindRecordFromData with a new record will add it to the loaded set and apply the attributes", ->
@Product.encode('name', 'id')
equal @Product.get('loaded.length'), 0
result = @Product._makeOrFindRecordFromData({id: 1, name: 'foo'})
equal @Product.get('loaded.length'), 1
ok @Product.get('loaded').has(result)
equal result.get('name'), 'foo'
test "_makeOrFindRecordFromData with an existing record will add it to the loaded set and apply the attributes", ->
@Product.encode('name', 'id')
product = @Product.createFromJSON(name: 'Test', id: 1, description: ' ')
equal @Product.get('loaded.length'), 1
result = @Product._makeOrFindRecordFromData({id: 1, name: 'foo'})
equal @Product.get('loaded.length'), 1
ok result == product
equal result.get('name'), 'foo'
test "primary key can be changed by setting primary key on the model class", ->
@Product.set 'primaryKey', 'uuid'
product = new @Product(uuid: "abc123")
equal product.get('id'), 'abc123'
test 'the \'lifecycle.state\' key should be bindable', ->
p = new @Product()
equal p.get('lifecycle.state'), "clean"
p.observe 'lifecycle.state', spy = createSpy()
p.set('unrelatedkey', 'silly')
ok spy.called
test 'bindable isDirty should correctly reflect an object\`s dirtiness', ->
p = new @Product()
equal p.get('lifecycle.state'), 'clean'
ok !p.get('isDirty')
p.set('waffle', 'tasty')
equal p.get('lifecycle.state'), 'dirty'
ok p.get('isDirty')
test 'the instantiated storage adapter should be returned when persisting', ->
returned = false
class StorageAdapter extends Batman.StorageAdapter
isTestStorageAdapter: true
class Product extends Batman.Model
returned = @persist StorageAdapter
ok returned.isTestStorageAdapter
test 'Nested _withoutDirtyTracking does not reset flag', ->
p = new @Product()
p._withoutDirtyTracking ->
equal p._pauseDirtyTracking, true
p._withoutDirtyTracking -> return
equal p._pauseDirtyTracking, true
equal p._pauseDirtyTracking, false
test 'options passed to persist should be mixed in to the storage adapter once instantiated', ->
returned = false
class StorageAdapter extends Batman.StorageAdapter
isTestStorageAdapter: true
class Product extends Batman.Model
@persist StorageAdapter, {foo: 'bar'}, {corge: 'corge'}
equal Product.storageAdapter().foo, 'bar'
equal Product.storageAdapter().corge, 'corge'
class Order extends Batman.Model
adapter = new StorageAdapter(Order)
Order.persist adapter, {baz: 'qux'}
equal adapter.baz, 'qux'
test "get('resourceName') should use the class level resourceName property", ->
class Product extends Batman.Model
@resourceName: 'foobar'
equal Product.get('resourceName'), 'foobar'
test "get('resourceName') should use the prototype level resourceName property", ->
oldError = Batman.developer
Batman.developer.error = createSpy()
class Product extends Batman.Model
resourceName: 'foobar'
equal Product.get('resourceName'), 'foobar'
Batman.developer.error = oldError
test "get('resourceName') should use the function name failing all else", ->
class Product extends Batman.Model
equal Product.get('resourceName'), 'product'
QUnit.module "Batman.Model class clearing",
setup: ->
class @Product extends Batman.Model
@encode 'name', 'cost'
@adapter = new TestStorageAdapter(@Product)
@adapter.storage =
'products1': {name: "One", cost: 10, id:1}
@Product.persist @adapter
asyncTest 'clearing the model should remove instances from the identity map', ->
@Product.load =>
equal @Product.get('loaded.length'), 1
@Product.clear()
equal @Product.get('loaded.length'), 0
QUnit.start()
asyncTest 'model will reload data from storage after clear', ->
@Product.find 1, (e, p) =>
equal p.get('cost'), 10
@adapter.storage =
'products1': {name: "One", cost: 20, id:1}
@Product.clear()
p.load (e, p) =>
equal p.get('cost'), 20
QUnit.start()
asyncTest "errors are cleared on load", ->
product = new @Product(id: 1)
product.get('errors').add "product", "generic error"
equal product.get('errors').length, 1
product.load =>
equal product.get('errors').length, 0
QUnit.start()
asyncTest 'model will be in clean state after reload', ->
@Product.find 1, (e, p) =>
equal p.get('cost'), 10
p.set('cost', 20)
equal p.get('lifecycle.state'), 'dirty'
@Product.find 1, (e, p) =>
equal p.get('lifecycle.state'), 'clean'
QUnit.start()
asyncTest 'model(s) will be in clean state after reload', ->
product = new @Product(id: 2)
p = @Product
p.load =>
equal p.get('loaded.first.cost'), 10
p.set('loaded.first.cost', 20)
equal p.get('loaded.first.lifecycle.state'), 'dirty'
p.load =>
equal p.get('loaded.first.lifecycle.state'), 'clean'
QUnit.start()
test "class promise accessors will be recalculated after clear", ->
i = 0
@Product.classAccessor 'promise', promise: (deliver) -> deliver(null, i++)
equal @Product.get('promise'), 0
@Product.clear()
equal @Product.get('promise'), 1
QUnit.module 'Batman.Model.urlNestsUnder',
setup: ->
class @Product extends Batman.Model
@persist Batman.RestStorage
@urlNestsUnder 'shop', 'manufacturer'
test 'urlNestsUnder should nest collection URLs', 1, ->
equal @Product.url(data: shop_id: 1), 'shops/1/products'
test 'urlNestsUnder should nest collection URLs under secondary parents if present', 1, ->
equal @Product.url(data: manufacturer_id: 1), 'manufacturers/1/products'
test 'urlNestsUnder should nest collection URLs under the first available parent', 1, ->
equal @Product.url(data: manufacturer_id: 1, shop_id: 2), 'shops/2/products'
test 'urlNestsUnder should nest record URLs', 1, ->
product = new @Product(id: 1, shop_id: 2)
equal product.url(), 'shops/2/products/1'
test 'urlNestsUnder should nest new record URLs', 1, ->
product = new @Product(shop_id: 1)
equal product.url(), 'shops/1/products'
test 'urlNestsUnder should nest record URLs under secondary parents if present', 1, ->
product = new @Product(id:1, manufacturer_id: 2)
equal product.url(), 'manufacturers/2/products/1'
test 'urlNestsUnder should nest record URLs under the first available parent', 1, ->
product = new @Product(id:1, shop_id: 2, manufacturer_id: 3)
equal product.url(), 'shops/2/products/1'
| 88089 | {TestStorageAdapter} = window
QUnit.module "Batman.Model",
setup: ->
class @Product extends Batman.Model
test "constructors should always be called with new", ->
Product = @Product
raises (-> product = Product()),
(message) -> ok message; true
Namespace = Product: Product
raises (-> product = Namespace.Product()),
(message) -> ok message; true
product = new Namespace.Product()
ok product instanceof Product
test "properties can be stored", ->
product = new @Product
product.set('foo', 'bar')
equal product.get('foo'), 'bar'
test "falsey properties can be stored", ->
product = new @Product
product.set('foo', false)
equal product.get('foo'), false
test "primary key is undefined on new models", ->
product = new @Product
ok product.isNew()
ok product.get('isNew')
equal typeof product.get('id'), 'undefined'
test "primary key is 'id' by default", ->
product = new @Product(id: 10)
equal product.get('id'), 10
test "integer string ids should be coerced into integers", 1, ->
product = new @Product(id: "1234")
strictEqual product.get('id'), 1234
test "non-integer string ids should not be coerced", 1, ->
product = new @Product(id: "123d")
strictEqual product.get('id'), "123d"
test "updateAttributes will update a model's attributes", ->
product = new @Product(id: 10)
product.updateAttributes {name: "foobar", id: 20}
equal product.get('id'), 20
equal product.get('name'), "foobar"
test "updateAttributes will returns the updated record", ->
product = new @Product(id: 10)
equal product, product.updateAttributes {name: "<NAME>", id: 20}
test "createFromJSON will create a record using encoders", ->
@Product.encode 'name', 'id'
product = @Product.createFromJSON(name: '<NAME>', id: 1, description: ' ')
ok product instanceof @Product
equal product.get('id'), 1
equal product.get('name'), '<NAME>'
equal product.get('description'), undefined
test "createFromJSON leaves the record clean", ->
@Product.encode 'name', 'id'
product = @Product.createFromJSON(name: '<NAME>', id: 1, description: ' ')
equal product.get('lifecycle.state'), 'clean'
equal product.get('dirtyKeys').length, 0
test "createFromJSON will return an existing instance if in the identity map", ->
@Product.encode 'name', 'id'
product = @Product.createFromJSON(name: '<NAME>', id: 1, description: ' ')
otherProduct = @Product.createFromJSON(id: 1)
strictEqual product, otherProduct
test "_makeOrFindRecordFromData with a new record will add it to the loaded set and apply the attributes", ->
@Product.encode('name', 'id')
equal @Product.get('loaded.length'), 0
result = @Product._makeOrFindRecordFromData({id: 1, name: '<NAME>'})
equal @Product.get('loaded.length'), 1
ok @Product.get('loaded').has(result)
equal result.get('name'), 'foo'
test "_makeOrFindRecordFromData with an existing record will add it to the loaded set and apply the attributes", ->
@Product.encode('name', 'id')
product = @Product.createFromJSON(name: '<NAME>', id: 1, description: ' ')
equal @Product.get('loaded.length'), 1
result = @Product._makeOrFindRecordFromData({id: 1, name: 'foo'})
equal @Product.get('loaded.length'), 1
ok result == product
equal result.get('name'), 'foo'
test "primary key can be changed by setting primary key on the model class", ->
@Product.set 'primaryKey', 'uuid'
product = new @Product(uuid: "abc123")
equal product.get('id'), 'abc123'
test 'the \'lifecycle.state\' key should be bindable', ->
p = new @Product()
equal p.get('lifecycle.state'), "clean"
p.observe 'lifecycle.state', spy = createSpy()
p.set('unrelatedkey', 'silly')
ok spy.called
test 'bindable isDirty should correctly reflect an object\`s dirtiness', ->
p = new @Product()
equal p.get('lifecycle.state'), 'clean'
ok !p.get('isDirty')
p.set('waffle', 'tasty')
equal p.get('lifecycle.state'), 'dirty'
ok p.get('isDirty')
test 'the instantiated storage adapter should be returned when persisting', ->
returned = false
class StorageAdapter extends Batman.StorageAdapter
isTestStorageAdapter: true
class Product extends Batman.Model
returned = @persist StorageAdapter
ok returned.isTestStorageAdapter
test 'Nested _withoutDirtyTracking does not reset flag', ->
p = new @Product()
p._withoutDirtyTracking ->
equal p._pauseDirtyTracking, true
p._withoutDirtyTracking -> return
equal p._pauseDirtyTracking, true
equal p._pauseDirtyTracking, false
test 'options passed to persist should be mixed in to the storage adapter once instantiated', ->
returned = false
class StorageAdapter extends Batman.StorageAdapter
isTestStorageAdapter: true
class Product extends Batman.Model
@persist StorageAdapter, {foo: 'bar'}, {corge: 'corge'}
equal Product.storageAdapter().foo, 'bar'
equal Product.storageAdapter().corge, 'corge'
class Order extends Batman.Model
adapter = new StorageAdapter(Order)
Order.persist adapter, {baz: 'qux'}
equal adapter.baz, 'qux'
test "get('resourceName') should use the class level resourceName property", ->
class Product extends Batman.Model
@resourceName: 'foobar'
equal Product.get('resourceName'), 'foobar'
test "get('resourceName') should use the prototype level resourceName property", ->
oldError = Batman.developer
Batman.developer.error = createSpy()
class Product extends Batman.Model
resourceName: 'foobar'
equal Product.get('resourceName'), 'foobar'
Batman.developer.error = oldError
test "get('resourceName') should use the function name failing all else", ->
class Product extends Batman.Model
equal Product.get('resourceName'), 'product'
QUnit.module "Batman.Model class clearing",
setup: ->
class @Product extends Batman.Model
@encode 'name', 'cost'
@adapter = new TestStorageAdapter(@Product)
@adapter.storage =
'products1': {name: "<NAME>", cost: 10, id:1}
@Product.persist @adapter
asyncTest 'clearing the model should remove instances from the identity map', ->
@Product.load =>
equal @Product.get('loaded.length'), 1
@Product.clear()
equal @Product.get('loaded.length'), 0
QUnit.start()
asyncTest 'model will reload data from storage after clear', ->
@Product.find 1, (e, p) =>
equal p.get('cost'), 10
@adapter.storage =
'products1': {name: "<NAME>", cost: 20, id:1}
@Product.clear()
p.load (e, p) =>
equal p.get('cost'), 20
QUnit.start()
asyncTest "errors are cleared on load", ->
product = new @Product(id: 1)
product.get('errors').add "product", "generic error"
equal product.get('errors').length, 1
product.load =>
equal product.get('errors').length, 0
QUnit.start()
asyncTest 'model will be in clean state after reload', ->
@Product.find 1, (e, p) =>
equal p.get('cost'), 10
p.set('cost', 20)
equal p.get('lifecycle.state'), 'dirty'
@Product.find 1, (e, p) =>
equal p.get('lifecycle.state'), 'clean'
QUnit.start()
asyncTest 'model(s) will be in clean state after reload', ->
product = new @Product(id: 2)
p = @Product
p.load =>
equal p.get('loaded.first.cost'), 10
p.set('loaded.first.cost', 20)
equal p.get('loaded.first.lifecycle.state'), 'dirty'
p.load =>
equal p.get('loaded.first.lifecycle.state'), 'clean'
QUnit.start()
test "class promise accessors will be recalculated after clear", ->
i = 0
@Product.classAccessor 'promise', promise: (deliver) -> deliver(null, i++)
equal @Product.get('promise'), 0
@Product.clear()
equal @Product.get('promise'), 1
QUnit.module 'Batman.Model.urlNestsUnder',
setup: ->
class @Product extends Batman.Model
@persist Batman.RestStorage
@urlNestsUnder 'shop', 'manufacturer'
test 'urlNestsUnder should nest collection URLs', 1, ->
equal @Product.url(data: shop_id: 1), 'shops/1/products'
test 'urlNestsUnder should nest collection URLs under secondary parents if present', 1, ->
equal @Product.url(data: manufacturer_id: 1), 'manufacturers/1/products'
test 'urlNestsUnder should nest collection URLs under the first available parent', 1, ->
equal @Product.url(data: manufacturer_id: 1, shop_id: 2), 'shops/2/products'
test 'urlNestsUnder should nest record URLs', 1, ->
product = new @Product(id: 1, shop_id: 2)
equal product.url(), 'shops/2/products/1'
test 'urlNestsUnder should nest new record URLs', 1, ->
product = new @Product(shop_id: 1)
equal product.url(), 'shops/1/products'
test 'urlNestsUnder should nest record URLs under secondary parents if present', 1, ->
product = new @Product(id:1, manufacturer_id: 2)
equal product.url(), 'manufacturers/2/products/1'
test 'urlNestsUnder should nest record URLs under the first available parent', 1, ->
product = new @Product(id:1, shop_id: 2, manufacturer_id: 3)
equal product.url(), 'shops/2/products/1'
| true | {TestStorageAdapter} = window
QUnit.module "Batman.Model",
setup: ->
class @Product extends Batman.Model
test "constructors should always be called with new", ->
Product = @Product
raises (-> product = Product()),
(message) -> ok message; true
Namespace = Product: Product
raises (-> product = Namespace.Product()),
(message) -> ok message; true
product = new Namespace.Product()
ok product instanceof Product
test "properties can be stored", ->
product = new @Product
product.set('foo', 'bar')
equal product.get('foo'), 'bar'
test "falsey properties can be stored", ->
product = new @Product
product.set('foo', false)
equal product.get('foo'), false
test "primary key is undefined on new models", ->
product = new @Product
ok product.isNew()
ok product.get('isNew')
equal typeof product.get('id'), 'undefined'
test "primary key is 'id' by default", ->
product = new @Product(id: 10)
equal product.get('id'), 10
test "integer string ids should be coerced into integers", 1, ->
product = new @Product(id: "1234")
strictEqual product.get('id'), 1234
test "non-integer string ids should not be coerced", 1, ->
product = new @Product(id: "123d")
strictEqual product.get('id'), "123d"
test "updateAttributes will update a model's attributes", ->
product = new @Product(id: 10)
product.updateAttributes {name: "foobar", id: 20}
equal product.get('id'), 20
equal product.get('name'), "foobar"
test "updateAttributes will returns the updated record", ->
product = new @Product(id: 10)
equal product, product.updateAttributes {name: "PI:NAME:<NAME>END_PI", id: 20}
test "createFromJSON will create a record using encoders", ->
@Product.encode 'name', 'id'
product = @Product.createFromJSON(name: 'PI:NAME:<NAME>END_PI', id: 1, description: ' ')
ok product instanceof @Product
equal product.get('id'), 1
equal product.get('name'), 'PI:NAME:<NAME>END_PI'
equal product.get('description'), undefined
test "createFromJSON leaves the record clean", ->
@Product.encode 'name', 'id'
product = @Product.createFromJSON(name: 'PI:NAME:<NAME>END_PI', id: 1, description: ' ')
equal product.get('lifecycle.state'), 'clean'
equal product.get('dirtyKeys').length, 0
test "createFromJSON will return an existing instance if in the identity map", ->
@Product.encode 'name', 'id'
product = @Product.createFromJSON(name: 'PI:NAME:<NAME>END_PI', id: 1, description: ' ')
otherProduct = @Product.createFromJSON(id: 1)
strictEqual product, otherProduct
test "_makeOrFindRecordFromData with a new record will add it to the loaded set and apply the attributes", ->
@Product.encode('name', 'id')
equal @Product.get('loaded.length'), 0
result = @Product._makeOrFindRecordFromData({id: 1, name: 'PI:NAME:<NAME>END_PI'})
equal @Product.get('loaded.length'), 1
ok @Product.get('loaded').has(result)
equal result.get('name'), 'foo'
test "_makeOrFindRecordFromData with an existing record will add it to the loaded set and apply the attributes", ->
@Product.encode('name', 'id')
product = @Product.createFromJSON(name: 'PI:NAME:<NAME>END_PI', id: 1, description: ' ')
equal @Product.get('loaded.length'), 1
result = @Product._makeOrFindRecordFromData({id: 1, name: 'foo'})
equal @Product.get('loaded.length'), 1
ok result == product
equal result.get('name'), 'foo'
test "primary key can be changed by setting primary key on the model class", ->
@Product.set 'primaryKey', 'uuid'
product = new @Product(uuid: "abc123")
equal product.get('id'), 'abc123'
test 'the \'lifecycle.state\' key should be bindable', ->
p = new @Product()
equal p.get('lifecycle.state'), "clean"
p.observe 'lifecycle.state', spy = createSpy()
p.set('unrelatedkey', 'silly')
ok spy.called
test 'bindable isDirty should correctly reflect an object\`s dirtiness', ->
p = new @Product()
equal p.get('lifecycle.state'), 'clean'
ok !p.get('isDirty')
p.set('waffle', 'tasty')
equal p.get('lifecycle.state'), 'dirty'
ok p.get('isDirty')
test 'the instantiated storage adapter should be returned when persisting', ->
returned = false
class StorageAdapter extends Batman.StorageAdapter
isTestStorageAdapter: true
class Product extends Batman.Model
returned = @persist StorageAdapter
ok returned.isTestStorageAdapter
test 'Nested _withoutDirtyTracking does not reset flag', ->
p = new @Product()
p._withoutDirtyTracking ->
equal p._pauseDirtyTracking, true
p._withoutDirtyTracking -> return
equal p._pauseDirtyTracking, true
equal p._pauseDirtyTracking, false
test 'options passed to persist should be mixed in to the storage adapter once instantiated', ->
returned = false
class StorageAdapter extends Batman.StorageAdapter
isTestStorageAdapter: true
class Product extends Batman.Model
@persist StorageAdapter, {foo: 'bar'}, {corge: 'corge'}
equal Product.storageAdapter().foo, 'bar'
equal Product.storageAdapter().corge, 'corge'
class Order extends Batman.Model
adapter = new StorageAdapter(Order)
Order.persist adapter, {baz: 'qux'}
equal adapter.baz, 'qux'
test "get('resourceName') should use the class level resourceName property", ->
class Product extends Batman.Model
@resourceName: 'foobar'
equal Product.get('resourceName'), 'foobar'
test "get('resourceName') should use the prototype level resourceName property", ->
oldError = Batman.developer
Batman.developer.error = createSpy()
class Product extends Batman.Model
resourceName: 'foobar'
equal Product.get('resourceName'), 'foobar'
Batman.developer.error = oldError
test "get('resourceName') should use the function name failing all else", ->
class Product extends Batman.Model
equal Product.get('resourceName'), 'product'
QUnit.module "Batman.Model class clearing",
setup: ->
class @Product extends Batman.Model
@encode 'name', 'cost'
@adapter = new TestStorageAdapter(@Product)
@adapter.storage =
'products1': {name: "PI:NAME:<NAME>END_PI", cost: 10, id:1}
@Product.persist @adapter
asyncTest 'clearing the model should remove instances from the identity map', ->
@Product.load =>
equal @Product.get('loaded.length'), 1
@Product.clear()
equal @Product.get('loaded.length'), 0
QUnit.start()
asyncTest 'model will reload data from storage after clear', ->
@Product.find 1, (e, p) =>
equal p.get('cost'), 10
@adapter.storage =
'products1': {name: "PI:NAME:<NAME>END_PI", cost: 20, id:1}
@Product.clear()
p.load (e, p) =>
equal p.get('cost'), 20
QUnit.start()
asyncTest "errors are cleared on load", ->
product = new @Product(id: 1)
product.get('errors').add "product", "generic error"
equal product.get('errors').length, 1
product.load =>
equal product.get('errors').length, 0
QUnit.start()
asyncTest 'model will be in clean state after reload', ->
@Product.find 1, (e, p) =>
equal p.get('cost'), 10
p.set('cost', 20)
equal p.get('lifecycle.state'), 'dirty'
@Product.find 1, (e, p) =>
equal p.get('lifecycle.state'), 'clean'
QUnit.start()
asyncTest 'model(s) will be in clean state after reload', ->
product = new @Product(id: 2)
p = @Product
p.load =>
equal p.get('loaded.first.cost'), 10
p.set('loaded.first.cost', 20)
equal p.get('loaded.first.lifecycle.state'), 'dirty'
p.load =>
equal p.get('loaded.first.lifecycle.state'), 'clean'
QUnit.start()
test "class promise accessors will be recalculated after clear", ->
i = 0
@Product.classAccessor 'promise', promise: (deliver) -> deliver(null, i++)
equal @Product.get('promise'), 0
@Product.clear()
equal @Product.get('promise'), 1
QUnit.module 'Batman.Model.urlNestsUnder',
setup: ->
class @Product extends Batman.Model
@persist Batman.RestStorage
@urlNestsUnder 'shop', 'manufacturer'
test 'urlNestsUnder should nest collection URLs', 1, ->
equal @Product.url(data: shop_id: 1), 'shops/1/products'
test 'urlNestsUnder should nest collection URLs under secondary parents if present', 1, ->
equal @Product.url(data: manufacturer_id: 1), 'manufacturers/1/products'
test 'urlNestsUnder should nest collection URLs under the first available parent', 1, ->
equal @Product.url(data: manufacturer_id: 1, shop_id: 2), 'shops/2/products'
test 'urlNestsUnder should nest record URLs', 1, ->
product = new @Product(id: 1, shop_id: 2)
equal product.url(), 'shops/2/products/1'
test 'urlNestsUnder should nest new record URLs', 1, ->
product = new @Product(shop_id: 1)
equal product.url(), 'shops/1/products'
test 'urlNestsUnder should nest record URLs under secondary parents if present', 1, ->
product = new @Product(id:1, manufacturer_id: 2)
equal product.url(), 'manufacturers/2/products/1'
test 'urlNestsUnder should nest record URLs under the first available parent', 1, ->
product = new @Product(id:1, shop_id: 2, manufacturer_id: 3)
equal product.url(), 'shops/2/products/1'
|
[
{
"context": "###\n # Utils: Common Scripts Library\n # @Author: BoringTu\n # @Email: work@BoringTu.com\n###\ndefine ['md5', '",
"end": 57,
"score": 0.9993181824684143,
"start": 49,
"tag": "USERNAME",
"value": "BoringTu"
},
{
"context": "on Scripts Library\n # @Author: BoringTu\n # @... | src/coffee/utils.coffee | boringtu/boring-utils | 0 | ###
# Utils: Common Scripts Library
# @Author: BoringTu
# @Email: work@BoringTu.com
###
define ['md5', 'base64'], (md5) ->
"use strict"
# Populate the class2type map
class2type = []
for i, name of 'Boolean Number String Function Array Date RegExp Object Error'.split ' '
class2type[ "[object #{ name }]" ] = name.toLowerCase()
class Utils
###
# 深度 clone 对象
# @param obj [Object] 必填。将要 clone 的对象
###
clone: (obj) ->
return obj unless typeof obj is 'object' and obj?
if obj instanceof Date
re = new Date()
re.setTime obj.getTime()
return re
re = if obj instanceof Array then [] else {}
for own o, val of obj
if typeof val is 'object'
re[o] = @clone val
else
re[o] = val
re
###
# 数据参数化
# e.g. {"a": 1, "b": 2} => "a=1&b=2"
###
parameterization: (data = {}) ->
re = ""
fun = (str) -> "#{ str }".replace /\s/g, '_'
re += "&#{ fun k }=#{ fun v }" for own k, v of data
re.slice 1
isWindow: (obj) ->
obj? and obj is obj.window
type: (obj) ->
if obj?
if typeof obj is 'object' or typeof obj is 'function' then class2type[toString.call obj] or 'object' else typeof obj
else
"#{ obj }"
isArray: Array.isArray or (obj) -> 'array' is @type obj
###
# 判断参数是否是一个纯粹的对象
#
# via: jQuery
# @webSite: https://jquery.com
###
isPlainObject: (obj) ->
# Must be an Object.
# Because of IE, we also have to check the presence of the constructor property.
# Make sure that DOM nodes and window objects don't pass through, as well
return false if !obj or @type(obj) isnt 'object' or obj.nodeType or @isWindow obj
hasOwn = ({}).hasOwnProperty
try
# Not own constructor property must be Object
return false if obj.constructor and !hasOwn.call(obj, 'constructor') and !hasOwn.call obj.constructor.prototype, 'isPrototypeOf'
catch e
# IE8,9 Will throw exceptions on certain host objects #9897
return false
temp = null for key of obj
key is undefined or hasOwn.call obj, key
###
# 扩展对象
# extend [isDeep,] target, obj1[, obj2[, obj3[, ...]]]
#
# via: jQuery
# @webSite: https://jquery.com
###
extend: ->
#var src, copyIsArray, copy, name, options, clone,
target = arguments[0] or {}
i = 1
length = arguments.length
deep = false
# Handle a deep copy situation
if typeof target is 'boolean'
deep = target
# skip the boolean and the target
target = arguments[i] or {}
i++
# Handle case when target is a string or something (possible in deep copy)
if typeof target isnt 'object' and not @isFunction target
target = {}
# extend jQuery itself if only one argument is passed
if i is length
target = @
i--
while i < length
# Only deal with non-null/undefined values
# TODO 看下转的对不对
#if ( (options = arguments[ i ]) != null ) {
if (options = arguments[ i ])?
# Extend the base object
for name, copy of options
src = target[ name ]
# Prevent never-ending loop
continue if target is copy
# Recurse if we're merging plain objects or arrays
if deep and copy and ( @isPlainObject(copy) or copyIsArray = @isArray copy )
if copyIsArray
copyIsArray = false
clone = if src and @isArray src then src else []
else
clone = if src and @isPlainObject src then src else {}
# Never move original objects, clone them
target[ name ] = @extend deep, clone, copy
# Don't bring in undefined values
else if copy isnt undefined
target[ name ] = copy
i++
# Return the modified object
target
###
# 格式化金额
# @param money [string/Number] 待精确的金额
# @param precision [int] 小数点后精确位数 默认:4
# e.g.: 1234567.89 => 1,234,567.8900
###
formatMoney: (money, precision = 4) ->
formatRound = (money) -> "#{ money }".replace /(\d+?)(?=(?:\d{3})+$)/g, '$1,'
money = money + ''
temp = money.split '.'
round = +temp[0]
round = formatRound round
return round unless precision
decimal = '' + Math.round ".#{ temp[1] or 0 }" * Math.pow 10, precision
"#{ formatRound round }.#{ ('0' for i in [0...precision - decimal.length]).join '' }#{ decimal }"
###
# 获得指定日期规范格式<yyyy-MM-dd>的字符串数组
# @param param [Object] 选填。JSON对象。
# @param param - date [Date/String] 选填。欲格式化的Date/String类型的数据。如为空,则返回当前日期。
# @param param - forward [Number] 选填。提前的天数。支持0和负整数。如果调用时带有此参数,将返回一个包含两个元素的数组,第一个日期早于第二个日期。
###
getDate: (param) ->
return if not param
date = param['date'] or new Date()
date = new Date(date) if typeof date is 'string'
if /^-?\d+$/.test param['forward'] # forward为整数时(包括0和正负整数)
af_day = date.getTime()
be_day = af_day - param['forward'] * 24 * 60 * 60 * 1000
af_day = date.getFormatDate new Date(af_day)
be_day = date.getFormatDate new Date(be_day)
return [be_day, af_day]
return
#****************************** 内部函数 ******************************#
###
# 获得指定日期、时间规范格式<yyyy-MM-dd>|<HH:mm:ss>|<yyyy-MM-dd HH:mm:ss>的字符串
# @param param [Object] 选填。JSON对象。
# @param param - date [Date] 选填。欲格式化的Date类型的数据。如为空,则默认当前日期。
# @param param - hasDate [Boolean] 选填。返回的规范化字符串带有“日期”。
# @param param - hasTime [Boolean] 选填。返回的规范化字符串带有“时间”。
# @param param - forward [Number] 选填。提前的天数。支持0和负整数。如果调用时带有此参数,将返回一个包含两个元素的数组,第一个日期早于第二个日期。
# 注:此函数是用来追加到Date prototype的,不能直接调用。
###
_formatDate = (param) ->
date = param['date'] or @
y = date.getFullYear()
M = date.getMonth() + 1
M = if (M + '').length > 1 then M else '0' + M
d = date.getDate()
d = if (d + '').length > 1 then d else '0' + d
H = date.getHours()
H = if (H + '').length > 1 then H else '0' + H
m = date.getMinutes()
m = if (m + '').length > 1 then m else '0' + m
s = date.getSeconds()
s = if (s + '').length > 1 then s else '0' + s
hD = param.hasDate
hT = param.hasTime
rD = if hD then (y + '-' + M + '-' + d) else ''
rT = if hT then (H + ':' + m + ':' + s) else ''
re = "#{ rD }#{ if hD and hT then ' ' else '' }#{ rT }"
date = undefined
re
###
# 获得指定月份第一天的规范格式<yyyy-MM-dd>的字符串
# @param date [Date/String] 必填。指定月份的Date对象或可以转换成Date对象的字符串
###
_firstDayOfMonth = (date) ->
date = new Date date if typeof date is 'string'
new Date date.setDate(1)
###
# 获得指定月份最后一天的规范格式<yyyy-MM-dd>的字符串
# @param date [Date/String] 必填。指定月份的Date对象或可以转换成Date对象的字符串
###
_lastDayOfMonth = (date) ->
date = new Date date if typeof date is 'string'
date = new Date date.setDate(1)
re = date.setMonth(date.getMonth() + 1) - 1 * 24 * 60 * 60 * 1000
new Date re
#****************************** 修改原型 ******************************#
###
# 获取格式化日期:2000-01-01
###
Date::getFormatDate = (date = @) ->
_formatDate.call @, {date: date, hasDate: 1}
###
# 获取格式化时间:00:00:00
###
Date::getFormatTime = (date = @) ->
_formatDate.call @, {date: date, hasTime: 1}
###
# 获取格式化日期+时间:2000-01-01 00:00:00
###
Date::getFormatDateAndTime = (date = @) ->
_formatDate.call @, {date: date, hasDate: 1, hasTime: 1}
###
# 获取指定月份第一天的格式化日期:2000-01-01
# @param date [Date/String]
###
Date::firstDayOfMonth = (date = @) ->
_firstDayOfMonth.call @, date
###
# 获取指定月份最后一天的格式化日期:2000-01-31
# @param date [Date/String]
###
Date::lastDayOfMonth = (date = @) ->
_lastDayOfMonth.call @, date
###
# 获取 n 天前的日期(n 可为负)
###
Date::beforeDays = (n, date = @) ->
new Date date.getTime() - n * 1000 * 60 * 60 * 24
###
# 获取 n 天后的日期(n 可为负)
###
Date::afterDays = (n, date = @) ->
new Date date.getTime() + n * 1000 * 60 * 60 * 24
###
# 获取 n 个月前的日期(n 可为负)
###
Date::beforeMonths = (n, date = @) ->
new Date date.setMonth date.getMonth() - n
###
# 获取 n 天后的日期(n 可为负)
###
Date::afterMonths = (n, date = @) ->
new Date date.setMonth date.getMonth() + n
###
# 去空格 - 前后空格都去掉
###
String::trim = -> @replace /(^\s*)|(\s*$)/g, ''
###
# 去空格 - 去前面的空格
###
String::trimPre = -> @replace /(^\s*)/g, ''
###
# 去空格 - 去后面的空格
###
String::trimSuf = -> @replace /(\s*$)/g, ''
###
# 处理JSON库
###
String::toJSON = -> JSON.parse @
###
# 将 $、<、>、"、',与 / 转义成 HTML 字符
###
String::encodeHTML = (onlyEncodeScript) ->
return @ unless @
encodeHTMLRules =
"&": "&"
"<": "<"
">": ">"
'"': '"'
"'": '''
"/": '/'
if onlyEncodeScript
matchHTML = /<\/?\s*(script|iframe)[\s\S]*?>/gi
str = @replace matchHTML, (m) ->
switch true
when /script/i.test m
s = 'script'
when /iframe/i.test m
s = 'iframe'
else
s = ''
"#{ encodeHTMLRules['<'] }#{ if -1 is m.indexOf '/' then '' else encodeHTMLRules['/'] }#{ s }#{ encodeHTMLRules['>'] }"
return str.replace /on[\w]+\s*=/gi, ''
else
matchHTML = /&(?!#?\w+;)|<|>|"|'|\//g
return @replace matchHTML, (m) -> encodeHTMLRules[m] or m
###
# 将 $、<、>、"、',与 / 从 HTML 字符 反转义成正常字符
###
String::decodeHTML = String::decodeHTML or ->
decodeHTMLRules =
"&": "&"
"<": "<"
">": ">"
'"': '"'
''': "'"
'/': "/"
matchHTML = /&|<|>|"|'|//g
if @ then @replace(matchHTML, (m) -> decodeHTMLRules[m] or m) else @
String::utf16to8 = ->
out = ''
len = @length
for i in [0...len]
c = @charCodeAt(i)
if c >= 0x0001 and c <= 0x007F
out += @charAt(i)
else if c > 0x07FF
out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F))
out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F))
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F))
else
out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F))
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F))
out
# 验证 Luhn 算法 return true / false
String::checkLuhn = ->
num = @split ''
len = num.length
sum = 0
for i in [0...len]
count = i + 1
n = +num[len - 1 - i]
if count % 2 is 0
# 从最后一位数字开始,偶数位
n = n * 2
n = n - 9 unless n < 10
sum += n
return sum % 10 is 0
###
# Array: 判断当前 array 中是否存在指定元素
###
Array::has = (obj) -> @indexOf(obj) isnt -1
###
# Array: 获取最后一个元素
###
Array::last = -> @[@length - 1]
###
# Array: 去重
# @param bool [Boolean] 是否返回移除的元素array 默认false
###
Array::unique = (bool = false) ->
# 将被替换的结果array
result = []
# 返回的移除元素array
re = []
# 用于查询查询是否重复的hash map
hash = {}
if bool
for obj in @
if hash[obj]
re.push obj
else
result.push obj
hash[obj] = true
return [result, re]
else
for obj in @
unless hash[obj]
result.push obj
hash[obj] = true
return result
###
# 大数据量时,splice会比较低效,可以换一种方式
#
hash = {}
i = 0
temp = @[0]
while temp
if hash[temp]
@splice i--, 1
else
hash[temp] = true
temp = @[++i]
@
###
###
# Array: 移除参数中的元素
###
Array::remove = (obj) ->
i = @.indexOf obj
return null if i is -1
return @.splice(i, 1)[0]
###
# 处理Base64库
###
if Object.defineProperty
Base64.extendString()
else
String::toBase64 = (urisafe) ->
Base64[if urisafe then 'encodeURI' else 'encode'] @
String::toBase64URI = ->
Base64['encodeURI'] @
String::fromBase64 = ->
Base64['decode'] @
###
# 处理md5库
###
String::md5 = -> md5.apply null, [@].concat [].slice.apply arguments
###
# 精确小数点位数
# @param count [int] 精确小数点后位数
# @param round [Boolean] 是否四舍五入(默认:yes)
###
Number::accurate = (count, round = yes) ->
if @.valueOf() is 0
return '0' if count is 0
re = '0.'
re += '0' for x in [0...count]
return re
temp = Math.pow 10, count
num = Math[if round then 'round' else 'floor'] @ * temp
num = num / temp
str = num.toString()
len = count - str.replace(/^\d+\.*/, '').length
txt = str
txt += (if num % 1 is 0 then '.' else '') if len
txt += '0' for i in [0...len]
return txt
###
# 判断当前数字是否是质数
###
Number::isPrime = ->
throw "The #{ @ } is neither a prime number nor a composite number." if @ in [0, 1]
throw 'The Number which to check is a composite number or not must be a natural number.' if @ % 1
return yes if @ < 4
for i in [2..Math.sqrt @]
return no unless @ % i
return yes
###
# 阶乘 num!
# @param num [int] 操作数
###
Math.factorial = (num) ->
throw 'The number to calculate for factorial must be a positive integer.' unless num is Math.abs num
throw 'The number to calculate for factorial must be a int number.' unless num % 1 is 0
return 1 if num is 0
formula = (num, total) ->
return total if num is 1
return formula num - 1, num * total
formula num, 1
###
# 排列(Arrangement)
# A(n,m)
# @param n [int] 元素的总个数
# @param m [int] 参与选择的元素个数
###
Math.arrangement = (n, m) ->
return 0 if n < m
a = Math.factorial n
b = Math.factorial n - m
a / b
###
# 组合(Combination)
# C(n,m)
# @param n [int] 元素的总个数
# @param m [int] 参与选择的元素个数
###
Math.combination = (n, m) ->
return 0 if n < m
a = Math.arrangement n, m
b = Math.factorial m
a / b
###
# int 随机数
# @param min [int] 随机范围的最小数字
# @param max [int] 随机范围的最大数字
###
Math.intRange = (min = 0, max = 0) ->
min + Math.round Math.random() * (max - 1)
###
# 交集(Intersection)
###
Array.intersection = (a, b) ->
re = []
for x in a.unique()
re.push x if x in b
re
###
# 并集(Union)
###
Array.union = ->
re = []
for arr in arguments
re = re.concat arr
re.unique()
###
# 栈
###
class Stack
constructor: ->
@dataStore = []
top: 0
push: (element) -> @dataStore[@top++] = element
pop: -> @dataStore[--@top]
peek: -> @dataStore[@top - 1]
clear: -> @top = 0
clone: ->
obj = new Stack()
obj.dataStore = SMG.utils.clone @dataStore
obj.top = @top
obj
Object.defineProperties Stack::,
length:
get: -> @top
window.Stack = Stack
###
# 队列
###
class Queue
constructor: ->
@dataStore = []
enqueue: (element) -> @dataStore.push element
dequeue: -> @dataStore.shift()
first: -> @dataStore[0]
end: -> @dataStore[@length - 1]
clear: -> @dataStore = []
toString: ->
str = ''
str += "#{ el }#{ if i + 1 isnt @length then '\n' else '' }" for el, i in @dataStore
str
Object.defineProperties Queue::,
length:
get: -> @dataStore.length
window.Queue = Queue
Utils
| 47988 | ###
# Utils: Common Scripts Library
# @Author: BoringTu
# @Email: <EMAIL>
###
define ['md5', 'base64'], (md5) ->
"use strict"
# Populate the class2type map
class2type = []
for i, name of 'Boolean Number String Function Array Date RegExp Object Error'.split ' '
class2type[ "[object #{ name }]" ] = name.toLowerCase()
class Utils
###
# 深度 clone 对象
# @param obj [Object] 必填。将要 clone 的对象
###
clone: (obj) ->
return obj unless typeof obj is 'object' and obj?
if obj instanceof Date
re = new Date()
re.setTime obj.getTime()
return re
re = if obj instanceof Array then [] else {}
for own o, val of obj
if typeof val is 'object'
re[o] = @clone val
else
re[o] = val
re
###
# 数据参数化
# e.g. {"a": 1, "b": 2} => "a=1&b=2"
###
parameterization: (data = {}) ->
re = ""
fun = (str) -> "#{ str }".replace /\s/g, '_'
re += "&#{ fun k }=#{ fun v }" for own k, v of data
re.slice 1
isWindow: (obj) ->
obj? and obj is obj.window
type: (obj) ->
if obj?
if typeof obj is 'object' or typeof obj is 'function' then class2type[toString.call obj] or 'object' else typeof obj
else
"#{ obj }"
isArray: Array.isArray or (obj) -> 'array' is @type obj
###
# 判断参数是否是一个纯粹的对象
#
# via: jQuery
# @webSite: https://jquery.com
###
isPlainObject: (obj) ->
# Must be an Object.
# Because of IE, we also have to check the presence of the constructor property.
# Make sure that DOM nodes and window objects don't pass through, as well
return false if !obj or @type(obj) isnt 'object' or obj.nodeType or @isWindow obj
hasOwn = ({}).hasOwnProperty
try
# Not own constructor property must be Object
return false if obj.constructor and !hasOwn.call(obj, 'constructor') and !hasOwn.call obj.constructor.prototype, 'isPrototypeOf'
catch e
# IE8,9 Will throw exceptions on certain host objects #9897
return false
temp = null for key of obj
key is undefined or hasOwn.call obj, key
###
# 扩展对象
# extend [isDeep,] target, obj1[, obj2[, obj3[, ...]]]
#
# via: jQuery
# @webSite: https://jquery.com
###
extend: ->
#var src, copyIsArray, copy, name, options, clone,
target = arguments[0] or {}
i = 1
length = arguments.length
deep = false
# Handle a deep copy situation
if typeof target is 'boolean'
deep = target
# skip the boolean and the target
target = arguments[i] or {}
i++
# Handle case when target is a string or something (possible in deep copy)
if typeof target isnt 'object' and not @isFunction target
target = {}
# extend jQuery itself if only one argument is passed
if i is length
target = @
i--
while i < length
# Only deal with non-null/undefined values
# TODO 看下转的对不对
#if ( (options = arguments[ i ]) != null ) {
if (options = arguments[ i ])?
# Extend the base object
for name, copy of options
src = target[ name ]
# Prevent never-ending loop
continue if target is copy
# Recurse if we're merging plain objects or arrays
if deep and copy and ( @isPlainObject(copy) or copyIsArray = @isArray copy )
if copyIsArray
copyIsArray = false
clone = if src and @isArray src then src else []
else
clone = if src and @isPlainObject src then src else {}
# Never move original objects, clone them
target[ name ] = @extend deep, clone, copy
# Don't bring in undefined values
else if copy isnt undefined
target[ name ] = copy
i++
# Return the modified object
target
###
# 格式化金额
# @param money [string/Number] 待精确的金额
# @param precision [int] 小数点后精确位数 默认:4
# e.g.: 1234567.89 => 1,234,567.8900
###
formatMoney: (money, precision = 4) ->
formatRound = (money) -> "#{ money }".replace /(\d+?)(?=(?:\d{3})+$)/g, '$1,'
money = money + ''
temp = money.split '.'
round = +temp[0]
round = formatRound round
return round unless precision
decimal = '' + Math.round ".#{ temp[1] or 0 }" * Math.pow 10, precision
"#{ formatRound round }.#{ ('0' for i in [0...precision - decimal.length]).join '' }#{ decimal }"
###
# 获得指定日期规范格式<yyyy-MM-dd>的字符串数组
# @param param [Object] 选填。JSON对象。
# @param param - date [Date/String] 选填。欲格式化的Date/String类型的数据。如为空,则返回当前日期。
# @param param - forward [Number] 选填。提前的天数。支持0和负整数。如果调用时带有此参数,将返回一个包含两个元素的数组,第一个日期早于第二个日期。
###
getDate: (param) ->
return if not param
date = param['date'] or new Date()
date = new Date(date) if typeof date is 'string'
if /^-?\d+$/.test param['forward'] # forward为整数时(包括0和正负整数)
af_day = date.getTime()
be_day = af_day - param['forward'] * 24 * 60 * 60 * 1000
af_day = date.getFormatDate new Date(af_day)
be_day = date.getFormatDate new Date(be_day)
return [be_day, af_day]
return
#****************************** 内部函数 ******************************#
###
# 获得指定日期、时间规范格式<yyyy-MM-dd>|<HH:mm:ss>|<yyyy-MM-dd HH:mm:ss>的字符串
# @param param [Object] 选填。JSON对象。
# @param param - date [Date] 选填。欲格式化的Date类型的数据。如为空,则默认当前日期。
# @param param - hasDate [Boolean] 选填。返回的规范化字符串带有“日期”。
# @param param - hasTime [Boolean] 选填。返回的规范化字符串带有“时间”。
# @param param - forward [Number] 选填。提前的天数。支持0和负整数。如果调用时带有此参数,将返回一个包含两个元素的数组,第一个日期早于第二个日期。
# 注:此函数是用来追加到Date prototype的,不能直接调用。
###
_formatDate = (param) ->
date = param['date'] or @
y = date.getFullYear()
M = date.getMonth() + 1
M = if (M + '').length > 1 then M else '0' + M
d = date.getDate()
d = if (d + '').length > 1 then d else '0' + d
H = date.getHours()
H = if (H + '').length > 1 then H else '0' + H
m = date.getMinutes()
m = if (m + '').length > 1 then m else '0' + m
s = date.getSeconds()
s = if (s + '').length > 1 then s else '0' + s
hD = param.hasDate
hT = param.hasTime
rD = if hD then (y + '-' + M + '-' + d) else ''
rT = if hT then (H + ':' + m + ':' + s) else ''
re = "#{ rD }#{ if hD and hT then ' ' else '' }#{ rT }"
date = undefined
re
###
# 获得指定月份第一天的规范格式<yyyy-MM-dd>的字符串
# @param date [Date/String] 必填。指定月份的Date对象或可以转换成Date对象的字符串
###
_firstDayOfMonth = (date) ->
date = new Date date if typeof date is 'string'
new Date date.setDate(1)
###
# 获得指定月份最后一天的规范格式<yyyy-MM-dd>的字符串
# @param date [Date/String] 必填。指定月份的Date对象或可以转换成Date对象的字符串
###
_lastDayOfMonth = (date) ->
date = new Date date if typeof date is 'string'
date = new Date date.setDate(1)
re = date.setMonth(date.getMonth() + 1) - 1 * 24 * 60 * 60 * 1000
new Date re
#****************************** 修改原型 ******************************#
###
# 获取格式化日期:2000-01-01
###
Date::getFormatDate = (date = @) ->
_formatDate.call @, {date: date, hasDate: 1}
###
# 获取格式化时间:00:00:00
###
Date::getFormatTime = (date = @) ->
_formatDate.call @, {date: date, hasTime: 1}
###
# 获取格式化日期+时间:2000-01-01 00:00:00
###
Date::getFormatDateAndTime = (date = @) ->
_formatDate.call @, {date: date, hasDate: 1, hasTime: 1}
###
# 获取指定月份第一天的格式化日期:2000-01-01
# @param date [Date/String]
###
Date::firstDayOfMonth = (date = @) ->
_firstDayOfMonth.call @, date
###
# 获取指定月份最后一天的格式化日期:2000-01-31
# @param date [Date/String]
###
Date::lastDayOfMonth = (date = @) ->
_lastDayOfMonth.call @, date
###
# 获取 n 天前的日期(n 可为负)
###
Date::beforeDays = (n, date = @) ->
new Date date.getTime() - n * 1000 * 60 * 60 * 24
###
# 获取 n 天后的日期(n 可为负)
###
Date::afterDays = (n, date = @) ->
new Date date.getTime() + n * 1000 * 60 * 60 * 24
###
# 获取 n 个月前的日期(n 可为负)
###
Date::beforeMonths = (n, date = @) ->
new Date date.setMonth date.getMonth() - n
###
# 获取 n 天后的日期(n 可为负)
###
Date::afterMonths = (n, date = @) ->
new Date date.setMonth date.getMonth() + n
###
# 去空格 - 前后空格都去掉
###
String::trim = -> @replace /(^\s*)|(\s*$)/g, ''
###
# 去空格 - 去前面的空格
###
String::trimPre = -> @replace /(^\s*)/g, ''
###
# 去空格 - 去后面的空格
###
String::trimSuf = -> @replace /(\s*$)/g, ''
###
# 处理JSON库
###
String::toJSON = -> JSON.parse @
###
# 将 $、<、>、"、',与 / 转义成 HTML 字符
###
String::encodeHTML = (onlyEncodeScript) ->
return @ unless @
encodeHTMLRules =
"&": "&"
"<": "<"
">": ">"
'"': '"'
"'": '''
"/": '/'
if onlyEncodeScript
matchHTML = /<\/?\s*(script|iframe)[\s\S]*?>/gi
str = @replace matchHTML, (m) ->
switch true
when /script/i.test m
s = 'script'
when /iframe/i.test m
s = 'iframe'
else
s = ''
"#{ encodeHTMLRules['<'] }#{ if -1 is m.indexOf '/' then '' else encodeHTMLRules['/'] }#{ s }#{ encodeHTMLRules['>'] }"
return str.replace /on[\w]+\s*=/gi, ''
else
matchHTML = /&(?!#?\w+;)|<|>|"|'|\//g
return @replace matchHTML, (m) -> encodeHTMLRules[m] or m
###
# 将 $、<、>、"、',与 / 从 HTML 字符 反转义成正常字符
###
String::decodeHTML = String::decodeHTML or ->
decodeHTMLRules =
"&": "&"
"<": "<"
">": ">"
'"': '"'
''': "'"
'/': "/"
matchHTML = /&|<|>|"|'|//g
if @ then @replace(matchHTML, (m) -> decodeHTMLRules[m] or m) else @
String::utf16to8 = ->
out = ''
len = @length
for i in [0...len]
c = @charCodeAt(i)
if c >= 0x0001 and c <= 0x007F
out += @charAt(i)
else if c > 0x07FF
out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F))
out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F))
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F))
else
out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F))
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F))
out
# 验证 Luhn 算法 return true / false
String::checkLuhn = ->
num = @split ''
len = num.length
sum = 0
for i in [0...len]
count = i + 1
n = +num[len - 1 - i]
if count % 2 is 0
# 从最后一位数字开始,偶数位
n = n * 2
n = n - 9 unless n < 10
sum += n
return sum % 10 is 0
###
# Array: 判断当前 array 中是否存在指定元素
###
Array::has = (obj) -> @indexOf(obj) isnt -1
###
# Array: 获取最后一个元素
###
Array::last = -> @[@length - 1]
###
# Array: 去重
# @param bool [Boolean] 是否返回移除的元素array 默认false
###
Array::unique = (bool = false) ->
# 将被替换的结果array
result = []
# 返回的移除元素array
re = []
# 用于查询查询是否重复的hash map
hash = {}
if bool
for obj in @
if hash[obj]
re.push obj
else
result.push obj
hash[obj] = true
return [result, re]
else
for obj in @
unless hash[obj]
result.push obj
hash[obj] = true
return result
###
# 大数据量时,splice会比较低效,可以换一种方式
#
hash = {}
i = 0
temp = @[0]
while temp
if hash[temp]
@splice i--, 1
else
hash[temp] = true
temp = @[++i]
@
###
###
# Array: 移除参数中的元素
###
Array::remove = (obj) ->
i = @.indexOf obj
return null if i is -1
return @.splice(i, 1)[0]
###
# 处理Base64库
###
if Object.defineProperty
Base64.extendString()
else
String::toBase64 = (urisafe) ->
Base64[if urisafe then 'encodeURI' else 'encode'] @
String::toBase64URI = ->
Base64['encodeURI'] @
String::fromBase64 = ->
Base64['decode'] @
###
# 处理md5库
###
String::md5 = -> md5.apply null, [@].concat [].slice.apply arguments
###
# 精确小数点位数
# @param count [int] 精确小数点后位数
# @param round [Boolean] 是否四舍五入(默认:yes)
###
Number::accurate = (count, round = yes) ->
if @.valueOf() is 0
return '0' if count is 0
re = '0.'
re += '0' for x in [0...count]
return re
temp = Math.pow 10, count
num = Math[if round then 'round' else 'floor'] @ * temp
num = num / temp
str = num.toString()
len = count - str.replace(/^\d+\.*/, '').length
txt = str
txt += (if num % 1 is 0 then '.' else '') if len
txt += '0' for i in [0...len]
return txt
###
# 判断当前数字是否是质数
###
Number::isPrime = ->
throw "The #{ @ } is neither a prime number nor a composite number." if @ in [0, 1]
throw 'The Number which to check is a composite number or not must be a natural number.' if @ % 1
return yes if @ < 4
for i in [2..Math.sqrt @]
return no unless @ % i
return yes
###
# 阶乘 num!
# @param num [int] 操作数
###
Math.factorial = (num) ->
throw 'The number to calculate for factorial must be a positive integer.' unless num is Math.abs num
throw 'The number to calculate for factorial must be a int number.' unless num % 1 is 0
return 1 if num is 0
formula = (num, total) ->
return total if num is 1
return formula num - 1, num * total
formula num, 1
###
# 排列(Arrangement)
# A(n,m)
# @param n [int] 元素的总个数
# @param m [int] 参与选择的元素个数
###
Math.arrangement = (n, m) ->
return 0 if n < m
a = Math.factorial n
b = Math.factorial n - m
a / b
###
# 组合(Combination)
# C(n,m)
# @param n [int] 元素的总个数
# @param m [int] 参与选择的元素个数
###
Math.combination = (n, m) ->
return 0 if n < m
a = Math.arrangement n, m
b = Math.factorial m
a / b
###
# int 随机数
# @param min [int] 随机范围的最小数字
# @param max [int] 随机范围的最大数字
###
Math.intRange = (min = 0, max = 0) ->
min + Math.round Math.random() * (max - 1)
###
# 交集(Intersection)
###
Array.intersection = (a, b) ->
re = []
for x in a.unique()
re.push x if x in b
re
###
# 并集(Union)
###
Array.union = ->
re = []
for arr in arguments
re = re.concat arr
re.unique()
###
# 栈
###
class Stack
constructor: ->
@dataStore = []
top: 0
push: (element) -> @dataStore[@top++] = element
pop: -> @dataStore[--@top]
peek: -> @dataStore[@top - 1]
clear: -> @top = 0
clone: ->
obj = new Stack()
obj.dataStore = SMG.utils.clone @dataStore
obj.top = @top
obj
Object.defineProperties Stack::,
length:
get: -> @top
window.Stack = Stack
###
# 队列
###
class Queue
constructor: ->
@dataStore = []
enqueue: (element) -> @dataStore.push element
dequeue: -> @dataStore.shift()
first: -> @dataStore[0]
end: -> @dataStore[@length - 1]
clear: -> @dataStore = []
toString: ->
str = ''
str += "#{ el }#{ if i + 1 isnt @length then '\n' else '' }" for el, i in @dataStore
str
Object.defineProperties Queue::,
length:
get: -> @dataStore.length
window.Queue = Queue
Utils
| true | ###
# Utils: Common Scripts Library
# @Author: BoringTu
# @Email: PI:EMAIL:<EMAIL>END_PI
###
define ['md5', 'base64'], (md5) ->
"use strict"
# Populate the class2type map
class2type = []
for i, name of 'Boolean Number String Function Array Date RegExp Object Error'.split ' '
class2type[ "[object #{ name }]" ] = name.toLowerCase()
class Utils
###
# 深度 clone 对象
# @param obj [Object] 必填。将要 clone 的对象
###
clone: (obj) ->
return obj unless typeof obj is 'object' and obj?
if obj instanceof Date
re = new Date()
re.setTime obj.getTime()
return re
re = if obj instanceof Array then [] else {}
for own o, val of obj
if typeof val is 'object'
re[o] = @clone val
else
re[o] = val
re
###
# 数据参数化
# e.g. {"a": 1, "b": 2} => "a=1&b=2"
###
parameterization: (data = {}) ->
re = ""
fun = (str) -> "#{ str }".replace /\s/g, '_'
re += "&#{ fun k }=#{ fun v }" for own k, v of data
re.slice 1
isWindow: (obj) ->
obj? and obj is obj.window
type: (obj) ->
if obj?
if typeof obj is 'object' or typeof obj is 'function' then class2type[toString.call obj] or 'object' else typeof obj
else
"#{ obj }"
isArray: Array.isArray or (obj) -> 'array' is @type obj
###
# 判断参数是否是一个纯粹的对象
#
# via: jQuery
# @webSite: https://jquery.com
###
isPlainObject: (obj) ->
# Must be an Object.
# Because of IE, we also have to check the presence of the constructor property.
# Make sure that DOM nodes and window objects don't pass through, as well
return false if !obj or @type(obj) isnt 'object' or obj.nodeType or @isWindow obj
hasOwn = ({}).hasOwnProperty
try
# Not own constructor property must be Object
return false if obj.constructor and !hasOwn.call(obj, 'constructor') and !hasOwn.call obj.constructor.prototype, 'isPrototypeOf'
catch e
# IE8,9 Will throw exceptions on certain host objects #9897
return false
temp = null for key of obj
key is undefined or hasOwn.call obj, key
###
# 扩展对象
# extend [isDeep,] target, obj1[, obj2[, obj3[, ...]]]
#
# via: jQuery
# @webSite: https://jquery.com
###
extend: ->
#var src, copyIsArray, copy, name, options, clone,
target = arguments[0] or {}
i = 1
length = arguments.length
deep = false
# Handle a deep copy situation
if typeof target is 'boolean'
deep = target
# skip the boolean and the target
target = arguments[i] or {}
i++
# Handle case when target is a string or something (possible in deep copy)
if typeof target isnt 'object' and not @isFunction target
target = {}
# extend jQuery itself if only one argument is passed
if i is length
target = @
i--
while i < length
# Only deal with non-null/undefined values
# TODO 看下转的对不对
#if ( (options = arguments[ i ]) != null ) {
if (options = arguments[ i ])?
# Extend the base object
for name, copy of options
src = target[ name ]
# Prevent never-ending loop
continue if target is copy
# Recurse if we're merging plain objects or arrays
if deep and copy and ( @isPlainObject(copy) or copyIsArray = @isArray copy )
if copyIsArray
copyIsArray = false
clone = if src and @isArray src then src else []
else
clone = if src and @isPlainObject src then src else {}
# Never move original objects, clone them
target[ name ] = @extend deep, clone, copy
# Don't bring in undefined values
else if copy isnt undefined
target[ name ] = copy
i++
# Return the modified object
target
###
# 格式化金额
# @param money [string/Number] 待精确的金额
# @param precision [int] 小数点后精确位数 默认:4
# e.g.: 1234567.89 => 1,234,567.8900
###
formatMoney: (money, precision = 4) ->
formatRound = (money) -> "#{ money }".replace /(\d+?)(?=(?:\d{3})+$)/g, '$1,'
money = money + ''
temp = money.split '.'
round = +temp[0]
round = formatRound round
return round unless precision
decimal = '' + Math.round ".#{ temp[1] or 0 }" * Math.pow 10, precision
"#{ formatRound round }.#{ ('0' for i in [0...precision - decimal.length]).join '' }#{ decimal }"
###
# 获得指定日期规范格式<yyyy-MM-dd>的字符串数组
# @param param [Object] 选填。JSON对象。
# @param param - date [Date/String] 选填。欲格式化的Date/String类型的数据。如为空,则返回当前日期。
# @param param - forward [Number] 选填。提前的天数。支持0和负整数。如果调用时带有此参数,将返回一个包含两个元素的数组,第一个日期早于第二个日期。
###
getDate: (param) ->
return if not param
date = param['date'] or new Date()
date = new Date(date) if typeof date is 'string'
if /^-?\d+$/.test param['forward'] # forward为整数时(包括0和正负整数)
af_day = date.getTime()
be_day = af_day - param['forward'] * 24 * 60 * 60 * 1000
af_day = date.getFormatDate new Date(af_day)
be_day = date.getFormatDate new Date(be_day)
return [be_day, af_day]
return
#****************************** 内部函数 ******************************#
###
# 获得指定日期、时间规范格式<yyyy-MM-dd>|<HH:mm:ss>|<yyyy-MM-dd HH:mm:ss>的字符串
# @param param [Object] 选填。JSON对象。
# @param param - date [Date] 选填。欲格式化的Date类型的数据。如为空,则默认当前日期。
# @param param - hasDate [Boolean] 选填。返回的规范化字符串带有“日期”。
# @param param - hasTime [Boolean] 选填。返回的规范化字符串带有“时间”。
# @param param - forward [Number] 选填。提前的天数。支持0和负整数。如果调用时带有此参数,将返回一个包含两个元素的数组,第一个日期早于第二个日期。
# 注:此函数是用来追加到Date prototype的,不能直接调用。
###
_formatDate = (param) ->
date = param['date'] or @
y = date.getFullYear()
M = date.getMonth() + 1
M = if (M + '').length > 1 then M else '0' + M
d = date.getDate()
d = if (d + '').length > 1 then d else '0' + d
H = date.getHours()
H = if (H + '').length > 1 then H else '0' + H
m = date.getMinutes()
m = if (m + '').length > 1 then m else '0' + m
s = date.getSeconds()
s = if (s + '').length > 1 then s else '0' + s
hD = param.hasDate
hT = param.hasTime
rD = if hD then (y + '-' + M + '-' + d) else ''
rT = if hT then (H + ':' + m + ':' + s) else ''
re = "#{ rD }#{ if hD and hT then ' ' else '' }#{ rT }"
date = undefined
re
###
# 获得指定月份第一天的规范格式<yyyy-MM-dd>的字符串
# @param date [Date/String] 必填。指定月份的Date对象或可以转换成Date对象的字符串
###
_firstDayOfMonth = (date) ->
date = new Date date if typeof date is 'string'
new Date date.setDate(1)
###
# 获得指定月份最后一天的规范格式<yyyy-MM-dd>的字符串
# @param date [Date/String] 必填。指定月份的Date对象或可以转换成Date对象的字符串
###
_lastDayOfMonth = (date) ->
date = new Date date if typeof date is 'string'
date = new Date date.setDate(1)
re = date.setMonth(date.getMonth() + 1) - 1 * 24 * 60 * 60 * 1000
new Date re
#****************************** 修改原型 ******************************#
###
# 获取格式化日期:2000-01-01
###
Date::getFormatDate = (date = @) ->
_formatDate.call @, {date: date, hasDate: 1}
###
# 获取格式化时间:00:00:00
###
Date::getFormatTime = (date = @) ->
_formatDate.call @, {date: date, hasTime: 1}
###
# 获取格式化日期+时间:2000-01-01 00:00:00
###
Date::getFormatDateAndTime = (date = @) ->
_formatDate.call @, {date: date, hasDate: 1, hasTime: 1}
###
# 获取指定月份第一天的格式化日期:2000-01-01
# @param date [Date/String]
###
Date::firstDayOfMonth = (date = @) ->
_firstDayOfMonth.call @, date
###
# 获取指定月份最后一天的格式化日期:2000-01-31
# @param date [Date/String]
###
Date::lastDayOfMonth = (date = @) ->
_lastDayOfMonth.call @, date
###
# 获取 n 天前的日期(n 可为负)
###
Date::beforeDays = (n, date = @) ->
new Date date.getTime() - n * 1000 * 60 * 60 * 24
###
# 获取 n 天后的日期(n 可为负)
###
Date::afterDays = (n, date = @) ->
new Date date.getTime() + n * 1000 * 60 * 60 * 24
###
# 获取 n 个月前的日期(n 可为负)
###
Date::beforeMonths = (n, date = @) ->
new Date date.setMonth date.getMonth() - n
###
# 获取 n 天后的日期(n 可为负)
###
Date::afterMonths = (n, date = @) ->
new Date date.setMonth date.getMonth() + n
###
# 去空格 - 前后空格都去掉
###
String::trim = -> @replace /(^\s*)|(\s*$)/g, ''
###
# 去空格 - 去前面的空格
###
String::trimPre = -> @replace /(^\s*)/g, ''
###
# 去空格 - 去后面的空格
###
String::trimSuf = -> @replace /(\s*$)/g, ''
###
# 处理JSON库
###
String::toJSON = -> JSON.parse @
###
# 将 $、<、>、"、',与 / 转义成 HTML 字符
###
String::encodeHTML = (onlyEncodeScript) ->
return @ unless @
encodeHTMLRules =
"&": "&"
"<": "<"
">": ">"
'"': '"'
"'": '''
"/": '/'
if onlyEncodeScript
matchHTML = /<\/?\s*(script|iframe)[\s\S]*?>/gi
str = @replace matchHTML, (m) ->
switch true
when /script/i.test m
s = 'script'
when /iframe/i.test m
s = 'iframe'
else
s = ''
"#{ encodeHTMLRules['<'] }#{ if -1 is m.indexOf '/' then '' else encodeHTMLRules['/'] }#{ s }#{ encodeHTMLRules['>'] }"
return str.replace /on[\w]+\s*=/gi, ''
else
matchHTML = /&(?!#?\w+;)|<|>|"|'|\//g
return @replace matchHTML, (m) -> encodeHTMLRules[m] or m
###
# 将 $、<、>、"、',与 / 从 HTML 字符 反转义成正常字符
###
String::decodeHTML = String::decodeHTML or ->
decodeHTMLRules =
"&": "&"
"<": "<"
">": ">"
'"': '"'
''': "'"
'/': "/"
matchHTML = /&|<|>|"|'|//g
if @ then @replace(matchHTML, (m) -> decodeHTMLRules[m] or m) else @
String::utf16to8 = ->
out = ''
len = @length
for i in [0...len]
c = @charCodeAt(i)
if c >= 0x0001 and c <= 0x007F
out += @charAt(i)
else if c > 0x07FF
out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F))
out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F))
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F))
else
out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F))
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F))
out
# 验证 Luhn 算法 return true / false
String::checkLuhn = ->
num = @split ''
len = num.length
sum = 0
for i in [0...len]
count = i + 1
n = +num[len - 1 - i]
if count % 2 is 0
# 从最后一位数字开始,偶数位
n = n * 2
n = n - 9 unless n < 10
sum += n
return sum % 10 is 0
###
# Array: 判断当前 array 中是否存在指定元素
###
Array::has = (obj) -> @indexOf(obj) isnt -1
###
# Array: 获取最后一个元素
###
Array::last = -> @[@length - 1]
###
# Array: 去重
# @param bool [Boolean] 是否返回移除的元素array 默认false
###
Array::unique = (bool = false) ->
# 将被替换的结果array
result = []
# 返回的移除元素array
re = []
# 用于查询查询是否重复的hash map
hash = {}
if bool
for obj in @
if hash[obj]
re.push obj
else
result.push obj
hash[obj] = true
return [result, re]
else
for obj in @
unless hash[obj]
result.push obj
hash[obj] = true
return result
###
# 大数据量时,splice会比较低效,可以换一种方式
#
hash = {}
i = 0
temp = @[0]
while temp
if hash[temp]
@splice i--, 1
else
hash[temp] = true
temp = @[++i]
@
###
###
# Array: 移除参数中的元素
###
Array::remove = (obj) ->
i = @.indexOf obj
return null if i is -1
return @.splice(i, 1)[0]
###
# 处理Base64库
###
if Object.defineProperty
Base64.extendString()
else
String::toBase64 = (urisafe) ->
Base64[if urisafe then 'encodeURI' else 'encode'] @
String::toBase64URI = ->
Base64['encodeURI'] @
String::fromBase64 = ->
Base64['decode'] @
###
# 处理md5库
###
String::md5 = -> md5.apply null, [@].concat [].slice.apply arguments
###
# 精确小数点位数
# @param count [int] 精确小数点后位数
# @param round [Boolean] 是否四舍五入(默认:yes)
###
Number::accurate = (count, round = yes) ->
if @.valueOf() is 0
return '0' if count is 0
re = '0.'
re += '0' for x in [0...count]
return re
temp = Math.pow 10, count
num = Math[if round then 'round' else 'floor'] @ * temp
num = num / temp
str = num.toString()
len = count - str.replace(/^\d+\.*/, '').length
txt = str
txt += (if num % 1 is 0 then '.' else '') if len
txt += '0' for i in [0...len]
return txt
###
# 判断当前数字是否是质数
###
Number::isPrime = ->
throw "The #{ @ } is neither a prime number nor a composite number." if @ in [0, 1]
throw 'The Number which to check is a composite number or not must be a natural number.' if @ % 1
return yes if @ < 4
for i in [2..Math.sqrt @]
return no unless @ % i
return yes
###
# 阶乘 num!
# @param num [int] 操作数
###
Math.factorial = (num) ->
throw 'The number to calculate for factorial must be a positive integer.' unless num is Math.abs num
throw 'The number to calculate for factorial must be a int number.' unless num % 1 is 0
return 1 if num is 0
formula = (num, total) ->
return total if num is 1
return formula num - 1, num * total
formula num, 1
###
# 排列(Arrangement)
# A(n,m)
# @param n [int] 元素的总个数
# @param m [int] 参与选择的元素个数
###
Math.arrangement = (n, m) ->
return 0 if n < m
a = Math.factorial n
b = Math.factorial n - m
a / b
###
# 组合(Combination)
# C(n,m)
# @param n [int] 元素的总个数
# @param m [int] 参与选择的元素个数
###
Math.combination = (n, m) ->
return 0 if n < m
a = Math.arrangement n, m
b = Math.factorial m
a / b
###
# int 随机数
# @param min [int] 随机范围的最小数字
# @param max [int] 随机范围的最大数字
###
Math.intRange = (min = 0, max = 0) ->
min + Math.round Math.random() * (max - 1)
###
# 交集(Intersection)
###
Array.intersection = (a, b) ->
re = []
for x in a.unique()
re.push x if x in b
re
###
# 并集(Union)
###
Array.union = ->
re = []
for arr in arguments
re = re.concat arr
re.unique()
###
# 栈
###
class Stack
constructor: ->
@dataStore = []
top: 0
push: (element) -> @dataStore[@top++] = element
pop: -> @dataStore[--@top]
peek: -> @dataStore[@top - 1]
clear: -> @top = 0
clone: ->
obj = new Stack()
obj.dataStore = SMG.utils.clone @dataStore
obj.top = @top
obj
Object.defineProperties Stack::,
length:
get: -> @top
window.Stack = Stack
###
# 队列
###
class Queue
constructor: ->
@dataStore = []
enqueue: (element) -> @dataStore.push element
dequeue: -> @dataStore.shift()
first: -> @dataStore[0]
end: -> @dataStore[@length - 1]
clear: -> @dataStore = []
toString: ->
str = ''
str += "#{ el }#{ if i + 1 isnt @length then '\n' else '' }" for el, i in @dataStore
str
Object.defineProperties Queue::,
length:
get: -> @dataStore.length
window.Queue = Queue
Utils
|
[
{
"context": "###\nSyntax Diagram Creator\n\nCopyright (c) 2011 Brian Li\nLicensed under the MIT license.\n###\n\"use strict\"\n",
"end": 55,
"score": 0.9996969699859619,
"start": 47,
"tag": "NAME",
"value": "Brian Li"
}
] | src/syntax-diagram.coffee | brian14708/syntax-diagram | 4 | ###
Syntax Diagram Creator
Copyright (c) 2011 Brian Li
Licensed under the MIT license.
###
"use strict"
## Utility functions
is_arr = (arr) -> arr instanceof Array
is_obj = (obj) -> obj? and typeof obj == "object" and not is_arr(obj)
is_str = (str) -> typeof str == "string"
count_char = (str, ch) -> str.split(ch).length - 1
merge_arr = () ->
tmp = []
for arr in arguments
if is_arr(arr)
tmp.push.apply(tmp, arr)
else
tmp.push(arr)
return tmp
##
html_enity = /\&\#(\d+);/g
remove_html_enity = if count_char(document.charset or \
document.characterSet or \
"", "UTF") > 0
then (str, keep_whitespace) ->
r = str.replace(html_enity, (match, capture) ->
c = +capture
if not keep_whitespace
if c == 32
return "\u00abSP\u00bb"
else if c == 9
return "\u00abTAB\u00bb"
else if c == 10
return "\u00abNL\u00bb"
else if c == 13
return "\u00abCR\u00bb"
return String.fromCharCode(c)
)
return if r.match(/^\s*$/) then "\u00ab\u2422\u00bb" else r
else (str, keep_whitespace) ->
r = str.replace(html_enity, (match, capture) ->
c = +capture
if not keep_whitespace
if c == 32
return "<<SP>>"
else if c == 9
return "<<TAB>>"
else if c == 10
return "<<NL>>"
else if c == 13
return "<<CR>>"
return String.fromCharCode(c)
)
return if r.match(/^\s*$/) then "<<WHITESPACE>>" else r
# get next word
next_word = (text, state) ->
state or= { next: 0 }
start = state.next
len = text.length
# skip space if a word starts with space
if text.charAt(start) == " " then ++start
if start >= len then return null
end = start
while end < len
# special characters
if text.charAt(end) in [" ", "(", ")", "*", "<", ">", "|"] then break
++end
# if length of word is 1
if start == end then ++end
word = text.substring(start, end)
return { next: end, word: word }
# analyse words
analyse = (words) ->
words_len = words.length
parse = (idx, single_token) ->
result = []
break_flag = !!single_token
while idx < words_len
c = words[idx]
if c == "("
# new group
next = parse(idx + 1)
result.push(next.result)
idx = next.index
else if c == "<"
# add arguments
if result.length > 0
tmp = result.pop()
if is_obj(tmp)
next = parse(idx + 1)
idx = next.index
tmp.args or= []
tmp.args.push(next.result)
result.push(tmp)
else
throw "SyntaxError"
else
throw "SyntaxError"
else if c == "*"
# repeat
tmp = result.pop()
result.push({
data: tmp,
type: "repeat",
})
++idx
else if c == "|"
# or
tmp = if result.length > 0 then result.pop() else null
next = parse(idx + 1, true)
idx = next.index
if is_obj(tmp) and tmp.type != "repeat"
if not is_arr(tmp.data) then tmp.data = [tmp.data]
tmp.data.push(next.result)
result.push(tmp)
else
result.push({
data: [tmp, next.result],
type: "or",
})
else if c == ")"
break_flag = true
++idx
else if c == ">"
result.reverse()
break_flag = true
++idx
else
result.push(words[idx])
++idx
if break_flag then break
return { result: result, index: idx }
return parse(0).result
# reduce redundant
reduce = (obj) ->
if is_arr(obj)
# flatten the array
if obj.length == 0 then return null
else if obj.length == 1 then return reduce(obj[0])
else return (reduce(v) for v in obj)
else if is_obj(obj)
tmp = {}
tmp[k] = reduce(v) for k, v of obj
if tmp.type == "repeat"
tmp.args or= [null]
if not is_arr(tmp.args) then tmp.args = [tmp.args]
return [null, tmp, null]
else
return obj
parse = (text) ->
text = text
# clean the text
# remove comments as long as the # isn't after a \
.replace(/(^|[^\\])#.+/g, "$1")
# escape characters
.replace(/\\./g, (match) ->
c = match.charCodeAt(1)
if c == 116 # t
c = 9
else if c == 110 # n
c = 10
else if c == 114 # r
c = 13
return "&#" + c + ";"
)
# clean whitespace
.replace(/\s+/g, " ")
# transform text
# optional element [x] <=> (|x) as long as
# x only contains or e.g. [a|b|c]
.replace(///
\[
\s* # ignore starting and ending spaces
(
[^
\s # no groups
\(\)
\[\] # no optional
\* # no repeat
]*
)
\s*
\]
///g, "(|$1)")
# optional element [x] <=> (|(x))
# e.g. [[a] [b]]
.replace(/\[/g, "(|(")
.replace(/\]/g, "))")
# remove redundant *
# e.g. a****** <=> a*
.replace(/\*+/g, "*")
# parenthese pairs
if (count_char(text, "(") != count_char(text, ")")) or
(count_char(text, "<") != count_char(text, ">"))
throw "SyntaxError: unmatched parenthese"
# retrieve all the words
words = []
word = null
while word = next_word(text, word)
words.push(word.word)
# name of the graph
name = null
if words[1] == ":="
name = words.shift()
words.shift()
result = analyse(words)
result = reduce(result)
# force result to be an array
result = if is_arr(result) then result else [result]
# make sure that result starts and ends with null
result.push(null)
result.unshift(null)
return { name: name, syntax: result }
draw_box = (g, text, x, y, monospaced=false) ->
t = g.text(x, y, text).attr({
"font-family": if monospaced then "consolas,monospaced" else "helvetica,arial",
"font-style" : if monospaced then "normal" else "italic",
"font-size" : 20,
"font-weight": if monospaced then "normal" else "bold",
"text-anchor": "start",
})
bbox = t.getBBox()
r = g.rect(bbox.x - 10, bbox.y - 6, \
bbox.width + 20, bbox.height + 12, \
if monospaced then 10 else 0).attr({
fill: "#EEE",
"stroke-width": 4,
})
r.insertBefore(t)
st = g.set(r, t)
st.translate(x - st.getBBox().x, 0) # move to x
return st
paths = []
connect = (g, p1, p2, outwards=0) ->
start = p1.end
end = p2.start
# horizontal straight line
deltaY = Math.abs(end[1] - start[1])
if deltaY < 1e-4 then outwards = 0
curve = (p1, p2, p3) -> [p1[0], p1[1], p2[0], p2[1], p3[0], p3[1]].join(" ")
if outwards == 2
# outwards right (or)
aux1 = [Math.max(start[0] - 20, end[0] - 20, start[0]), start[1]]
c1 = [aux1[0] + 10, aux1[1]]
aux2 = [Math.max(start[0] - 10, end[0] - 10, start[0]), start[1] - 10]
aux3 = [aux2[0], end[1] + 10]
c2 = [aux3[0], aux3[1] - 10]
paths.push("M", start.join(" "),
"L", aux1.join(" "),
"C", curve(c1, aux2, aux2),
"L", aux3.join(" "),
"C", curve(c2, end, end)
)
else if outwards == -2
# outwards left (or)
c1 = [start[0] + 10, start[1]]
aux1 = [Math.min(start[0] + 10, end[0] + 10, end[0]), start[1] + 10]
aux2 = [aux1[0], Math.max(start[1], end[1] - 10)]
c2 = [aux2[0], aux2[1] + 10]
aux3 = [Math.min(start[0] + 20, end[0] + 20, end[0]), end[1]]
paths.push("M", start.join(" "),
"C", curve(c1, aux1, aux1),
"L", aux2.join(" "),
"C", curve(c2, aux3, aux3),
"L", end.join(" ")
)
else if outwards == 1
# outwards right (repeat)
deltaY *= 0.5
aux1 = [Math.max(start[0], end[0]), start[1]]
aux2 = [aux1[0], end[1]]
c1 = [aux1[0] + deltaY, aux1[1]]
c2 = [aux2[0] + deltaY, aux2[1]]
paths.push("M", start.join(" "),
"L", aux1.join(" "),
"C", curve(c1, c2, aux2),
"L", end.join(" ")
)
else if outwards == -1
# outwards left (repeat)
deltaY *= 0.5
aux1 = [Math.min(start[0], end[0]), start[1]]
aux2 = [aux1[0], end[1]]
c1 = [aux1[0] - deltaY, aux1[1]]
c2 = [aux2[0] - deltaY, aux2[1]]
paths.push("M", start.join(" "),
"L", aux1.join(" "),
"C", curve(c1, c2, aux2),
"L", end.join(" "))
else
# straight line
paths.push("M", start.join(" "),
"L", end.join(" ")
)
return
traverse_draw = (g, obj, x, y) ->
start_marker = g.circle(x, y, 10).attr({
fill: "#FFF",
stroke: "#000",
"stroke-width": 4,
})
traverse = (obj, parallel) ->
# traverse the data set and retrieve and draw all the nodes
if is_arr(obj)
st = g.set()
dy = 0
widths = []
if parallel then start_x = x
for v in obj
tmp = traverse(v)
bbox = tmp.getBBox()
if parallel
# align vertial
x = start_x
tmp.translate(0, dy)
widths.push(bbox.width)
dy += bbox.height + 15
else
x = bbox.x + bbox.width + 20
st.push(tmp)
# align center
if parallel
max_width = Math.max.apply(Math, widths)
for i in [0...st.items.length]
st.items[i].translate(0.5 * (max_width - widths[i]), 0)
return st
else if is_obj(obj)
return traverse(
# traverse args if present
(if obj.args? then [obj.data, obj.args] else obj.data),
true
)
else
if obj?
# draw boxes
mono = false
if obj.match(/^((\".*\")|(\'.*\'))$/)?
mono = true
obj = obj.substring(1, obj.length - 1)
# remove whitespace if not monospaced
return draw_box(g, remove_html_enity(obj, not mono), x, y, mono)
else
# null element boxes
box = draw_box(g, "-", x, y).attr({ opacity: 0 })
bbox = box.getBBox()
_y = bbox.y + bbox.height * 0.5
box.push(g.path("M" + bbox.x + " " + _y +
"L" + (bbox.x + bbox.width) + " " + _y).attr({
"stroke-width": 4,
"stroke-linecap": "round",
}))
return box
traverse_connect = (obj, st, prev) ->
if is_arr(obj)
tmp = []
for i in [0...obj.length]
tmp.push(traverse_connect(obj[i], st[i], \
if i > 0 then tmp[i-1] else prev))
for i in [0...obj.length-1]
connect(g, tmp[i], tmp[i+1]) # linearly connect elements
# connect the "or" elements
if tmp[i].or?
connect(g, j, tmp[i+1], 2) for j in tmp[i].or
return { start: tmp[0].start, end: tmp[obj.length-1].end }
else if is_obj(obj)
if obj.type == "or"
tmp = []
unconnected = [] # unconnected to the next element
for i in [0...obj.data.length]
tmp.push(traverse_connect(obj.data[i], st[i], \
if i > 0 then tmp[i-1] else prev))
connect(g, prev, tmp[i], -2)
unconnected.push(tmp[i])
unconnected.shift() # first element is connect by the upper levels
tmp[0].or = unconnected
return tmp[0]
else if obj.type == "repeat"
data = [obj.data, obj.args]
tmp = []
for i in [0...data.length]
tmp.push(traverse_connect(data[i], st[i], prev))
if i > 0 # args
connect(g, {end: tmp[0].end}, {start: tmp[i].end}, 1)
connect(g, {end: tmp[0].start}, {start: tmp[i].start}, -1)
return tmp[0]
else
# return the dimensions of current box
bbox = st.getBBox()
_y = bbox.y + bbox.height * 0.5
return {
start: [bbox.x, _y],
end: [bbox.x + bbox.width, _y],
}
result = traverse(obj)
graph = traverse_connect(obj, result)
bbox = result.getBBox()
x = bbox.x + bbox.width
end_marker = g.circle(x, y, 10).attr({
fill: "#FFF",
stroke: "#000",
"stroke-width": 4,
})
# width and height of graph
h = bbox.height + bbox.y + 5
bbox = end_marker.getBBox()
w = bbox.width + bbox.x + 16
# connect start and end marker
connect(g, graph, {
start: [
bbox.x,
bbox.y + bbox.height * 0.5
]
})
bbox = start_marker.getBBox()
connect(g, {
end: [
bbox.x + bbox.width,
bbox.y + bbox.height * 0.5
]
}, graph)
start_marker.toFront()
p = g.path(paths.join("")).attr({
"stroke-width": 4,
"stroke-linecap": "butt",
}).toBack()
# reset paths
paths = []
return {
width: w,
height: h,
all: g.set(result, p, start_marker, end_marker),
}
draw = (elem, syntax)->
elem.innerHTML = ""
w = elem.offsetWidth
h = elem.offsetHeight
paper = Raphael(elem, w, h)
height_sum = 0
width_max = 0
for s in syntax
d = traverse_draw(paper, s.syntax, 30, if s.name then 55 else 30)
d.all.translate(0, height_sum)
if s.name
paper.text(10, 16, remove_html_enity(s.name, true)).attr({
"font-family": "helvetica,arial",
"font-style" : "italic",
"font-size" : 24,
"font-weight": "bold",
"text-anchor": "start",
}).translate(0, height_sum)
height_sum += d.height
width_max = Math.max(width_max, d.width)
paper.setSize(width_max, height_sum)
return d
window.SyntaxDiagram = (elem, code) ->
parsed = []
for c in code.split("====\n")
parsed.push(parse(c))
if is_str(elem)
elem = document.getElementById(elem)
return draw(elem, parsed)
| 117126 | ###
Syntax Diagram Creator
Copyright (c) 2011 <NAME>
Licensed under the MIT license.
###
"use strict"
## Utility functions
is_arr = (arr) -> arr instanceof Array
is_obj = (obj) -> obj? and typeof obj == "object" and not is_arr(obj)
is_str = (str) -> typeof str == "string"
count_char = (str, ch) -> str.split(ch).length - 1
merge_arr = () ->
tmp = []
for arr in arguments
if is_arr(arr)
tmp.push.apply(tmp, arr)
else
tmp.push(arr)
return tmp
##
html_enity = /\&\#(\d+);/g
remove_html_enity = if count_char(document.charset or \
document.characterSet or \
"", "UTF") > 0
then (str, keep_whitespace) ->
r = str.replace(html_enity, (match, capture) ->
c = +capture
if not keep_whitespace
if c == 32
return "\u00abSP\u00bb"
else if c == 9
return "\u00abTAB\u00bb"
else if c == 10
return "\u00abNL\u00bb"
else if c == 13
return "\u00abCR\u00bb"
return String.fromCharCode(c)
)
return if r.match(/^\s*$/) then "\u00ab\u2422\u00bb" else r
else (str, keep_whitespace) ->
r = str.replace(html_enity, (match, capture) ->
c = +capture
if not keep_whitespace
if c == 32
return "<<SP>>"
else if c == 9
return "<<TAB>>"
else if c == 10
return "<<NL>>"
else if c == 13
return "<<CR>>"
return String.fromCharCode(c)
)
return if r.match(/^\s*$/) then "<<WHITESPACE>>" else r
# get next word
next_word = (text, state) ->
state or= { next: 0 }
start = state.next
len = text.length
# skip space if a word starts with space
if text.charAt(start) == " " then ++start
if start >= len then return null
end = start
while end < len
# special characters
if text.charAt(end) in [" ", "(", ")", "*", "<", ">", "|"] then break
++end
# if length of word is 1
if start == end then ++end
word = text.substring(start, end)
return { next: end, word: word }
# analyse words
analyse = (words) ->
words_len = words.length
parse = (idx, single_token) ->
result = []
break_flag = !!single_token
while idx < words_len
c = words[idx]
if c == "("
# new group
next = parse(idx + 1)
result.push(next.result)
idx = next.index
else if c == "<"
# add arguments
if result.length > 0
tmp = result.pop()
if is_obj(tmp)
next = parse(idx + 1)
idx = next.index
tmp.args or= []
tmp.args.push(next.result)
result.push(tmp)
else
throw "SyntaxError"
else
throw "SyntaxError"
else if c == "*"
# repeat
tmp = result.pop()
result.push({
data: tmp,
type: "repeat",
})
++idx
else if c == "|"
# or
tmp = if result.length > 0 then result.pop() else null
next = parse(idx + 1, true)
idx = next.index
if is_obj(tmp) and tmp.type != "repeat"
if not is_arr(tmp.data) then tmp.data = [tmp.data]
tmp.data.push(next.result)
result.push(tmp)
else
result.push({
data: [tmp, next.result],
type: "or",
})
else if c == ")"
break_flag = true
++idx
else if c == ">"
result.reverse()
break_flag = true
++idx
else
result.push(words[idx])
++idx
if break_flag then break
return { result: result, index: idx }
return parse(0).result
# reduce redundant
reduce = (obj) ->
if is_arr(obj)
# flatten the array
if obj.length == 0 then return null
else if obj.length == 1 then return reduce(obj[0])
else return (reduce(v) for v in obj)
else if is_obj(obj)
tmp = {}
tmp[k] = reduce(v) for k, v of obj
if tmp.type == "repeat"
tmp.args or= [null]
if not is_arr(tmp.args) then tmp.args = [tmp.args]
return [null, tmp, null]
else
return obj
parse = (text) ->
text = text
# clean the text
# remove comments as long as the # isn't after a \
.replace(/(^|[^\\])#.+/g, "$1")
# escape characters
.replace(/\\./g, (match) ->
c = match.charCodeAt(1)
if c == 116 # t
c = 9
else if c == 110 # n
c = 10
else if c == 114 # r
c = 13
return "&#" + c + ";"
)
# clean whitespace
.replace(/\s+/g, " ")
# transform text
# optional element [x] <=> (|x) as long as
# x only contains or e.g. [a|b|c]
.replace(///
\[
\s* # ignore starting and ending spaces
(
[^
\s # no groups
\(\)
\[\] # no optional
\* # no repeat
]*
)
\s*
\]
///g, "(|$1)")
# optional element [x] <=> (|(x))
# e.g. [[a] [b]]
.replace(/\[/g, "(|(")
.replace(/\]/g, "))")
# remove redundant *
# e.g. a****** <=> a*
.replace(/\*+/g, "*")
# parenthese pairs
if (count_char(text, "(") != count_char(text, ")")) or
(count_char(text, "<") != count_char(text, ">"))
throw "SyntaxError: unmatched parenthese"
# retrieve all the words
words = []
word = null
while word = next_word(text, word)
words.push(word.word)
# name of the graph
name = null
if words[1] == ":="
name = words.shift()
words.shift()
result = analyse(words)
result = reduce(result)
# force result to be an array
result = if is_arr(result) then result else [result]
# make sure that result starts and ends with null
result.push(null)
result.unshift(null)
return { name: name, syntax: result }
draw_box = (g, text, x, y, monospaced=false) ->
t = g.text(x, y, text).attr({
"font-family": if monospaced then "consolas,monospaced" else "helvetica,arial",
"font-style" : if monospaced then "normal" else "italic",
"font-size" : 20,
"font-weight": if monospaced then "normal" else "bold",
"text-anchor": "start",
})
bbox = t.getBBox()
r = g.rect(bbox.x - 10, bbox.y - 6, \
bbox.width + 20, bbox.height + 12, \
if monospaced then 10 else 0).attr({
fill: "#EEE",
"stroke-width": 4,
})
r.insertBefore(t)
st = g.set(r, t)
st.translate(x - st.getBBox().x, 0) # move to x
return st
paths = []
connect = (g, p1, p2, outwards=0) ->
start = p1.end
end = p2.start
# horizontal straight line
deltaY = Math.abs(end[1] - start[1])
if deltaY < 1e-4 then outwards = 0
curve = (p1, p2, p3) -> [p1[0], p1[1], p2[0], p2[1], p3[0], p3[1]].join(" ")
if outwards == 2
# outwards right (or)
aux1 = [Math.max(start[0] - 20, end[0] - 20, start[0]), start[1]]
c1 = [aux1[0] + 10, aux1[1]]
aux2 = [Math.max(start[0] - 10, end[0] - 10, start[0]), start[1] - 10]
aux3 = [aux2[0], end[1] + 10]
c2 = [aux3[0], aux3[1] - 10]
paths.push("M", start.join(" "),
"L", aux1.join(" "),
"C", curve(c1, aux2, aux2),
"L", aux3.join(" "),
"C", curve(c2, end, end)
)
else if outwards == -2
# outwards left (or)
c1 = [start[0] + 10, start[1]]
aux1 = [Math.min(start[0] + 10, end[0] + 10, end[0]), start[1] + 10]
aux2 = [aux1[0], Math.max(start[1], end[1] - 10)]
c2 = [aux2[0], aux2[1] + 10]
aux3 = [Math.min(start[0] + 20, end[0] + 20, end[0]), end[1]]
paths.push("M", start.join(" "),
"C", curve(c1, aux1, aux1),
"L", aux2.join(" "),
"C", curve(c2, aux3, aux3),
"L", end.join(" ")
)
else if outwards == 1
# outwards right (repeat)
deltaY *= 0.5
aux1 = [Math.max(start[0], end[0]), start[1]]
aux2 = [aux1[0], end[1]]
c1 = [aux1[0] + deltaY, aux1[1]]
c2 = [aux2[0] + deltaY, aux2[1]]
paths.push("M", start.join(" "),
"L", aux1.join(" "),
"C", curve(c1, c2, aux2),
"L", end.join(" ")
)
else if outwards == -1
# outwards left (repeat)
deltaY *= 0.5
aux1 = [Math.min(start[0], end[0]), start[1]]
aux2 = [aux1[0], end[1]]
c1 = [aux1[0] - deltaY, aux1[1]]
c2 = [aux2[0] - deltaY, aux2[1]]
paths.push("M", start.join(" "),
"L", aux1.join(" "),
"C", curve(c1, c2, aux2),
"L", end.join(" "))
else
# straight line
paths.push("M", start.join(" "),
"L", end.join(" ")
)
return
traverse_draw = (g, obj, x, y) ->
start_marker = g.circle(x, y, 10).attr({
fill: "#FFF",
stroke: "#000",
"stroke-width": 4,
})
traverse = (obj, parallel) ->
# traverse the data set and retrieve and draw all the nodes
if is_arr(obj)
st = g.set()
dy = 0
widths = []
if parallel then start_x = x
for v in obj
tmp = traverse(v)
bbox = tmp.getBBox()
if parallel
# align vertial
x = start_x
tmp.translate(0, dy)
widths.push(bbox.width)
dy += bbox.height + 15
else
x = bbox.x + bbox.width + 20
st.push(tmp)
# align center
if parallel
max_width = Math.max.apply(Math, widths)
for i in [0...st.items.length]
st.items[i].translate(0.5 * (max_width - widths[i]), 0)
return st
else if is_obj(obj)
return traverse(
# traverse args if present
(if obj.args? then [obj.data, obj.args] else obj.data),
true
)
else
if obj?
# draw boxes
mono = false
if obj.match(/^((\".*\")|(\'.*\'))$/)?
mono = true
obj = obj.substring(1, obj.length - 1)
# remove whitespace if not monospaced
return draw_box(g, remove_html_enity(obj, not mono), x, y, mono)
else
# null element boxes
box = draw_box(g, "-", x, y).attr({ opacity: 0 })
bbox = box.getBBox()
_y = bbox.y + bbox.height * 0.5
box.push(g.path("M" + bbox.x + " " + _y +
"L" + (bbox.x + bbox.width) + " " + _y).attr({
"stroke-width": 4,
"stroke-linecap": "round",
}))
return box
traverse_connect = (obj, st, prev) ->
if is_arr(obj)
tmp = []
for i in [0...obj.length]
tmp.push(traverse_connect(obj[i], st[i], \
if i > 0 then tmp[i-1] else prev))
for i in [0...obj.length-1]
connect(g, tmp[i], tmp[i+1]) # linearly connect elements
# connect the "or" elements
if tmp[i].or?
connect(g, j, tmp[i+1], 2) for j in tmp[i].or
return { start: tmp[0].start, end: tmp[obj.length-1].end }
else if is_obj(obj)
if obj.type == "or"
tmp = []
unconnected = [] # unconnected to the next element
for i in [0...obj.data.length]
tmp.push(traverse_connect(obj.data[i], st[i], \
if i > 0 then tmp[i-1] else prev))
connect(g, prev, tmp[i], -2)
unconnected.push(tmp[i])
unconnected.shift() # first element is connect by the upper levels
tmp[0].or = unconnected
return tmp[0]
else if obj.type == "repeat"
data = [obj.data, obj.args]
tmp = []
for i in [0...data.length]
tmp.push(traverse_connect(data[i], st[i], prev))
if i > 0 # args
connect(g, {end: tmp[0].end}, {start: tmp[i].end}, 1)
connect(g, {end: tmp[0].start}, {start: tmp[i].start}, -1)
return tmp[0]
else
# return the dimensions of current box
bbox = st.getBBox()
_y = bbox.y + bbox.height * 0.5
return {
start: [bbox.x, _y],
end: [bbox.x + bbox.width, _y],
}
result = traverse(obj)
graph = traverse_connect(obj, result)
bbox = result.getBBox()
x = bbox.x + bbox.width
end_marker = g.circle(x, y, 10).attr({
fill: "#FFF",
stroke: "#000",
"stroke-width": 4,
})
# width and height of graph
h = bbox.height + bbox.y + 5
bbox = end_marker.getBBox()
w = bbox.width + bbox.x + 16
# connect start and end marker
connect(g, graph, {
start: [
bbox.x,
bbox.y + bbox.height * 0.5
]
})
bbox = start_marker.getBBox()
connect(g, {
end: [
bbox.x + bbox.width,
bbox.y + bbox.height * 0.5
]
}, graph)
start_marker.toFront()
p = g.path(paths.join("")).attr({
"stroke-width": 4,
"stroke-linecap": "butt",
}).toBack()
# reset paths
paths = []
return {
width: w,
height: h,
all: g.set(result, p, start_marker, end_marker),
}
draw = (elem, syntax)->
elem.innerHTML = ""
w = elem.offsetWidth
h = elem.offsetHeight
paper = Raphael(elem, w, h)
height_sum = 0
width_max = 0
for s in syntax
d = traverse_draw(paper, s.syntax, 30, if s.name then 55 else 30)
d.all.translate(0, height_sum)
if s.name
paper.text(10, 16, remove_html_enity(s.name, true)).attr({
"font-family": "helvetica,arial",
"font-style" : "italic",
"font-size" : 24,
"font-weight": "bold",
"text-anchor": "start",
}).translate(0, height_sum)
height_sum += d.height
width_max = Math.max(width_max, d.width)
paper.setSize(width_max, height_sum)
return d
window.SyntaxDiagram = (elem, code) ->
parsed = []
for c in code.split("====\n")
parsed.push(parse(c))
if is_str(elem)
elem = document.getElementById(elem)
return draw(elem, parsed)
| true | ###
Syntax Diagram Creator
Copyright (c) 2011 PI:NAME:<NAME>END_PI
Licensed under the MIT license.
###
"use strict"
## Utility functions
is_arr = (arr) -> arr instanceof Array
is_obj = (obj) -> obj? and typeof obj == "object" and not is_arr(obj)
is_str = (str) -> typeof str == "string"
count_char = (str, ch) -> str.split(ch).length - 1
merge_arr = () ->
tmp = []
for arr in arguments
if is_arr(arr)
tmp.push.apply(tmp, arr)
else
tmp.push(arr)
return tmp
##
html_enity = /\&\#(\d+);/g
remove_html_enity = if count_char(document.charset or \
document.characterSet or \
"", "UTF") > 0
then (str, keep_whitespace) ->
r = str.replace(html_enity, (match, capture) ->
c = +capture
if not keep_whitespace
if c == 32
return "\u00abSP\u00bb"
else if c == 9
return "\u00abTAB\u00bb"
else if c == 10
return "\u00abNL\u00bb"
else if c == 13
return "\u00abCR\u00bb"
return String.fromCharCode(c)
)
return if r.match(/^\s*$/) then "\u00ab\u2422\u00bb" else r
else (str, keep_whitespace) ->
r = str.replace(html_enity, (match, capture) ->
c = +capture
if not keep_whitespace
if c == 32
return "<<SP>>"
else if c == 9
return "<<TAB>>"
else if c == 10
return "<<NL>>"
else if c == 13
return "<<CR>>"
return String.fromCharCode(c)
)
return if r.match(/^\s*$/) then "<<WHITESPACE>>" else r
# get next word
next_word = (text, state) ->
state or= { next: 0 }
start = state.next
len = text.length
# skip space if a word starts with space
if text.charAt(start) == " " then ++start
if start >= len then return null
end = start
while end < len
# special characters
if text.charAt(end) in [" ", "(", ")", "*", "<", ">", "|"] then break
++end
# if length of word is 1
if start == end then ++end
word = text.substring(start, end)
return { next: end, word: word }
# analyse words
analyse = (words) ->
words_len = words.length
parse = (idx, single_token) ->
result = []
break_flag = !!single_token
while idx < words_len
c = words[idx]
if c == "("
# new group
next = parse(idx + 1)
result.push(next.result)
idx = next.index
else if c == "<"
# add arguments
if result.length > 0
tmp = result.pop()
if is_obj(tmp)
next = parse(idx + 1)
idx = next.index
tmp.args or= []
tmp.args.push(next.result)
result.push(tmp)
else
throw "SyntaxError"
else
throw "SyntaxError"
else if c == "*"
# repeat
tmp = result.pop()
result.push({
data: tmp,
type: "repeat",
})
++idx
else if c == "|"
# or
tmp = if result.length > 0 then result.pop() else null
next = parse(idx + 1, true)
idx = next.index
if is_obj(tmp) and tmp.type != "repeat"
if not is_arr(tmp.data) then tmp.data = [tmp.data]
tmp.data.push(next.result)
result.push(tmp)
else
result.push({
data: [tmp, next.result],
type: "or",
})
else if c == ")"
break_flag = true
++idx
else if c == ">"
result.reverse()
break_flag = true
++idx
else
result.push(words[idx])
++idx
if break_flag then break
return { result: result, index: idx }
return parse(0).result
# reduce redundant
reduce = (obj) ->
if is_arr(obj)
# flatten the array
if obj.length == 0 then return null
else if obj.length == 1 then return reduce(obj[0])
else return (reduce(v) for v in obj)
else if is_obj(obj)
tmp = {}
tmp[k] = reduce(v) for k, v of obj
if tmp.type == "repeat"
tmp.args or= [null]
if not is_arr(tmp.args) then tmp.args = [tmp.args]
return [null, tmp, null]
else
return obj
parse = (text) ->
text = text
# clean the text
# remove comments as long as the # isn't after a \
.replace(/(^|[^\\])#.+/g, "$1")
# escape characters
.replace(/\\./g, (match) ->
c = match.charCodeAt(1)
if c == 116 # t
c = 9
else if c == 110 # n
c = 10
else if c == 114 # r
c = 13
return "&#" + c + ";"
)
# clean whitespace
.replace(/\s+/g, " ")
# transform text
# optional element [x] <=> (|x) as long as
# x only contains or e.g. [a|b|c]
.replace(///
\[
\s* # ignore starting and ending spaces
(
[^
\s # no groups
\(\)
\[\] # no optional
\* # no repeat
]*
)
\s*
\]
///g, "(|$1)")
# optional element [x] <=> (|(x))
# e.g. [[a] [b]]
.replace(/\[/g, "(|(")
.replace(/\]/g, "))")
# remove redundant *
# e.g. a****** <=> a*
.replace(/\*+/g, "*")
# parenthese pairs
if (count_char(text, "(") != count_char(text, ")")) or
(count_char(text, "<") != count_char(text, ">"))
throw "SyntaxError: unmatched parenthese"
# retrieve all the words
words = []
word = null
while word = next_word(text, word)
words.push(word.word)
# name of the graph
name = null
if words[1] == ":="
name = words.shift()
words.shift()
result = analyse(words)
result = reduce(result)
# force result to be an array
result = if is_arr(result) then result else [result]
# make sure that result starts and ends with null
result.push(null)
result.unshift(null)
return { name: name, syntax: result }
draw_box = (g, text, x, y, monospaced=false) ->
t = g.text(x, y, text).attr({
"font-family": if monospaced then "consolas,monospaced" else "helvetica,arial",
"font-style" : if monospaced then "normal" else "italic",
"font-size" : 20,
"font-weight": if monospaced then "normal" else "bold",
"text-anchor": "start",
})
bbox = t.getBBox()
r = g.rect(bbox.x - 10, bbox.y - 6, \
bbox.width + 20, bbox.height + 12, \
if monospaced then 10 else 0).attr({
fill: "#EEE",
"stroke-width": 4,
})
r.insertBefore(t)
st = g.set(r, t)
st.translate(x - st.getBBox().x, 0) # move to x
return st
paths = []
connect = (g, p1, p2, outwards=0) ->
start = p1.end
end = p2.start
# horizontal straight line
deltaY = Math.abs(end[1] - start[1])
if deltaY < 1e-4 then outwards = 0
curve = (p1, p2, p3) -> [p1[0], p1[1], p2[0], p2[1], p3[0], p3[1]].join(" ")
if outwards == 2
# outwards right (or)
aux1 = [Math.max(start[0] - 20, end[0] - 20, start[0]), start[1]]
c1 = [aux1[0] + 10, aux1[1]]
aux2 = [Math.max(start[0] - 10, end[0] - 10, start[0]), start[1] - 10]
aux3 = [aux2[0], end[1] + 10]
c2 = [aux3[0], aux3[1] - 10]
paths.push("M", start.join(" "),
"L", aux1.join(" "),
"C", curve(c1, aux2, aux2),
"L", aux3.join(" "),
"C", curve(c2, end, end)
)
else if outwards == -2
# outwards left (or)
c1 = [start[0] + 10, start[1]]
aux1 = [Math.min(start[0] + 10, end[0] + 10, end[0]), start[1] + 10]
aux2 = [aux1[0], Math.max(start[1], end[1] - 10)]
c2 = [aux2[0], aux2[1] + 10]
aux3 = [Math.min(start[0] + 20, end[0] + 20, end[0]), end[1]]
paths.push("M", start.join(" "),
"C", curve(c1, aux1, aux1),
"L", aux2.join(" "),
"C", curve(c2, aux3, aux3),
"L", end.join(" ")
)
else if outwards == 1
# outwards right (repeat)
deltaY *= 0.5
aux1 = [Math.max(start[0], end[0]), start[1]]
aux2 = [aux1[0], end[1]]
c1 = [aux1[0] + deltaY, aux1[1]]
c2 = [aux2[0] + deltaY, aux2[1]]
paths.push("M", start.join(" "),
"L", aux1.join(" "),
"C", curve(c1, c2, aux2),
"L", end.join(" ")
)
else if outwards == -1
# outwards left (repeat)
deltaY *= 0.5
aux1 = [Math.min(start[0], end[0]), start[1]]
aux2 = [aux1[0], end[1]]
c1 = [aux1[0] - deltaY, aux1[1]]
c2 = [aux2[0] - deltaY, aux2[1]]
paths.push("M", start.join(" "),
"L", aux1.join(" "),
"C", curve(c1, c2, aux2),
"L", end.join(" "))
else
# straight line
paths.push("M", start.join(" "),
"L", end.join(" ")
)
return
traverse_draw = (g, obj, x, y) ->
start_marker = g.circle(x, y, 10).attr({
fill: "#FFF",
stroke: "#000",
"stroke-width": 4,
})
traverse = (obj, parallel) ->
# traverse the data set and retrieve and draw all the nodes
if is_arr(obj)
st = g.set()
dy = 0
widths = []
if parallel then start_x = x
for v in obj
tmp = traverse(v)
bbox = tmp.getBBox()
if parallel
# align vertial
x = start_x
tmp.translate(0, dy)
widths.push(bbox.width)
dy += bbox.height + 15
else
x = bbox.x + bbox.width + 20
st.push(tmp)
# align center
if parallel
max_width = Math.max.apply(Math, widths)
for i in [0...st.items.length]
st.items[i].translate(0.5 * (max_width - widths[i]), 0)
return st
else if is_obj(obj)
return traverse(
# traverse args if present
(if obj.args? then [obj.data, obj.args] else obj.data),
true
)
else
if obj?
# draw boxes
mono = false
if obj.match(/^((\".*\")|(\'.*\'))$/)?
mono = true
obj = obj.substring(1, obj.length - 1)
# remove whitespace if not monospaced
return draw_box(g, remove_html_enity(obj, not mono), x, y, mono)
else
# null element boxes
box = draw_box(g, "-", x, y).attr({ opacity: 0 })
bbox = box.getBBox()
_y = bbox.y + bbox.height * 0.5
box.push(g.path("M" + bbox.x + " " + _y +
"L" + (bbox.x + bbox.width) + " " + _y).attr({
"stroke-width": 4,
"stroke-linecap": "round",
}))
return box
traverse_connect = (obj, st, prev) ->
if is_arr(obj)
tmp = []
for i in [0...obj.length]
tmp.push(traverse_connect(obj[i], st[i], \
if i > 0 then tmp[i-1] else prev))
for i in [0...obj.length-1]
connect(g, tmp[i], tmp[i+1]) # linearly connect elements
# connect the "or" elements
if tmp[i].or?
connect(g, j, tmp[i+1], 2) for j in tmp[i].or
return { start: tmp[0].start, end: tmp[obj.length-1].end }
else if is_obj(obj)
if obj.type == "or"
tmp = []
unconnected = [] # unconnected to the next element
for i in [0...obj.data.length]
tmp.push(traverse_connect(obj.data[i], st[i], \
if i > 0 then tmp[i-1] else prev))
connect(g, prev, tmp[i], -2)
unconnected.push(tmp[i])
unconnected.shift() # first element is connect by the upper levels
tmp[0].or = unconnected
return tmp[0]
else if obj.type == "repeat"
data = [obj.data, obj.args]
tmp = []
for i in [0...data.length]
tmp.push(traverse_connect(data[i], st[i], prev))
if i > 0 # args
connect(g, {end: tmp[0].end}, {start: tmp[i].end}, 1)
connect(g, {end: tmp[0].start}, {start: tmp[i].start}, -1)
return tmp[0]
else
# return the dimensions of current box
bbox = st.getBBox()
_y = bbox.y + bbox.height * 0.5
return {
start: [bbox.x, _y],
end: [bbox.x + bbox.width, _y],
}
result = traverse(obj)
graph = traverse_connect(obj, result)
bbox = result.getBBox()
x = bbox.x + bbox.width
end_marker = g.circle(x, y, 10).attr({
fill: "#FFF",
stroke: "#000",
"stroke-width": 4,
})
# width and height of graph
h = bbox.height + bbox.y + 5
bbox = end_marker.getBBox()
w = bbox.width + bbox.x + 16
# connect start and end marker
connect(g, graph, {
start: [
bbox.x,
bbox.y + bbox.height * 0.5
]
})
bbox = start_marker.getBBox()
connect(g, {
end: [
bbox.x + bbox.width,
bbox.y + bbox.height * 0.5
]
}, graph)
start_marker.toFront()
p = g.path(paths.join("")).attr({
"stroke-width": 4,
"stroke-linecap": "butt",
}).toBack()
# reset paths
paths = []
return {
width: w,
height: h,
all: g.set(result, p, start_marker, end_marker),
}
draw = (elem, syntax)->
elem.innerHTML = ""
w = elem.offsetWidth
h = elem.offsetHeight
paper = Raphael(elem, w, h)
height_sum = 0
width_max = 0
for s in syntax
d = traverse_draw(paper, s.syntax, 30, if s.name then 55 else 30)
d.all.translate(0, height_sum)
if s.name
paper.text(10, 16, remove_html_enity(s.name, true)).attr({
"font-family": "helvetica,arial",
"font-style" : "italic",
"font-size" : 24,
"font-weight": "bold",
"text-anchor": "start",
}).translate(0, height_sum)
height_sum += d.height
width_max = Math.max(width_max, d.width)
paper.setSize(width_max, height_sum)
return d
window.SyntaxDiagram = (elem, code) ->
parsed = []
for c in code.split("====\n")
parsed.push(parse(c))
if is_str(elem)
elem = document.getElementById(elem)
return draw(elem, parsed)
|
[
{
"context": "ew Tests for no-constant-condition rule.\n# @author Christian Schulz <http://rndm.de>\n###\n\n'use strict'\n\n#------------",
"end": 85,
"score": 0.999686062335968,
"start": 69,
"tag": "NAME",
"value": "Christian Schulz"
}
] | src/tests/rules/no-constant-condition.coffee | danielbayley/eslint-plugin-coffee | 0 | ###*
# @fileoverview Tests for no-constant-condition rule.
# @author Christian Schulz <http://rndm.de>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-constant-condition'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-constant-condition', rule,
valid: [
'if a then ;'
'if (a == 0) then ;'
'if (a = f()) then ;'
'if (1; a) then ;'
"if ('every' of []) then ;"
'while (~!a) then ;'
'while (a = b) then ;'
'if q > 0 then 1 else 2'
'while (x += 3) then ;'
# #5228, typeof conditions
"if typeof x is 'undefined' then ;"
"if a is 'str' and typeof b then ;"
'typeof a == typeof b'
"typeof 'a' is 'string' or typeof b is 'string'"
# #5693
"if (xyz is 'str1' && abc is 'str2') then ;"
"if (xyz is 'str1' || abc is 'str2') then ;"
"if (xyz is 'str1' || abc is 'str2' && pqr is 5) then ;"
"if (typeof abc is 'string' && abc is 'str2') then ;"
"if (false || abc is 'str') then ;"
"if (true && abc is 'str') then ;"
"if (typeof 'str' && abc is 'str') then ;"
"if (abc is 'str' || no || def is 'str') then ;"
"if (true && abc is 'str' || def is 'str') then ;"
"if (yes && typeof abc is 'string') then ;"
,
# { checkLoops: false }
code: 'while (true) then ;', options: [checkLoops: no]
,
code: 'loop then ;', options: [checkLoops: no]
,
'''
foo = ->
while true
yield 'foo'
'''
'''
foo = ->
while yes
while true
yield
'''
'''
foo = ->
while true
-> yield
yield
'''
]
invalid: [
code: 'if true then 1 else 2'
errors: [messageId: 'unexpected', type: 'Literal']
,
code: 'if yes then 1 else 2'
errors: [messageId: 'unexpected', type: 'Literal']
,
code: 'if q = 0 then 1 else 2'
errors: [messageId: 'unexpected', type: 'AssignmentExpression']
,
code: 'if (q = 0) then 1 else 2'
errors: [messageId: 'unexpected', type: 'AssignmentExpression']
,
code: 'if (-2) then ;'
errors: [messageId: 'unexpected', type: 'UnaryExpression']
,
code: 'if (true) then ;'
errors: [messageId: 'unexpected', type: 'Literal']
,
code: 'if ({}) then ;'
errors: [messageId: 'unexpected', type: 'ObjectExpression']
,
code: 'if (0 < 1) then ;'
errors: [messageId: 'unexpected', type: 'BinaryExpression']
,
code: 'if (0 || 1) then ;'
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: 'if (0 ? 1) then ;'
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: 'if (a; 1) then ;'
errors: [messageId: 'unexpected', type: 'SequenceExpression']
,
code: 'while ([]) then ;'
errors: [messageId: 'unexpected', type: 'ArrayExpression']
,
code: 'while (~!0) then ;'
errors: [messageId: 'unexpected', type: 'UnaryExpression']
,
code: 'while (x = 1) then ;'
errors: [messageId: 'unexpected', type: 'AssignmentExpression']
,
code: 'while (->) then ;'
errors: [messageId: 'unexpected', type: 'FunctionExpression']
,
code: 'while (true) then ;'
errors: [messageId: 'unexpected', type: 'Literal']
,
code: 'loop then ;', errors: [messageId: 'unexpected', type: 'Literal']
,
# #5228 , typeof conditions
code: 'if (typeof x) then ;'
errors: [messageId: 'unexpected', type: 'UnaryExpression']
,
code: "if (typeof 'abc' is 'string') then ;"
errors: [messageId: 'unexpected', type: 'BinaryExpression']
,
code: 'if (a = typeof b) then ;'
errors: [messageId: 'unexpected', type: 'AssignmentExpression']
,
code: 'if (a; typeof b) then ;'
errors: [messageId: 'unexpected', type: 'SequenceExpression']
,
code: "if (typeof 'a' == 'string' or typeof 'b' == 'string') then ;"
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: 'while (typeof x) then ;'
errors: [messageId: 'unexpected', type: 'UnaryExpression']
,
# #5693
code: "if (no and abc is 'str') then ;"
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: "if (true || abc is 'str') then ;"
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: "if (abc is 'str' || true) then ;"
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: "if (abc is 'str' || true || def is 'str') then ;"
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: 'if (no ? yes) then ;'
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: "if (typeof abc is 'str' || true) then ;"
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: '''
->
while (true)
;
yield 'foo'
'''
errors: [messageId: 'unexpected', type: 'Literal']
,
code: '''
->
loop
yield 'foo' if true
'''
errors: [messageId: 'unexpected', type: 'Literal']
,
code: '''
->
while true
yield 'foo'
while true
;
'''
errors: [messageId: 'unexpected', type: 'Literal']
,
code: '''
a = ->
while true
;
yield 'foo'
'''
errors: [messageId: 'unexpected', type: 'Literal']
,
code: '''
while true
-> yield
'''
errors: [messageId: 'unexpected', type: 'Literal']
,
code: '''
->
yield 'foo' if yes
'''
errors: [messageId: 'unexpected', type: 'Literal']
,
code: '''
foo = ->
while true
bar = ->
while true
yield
'''
errors: [messageId: 'unexpected', type: 'Literal']
]
| 21713 | ###*
# @fileoverview Tests for no-constant-condition rule.
# @author <NAME> <http://rndm.de>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-constant-condition'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-constant-condition', rule,
valid: [
'if a then ;'
'if (a == 0) then ;'
'if (a = f()) then ;'
'if (1; a) then ;'
"if ('every' of []) then ;"
'while (~!a) then ;'
'while (a = b) then ;'
'if q > 0 then 1 else 2'
'while (x += 3) then ;'
# #5228, typeof conditions
"if typeof x is 'undefined' then ;"
"if a is 'str' and typeof b then ;"
'typeof a == typeof b'
"typeof 'a' is 'string' or typeof b is 'string'"
# #5693
"if (xyz is 'str1' && abc is 'str2') then ;"
"if (xyz is 'str1' || abc is 'str2') then ;"
"if (xyz is 'str1' || abc is 'str2' && pqr is 5) then ;"
"if (typeof abc is 'string' && abc is 'str2') then ;"
"if (false || abc is 'str') then ;"
"if (true && abc is 'str') then ;"
"if (typeof 'str' && abc is 'str') then ;"
"if (abc is 'str' || no || def is 'str') then ;"
"if (true && abc is 'str' || def is 'str') then ;"
"if (yes && typeof abc is 'string') then ;"
,
# { checkLoops: false }
code: 'while (true) then ;', options: [checkLoops: no]
,
code: 'loop then ;', options: [checkLoops: no]
,
'''
foo = ->
while true
yield 'foo'
'''
'''
foo = ->
while yes
while true
yield
'''
'''
foo = ->
while true
-> yield
yield
'''
]
invalid: [
code: 'if true then 1 else 2'
errors: [messageId: 'unexpected', type: 'Literal']
,
code: 'if yes then 1 else 2'
errors: [messageId: 'unexpected', type: 'Literal']
,
code: 'if q = 0 then 1 else 2'
errors: [messageId: 'unexpected', type: 'AssignmentExpression']
,
code: 'if (q = 0) then 1 else 2'
errors: [messageId: 'unexpected', type: 'AssignmentExpression']
,
code: 'if (-2) then ;'
errors: [messageId: 'unexpected', type: 'UnaryExpression']
,
code: 'if (true) then ;'
errors: [messageId: 'unexpected', type: 'Literal']
,
code: 'if ({}) then ;'
errors: [messageId: 'unexpected', type: 'ObjectExpression']
,
code: 'if (0 < 1) then ;'
errors: [messageId: 'unexpected', type: 'BinaryExpression']
,
code: 'if (0 || 1) then ;'
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: 'if (0 ? 1) then ;'
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: 'if (a; 1) then ;'
errors: [messageId: 'unexpected', type: 'SequenceExpression']
,
code: 'while ([]) then ;'
errors: [messageId: 'unexpected', type: 'ArrayExpression']
,
code: 'while (~!0) then ;'
errors: [messageId: 'unexpected', type: 'UnaryExpression']
,
code: 'while (x = 1) then ;'
errors: [messageId: 'unexpected', type: 'AssignmentExpression']
,
code: 'while (->) then ;'
errors: [messageId: 'unexpected', type: 'FunctionExpression']
,
code: 'while (true) then ;'
errors: [messageId: 'unexpected', type: 'Literal']
,
code: 'loop then ;', errors: [messageId: 'unexpected', type: 'Literal']
,
# #5228 , typeof conditions
code: 'if (typeof x) then ;'
errors: [messageId: 'unexpected', type: 'UnaryExpression']
,
code: "if (typeof 'abc' is 'string') then ;"
errors: [messageId: 'unexpected', type: 'BinaryExpression']
,
code: 'if (a = typeof b) then ;'
errors: [messageId: 'unexpected', type: 'AssignmentExpression']
,
code: 'if (a; typeof b) then ;'
errors: [messageId: 'unexpected', type: 'SequenceExpression']
,
code: "if (typeof 'a' == 'string' or typeof 'b' == 'string') then ;"
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: 'while (typeof x) then ;'
errors: [messageId: 'unexpected', type: 'UnaryExpression']
,
# #5693
code: "if (no and abc is 'str') then ;"
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: "if (true || abc is 'str') then ;"
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: "if (abc is 'str' || true) then ;"
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: "if (abc is 'str' || true || def is 'str') then ;"
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: 'if (no ? yes) then ;'
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: "if (typeof abc is 'str' || true) then ;"
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: '''
->
while (true)
;
yield 'foo'
'''
errors: [messageId: 'unexpected', type: 'Literal']
,
code: '''
->
loop
yield 'foo' if true
'''
errors: [messageId: 'unexpected', type: 'Literal']
,
code: '''
->
while true
yield 'foo'
while true
;
'''
errors: [messageId: 'unexpected', type: 'Literal']
,
code: '''
a = ->
while true
;
yield 'foo'
'''
errors: [messageId: 'unexpected', type: 'Literal']
,
code: '''
while true
-> yield
'''
errors: [messageId: 'unexpected', type: 'Literal']
,
code: '''
->
yield 'foo' if yes
'''
errors: [messageId: 'unexpected', type: 'Literal']
,
code: '''
foo = ->
while true
bar = ->
while true
yield
'''
errors: [messageId: 'unexpected', type: 'Literal']
]
| true | ###*
# @fileoverview Tests for no-constant-condition rule.
# @author PI:NAME:<NAME>END_PI <http://rndm.de>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-constant-condition'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-constant-condition', rule,
valid: [
'if a then ;'
'if (a == 0) then ;'
'if (a = f()) then ;'
'if (1; a) then ;'
"if ('every' of []) then ;"
'while (~!a) then ;'
'while (a = b) then ;'
'if q > 0 then 1 else 2'
'while (x += 3) then ;'
# #5228, typeof conditions
"if typeof x is 'undefined' then ;"
"if a is 'str' and typeof b then ;"
'typeof a == typeof b'
"typeof 'a' is 'string' or typeof b is 'string'"
# #5693
"if (xyz is 'str1' && abc is 'str2') then ;"
"if (xyz is 'str1' || abc is 'str2') then ;"
"if (xyz is 'str1' || abc is 'str2' && pqr is 5) then ;"
"if (typeof abc is 'string' && abc is 'str2') then ;"
"if (false || abc is 'str') then ;"
"if (true && abc is 'str') then ;"
"if (typeof 'str' && abc is 'str') then ;"
"if (abc is 'str' || no || def is 'str') then ;"
"if (true && abc is 'str' || def is 'str') then ;"
"if (yes && typeof abc is 'string') then ;"
,
# { checkLoops: false }
code: 'while (true) then ;', options: [checkLoops: no]
,
code: 'loop then ;', options: [checkLoops: no]
,
'''
foo = ->
while true
yield 'foo'
'''
'''
foo = ->
while yes
while true
yield
'''
'''
foo = ->
while true
-> yield
yield
'''
]
invalid: [
code: 'if true then 1 else 2'
errors: [messageId: 'unexpected', type: 'Literal']
,
code: 'if yes then 1 else 2'
errors: [messageId: 'unexpected', type: 'Literal']
,
code: 'if q = 0 then 1 else 2'
errors: [messageId: 'unexpected', type: 'AssignmentExpression']
,
code: 'if (q = 0) then 1 else 2'
errors: [messageId: 'unexpected', type: 'AssignmentExpression']
,
code: 'if (-2) then ;'
errors: [messageId: 'unexpected', type: 'UnaryExpression']
,
code: 'if (true) then ;'
errors: [messageId: 'unexpected', type: 'Literal']
,
code: 'if ({}) then ;'
errors: [messageId: 'unexpected', type: 'ObjectExpression']
,
code: 'if (0 < 1) then ;'
errors: [messageId: 'unexpected', type: 'BinaryExpression']
,
code: 'if (0 || 1) then ;'
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: 'if (0 ? 1) then ;'
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: 'if (a; 1) then ;'
errors: [messageId: 'unexpected', type: 'SequenceExpression']
,
code: 'while ([]) then ;'
errors: [messageId: 'unexpected', type: 'ArrayExpression']
,
code: 'while (~!0) then ;'
errors: [messageId: 'unexpected', type: 'UnaryExpression']
,
code: 'while (x = 1) then ;'
errors: [messageId: 'unexpected', type: 'AssignmentExpression']
,
code: 'while (->) then ;'
errors: [messageId: 'unexpected', type: 'FunctionExpression']
,
code: 'while (true) then ;'
errors: [messageId: 'unexpected', type: 'Literal']
,
code: 'loop then ;', errors: [messageId: 'unexpected', type: 'Literal']
,
# #5228 , typeof conditions
code: 'if (typeof x) then ;'
errors: [messageId: 'unexpected', type: 'UnaryExpression']
,
code: "if (typeof 'abc' is 'string') then ;"
errors: [messageId: 'unexpected', type: 'BinaryExpression']
,
code: 'if (a = typeof b) then ;'
errors: [messageId: 'unexpected', type: 'AssignmentExpression']
,
code: 'if (a; typeof b) then ;'
errors: [messageId: 'unexpected', type: 'SequenceExpression']
,
code: "if (typeof 'a' == 'string' or typeof 'b' == 'string') then ;"
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: 'while (typeof x) then ;'
errors: [messageId: 'unexpected', type: 'UnaryExpression']
,
# #5693
code: "if (no and abc is 'str') then ;"
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: "if (true || abc is 'str') then ;"
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: "if (abc is 'str' || true) then ;"
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: "if (abc is 'str' || true || def is 'str') then ;"
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: 'if (no ? yes) then ;'
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: "if (typeof abc is 'str' || true) then ;"
errors: [messageId: 'unexpected', type: 'LogicalExpression']
,
code: '''
->
while (true)
;
yield 'foo'
'''
errors: [messageId: 'unexpected', type: 'Literal']
,
code: '''
->
loop
yield 'foo' if true
'''
errors: [messageId: 'unexpected', type: 'Literal']
,
code: '''
->
while true
yield 'foo'
while true
;
'''
errors: [messageId: 'unexpected', type: 'Literal']
,
code: '''
a = ->
while true
;
yield 'foo'
'''
errors: [messageId: 'unexpected', type: 'Literal']
,
code: '''
while true
-> yield
'''
errors: [messageId: 'unexpected', type: 'Literal']
,
code: '''
->
yield 'foo' if yes
'''
errors: [messageId: 'unexpected', type: 'Literal']
,
code: '''
foo = ->
while true
bar = ->
while true
yield
'''
errors: [messageId: 'unexpected', type: 'Literal']
]
|
[
{
"context": "l/send\"\n\t\t\tsimulate: true\n\n_Cnf =\n\trealReceiver: \"mp@tcs.de\"\n\trealCcReceiver: \"mp+cc@tcs.de\"\n\trealBccReceiver",
"end": 406,
"score": 0.9999266862869263,
"start": 397,
"tag": "EMAIL",
"value": "mp@tcs.de"
},
{
"context": "nf =\n\trealReceiver: \"mp@tcs.d... | _src/test/test.coffee | mpneuried/tcs_mail_node_client | 1 | fs = require("fs")
should = require('should')
MailFactory = require("../lib/index")
Mail = require("../lib/index").mail
try
_factoryB = require( "../test_config_factoryB.js" )
console.info "Using config for FactoryB of file `test_config_factoryB.js"
catch _err
_factoryB =
appid: "wmshop"
config:
endpoint: "http://localhost:3000/email/send"
simulate: true
_Cnf =
realReceiver: "mp@tcs.de"
realCcReceiver: "mp+cc@tcs.de"
realBccReceiver: "mp+bcc@tcs.de"
factoryA:
appid: "wmshop"
config:
simulate: true
factoryB: _factoryB
randRange = ( lowVal, highVal )->
Math.floor( Math.random()*(highVal-lowVal+1 ))+lowVal
randomString = ( string_length = 5, specialLevel = 0, spaces = .1, breaks = 0 ) ->
chars = "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"
chars += "0123456789" if specialLevel >= 1
chars += "_-@:." if specialLevel >= 2
chars += "!\"§$%&/()=?*'_:;,.-#+¬”#£fi^\\˜·¯˙˚«∑€®†Ω¨⁄øπ•‘æœ@∆ºª©ƒ∂‚å–…∞µ~∫√ç≈¥" if specialLevel >= 3
randomstring = ""
i = 0
while i < string_length
rnum = Math.floor(Math.random() * chars.length)
if spaces > 0 and ( randRange( 0, 100 ) < ( 100 * spaces ) )
randomstring += " "
else if breaks > 0 and ( randRange( 0, 100 ) < ( 100 * breaks ) )
randomstring += "\n"
else
randomstring += chars.substring(rnum, rnum + 1)
i++
randomstring
randomstring
describe 'MAIL-FACTORY-TEST', ->
before ( done )->
done()
return
after ( done )->
done()
return
mailFactoryA = null
describe 'initialize & configure', ->
it 'create new factory', ( done )->
mailFactoryA = new MailFactory( _Cnf.factoryA.appid, _Cnf.factoryA.config )
mailFactoryA.should.be.an.instanceOf MailFactory
done()
return
it 'change configuration with no content', ( done )->
_cnf = mailFactoryA.config()
_cnf.should.be.an.instanceOf Object
done()
return
it 'change configuration - wrong sendermail', ( done )->
_cnf = mailFactoryA.config( sendermail: "test@tcs.de" )
_cnf.should.have.property( "sendermail" ).with.be.a.String().and.equal "test@tcs.de"
done()
return
it 'change configuration - wrong sendermail', ( done )->
try
_cnf = mailFactoryA.config( sendermail: "wrongmail" )
catch _err
_err.name.should.equal( "validation-config-sendermail" )
done()
return
throw new Error( "wrong sendermail not thrown" )
return
it 'change configuration - multiple sendermails', ( done )->
try
_cnf = mailFactoryA.config( sendermail: [ "test@success.de", "check@success.com" ] )
catch _err
_err.name.should.equal( "validation-config-sendermail" )
done()
return
throw new Error( "wrong sendermail not thrown" )
return
it 'change configuration - endpoint', ( done )->
_cnf = mailFactoryA.config( endpoint: "http://nodetest.tcs.de/email/send" )
_cnf.should.have.property( "endpoint" ).with.be.a.String().and.equal "http://nodetest.tcs.de/email/send"
done()
return
it 'change configuration - wrong endpoint', ( done )->
try
_cnf = mailFactoryA.config( endpoint: "wrongurl" )
catch _err
_err.name.should.equal( "validation-config-endpoint" )
done()
return
throw new Error( "wrong endpoint not thrown" )
return
it 'change configuration - multiple endpoints', ( done )->
try
_cnf = mailFactoryA.config( endpoint: [ "http://node.tcs.de/email/send", "http://nodetest.tcs.de/email/send" ] )
catch _err
_err.name.should.equal( "validation-config-endpoint" )
done()
return
throw new Error( "wrong endpoint not thrown" )
return
it 'change configuration - security with ignored keys', ( done )->
_cnf = mailFactoryA.config( security: { b: "asdf", a: 123 } )
_cnf.should.have.property( "security" ).with.be.a.Object().and.eql {}
done()
return
it 'change configuration - security', ( done )->
_cnf = mailFactoryA.config( security: { apikey: "abcdefg", xxx: 1233 } )
_cnf.should.have.property( "security" ).with.be.a.Object().and.eql { apikey: "abcdefg" }
done()
return
it 'change configuration - wrong security', ( done )->
try
_cnf = mailFactoryA.config( security: "123" )
catch _err
_err.name.should.equal( "validation-config-security" )
done()
return
throw new Error( "wrong security not thrown" )
return
it 'change configuration - returnpath', ( done )->
_cnf = mailFactoryA.config( returnPath: "return@tcs.de" )
_cnf.should.have.property( "returnPath" ).with.be.a.String().and.equal "return@tcs.de"
done()
return
it 'change configuration - returnpath null', ( done )->
_cnf = mailFactoryA.config( returnPath: null )
done()
return
it 'change configuration - wrong returnpath', ( done )->
try
_cnf = mailFactoryA.config( returnPath: "wrongmail" )
catch _err
_err.name.should.equal( "validation-config-returnpath" )
done()
return
throw new Error( "wrong returnpath not thrown" )
return
it 'change configuration - multiple returnpaths', ( done )->
try
_cnf = mailFactoryA.config( returnPath: [ "test@success.de", "check@success.com" ] )
catch _err
_err.name.should.equal( "validation-config-returnpath" )
done()
return
throw new Error( "wrong returnpath not thrown" )
return
it 'change configuration - from', ( done )->
_cnf = mailFactoryA.config( from: "return@tcs.de" )
done()
return
it 'change configuration - wrong from', ( done )->
try
_cnf = mailFactoryA.config( from: "wrongmail" )
catch _err
_err.name.should.equal( "validation-config-from" )
done()
return
throw new Error( "wrong from not thrown" )
return
it 'change configuration - multiple froms', ( done )->
try
_cnf = mailFactoryA.config( from: [ "test@success.de", "check@success.com" ] )
catch _err
_err.name.should.equal( "validation-config-from" )
done()
return
throw new Error( "wrong from not thrown" )
return
it 'change configuration - reply', ( done )->
_cnf = mailFactoryA.config( reply: "return@tcs.de" )
_cnf.should.have.property( "reply" ).with.be.a.String().and.equal "return@tcs.de"
done()
return
it 'change configuration - wrong reply', ( done )->
try
_cnf = mailFactoryA.config( reply: "wrongmail" )
catch _err
_err.name.should.equal( "validation-config-reply" )
done()
return
throw new Error( "wrong reply not thrown" )
return
it 'change configuration - multiple replys', ( done )->
_cnf = mailFactoryA.config( reply: [ "test@success.de", "check@success.com" ] )
_cnf.should.have.property( "reply" ).with.be.an.instanceOf( Array ).and.have.length( 2 )
done()
return
it 'change configuration - multiple replys + one wrong', ( done )->
try
_cnf = mailFactoryA.config( reply: [ "test@success.de", "wrongmail" ] )
throw new Error( "wrong reply not thrown" )
catch _err
_err.name.should.equal( "validation-config-reply" )
done()
return
return
describe 'factory methods', ->
mails = []
it 'create a mail', ( done )->
mail = mailFactoryA.create()
mails.push( mail )
mail.should.be.instanceOf Mail
mails[ 0 ].should.eql( mail )
done()
return
it 'get a mail', ( done )->
mail = mailFactoryA.get( mails[ 0 ].id )
mail.should.be.instanceOf Mail
mails[ 0 ].should.eql( mail )
done()
return
it 'destroy a mail', ( done )->
mail = mailFactoryA.get( mails[ 0 ].id )
mail.destroy()
mail = mailFactoryA.get( mails[ 0 ].id )
should.not.exist( mail )
mails = []
done()
return
it 'add 4 mails', ( done )->
for i in [0..3]
mails.push mailFactoryA.create().subject( "TEST #{i}" ).text( "CONTENT #{i}" ).to( "test#{i}@tcs.de" )
mailFactoryA.count().should.equal mails.length
done()
return
it 'send all mails', ( done )->
mailFactoryA.sendAll ( err )->
should.not.exist( err )
mailFactoryA.count().should.equal 0
mails = []
done()
return
return
return
describe 'mail methods', ->
mails = []
mailA = null
it 'create a test mail', ( done )->
mailA = mailFactoryA.create()
mails.push( mailA )
mailA.should.be.instanceOf Mail
mails[ 0 ].should.eql( mailA )
done()
return
it 'set to - single', ( done )->
_to = mailA.to( "test@tcs.de" ).to()
_to.should.be.a.String().and.equal "test@tcs.de"
done()
return
it 'set to - reset', ( done )->
_to = mailA.to( false ).to()
should.not.exist( _to )
done()
return
it 'set to - multiple', ( done )->
_to = mailA.to( [ "testA@tcs.de", "testB@tcs.de", "testC@tcs.de" ] ).to()
_to.should.be.an.Array().and.have.length( 3 )
done()
return
it 'set to - single wrong', ( done )->
try
_to = mailA.to( "testAtcs.de" )
catch _err
_err.name.should.equal( "validation-mail-to" )
done()
return
throw new Error( "wrong to - single not thrown" )
return
it 'set to - multiple wrong', ( done )->
try
_to = mailA.to( [ "testA@tcs.de", "testBtcs.de", "testC@tcs.de" ] )
catch _err
_err.name.should.equal( "validation-mail-to" )
done()
return
throw new Error( "wrong to - multiple not thrown" )
return
it 'set cc - single', ( done )->
_cc = mailA.cc( "test@tcs.de" ).cc()
_cc.should.be.a.String().and.equal "test@tcs.de"
done()
return
it 'set cc - multiple', ( done )->
_cc = mailA.cc( [ "testA@tcs.de", "testB@tcs.de", "testC@tcs.de" ] ).cc()
_cc.should.be.an.Array().and.have.length( 3 )
done()
return
it 'set cc - single wrong', ( done )->
try
_cc = mailA.cc( "testAtcs.de" )
catch _err
_err.name.should.equal( "validation-mail-cc" )
done()
return
throw new Error( "wrong cc - single not thrown" )
return
it 'set cc - multiple wrong', ( done )->
try
_cc = mailA.cc( [ "testA@tcs.de", "testBtcs.de", "testC@tcs.de" ] )
catch _err
_err.name.should.equal( "validation-mail-cc" )
done()
return
throw new Error( "wrong cc - multiple not thrown" )
return
it 'set cc - reset', ( done )->
_cc = mailA.cc( false ).cc()
should.not.exist( _cc )
done()
return
it 'set bcc - single', ( done )->
_bcc = mailA.bcc( "test@tcs.de" ).bcc()
_bcc.should.be.a.String().and.equal "test@tcs.de"
done()
return
it 'set bcc - multiple', ( done )->
_bcc = mailA.bcc( [ "testA@tcs.de", "testB@tcs.de", "testC@tcs.de" ] ).bcc()
_bcc.should.be.an.Array().and.have.length( 3 )
done()
return
it 'set bcc - single wrong', ( done )->
try
_bcc = mailA.bcc( "testAtcs.de" )
catch _err
_err.name.should.equal( "validation-mail-bcc" )
done()
return
throw new Error( "wrong bcc - single not thrown" )
return
it 'set bcc - multiple wrong', ( done )->
try
_bcc = mailA.bcc( [ "testA@tcs.de", "testBtcs.de", "testC@tcs.de" ] )
catch _err
_err.name.should.equal( "validation-mail-bcc" )
done()
return
throw new Error( "wrong bcc - multiple not thrown" )
return
it 'set bcc - reset', ( done )->
_bcc = mailA.bcc( false ).bcc()
should.not.exist( _bcc )
done()
return
it 'set subject', ( done )->
_subject = mailA.subject( "Test Subject" ).subject()
_subject.should.be.a.String().and.equal "Test Subject"
done()
return
it 'set subject - long', ( done )->
_val = randomString( 150, 2, .2, .05 )
_subject = mailA.subject( _val ).subject()
_subject.should.be.a.String().and.equal _val
done()
return
it 'set subject - html', ( done )->
_val = "<b>This is my html string</b>"
_subject = mailA.subject( _val ).subject()
_subject.should.be.a.String().and.equal _val
done()
return
it 'set subject - reset', ( done )->
try
mailA.subject( false )
catch _err
_err.name.should.equal( "validation-mail-subject" )
_val = "<b>This is my html string</b>"
_subject = mailA.subject()
_subject.should.be.a.String().and.equal _val
done()
return
throw new Error( "wrong subject - reset not thrown" )
return
it 'set subject - wrong type', ( done )->
_val = [ "my array subject" ]
try
mailA.subject( _val )
catch _err
_err.name.should.equal( "validation-mail-subject" )
done()
return
throw new Error( "wrong subject - type not thrown" )
return
it 'set text', ( done )->
_val = randomString( 150, 2, .2, .05 )
_text = mailA.text( _val ).text()
_text.should.be.a.String().and.equal _val
done()
return
it 'set text - html', ( done )->
_val = "<b>My HTML subject</b>"
_text = mailA.text( _val ).text()
_text.should.be.a.String().and.equal _val
done()
return
it 'set text - reset', ( done )->
_val = false
_text = mailA.text( _val ).text()
should.not.exist( _text )
done()
return
it 'set text - long', ( done )->
_val = randomString( 1000, 2, .2, .05 )
_text = mailA.text( _val ).text()
_text.should.be.a.String().and.equal _val
done()
return
it 'set text - wrong type', ( done )->
_val = [ "my array text" ]
try
mailA.text( _val )
catch _err
_err.name.should.equal( "validation-mail-text" )
done()
return
throw new Error( "wrong text - type not thrown" )
return
it 'set html', ( done )->
_val = randomString( 150, 2, .2, .05 )
_html = mailA.html( _val ).html()
_html.should.be.a.String().and.equal _val
done()
return
it 'set html - html from file', ( done )->
fs.readFile './test/data/html_example.html', ( err, file )->
if err
throw err
return
_val = file.toString( "utf-8" )
_html = mailA.html( _val ).html()
_html.should.be.a.String().and.equal _val
done()
return
return
it 'set html - reset', ( done )->
_val = false
_html = mailA.html( _val ).html()
should.not.exist( _html )
done()
return
it 'set html - wrong type', ( done )->
_val = [ "my array html" ]
try
mailA.html( _val )
catch _err
_err.name.should.equal( "validation-mail-html" )
done()
return
throw new Error( "wrong html - type not thrown" )
return
it 'set reply - single', ( done )->
_reply = mailA.reply( "test@tcs.de" ).reply()
_reply.should.be.a.String().and.equal "test@tcs.de"
done()
return
it 'set reply - reset', ( done )->
_reply = mailA.reply( false ).reply()
should.not.exist( _reply )
done()
return
it 'set reply - multiple', ( done )->
_reply = mailA.reply( [ "testA@tcs.de", "testB@tcs.de", "testC@tcs.de" ] ).reply()
_reply.should.be.an.Array().and.have.length( 3 )
done()
return
it 'set reply - single wrong', ( done )->
try
_reply = mailA.reply( "testAtcs.de" )
throw new Error( "wrong reply - single not thrown" )
catch _err
_err.name.should.equal( "validation-mail-reply" )
done()
return
it 'set reply - multiple wrong', ( done )->
try
_reply = mailA.reply( [ "testA@tcs.de", "testBtcs.de", "testC@tcs.de" ] )
catch _err
_err.name.should.equal( "validation-mail-reply" )
done()
return
throw new Error( "wrong reply - multiple not thrown" )
return
it 'set returnPath - single', ( done )->
_returnPath = mailA.returnPath( "test@tcs.de" ).returnPath()
_returnPath.should.be.a.String().and.equal "test@tcs.de"
done()
return
it 'set returnPath - reset', ( done )->
_returnPath = mailA.returnPath( false ).returnPath()
should.not.exist( _returnPath )
done()
return
it 'set returnPath - multiple', ( done )->
try
_returnPath = mailA.returnPath( [ "testA@tcs.de", "testB@tcs.de", "testC@tcs.de" ] )
catch _err
_err.name.should.equal( "validation-mail-returnpath" )
done()
return
throw new Error( "wrong returnPath - multiple not thrown" )
return
it 'set returnPath - single wrong', ( done )->
try
_returnPath = mailA.returnPath( "testAtcs.de" )
catch _err
_err.name.should.equal( "validation-mail-returnpath" )
done()
return
throw new Error( "wrong returnPath - single not thrown" )
return
it 'send this mail', ( done )->
mailA.send ( err )->
if err
throw err
return
done()
return
return
return
describe 'mail send tests', ->
mailFactoryB = null
it 'create new factory', ( done )->
mailFactoryB = new MailFactory( _Cnf.factoryB.appid, _Cnf.factoryB.config )
mailFactoryB.should.be.an.instanceOf MailFactory
done()
return
it 'create and send mail - simple', ( done )->
_mail = mailFactoryB.create().subject( "Simple Test" ).text( "TEST" ).to( _Cnf.realReceiver )
_mail.send ( err, result )->
should.not.exist( err )
result.should.have.property( "recipients" ).with.be.an.Array().and.containEql( _Cnf.realReceiver )
done()
return
return
it 'create and send mail - missing subject', ( done )->
mailFactoryB.create().to( "testB@tcs.de" ).send ( err )->
should.exist( err )
err.should.have.property( "name" ).with.be.a.String().and.equal "validation-mail-subject-missing"
done()
return
return
it 'create and send mail - missing receiver', ( done )->
mailFactoryB.create().subject( "no receiver" ).send ( err )->
should.exist( err )
err.should.have.property( "name" ).with.be.a.String().and.equal "validation-mail-receiver-missing"
done()
return
return
it 'create and send mail - missing content', ( done )->
mailFactoryB.create().subject( "missing content" ).bcc( _Cnf.realReceiver ).send ( err, result )->
should.exist( err )
err.should.have.property( "name" ).with.be.a.String().and.equal "validation-mail-content-missing"
done()
return
return
it 'create and send mail - with html content', ( done )->
mailFactoryB.create().subject( "HTML TEST" ).html( "<html><header><style>h1{color:#f00;}</style></header><body><h1 class=\"test\">Simple html content</h1><p>Test the sending of mails</p></html></body>" ).to( _Cnf.realReceiver ).send ( err, result )->
should.not.exist( err )
result.should.have.property( "recipients" ).with.be.an.Array().and.containEql( _Cnf.realReceiver )
done()
return
return
it 'create and send mail - with large html content', ( done )->
fs.readFile './test/data/html_example.html', ( err, file )->
if err
throw err
return
_val = file.toString( "utf-8" )
mailFactoryB.create().subject( "TCS E-Mail Node Client" ).html( _val ).to( _Cnf.realReceiver ).bcc( _Cnf.realCcReceiver ).send ( err, result )->
should.not.exist( err )
result.should.have.property( "recipients" ).with.be.an.Array().and.containEql( _Cnf.realReceiver )
done()
return
return
return
return
return
| 168065 | fs = require("fs")
should = require('should')
MailFactory = require("../lib/index")
Mail = require("../lib/index").mail
try
_factoryB = require( "../test_config_factoryB.js" )
console.info "Using config for FactoryB of file `test_config_factoryB.js"
catch _err
_factoryB =
appid: "wmshop"
config:
endpoint: "http://localhost:3000/email/send"
simulate: true
_Cnf =
realReceiver: "<EMAIL>"
realCcReceiver: "<EMAIL>"
realBccReceiver: "<EMAIL>"
factoryA:
appid: "wmshop"
config:
simulate: true
factoryB: _factoryB
randRange = ( lowVal, highVal )->
Math.floor( Math.random()*(highVal-lowVal+1 ))+lowVal
randomString = ( string_length = 5, specialLevel = 0, spaces = .1, breaks = 0 ) ->
chars = "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"
chars += "0123456789" if specialLevel >= 1
chars += "_-@:." if specialLevel >= 2
chars += "!\"§$%&/()=?*'_:;,.-#+¬”#£fi^\\˜·¯˙˚«∑€®†Ω¨⁄øπ•‘æœ@∆ºª©ƒ∂‚å–…∞µ~∫√ç≈¥" if specialLevel >= 3
randomstring = ""
i = 0
while i < string_length
rnum = Math.floor(Math.random() * chars.length)
if spaces > 0 and ( randRange( 0, 100 ) < ( 100 * spaces ) )
randomstring += " "
else if breaks > 0 and ( randRange( 0, 100 ) < ( 100 * breaks ) )
randomstring += "\n"
else
randomstring += chars.substring(rnum, rnum + 1)
i++
randomstring
randomstring
describe 'MAIL-FACTORY-TEST', ->
before ( done )->
done()
return
after ( done )->
done()
return
mailFactoryA = null
describe 'initialize & configure', ->
it 'create new factory', ( done )->
mailFactoryA = new MailFactory( _Cnf.factoryA.appid, _Cnf.factoryA.config )
mailFactoryA.should.be.an.instanceOf MailFactory
done()
return
it 'change configuration with no content', ( done )->
_cnf = mailFactoryA.config()
_cnf.should.be.an.instanceOf Object
done()
return
it 'change configuration - wrong sendermail', ( done )->
_cnf = mailFactoryA.config( sendermail: "<EMAIL>" )
_cnf.should.have.property( "sendermail" ).with.be.a.String().and.equal "<EMAIL>"
done()
return
it 'change configuration - wrong sendermail', ( done )->
try
_cnf = mailFactoryA.config( sendermail: "wrongmail" )
catch _err
_err.name.should.equal( "validation-config-sendermail" )
done()
return
throw new Error( "wrong sendermail not thrown" )
return
it 'change configuration - multiple sendermails', ( done )->
try
_cnf = mailFactoryA.config( sendermail: [ "<EMAIL>", "<EMAIL>" ] )
catch _err
_err.name.should.equal( "validation-config-sendermail" )
done()
return
throw new Error( "wrong sendermail not thrown" )
return
it 'change configuration - endpoint', ( done )->
_cnf = mailFactoryA.config( endpoint: "http://nodetest.tcs.de/email/send" )
_cnf.should.have.property( "endpoint" ).with.be.a.String().and.equal "http://nodetest.tcs.de/email/send"
done()
return
it 'change configuration - wrong endpoint', ( done )->
try
_cnf = mailFactoryA.config( endpoint: "wrongurl" )
catch _err
_err.name.should.equal( "validation-config-endpoint" )
done()
return
throw new Error( "wrong endpoint not thrown" )
return
it 'change configuration - multiple endpoints', ( done )->
try
_cnf = mailFactoryA.config( endpoint: [ "http://node.tcs.de/email/send", "http://nodetest.tcs.de/email/send" ] )
catch _err
_err.name.should.equal( "validation-config-endpoint" )
done()
return
throw new Error( "wrong endpoint not thrown" )
return
it 'change configuration - security with ignored keys', ( done )->
_cnf = mailFactoryA.config( security: { b: "asdf", a: 123 } )
_cnf.should.have.property( "security" ).with.be.a.Object().and.eql {}
done()
return
it 'change configuration - security', ( done )->
_cnf = mailFactoryA.config( security: { apikey: "<KEY>", xxx: 1233 } )
_cnf.should.have.property( "security" ).with.be.a.Object().and.eql { apikey: "<KEY>" }
done()
return
it 'change configuration - wrong security', ( done )->
try
_cnf = mailFactoryA.config( security: "123" )
catch _err
_err.name.should.equal( "validation-config-security" )
done()
return
throw new Error( "wrong security not thrown" )
return
it 'change configuration - returnpath', ( done )->
_cnf = mailFactoryA.config( returnPath: "<EMAIL>" )
_cnf.should.have.property( "returnPath" ).with.be.a.String().and.equal "<EMAIL>"
done()
return
it 'change configuration - returnpath null', ( done )->
_cnf = mailFactoryA.config( returnPath: null )
done()
return
it 'change configuration - wrong returnpath', ( done )->
try
_cnf = mailFactoryA.config( returnPath: "wrongmail" )
catch _err
_err.name.should.equal( "validation-config-returnpath" )
done()
return
throw new Error( "wrong returnpath not thrown" )
return
it 'change configuration - multiple returnpaths', ( done )->
try
_cnf = mailFactoryA.config( returnPath: [ "<EMAIL>", "<EMAIL>" ] )
catch _err
_err.name.should.equal( "validation-config-returnpath" )
done()
return
throw new Error( "wrong returnpath not thrown" )
return
it 'change configuration - from', ( done )->
_cnf = mailFactoryA.config( from: "<EMAIL>" )
done()
return
it 'change configuration - wrong from', ( done )->
try
_cnf = mailFactoryA.config( from: "wrongmail" )
catch _err
_err.name.should.equal( "validation-config-from" )
done()
return
throw new Error( "wrong from not thrown" )
return
it 'change configuration - multiple froms', ( done )->
try
_cnf = mailFactoryA.config( from: [ "<EMAIL>", "<EMAIL>" ] )
catch _err
_err.name.should.equal( "validation-config-from" )
done()
return
throw new Error( "wrong from not thrown" )
return
it 'change configuration - reply', ( done )->
_cnf = mailFactoryA.config( reply: "<EMAIL>" )
_cnf.should.have.property( "reply" ).with.be.a.String().and.equal "<EMAIL>"
done()
return
it 'change configuration - wrong reply', ( done )->
try
_cnf = mailFactoryA.config( reply: "wrongmail" )
catch _err
_err.name.should.equal( "validation-config-reply" )
done()
return
throw new Error( "wrong reply not thrown" )
return
it 'change configuration - multiple replys', ( done )->
_cnf = mailFactoryA.config( reply: [ "<EMAIL>", "<EMAIL>" ] )
_cnf.should.have.property( "reply" ).with.be.an.instanceOf( Array ).and.have.length( 2 )
done()
return
it 'change configuration - multiple replys + one wrong', ( done )->
try
_cnf = mailFactoryA.config( reply: [ "<EMAIL>", "wrongmail" ] )
throw new Error( "wrong reply not thrown" )
catch _err
_err.name.should.equal( "validation-config-reply" )
done()
return
return
describe 'factory methods', ->
mails = []
it 'create a mail', ( done )->
mail = mailFactoryA.create()
mails.push( mail )
mail.should.be.instanceOf Mail
mails[ 0 ].should.eql( mail )
done()
return
it 'get a mail', ( done )->
mail = mailFactoryA.get( mails[ 0 ].id )
mail.should.be.instanceOf Mail
mails[ 0 ].should.eql( mail )
done()
return
it 'destroy a mail', ( done )->
mail = mailFactoryA.get( mails[ 0 ].id )
mail.destroy()
mail = mailFactoryA.get( mails[ 0 ].id )
should.not.exist( mail )
mails = []
done()
return
it 'add 4 mails', ( done )->
for i in [0..3]
mails.push mailFactoryA.create().subject( "TEST #{i}" ).text( "CONTENT #{i}" ).to( "<EMAIL>" )
mailFactoryA.count().should.equal mails.length
done()
return
it 'send all mails', ( done )->
mailFactoryA.sendAll ( err )->
should.not.exist( err )
mailFactoryA.count().should.equal 0
mails = []
done()
return
return
return
describe 'mail methods', ->
mails = []
mailA = null
it 'create a test mail', ( done )->
mailA = mailFactoryA.create()
mails.push( mailA )
mailA.should.be.instanceOf Mail
mails[ 0 ].should.eql( mailA )
done()
return
it 'set to - single', ( done )->
_to = mailA.to( "<EMAIL>" ).to()
_to.should.be.a.String().and.equal "<EMAIL>"
done()
return
it 'set to - reset', ( done )->
_to = mailA.to( false ).to()
should.not.exist( _to )
done()
return
it 'set to - multiple', ( done )->
_to = mailA.to( [ "<EMAIL>", "<EMAIL>", "<EMAIL>" ] ).to()
_to.should.be.an.Array().and.have.length( 3 )
done()
return
it 'set to - single wrong', ( done )->
try
_to = mailA.to( "testAtcs.de" )
catch _err
_err.name.should.equal( "validation-mail-to" )
done()
return
throw new Error( "wrong to - single not thrown" )
return
it 'set to - multiple wrong', ( done )->
try
_to = mailA.to( [ "<EMAIL>", "<EMAIL>", "<EMAIL>" ] )
catch _err
_err.name.should.equal( "validation-mail-to" )
done()
return
throw new Error( "wrong to - multiple not thrown" )
return
it 'set cc - single', ( done )->
_cc = mailA.cc( "<EMAIL>" ).cc()
_cc.should.be.a.String().and.equal "<EMAIL>"
done()
return
it 'set cc - multiple', ( done )->
_cc = mailA.cc( [ "<EMAIL>", "<EMAIL>", "<EMAIL>" ] ).cc()
_cc.should.be.an.Array().and.have.length( 3 )
done()
return
it 'set cc - single wrong', ( done )->
try
_cc = mailA.cc( "testAtcs.de" )
catch _err
_err.name.should.equal( "validation-mail-cc" )
done()
return
throw new Error( "wrong cc - single not thrown" )
return
it 'set cc - multiple wrong', ( done )->
try
_cc = mailA.cc( [ "<EMAIL>", "testBtcs.de", "<EMAIL>" ] )
catch _err
_err.name.should.equal( "validation-mail-cc" )
done()
return
throw new Error( "wrong cc - multiple not thrown" )
return
it 'set cc - reset', ( done )->
_cc = mailA.cc( false ).cc()
should.not.exist( _cc )
done()
return
it 'set bcc - single', ( done )->
_bcc = mailA.bcc( "<EMAIL>" ).bcc()
_bcc.should.be.a.String().and.equal "<EMAIL>"
done()
return
it 'set bcc - multiple', ( done )->
_bcc = mailA.bcc( [ "<EMAIL>", "<EMAIL>", "<EMAIL>" ] ).bcc()
_bcc.should.be.an.Array().and.have.length( 3 )
done()
return
it 'set bcc - single wrong', ( done )->
try
_bcc = mailA.bcc( "testAtcs.de" )
catch _err
_err.name.should.equal( "validation-mail-bcc" )
done()
return
throw new Error( "wrong bcc - single not thrown" )
return
it 'set bcc - multiple wrong', ( done )->
try
_bcc = mailA.bcc( [ "<EMAIL>", "testBtcs.de", "<EMAIL>" ] )
catch _err
_err.name.should.equal( "validation-mail-bcc" )
done()
return
throw new Error( "wrong bcc - multiple not thrown" )
return
it 'set bcc - reset', ( done )->
_bcc = mailA.bcc( false ).bcc()
should.not.exist( _bcc )
done()
return
it 'set subject', ( done )->
_subject = mailA.subject( "Test Subject" ).subject()
_subject.should.be.a.String().and.equal "Test Subject"
done()
return
it 'set subject - long', ( done )->
_val = randomString( 150, 2, .2, .05 )
_subject = mailA.subject( _val ).subject()
_subject.should.be.a.String().and.equal _val
done()
return
it 'set subject - html', ( done )->
_val = "<b>This is my html string</b>"
_subject = mailA.subject( _val ).subject()
_subject.should.be.a.String().and.equal _val
done()
return
it 'set subject - reset', ( done )->
try
mailA.subject( false )
catch _err
_err.name.should.equal( "validation-mail-subject" )
_val = "<b>This is my html string</b>"
_subject = mailA.subject()
_subject.should.be.a.String().and.equal _val
done()
return
throw new Error( "wrong subject - reset not thrown" )
return
it 'set subject - wrong type', ( done )->
_val = [ "my array subject" ]
try
mailA.subject( _val )
catch _err
_err.name.should.equal( "validation-mail-subject" )
done()
return
throw new Error( "wrong subject - type not thrown" )
return
it 'set text', ( done )->
_val = randomString( 150, 2, .2, .05 )
_text = mailA.text( _val ).text()
_text.should.be.a.String().and.equal _val
done()
return
it 'set text - html', ( done )->
_val = "<b>My HTML subject</b>"
_text = mailA.text( _val ).text()
_text.should.be.a.String().and.equal _val
done()
return
it 'set text - reset', ( done )->
_val = false
_text = mailA.text( _val ).text()
should.not.exist( _text )
done()
return
it 'set text - long', ( done )->
_val = randomString( 1000, 2, .2, .05 )
_text = mailA.text( _val ).text()
_text.should.be.a.String().and.equal _val
done()
return
it 'set text - wrong type', ( done )->
_val = [ "my array text" ]
try
mailA.text( _val )
catch _err
_err.name.should.equal( "validation-mail-text" )
done()
return
throw new Error( "wrong text - type not thrown" )
return
it 'set html', ( done )->
_val = randomString( 150, 2, .2, .05 )
_html = mailA.html( _val ).html()
_html.should.be.a.String().and.equal _val
done()
return
it 'set html - html from file', ( done )->
fs.readFile './test/data/html_example.html', ( err, file )->
if err
throw err
return
_val = file.toString( "utf-8" )
_html = mailA.html( _val ).html()
_html.should.be.a.String().and.equal _val
done()
return
return
it 'set html - reset', ( done )->
_val = false
_html = mailA.html( _val ).html()
should.not.exist( _html )
done()
return
it 'set html - wrong type', ( done )->
_val = [ "my array html" ]
try
mailA.html( _val )
catch _err
_err.name.should.equal( "validation-mail-html" )
done()
return
throw new Error( "wrong html - type not thrown" )
return
it 'set reply - single', ( done )->
_reply = mailA.reply( "<EMAIL>" ).reply()
_reply.should.be.a.String().and.equal "<EMAIL>"
done()
return
it 'set reply - reset', ( done )->
_reply = mailA.reply( false ).reply()
should.not.exist( _reply )
done()
return
it 'set reply - multiple', ( done )->
_reply = mailA.reply( [ "<EMAIL>", "<EMAIL>", "<EMAIL>" ] ).reply()
_reply.should.be.an.Array().and.have.length( 3 )
done()
return
it 'set reply - single wrong', ( done )->
try
_reply = mailA.reply( "testAtcs.de" )
throw new Error( "wrong reply - single not thrown" )
catch _err
_err.name.should.equal( "validation-mail-reply" )
done()
return
it 'set reply - multiple wrong', ( done )->
try
_reply = mailA.reply( [ "<EMAIL>", "<EMAIL>", "<EMAIL>" ] )
catch _err
_err.name.should.equal( "validation-mail-reply" )
done()
return
throw new Error( "wrong reply - multiple not thrown" )
return
it 'set returnPath - single', ( done )->
_returnPath = mailA.returnPath( "<EMAIL>" ).returnPath()
_returnPath.should.be.a.String().and.equal "<EMAIL>"
done()
return
it 'set returnPath - reset', ( done )->
_returnPath = mailA.returnPath( false ).returnPath()
should.not.exist( _returnPath )
done()
return
it 'set returnPath - multiple', ( done )->
try
_returnPath = mailA.returnPath( [ "<EMAIL>", "<EMAIL>", "<EMAIL>" ] )
catch _err
_err.name.should.equal( "validation-mail-returnpath" )
done()
return
throw new Error( "wrong returnPath - multiple not thrown" )
return
it 'set returnPath - single wrong', ( done )->
try
_returnPath = mailA.returnPath( "testAtcs.de" )
catch _err
_err.name.should.equal( "validation-mail-returnpath" )
done()
return
throw new Error( "wrong returnPath - single not thrown" )
return
it 'send this mail', ( done )->
mailA.send ( err )->
if err
throw err
return
done()
return
return
return
describe 'mail send tests', ->
mailFactoryB = null
it 'create new factory', ( done )->
mailFactoryB = new MailFactory( _Cnf.factoryB.appid, _Cnf.factoryB.config )
mailFactoryB.should.be.an.instanceOf MailFactory
done()
return
it 'create and send mail - simple', ( done )->
_mail = mailFactoryB.create().subject( "Simple Test" ).text( "TEST" ).to( _Cnf.realReceiver )
_mail.send ( err, result )->
should.not.exist( err )
result.should.have.property( "recipients" ).with.be.an.Array().and.containEql( _Cnf.realReceiver )
done()
return
return
it 'create and send mail - missing subject', ( done )->
mailFactoryB.create().to( "<EMAIL>" ).send ( err )->
should.exist( err )
err.should.have.property( "name" ).with.be.a.String().and.equal "validation-mail-subject-missing"
done()
return
return
it 'create and send mail - missing receiver', ( done )->
mailFactoryB.create().subject( "no receiver" ).send ( err )->
should.exist( err )
err.should.have.property( "name" ).with.be.a.String().and.equal "validation-mail-receiver-missing"
done()
return
return
it 'create and send mail - missing content', ( done )->
mailFactoryB.create().subject( "missing content" ).bcc( _Cnf.realReceiver ).send ( err, result )->
should.exist( err )
err.should.have.property( "name" ).with.be.a.String().and.equal "validation-mail-content-missing"
done()
return
return
it 'create and send mail - with html content', ( done )->
mailFactoryB.create().subject( "HTML TEST" ).html( "<html><header><style>h1{color:#f00;}</style></header><body><h1 class=\"test\">Simple html content</h1><p>Test the sending of mails</p></html></body>" ).to( _Cnf.realReceiver ).send ( err, result )->
should.not.exist( err )
result.should.have.property( "recipients" ).with.be.an.Array().and.containEql( _Cnf.realReceiver )
done()
return
return
it 'create and send mail - with large html content', ( done )->
fs.readFile './test/data/html_example.html', ( err, file )->
if err
throw err
return
_val = file.toString( "utf-8" )
mailFactoryB.create().subject( "TCS E-Mail Node Client" ).html( _val ).to( _Cnf.realReceiver ).bcc( _Cnf.realCcReceiver ).send ( err, result )->
should.not.exist( err )
result.should.have.property( "recipients" ).with.be.an.Array().and.containEql( _Cnf.realReceiver )
done()
return
return
return
return
return
| true | fs = require("fs")
should = require('should')
MailFactory = require("../lib/index")
Mail = require("../lib/index").mail
try
_factoryB = require( "../test_config_factoryB.js" )
console.info "Using config for FactoryB of file `test_config_factoryB.js"
catch _err
_factoryB =
appid: "wmshop"
config:
endpoint: "http://localhost:3000/email/send"
simulate: true
_Cnf =
realReceiver: "PI:EMAIL:<EMAIL>END_PI"
realCcReceiver: "PI:EMAIL:<EMAIL>END_PI"
realBccReceiver: "PI:EMAIL:<EMAIL>END_PI"
factoryA:
appid: "wmshop"
config:
simulate: true
factoryB: _factoryB
randRange = ( lowVal, highVal )->
Math.floor( Math.random()*(highVal-lowVal+1 ))+lowVal
randomString = ( string_length = 5, specialLevel = 0, spaces = .1, breaks = 0 ) ->
chars = "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"
chars += "0123456789" if specialLevel >= 1
chars += "_-@:." if specialLevel >= 2
chars += "!\"§$%&/()=?*'_:;,.-#+¬”#£fi^\\˜·¯˙˚«∑€®†Ω¨⁄øπ•‘æœ@∆ºª©ƒ∂‚å–…∞µ~∫√ç≈¥" if specialLevel >= 3
randomstring = ""
i = 0
while i < string_length
rnum = Math.floor(Math.random() * chars.length)
if spaces > 0 and ( randRange( 0, 100 ) < ( 100 * spaces ) )
randomstring += " "
else if breaks > 0 and ( randRange( 0, 100 ) < ( 100 * breaks ) )
randomstring += "\n"
else
randomstring += chars.substring(rnum, rnum + 1)
i++
randomstring
randomstring
describe 'MAIL-FACTORY-TEST', ->
before ( done )->
done()
return
after ( done )->
done()
return
mailFactoryA = null
describe 'initialize & configure', ->
it 'create new factory', ( done )->
mailFactoryA = new MailFactory( _Cnf.factoryA.appid, _Cnf.factoryA.config )
mailFactoryA.should.be.an.instanceOf MailFactory
done()
return
it 'change configuration with no content', ( done )->
_cnf = mailFactoryA.config()
_cnf.should.be.an.instanceOf Object
done()
return
it 'change configuration - wrong sendermail', ( done )->
_cnf = mailFactoryA.config( sendermail: "PI:EMAIL:<EMAIL>END_PI" )
_cnf.should.have.property( "sendermail" ).with.be.a.String().and.equal "PI:EMAIL:<EMAIL>END_PI"
done()
return
it 'change configuration - wrong sendermail', ( done )->
try
_cnf = mailFactoryA.config( sendermail: "wrongmail" )
catch _err
_err.name.should.equal( "validation-config-sendermail" )
done()
return
throw new Error( "wrong sendermail not thrown" )
return
it 'change configuration - multiple sendermails', ( done )->
try
_cnf = mailFactoryA.config( sendermail: [ "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI" ] )
catch _err
_err.name.should.equal( "validation-config-sendermail" )
done()
return
throw new Error( "wrong sendermail not thrown" )
return
it 'change configuration - endpoint', ( done )->
_cnf = mailFactoryA.config( endpoint: "http://nodetest.tcs.de/email/send" )
_cnf.should.have.property( "endpoint" ).with.be.a.String().and.equal "http://nodetest.tcs.de/email/send"
done()
return
it 'change configuration - wrong endpoint', ( done )->
try
_cnf = mailFactoryA.config( endpoint: "wrongurl" )
catch _err
_err.name.should.equal( "validation-config-endpoint" )
done()
return
throw new Error( "wrong endpoint not thrown" )
return
it 'change configuration - multiple endpoints', ( done )->
try
_cnf = mailFactoryA.config( endpoint: [ "http://node.tcs.de/email/send", "http://nodetest.tcs.de/email/send" ] )
catch _err
_err.name.should.equal( "validation-config-endpoint" )
done()
return
throw new Error( "wrong endpoint not thrown" )
return
it 'change configuration - security with ignored keys', ( done )->
_cnf = mailFactoryA.config( security: { b: "asdf", a: 123 } )
_cnf.should.have.property( "security" ).with.be.a.Object().and.eql {}
done()
return
it 'change configuration - security', ( done )->
_cnf = mailFactoryA.config( security: { apikey: "PI:KEY:<KEY>END_PI", xxx: 1233 } )
_cnf.should.have.property( "security" ).with.be.a.Object().and.eql { apikey: "PI:KEY:<KEY>END_PI" }
done()
return
it 'change configuration - wrong security', ( done )->
try
_cnf = mailFactoryA.config( security: "123" )
catch _err
_err.name.should.equal( "validation-config-security" )
done()
return
throw new Error( "wrong security not thrown" )
return
it 'change configuration - returnpath', ( done )->
_cnf = mailFactoryA.config( returnPath: "PI:EMAIL:<EMAIL>END_PI" )
_cnf.should.have.property( "returnPath" ).with.be.a.String().and.equal "PI:EMAIL:<EMAIL>END_PI"
done()
return
it 'change configuration - returnpath null', ( done )->
_cnf = mailFactoryA.config( returnPath: null )
done()
return
it 'change configuration - wrong returnpath', ( done )->
try
_cnf = mailFactoryA.config( returnPath: "wrongmail" )
catch _err
_err.name.should.equal( "validation-config-returnpath" )
done()
return
throw new Error( "wrong returnpath not thrown" )
return
it 'change configuration - multiple returnpaths', ( done )->
try
_cnf = mailFactoryA.config( returnPath: [ "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI" ] )
catch _err
_err.name.should.equal( "validation-config-returnpath" )
done()
return
throw new Error( "wrong returnpath not thrown" )
return
it 'change configuration - from', ( done )->
_cnf = mailFactoryA.config( from: "PI:EMAIL:<EMAIL>END_PI" )
done()
return
it 'change configuration - wrong from', ( done )->
try
_cnf = mailFactoryA.config( from: "wrongmail" )
catch _err
_err.name.should.equal( "validation-config-from" )
done()
return
throw new Error( "wrong from not thrown" )
return
it 'change configuration - multiple froms', ( done )->
try
_cnf = mailFactoryA.config( from: [ "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI" ] )
catch _err
_err.name.should.equal( "validation-config-from" )
done()
return
throw new Error( "wrong from not thrown" )
return
it 'change configuration - reply', ( done )->
_cnf = mailFactoryA.config( reply: "PI:EMAIL:<EMAIL>END_PI" )
_cnf.should.have.property( "reply" ).with.be.a.String().and.equal "PI:EMAIL:<EMAIL>END_PI"
done()
return
it 'change configuration - wrong reply', ( done )->
try
_cnf = mailFactoryA.config( reply: "wrongmail" )
catch _err
_err.name.should.equal( "validation-config-reply" )
done()
return
throw new Error( "wrong reply not thrown" )
return
it 'change configuration - multiple replys', ( done )->
_cnf = mailFactoryA.config( reply: [ "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI" ] )
_cnf.should.have.property( "reply" ).with.be.an.instanceOf( Array ).and.have.length( 2 )
done()
return
it 'change configuration - multiple replys + one wrong', ( done )->
try
_cnf = mailFactoryA.config( reply: [ "PI:EMAIL:<EMAIL>END_PI", "wrongmail" ] )
throw new Error( "wrong reply not thrown" )
catch _err
_err.name.should.equal( "validation-config-reply" )
done()
return
return
describe 'factory methods', ->
mails = []
it 'create a mail', ( done )->
mail = mailFactoryA.create()
mails.push( mail )
mail.should.be.instanceOf Mail
mails[ 0 ].should.eql( mail )
done()
return
it 'get a mail', ( done )->
mail = mailFactoryA.get( mails[ 0 ].id )
mail.should.be.instanceOf Mail
mails[ 0 ].should.eql( mail )
done()
return
it 'destroy a mail', ( done )->
mail = mailFactoryA.get( mails[ 0 ].id )
mail.destroy()
mail = mailFactoryA.get( mails[ 0 ].id )
should.not.exist( mail )
mails = []
done()
return
it 'add 4 mails', ( done )->
for i in [0..3]
mails.push mailFactoryA.create().subject( "TEST #{i}" ).text( "CONTENT #{i}" ).to( "PI:EMAIL:<EMAIL>END_PI" )
mailFactoryA.count().should.equal mails.length
done()
return
it 'send all mails', ( done )->
mailFactoryA.sendAll ( err )->
should.not.exist( err )
mailFactoryA.count().should.equal 0
mails = []
done()
return
return
return
describe 'mail methods', ->
mails = []
mailA = null
it 'create a test mail', ( done )->
mailA = mailFactoryA.create()
mails.push( mailA )
mailA.should.be.instanceOf Mail
mails[ 0 ].should.eql( mailA )
done()
return
it 'set to - single', ( done )->
_to = mailA.to( "PI:EMAIL:<EMAIL>END_PI" ).to()
_to.should.be.a.String().and.equal "PI:EMAIL:<EMAIL>END_PI"
done()
return
it 'set to - reset', ( done )->
_to = mailA.to( false ).to()
should.not.exist( _to )
done()
return
it 'set to - multiple', ( done )->
_to = mailA.to( [ "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI" ] ).to()
_to.should.be.an.Array().and.have.length( 3 )
done()
return
it 'set to - single wrong', ( done )->
try
_to = mailA.to( "testAtcs.de" )
catch _err
_err.name.should.equal( "validation-mail-to" )
done()
return
throw new Error( "wrong to - single not thrown" )
return
it 'set to - multiple wrong', ( done )->
try
_to = mailA.to( [ "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI" ] )
catch _err
_err.name.should.equal( "validation-mail-to" )
done()
return
throw new Error( "wrong to - multiple not thrown" )
return
it 'set cc - single', ( done )->
_cc = mailA.cc( "PI:EMAIL:<EMAIL>END_PI" ).cc()
_cc.should.be.a.String().and.equal "PI:EMAIL:<EMAIL>END_PI"
done()
return
it 'set cc - multiple', ( done )->
_cc = mailA.cc( [ "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI" ] ).cc()
_cc.should.be.an.Array().and.have.length( 3 )
done()
return
it 'set cc - single wrong', ( done )->
try
_cc = mailA.cc( "testAtcs.de" )
catch _err
_err.name.should.equal( "validation-mail-cc" )
done()
return
throw new Error( "wrong cc - single not thrown" )
return
it 'set cc - multiple wrong', ( done )->
try
_cc = mailA.cc( [ "PI:EMAIL:<EMAIL>END_PI", "testBtcs.de", "PI:EMAIL:<EMAIL>END_PI" ] )
catch _err
_err.name.should.equal( "validation-mail-cc" )
done()
return
throw new Error( "wrong cc - multiple not thrown" )
return
it 'set cc - reset', ( done )->
_cc = mailA.cc( false ).cc()
should.not.exist( _cc )
done()
return
it 'set bcc - single', ( done )->
_bcc = mailA.bcc( "PI:EMAIL:<EMAIL>END_PI" ).bcc()
_bcc.should.be.a.String().and.equal "PI:EMAIL:<EMAIL>END_PI"
done()
return
it 'set bcc - multiple', ( done )->
_bcc = mailA.bcc( [ "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI" ] ).bcc()
_bcc.should.be.an.Array().and.have.length( 3 )
done()
return
it 'set bcc - single wrong', ( done )->
try
_bcc = mailA.bcc( "testAtcs.de" )
catch _err
_err.name.should.equal( "validation-mail-bcc" )
done()
return
throw new Error( "wrong bcc - single not thrown" )
return
it 'set bcc - multiple wrong', ( done )->
try
_bcc = mailA.bcc( [ "PI:EMAIL:<EMAIL>END_PI", "testBtcs.de", "PI:EMAIL:<EMAIL>END_PI" ] )
catch _err
_err.name.should.equal( "validation-mail-bcc" )
done()
return
throw new Error( "wrong bcc - multiple not thrown" )
return
it 'set bcc - reset', ( done )->
_bcc = mailA.bcc( false ).bcc()
should.not.exist( _bcc )
done()
return
it 'set subject', ( done )->
_subject = mailA.subject( "Test Subject" ).subject()
_subject.should.be.a.String().and.equal "Test Subject"
done()
return
it 'set subject - long', ( done )->
_val = randomString( 150, 2, .2, .05 )
_subject = mailA.subject( _val ).subject()
_subject.should.be.a.String().and.equal _val
done()
return
it 'set subject - html', ( done )->
_val = "<b>This is my html string</b>"
_subject = mailA.subject( _val ).subject()
_subject.should.be.a.String().and.equal _val
done()
return
it 'set subject - reset', ( done )->
try
mailA.subject( false )
catch _err
_err.name.should.equal( "validation-mail-subject" )
_val = "<b>This is my html string</b>"
_subject = mailA.subject()
_subject.should.be.a.String().and.equal _val
done()
return
throw new Error( "wrong subject - reset not thrown" )
return
it 'set subject - wrong type', ( done )->
_val = [ "my array subject" ]
try
mailA.subject( _val )
catch _err
_err.name.should.equal( "validation-mail-subject" )
done()
return
throw new Error( "wrong subject - type not thrown" )
return
it 'set text', ( done )->
_val = randomString( 150, 2, .2, .05 )
_text = mailA.text( _val ).text()
_text.should.be.a.String().and.equal _val
done()
return
it 'set text - html', ( done )->
_val = "<b>My HTML subject</b>"
_text = mailA.text( _val ).text()
_text.should.be.a.String().and.equal _val
done()
return
it 'set text - reset', ( done )->
_val = false
_text = mailA.text( _val ).text()
should.not.exist( _text )
done()
return
it 'set text - long', ( done )->
_val = randomString( 1000, 2, .2, .05 )
_text = mailA.text( _val ).text()
_text.should.be.a.String().and.equal _val
done()
return
it 'set text - wrong type', ( done )->
_val = [ "my array text" ]
try
mailA.text( _val )
catch _err
_err.name.should.equal( "validation-mail-text" )
done()
return
throw new Error( "wrong text - type not thrown" )
return
it 'set html', ( done )->
_val = randomString( 150, 2, .2, .05 )
_html = mailA.html( _val ).html()
_html.should.be.a.String().and.equal _val
done()
return
it 'set html - html from file', ( done )->
fs.readFile './test/data/html_example.html', ( err, file )->
if err
throw err
return
_val = file.toString( "utf-8" )
_html = mailA.html( _val ).html()
_html.should.be.a.String().and.equal _val
done()
return
return
it 'set html - reset', ( done )->
_val = false
_html = mailA.html( _val ).html()
should.not.exist( _html )
done()
return
it 'set html - wrong type', ( done )->
_val = [ "my array html" ]
try
mailA.html( _val )
catch _err
_err.name.should.equal( "validation-mail-html" )
done()
return
throw new Error( "wrong html - type not thrown" )
return
it 'set reply - single', ( done )->
_reply = mailA.reply( "PI:EMAIL:<EMAIL>END_PI" ).reply()
_reply.should.be.a.String().and.equal "PI:EMAIL:<EMAIL>END_PI"
done()
return
it 'set reply - reset', ( done )->
_reply = mailA.reply( false ).reply()
should.not.exist( _reply )
done()
return
it 'set reply - multiple', ( done )->
_reply = mailA.reply( [ "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI" ] ).reply()
_reply.should.be.an.Array().and.have.length( 3 )
done()
return
it 'set reply - single wrong', ( done )->
try
_reply = mailA.reply( "testAtcs.de" )
throw new Error( "wrong reply - single not thrown" )
catch _err
_err.name.should.equal( "validation-mail-reply" )
done()
return
it 'set reply - multiple wrong', ( done )->
try
_reply = mailA.reply( [ "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI" ] )
catch _err
_err.name.should.equal( "validation-mail-reply" )
done()
return
throw new Error( "wrong reply - multiple not thrown" )
return
it 'set returnPath - single', ( done )->
_returnPath = mailA.returnPath( "PI:EMAIL:<EMAIL>END_PI" ).returnPath()
_returnPath.should.be.a.String().and.equal "PI:EMAIL:<EMAIL>END_PI"
done()
return
it 'set returnPath - reset', ( done )->
_returnPath = mailA.returnPath( false ).returnPath()
should.not.exist( _returnPath )
done()
return
it 'set returnPath - multiple', ( done )->
try
_returnPath = mailA.returnPath( [ "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI" ] )
catch _err
_err.name.should.equal( "validation-mail-returnpath" )
done()
return
throw new Error( "wrong returnPath - multiple not thrown" )
return
it 'set returnPath - single wrong', ( done )->
try
_returnPath = mailA.returnPath( "testAtcs.de" )
catch _err
_err.name.should.equal( "validation-mail-returnpath" )
done()
return
throw new Error( "wrong returnPath - single not thrown" )
return
it 'send this mail', ( done )->
mailA.send ( err )->
if err
throw err
return
done()
return
return
return
describe 'mail send tests', ->
mailFactoryB = null
it 'create new factory', ( done )->
mailFactoryB = new MailFactory( _Cnf.factoryB.appid, _Cnf.factoryB.config )
mailFactoryB.should.be.an.instanceOf MailFactory
done()
return
it 'create and send mail - simple', ( done )->
_mail = mailFactoryB.create().subject( "Simple Test" ).text( "TEST" ).to( _Cnf.realReceiver )
_mail.send ( err, result )->
should.not.exist( err )
result.should.have.property( "recipients" ).with.be.an.Array().and.containEql( _Cnf.realReceiver )
done()
return
return
it 'create and send mail - missing subject', ( done )->
mailFactoryB.create().to( "PI:EMAIL:<EMAIL>END_PI" ).send ( err )->
should.exist( err )
err.should.have.property( "name" ).with.be.a.String().and.equal "validation-mail-subject-missing"
done()
return
return
it 'create and send mail - missing receiver', ( done )->
mailFactoryB.create().subject( "no receiver" ).send ( err )->
should.exist( err )
err.should.have.property( "name" ).with.be.a.String().and.equal "validation-mail-receiver-missing"
done()
return
return
it 'create and send mail - missing content', ( done )->
mailFactoryB.create().subject( "missing content" ).bcc( _Cnf.realReceiver ).send ( err, result )->
should.exist( err )
err.should.have.property( "name" ).with.be.a.String().and.equal "validation-mail-content-missing"
done()
return
return
it 'create and send mail - with html content', ( done )->
mailFactoryB.create().subject( "HTML TEST" ).html( "<html><header><style>h1{color:#f00;}</style></header><body><h1 class=\"test\">Simple html content</h1><p>Test the sending of mails</p></html></body>" ).to( _Cnf.realReceiver ).send ( err, result )->
should.not.exist( err )
result.should.have.property( "recipients" ).with.be.an.Array().and.containEql( _Cnf.realReceiver )
done()
return
return
it 'create and send mail - with large html content', ( done )->
fs.readFile './test/data/html_example.html', ( err, file )->
if err
throw err
return
_val = file.toString( "utf-8" )
mailFactoryB.create().subject( "TCS E-Mail Node Client" ).html( _val ).to( _Cnf.realReceiver ).bcc( _Cnf.realCcReceiver ).send ( err, result )->
should.not.exist( err )
result.should.have.property( "recipients" ).with.be.an.Array().and.containEql( _Cnf.realReceiver )
done()
return
return
return
return
return
|
[
{
"context": " {String} accountId The account to access, e.g. '555666777888'.\n@param {String} instanceType The inst",
"end": 385,
"score": 0.5898927450180054,
"start": 384,
"tag": "KEY",
"value": "5"
},
{
"context": "accountId The account to access, e.g. '555666777888'.\n@param {Str... | src/actions/assumeRole.coffee | nerdfiles/was | 0 | ###
@fileOverview ./src/actions/assumeRole.coffee
###
# Core.
import { util } from 'util'
# NPM.
import { AWS } from 'aws-sdk'
# Infrastructure.
import { Action } from 'mover'
# Actions.
import { DescribeInstances } from './describeInstances'
###
Obtain the running instance count for a particular type from another account.
@param {String} accountId The account to access, e.g. '555666777888'.
@param {String} instanceType The instance type, e.g. 't2.medium'.
@param {Function} callback Of the form function (error, count).
###
class ObtainInstanceCount extends Action
constructor: (accountId, instanceType, callback) ->
# This client uses the default configuration read from the environment or
# instance metadata.
@stsClient = new AWS.STS()
@defaultRoleConfig =
RoleSessionName : 'instance-counter'
DurationSeconds : 3600
RoleArn : util.format(
'arn:aws:iam::%s:role/CrossAccountInstanceCounter',
accountId
),
assume: (roleConfig={}) ->
loadedRoleConfig = roleConfig || @defaultRoleConfig
@stsClient.assumeRole(
loadedRoleConfig,
assumedRole
)
assumedRole = (error, response) ->
if error
return callback(error)
ec2Client = new AWS.EC2
accessKeyId : response.Credentials.AccessKeyId
secretAccessKey : response.Credentials.SecretAccessKey
sessionToken : response.Credentials.SessionToken
DescribeInstances(ec2Client, instanceType, callback)
export default ObtainInstanceCount
| 179766 | ###
@fileOverview ./src/actions/assumeRole.coffee
###
# Core.
import { util } from 'util'
# NPM.
import { AWS } from 'aws-sdk'
# Infrastructure.
import { Action } from 'mover'
# Actions.
import { DescribeInstances } from './describeInstances'
###
Obtain the running instance count for a particular type from another account.
@param {String} accountId The account to access, e.g. '5<KEY>566677788<KEY>'.
@param {String} instanceType The instance type, e.g. 't2.medium'.
@param {Function} callback Of the form function (error, count).
###
class ObtainInstanceCount extends Action
constructor: (accountId, instanceType, callback) ->
# This client uses the default configuration read from the environment or
# instance metadata.
@stsClient = new AWS.STS()
@defaultRoleConfig =
RoleSessionName : 'instance-counter'
DurationSeconds : 3600
RoleArn : util.format(
'arn:aws:iam::%s:role/CrossAccountInstanceCounter',
accountId
),
assume: (roleConfig={}) ->
loadedRoleConfig = roleConfig || @defaultRoleConfig
@stsClient.assumeRole(
loadedRoleConfig,
assumedRole
)
assumedRole = (error, response) ->
if error
return callback(error)
ec2Client = new AWS.EC2
accessKeyId : response.Credentials.AccessKeyId
secretAccessKey : response.Credentials.SecretAccessKey
sessionToken : response.Credentials.SessionToken
DescribeInstances(ec2Client, instanceType, callback)
export default ObtainInstanceCount
| true | ###
@fileOverview ./src/actions/assumeRole.coffee
###
# Core.
import { util } from 'util'
# NPM.
import { AWS } from 'aws-sdk'
# Infrastructure.
import { Action } from 'mover'
# Actions.
import { DescribeInstances } from './describeInstances'
###
Obtain the running instance count for a particular type from another account.
@param {String} accountId The account to access, e.g. '5PI:KEY:<KEY>END_PI566677788PI:KEY:<KEY>END_PI'.
@param {String} instanceType The instance type, e.g. 't2.medium'.
@param {Function} callback Of the form function (error, count).
###
class ObtainInstanceCount extends Action
constructor: (accountId, instanceType, callback) ->
# This client uses the default configuration read from the environment or
# instance metadata.
@stsClient = new AWS.STS()
@defaultRoleConfig =
RoleSessionName : 'instance-counter'
DurationSeconds : 3600
RoleArn : util.format(
'arn:aws:iam::%s:role/CrossAccountInstanceCounter',
accountId
),
assume: (roleConfig={}) ->
loadedRoleConfig = roleConfig || @defaultRoleConfig
@stsClient.assumeRole(
loadedRoleConfig,
assumedRole
)
assumedRole = (error, response) ->
if error
return callback(error)
ec2Client = new AWS.EC2
accessKeyId : response.Credentials.AccessKeyId
secretAccessKey : response.Credentials.SecretAccessKey
sessionToken : response.Credentials.SessionToken
DescribeInstances(ec2Client, instanceType, callback)
export default ObtainInstanceCount
|
[
{
"context": "# author : jelly, hunJ, myounghoPak\n# Dependency:\n# - cron\n# De",
"end": 16,
"score": 0.9401814937591553,
"start": 11,
"tag": "USERNAME",
"value": "jelly"
},
{
"context": "# author : jelly, hunJ, myounghoPak\n# Dependency:\n# - cron\n# Descr",
"end": 19,
... | scripts/tenten.coffee | kyunooh/bibly-bot | 0 | # author : jelly, hunJ, myounghoPak
# Dependency:
# - cron
# Description:
# 한국시간 (KST) 기준 23시가 되면 #_general 에 #darknight 로 이동하러는 메세지를 출력한다.
# 07시가 되면 #darknight 에 #_general 로 이동하라는 메세지를 출력한다.
cronJob = require('cron').CronJob
module.exports = (robot) ->
# darknightJob = new cronJob('0 0 23 * * *', wakeUpDarknight(robot), null, true, "Asia/Seoul")
tentenJob = new cronJob('0 10 10 * * *', tenten(robot), null, true, "Asia/Seoul")
tenten = (robot) ->
-> robot.messageRoom '#ten-ten', '텐텐십십쥬쥬열열1010tenten'
| 208878 | # author : jelly, <NAME>unJ, myounghoPak
# Dependency:
# - cron
# Description:
# 한국시간 (KST) 기준 23시가 되면 #_general 에 #darknight 로 이동하러는 메세지를 출력한다.
# 07시가 되면 #darknight 에 #_general 로 이동하라는 메세지를 출력한다.
cronJob = require('cron').CronJob
module.exports = (robot) ->
# darknightJob = new cronJob('0 0 23 * * *', wakeUpDarknight(robot), null, true, "Asia/Seoul")
tentenJob = new cronJob('0 10 10 * * *', tenten(robot), null, true, "Asia/Seoul")
tenten = (robot) ->
-> robot.messageRoom '#ten-ten', '텐텐십십쥬쥬열열1010tenten'
| true | # author : jelly, PI:NAME:<NAME>END_PIunJ, myounghoPak
# Dependency:
# - cron
# Description:
# 한국시간 (KST) 기준 23시가 되면 #_general 에 #darknight 로 이동하러는 메세지를 출력한다.
# 07시가 되면 #darknight 에 #_general 로 이동하라는 메세지를 출력한다.
cronJob = require('cron').CronJob
module.exports = (robot) ->
# darknightJob = new cronJob('0 0 23 * * *', wakeUpDarknight(robot), null, true, "Asia/Seoul")
tentenJob = new cronJob('0 10 10 * * *', tenten(robot), null, true, "Asia/Seoul")
tenten = (robot) ->
-> robot.messageRoom '#ten-ten', '텐텐십십쥬쥬열열1010tenten'
|
[
{
"context": " findByIdAndUpdate: -> this\n modelName: 'bobby'\n sort: -> this\n skip: -> this\n li",
"end": 430,
"score": 0.982324481010437,
"start": 425,
"tag": "NAME",
"value": "bobby"
},
{
"context": "ions =\n query:\n bob: 'jac... | test/server/common/crudModelFactory.coffee | valueflowquality/gi-util-update | 0 | path = require 'path'
expect = require('chai').expect
assert = require('chai').assert
mocks = require '../mocks'
sinon = mocks.sinon
dir = path.normalize __dirname + '../../../../server'
module.exports = () ->
describe 'CrudModelFactory', ->
crudModelFactory = require dir + '/common/crudModelFactory'
resource =
find: -> this
findOne: -> this
findByIdAndUpdate: -> this
modelName: 'bobby'
sort: -> this
skip: -> this
limit: -> this
exec: -> this
count: -> this
create: -> this
it 'Exports a factory function', (done) ->
expect(crudModelFactory).to.be.a('function')
done()
describe 'Function: (resource) -> { object }', ->
crud = null
beforeEach ->
crud = crudModelFactory resource
describe 'It outputs an object with properties:', ->
it 'name: String', ->
expect(crud).to.have.property 'name'
expect(crud.name).to.be.a('string')
it 'find: Function', ->
expect(crud).to.have.property 'find'
expect(crud.find).to.be.a('function')
it 'findById: Function', ->
expect(crud).to.have.property 'findById'
expect(crud.findById).to.be.a('function')
it 'findOne: Function', ->
expect(crud).to.have.property 'findOne'
expect(crud.findOne).to.be.a('function')
it 'findOneBy: Function', ->
expect(crud).to.have.property 'findOneBy'
expect(crud.findOneBy).to.be.a('function')
it 'create: Function', ->
expect(crud).to.have.property 'create'
expect(crud.create).to.be.a('function')
it 'update: Function', ->
expect(crud).to.have.property 'update'
expect(crud.update).to.be.a('function')
it 'destroy: Function', ->
expect(crud).to.have.property 'destroy'
expect(crud.destroy).to.be.a('function')
it 'count: Function', ->
expect(crud).to.have.property 'count'
expect(crud.count).to.be.a('function')
describe 'name: String', ->
it 'exposes resource.modelName as its name', (done) ->
expect(crud.name).to.equal resource.modelName
done()
describe 'find: Function: (options, callback)
-> callback(err, results, pageCount)', ->
options = null
beforeEach (done) ->
options =
query:
bob: 'jack'
systemId: '124'
sinon.spy resource, 'find'
sinon.spy resource, 'sort'
sinon.spy resource, 'skip'
sinon.spy resource, 'limit'
sinon.stub resource, 'count'
sinon.stub resource, 'exec'
#this default behaviour for exec and count
#is overriden in certain tests
resource.exec.callsArgWith 0, null, []
resource.count.callsArgWith 1, null, 1
done()
afterEach (done) ->
resource.find.restore()
resource.sort.restore()
resource.skip.restore()
resource.limit.restore()
resource.count.restore()
resource.exec.restore()
done()
it 'it returns an error if options are not specified', (done) ->
crud.find null, (err, obj, pageCount) ->
expect(err).to.equal 'options must be specfied for find'
expect(obj).to.not.exist
expect(pageCount).to.equal 0
done()
it 'it returns an error if options.query is not specified', (done) ->
options =
somethingElse:
bob: 'jack'
crud.find options, (err, obj, pageCount) ->
expect(err).to.equal 'systemId not specified in query'
expect(obj).to.not.exist
expect(pageCount).to.equal 0
done()
it 'it returns an error if options.query does not specify a systemId'
, (done) ->
options =
query:
bob: 'jack'
crud.find options, (err, obj, pageCount) ->
expect(err).to.equal 'systemId not specified in query'
expect(obj).to.not.exist
expect(pageCount).to.equal 0
done()
it 'it calls resource.find with options.query', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.find.calledWith(options.query)).to.be.true
done()
it 'it calls resource.sort after calling find', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.sort.calledAfter(resource.find)).to.be.true
done()
it 'defaults to no sorting', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.sort.calledWith({})).to.be.true
done()
it 'but will sort with any value specified in options.sort', (done) ->
options.sort = {bob: "desc"}
crud.find options, (err, obj, pageCount) ->
expect(resource.sort.calledWith(options.sort)).to.be.true
done()
describe 'pagination', ->
it 'it defaults to asking for page 1', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.skip.calledWith(0)).to.be.true
done()
it 'it defaults to asking for at most 10000 results', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.limit.calledWith(10000)).to.be.true
done()
it 'calls skip after sort', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.skip.calledAfter(resource.sort)).to.be.true
done()
it 'calls limit after skip', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.limit.calledAfter(resource.skip)).to.be.true
done()
describe 'example with 30 results, options.page = 3,
options.max = 10', ->
beforeEach ->
resource.count.restore()
sinon.stub resource, 'count'
resource.count.callsArgWith 1, null, 30
options.page = 3
options.max = 10
it 'calls skip with 20', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.skip.calledWith(20)).to.be.true
done()
it 'calls limit with 10', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.limit.calledWith(10)).to.be.true
done()
it 'returns pageCount as celing of results / options.max'
, (done) ->
crud.find options, (err, obj, pageCount) ->
expect(pageCount).to.equal 3
done()
it 'returns an error if the find query fails', (done) ->
resource.exec.restore()
sinon.stub resource, 'exec'
resource.exec.callsArgWith 0, 'error', null, 0
crud.find options, (err, obj, pageCount) ->
assert resource.exec.called, "exec not called"
expect(err).to.equal 'error'
expect(obj).to.not.exist
expect(pageCount).to.equal 0
done()
it 'reports error if it cannot count the results', (done) ->
resource.count.restore()
sinon.stub resource, 'count'
resource.count.callsArgWith 1, 'some error', 2
crud.find options, (err, obj, pageCount) ->
assert resource.exec.called, "exec not called"
assert resource.count.called, "did not call count"
expect(err).to.equal 'could not count the results'
done()
it 'counts the total number of results in a find', (done) ->
resource.count.restore()
sinon.stub resource, 'count'
resource.count.callsArgWith 1, null, 25
options.max = 10
crud.find options, (err, obj, pageCount) ->
expect(err).to.not.exist
expect(obj).to.be.an 'array'
expect(pageCount).to.equal 3
options.max = 20
crud.find options, (err, obj, pageCount) ->
expect(err).to.not.exist
expect(obj).to.be.an 'array'
expect(pageCount).to.equal 2
done()
it 'returns nothing if that is all you ask for', (done) ->
options.max = -3
crud.find options, (err, obj, pageCount) ->
expect(err).to.not.exist
expect(obj).to.be.an 'array'
expect(pageCount).to.equal 0
options.max = 0
crud.find options, (err, obj, pageCount) ->
expect(err).to.not.exist
expect(obj).to.be.an 'array'
expect(pageCount).to.equal 0
assert resource.exec.callCount is 0
, "exec should not have been called"
assert resource.find.callCount is 0
, "find should not have been called"
done()
describe 'findOne: (query, callback) -> callback(err, obj)', ->
beforeEach (done) ->
sinon.stub resource, 'findOne'
resource.findOne.callsArgWith(1,null,{bob:"123"})
done()
afterEach (done) ->
resource.findOne.restore()
done()
it 'returns an error if systemId not specified on query', (done) ->
query =
_id: 'bob'
crud.findOne query, (err, obj) ->
expect(err).to.equal 'Cannot find ' +
resource.modelName + ' - no SystemId'
expect(obj).to.not.exist
done()
it 'returns and error if no query specified', (done) ->
crud.findOne null, (err, obj) ->
expect(err).to.equal 'Cannot find ' + resource.modelName +
' - no SystemId'
expect(obj).to.not.exist
done()
it 'returns object if found', (done) ->
query =
systemId: 123
_id: 'bob'
crud.findOne query, (err, obj) ->
assert resource.findOne.calledWith(
{'_id': 'bob', 'systemId': 123}
), "findOne not called correctly"
expect(err).to.not.exist
expect(obj).to.have.property 'bob', '123'
done()
it 'returns any errors from Resource.findOne', (done) ->
query =
systemId: 123
_id: 'bob'
resource.findOne.restore()
sinon.stub resource, 'findOne'
resource.findOne.callsArgWith 1, "an error", null
crud.findOne query, (err, obj) ->
expect(obj).to.not.exist
expect(err).to.equal 'an error'
done()
it 'returns an error if object not found', (done) ->
query =
systemId: 123
_id: 'bob'
resource.findOne.restore()
sinon.stub resource, 'findOne'
resource.findOne.callsArgWith 1, null, null
crud.findOne query, (err, obj) ->
expect(obj).to.not.exist
expect(err).to.equal 'Cannot find ' + resource.modelName
done()
describe 'findOneBy: Function', ->
beforeEach (done) ->
sinon.spy crud, 'findOne'
sinon.stub resource, 'findOne'
resource.findOne.callsArg 1
done()
afterEach (done) ->
crud.findOne.reset()
resource.findOne.restore()
done()
it 'forms a query from params and aliases findOne', (done) ->
crud.findOneBy 'akey', 'a value', 'a systemId', (err, obj) ->
assert crud.findOne.calledWith(
{akey: 'a value', systemId: 'a systemId'}, sinon.match.func
), 'findOne not passed correct query'
done()
describe 'findById: Function(id, systemId, callback)
-> callback(err, obj)', ->
beforeEach (done) ->
sinon.spy crud, 'findOneBy'
sinon.stub resource, 'findOne'
resource.findOne.callsArg 1
done()
afterEach (done) ->
crud.findOneBy.reset()
resource.findOne.restore()
done()
it 'aliases findOneBy', (done) ->
crud.findById '123', "systemId", (err, obj) ->
assert crud.findOneBy.calledWith(
'_id', '123', "systemId", sinon.match.func
), "findOne not called correctly"
done()
describe 'create: (json, callback) -> callback(err, obj)', ->
beforeEach (done) ->
sinon.stub resource, 'create'
done()
afterEach (done) ->
resource.create.restore()
done()
it 'returns an error if systemId not specified in json', (done) ->
json =
name: 'bob'
crud.create json, (err, obj) ->
expect(err).to.equal resource.modelName +
' could not be created - no systemId'
expect(obj).to.not.exist
done()
it 'passes json through to resource.create', (done) ->
json =
some: 'data'
systemId: '123'
resource.create.callsArgWith 1, null, {}
crud.create json, (err, obj) ->
expect(err).to.not.exist
expect(obj).to.be.an 'object'
expect(resource.create.called).to.be.true
expect(resource.create.calledWith(json, sinon.match.func)
, 'json did not match').to.be.true
done()
it 'returns the error if create errors', (done) ->
json =
some: 'data'
systemId: '123'
resource.create.callsArgWith 1, "an error",null
crud.create json, (err, obj) ->
expect(err).to.equal 'an error'
expect(obj).to.not.exist
done()
it 'returns the error if create returns nothing', (done) ->
json =
some: 'data'
systemId: '123'
resource.create.callsArgWith 1, null, null
crud.create json, (err, obj) ->
expect(err).to.equal resource.modelName + ' could not be saved'
expect(obj).to.not.exist
done()
it 'retuns the object passed by create if all ok', (done) ->
json =
some: 'data'
systemId: '123'
resource.create.callsArgWith 1, null, json
crud.create json, (err, obj) ->
expect(err).to.not.exist
expect(obj).to.equal json
done()
describe 'update: Function(id, json, callback)
-> callback(err, obj)', ->
beforeEach (done) ->
sinon.stub resource, 'findByIdAndUpdate'
resource.findByIdAndUpdate.callsArgWith 2, null, {}
done()
afterEach (done) ->
resource.findByIdAndUpdate.restore()
done()
it 'returns an error if systemId not specified in json', (done) ->
json =
_id: 'bob'
crud.update 'bob', json, (err, obj) ->
expect(err).to.equal resource.modelName +
' could not be updated - no systemId'
expect(obj).to.not.exist
done()
it 'passes json through to resource.findByIdAndUpdate', (done) ->
crud.update '123', {some: 'bad json', systemId: '123'}
, (err, obj) ->
expect(err).to.not.exist
expect(obj).to.be.an 'object'
assert resource.findByIdAndUpdate.calledWith(
'123', {some: 'bad json', systemId: '123'}, sinon.match.func
)
, 'findByIdAndUpdate not called with correct parameters'
done()
describe 'destroy: (id, systemId, callback) -> callback(err)', ->
it 'HAS NO TESTS YET :-(', (done) ->
done() | 193193 | path = require 'path'
expect = require('chai').expect
assert = require('chai').assert
mocks = require '../mocks'
sinon = mocks.sinon
dir = path.normalize __dirname + '../../../../server'
module.exports = () ->
describe 'CrudModelFactory', ->
crudModelFactory = require dir + '/common/crudModelFactory'
resource =
find: -> this
findOne: -> this
findByIdAndUpdate: -> this
modelName: '<NAME>'
sort: -> this
skip: -> this
limit: -> this
exec: -> this
count: -> this
create: -> this
it 'Exports a factory function', (done) ->
expect(crudModelFactory).to.be.a('function')
done()
describe 'Function: (resource) -> { object }', ->
crud = null
beforeEach ->
crud = crudModelFactory resource
describe 'It outputs an object with properties:', ->
it 'name: String', ->
expect(crud).to.have.property 'name'
expect(crud.name).to.be.a('string')
it 'find: Function', ->
expect(crud).to.have.property 'find'
expect(crud.find).to.be.a('function')
it 'findById: Function', ->
expect(crud).to.have.property 'findById'
expect(crud.findById).to.be.a('function')
it 'findOne: Function', ->
expect(crud).to.have.property 'findOne'
expect(crud.findOne).to.be.a('function')
it 'findOneBy: Function', ->
expect(crud).to.have.property 'findOneBy'
expect(crud.findOneBy).to.be.a('function')
it 'create: Function', ->
expect(crud).to.have.property 'create'
expect(crud.create).to.be.a('function')
it 'update: Function', ->
expect(crud).to.have.property 'update'
expect(crud.update).to.be.a('function')
it 'destroy: Function', ->
expect(crud).to.have.property 'destroy'
expect(crud.destroy).to.be.a('function')
it 'count: Function', ->
expect(crud).to.have.property 'count'
expect(crud.count).to.be.a('function')
describe 'name: String', ->
it 'exposes resource.modelName as its name', (done) ->
expect(crud.name).to.equal resource.modelName
done()
describe 'find: Function: (options, callback)
-> callback(err, results, pageCount)', ->
options = null
beforeEach (done) ->
options =
query:
bob: 'jack'
systemId: '124'
sinon.spy resource, 'find'
sinon.spy resource, 'sort'
sinon.spy resource, 'skip'
sinon.spy resource, 'limit'
sinon.stub resource, 'count'
sinon.stub resource, 'exec'
#this default behaviour for exec and count
#is overriden in certain tests
resource.exec.callsArgWith 0, null, []
resource.count.callsArgWith 1, null, 1
done()
afterEach (done) ->
resource.find.restore()
resource.sort.restore()
resource.skip.restore()
resource.limit.restore()
resource.count.restore()
resource.exec.restore()
done()
it 'it returns an error if options are not specified', (done) ->
crud.find null, (err, obj, pageCount) ->
expect(err).to.equal 'options must be specfied for find'
expect(obj).to.not.exist
expect(pageCount).to.equal 0
done()
it 'it returns an error if options.query is not specified', (done) ->
options =
somethingElse:
bob: 'jack'
crud.find options, (err, obj, pageCount) ->
expect(err).to.equal 'systemId not specified in query'
expect(obj).to.not.exist
expect(pageCount).to.equal 0
done()
it 'it returns an error if options.query does not specify a systemId'
, (done) ->
options =
query:
bob: 'jack'
crud.find options, (err, obj, pageCount) ->
expect(err).to.equal 'systemId not specified in query'
expect(obj).to.not.exist
expect(pageCount).to.equal 0
done()
it 'it calls resource.find with options.query', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.find.calledWith(options.query)).to.be.true
done()
it 'it calls resource.sort after calling find', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.sort.calledAfter(resource.find)).to.be.true
done()
it 'defaults to no sorting', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.sort.calledWith({})).to.be.true
done()
it 'but will sort with any value specified in options.sort', (done) ->
options.sort = {bob: "desc"}
crud.find options, (err, obj, pageCount) ->
expect(resource.sort.calledWith(options.sort)).to.be.true
done()
describe 'pagination', ->
it 'it defaults to asking for page 1', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.skip.calledWith(0)).to.be.true
done()
it 'it defaults to asking for at most 10000 results', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.limit.calledWith(10000)).to.be.true
done()
it 'calls skip after sort', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.skip.calledAfter(resource.sort)).to.be.true
done()
it 'calls limit after skip', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.limit.calledAfter(resource.skip)).to.be.true
done()
describe 'example with 30 results, options.page = 3,
options.max = 10', ->
beforeEach ->
resource.count.restore()
sinon.stub resource, 'count'
resource.count.callsArgWith 1, null, 30
options.page = 3
options.max = 10
it 'calls skip with 20', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.skip.calledWith(20)).to.be.true
done()
it 'calls limit with 10', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.limit.calledWith(10)).to.be.true
done()
it 'returns pageCount as celing of results / options.max'
, (done) ->
crud.find options, (err, obj, pageCount) ->
expect(pageCount).to.equal 3
done()
it 'returns an error if the find query fails', (done) ->
resource.exec.restore()
sinon.stub resource, 'exec'
resource.exec.callsArgWith 0, 'error', null, 0
crud.find options, (err, obj, pageCount) ->
assert resource.exec.called, "exec not called"
expect(err).to.equal 'error'
expect(obj).to.not.exist
expect(pageCount).to.equal 0
done()
it 'reports error if it cannot count the results', (done) ->
resource.count.restore()
sinon.stub resource, 'count'
resource.count.callsArgWith 1, 'some error', 2
crud.find options, (err, obj, pageCount) ->
assert resource.exec.called, "exec not called"
assert resource.count.called, "did not call count"
expect(err).to.equal 'could not count the results'
done()
it 'counts the total number of results in a find', (done) ->
resource.count.restore()
sinon.stub resource, 'count'
resource.count.callsArgWith 1, null, 25
options.max = 10
crud.find options, (err, obj, pageCount) ->
expect(err).to.not.exist
expect(obj).to.be.an 'array'
expect(pageCount).to.equal 3
options.max = 20
crud.find options, (err, obj, pageCount) ->
expect(err).to.not.exist
expect(obj).to.be.an 'array'
expect(pageCount).to.equal 2
done()
it 'returns nothing if that is all you ask for', (done) ->
options.max = -3
crud.find options, (err, obj, pageCount) ->
expect(err).to.not.exist
expect(obj).to.be.an 'array'
expect(pageCount).to.equal 0
options.max = 0
crud.find options, (err, obj, pageCount) ->
expect(err).to.not.exist
expect(obj).to.be.an 'array'
expect(pageCount).to.equal 0
assert resource.exec.callCount is 0
, "exec should not have been called"
assert resource.find.callCount is 0
, "find should not have been called"
done()
describe 'findOne: (query, callback) -> callback(err, obj)', ->
beforeEach (done) ->
sinon.stub resource, 'findOne'
resource.findOne.callsArgWith(1,null,{bob:"123"})
done()
afterEach (done) ->
resource.findOne.restore()
done()
it 'returns an error if systemId not specified on query', (done) ->
query =
_id: 'bob'
crud.findOne query, (err, obj) ->
expect(err).to.equal 'Cannot find ' +
resource.modelName + ' - no SystemId'
expect(obj).to.not.exist
done()
it 'returns and error if no query specified', (done) ->
crud.findOne null, (err, obj) ->
expect(err).to.equal 'Cannot find ' + resource.modelName +
' - no SystemId'
expect(obj).to.not.exist
done()
it 'returns object if found', (done) ->
query =
systemId: 123
_id: 'bob'
crud.findOne query, (err, obj) ->
assert resource.findOne.calledWith(
{'_id': 'bob', 'systemId': 123}
), "findOne not called correctly"
expect(err).to.not.exist
expect(obj).to.have.property 'bob', '123'
done()
it 'returns any errors from Resource.findOne', (done) ->
query =
systemId: 123
_id: '<NAME>'
resource.findOne.restore()
sinon.stub resource, 'findOne'
resource.findOne.callsArgWith 1, "an error", null
crud.findOne query, (err, obj) ->
expect(obj).to.not.exist
expect(err).to.equal 'an error'
done()
it 'returns an error if object not found', (done) ->
query =
systemId: 123
_id: '<NAME>'
resource.findOne.restore()
sinon.stub resource, 'findOne'
resource.findOne.callsArgWith 1, null, null
crud.findOne query, (err, obj) ->
expect(obj).to.not.exist
expect(err).to.equal 'Cannot find ' + resource.modelName
done()
describe 'findOneBy: Function', ->
beforeEach (done) ->
sinon.spy crud, 'findOne'
sinon.stub resource, 'findOne'
resource.findOne.callsArg 1
done()
afterEach (done) ->
crud.findOne.reset()
resource.findOne.restore()
done()
it 'forms a query from params and aliases findOne', (done) ->
crud.findOneBy 'akey', 'a value', 'a systemId', (err, obj) ->
assert crud.findOne.calledWith(
{akey: 'a value', systemId: 'a systemId'}, sinon.match.func
), 'findOne not passed correct query'
done()
describe 'findById: Function(id, systemId, callback)
-> callback(err, obj)', ->
beforeEach (done) ->
sinon.spy crud, 'findOneBy'
sinon.stub resource, 'findOne'
resource.findOne.callsArg 1
done()
afterEach (done) ->
crud.findOneBy.reset()
resource.findOne.restore()
done()
it 'aliases findOneBy', (done) ->
crud.findById '123', "systemId", (err, obj) ->
assert crud.findOneBy.calledWith(
'_id', '123', "systemId", sinon.match.func
), "findOne not called correctly"
done()
describe 'create: (json, callback) -> callback(err, obj)', ->
beforeEach (done) ->
sinon.stub resource, 'create'
done()
afterEach (done) ->
resource.create.restore()
done()
it 'returns an error if systemId not specified in json', (done) ->
json =
name: '<NAME>'
crud.create json, (err, obj) ->
expect(err).to.equal resource.modelName +
' could not be created - no systemId'
expect(obj).to.not.exist
done()
it 'passes json through to resource.create', (done) ->
json =
some: 'data'
systemId: '123'
resource.create.callsArgWith 1, null, {}
crud.create json, (err, obj) ->
expect(err).to.not.exist
expect(obj).to.be.an 'object'
expect(resource.create.called).to.be.true
expect(resource.create.calledWith(json, sinon.match.func)
, 'json did not match').to.be.true
done()
it 'returns the error if create errors', (done) ->
json =
some: 'data'
systemId: '123'
resource.create.callsArgWith 1, "an error",null
crud.create json, (err, obj) ->
expect(err).to.equal 'an error'
expect(obj).to.not.exist
done()
it 'returns the error if create returns nothing', (done) ->
json =
some: 'data'
systemId: '123'
resource.create.callsArgWith 1, null, null
crud.create json, (err, obj) ->
expect(err).to.equal resource.modelName + ' could not be saved'
expect(obj).to.not.exist
done()
it 'retuns the object passed by create if all ok', (done) ->
json =
some: 'data'
systemId: '123'
resource.create.callsArgWith 1, null, json
crud.create json, (err, obj) ->
expect(err).to.not.exist
expect(obj).to.equal json
done()
describe 'update: Function(id, json, callback)
-> callback(err, obj)', ->
beforeEach (done) ->
sinon.stub resource, 'findByIdAndUpdate'
resource.findByIdAndUpdate.callsArgWith 2, null, {}
done()
afterEach (done) ->
resource.findByIdAndUpdate.restore()
done()
it 'returns an error if systemId not specified in json', (done) ->
json =
_id: 'bob'
crud.update 'bob', json, (err, obj) ->
expect(err).to.equal resource.modelName +
' could not be updated - no systemId'
expect(obj).to.not.exist
done()
it 'passes json through to resource.findByIdAndUpdate', (done) ->
crud.update '123', {some: 'bad json', systemId: '123'}
, (err, obj) ->
expect(err).to.not.exist
expect(obj).to.be.an 'object'
assert resource.findByIdAndUpdate.calledWith(
'123', {some: 'bad json', systemId: '123'}, sinon.match.func
)
, 'findByIdAndUpdate not called with correct parameters'
done()
describe 'destroy: (id, systemId, callback) -> callback(err)', ->
it 'HAS NO TESTS YET :-(', (done) ->
done() | true | path = require 'path'
expect = require('chai').expect
assert = require('chai').assert
mocks = require '../mocks'
sinon = mocks.sinon
dir = path.normalize __dirname + '../../../../server'
module.exports = () ->
describe 'CrudModelFactory', ->
crudModelFactory = require dir + '/common/crudModelFactory'
resource =
find: -> this
findOne: -> this
findByIdAndUpdate: -> this
modelName: 'PI:NAME:<NAME>END_PI'
sort: -> this
skip: -> this
limit: -> this
exec: -> this
count: -> this
create: -> this
it 'Exports a factory function', (done) ->
expect(crudModelFactory).to.be.a('function')
done()
describe 'Function: (resource) -> { object }', ->
crud = null
beforeEach ->
crud = crudModelFactory resource
describe 'It outputs an object with properties:', ->
it 'name: String', ->
expect(crud).to.have.property 'name'
expect(crud.name).to.be.a('string')
it 'find: Function', ->
expect(crud).to.have.property 'find'
expect(crud.find).to.be.a('function')
it 'findById: Function', ->
expect(crud).to.have.property 'findById'
expect(crud.findById).to.be.a('function')
it 'findOne: Function', ->
expect(crud).to.have.property 'findOne'
expect(crud.findOne).to.be.a('function')
it 'findOneBy: Function', ->
expect(crud).to.have.property 'findOneBy'
expect(crud.findOneBy).to.be.a('function')
it 'create: Function', ->
expect(crud).to.have.property 'create'
expect(crud.create).to.be.a('function')
it 'update: Function', ->
expect(crud).to.have.property 'update'
expect(crud.update).to.be.a('function')
it 'destroy: Function', ->
expect(crud).to.have.property 'destroy'
expect(crud.destroy).to.be.a('function')
it 'count: Function', ->
expect(crud).to.have.property 'count'
expect(crud.count).to.be.a('function')
describe 'name: String', ->
it 'exposes resource.modelName as its name', (done) ->
expect(crud.name).to.equal resource.modelName
done()
describe 'find: Function: (options, callback)
-> callback(err, results, pageCount)', ->
options = null
beforeEach (done) ->
options =
query:
bob: 'jack'
systemId: '124'
sinon.spy resource, 'find'
sinon.spy resource, 'sort'
sinon.spy resource, 'skip'
sinon.spy resource, 'limit'
sinon.stub resource, 'count'
sinon.stub resource, 'exec'
#this default behaviour for exec and count
#is overriden in certain tests
resource.exec.callsArgWith 0, null, []
resource.count.callsArgWith 1, null, 1
done()
afterEach (done) ->
resource.find.restore()
resource.sort.restore()
resource.skip.restore()
resource.limit.restore()
resource.count.restore()
resource.exec.restore()
done()
it 'it returns an error if options are not specified', (done) ->
crud.find null, (err, obj, pageCount) ->
expect(err).to.equal 'options must be specfied for find'
expect(obj).to.not.exist
expect(pageCount).to.equal 0
done()
it 'it returns an error if options.query is not specified', (done) ->
options =
somethingElse:
bob: 'jack'
crud.find options, (err, obj, pageCount) ->
expect(err).to.equal 'systemId not specified in query'
expect(obj).to.not.exist
expect(pageCount).to.equal 0
done()
it 'it returns an error if options.query does not specify a systemId'
, (done) ->
options =
query:
bob: 'jack'
crud.find options, (err, obj, pageCount) ->
expect(err).to.equal 'systemId not specified in query'
expect(obj).to.not.exist
expect(pageCount).to.equal 0
done()
it 'it calls resource.find with options.query', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.find.calledWith(options.query)).to.be.true
done()
it 'it calls resource.sort after calling find', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.sort.calledAfter(resource.find)).to.be.true
done()
it 'defaults to no sorting', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.sort.calledWith({})).to.be.true
done()
it 'but will sort with any value specified in options.sort', (done) ->
options.sort = {bob: "desc"}
crud.find options, (err, obj, pageCount) ->
expect(resource.sort.calledWith(options.sort)).to.be.true
done()
describe 'pagination', ->
it 'it defaults to asking for page 1', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.skip.calledWith(0)).to.be.true
done()
it 'it defaults to asking for at most 10000 results', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.limit.calledWith(10000)).to.be.true
done()
it 'calls skip after sort', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.skip.calledAfter(resource.sort)).to.be.true
done()
it 'calls limit after skip', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.limit.calledAfter(resource.skip)).to.be.true
done()
describe 'example with 30 results, options.page = 3,
options.max = 10', ->
beforeEach ->
resource.count.restore()
sinon.stub resource, 'count'
resource.count.callsArgWith 1, null, 30
options.page = 3
options.max = 10
it 'calls skip with 20', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.skip.calledWith(20)).to.be.true
done()
it 'calls limit with 10', (done) ->
crud.find options, (err, obj, pageCount) ->
expect(resource.limit.calledWith(10)).to.be.true
done()
it 'returns pageCount as celing of results / options.max'
, (done) ->
crud.find options, (err, obj, pageCount) ->
expect(pageCount).to.equal 3
done()
it 'returns an error if the find query fails', (done) ->
resource.exec.restore()
sinon.stub resource, 'exec'
resource.exec.callsArgWith 0, 'error', null, 0
crud.find options, (err, obj, pageCount) ->
assert resource.exec.called, "exec not called"
expect(err).to.equal 'error'
expect(obj).to.not.exist
expect(pageCount).to.equal 0
done()
it 'reports error if it cannot count the results', (done) ->
resource.count.restore()
sinon.stub resource, 'count'
resource.count.callsArgWith 1, 'some error', 2
crud.find options, (err, obj, pageCount) ->
assert resource.exec.called, "exec not called"
assert resource.count.called, "did not call count"
expect(err).to.equal 'could not count the results'
done()
it 'counts the total number of results in a find', (done) ->
resource.count.restore()
sinon.stub resource, 'count'
resource.count.callsArgWith 1, null, 25
options.max = 10
crud.find options, (err, obj, pageCount) ->
expect(err).to.not.exist
expect(obj).to.be.an 'array'
expect(pageCount).to.equal 3
options.max = 20
crud.find options, (err, obj, pageCount) ->
expect(err).to.not.exist
expect(obj).to.be.an 'array'
expect(pageCount).to.equal 2
done()
it 'returns nothing if that is all you ask for', (done) ->
options.max = -3
crud.find options, (err, obj, pageCount) ->
expect(err).to.not.exist
expect(obj).to.be.an 'array'
expect(pageCount).to.equal 0
options.max = 0
crud.find options, (err, obj, pageCount) ->
expect(err).to.not.exist
expect(obj).to.be.an 'array'
expect(pageCount).to.equal 0
assert resource.exec.callCount is 0
, "exec should not have been called"
assert resource.find.callCount is 0
, "find should not have been called"
done()
describe 'findOne: (query, callback) -> callback(err, obj)', ->
beforeEach (done) ->
sinon.stub resource, 'findOne'
resource.findOne.callsArgWith(1,null,{bob:"123"})
done()
afterEach (done) ->
resource.findOne.restore()
done()
it 'returns an error if systemId not specified on query', (done) ->
query =
_id: 'bob'
crud.findOne query, (err, obj) ->
expect(err).to.equal 'Cannot find ' +
resource.modelName + ' - no SystemId'
expect(obj).to.not.exist
done()
it 'returns and error if no query specified', (done) ->
crud.findOne null, (err, obj) ->
expect(err).to.equal 'Cannot find ' + resource.modelName +
' - no SystemId'
expect(obj).to.not.exist
done()
it 'returns object if found', (done) ->
query =
systemId: 123
_id: 'bob'
crud.findOne query, (err, obj) ->
assert resource.findOne.calledWith(
{'_id': 'bob', 'systemId': 123}
), "findOne not called correctly"
expect(err).to.not.exist
expect(obj).to.have.property 'bob', '123'
done()
it 'returns any errors from Resource.findOne', (done) ->
query =
systemId: 123
_id: 'PI:NAME:<NAME>END_PI'
resource.findOne.restore()
sinon.stub resource, 'findOne'
resource.findOne.callsArgWith 1, "an error", null
crud.findOne query, (err, obj) ->
expect(obj).to.not.exist
expect(err).to.equal 'an error'
done()
it 'returns an error if object not found', (done) ->
query =
systemId: 123
_id: 'PI:NAME:<NAME>END_PI'
resource.findOne.restore()
sinon.stub resource, 'findOne'
resource.findOne.callsArgWith 1, null, null
crud.findOne query, (err, obj) ->
expect(obj).to.not.exist
expect(err).to.equal 'Cannot find ' + resource.modelName
done()
describe 'findOneBy: Function', ->
beforeEach (done) ->
sinon.spy crud, 'findOne'
sinon.stub resource, 'findOne'
resource.findOne.callsArg 1
done()
afterEach (done) ->
crud.findOne.reset()
resource.findOne.restore()
done()
it 'forms a query from params and aliases findOne', (done) ->
crud.findOneBy 'akey', 'a value', 'a systemId', (err, obj) ->
assert crud.findOne.calledWith(
{akey: 'a value', systemId: 'a systemId'}, sinon.match.func
), 'findOne not passed correct query'
done()
describe 'findById: Function(id, systemId, callback)
-> callback(err, obj)', ->
beforeEach (done) ->
sinon.spy crud, 'findOneBy'
sinon.stub resource, 'findOne'
resource.findOne.callsArg 1
done()
afterEach (done) ->
crud.findOneBy.reset()
resource.findOne.restore()
done()
it 'aliases findOneBy', (done) ->
crud.findById '123', "systemId", (err, obj) ->
assert crud.findOneBy.calledWith(
'_id', '123', "systemId", sinon.match.func
), "findOne not called correctly"
done()
describe 'create: (json, callback) -> callback(err, obj)', ->
beforeEach (done) ->
sinon.stub resource, 'create'
done()
afterEach (done) ->
resource.create.restore()
done()
it 'returns an error if systemId not specified in json', (done) ->
json =
name: 'PI:NAME:<NAME>END_PI'
crud.create json, (err, obj) ->
expect(err).to.equal resource.modelName +
' could not be created - no systemId'
expect(obj).to.not.exist
done()
it 'passes json through to resource.create', (done) ->
json =
some: 'data'
systemId: '123'
resource.create.callsArgWith 1, null, {}
crud.create json, (err, obj) ->
expect(err).to.not.exist
expect(obj).to.be.an 'object'
expect(resource.create.called).to.be.true
expect(resource.create.calledWith(json, sinon.match.func)
, 'json did not match').to.be.true
done()
it 'returns the error if create errors', (done) ->
json =
some: 'data'
systemId: '123'
resource.create.callsArgWith 1, "an error",null
crud.create json, (err, obj) ->
expect(err).to.equal 'an error'
expect(obj).to.not.exist
done()
it 'returns the error if create returns nothing', (done) ->
json =
some: 'data'
systemId: '123'
resource.create.callsArgWith 1, null, null
crud.create json, (err, obj) ->
expect(err).to.equal resource.modelName + ' could not be saved'
expect(obj).to.not.exist
done()
it 'retuns the object passed by create if all ok', (done) ->
json =
some: 'data'
systemId: '123'
resource.create.callsArgWith 1, null, json
crud.create json, (err, obj) ->
expect(err).to.not.exist
expect(obj).to.equal json
done()
describe 'update: Function(id, json, callback)
-> callback(err, obj)', ->
beforeEach (done) ->
sinon.stub resource, 'findByIdAndUpdate'
resource.findByIdAndUpdate.callsArgWith 2, null, {}
done()
afterEach (done) ->
resource.findByIdAndUpdate.restore()
done()
it 'returns an error if systemId not specified in json', (done) ->
json =
_id: 'bob'
crud.update 'bob', json, (err, obj) ->
expect(err).to.equal resource.modelName +
' could not be updated - no systemId'
expect(obj).to.not.exist
done()
it 'passes json through to resource.findByIdAndUpdate', (done) ->
crud.update '123', {some: 'bad json', systemId: '123'}
, (err, obj) ->
expect(err).to.not.exist
expect(obj).to.be.an 'object'
assert resource.findByIdAndUpdate.calledWith(
'123', {some: 'bad json', systemId: '123'}, sinon.match.func
)
, 'findByIdAndUpdate not called with correct parameters'
done()
describe 'destroy: (id, systemId, callback) -> callback(err)', ->
it 'HAS NO TESTS YET :-(', (done) ->
done() |
[
{
"context": "nysong'\n\n\ndescribe 'Tinysong', ->\n trackTitle = '꿈에'\n artistName = '박정현'\n startNo = 0\n\n describe ",
"end": 107,
"score": 0.7346437573432922,
"start": 106,
"tag": "NAME",
"value": "꿈"
},
{
"context": "nysong'\n\n\ndescribe 'Tinysong', ->\n trackTitle = '꿈에'\... | node_modules/grooveshark-streaming/test/Tinysong.test.coffee | samkreter/MusicChoose | 3 | should = require 'should'
Tinysong = require '../lib/Tinysong'
describe 'Tinysong', ->
trackTitle = '꿈에'
artistName = '박정현'
startNo = 0
describe 'Tinysong.getSongInfoArray(...)', ->
it 'should be done', (done) ->
Tinysong.getSongInfoArray trackTitle, artistName, startNo, (err, songInfoArray) ->
should.not.exist err
should.exist songInfoArray
songInfoArray.should.not.be.empty
done()
describe 'Tinysong.getSongInfo(...)', ->
it 'should be failed to find a song', (done) ->
Tinysong.getSongInfo 'nosonglikethis', 'nosingerlikethis', (err, songInfo) ->
should.not.exist err
should.not.exist songInfo
done()
it 'should be done', (done) ->
Tinysong.getSongInfo trackTitle, artistName, (err, songInfo) ->
should.not.exist err
should.exist songInfo
done()
| 185081 | should = require 'should'
Tinysong = require '../lib/Tinysong'
describe 'Tinysong', ->
trackTitle = '<NAME> <NAME>'
artistName = '<NAME>'
startNo = 0
describe 'Tinysong.getSongInfoArray(...)', ->
it 'should be done', (done) ->
Tinysong.getSongInfoArray trackTitle, artistName, startNo, (err, songInfoArray) ->
should.not.exist err
should.exist songInfoArray
songInfoArray.should.not.be.empty
done()
describe 'Tinysong.getSongInfo(...)', ->
it 'should be failed to find a song', (done) ->
Tinysong.getSongInfo 'nosonglikethis', 'nosingerlikethis', (err, songInfo) ->
should.not.exist err
should.not.exist songInfo
done()
it 'should be done', (done) ->
Tinysong.getSongInfo trackTitle, artistName, (err, songInfo) ->
should.not.exist err
should.exist songInfo
done()
| true | should = require 'should'
Tinysong = require '../lib/Tinysong'
describe 'Tinysong', ->
trackTitle = 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI'
artistName = 'PI:NAME:<NAME>END_PI'
startNo = 0
describe 'Tinysong.getSongInfoArray(...)', ->
it 'should be done', (done) ->
Tinysong.getSongInfoArray trackTitle, artistName, startNo, (err, songInfoArray) ->
should.not.exist err
should.exist songInfoArray
songInfoArray.should.not.be.empty
done()
describe 'Tinysong.getSongInfo(...)', ->
it 'should be failed to find a song', (done) ->
Tinysong.getSongInfo 'nosonglikethis', 'nosingerlikethis', (err, songInfo) ->
should.not.exist err
should.not.exist songInfo
done()
it 'should be done', (done) ->
Tinysong.getSongInfo trackTitle, artistName, (err, songInfo) ->
should.not.exist err
should.exist songInfo
done()
|
[
{
"context": " deferred = $q.defer()\n storage_key = \"#{user}_#{chart.from}_#{chart.to}\"\n stored_tracks = l",
"end": 4169,
"score": 0.8196202516555786,
"start": 4158,
"tag": "KEY",
"value": "\"#{user}_#{"
},
{
"context": "efer()\n storage_key = \"#{user}... | app/scripts/services/lastfm_charts.coffee | moneypenny/seasonal-playlister | 0 | 'use strict'
###*
# @ngdoc service
# @name seasonSoundApp.lastfmCharts
# @description
# # lastfmCharts
# Service in the seasonSoundApp.
###
angular.module('seasonSoundApp')
.service 'LastfmChartsSvc', ($q, $http, LastfmSvc, localStorageService) ->
class LastfmCharts
constructor: ->
@year_charts = []
@user = {}
@chart = {}
@neighbors = []
@load_status =
charts: false
chart: false
neighbors: false
reset_user: ->
for key, value of @user
delete @user[key]
reset_charts: ->
@load_status.charts = false
@load_status.neighbors = false
@year_charts.length = 0
@neighbors.length = 0
initialize_year_charts: (charts) ->
for week_chart in charts
year = week_chart.year()
year_chart = @year_charts.filter((obj) -> obj.year == year)[0]
if year_chart
year_chart.charts.push week_chart
else
year_chart = new YearChart
year: year
year_chart.charts.push week_chart
@year_charts.push year_chart
get_year_chart_from_year_charts: (year) ->
for year_chart in @year_charts
return year_chart if year_chart.year == year
return false
load_year_chart: (year) ->
year = parseInt(year, 10)
chart = @get_year_chart_from_year_charts(year)
for key, value of chart
@chart[key] = value
@load_status.chart = true
get_user_neighbors: (user_name) ->
deferred = $q.defer()
on_success = (data, status, headers, config) =>
if data.neighbours
for i in [0...Math.min(8, data.neighbours.user.length)] by 1
user_data = data.neighbours.user[i]
@neighbors.push new LastfmNeighbor(user_data)
@load_status.neighbors = true
deferred.resolve()
on_error = (data, status, headers, config) =>
deferred.reject
name: 'error_response'
data: data
status: status
headers: headers
config: config
LastfmSvc.get_user_neighbors_url user_name, (url) ->
$http.get(url).success(on_success).error(on_error)
deferred.promise
get_user_info: (user_name) ->
deferred = $q.defer()
on_success = (data, status, headers, config) =>
if data.user
for key, value of new LastfmUser(data.user)
@user[key] = value
deferred.resolve()
on_error = (data, status, headers, config) =>
deferred.reject
name: 'error_response'
data: data
status: status
headers: headers
config: config
LastfmSvc.get_user_info_url user_name, (url) ->
$http.get(url).success(on_success).error(on_error)
deferred.promise
get_charts_after_cutoff_date: (charts_data, cutoff_date) ->
charts = charts_data.map (data) -> new LastfmChart(data)
charts.filter (chart) -> chart.to_date() >= cutoff_date
get_weekly_chart_list_after_date: (user, cutoff_date) ->
deferred = $q.defer()
on_success = (data, status, headers, config) =>
if data.weeklychartlist
charts_data = data.weeklychartlist.chart.slice(0).reverse()
charts = @get_charts_after_cutoff_date(charts_data, cutoff_date)
@initialize_year_charts charts
deferred.resolve()
else if data.error
deferred.reject({name: data.error})
@load_status.charts = true
on_error = (data, status, headers, config) =>
deferred.reject
name: 'error_response'
data: data
status: status
headers: headers
config: config
@load_status.charts = true
LastfmSvc.get_weekly_chart_list_url user, (url) ->
$http.get(url).success(on_success).error(on_error)
deferred.promise
get_weekly_track_chart: (user, chart) ->
deferred = $q.defer()
storage_key = "#{user}_#{chart.from}_#{chart.to}"
stored_tracks = localStorageService.get(storage_key)
if stored_tracks
for track in stored_tracks
chart.tracks.push(track)
deferred.resolve()
else
on_success = (data) =>
if data.weeklytrackchart.track
for track_data in data.weeklytrackchart.track
chart.tracks.push(new LastfmTrack(track_data))
localStorageService.set(storage_key, JSON.stringify(chart.tracks))
deferred.resolve()
else if data.error
deferred.reject({name: data.error})
else
deferred.resolve()
on_error = (data, status, headers, config) ->
deferred.reject
name: 'error_response'
data: data
status: status
headers: headers
config: config
LastfmSvc.get_weekly_track_chart_url user, chart, (url) ->
$http.get(url).success(on_success).error(on_error)
deferred.promise
new LastfmCharts()
| 195168 | 'use strict'
###*
# @ngdoc service
# @name seasonSoundApp.lastfmCharts
# @description
# # lastfmCharts
# Service in the seasonSoundApp.
###
angular.module('seasonSoundApp')
.service 'LastfmChartsSvc', ($q, $http, LastfmSvc, localStorageService) ->
class LastfmCharts
constructor: ->
@year_charts = []
@user = {}
@chart = {}
@neighbors = []
@load_status =
charts: false
chart: false
neighbors: false
reset_user: ->
for key, value of @user
delete @user[key]
reset_charts: ->
@load_status.charts = false
@load_status.neighbors = false
@year_charts.length = 0
@neighbors.length = 0
initialize_year_charts: (charts) ->
for week_chart in charts
year = week_chart.year()
year_chart = @year_charts.filter((obj) -> obj.year == year)[0]
if year_chart
year_chart.charts.push week_chart
else
year_chart = new YearChart
year: year
year_chart.charts.push week_chart
@year_charts.push year_chart
get_year_chart_from_year_charts: (year) ->
for year_chart in @year_charts
return year_chart if year_chart.year == year
return false
load_year_chart: (year) ->
year = parseInt(year, 10)
chart = @get_year_chart_from_year_charts(year)
for key, value of chart
@chart[key] = value
@load_status.chart = true
get_user_neighbors: (user_name) ->
deferred = $q.defer()
on_success = (data, status, headers, config) =>
if data.neighbours
for i in [0...Math.min(8, data.neighbours.user.length)] by 1
user_data = data.neighbours.user[i]
@neighbors.push new LastfmNeighbor(user_data)
@load_status.neighbors = true
deferred.resolve()
on_error = (data, status, headers, config) =>
deferred.reject
name: 'error_response'
data: data
status: status
headers: headers
config: config
LastfmSvc.get_user_neighbors_url user_name, (url) ->
$http.get(url).success(on_success).error(on_error)
deferred.promise
get_user_info: (user_name) ->
deferred = $q.defer()
on_success = (data, status, headers, config) =>
if data.user
for key, value of new LastfmUser(data.user)
@user[key] = value
deferred.resolve()
on_error = (data, status, headers, config) =>
deferred.reject
name: 'error_response'
data: data
status: status
headers: headers
config: config
LastfmSvc.get_user_info_url user_name, (url) ->
$http.get(url).success(on_success).error(on_error)
deferred.promise
get_charts_after_cutoff_date: (charts_data, cutoff_date) ->
charts = charts_data.map (data) -> new LastfmChart(data)
charts.filter (chart) -> chart.to_date() >= cutoff_date
get_weekly_chart_list_after_date: (user, cutoff_date) ->
deferred = $q.defer()
on_success = (data, status, headers, config) =>
if data.weeklychartlist
charts_data = data.weeklychartlist.chart.slice(0).reverse()
charts = @get_charts_after_cutoff_date(charts_data, cutoff_date)
@initialize_year_charts charts
deferred.resolve()
else if data.error
deferred.reject({name: data.error})
@load_status.charts = true
on_error = (data, status, headers, config) =>
deferred.reject
name: 'error_response'
data: data
status: status
headers: headers
config: config
@load_status.charts = true
LastfmSvc.get_weekly_chart_list_url user, (url) ->
$http.get(url).success(on_success).error(on_error)
deferred.promise
get_weekly_track_chart: (user, chart) ->
deferred = $q.defer()
storage_key = <KEY>chart.from}_<KEY>chart.to}"
stored_tracks = localStorageService.get(storage_key)
if stored_tracks
for track in stored_tracks
chart.tracks.push(track)
deferred.resolve()
else
on_success = (data) =>
if data.weeklytrackchart.track
for track_data in data.weeklytrackchart.track
chart.tracks.push(new LastfmTrack(track_data))
localStorageService.set(storage_key, JSON.stringify(chart.tracks))
deferred.resolve()
else if data.error
deferred.reject({name: data.error})
else
deferred.resolve()
on_error = (data, status, headers, config) ->
deferred.reject
name: 'error_response'
data: data
status: status
headers: headers
config: config
LastfmSvc.get_weekly_track_chart_url user, chart, (url) ->
$http.get(url).success(on_success).error(on_error)
deferred.promise
new LastfmCharts()
| true | 'use strict'
###*
# @ngdoc service
# @name seasonSoundApp.lastfmCharts
# @description
# # lastfmCharts
# Service in the seasonSoundApp.
###
angular.module('seasonSoundApp')
.service 'LastfmChartsSvc', ($q, $http, LastfmSvc, localStorageService) ->
class LastfmCharts
constructor: ->
@year_charts = []
@user = {}
@chart = {}
@neighbors = []
@load_status =
charts: false
chart: false
neighbors: false
reset_user: ->
for key, value of @user
delete @user[key]
reset_charts: ->
@load_status.charts = false
@load_status.neighbors = false
@year_charts.length = 0
@neighbors.length = 0
initialize_year_charts: (charts) ->
for week_chart in charts
year = week_chart.year()
year_chart = @year_charts.filter((obj) -> obj.year == year)[0]
if year_chart
year_chart.charts.push week_chart
else
year_chart = new YearChart
year: year
year_chart.charts.push week_chart
@year_charts.push year_chart
get_year_chart_from_year_charts: (year) ->
for year_chart in @year_charts
return year_chart if year_chart.year == year
return false
load_year_chart: (year) ->
year = parseInt(year, 10)
chart = @get_year_chart_from_year_charts(year)
for key, value of chart
@chart[key] = value
@load_status.chart = true
get_user_neighbors: (user_name) ->
deferred = $q.defer()
on_success = (data, status, headers, config) =>
if data.neighbours
for i in [0...Math.min(8, data.neighbours.user.length)] by 1
user_data = data.neighbours.user[i]
@neighbors.push new LastfmNeighbor(user_data)
@load_status.neighbors = true
deferred.resolve()
on_error = (data, status, headers, config) =>
deferred.reject
name: 'error_response'
data: data
status: status
headers: headers
config: config
LastfmSvc.get_user_neighbors_url user_name, (url) ->
$http.get(url).success(on_success).error(on_error)
deferred.promise
get_user_info: (user_name) ->
deferred = $q.defer()
on_success = (data, status, headers, config) =>
if data.user
for key, value of new LastfmUser(data.user)
@user[key] = value
deferred.resolve()
on_error = (data, status, headers, config) =>
deferred.reject
name: 'error_response'
data: data
status: status
headers: headers
config: config
LastfmSvc.get_user_info_url user_name, (url) ->
$http.get(url).success(on_success).error(on_error)
deferred.promise
get_charts_after_cutoff_date: (charts_data, cutoff_date) ->
charts = charts_data.map (data) -> new LastfmChart(data)
charts.filter (chart) -> chart.to_date() >= cutoff_date
get_weekly_chart_list_after_date: (user, cutoff_date) ->
deferred = $q.defer()
on_success = (data, status, headers, config) =>
if data.weeklychartlist
charts_data = data.weeklychartlist.chart.slice(0).reverse()
charts = @get_charts_after_cutoff_date(charts_data, cutoff_date)
@initialize_year_charts charts
deferred.resolve()
else if data.error
deferred.reject({name: data.error})
@load_status.charts = true
on_error = (data, status, headers, config) =>
deferred.reject
name: 'error_response'
data: data
status: status
headers: headers
config: config
@load_status.charts = true
LastfmSvc.get_weekly_chart_list_url user, (url) ->
$http.get(url).success(on_success).error(on_error)
deferred.promise
get_weekly_track_chart: (user, chart) ->
deferred = $q.defer()
storage_key = PI:KEY:<KEY>END_PIchart.from}_PI:KEY:<KEY>END_PIchart.to}"
stored_tracks = localStorageService.get(storage_key)
if stored_tracks
for track in stored_tracks
chart.tracks.push(track)
deferred.resolve()
else
on_success = (data) =>
if data.weeklytrackchart.track
for track_data in data.weeklytrackchart.track
chart.tracks.push(new LastfmTrack(track_data))
localStorageService.set(storage_key, JSON.stringify(chart.tracks))
deferred.resolve()
else if data.error
deferred.reject({name: data.error})
else
deferred.resolve()
on_error = (data, status, headers, config) ->
deferred.reject
name: 'error_response'
data: data
status: status
headers: headers
config: config
LastfmSvc.get_weekly_track_chart_url user, chart, (url) ->
$http.get(url).success(on_success).error(on_error)
deferred.promise
new LastfmCharts()
|
[
{
"context": "Info\":\n message: \"authInfo\"\n data: \"knowuh@gmail.com\"\n \"extendedSupport\": false\n \"supportedF",
"end": 4025,
"score": 0.9999227523803711,
"start": 4009,
"tag": "EMAIL",
"value": "knowuh@gmail.com"
}
] | src/code/app.coffee | concord-consortium/lara-interactive-api | 1 | l = (require './log').instance()
_ = (require 'lodash')
iframePhone = require 'iframe-phone'
class App
constructor: () ->
@setUpButtons()
@bindShutterbug()
@setupInputWatchers()
@restartPhone($("#interactive-iframe"))
@globalState = {}
setSource: (src) ->
$src = $("#interactiveSource")
$iframe = $("#interactive-iframe")
@src = src
$src[0].value = @src
$iframe.attr('src', @src)
@restartPhone($("#interactive-iframe"))
setupInputWatchers: () ->
$src = $("#interactiveSource")
$iframe = $("#interactive-iframe")
@setSource($iframe.attr('src'))
$src.change (e) =>
@setSource(e.target.value)
$(".interactiveLink").click (e) =>
e.preventDefault()
@setSource($(e.target).attr('href'))
setUpButtons: () ->
buttons =
"initInteractive": (e) =>
value = $('#dataOut').val()
obj = JSON.parse(value) # TODO This has to be an object...
@post "initInteractive", obj
"saveInteractive": (e) =>
@post "getInteractiveState"
"loadInteractive": (e) =>
value = $('#dataOut').val()
obj = JSON.parse(value) # TODO This has to be an object...
@post "loadInteractive", obj
"getLearnerUrl": (e) =>
@post "getLearnerUrl"
"getExtendedSupport": (e) =>
@post "getExtendedSupport"
"getExtendedSupport": (e) =>
@post "getExtendedSupport"
"loadInteractiveGlobal": (e) =>
value = $('#dataOut').val()
if value.length < 1
value = '{"fake": "data", "for": "you"}'
@post "loadInteractiveGlobal", JSON.parse(value)
# TODO:
# "lara-logging-present": (e) =>
# l.info "getExtendedSupport called"
# @iframePhoneRpc.call message: 'lara-logging-present'
bindButton = (name,f) ->
$elm = $ "##{name}"
$elm.on "click", (e) -> f(e)
bindButton(buttonname, action) for buttonname, action of buttons
##
##
bindShutterbug: ->
source = "#interactive-iframe"
dest = "#snapshot"
$button = $("#takeSnapshot")
$button.click () ->
if window.Shutterbug
Shutterbug.snapshot
selector: source
dstSelector: dest
fail: () ->
l.info("App: snapshot fail")
server: "//snapshot.concord.org/shutterbug"
else
alert "shutterbug.js must be installed on the page"
$button2 = $("#takeSnapshotDev")
$button2.click () ->
if window.Shutterbug
Shutterbug.snapshot
selector: source
dstSelector: dest
fail: () ->
l.info("App: snapshot fail")
server: "//snapshotdev.concord.org/shutterbug"
else
alert "shutterbug.js must be installed on the page"
##
##
restartPhone: ($iframe) ->
if @iframePhone
@iframePhone.disconnect()
@iframePhone = null
@queue = []
@already_setup = false
@iframePhone = new iframePhone.ParentEndpoint($iframe[0], @phoneAnswered.bind(@))
# TODO: (rpc)
# @iframePhoneRpc = new iframePhone.IframePhoneRpcEndpoint
# phone: @iframePhone
# namespace: 'lara-logging'
##
##
phoneAnswered: ->
if @already_setup
l.info("App: phone rang, but I already answerd")
else
l.info("App: phone answered")
@already_setup = true
@registerHandlers()
##
##
registerHandlers: ->
setupMessage = (inboundMessage, response) =>
@iframePhone.addListener inboundMessage, (data) =>
l.info "App: #{inboundMessage} called with: #{JSON.stringify(data)}"
$('#dataIn').html JSON.stringify(data, null, " ")
if response and response.message
@iframePhone.post(response.message,response.data)
if response and response.handler
response.handler(data)
messageHandlers =
"setLearnerUrl": false
"interactiveState": false
"authoredState": false
"getAuthInfo":
message: "authInfo"
data: "knowuh@gmail.com"
"extendedSupport": false
"supportedFeatures": false
"interactiveStateGlobal":
handler: (data) =>
@globalState = _.extend(@globalState,data)
setupMessage(inboundMessage,response) for inboundMessage,response of messageHandlers
@already_setup = true
@post(msg.msg, msg.data) for msg in @queue
##
##
post: (msg,data) ->
if @already_setup
l.info("App: posting message #{msg} #{JSON.stringify data}")
@iframePhone.post(msg,data)
else
l.info("App: queueing message #{msg} #{JSON.stringify data}")
@queue.push
'msg': msg
'data': data
window.App = App
module.exports = App
| 26048 | l = (require './log').instance()
_ = (require 'lodash')
iframePhone = require 'iframe-phone'
class App
constructor: () ->
@setUpButtons()
@bindShutterbug()
@setupInputWatchers()
@restartPhone($("#interactive-iframe"))
@globalState = {}
setSource: (src) ->
$src = $("#interactiveSource")
$iframe = $("#interactive-iframe")
@src = src
$src[0].value = @src
$iframe.attr('src', @src)
@restartPhone($("#interactive-iframe"))
setupInputWatchers: () ->
$src = $("#interactiveSource")
$iframe = $("#interactive-iframe")
@setSource($iframe.attr('src'))
$src.change (e) =>
@setSource(e.target.value)
$(".interactiveLink").click (e) =>
e.preventDefault()
@setSource($(e.target).attr('href'))
setUpButtons: () ->
buttons =
"initInteractive": (e) =>
value = $('#dataOut').val()
obj = JSON.parse(value) # TODO This has to be an object...
@post "initInteractive", obj
"saveInteractive": (e) =>
@post "getInteractiveState"
"loadInteractive": (e) =>
value = $('#dataOut').val()
obj = JSON.parse(value) # TODO This has to be an object...
@post "loadInteractive", obj
"getLearnerUrl": (e) =>
@post "getLearnerUrl"
"getExtendedSupport": (e) =>
@post "getExtendedSupport"
"getExtendedSupport": (e) =>
@post "getExtendedSupport"
"loadInteractiveGlobal": (e) =>
value = $('#dataOut').val()
if value.length < 1
value = '{"fake": "data", "for": "you"}'
@post "loadInteractiveGlobal", JSON.parse(value)
# TODO:
# "lara-logging-present": (e) =>
# l.info "getExtendedSupport called"
# @iframePhoneRpc.call message: 'lara-logging-present'
bindButton = (name,f) ->
$elm = $ "##{name}"
$elm.on "click", (e) -> f(e)
bindButton(buttonname, action) for buttonname, action of buttons
##
##
bindShutterbug: ->
source = "#interactive-iframe"
dest = "#snapshot"
$button = $("#takeSnapshot")
$button.click () ->
if window.Shutterbug
Shutterbug.snapshot
selector: source
dstSelector: dest
fail: () ->
l.info("App: snapshot fail")
server: "//snapshot.concord.org/shutterbug"
else
alert "shutterbug.js must be installed on the page"
$button2 = $("#takeSnapshotDev")
$button2.click () ->
if window.Shutterbug
Shutterbug.snapshot
selector: source
dstSelector: dest
fail: () ->
l.info("App: snapshot fail")
server: "//snapshotdev.concord.org/shutterbug"
else
alert "shutterbug.js must be installed on the page"
##
##
restartPhone: ($iframe) ->
if @iframePhone
@iframePhone.disconnect()
@iframePhone = null
@queue = []
@already_setup = false
@iframePhone = new iframePhone.ParentEndpoint($iframe[0], @phoneAnswered.bind(@))
# TODO: (rpc)
# @iframePhoneRpc = new iframePhone.IframePhoneRpcEndpoint
# phone: @iframePhone
# namespace: 'lara-logging'
##
##
phoneAnswered: ->
if @already_setup
l.info("App: phone rang, but I already answerd")
else
l.info("App: phone answered")
@already_setup = true
@registerHandlers()
##
##
registerHandlers: ->
setupMessage = (inboundMessage, response) =>
@iframePhone.addListener inboundMessage, (data) =>
l.info "App: #{inboundMessage} called with: #{JSON.stringify(data)}"
$('#dataIn').html JSON.stringify(data, null, " ")
if response and response.message
@iframePhone.post(response.message,response.data)
if response and response.handler
response.handler(data)
messageHandlers =
"setLearnerUrl": false
"interactiveState": false
"authoredState": false
"getAuthInfo":
message: "authInfo"
data: "<EMAIL>"
"extendedSupport": false
"supportedFeatures": false
"interactiveStateGlobal":
handler: (data) =>
@globalState = _.extend(@globalState,data)
setupMessage(inboundMessage,response) for inboundMessage,response of messageHandlers
@already_setup = true
@post(msg.msg, msg.data) for msg in @queue
##
##
post: (msg,data) ->
if @already_setup
l.info("App: posting message #{msg} #{JSON.stringify data}")
@iframePhone.post(msg,data)
else
l.info("App: queueing message #{msg} #{JSON.stringify data}")
@queue.push
'msg': msg
'data': data
window.App = App
module.exports = App
| true | l = (require './log').instance()
_ = (require 'lodash')
iframePhone = require 'iframe-phone'
class App
constructor: () ->
@setUpButtons()
@bindShutterbug()
@setupInputWatchers()
@restartPhone($("#interactive-iframe"))
@globalState = {}
setSource: (src) ->
$src = $("#interactiveSource")
$iframe = $("#interactive-iframe")
@src = src
$src[0].value = @src
$iframe.attr('src', @src)
@restartPhone($("#interactive-iframe"))
setupInputWatchers: () ->
$src = $("#interactiveSource")
$iframe = $("#interactive-iframe")
@setSource($iframe.attr('src'))
$src.change (e) =>
@setSource(e.target.value)
$(".interactiveLink").click (e) =>
e.preventDefault()
@setSource($(e.target).attr('href'))
setUpButtons: () ->
buttons =
"initInteractive": (e) =>
value = $('#dataOut').val()
obj = JSON.parse(value) # TODO This has to be an object...
@post "initInteractive", obj
"saveInteractive": (e) =>
@post "getInteractiveState"
"loadInteractive": (e) =>
value = $('#dataOut').val()
obj = JSON.parse(value) # TODO This has to be an object...
@post "loadInteractive", obj
"getLearnerUrl": (e) =>
@post "getLearnerUrl"
"getExtendedSupport": (e) =>
@post "getExtendedSupport"
"getExtendedSupport": (e) =>
@post "getExtendedSupport"
"loadInteractiveGlobal": (e) =>
value = $('#dataOut').val()
if value.length < 1
value = '{"fake": "data", "for": "you"}'
@post "loadInteractiveGlobal", JSON.parse(value)
# TODO:
# "lara-logging-present": (e) =>
# l.info "getExtendedSupport called"
# @iframePhoneRpc.call message: 'lara-logging-present'
bindButton = (name,f) ->
$elm = $ "##{name}"
$elm.on "click", (e) -> f(e)
bindButton(buttonname, action) for buttonname, action of buttons
##
##
bindShutterbug: ->
source = "#interactive-iframe"
dest = "#snapshot"
$button = $("#takeSnapshot")
$button.click () ->
if window.Shutterbug
Shutterbug.snapshot
selector: source
dstSelector: dest
fail: () ->
l.info("App: snapshot fail")
server: "//snapshot.concord.org/shutterbug"
else
alert "shutterbug.js must be installed on the page"
$button2 = $("#takeSnapshotDev")
$button2.click () ->
if window.Shutterbug
Shutterbug.snapshot
selector: source
dstSelector: dest
fail: () ->
l.info("App: snapshot fail")
server: "//snapshotdev.concord.org/shutterbug"
else
alert "shutterbug.js must be installed on the page"
##
##
restartPhone: ($iframe) ->
if @iframePhone
@iframePhone.disconnect()
@iframePhone = null
@queue = []
@already_setup = false
@iframePhone = new iframePhone.ParentEndpoint($iframe[0], @phoneAnswered.bind(@))
# TODO: (rpc)
# @iframePhoneRpc = new iframePhone.IframePhoneRpcEndpoint
# phone: @iframePhone
# namespace: 'lara-logging'
##
##
phoneAnswered: ->
if @already_setup
l.info("App: phone rang, but I already answerd")
else
l.info("App: phone answered")
@already_setup = true
@registerHandlers()
##
##
registerHandlers: ->
setupMessage = (inboundMessage, response) =>
@iframePhone.addListener inboundMessage, (data) =>
l.info "App: #{inboundMessage} called with: #{JSON.stringify(data)}"
$('#dataIn').html JSON.stringify(data, null, " ")
if response and response.message
@iframePhone.post(response.message,response.data)
if response and response.handler
response.handler(data)
messageHandlers =
"setLearnerUrl": false
"interactiveState": false
"authoredState": false
"getAuthInfo":
message: "authInfo"
data: "PI:EMAIL:<EMAIL>END_PI"
"extendedSupport": false
"supportedFeatures": false
"interactiveStateGlobal":
handler: (data) =>
@globalState = _.extend(@globalState,data)
setupMessage(inboundMessage,response) for inboundMessage,response of messageHandlers
@already_setup = true
@post(msg.msg, msg.data) for msg in @queue
##
##
post: (msg,data) ->
if @already_setup
l.info("App: posting message #{msg} #{JSON.stringify data}")
@iframePhone.post(msg,data)
else
l.info("App: queueing message #{msg} #{JSON.stringify data}")
@queue.push
'msg': msg
'data': data
window.App = App
module.exports = App
|
[
{
"context": "###\n * @author \t\tAbdelhakim RAFIK\n * @version \tv1.0.1\n * @license \tMIT License\n * @",
"end": 33,
"score": 0.9998891949653625,
"start": 17,
"tag": "NAME",
"value": "Abdelhakim RAFIK"
},
{
"context": "nse \tMIT License\n * @copyright \tCopyright (c) 2021 Abdelhaki... | src/app/models/pharmacy.coffee | AbdelhakimRafik/Pharmalogy-API | 0 | ###
* @author Abdelhakim RAFIK
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 Abdelhakim RAFIK
* @date Mar 2021
###
{ DataTypes, Model } = require 'sequelize'
{ sequelize } = require '../../database'
User = require './user'
###
Pharmacy model
###
module.exports = Pharmacy = sequelize.define 'Pharmacy',
name:
allowNull: false
type: DataTypes.STRING
addresse:
type: DataTypes.STRING
email:
type: DataTypes.STRING
webSite:
type: DataTypes.STRING
phone:
type: DataTypes.STRING 10
city:
allowNull: false,
type: DataTypes.STRING
country:
allowNull: false,
type: DataTypes.STRING
longitude:
allowNull: false
type: DataTypes.DOUBLE
latitude:
allowNull: false
type: DataTypes.DOUBLE
image:
allowNull: true
type: DataTypes.STRING
status:
allowNull: false
type: DataTypes.BOOLEAN
defaultValue: false
createdAt:
allowNull: false
type: DataTypes.DATE
updatedAt:
allowNull: false
type: DataTypes.DATE
,
# define table name in database
tableName: 'pharmacies'
# create pharmacy - users association
# Pharmacy.hasMany User,
# foreignKey: 'pharmacy' | 98418 | ###
* @author <NAME>
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 <NAME>
* @date Mar 2021
###
{ DataTypes, Model } = require 'sequelize'
{ sequelize } = require '../../database'
User = require './user'
###
Pharmacy model
###
module.exports = Pharmacy = sequelize.define 'Pharmacy',
name:
allowNull: false
type: DataTypes.STRING
addresse:
type: DataTypes.STRING
email:
type: DataTypes.STRING
webSite:
type: DataTypes.STRING
phone:
type: DataTypes.STRING 10
city:
allowNull: false,
type: DataTypes.STRING
country:
allowNull: false,
type: DataTypes.STRING
longitude:
allowNull: false
type: DataTypes.DOUBLE
latitude:
allowNull: false
type: DataTypes.DOUBLE
image:
allowNull: true
type: DataTypes.STRING
status:
allowNull: false
type: DataTypes.BOOLEAN
defaultValue: false
createdAt:
allowNull: false
type: DataTypes.DATE
updatedAt:
allowNull: false
type: DataTypes.DATE
,
# define table name in database
tableName: 'pharmacies'
# create pharmacy - users association
# Pharmacy.hasMany User,
# foreignKey: 'pharmacy' | true | ###
* @author PI:NAME:<NAME>END_PI
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 PI:NAME:<NAME>END_PI
* @date Mar 2021
###
{ DataTypes, Model } = require 'sequelize'
{ sequelize } = require '../../database'
User = require './user'
###
Pharmacy model
###
module.exports = Pharmacy = sequelize.define 'Pharmacy',
name:
allowNull: false
type: DataTypes.STRING
addresse:
type: DataTypes.STRING
email:
type: DataTypes.STRING
webSite:
type: DataTypes.STRING
phone:
type: DataTypes.STRING 10
city:
allowNull: false,
type: DataTypes.STRING
country:
allowNull: false,
type: DataTypes.STRING
longitude:
allowNull: false
type: DataTypes.DOUBLE
latitude:
allowNull: false
type: DataTypes.DOUBLE
image:
allowNull: true
type: DataTypes.STRING
status:
allowNull: false
type: DataTypes.BOOLEAN
defaultValue: false
createdAt:
allowNull: false
type: DataTypes.DATE
updatedAt:
allowNull: false
type: DataTypes.DATE
,
# define table name in database
tableName: 'pharmacies'
# create pharmacy - users association
# Pharmacy.hasMany User,
# foreignKey: 'pharmacy' |
[
{
"context": "ration = {}\nconfiguration[nerfed + \"username\"] = \"username\"\nconfiguration[nerfed + \"_password\"] = new Buffer",
"end": 203,
"score": 0.9993883371353149,
"start": 195,
"tag": "USERNAME",
"value": "username"
},
{
"context": "\"\nconfiguration[nerfed + \"_password\"... | deps/npm/node_modules/npm-registry-client/test/tag.coffee | lxe/io.coffee | 0 | tap = require("tap")
server = require("./lib/server.js")
common = require("./lib/common.js")
nerfed = "//localhost:" + server.port + "/:"
configuration = {}
configuration[nerfed + "username"] = "username"
configuration[nerfed + "_password"] = new Buffer("%1234@asdf%").toString("base64")
configuration[nerfed + "email"] = "i@izs.me"
client = common.freshClient(configuration)
tap.test "tag a package", (t) ->
server.expect "PUT", "/underscore/not-lodash", (req, res) ->
t.equal req.method, "PUT"
b = ""
req.setEncoding "utf8"
req.on "data", (d) ->
b += d
return
req.on "end", ->
updated = JSON.parse(b)
t.deepEqual updated,
"1.3.2": {}
res.statusCode = 201
res.json tagged: true
return
return
client.tag "http://localhost:1337/underscore",
"1.3.2": {}
, "not-lodash", (error, data) ->
t.ifError error, "no errors"
t.ok data.tagged, "was tagged"
t.end()
return
return
| 167189 | tap = require("tap")
server = require("./lib/server.js")
common = require("./lib/common.js")
nerfed = "//localhost:" + server.port + "/:"
configuration = {}
configuration[nerfed + "username"] = "username"
configuration[nerfed + "_password"] = new Buffer("<PASSWORD>%").toString("base64")
configuration[nerfed + "email"] = "<EMAIL>"
client = common.freshClient(configuration)
tap.test "tag a package", (t) ->
server.expect "PUT", "/underscore/not-lodash", (req, res) ->
t.equal req.method, "PUT"
b = ""
req.setEncoding "utf8"
req.on "data", (d) ->
b += d
return
req.on "end", ->
updated = JSON.parse(b)
t.deepEqual updated,
"1.3.2": {}
res.statusCode = 201
res.json tagged: true
return
return
client.tag "http://localhost:1337/underscore",
"1.3.2": {}
, "not-lodash", (error, data) ->
t.ifError error, "no errors"
t.ok data.tagged, "was tagged"
t.end()
return
return
| true | tap = require("tap")
server = require("./lib/server.js")
common = require("./lib/common.js")
nerfed = "//localhost:" + server.port + "/:"
configuration = {}
configuration[nerfed + "username"] = "username"
configuration[nerfed + "_password"] = new Buffer("PI:PASSWORD:<PASSWORD>END_PI%").toString("base64")
configuration[nerfed + "email"] = "PI:EMAIL:<EMAIL>END_PI"
client = common.freshClient(configuration)
tap.test "tag a package", (t) ->
server.expect "PUT", "/underscore/not-lodash", (req, res) ->
t.equal req.method, "PUT"
b = ""
req.setEncoding "utf8"
req.on "data", (d) ->
b += d
return
req.on "end", ->
updated = JSON.parse(b)
t.deepEqual updated,
"1.3.2": {}
res.statusCode = 201
res.json tagged: true
return
return
client.tag "http://localhost:1337/underscore",
"1.3.2": {}
, "not-lodash", (error, data) ->
t.ifError error, "no errors"
t.ok data.tagged, "was tagged"
t.end()
return
return
|
[
{
"context": "y(\n usernameField: 'email'\n passwordField: 'password' # this is the virtual field on the model\n , (em",
"end": 205,
"score": 0.998004138469696,
"start": 197,
"tag": "PASSWORD",
"value": "password"
}
] | server/auth/local/passport.coffee | harryoh/node-dd-shortener | 0 | passport = require 'passport'
LocalStrategy = require('passport-local').Strategy
exports.setup = (User, config) ->
passport.use new LocalStrategy(
usernameField: 'email'
passwordField: 'password' # this is the virtual field on the model
, (email, password, done) ->
User.findOne
email: email.toLowerCase()
, (err, user) ->
return done(err) if err
if not user
return done(null, false,
message: 'This email is not registered.'
)
unless user.authenticate(password)
return done(null, false,
message: 'This password is not correct.'
)
done null, user
)
| 24288 | passport = require 'passport'
LocalStrategy = require('passport-local').Strategy
exports.setup = (User, config) ->
passport.use new LocalStrategy(
usernameField: 'email'
passwordField: '<PASSWORD>' # this is the virtual field on the model
, (email, password, done) ->
User.findOne
email: email.toLowerCase()
, (err, user) ->
return done(err) if err
if not user
return done(null, false,
message: 'This email is not registered.'
)
unless user.authenticate(password)
return done(null, false,
message: 'This password is not correct.'
)
done null, user
)
| true | passport = require 'passport'
LocalStrategy = require('passport-local').Strategy
exports.setup = (User, config) ->
passport.use new LocalStrategy(
usernameField: 'email'
passwordField: 'PI:PASSWORD:<PASSWORD>END_PI' # this is the virtual field on the model
, (email, password, done) ->
User.findOne
email: email.toLowerCase()
, (err, user) ->
return done(err) if err
if not user
return done(null, false,
message: 'This email is not registered.'
)
unless user.authenticate(password)
return done(null, false,
message: 'This password is not correct.'
)
done null, user
)
|
[
{
"context": "get.min.js\n###\n\n###* @preserve https://github.com/NateShoffner/github-widget\nModified work Copyright (c) 2016 Na",
"end": 232,
"score": 0.9973659515380859,
"start": 220,
"tag": "USERNAME",
"value": "NateShoffner"
},
{
"context": "ner/github-widget\nModified work Cop... | vendor/ns-github-widget/github-widget.coffee | Zenahr/personal-main-website | 0 | ###
# to minify:
java -jar /usr/local/closure-compiler/compiler.jar \
--compilation_level SIMPLE_OPTIMIZATIONS \
--js github-widget.js \
--js_output_file github-widget.min.js
###
###* @preserve https://github.com/NateShoffner/github-widget
Modified work Copyright (c) 2016 Nate Shoffner
Original work Copyright (c) 2011 - 2012 George MacKerron
Released under the MIT licence: http://opensource.org/licenses/mit-license ###
makeWidget = (repos, div, opts) ->
make cls: 'gw-clearer', prevSib: div
for repo in repos
make parent: div, cls: 'gw-repo-outer', kids: [
make cls: 'gw-repo', kids: [
make cls: 'gw-title', kids: [
make tag: 'ul', cls: 'gw-stats', kids: [
make tag: 'li', text: repo.watchers, cls: 'gw-watchers'
make tag: 'li', text: repo.forks, cls: 'gw-forks']
make tag: 'a', href: repo.html_url, text: repo.name, cls: 'gw-name']
make cls: 'gw-lang', text: if repo.language? then repo.language else "Unknown Language"
make cls: 'gw-repo-desc', text: if repo.description? then repo.description else "No description available"
if opts.websiteLinks and repo.homepage?
make cls: 'gw-homepage', kids: [
make tag: 'a', href: repo.homepage, text: 'Homepage']]]
datetimeRegex = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/
@initialize_github_widgets = ->
for div in (get tag: 'div', cls: 'github-widget')
initialize_github_widget(div)
@initialize_github_widget = (div) ->
do (div) -> # close over correct div
# remove existing repo nodes
repo_nodes = div.getElementsByClassName('gw-repo-outer')
while (repo_nodes[0])
repo_nodes[0].parentNode.removeChild(repo_nodes[0]);
users = (div.getAttribute 'data-user').split ','
opts = div.getAttribute 'data-options'
opts = if typeof opts is 'string' then JSON.parse(opts) else {}
sortBy = opts.sortBy or 'watchers'
limit = parseInt(opts.limit) or Infinity
per_page = parseInt(opts.per_page) or 100
repos = []
userCount = 0
for user in users
url = "https://api.github.com/users/#{user}/repos?callback=<cb>&per_page=" + per_page
jsonp url: url, success: (payload) ->
if payload.data.length > 0
first_repo = payload.data[0]
userName = first_repo.owner.login
siteRepoNames = ["#{userName}.github.com".toLowerCase(), "#{userName}.github.io".toLowerCase()]
for repo in payload.data
continue if (not opts.forks and repo.fork) or (not opts.pages and repo.name.toLowerCase() in siteRepoNames)
repos.push repo
userCount++
if userCount is users.length and repos.length > 0
if datetimeRegex.test(repos[0][sortBy])
repos = repos.sort((a, b) -> new Date(b[sortBy])-new Date(a[sortBy]))
else
repos = repos.sort((a, b) -> b[sortBy] - a[sortBy])
repos = repos[0..limit - 1]
makeWidget repos, div, opts
# support functions
cls = (el, opts = {}) -> # cut-down version: no manipulation support
classHash = {}
classes = el.className.match(cls.re)
if classes?
(classHash[c] = yes) for c in classes
hasClasses = opts.has?.match(cls.re)
if hasClasses?
(return no unless classHash[c]) for c in hasClasses
return yes
null
cls.re = /\S+/g
get = (opts = {}) ->
inside = opts.inside ? document
tag = opts.tag ? '*'
if opts.id?
return inside.getElementById opts.id
hasCls = opts.cls?
if hasCls and tag is '*' and inside.getElementsByClassName?
return inside.getElementsByClassName opts.cls
els = inside.getElementsByTagName tag
if hasCls then els = (el for el in els when cls el, has: opts.cls)
if not opts.multi? and tag.toLowerCase() in get.uniqueTags then els[0] ? null else els
get.uniqueTags = 'html body frameset head title base'.split(' ')
text = (t) -> document.createTextNode '' + t
make = (opts = {}) -> # opts: tag, parent, prevSib, text, cls, [attrib]
t = document.createElement opts.tag ? 'div'
for own k, v of opts
switch k
when 'tag' then continue
when 'parent' then v.appendChild t
when 'kids' then t.appendChild c for c in v when c?
when 'prevSib' then v.parentNode.insertBefore t, v.nextSibling
when 'text' then t.appendChild text v
when 'cls' then t.className = v
else t[k] = v
t
jsonp = (opts) ->
callbackName = opts.callback ? '_JSONPCallback_' + jsonp.callbackNum++
url = opts.url.replace '<cb>', callbackName
window[callbackName] = opts.success ? jsonp.noop
make tag: 'script', src: url, parent: (get tag: 'head')
jsonp.callbackNum = 0
jsonp.noop = -> | 186156 | ###
# to minify:
java -jar /usr/local/closure-compiler/compiler.jar \
--compilation_level SIMPLE_OPTIMIZATIONS \
--js github-widget.js \
--js_output_file github-widget.min.js
###
###* @preserve https://github.com/NateShoffner/github-widget
Modified work Copyright (c) 2016 <NAME>
Original work Copyright (c) 2011 - 2012 <NAME>
Released under the MIT licence: http://opensource.org/licenses/mit-license ###
makeWidget = (repos, div, opts) ->
make cls: 'gw-clearer', prevSib: div
for repo in repos
make parent: div, cls: 'gw-repo-outer', kids: [
make cls: 'gw-repo', kids: [
make cls: 'gw-title', kids: [
make tag: 'ul', cls: 'gw-stats', kids: [
make tag: 'li', text: repo.watchers, cls: 'gw-watchers'
make tag: 'li', text: repo.forks, cls: 'gw-forks']
make tag: 'a', href: repo.html_url, text: repo.name, cls: 'gw-name']
make cls: 'gw-lang', text: if repo.language? then repo.language else "Unknown Language"
make cls: 'gw-repo-desc', text: if repo.description? then repo.description else "No description available"
if opts.websiteLinks and repo.homepage?
make cls: 'gw-homepage', kids: [
make tag: 'a', href: repo.homepage, text: 'Homepage']]]
datetimeRegex = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/
@initialize_github_widgets = ->
for div in (get tag: 'div', cls: 'github-widget')
initialize_github_widget(div)
@initialize_github_widget = (div) ->
do (div) -> # close over correct div
# remove existing repo nodes
repo_nodes = div.getElementsByClassName('gw-repo-outer')
while (repo_nodes[0])
repo_nodes[0].parentNode.removeChild(repo_nodes[0]);
users = (div.getAttribute 'data-user').split ','
opts = div.getAttribute 'data-options'
opts = if typeof opts is 'string' then JSON.parse(opts) else {}
sortBy = opts.sortBy or 'watchers'
limit = parseInt(opts.limit) or Infinity
per_page = parseInt(opts.per_page) or 100
repos = []
userCount = 0
for user in users
url = "https://api.github.com/users/#{user}/repos?callback=<cb>&per_page=" + per_page
jsonp url: url, success: (payload) ->
if payload.data.length > 0
first_repo = payload.data[0]
userName = first_repo.owner.login
siteRepoNames = ["#{userName}.github.com".toLowerCase(), "#{userName}.github.io".toLowerCase()]
for repo in payload.data
continue if (not opts.forks and repo.fork) or (not opts.pages and repo.name.toLowerCase() in siteRepoNames)
repos.push repo
userCount++
if userCount is users.length and repos.length > 0
if datetimeRegex.test(repos[0][sortBy])
repos = repos.sort((a, b) -> new Date(b[sortBy])-new Date(a[sortBy]))
else
repos = repos.sort((a, b) -> b[sortBy] - a[sortBy])
repos = repos[0..limit - 1]
makeWidget repos, div, opts
# support functions
cls = (el, opts = {}) -> # cut-down version: no manipulation support
classHash = {}
classes = el.className.match(cls.re)
if classes?
(classHash[c] = yes) for c in classes
hasClasses = opts.has?.match(cls.re)
if hasClasses?
(return no unless classHash[c]) for c in hasClasses
return yes
null
cls.re = /\S+/g
get = (opts = {}) ->
inside = opts.inside ? document
tag = opts.tag ? '*'
if opts.id?
return inside.getElementById opts.id
hasCls = opts.cls?
if hasCls and tag is '*' and inside.getElementsByClassName?
return inside.getElementsByClassName opts.cls
els = inside.getElementsByTagName tag
if hasCls then els = (el for el in els when cls el, has: opts.cls)
if not opts.multi? and tag.toLowerCase() in get.uniqueTags then els[0] ? null else els
get.uniqueTags = 'html body frameset head title base'.split(' ')
text = (t) -> document.createTextNode '' + t
make = (opts = {}) -> # opts: tag, parent, prevSib, text, cls, [attrib]
t = document.createElement opts.tag ? 'div'
for own k, v of opts
switch k
when 'tag' then continue
when 'parent' then v.appendChild t
when 'kids' then t.appendChild c for c in v when c?
when 'prevSib' then v.parentNode.insertBefore t, v.nextSibling
when 'text' then t.appendChild text v
when 'cls' then t.className = v
else t[k] = v
t
jsonp = (opts) ->
callbackName = opts.callback ? '_JSONPCallback_' + jsonp.callbackNum++
url = opts.url.replace '<cb>', callbackName
window[callbackName] = opts.success ? jsonp.noop
make tag: 'script', src: url, parent: (get tag: 'head')
jsonp.callbackNum = 0
jsonp.noop = -> | true | ###
# to minify:
java -jar /usr/local/closure-compiler/compiler.jar \
--compilation_level SIMPLE_OPTIMIZATIONS \
--js github-widget.js \
--js_output_file github-widget.min.js
###
###* @preserve https://github.com/NateShoffner/github-widget
Modified work Copyright (c) 2016 PI:NAME:<NAME>END_PI
Original work Copyright (c) 2011 - 2012 PI:NAME:<NAME>END_PI
Released under the MIT licence: http://opensource.org/licenses/mit-license ###
makeWidget = (repos, div, opts) ->
make cls: 'gw-clearer', prevSib: div
for repo in repos
make parent: div, cls: 'gw-repo-outer', kids: [
make cls: 'gw-repo', kids: [
make cls: 'gw-title', kids: [
make tag: 'ul', cls: 'gw-stats', kids: [
make tag: 'li', text: repo.watchers, cls: 'gw-watchers'
make tag: 'li', text: repo.forks, cls: 'gw-forks']
make tag: 'a', href: repo.html_url, text: repo.name, cls: 'gw-name']
make cls: 'gw-lang', text: if repo.language? then repo.language else "Unknown Language"
make cls: 'gw-repo-desc', text: if repo.description? then repo.description else "No description available"
if opts.websiteLinks and repo.homepage?
make cls: 'gw-homepage', kids: [
make tag: 'a', href: repo.homepage, text: 'Homepage']]]
datetimeRegex = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/
@initialize_github_widgets = ->
for div in (get tag: 'div', cls: 'github-widget')
initialize_github_widget(div)
@initialize_github_widget = (div) ->
do (div) -> # close over correct div
# remove existing repo nodes
repo_nodes = div.getElementsByClassName('gw-repo-outer')
while (repo_nodes[0])
repo_nodes[0].parentNode.removeChild(repo_nodes[0]);
users = (div.getAttribute 'data-user').split ','
opts = div.getAttribute 'data-options'
opts = if typeof opts is 'string' then JSON.parse(opts) else {}
sortBy = opts.sortBy or 'watchers'
limit = parseInt(opts.limit) or Infinity
per_page = parseInt(opts.per_page) or 100
repos = []
userCount = 0
for user in users
url = "https://api.github.com/users/#{user}/repos?callback=<cb>&per_page=" + per_page
jsonp url: url, success: (payload) ->
if payload.data.length > 0
first_repo = payload.data[0]
userName = first_repo.owner.login
siteRepoNames = ["#{userName}.github.com".toLowerCase(), "#{userName}.github.io".toLowerCase()]
for repo in payload.data
continue if (not opts.forks and repo.fork) or (not opts.pages and repo.name.toLowerCase() in siteRepoNames)
repos.push repo
userCount++
if userCount is users.length and repos.length > 0
if datetimeRegex.test(repos[0][sortBy])
repos = repos.sort((a, b) -> new Date(b[sortBy])-new Date(a[sortBy]))
else
repos = repos.sort((a, b) -> b[sortBy] - a[sortBy])
repos = repos[0..limit - 1]
makeWidget repos, div, opts
# support functions
cls = (el, opts = {}) -> # cut-down version: no manipulation support
classHash = {}
classes = el.className.match(cls.re)
if classes?
(classHash[c] = yes) for c in classes
hasClasses = opts.has?.match(cls.re)
if hasClasses?
(return no unless classHash[c]) for c in hasClasses
return yes
null
cls.re = /\S+/g
get = (opts = {}) ->
inside = opts.inside ? document
tag = opts.tag ? '*'
if opts.id?
return inside.getElementById opts.id
hasCls = opts.cls?
if hasCls and tag is '*' and inside.getElementsByClassName?
return inside.getElementsByClassName opts.cls
els = inside.getElementsByTagName tag
if hasCls then els = (el for el in els when cls el, has: opts.cls)
if not opts.multi? and tag.toLowerCase() in get.uniqueTags then els[0] ? null else els
get.uniqueTags = 'html body frameset head title base'.split(' ')
text = (t) -> document.createTextNode '' + t
make = (opts = {}) -> # opts: tag, parent, prevSib, text, cls, [attrib]
t = document.createElement opts.tag ? 'div'
for own k, v of opts
switch k
when 'tag' then continue
when 'parent' then v.appendChild t
when 'kids' then t.appendChild c for c in v when c?
when 'prevSib' then v.parentNode.insertBefore t, v.nextSibling
when 'text' then t.appendChild text v
when 'cls' then t.className = v
else t[k] = v
t
jsonp = (opts) ->
callbackName = opts.callback ? '_JSONPCallback_' + jsonp.callbackNum++
url = opts.url.replace '<cb>', callbackName
window[callbackName] = opts.success ? jsonp.noop
make tag: 'script', src: url, parent: (get tag: 'head')
jsonp.callbackNum = 0
jsonp.noop = -> |
[
{
"context": " function called isRussian.\n\n\n# coffee =\n# name: 'Russian'\n# level: 2\n# isRussian: -> @name is 'Russian'\n\nc",
"end": 255,
"score": 0.9781309962272644,
"start": 248,
"tag": "NAME",
"value": "Russian"
},
{
"context": "Russian: -> @name is 'Russian'\n\ncoffee =\n ... | learn-coffee-script/Level 6/06-01 Classes Part I.coffee | roycetech/learn-js | 0 | # Create a Coffee class that will produce coffee objects. In that class, create a constructor that takes name and level as arguments and sets them as instance variables. Also, make sure you create a function called isRussian.
# coffee =
# name: 'Russian'
# level: 2
# isRussian: -> @name is 'Russian'
coffee =
name: 'Russian'
level: 2
isRussian: -> @name is 'Russian'
class Coffee
constructor: (@name, @level) ->
isRussian: -> @name is 'Russian'
| 91240 | # Create a Coffee class that will produce coffee objects. In that class, create a constructor that takes name and level as arguments and sets them as instance variables. Also, make sure you create a function called isRussian.
# coffee =
# name: '<NAME>'
# level: 2
# isRussian: -> @name is 'Russian'
coffee =
name: '<NAME>'
level: 2
isRussian: -> @name is 'Russian'
class Coffee
constructor: (@name, @level) ->
isRussian: -> @name is 'Russian'
| true | # Create a Coffee class that will produce coffee objects. In that class, create a constructor that takes name and level as arguments and sets them as instance variables. Also, make sure you create a function called isRussian.
# coffee =
# name: 'PI:NAME:<NAME>END_PI'
# level: 2
# isRussian: -> @name is 'Russian'
coffee =
name: 'PI:NAME:<NAME>END_PI'
level: 2
isRussian: -> @name is 'Russian'
class Coffee
constructor: (@name, @level) ->
isRussian: -> @name is 'Russian'
|
[
{
"context": "\"\n worksheetId: \"od6\"\n oauth:\n email: \"686870306377-e9n4nmb6e13r88qgtjrd7vdfuqjs2q0e@developer.gserviceaccount.com\"\n keyFile: \"outbox.pem\"\n , sheetReady = (er",
"end": 512,
"score": 0.95203697681427,
"start": 437,
"tag": "EMAIL",
"value": "686870306... | ComputerSide/PressTo/Web/Server/devinfo.coffee | tnwinc/PressTo | 0 | Spreadsheet = require('edit-google-spreadsheet')
_ = require 'underscore'
request = require 'request-json'
client = request.newClient 'https://slack.com/'
Secret = require './secret'
Q = require 'q'
module.exports = ()->
payload = []
deferred = Q.defer()
Spreadsheet.load
debug: true
spreadsheetId: '1ha75e_ALAzkkbOv8mp_s5HhD1okQiqGlYKQhckkjHe8'
worksheetName: "People"
worksheetId: "od6"
oauth:
email: "686870306377-e9n4nmb6e13r88qgtjrd7vdfuqjs2q0e@developer.gserviceaccount.com"
keyFile: "outbox.pem"
, sheetReady = (err, spreadsheet)->
throw err if err
spreadsheet.receive (err, rows, info)->
throw err if err
devs = _.filter rows, (row, index)-> index >2 and index < 29
client.get "api/users.list?token=#{Secret.token}", (err, response, profiles)->
_(devs).each (dev, index)->
info =
id: index
name: dev[1]
title: 'not sure what I do :-/'
phone: dev[2]
email: dev[3]
vacation: dev[4]
hangouts_id: dev[6]
imageUrl: null
skype_id: null
memberFound = _(profiles.members).find (member)-> dev[1] is member.profile.real_name_normalized
if memberFound
info.imageUrl = memberFound.profile.image_192
info.skype_id = memberFound.profile.skype
info.title = memberFound.profile.title
payload.push info
sortedPayload = _(payload).sortBy('name')
deferred.resolve sortedPayload
return deferred.promise
| 111919 | Spreadsheet = require('edit-google-spreadsheet')
_ = require 'underscore'
request = require 'request-json'
client = request.newClient 'https://slack.com/'
Secret = require './secret'
Q = require 'q'
module.exports = ()->
payload = []
deferred = Q.defer()
Spreadsheet.load
debug: true
spreadsheetId: '1ha75e_ALAzkkbOv8mp_s5HhD1okQiqGlYKQhckkjHe8'
worksheetName: "People"
worksheetId: "od6"
oauth:
email: "<EMAIL>"
keyFile: "<KEY>"
, sheetReady = (err, spreadsheet)->
throw err if err
spreadsheet.receive (err, rows, info)->
throw err if err
devs = _.filter rows, (row, index)-> index >2 and index < 29
client.get "api/users.list?token=#{Secret.token}", (err, response, profiles)->
_(devs).each (dev, index)->
info =
id: index
name: dev[1]
title: 'not sure what I do :-/'
phone: dev[2]
email: dev[3]
vacation: dev[4]
hangouts_id: dev[6]
imageUrl: null
skype_id: null
memberFound = _(profiles.members).find (member)-> dev[1] is member.profile.real_name_normalized
if memberFound
info.imageUrl = memberFound.profile.image_192
info.skype_id = memberFound.profile.skype
info.title = memberFound.profile.title
payload.push info
sortedPayload = _(payload).sortBy('name')
deferred.resolve sortedPayload
return deferred.promise
| true | Spreadsheet = require('edit-google-spreadsheet')
_ = require 'underscore'
request = require 'request-json'
client = request.newClient 'https://slack.com/'
Secret = require './secret'
Q = require 'q'
module.exports = ()->
payload = []
deferred = Q.defer()
Spreadsheet.load
debug: true
spreadsheetId: '1ha75e_ALAzkkbOv8mp_s5HhD1okQiqGlYKQhckkjHe8'
worksheetName: "People"
worksheetId: "od6"
oauth:
email: "PI:EMAIL:<EMAIL>END_PI"
keyFile: "PI:KEY:<KEY>END_PI"
, sheetReady = (err, spreadsheet)->
throw err if err
spreadsheet.receive (err, rows, info)->
throw err if err
devs = _.filter rows, (row, index)-> index >2 and index < 29
client.get "api/users.list?token=#{Secret.token}", (err, response, profiles)->
_(devs).each (dev, index)->
info =
id: index
name: dev[1]
title: 'not sure what I do :-/'
phone: dev[2]
email: dev[3]
vacation: dev[4]
hangouts_id: dev[6]
imageUrl: null
skype_id: null
memberFound = _(profiles.members).find (member)-> dev[1] is member.profile.real_name_normalized
if memberFound
info.imageUrl = memberFound.profile.image_192
info.skype_id = memberFound.profile.skype
info.title = memberFound.profile.title
payload.push info
sortedPayload = _(payload).sortBy('name')
deferred.resolve sortedPayload
return deferred.promise
|
[
{
"context": "e', ->\n original = @Test.build id: 1, name: 'foobar', 'thing': 'baseclass'\n clone = original.",
"end": 2292,
"score": 0.4378427267074585,
"start": 2286,
"tag": "NAME",
"value": "foobar"
},
{
"context": ", ->\n rawData = '{\"fluffy\": {\"id\": 1, \"name... | spec/joosy/resources/rest_spec.coffee | alexshuhin/joosy | 0 | describe "Joosy.Resources.REST", ->
class FluffyInline extends Joosy.Resources.REST
@entity 'fluffy_inline'
class FluffyParent extends Joosy.Resources.REST
@entity 'fluffy_parent'
class Fluffy extends Joosy.Resources.REST
@entity 'fluffy'
@map 'fluffy_inlines', FluffyInline
class Interpolated extends Joosy.Resources.REST
@entity 'test'
@source '/grand_parents/:grand_parent_id/parents/:parent_id/tests'
Joosy.namespace 'Deeply.Nested', ->
class @Entity extends Joosy.Resources.REST
@entity 'entity'
Joosy.namespace 'Animal', ->
class @Cat extends Joosy.Resources.REST
@entity 'cat'
beforeEach ->
@server = sinon.fakeServer.create()
afterEach ->
@server.restore()
checkAndRespond = (target, method, url, data) ->
expect(target.method).toEqual method
expect(target.url).toMatch url
target.respond 200, 'Content-Type': 'application/json', data
describe '@at', ->
# clone won't be instanceof Fluffy in IE
#expect(clone.build({}) instanceof Fluffy).toBeTruthy()
beforeEach ->
class @Test extends Joosy.Resources.REST
@entity 'test'
it 'returns base class child', ->
clone = @Test.at 'rumbas'
expect(Joosy.Module.hasAncestor(clone, @Test)).toBeTruthy()
it 'accepts string', ->
clone = @Test.at 'rumbas'
expect(clone.collectionPath()).toEqual '/rumbas/tests'
it 'makes a class whose instances get new source too', ->
clone = @Test.at 'rumbas'
expect(clone.build(id: 1).memberPath()).toEqual '/rumbas/tests/1'
it 'accepts another resource instance', ->
clone = @Test.at Fluffy.build(id: 1)
expect(clone.collectionPath()).toEqual '/fluffies/1/tests'
it 'accepts array', ->
clone = @Test.at ['rumbas', Fluffy.build(id: 1), 'salsas']
expect(clone.collectionPath()).toEqual '/rumbas/fluffies/1/salsas/tests'
it 'accepts sequential attributes', ->
clone = @Test.at 'rumbas', 'salsas', Fluffy.build(id: 1)
expect(clone.collectionPath()).toEqual '/rumbas/salsas/fluffies/1/tests'
describe '::at', ->
beforeEach ->
class @Test extends Joosy.Resources.REST
@entity 'test'
it 'returns base class instance', ->
original = @Test.build id: 1, name: 'foobar', 'thing': 'baseclass'
clone = original.at 'rumbas'
expect(clone instanceof @Test).toBeTruthy()
expect(clone.data).toEqual original.data
it 'accepts string', ->
clone = @Test.build(id: 1).at('rumbas')
expect(clone.memberPath()).toEqual '/rumbas/tests/1'
it 'accepts another resource instance', ->
clone = @Test.build(id: 1).at(Fluffy.build(id: 1))
expect(clone.memberPath()).toEqual '/fluffies/1/tests/1'
it 'accepts array', ->
clone = @Test.build(id: 1).at ['rumbas', Fluffy.build(id: 1), 'salsas']
expect(clone.memberPath()).toEqual '/rumbas/fluffies/1/salsas/tests/1'
it 'accepts sequential attributes', ->
clone = @Test.build(id: 1).at 'rumbas', 'salsas', Fluffy.build(id: 1)
expect(clone.memberPath()).toEqual '/rumbas/salsas/fluffies/1/tests/1'
describe '@memberPath', ->
it 'builds member path', ->
expect(Fluffy.memberPath 1).toEqual '/fluffies/1'
it 'builds member path with action', ->
expect(Fluffy.memberPath 1, action: 'test').toEqual '/fluffies/1/test'
describe 'with interpolation', ->
it 'builds member path', ->
expect(Interpolated.memberPath([1,2,3])).toEqual '/grand_parents/1/parents/2/tests/3'
it 'saves member path for single instance', ->
item = Interpolated.find [1,2,3]
checkAndRespond @server.requests[0], 'GET', /^\/grand_parents\/1\/parents\/2\/tests\/3\?_=\d+/, '{"test": {"id": 3}}'
expect(item.memberPath()).toEqual '/grand_parents/1/parents/2/tests/3'
it 'saves member path for instances collection', ->
items = Interpolated.all [1,2]
checkAndRespond @server.requests[0], 'GET', /^\/grand_parents\/1\/parents\/2\/tests\?_=\d+/, '{"tests": [{"test": {"id": 3}}]}'
expect(items[0].memberPath()).toEqual '/grand_parents/1/parents/2/tests/3'
describe '@collectionPath', ->
it 'builds collection path', ->
expect(Fluffy.collectionPath()).toEqual '/fluffies'
it 'builds collection path with action', ->
expect(Fluffy.collectionPath action: 'test').toEqual '/fluffies/test'
describe 'with interpolation', ->
it 'builds collection path', ->
expect(Interpolated.collectionPath([1,2])).toEqual '/grand_parents/1/parents/2/tests'
describe 'with namespace', ->
it 'builds collection path', ->
expect(Deeply.Nested.Entity.collectionPath([1,2])).toEqual '/deeply/nested/entities'
describe '@find(:id)', ->
rawData = '{"fluffy": {"id": 1, "name": "test1"}}'
beforeEach ->
@callback = sinon.spy (error, target, data) ->
expect(target instanceof Fluffy).toEqual true
expect(target.id()).toEqual 1
expect(target.get 'name').toEqual 'test1'
expect(data).toEqual $.parseJSON(rawData)
it "gets item without params", ->
resource = Fluffy.find 1, @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/1\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "gets item with action", ->
resource = Fluffy.find 1, {action: 'action'}, @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/1\/action\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "gets item with params", ->
resource = Fluffy.find 1, params: {foo: 'bar'}, @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/1\?foo=bar&_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "gets item with url", ->
resource = Fluffy.find 1, url: '/some/custom/url', @callback
checkAndRespond @server.requests[0], 'GET', /^\/some\/custom\/url\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "gets item with direct assignation", ->
resource = Fluffy.find 1, (error, cbResource) ->
expect(resource).toBe cbResource
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/1\?_=\d+/, rawData
describe '@all', ->
rawData = '{"page": 42, "fluffies": [{"id": 1, "name": "test1"}, {"id": 2, "name": "test2"}]}'
beforeEach ->
@callback = sinon.spy (error, target, data) ->
expect(target instanceof Joosy.Resources.RESTCollection).toEqual true
expect(target.length).toEqual 2
expect(target[0] instanceof Fluffy).toEqual true
expect(data).toEqual $.parseJSON(rawData)
it "gets collection without params", ->
resource = Fluffy.all @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "gets collection with action", ->
resource = Fluffy.all {action: 'action'}, @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/action\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "gets collection with params", ->
resource = Fluffy.all {params: {foo: 'bar'}}, @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\?foo=bar&_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it 'gets collection with url', ->
resource = Fluffy.all url: '/some/custom/url', @callback
checkAndRespond @server.requests[0], 'GET', /^\/some\/custom\/url\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "reloads resource", ->
rawData = '{"fluffy": {"id": 1, "name": "test1"}}'
resource = Fluffy.find 1
callback = sinon.spy()
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/1\?_=\d+/, rawData
resource.bind 'changed', callback = sinon.spy()
resource.reload()
checkAndRespond @server.requests[1], 'GET', /^\/fluffies\/1\?_=\d+/, rawData
expect(callback.callCount).toEqual 1
it "reloads collection", ->
rawData = '{"page": 42, "fluffies": [{"id": 1, "name": "test1"}, {"id": 2, "name": "test2"}]}'
collection = undefined
@callback = sinon.spy (error, target, data) ->
expect(target instanceof Joosy.Resources.RESTCollection).toEqual true
collection = target
resource = Fluffy.all @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
collection.reload(@callback)
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
describe "requests", ->
rawData = '{"foo": "bar"}'
callback = sinon.spy (error, data) ->
expect(data).toEqual {foo: 'bar'}
describe "member", ->
resource = Fluffy.build id: 1
it "with get", ->
resource.send 'get', {action: 'foo', params: {foo: 'bar'}}, callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/1\/foo\?foo=bar&_=\d+/, rawData
it "with post", ->
resource.send 'post', callback
checkAndRespond @server.requests[0], 'POST', /^\/fluffies\/1/, rawData
it "with put", ->
resource.send 'put', callback
checkAndRespond @server.requests[0], 'PUT', /^\/fluffies\/1/, rawData
it "with delete", ->
resource.send 'delete', callback
checkAndRespond @server.requests[0], 'DELETE', /^\/fluffies\/1/, rawData
describe "collection", ->
resource = Fluffy
it "with get", ->
resource.send 'get', {action: 'foo', params: {foo: 'bar'}}, callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/foo\?foo=bar&_=\d+/, rawData
it "with post", ->
resource.send 'post', callback
checkAndRespond @server.requests[0], 'POST', /^\/fluffies/, rawData
it "with put", ->
resource.send 'put', callback
checkAndRespond @server.requests[0], 'PUT', /^\/fluffies/, rawData
it "with delete", ->
resource.send 'delete', callback
checkAndRespond @server.requests[0], 'DELETE', /^\/fluffies/, rawData
describe "save", ->
beforeEach ->
class @Resource extends Joosy.Resources.REST
@entity 'resource'
@beforeSave (data) ->
data.tested = true
data
it "creates", ->
resource = new @Resource(foo: 'bar')
resource.save()
checkAndRespond @server.requests[0], 'POST', /^\/resources/, rawData
expect(@server.requests[0].requestBody).toEqual 'foo=bar&tested=true'
it "updates", ->
resource = new @Resource(id: 1, foo: 'bar')
resource.save()
checkAndRespond @server.requests[0], 'PUT', /^\/resources\/1/, rawData
expect(@server.requests[0].requestBody).toEqual 'id=1&foo=bar&tested=true' | 154398 | describe "Joosy.Resources.REST", ->
class FluffyInline extends Joosy.Resources.REST
@entity 'fluffy_inline'
class FluffyParent extends Joosy.Resources.REST
@entity 'fluffy_parent'
class Fluffy extends Joosy.Resources.REST
@entity 'fluffy'
@map 'fluffy_inlines', FluffyInline
class Interpolated extends Joosy.Resources.REST
@entity 'test'
@source '/grand_parents/:grand_parent_id/parents/:parent_id/tests'
Joosy.namespace 'Deeply.Nested', ->
class @Entity extends Joosy.Resources.REST
@entity 'entity'
Joosy.namespace 'Animal', ->
class @Cat extends Joosy.Resources.REST
@entity 'cat'
beforeEach ->
@server = sinon.fakeServer.create()
afterEach ->
@server.restore()
checkAndRespond = (target, method, url, data) ->
expect(target.method).toEqual method
expect(target.url).toMatch url
target.respond 200, 'Content-Type': 'application/json', data
describe '@at', ->
# clone won't be instanceof Fluffy in IE
#expect(clone.build({}) instanceof Fluffy).toBeTruthy()
beforeEach ->
class @Test extends Joosy.Resources.REST
@entity 'test'
it 'returns base class child', ->
clone = @Test.at 'rumbas'
expect(Joosy.Module.hasAncestor(clone, @Test)).toBeTruthy()
it 'accepts string', ->
clone = @Test.at 'rumbas'
expect(clone.collectionPath()).toEqual '/rumbas/tests'
it 'makes a class whose instances get new source too', ->
clone = @Test.at 'rumbas'
expect(clone.build(id: 1).memberPath()).toEqual '/rumbas/tests/1'
it 'accepts another resource instance', ->
clone = @Test.at Fluffy.build(id: 1)
expect(clone.collectionPath()).toEqual '/fluffies/1/tests'
it 'accepts array', ->
clone = @Test.at ['rumbas', Fluffy.build(id: 1), 'salsas']
expect(clone.collectionPath()).toEqual '/rumbas/fluffies/1/salsas/tests'
it 'accepts sequential attributes', ->
clone = @Test.at 'rumbas', 'salsas', Fluffy.build(id: 1)
expect(clone.collectionPath()).toEqual '/rumbas/salsas/fluffies/1/tests'
describe '::at', ->
beforeEach ->
class @Test extends Joosy.Resources.REST
@entity 'test'
it 'returns base class instance', ->
original = @Test.build id: 1, name: '<NAME>', 'thing': 'baseclass'
clone = original.at 'rumbas'
expect(clone instanceof @Test).toBeTruthy()
expect(clone.data).toEqual original.data
it 'accepts string', ->
clone = @Test.build(id: 1).at('rumbas')
expect(clone.memberPath()).toEqual '/rumbas/tests/1'
it 'accepts another resource instance', ->
clone = @Test.build(id: 1).at(Fluffy.build(id: 1))
expect(clone.memberPath()).toEqual '/fluffies/1/tests/1'
it 'accepts array', ->
clone = @Test.build(id: 1).at ['rumbas', Fluffy.build(id: 1), 'salsas']
expect(clone.memberPath()).toEqual '/rumbas/fluffies/1/salsas/tests/1'
it 'accepts sequential attributes', ->
clone = @Test.build(id: 1).at 'rumbas', 'salsas', Fluffy.build(id: 1)
expect(clone.memberPath()).toEqual '/rumbas/salsas/fluffies/1/tests/1'
describe '@memberPath', ->
it 'builds member path', ->
expect(Fluffy.memberPath 1).toEqual '/fluffies/1'
it 'builds member path with action', ->
expect(Fluffy.memberPath 1, action: 'test').toEqual '/fluffies/1/test'
describe 'with interpolation', ->
it 'builds member path', ->
expect(Interpolated.memberPath([1,2,3])).toEqual '/grand_parents/1/parents/2/tests/3'
it 'saves member path for single instance', ->
item = Interpolated.find [1,2,3]
checkAndRespond @server.requests[0], 'GET', /^\/grand_parents\/1\/parents\/2\/tests\/3\?_=\d+/, '{"test": {"id": 3}}'
expect(item.memberPath()).toEqual '/grand_parents/1/parents/2/tests/3'
it 'saves member path for instances collection', ->
items = Interpolated.all [1,2]
checkAndRespond @server.requests[0], 'GET', /^\/grand_parents\/1\/parents\/2\/tests\?_=\d+/, '{"tests": [{"test": {"id": 3}}]}'
expect(items[0].memberPath()).toEqual '/grand_parents/1/parents/2/tests/3'
describe '@collectionPath', ->
it 'builds collection path', ->
expect(Fluffy.collectionPath()).toEqual '/fluffies'
it 'builds collection path with action', ->
expect(Fluffy.collectionPath action: 'test').toEqual '/fluffies/test'
describe 'with interpolation', ->
it 'builds collection path', ->
expect(Interpolated.collectionPath([1,2])).toEqual '/grand_parents/1/parents/2/tests'
describe 'with namespace', ->
it 'builds collection path', ->
expect(Deeply.Nested.Entity.collectionPath([1,2])).toEqual '/deeply/nested/entities'
describe '@find(:id)', ->
rawData = '{"fluffy": {"id": 1, "name": "test1"}}'
beforeEach ->
@callback = sinon.spy (error, target, data) ->
expect(target instanceof Fluffy).toEqual true
expect(target.id()).toEqual 1
expect(target.get 'name').toEqual 'test1'
expect(data).toEqual $.parseJSON(rawData)
it "gets item without params", ->
resource = Fluffy.find 1, @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/1\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "gets item with action", ->
resource = Fluffy.find 1, {action: 'action'}, @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/1\/action\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "gets item with params", ->
resource = Fluffy.find 1, params: {foo: 'bar'}, @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/1\?foo=bar&_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "gets item with url", ->
resource = Fluffy.find 1, url: '/some/custom/url', @callback
checkAndRespond @server.requests[0], 'GET', /^\/some\/custom\/url\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "gets item with direct assignation", ->
resource = Fluffy.find 1, (error, cbResource) ->
expect(resource).toBe cbResource
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/1\?_=\d+/, rawData
describe '@all', ->
rawData = '{"page": 42, "fluffies": [{"id": 1, "name": "<NAME>"}, {"id": 2, "name": "<NAME>"}]}'
beforeEach ->
@callback = sinon.spy (error, target, data) ->
expect(target instanceof Joosy.Resources.RESTCollection).toEqual true
expect(target.length).toEqual 2
expect(target[0] instanceof Fluffy).toEqual true
expect(data).toEqual $.parseJSON(rawData)
it "gets collection without params", ->
resource = Fluffy.all @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "gets collection with action", ->
resource = Fluffy.all {action: 'action'}, @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/action\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "gets collection with params", ->
resource = Fluffy.all {params: {foo: 'bar'}}, @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\?foo=bar&_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it 'gets collection with url', ->
resource = Fluffy.all url: '/some/custom/url', @callback
checkAndRespond @server.requests[0], 'GET', /^\/some\/custom\/url\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "reloads resource", ->
rawData = '{"fluffy": {"id": 1, "name": "<NAME>"}}'
resource = Fluffy.find 1
callback = sinon.spy()
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/1\?_=\d+/, rawData
resource.bind 'changed', callback = sinon.spy()
resource.reload()
checkAndRespond @server.requests[1], 'GET', /^\/fluffies\/1\?_=\d+/, rawData
expect(callback.callCount).toEqual 1
it "reloads collection", ->
rawData = '{"page": 42, "fluffies": [{"id": 1, "name": "<NAME>"}, {"id": 2, "name": "<NAME>"}]}'
collection = undefined
@callback = sinon.spy (error, target, data) ->
expect(target instanceof Joosy.Resources.RESTCollection).toEqual true
collection = target
resource = Fluffy.all @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
collection.reload(@callback)
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
describe "requests", ->
rawData = '{"foo": "bar"}'
callback = sinon.spy (error, data) ->
expect(data).toEqual {foo: 'bar'}
describe "member", ->
resource = Fluffy.build id: 1
it "with get", ->
resource.send 'get', {action: 'foo', params: {foo: 'bar'}}, callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/1\/foo\?foo=bar&_=\d+/, rawData
it "with post", ->
resource.send 'post', callback
checkAndRespond @server.requests[0], 'POST', /^\/fluffies\/1/, rawData
it "with put", ->
resource.send 'put', callback
checkAndRespond @server.requests[0], 'PUT', /^\/fluffies\/1/, rawData
it "with delete", ->
resource.send 'delete', callback
checkAndRespond @server.requests[0], 'DELETE', /^\/fluffies\/1/, rawData
describe "collection", ->
resource = Fluffy
it "with get", ->
resource.send 'get', {action: 'foo', params: {foo: 'bar'}}, callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/foo\?foo=bar&_=\d+/, rawData
it "with post", ->
resource.send 'post', callback
checkAndRespond @server.requests[0], 'POST', /^\/fluffies/, rawData
it "with put", ->
resource.send 'put', callback
checkAndRespond @server.requests[0], 'PUT', /^\/fluffies/, rawData
it "with delete", ->
resource.send 'delete', callback
checkAndRespond @server.requests[0], 'DELETE', /^\/fluffies/, rawData
describe "save", ->
beforeEach ->
class @Resource extends Joosy.Resources.REST
@entity 'resource'
@beforeSave (data) ->
data.tested = true
data
it "creates", ->
resource = new @Resource(foo: 'bar')
resource.save()
checkAndRespond @server.requests[0], 'POST', /^\/resources/, rawData
expect(@server.requests[0].requestBody).toEqual 'foo=bar&tested=true'
it "updates", ->
resource = new @Resource(id: 1, foo: 'bar')
resource.save()
checkAndRespond @server.requests[0], 'PUT', /^\/resources\/1/, rawData
expect(@server.requests[0].requestBody).toEqual 'id=1&foo=bar&tested=true' | true | describe "Joosy.Resources.REST", ->
class FluffyInline extends Joosy.Resources.REST
@entity 'fluffy_inline'
class FluffyParent extends Joosy.Resources.REST
@entity 'fluffy_parent'
class Fluffy extends Joosy.Resources.REST
@entity 'fluffy'
@map 'fluffy_inlines', FluffyInline
class Interpolated extends Joosy.Resources.REST
@entity 'test'
@source '/grand_parents/:grand_parent_id/parents/:parent_id/tests'
Joosy.namespace 'Deeply.Nested', ->
class @Entity extends Joosy.Resources.REST
@entity 'entity'
Joosy.namespace 'Animal', ->
class @Cat extends Joosy.Resources.REST
@entity 'cat'
beforeEach ->
@server = sinon.fakeServer.create()
afterEach ->
@server.restore()
checkAndRespond = (target, method, url, data) ->
expect(target.method).toEqual method
expect(target.url).toMatch url
target.respond 200, 'Content-Type': 'application/json', data
describe '@at', ->
# clone won't be instanceof Fluffy in IE
#expect(clone.build({}) instanceof Fluffy).toBeTruthy()
beforeEach ->
class @Test extends Joosy.Resources.REST
@entity 'test'
it 'returns base class child', ->
clone = @Test.at 'rumbas'
expect(Joosy.Module.hasAncestor(clone, @Test)).toBeTruthy()
it 'accepts string', ->
clone = @Test.at 'rumbas'
expect(clone.collectionPath()).toEqual '/rumbas/tests'
it 'makes a class whose instances get new source too', ->
clone = @Test.at 'rumbas'
expect(clone.build(id: 1).memberPath()).toEqual '/rumbas/tests/1'
it 'accepts another resource instance', ->
clone = @Test.at Fluffy.build(id: 1)
expect(clone.collectionPath()).toEqual '/fluffies/1/tests'
it 'accepts array', ->
clone = @Test.at ['rumbas', Fluffy.build(id: 1), 'salsas']
expect(clone.collectionPath()).toEqual '/rumbas/fluffies/1/salsas/tests'
it 'accepts sequential attributes', ->
clone = @Test.at 'rumbas', 'salsas', Fluffy.build(id: 1)
expect(clone.collectionPath()).toEqual '/rumbas/salsas/fluffies/1/tests'
describe '::at', ->
beforeEach ->
class @Test extends Joosy.Resources.REST
@entity 'test'
it 'returns base class instance', ->
original = @Test.build id: 1, name: 'PI:NAME:<NAME>END_PI', 'thing': 'baseclass'
clone = original.at 'rumbas'
expect(clone instanceof @Test).toBeTruthy()
expect(clone.data).toEqual original.data
it 'accepts string', ->
clone = @Test.build(id: 1).at('rumbas')
expect(clone.memberPath()).toEqual '/rumbas/tests/1'
it 'accepts another resource instance', ->
clone = @Test.build(id: 1).at(Fluffy.build(id: 1))
expect(clone.memberPath()).toEqual '/fluffies/1/tests/1'
it 'accepts array', ->
clone = @Test.build(id: 1).at ['rumbas', Fluffy.build(id: 1), 'salsas']
expect(clone.memberPath()).toEqual '/rumbas/fluffies/1/salsas/tests/1'
it 'accepts sequential attributes', ->
clone = @Test.build(id: 1).at 'rumbas', 'salsas', Fluffy.build(id: 1)
expect(clone.memberPath()).toEqual '/rumbas/salsas/fluffies/1/tests/1'
describe '@memberPath', ->
it 'builds member path', ->
expect(Fluffy.memberPath 1).toEqual '/fluffies/1'
it 'builds member path with action', ->
expect(Fluffy.memberPath 1, action: 'test').toEqual '/fluffies/1/test'
describe 'with interpolation', ->
it 'builds member path', ->
expect(Interpolated.memberPath([1,2,3])).toEqual '/grand_parents/1/parents/2/tests/3'
it 'saves member path for single instance', ->
item = Interpolated.find [1,2,3]
checkAndRespond @server.requests[0], 'GET', /^\/grand_parents\/1\/parents\/2\/tests\/3\?_=\d+/, '{"test": {"id": 3}}'
expect(item.memberPath()).toEqual '/grand_parents/1/parents/2/tests/3'
it 'saves member path for instances collection', ->
items = Interpolated.all [1,2]
checkAndRespond @server.requests[0], 'GET', /^\/grand_parents\/1\/parents\/2\/tests\?_=\d+/, '{"tests": [{"test": {"id": 3}}]}'
expect(items[0].memberPath()).toEqual '/grand_parents/1/parents/2/tests/3'
describe '@collectionPath', ->
it 'builds collection path', ->
expect(Fluffy.collectionPath()).toEqual '/fluffies'
it 'builds collection path with action', ->
expect(Fluffy.collectionPath action: 'test').toEqual '/fluffies/test'
describe 'with interpolation', ->
it 'builds collection path', ->
expect(Interpolated.collectionPath([1,2])).toEqual '/grand_parents/1/parents/2/tests'
describe 'with namespace', ->
it 'builds collection path', ->
expect(Deeply.Nested.Entity.collectionPath([1,2])).toEqual '/deeply/nested/entities'
describe '@find(:id)', ->
rawData = '{"fluffy": {"id": 1, "name": "test1"}}'
beforeEach ->
@callback = sinon.spy (error, target, data) ->
expect(target instanceof Fluffy).toEqual true
expect(target.id()).toEqual 1
expect(target.get 'name').toEqual 'test1'
expect(data).toEqual $.parseJSON(rawData)
it "gets item without params", ->
resource = Fluffy.find 1, @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/1\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "gets item with action", ->
resource = Fluffy.find 1, {action: 'action'}, @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/1\/action\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "gets item with params", ->
resource = Fluffy.find 1, params: {foo: 'bar'}, @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/1\?foo=bar&_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "gets item with url", ->
resource = Fluffy.find 1, url: '/some/custom/url', @callback
checkAndRespond @server.requests[0], 'GET', /^\/some\/custom\/url\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "gets item with direct assignation", ->
resource = Fluffy.find 1, (error, cbResource) ->
expect(resource).toBe cbResource
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/1\?_=\d+/, rawData
describe '@all', ->
rawData = '{"page": 42, "fluffies": [{"id": 1, "name": "PI:NAME:<NAME>END_PI"}, {"id": 2, "name": "PI:NAME:<NAME>END_PI"}]}'
beforeEach ->
@callback = sinon.spy (error, target, data) ->
expect(target instanceof Joosy.Resources.RESTCollection).toEqual true
expect(target.length).toEqual 2
expect(target[0] instanceof Fluffy).toEqual true
expect(data).toEqual $.parseJSON(rawData)
it "gets collection without params", ->
resource = Fluffy.all @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "gets collection with action", ->
resource = Fluffy.all {action: 'action'}, @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/action\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "gets collection with params", ->
resource = Fluffy.all {params: {foo: 'bar'}}, @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\?foo=bar&_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it 'gets collection with url', ->
resource = Fluffy.all url: '/some/custom/url', @callback
checkAndRespond @server.requests[0], 'GET', /^\/some\/custom\/url\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
it "reloads resource", ->
rawData = '{"fluffy": {"id": 1, "name": "PI:NAME:<NAME>END_PI"}}'
resource = Fluffy.find 1
callback = sinon.spy()
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/1\?_=\d+/, rawData
resource.bind 'changed', callback = sinon.spy()
resource.reload()
checkAndRespond @server.requests[1], 'GET', /^\/fluffies\/1\?_=\d+/, rawData
expect(callback.callCount).toEqual 1
it "reloads collection", ->
rawData = '{"page": 42, "fluffies": [{"id": 1, "name": "PI:NAME:<NAME>END_PI"}, {"id": 2, "name": "PI:NAME:<NAME>END_PI"}]}'
collection = undefined
@callback = sinon.spy (error, target, data) ->
expect(target instanceof Joosy.Resources.RESTCollection).toEqual true
collection = target
resource = Fluffy.all @callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
collection.reload(@callback)
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\?_=\d+/, rawData
expect(@callback.callCount).toEqual 1
describe "requests", ->
rawData = '{"foo": "bar"}'
callback = sinon.spy (error, data) ->
expect(data).toEqual {foo: 'bar'}
describe "member", ->
resource = Fluffy.build id: 1
it "with get", ->
resource.send 'get', {action: 'foo', params: {foo: 'bar'}}, callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/1\/foo\?foo=bar&_=\d+/, rawData
it "with post", ->
resource.send 'post', callback
checkAndRespond @server.requests[0], 'POST', /^\/fluffies\/1/, rawData
it "with put", ->
resource.send 'put', callback
checkAndRespond @server.requests[0], 'PUT', /^\/fluffies\/1/, rawData
it "with delete", ->
resource.send 'delete', callback
checkAndRespond @server.requests[0], 'DELETE', /^\/fluffies\/1/, rawData
describe "collection", ->
resource = Fluffy
it "with get", ->
resource.send 'get', {action: 'foo', params: {foo: 'bar'}}, callback
checkAndRespond @server.requests[0], 'GET', /^\/fluffies\/foo\?foo=bar&_=\d+/, rawData
it "with post", ->
resource.send 'post', callback
checkAndRespond @server.requests[0], 'POST', /^\/fluffies/, rawData
it "with put", ->
resource.send 'put', callback
checkAndRespond @server.requests[0], 'PUT', /^\/fluffies/, rawData
it "with delete", ->
resource.send 'delete', callback
checkAndRespond @server.requests[0], 'DELETE', /^\/fluffies/, rawData
describe "save", ->
beforeEach ->
class @Resource extends Joosy.Resources.REST
@entity 'resource'
@beforeSave (data) ->
data.tested = true
data
it "creates", ->
resource = new @Resource(foo: 'bar')
resource.save()
checkAndRespond @server.requests[0], 'POST', /^\/resources/, rawData
expect(@server.requests[0].requestBody).toEqual 'foo=bar&tested=true'
it "updates", ->
resource = new @Resource(id: 1, foo: 'bar')
resource.save()
checkAndRespond @server.requests[0], 'PUT', /^\/resources\/1/, rawData
expect(@server.requests[0].requestBody).toEqual 'id=1&foo=bar&tested=true' |
[
{
"context": "\n team = generateTeam()\n team[0] = Factory(\"Latias\", item: \"Soul Dew\", moves: [ \"Psychic\" ])\n con",
"end": 941,
"score": 0.7346229553222656,
"start": 935,
"tag": "NAME",
"value": "Latias"
},
{
"context": "\n team = generateTeam()\n team[0] = Fact... | test/server/conditions/unreleased_ban_spec.coffee | sarenji/pokebattle-sim | 5 | require '../../helpers'
{BattleServer} = require('../../../server/server')
{User} = require('../../../server/user')
{Conditions} = require '../../../shared/conditions'
{Factory} = require '../../factory'
should = require('should')
generateTeam = ->
[ Factory("Magikarp")
Factory("Gyarados")
Factory('Hitmonchan')
Factory("Celebi")
Factory("Blissey")
Factory("Alakazam") ]
describe 'Validations: Unreleased Ban', ->
it "returns an error if a pokemon is unreleased", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = Factory("Hoopa", item: "Leftovers", moves: [ "Moonblast" ])
conditions = [ Conditions.UNRELEASED_BAN ]
server.validateTeam(team, format, conditions).should.not.be.empty
it "returns an error if a pokemon has an unreleased item", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = Factory("Latias", item: "Soul Dew", moves: [ "Psychic" ])
conditions = [ Conditions.UNRELEASED_BAN ]
server.validateTeam(team, format, conditions).should.not.be.empty
it "returns an error if a pokemon has an unreleased ability", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = Factory("Suicune", ability: "Water Absorb", moves: [ "Surf" ])
conditions = [ Conditions.UNRELEASED_BAN ]
server.validateTeam(team, format, conditions).should.not.be.empty
it "returns no error if all pokemon have nothing unreleased", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = Factory("Latias", item: "Leftovers", moves: [ "Psychic" ])
conditions = [ Conditions.UNRELEASED_BAN ]
server.validateTeam(team, format, conditions).should.be.empty
it "returns no error if a pokemon has a dream world ability that is the same as a regular ability", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = Factory("Metapod", ability: "Shed Skin", moves: [ "Tackle" ])
conditions = [ Conditions.UNRELEASED_BAN ]
server.validateTeam(team, format, conditions).should.be.empty
it "ignores invalid pokemon", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = {species: "I'm a totally fake Pokemon."}
conditions = [ Conditions.UNRELEASED_BAN ]
(-> server.validateTeam(team, format, conditions)).should.not.throw()
| 74484 | require '../../helpers'
{BattleServer} = require('../../../server/server')
{User} = require('../../../server/user')
{Conditions} = require '../../../shared/conditions'
{Factory} = require '../../factory'
should = require('should')
generateTeam = ->
[ Factory("Magikarp")
Factory("Gyarados")
Factory('Hitmonchan')
Factory("Celebi")
Factory("Blissey")
Factory("Alakazam") ]
describe 'Validations: Unreleased Ban', ->
it "returns an error if a pokemon is unreleased", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = Factory("Hoopa", item: "Leftovers", moves: [ "Moonblast" ])
conditions = [ Conditions.UNRELEASED_BAN ]
server.validateTeam(team, format, conditions).should.not.be.empty
it "returns an error if a pokemon has an unreleased item", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = Factory("<NAME>", item: "Soul Dew", moves: [ "Psychic" ])
conditions = [ Conditions.UNRELEASED_BAN ]
server.validateTeam(team, format, conditions).should.not.be.empty
it "returns an error if a pokemon has an unreleased ability", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = Factory("Suicune", ability: "Water Absorb", moves: [ "Surf" ])
conditions = [ Conditions.UNRELEASED_BAN ]
server.validateTeam(team, format, conditions).should.not.be.empty
it "returns no error if all pokemon have nothing unreleased", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = Factory("<NAME>", item: "Leftovers", moves: [ "Psychic" ])
conditions = [ Conditions.UNRELEASED_BAN ]
server.validateTeam(team, format, conditions).should.be.empty
it "returns no error if a pokemon has a dream world ability that is the same as a regular ability", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = Factory("Metapod", ability: "Shed Skin", moves: [ "Tackle" ])
conditions = [ Conditions.UNRELEASED_BAN ]
server.validateTeam(team, format, conditions).should.be.empty
it "ignores invalid pokemon", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = {species: "I'm a totally fake Pokemon."}
conditions = [ Conditions.UNRELEASED_BAN ]
(-> server.validateTeam(team, format, conditions)).should.not.throw()
| true | require '../../helpers'
{BattleServer} = require('../../../server/server')
{User} = require('../../../server/user')
{Conditions} = require '../../../shared/conditions'
{Factory} = require '../../factory'
should = require('should')
generateTeam = ->
[ Factory("Magikarp")
Factory("Gyarados")
Factory('Hitmonchan')
Factory("Celebi")
Factory("Blissey")
Factory("Alakazam") ]
describe 'Validations: Unreleased Ban', ->
it "returns an error if a pokemon is unreleased", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = Factory("Hoopa", item: "Leftovers", moves: [ "Moonblast" ])
conditions = [ Conditions.UNRELEASED_BAN ]
server.validateTeam(team, format, conditions).should.not.be.empty
it "returns an error if a pokemon has an unreleased item", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = Factory("PI:NAME:<NAME>END_PI", item: "Soul Dew", moves: [ "Psychic" ])
conditions = [ Conditions.UNRELEASED_BAN ]
server.validateTeam(team, format, conditions).should.not.be.empty
it "returns an error if a pokemon has an unreleased ability", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = Factory("Suicune", ability: "Water Absorb", moves: [ "Surf" ])
conditions = [ Conditions.UNRELEASED_BAN ]
server.validateTeam(team, format, conditions).should.not.be.empty
it "returns no error if all pokemon have nothing unreleased", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = Factory("PI:NAME:<NAME>END_PI", item: "Leftovers", moves: [ "Psychic" ])
conditions = [ Conditions.UNRELEASED_BAN ]
server.validateTeam(team, format, conditions).should.be.empty
it "returns no error if a pokemon has a dream world ability that is the same as a regular ability", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = Factory("Metapod", ability: "Shed Skin", moves: [ "Tackle" ])
conditions = [ Conditions.UNRELEASED_BAN ]
server.validateTeam(team, format, conditions).should.be.empty
it "ignores invalid pokemon", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = {species: "I'm a totally fake Pokemon."}
conditions = [ Conditions.UNRELEASED_BAN ]
(-> server.validateTeam(team, format, conditions)).should.not.throw()
|
[
{
"context": "erta el usuario\n owner_user: _.omit(user, 'passowrd')\n # owner_user = user\n\n )\n noti",
"end": 1716,
"score": 0.9820706248283386,
"start": 1708,
"tag": "PASSWORD",
"value": "passowrd"
}
] | controllers/Noticias.coffee | develvad/NodeCMS | 1 | NoticiaM = require("../models/Noticias").NoticiasModelo
User = require("../models/User").UsersModelo
_ = require('underscore')
exports.noticias = (req, res, next) ->
NoticiaM.find({},(err, noticias) ->
if not err
console.log noticias
# Return JSON
# El cliente recibe "response"
# response.title
# response. status
# response.noticias
res.send(
title: "pepe",
status:200,
noticias: noticias
)
else
console.log err
)
exports.leer10 = (req, res, next) ->
NoticiaM.find({},{},{limit:10},(err, noticias) ->
if not err
console.log noticias
res.render('index', {noticias: noticias})
else
console.log err
)
exports.escribeloTodo = (req, res, next) ->
ejemplo = new NoticiaM(
titulo : "Titulo1",
descripcion : "Descripcion1",
enlace: "http://www.google.es",
fecha: "2015-01-01"
)
ejemplo.save((err) ->
res.render("index", title: "Vladi")
)
exports.get = (req, res, next) ->
NoticiaM.find({},(err, noticias) ->
if not err
console.log noticias
res.render('panel/index', {noticias: noticias, user: req.session.user})
else
console.log err
)
# Insert de noticia + propietario de la noticia
exports.post = (req, res, next) ->
User.findOne(_id: req.body.user_id, (err, user) ->
if not err
console.log user
noticia = new NoticiaM(
titulo : req.body.titulo,
descripcion : req.body.descripcion,
enlace: req.body.enlace,
fecha: Date.now(),
#owner_user: _.pick(user, '_id', 'email' ,'name', 'surname', 'locality', 'street'); # inserta el usuario
owner_user: _.omit(user, 'passowrd')
# owner_user = user
)
noticia.save()
res.redirect('/panel/index')
)
## Sistemas de plantillas para user con backbone
# mustache.js Ej: {{ user.name }}
# underscore.js # Yo uso este! Ej: <%= user.name %>
exports.newform = (req, res, next) ->
res.render('panel/index', {user: req.session.user}) | 88530 | NoticiaM = require("../models/Noticias").NoticiasModelo
User = require("../models/User").UsersModelo
_ = require('underscore')
exports.noticias = (req, res, next) ->
NoticiaM.find({},(err, noticias) ->
if not err
console.log noticias
# Return JSON
# El cliente recibe "response"
# response.title
# response. status
# response.noticias
res.send(
title: "pepe",
status:200,
noticias: noticias
)
else
console.log err
)
exports.leer10 = (req, res, next) ->
NoticiaM.find({},{},{limit:10},(err, noticias) ->
if not err
console.log noticias
res.render('index', {noticias: noticias})
else
console.log err
)
exports.escribeloTodo = (req, res, next) ->
ejemplo = new NoticiaM(
titulo : "Titulo1",
descripcion : "Descripcion1",
enlace: "http://www.google.es",
fecha: "2015-01-01"
)
ejemplo.save((err) ->
res.render("index", title: "Vladi")
)
exports.get = (req, res, next) ->
NoticiaM.find({},(err, noticias) ->
if not err
console.log noticias
res.render('panel/index', {noticias: noticias, user: req.session.user})
else
console.log err
)
# Insert de noticia + propietario de la noticia
exports.post = (req, res, next) ->
User.findOne(_id: req.body.user_id, (err, user) ->
if not err
console.log user
noticia = new NoticiaM(
titulo : req.body.titulo,
descripcion : req.body.descripcion,
enlace: req.body.enlace,
fecha: Date.now(),
#owner_user: _.pick(user, '_id', 'email' ,'name', 'surname', 'locality', 'street'); # inserta el usuario
owner_user: _.omit(user, '<PASSWORD>')
# owner_user = user
)
noticia.save()
res.redirect('/panel/index')
)
## Sistemas de plantillas para user con backbone
# mustache.js Ej: {{ user.name }}
# underscore.js # Yo uso este! Ej: <%= user.name %>
exports.newform = (req, res, next) ->
res.render('panel/index', {user: req.session.user}) | true | NoticiaM = require("../models/Noticias").NoticiasModelo
User = require("../models/User").UsersModelo
_ = require('underscore')
exports.noticias = (req, res, next) ->
NoticiaM.find({},(err, noticias) ->
if not err
console.log noticias
# Return JSON
# El cliente recibe "response"
# response.title
# response. status
# response.noticias
res.send(
title: "pepe",
status:200,
noticias: noticias
)
else
console.log err
)
exports.leer10 = (req, res, next) ->
NoticiaM.find({},{},{limit:10},(err, noticias) ->
if not err
console.log noticias
res.render('index', {noticias: noticias})
else
console.log err
)
exports.escribeloTodo = (req, res, next) ->
ejemplo = new NoticiaM(
titulo : "Titulo1",
descripcion : "Descripcion1",
enlace: "http://www.google.es",
fecha: "2015-01-01"
)
ejemplo.save((err) ->
res.render("index", title: "Vladi")
)
exports.get = (req, res, next) ->
NoticiaM.find({},(err, noticias) ->
if not err
console.log noticias
res.render('panel/index', {noticias: noticias, user: req.session.user})
else
console.log err
)
# Insert de noticia + propietario de la noticia
exports.post = (req, res, next) ->
User.findOne(_id: req.body.user_id, (err, user) ->
if not err
console.log user
noticia = new NoticiaM(
titulo : req.body.titulo,
descripcion : req.body.descripcion,
enlace: req.body.enlace,
fecha: Date.now(),
#owner_user: _.pick(user, '_id', 'email' ,'name', 'surname', 'locality', 'street'); # inserta el usuario
owner_user: _.omit(user, 'PI:PASSWORD:<PASSWORD>END_PI')
# owner_user = user
)
noticia.save()
res.redirect('/panel/index')
)
## Sistemas de plantillas para user con backbone
# mustache.js Ej: {{ user.name }}
# underscore.js # Yo uso este! Ej: <%= user.name %>
exports.newform = (req, res, next) ->
res.render('panel/index', {user: req.session.user}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.